From 2990caa9a479b24a29867c5cf77dbc699ed810ec Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 19:31:07 +0000 Subject: [PATCH 1/7] fix(telemetry): keep throttled telemetry batches instead of dropping them /telemetry-ext answers bursts with 429 (Retry-After: 1). Telemetry retries are 100 ms apart, so all three land inside the throttle window and the batch is dropped. With telemetry on, one process at ~650 QPS lost 9-20% of its events this way, and every retry logged a WARN to the application's stderr. A background export that ends in 429/503 now puts its batch back on the queue (bounded at 10,000 events, oldest dropped first) and pauses background flushes for 1 s, doubling per consecutive throttled export up to 30 s. The close-time flush ignores the pause and makes one export attempt as before, so close is never slower than today. Telemetry retries log at debug, like the other telemetry export failures. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 1 + src/client/http.rs | 18 ++- src/telemetry/client.rs | 248 ++++++++++++++++++++++++++++++++++-- src/telemetry/databricks.rs | 30 ++++- src/telemetry/exporter.rs | 22 ++-- 5 files changed, 297 insertions(+), 22 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..46e6de85 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,6 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. +- Telemetry batches rejected with HTTP 429/503 are kept and sent again after a backoff instead of being dropped, and telemetry retries log at debug instead of warn. The final flush on close is unchanged. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/client/http.rs b/src/client/http.rs index e5f9ad0b..d585e6b9 100644 --- a/src/client/http.rs +++ b/src/client/http.rs @@ -36,6 +36,18 @@ use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use tokio::time::sleep; +/// Log a retry. Telemetry export is fail-open background work, so its +/// retries (e.g. a throttled `/telemetry-ext`) log at debug, not warn. +macro_rules! retry_log { + ($request_type:expr, $($arg:tt)*) => { + if $request_type.category() == RequestCategory::Telemetry { + debug!($($arg)*) + } else { + warn!($($arg)*) + } + }; +} + /// Build an `Error` for a transport-level non-2xx HTTP response, parsing /// the SEA error envelope out of the response body when present. /// @@ -988,7 +1000,8 @@ impl DatabricksHttpClient { )); } - warn!( + retry_log!( + request_type, "{:?}: HTTP {} (attempt {}/{}), waiting {:.1}s before retry", request_type, status.as_u16(), @@ -1040,7 +1053,8 @@ impl DatabricksHttpClient { ))); } - warn!( + retry_log!( + request_type, "{:?}: error (attempt {}/{}): {}, waiting {:.1}s before retry", request_type, attempts, diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index e625279e..b4fdc0ab 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -12,30 +12,53 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::exporter::{export_batch, TelemetryExporter}; +use super::exporter::{export_batch, TelemetryExportError, TelemetryExporter}; use super::models::TelemetryFrontendLog; use crate::config::TelemetryConfig; use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use tokio::runtime::{Handle, Runtime}; const STATE_ACTIVE: u8 = 0; const STATE_CLOSING: u8 = 1; const STATE_CLOSED: u8 = 2; +// After a throttled background export, background flushes pause for this +// long, doubling per consecutive throttled export up to the cap. The endpoint +// sends `Retry-After: 1` when it throttles. +#[cfg(not(test))] +const INITIAL_THROTTLE_BACKOFF: Duration = Duration::from_secs(1); +#[cfg(test)] +const INITIAL_THROTTLE_BACKOFF: Duration = Duration::from_millis(200); +const MAX_THROTTLE_BACKOFF: Duration = Duration::from_secs(30); +/// Events kept while throttled (at least one batch); past this the oldest are +/// dropped. Sized for several seconds of backoff at ~1k events/s (~14 MB). +#[cfg(not(test))] +const MAX_PENDING_EVENTS: usize = 10_000; +#[cfg(test)] +const MAX_PENDING_EVENTS: usize = 20; + pub(super) struct TelemetryClient { exporter: Arc, batch_size: usize, - flush_interval: std::time::Duration, - close_flush_timeout: std::time::Duration, + flush_interval: Duration, + close_flush_timeout: Duration, pending: Mutex>, queue_count: AtomicUsize, flush_lock: tokio::sync::Mutex<()>, + throttle: Mutex, state: AtomicU8, timer: Mutex>>, runtime_handle: Handle, } +#[derive(Default)] +struct Throttle { + until: Option, + backoff: Duration, +} + impl TelemetryClient { pub(super) fn new( config: &TelemetryConfig, @@ -60,6 +83,7 @@ impl TelemetryClient { pending: Mutex::new(Vec::new()), queue_count: AtomicUsize::new(0), flush_lock: tokio::sync::Mutex::new(()), + throttle: Mutex::new(Throttle::default()), state: AtomicU8::new(STATE_ACTIVE), timer: Mutex::new(None), runtime_handle, @@ -79,7 +103,7 @@ impl TelemetryClient { self.queue_count.fetch_add(1, Ordering::AcqRel) + 1 }; - if count >= self.batch_size { + if count >= self.batch_size && !self.throttled() { let client = Arc::clone(self); self.runtime_handle.spawn(async move { client.flush_once_if_idle().await; @@ -131,25 +155,73 @@ impl TelemetryClient { self.state.store(STATE_CLOSED, Ordering::Release); } + /// Background (batch-size or timer) flush. Skipped while throttled; a + /// throttled batch goes back to the queue for a later flush. async fn flush_once_if_idle(self: Arc) { + if self.throttled() { + return; + } let Ok(_guard) = self.flush_lock.try_lock() else { return; }; - self.export_pending().await; + self.export_pending(true).await; } + /// Close-time flush: one export attempt regardless of throttling, so close + /// never waits out a backoff. async fn flush_once_wait(self: &Arc) { let _guard = self.flush_lock.lock().await; - self.export_pending().await; + self.export_pending(false).await; } - async fn export_pending(&self) { + async fn export_pending(&self, requeue_if_throttled: bool) { let batch = self.drain_pending(); if batch.is_empty() { return; } - export_batch(Arc::clone(&self.exporter), batch).await; + match export_batch(Arc::clone(&self.exporter), &batch).await { + Ok(()) => { + *self.throttle.lock().expect("poisoned telemetry throttle") = Throttle::default() + } + Err(TelemetryExportError::Throttled(_)) if requeue_if_throttled => { + self.back_off(); + self.requeue(batch); + } + Err(_) => {} + } + } + + fn throttled(&self) -> bool { + let throttle = self.throttle.lock().expect("poisoned telemetry throttle"); + throttle.until.is_some_and(|until| Instant::now() < until) + } + + fn back_off(&self) { + let mut throttle = self.throttle.lock().expect("poisoned telemetry throttle"); + throttle.backoff = if throttle.backoff.is_zero() { + INITIAL_THROTTLE_BACKOFF + } else { + (throttle.backoff * 2).min(MAX_THROTTLE_BACKOFF) + }; + throttle.until = Some(Instant::now() + throttle.backoff); + } + + /// Put a throttled batch back ahead of events queued since it was drained. + fn requeue(&self, mut batch: Vec) { + let mut pending = self.pending.lock().expect("poisoned telemetry queue"); + batch.append(&mut pending); + let cap = MAX_PENDING_EVENTS.max(self.batch_size); + let excess = batch.len().saturating_sub(cap); + if excess > 0 { + batch.drain(..excess); + tracing::debug!( + dropped = excess, + "telemetry backlog full while throttled; dropping oldest events" + ); + } + self.queue_count.store(batch.len(), Ordering::Release); + *pending = batch; } fn drain_pending(&self) -> Vec { @@ -338,6 +410,166 @@ mod tests { assert_eq!(requests[0].proto_logs.len(), 1); } + #[tokio::test] + async fn throttled_background_export_is_retried_after_backoff() { + let exporter = ThrottlingExporter::new(1); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 2, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + + client.enqueue(sample_log("one")); + client.enqueue(sample_log("two")); + wait_until(|| client.throttled()).await; + + // A full batch inside the backoff does not trigger another export. + client.enqueue(sample_log("three")); + tokio::time::sleep(Duration::from_millis(20)).await; + assert_eq!(exporter.ids().len(), 1); + + tokio::time::sleep(INITIAL_THROTTLE_BACKOFF).await; + client.enqueue(sample_log("four")); + wait_until(|| exporter.ids().len() == 2).await; + + assert_eq!(exporter.ids()[1], ["one", "two", "three", "four"]); + assert!(!client.throttled()); + client.close().await; + } + + #[tokio::test] + async fn close_flush_ignores_backoff_and_does_not_requeue() { + let exporter = ThrottlingExporter::new(usize::MAX); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 1, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + + client.enqueue(sample_log("one")); + wait_until(|| client.throttled()).await; + client.enqueue(sample_log("two")); + assert!(client.throttled()); + + client.close().await; + + assert_eq!(exporter.ids(), [vec!["one"], vec!["one", "two"]]); + assert!(client.pending.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn requeue_keeps_oldest_first_and_caps_backlog() { + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 2, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(ThrottlingExporter::new(0))) + .expect("telemetry runtime should start"); + *client.pending.lock().unwrap() = (0..5).map(|i| sample_log(&format!("new{i}"))).collect(); + + client.requeue((0..18).map(|i| sample_log(&format!("old{i}"))).collect()); + + let pending = client.pending.lock().unwrap(); + assert_eq!(pending.len(), MAX_PENDING_EVENTS); + assert_eq!(pending[0].frontend_log_event_id, "old3"); + assert_eq!(pending[19].frontend_log_event_id, "new4"); + assert_eq!(client.queue_count.load(Ordering::Acquire), pending.len()); + } + + #[tokio::test] + async fn backoff_doubles_up_to_cap() { + let config = TelemetryConfig { + enabled: Some(true), + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(ThrottlingExporter::new(0))) + .expect("telemetry runtime should start"); + + let mut seen = Vec::new(); + for _ in 0..10 { + client.back_off(); + seen.push(client.throttle.lock().unwrap().backoff); + } + + assert_eq!(seen[0], INITIAL_THROTTLE_BACKOFF); + assert_eq!(seen[1], INITIAL_THROTTLE_BACKOFF * 2); + assert_eq!(*seen.last().unwrap(), MAX_THROTTLE_BACKOFF); + } + + /// Throttles the first `throttled` exports, then accepts; records the + /// event ids of every export attempt. + #[derive(Clone)] + struct ThrottlingExporter { + throttled: usize, + attempts: Arc>>>, + } + + impl ThrottlingExporter { + fn new(throttled: usize) -> Self { + Self { + throttled, + attempts: Arc::default(), + } + } + + fn ids(&self) -> Vec> { + self.attempts.lock().unwrap().clone() + } + } + + impl TelemetryExporter for ThrottlingExporter { + fn export<'a>( + &'a self, + request: TelemetryRequest, + ) -> std::pin::Pin< + Box< + dyn std::future::Future + + Send + + 'a, + >, + > { + Box::pin(async move { + let ids = request + .proto_logs + .iter() + .map(|log| { + serde_json::from_str::(log).unwrap() + ["frontend_log_event_id"] + .as_str() + .unwrap() + .to_string() + }) + .collect(); + let mut attempts = self.attempts.lock().unwrap(); + attempts.push(ids); + if attempts.len() <= self.throttled { + Err(TelemetryExportError::Throttled("HTTP 429".to_string())) + } else { + Ok(()) + } + }) + } + } + + async fn wait_until(mut condition: impl FnMut() -> bool) { + tokio::time::timeout(Duration::from_secs(2), async { + while !condition() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .expect("condition should become true"); + } + fn sample_log(id: &str) -> TelemetryFrontendLog { TelemetryFrontendLog { frontend_log_event_id: id.to_string(), diff --git a/src/telemetry/databricks.rs b/src/telemetry/databricks.rs index 2c3a4c14..0a722198 100644 --- a/src/telemetry/databricks.rs +++ b/src/telemetry/databricks.rs @@ -16,6 +16,7 @@ use super::exporter::{TelemetryExportError, TelemetryExportResult, TelemetryExpo use super::models::TelemetryRequest; use crate::client::retry::RequestType; use crate::client::DatabricksHttpClient; +use crate::kernel_error::Error as KernelError; use reqwest::header::{HeaderValue, CONTENT_TYPE}; use reqwest::{Body, Method, Request, Url}; use std::future::Future; @@ -70,11 +71,18 @@ impl TelemetryExporter for DatabricksTelemetryExporter { .execute(request, RequestType::TelemetryExport) .await .map(|_| ()) - .map_err(|e| TelemetryExportError::Export(e.to_string())) + .map_err(export_error) }) } } +fn export_error(error: KernelError) -> TelemetryExportError { + match error.http_status { + Some(429 | 503) => TelemetryExportError::Throttled(error.to_string()), + _ => TelemetryExportError::Export(error.to_string()), + } +} + fn build_export_request( endpoint_url: &str, request: &TelemetryRequest, @@ -118,6 +126,26 @@ mod tests { ); } + #[test] + fn rate_limit_statuses_classify_as_throttled() { + for status in [429, 503] { + assert!(matches!( + export_error(KernelError::from_http_status(status)), + TelemetryExportError::Throttled(_) + )); + } + for status in [400, 500] { + assert!(matches!( + export_error(KernelError::from_http_status(status)), + TelemetryExportError::Export(_) + )); + } + assert!(matches!( + export_error(KernelError::network_error()), + TelemetryExportError::Export(_) + )); + } + #[test] fn build_export_request_sets_method_url_json_body_and_content_type() { let telemetry_request = TelemetryRequest { diff --git a/src/telemetry/exporter.rs b/src/telemetry/exporter.rs index 536ced0e..c1fa2cff 100644 --- a/src/telemetry/exporter.rs +++ b/src/telemetry/exporter.rs @@ -25,6 +25,10 @@ pub(crate) enum TelemetryExportError { Serialization(#[from] serde_json::Error), #[error("telemetry export failed: {0}")] Export(String), + /// The endpoint rate-limited the export (HTTP 429 or 503). The batch was + /// not accepted and can be sent again later. + #[error("telemetry export throttled: {0}")] + Throttled(String), } pub(crate) trait TelemetryExporter: Send + Sync { @@ -36,17 +40,13 @@ pub(crate) trait TelemetryExporter: Send + Sync { pub(super) async fn export_batch( exporter: Arc, - batch: Vec, -) { - let request = match TelemetryRequest::from_logs(&batch) { - Ok(request) => request, - Err(e) => { - tracing::debug!(error = %e, "failed to serialize telemetry batch"); - return; - } - }; + batch: &[TelemetryFrontendLog], +) -> TelemetryExportResult { + let request = TelemetryRequest::from_logs(batch).inspect_err(|e| { + tracing::debug!(error = %e, "failed to serialize telemetry batch"); + })?; - if let Err(e) = exporter.export(request).await { + exporter.export(request).await.inspect_err(|e| { tracing::debug!(error = %e, "failed to export telemetry batch"); - } + }) } From a5c0068e4190884d20ab97f04a95039f8036bde9 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:39:16 +0000 Subject: [PATCH 2/7] fix(telemetry): keep the backlog on session-release flushes; cap events per post Review follow-up. flush_bounded also runs when a host's last session closes while the client stays in use, and that path dropped a throttled backlog. It now re-queues on 429/503 like background flushes; only the final close (client closing) still drops. Each export now sends at most max(batch_size, 1000) of the oldest events, and flushes keep going while a backlog remains, so a backlog left by throttling is not sent as one multi-megabyte request. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 2 +- src/telemetry/client.rs | 128 +++++++++++++++++++++++++++++++++++----- 2 files changed, 113 insertions(+), 17 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 46e6de85..0f00099d 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,7 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. -- Telemetry batches rejected with HTTP 429/503 are kept and sent again after a backoff instead of being dropped, and telemetry retries log at debug instead of warn. The final flush on close is unchanged. +- Telemetry batches rejected with HTTP 429/503 are kept and sent again after a backoff instead of being dropped, at most 1,000 events per request, and telemetry retries log at debug instead of warn. Flushes on session close never wait out the backoff. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index b4fdc0ab..36e26f05 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -38,6 +38,12 @@ const MAX_THROTTLE_BACKOFF: Duration = Duration::from_secs(30); const MAX_PENDING_EVENTS: usize = 10_000; #[cfg(test)] const MAX_PENDING_EVENTS: usize = 20; +/// Most events per POST (at least one batch), so a backlog left by throttling +/// goes out in bounded requests (~1.4 MB) rather than one large one. +#[cfg(not(test))] +const MAX_EVENTS_PER_EXPORT: usize = 1_000; +#[cfg(test)] +const MAX_EVENTS_PER_EXPORT: usize = 50; pub(super) struct TelemetryClient { exporter: Arc, @@ -164,31 +170,43 @@ impl TelemetryClient { let Ok(_guard) = self.flush_lock.try_lock() else { return; }; - self.export_pending(true).await; + // Keep going while a backlog left by throttling still fills a batch. + loop { + let delivered = self.export_once(true).await; + if !delivered || self.queue_count.load(Ordering::Acquire) < self.batch_size { + break; + } + } } - /// Close-time flush: one export attempt regardless of throttling, so close - /// never waits out a backoff. + /// Session-release and close flush. Sends everything queued without + /// waiting out a backoff. While the client stays in use a throttled batch + /// is kept; once it is closing, it is dropped as before. async fn flush_once_wait(self: &Arc) { let _guard = self.flush_lock.lock().await; - self.export_pending(false).await; + let requeue_if_throttled = self.state.load(Ordering::Acquire) == STATE_ACTIVE; + while self.export_once(requeue_if_throttled).await {} } - async fn export_pending(&self, requeue_if_throttled: bool) { - let batch = self.drain_pending(); + /// Export the oldest queued events in one request. Returns whether a + /// non-empty batch was delivered. + async fn export_once(&self, requeue_if_throttled: bool) -> bool { + let batch = self.drain_pending(MAX_EVENTS_PER_EXPORT.max(self.batch_size)); if batch.is_empty() { - return; + return false; } match export_batch(Arc::clone(&self.exporter), &batch).await { Ok(()) => { - *self.throttle.lock().expect("poisoned telemetry throttle") = Throttle::default() + *self.throttle.lock().expect("poisoned telemetry throttle") = Throttle::default(); + true } Err(TelemetryExportError::Throttled(_)) if requeue_if_throttled => { self.back_off(); self.requeue(batch); + false } - Err(_) => {} + Err(_) => false, } } @@ -224,13 +242,12 @@ impl TelemetryClient { *pending = batch; } - fn drain_pending(&self) -> Vec { - let drained = self - .pending - .lock() - .expect("poisoned telemetry queue") - .drain(..) - .collect::>(); + fn drain_pending(&self, limit: usize) -> Vec { + let drained = { + let mut pending = self.pending.lock().expect("poisoned telemetry queue"); + let n = pending.len().min(limit); + pending.drain(..n).collect::>() + }; self.queue_count.fetch_sub(drained.len(), Ordering::AcqRel); drained } @@ -463,6 +480,85 @@ mod tests { assert!(client.pending.lock().unwrap().is_empty()); } + #[tokio::test] + async fn session_release_flush_keeps_throttled_batch() { + let exporter = ThrottlingExporter::new(usize::MAX); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 1, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + + client.enqueue(sample_log("one")); + wait_until(|| client.throttled()).await; + + // The flush run when a host's last session closes ignores the backoff, + // but the client stays in use, so a throttled batch is kept. + client.flush_bounded().await; + + assert_eq!(exporter.ids(), [vec!["one"], vec!["one"]]); + assert_eq!(client.pending.lock().unwrap().len(), 1); + assert_eq!( + client.throttle.lock().unwrap().backoff, + INITIAL_THROTTLE_BACKOFF * 2 + ); + client.close().await; + } + + #[tokio::test] + async fn flush_sends_backlog_in_bounded_posts() { + let exporter = ThrottlingExporter::new(0); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 2, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + let backlog = (0..120) + .map(|i| sample_log(&format!("e{i}"))) + .collect::>(); + client.queue_count.store(backlog.len(), Ordering::Release); + *client.pending.lock().unwrap() = backlog; + + client.flush_bounded().await; + + let sizes = exporter.ids().iter().map(Vec::len).collect::>(); + assert_eq!(sizes, [MAX_EVENTS_PER_EXPORT, MAX_EVENTS_PER_EXPORT, 20]); + assert_eq!(exporter.ids()[0][0], "e0"); + client.close().await; + } + + #[tokio::test] + async fn background_flush_drains_backlog_in_bounded_posts() { + let exporter = ThrottlingExporter::new(0); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 2, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + let backlog = (0..119) + .map(|i| sample_log(&format!("e{i}"))) + .collect::>(); + client.queue_count.store(backlog.len(), Ordering::Release); + *client.pending.lock().unwrap() = backlog; + + client.enqueue(sample_log("e119")); + wait_until(|| exporter.ids().len() == 3).await; + + let sizes = exporter.ids().iter().map(Vec::len).collect::>(); + assert_eq!(sizes, [MAX_EVENTS_PER_EXPORT, MAX_EVENTS_PER_EXPORT, 20]); + assert!(client.pending.lock().unwrap().is_empty()); + client.close().await; + } + #[tokio::test] async fn requeue_keeps_oldest_first_and_caps_backlog() { let config = TelemetryConfig { From c08a2c77a85d2de5527d961008292558739147a2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 21:02:29 +0000 Subject: [PATCH 3/7] fix(telemetry): enforce the backlog cap on enqueue; keep cancelled batches Review follow-up. The 10,000-event cap was only applied when a batch was re-queued, so the queue could grow past it while flushes were backed off. enqueue now drops the oldest event once the queue is full (the queue is a VecDeque), and dropped events are counted and logged at debug once per export. A drained batch is now held by a guard while its export is in flight. If the client is still in use and the export is throttled or cancelled (the flush_bounded timeout), the guard puts the batch back. The final close still stops at its first failed post, and now logs and clears whatever it leaves behind. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/telemetry/client.rs | 220 ++++++++++++++++++++++++++++++++++------ 1 file changed, 191 insertions(+), 29 deletions(-) diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index 36e26f05..84620bca 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -15,6 +15,7 @@ use super::exporter::{export_batch, TelemetryExportError, TelemetryExporter}; use super::models::TelemetryFrontendLog; use crate::config::TelemetryConfig; +use std::collections::VecDeque; use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -32,12 +33,13 @@ const INITIAL_THROTTLE_BACKOFF: Duration = Duration::from_secs(1); #[cfg(test)] const INITIAL_THROTTLE_BACKOFF: Duration = Duration::from_millis(200); const MAX_THROTTLE_BACKOFF: Duration = Duration::from_secs(30); -/// Events kept while throttled (at least one batch); past this the oldest are -/// dropped. Sized for several seconds of backoff at ~1k events/s (~14 MB). +/// Most events queued (at least one batch); past this the oldest are dropped. +/// Only reached while throttled. Sized for several seconds of backoff at ~1k +/// events/s (~14 MB). #[cfg(not(test))] const MAX_PENDING_EVENTS: usize = 10_000; #[cfg(test)] -const MAX_PENDING_EVENTS: usize = 20; +const MAX_PENDING_EVENTS: usize = 200; /// Most events per POST (at least one batch), so a backlog left by throttling /// goes out in bounded requests (~1.4 MB) rather than one large one. #[cfg(not(test))] @@ -50,8 +52,10 @@ pub(super) struct TelemetryClient { batch_size: usize, flush_interval: Duration, close_flush_timeout: Duration, - pending: Mutex>, + pending: Mutex>, queue_count: AtomicUsize, + /// Events dropped because the queue was full, not yet logged. + dropped: AtomicUsize, flush_lock: tokio::sync::Mutex<()>, throttle: Mutex, state: AtomicU8, @@ -65,6 +69,22 @@ struct Throttle { backoff: Duration, } +/// A drained batch whose export is in flight; still non-empty when dropped +/// (export throttled or cancelled), it goes back to the queue. +struct InFlight<'a> { + client: &'a TelemetryClient, + batch: Vec, + requeue_on_drop: bool, +} + +impl Drop for InFlight<'_> { + fn drop(&mut self) { + if self.requeue_on_drop && !self.batch.is_empty() { + self.client.requeue(std::mem::take(&mut self.batch)); + } + } +} + impl TelemetryClient { pub(super) fn new( config: &TelemetryConfig, @@ -86,8 +106,9 @@ impl TelemetryClient { batch_size: config.batch_size, flush_interval: config.flush_interval, close_flush_timeout: config.close_flush_timeout, - pending: Mutex::new(Vec::new()), + pending: Mutex::new(VecDeque::new()), queue_count: AtomicUsize::new(0), + dropped: AtomicUsize::new(0), flush_lock: tokio::sync::Mutex::new(()), throttle: Mutex::new(Throttle::default()), state: AtomicU8::new(STATE_ACTIVE), @@ -105,8 +126,14 @@ impl TelemetryClient { let count = { let mut pending = self.pending.lock().expect("poisoned telemetry queue"); - pending.push(log); - self.queue_count.fetch_add(1, Ordering::AcqRel) + 1 + if pending.len() >= self.pending_cap() { + pending.pop_front(); + self.dropped.fetch_add(1, Ordering::Relaxed); + } else { + self.queue_count.fetch_add(1, Ordering::AcqRel); + } + pending.push_back(log); + pending.len() }; if count >= self.batch_size && !self.throttled() { @@ -158,6 +185,11 @@ impl TelemetryClient { timer.abort(); } self.flush_bounded().await; + // The final flush stops at its first failed post; say what it left. + let abandoned = self.drain_pending(usize::MAX).len(); + if abandoned > 0 { + tracing::debug!(abandoned, "telemetry client closed with undelivered events"); + } self.state.store(STATE_CLOSED, Ordering::Release); } @@ -189,27 +221,48 @@ impl TelemetryClient { } /// Export the oldest queued events in one request. Returns whether a - /// non-empty batch was delivered. + /// non-empty batch was delivered. With `requeue_if_throttled`, a throttled + /// batch, or one whose export is cancelled (flush timeout), is re-queued. async fn export_once(&self, requeue_if_throttled: bool) -> bool { - let batch = self.drain_pending(MAX_EVENTS_PER_EXPORT.max(self.batch_size)); - if batch.is_empty() { + let mut in_flight = InFlight { + client: self, + batch: self.drain_pending(MAX_EVENTS_PER_EXPORT.max(self.batch_size)), + requeue_on_drop: requeue_if_throttled, + }; + if in_flight.batch.is_empty() { return false; } - match export_batch(Arc::clone(&self.exporter), &batch).await { + let result = export_batch(Arc::clone(&self.exporter), &in_flight.batch).await; + let dropped = self.dropped.swap(0, Ordering::Relaxed); + if dropped > 0 { + tracing::debug!( + dropped, + "telemetry backlog full while throttled; dropped oldest events" + ); + } + match result { Ok(()) => { + in_flight.batch.clear(); *self.throttle.lock().expect("poisoned telemetry throttle") = Throttle::default(); true } + // `in_flight` puts the batch back when it drops. Err(TelemetryExportError::Throttled(_)) if requeue_if_throttled => { self.back_off(); - self.requeue(batch); false } - Err(_) => false, + Err(_) => { + in_flight.batch.clear(); + false + } } } + fn pending_cap(&self) -> usize { + MAX_PENDING_EVENTS.max(self.batch_size) + } + fn throttled(&self) -> bool { let throttle = self.throttle.lock().expect("poisoned telemetry throttle"); throttle.until.is_some_and(|until| Instant::now() < until) @@ -225,21 +278,18 @@ impl TelemetryClient { throttle.until = Some(Instant::now() + throttle.backoff); } - /// Put a throttled batch back ahead of events queued since it was drained. - fn requeue(&self, mut batch: Vec) { + /// Put a batch back ahead of events queued since it was drained. + fn requeue(&self, batch: Vec) { let mut pending = self.pending.lock().expect("poisoned telemetry queue"); - batch.append(&mut pending); - let cap = MAX_PENDING_EVENTS.max(self.batch_size); - let excess = batch.len().saturating_sub(cap); + for log in batch.into_iter().rev() { + pending.push_front(log); + } + let excess = pending.len().saturating_sub(self.pending_cap()); if excess > 0 { - batch.drain(..excess); - tracing::debug!( - dropped = excess, - "telemetry backlog full while throttled; dropping oldest events" - ); + pending.drain(..excess); + self.dropped.fetch_add(excess, Ordering::Relaxed); } - self.queue_count.store(batch.len(), Ordering::Release); - *pending = batch; + self.queue_count.store(pending.len(), Ordering::Release); } fn drain_pending(&self, limit: usize) -> Vec { @@ -523,7 +573,7 @@ mod tests { .map(|i| sample_log(&format!("e{i}"))) .collect::>(); client.queue_count.store(backlog.len(), Ordering::Release); - *client.pending.lock().unwrap() = backlog; + *client.pending.lock().unwrap() = backlog.into(); client.flush_bounded().await; @@ -548,7 +598,7 @@ mod tests { .map(|i| sample_log(&format!("e{i}"))) .collect::>(); client.queue_count.store(backlog.len(), Ordering::Release); - *client.pending.lock().unwrap() = backlog; + *client.pending.lock().unwrap() = backlog.into(); client.enqueue(sample_log("e119")); wait_until(|| exporter.ids().len() == 3).await; @@ -559,6 +609,110 @@ mod tests { client.close().await; } + #[tokio::test] + async fn enqueue_caps_backlog_while_throttled() { + let exporter = ThrottlingExporter::new(usize::MAX); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 1, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + + client.enqueue(sample_log("first")); + wait_until(|| client.throttled()).await; + for i in 0..MAX_PENDING_EVENTS + 10 { + client.enqueue(sample_log(&format!("e{i}"))); + } + + { + let pending = client.pending.lock().unwrap(); + assert_eq!(pending.len(), MAX_PENDING_EVENTS); + assert_eq!(pending[0].frontend_log_event_id, "e10"); + assert_eq!( + pending[MAX_PENDING_EVENTS - 1].frontend_log_event_id, + format!("e{}", MAX_PENDING_EVENTS + 9) + ); + } + assert_eq!( + client.queue_count.load(Ordering::Acquire), + MAX_PENDING_EVENTS + ); + assert_eq!(client.dropped.load(Ordering::Relaxed), 11); + client.close().await; + } + + #[tokio::test] + async fn close_stops_at_first_failed_post_and_clears_the_rest() { + let exporter = ThrottlingExporter::new(usize::MAX); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 2, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + let backlog = (0..120) + .map(|i| sample_log(&format!("e{i}"))) + .collect::>(); + client.queue_count.store(backlog.len(), Ordering::Release); + *client.pending.lock().unwrap() = backlog; + + client.close().await; + + assert_eq!(exporter.ids().len(), 1); + assert_eq!(exporter.ids()[0].len(), MAX_EVENTS_PER_EXPORT); + assert!(client.pending.lock().unwrap().is_empty()); + assert_eq!(client.queue_count.load(Ordering::Acquire), 0); + } + + #[tokio::test] + async fn timed_out_session_release_flush_keeps_in_flight_batch() { + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 100, + flush_interval: Duration::from_secs(60), + close_flush_timeout: Duration::from_millis(50), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(HangingExporter)) + .expect("telemetry runtime should start"); + client.enqueue(sample_log("one")); + client.enqueue(sample_log("two")); + + client.flush_bounded().await; + + let pending = client.pending.lock().unwrap(); + let ids = pending + .iter() + .map(|log| log.frontend_log_event_id.as_str()) + .collect::>(); + assert_eq!(ids, ["one", "two"]); + } + + /// Never completes an export. + struct HangingExporter; + + impl TelemetryExporter for HangingExporter { + fn export<'a>( + &'a self, + _request: TelemetryRequest, + ) -> std::pin::Pin< + Box< + dyn std::future::Future + + Send + + 'a, + >, + > { + Box::pin(std::future::pending::< + super::super::exporter::TelemetryExportResult, + >()) + } + } + #[tokio::test] async fn requeue_keeps_oldest_first_and_caps_backlog() { let config = TelemetryConfig { @@ -571,12 +725,20 @@ mod tests { .expect("telemetry runtime should start"); *client.pending.lock().unwrap() = (0..5).map(|i| sample_log(&format!("new{i}"))).collect(); - client.requeue((0..18).map(|i| sample_log(&format!("old{i}"))).collect()); + client.requeue( + (0..MAX_PENDING_EVENTS - 2) + .map(|i| sample_log(&format!("old{i}"))) + .collect(), + ); let pending = client.pending.lock().unwrap(); assert_eq!(pending.len(), MAX_PENDING_EVENTS); assert_eq!(pending[0].frontend_log_event_id, "old3"); - assert_eq!(pending[19].frontend_log_event_id, "new4"); + assert_eq!( + pending[MAX_PENDING_EVENTS - 1].frontend_log_event_id, + "new4" + ); + assert_eq!(client.dropped.load(Ordering::Relaxed), 3); assert_eq!(client.queue_count.load(Ordering::Acquire), pending.len()); } From 043ceb68479a8a890d3355f9c6c6cef8ef075d1a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 21:29:34 +0000 Subject: [PATCH 4/7] fix(telemetry): re-queue only rejected batches; never into a closed client Review follow-up. A batch whose export was cancelled by the flush timeout was re-queued even though the server may already have accepted it, so it could be delivered twice. Only a definitive 429/503 re-queues now. A cancelled export drops its batch, as before this PR, and the in-flight guard is gone. A background export that is throttled after close() has given up waiting for it no longer re-queues into the closed client: requeue drops the batch once the client is not active, checked under the queue lock. drain_pending now updates queue_count under the same lock, so the count can no longer wrap. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/telemetry/client.rs | 129 +++++++++++++++++++++++----------------- 1 file changed, 76 insertions(+), 53 deletions(-) diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index 84620bca..118482a2 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -69,22 +69,6 @@ struct Throttle { backoff: Duration, } -/// A drained batch whose export is in flight; still non-empty when dropped -/// (export throttled or cancelled), it goes back to the queue. -struct InFlight<'a> { - client: &'a TelemetryClient, - batch: Vec, - requeue_on_drop: bool, -} - -impl Drop for InFlight<'_> { - fn drop(&mut self) { - if self.requeue_on_drop && !self.batch.is_empty() { - self.client.requeue(std::mem::take(&mut self.batch)); - } - } -} - impl TelemetryClient { pub(super) fn new( config: &TelemetryConfig, @@ -221,19 +205,17 @@ impl TelemetryClient { } /// Export the oldest queued events in one request. Returns whether a - /// non-empty batch was delivered. With `requeue_if_throttled`, a throttled - /// batch, or one whose export is cancelled (flush timeout), is re-queued. + /// non-empty batch was delivered. With `requeue_if_throttled`, a batch the + /// endpoint rejected with 429/503 is re-queued. Any other failure, or a + /// cancelled export (flush timeout), drops it, since the server may + /// already have accepted it. async fn export_once(&self, requeue_if_throttled: bool) -> bool { - let mut in_flight = InFlight { - client: self, - batch: self.drain_pending(MAX_EVENTS_PER_EXPORT.max(self.batch_size)), - requeue_on_drop: requeue_if_throttled, - }; - if in_flight.batch.is_empty() { + let batch = self.drain_pending(MAX_EVENTS_PER_EXPORT.max(self.batch_size)); + if batch.is_empty() { return false; } - let result = export_batch(Arc::clone(&self.exporter), &in_flight.batch).await; + let result = export_batch(Arc::clone(&self.exporter), &batch).await; let dropped = self.dropped.swap(0, Ordering::Relaxed); if dropped > 0 { tracing::debug!( @@ -243,19 +225,15 @@ impl TelemetryClient { } match result { Ok(()) => { - in_flight.batch.clear(); *self.throttle.lock().expect("poisoned telemetry throttle") = Throttle::default(); true } - // `in_flight` puts the batch back when it drops. Err(TelemetryExportError::Throttled(_)) if requeue_if_throttled => { self.back_off(); + self.requeue(batch); false } - Err(_) => { - in_flight.batch.clear(); - false - } + Err(_) => false, } } @@ -278,9 +256,17 @@ impl TelemetryClient { throttle.until = Some(Instant::now() + throttle.backoff); } - /// Put a batch back ahead of events queued since it was drained. + /// Put a batch back ahead of events queued since it was drained. Once the + /// client is closing nothing would send it, so it is dropped instead. fn requeue(&self, batch: Vec) { let mut pending = self.pending.lock().expect("poisoned telemetry queue"); + if self.state.load(Ordering::Acquire) != STATE_ACTIVE { + tracing::debug!( + abandoned = batch.len(), + "telemetry client closed during a throttled export; dropping its events" + ); + return; + } for log in batch.into_iter().rev() { pending.push_front(log); } @@ -293,12 +279,10 @@ impl TelemetryClient { } fn drain_pending(&self, limit: usize) -> Vec { - let drained = { - let mut pending = self.pending.lock().expect("poisoned telemetry queue"); - let n = pending.len().min(limit); - pending.drain(..n).collect::>() - }; - self.queue_count.fetch_sub(drained.len(), Ordering::AcqRel); + let mut pending = self.pending.lock().expect("poisoned telemetry queue"); + let n = pending.len().min(limit); + let drained = pending.drain(..n).collect::>(); + self.queue_count.store(pending.len(), Ordering::Release); drained } @@ -670,7 +654,7 @@ mod tests { } #[tokio::test] - async fn timed_out_session_release_flush_keeps_in_flight_batch() { + async fn timed_out_flush_does_not_requeue_in_flight_batch() { let config = TelemetryConfig { enabled: Some(true), batch_size: 100, @@ -678,25 +662,62 @@ mod tests { close_flush_timeout: Duration::from_millis(50), ..TelemetryConfig::default() }; - let client = TelemetryClient::new(&config, Arc::new(HangingExporter)) - .expect("telemetry runtime should start"); + let client = TelemetryClient::new( + &config, + Arc::new(SlowThrottlingExporter::new(Duration::from_secs(3600))), + ) + .expect("telemetry runtime should start"); client.enqueue(sample_log("one")); client.enqueue(sample_log("two")); + // The server may already have accepted a batch whose response came + // too late, so a cancelled export is not sent again. client.flush_bounded().await; - let pending = client.pending.lock().unwrap(); - let ids = pending - .iter() - .map(|log| log.frontend_log_event_id.as_str()) - .collect::>(); - assert_eq!(ids, ["one", "two"]); + assert!(client.pending.lock().unwrap().is_empty()); + assert_eq!(client.queue_count.load(Ordering::Acquire), 0); } - /// Never completes an export. - struct HangingExporter; + #[tokio::test] + async fn throttled_export_finishing_after_close_is_dropped() { + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 1, + flush_interval: Duration::from_secs(60), + close_flush_timeout: Duration::from_millis(20), + ..TelemetryConfig::default() + }; + let exporter = Arc::new(SlowThrottlingExporter::new(Duration::from_millis(200))); + let client = TelemetryClient::new(&config, exporter.clone()) + .expect("telemetry runtime should start"); + client.enqueue(sample_log("one")); + wait_until(|| exporter.calls.load(Ordering::Acquire) == 1).await; + + // close() gives up waiting for the in-flight background export. + client.close().await; + assert_eq!(client.state.load(Ordering::Acquire), STATE_CLOSED); + wait_until(|| client.flush_lock.try_lock().is_ok()).await; - impl TelemetryExporter for HangingExporter { + assert!(client.pending.lock().unwrap().is_empty()); + assert_eq!(client.queue_count.load(Ordering::Acquire), 0); + } + + /// Answers every export with a throttle after `delay`. + struct SlowThrottlingExporter { + delay: Duration, + calls: AtomicUsize, + } + + impl SlowThrottlingExporter { + fn new(delay: Duration) -> Self { + Self { + delay, + calls: AtomicUsize::new(0), + } + } + } + + impl TelemetryExporter for SlowThrottlingExporter { fn export<'a>( &'a self, _request: TelemetryRequest, @@ -707,9 +728,11 @@ mod tests { + 'a, >, > { - Box::pin(std::future::pending::< - super::super::exporter::TelemetryExportResult, - >()) + Box::pin(async move { + self.calls.fetch_add(1, Ordering::AcqRel); + tokio::time::sleep(self.delay).await; + Err(TelemetryExportError::Throttled("HTTP 429".to_string())) + }) } } From edf2bbedea415298fab2962564579b00b4660447 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 21:48:56 +0000 Subject: [PATCH 5/7] fix(telemetry): re-queue a throttled batch before backing off Review follow-up. Setting the backoff before the batch was back in the queue let an observer of throttled() run ahead of the re-queue, which could make the close tests flaky. Also say in the changelog that a post holds max(batch_size, 1000) events. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- NEXT_CHANGELOG.md | 2 +- src/telemetry/client.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 0f00099d..f85b7049 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -26,7 +26,7 @@ changes go in their respective binding's NEXT_CHANGELOG. ### Fixed - `Session::open` authenticates once before resolving feature flags. A failed OAuth token request now fails the open immediately instead of being sent a second time by CreateSession. -- Telemetry batches rejected with HTTP 429/503 are kept and sent again after a backoff instead of being dropped, at most 1,000 events per request, and telemetry retries log at debug instead of warn. Flushes on session close never wait out the backoff. +- Telemetry batches rejected with HTTP 429/503 are kept and sent again after a backoff instead of being dropped, at most 1,000 events per request (or one batch, if larger), and telemetry retries log at debug instead of warn. Flushes on session close never wait out the backoff. --- *Note: When making changes, please add your change under the appropriate diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index 118482a2..3b65d75a 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -228,9 +228,10 @@ impl TelemetryClient { *self.throttle.lock().expect("poisoned telemetry throttle") = Throttle::default(); true } + // Re-queue first, so whoever sees the throttle also sees the batch. Err(TelemetryExportError::Throttled(_)) if requeue_if_throttled => { - self.back_off(); self.requeue(batch); + self.back_off(); false } Err(_) => false, From d552b29c791e1831f7a9a4da87fe7f6286d6d810 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 22:05:23 +0000 Subject: [PATCH 6/7] fix(telemetry): don't post session-release flushes into a throttle Review follow-up. While the client is still in use and throttled, the flush run when a host's last session closes now leaves the queue to the background flush instead of posting into the throttle window and doubling the backoff on every session close. close() also reports events dropped at the queue cap. A wiremock test checks that a 429/503 coming out of the HTTP retry loop (retries exhausted, or retry budget exceeded) classifies as Throttled. Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/telemetry/client.rs | 51 ++++++++++++++++++++++------ src/telemetry/databricks.rs | 66 +++++++++++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 10 deletions(-) diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index 3b65d75a..4f2c221a 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -171,8 +171,13 @@ impl TelemetryClient { self.flush_bounded().await; // The final flush stops at its first failed post; say what it left. let abandoned = self.drain_pending(usize::MAX).len(); - if abandoned > 0 { - tracing::debug!(abandoned, "telemetry client closed with undelivered events"); + let dropped = self.dropped.swap(0, Ordering::Relaxed); + if abandoned > 0 || dropped > 0 { + tracing::debug!( + abandoned, + dropped, + "telemetry client closed with undelivered events" + ); } self.state.store(STATE_CLOSED, Ordering::Release); } @@ -196,12 +201,16 @@ impl TelemetryClient { } /// Session-release and close flush. Sends everything queued without - /// waiting out a backoff. While the client stays in use a throttled batch - /// is kept; once it is closing, it is dropped as before. + /// waiting out a backoff. While the client stays in use and is throttled, + /// the queue is left for the background flush after the backoff; once it + /// is closing, one attempt is made and a throttled batch is dropped. async fn flush_once_wait(self: &Arc) { let _guard = self.flush_lock.lock().await; - let requeue_if_throttled = self.state.load(Ordering::Acquire) == STATE_ACTIVE; - while self.export_once(requeue_if_throttled).await {} + let active = self.state.load(Ordering::Acquire) == STATE_ACTIVE; + if active && self.throttled() { + return; + } + while self.export_once(active).await {} } /// Export the oldest queued events in one request. Returns whether a @@ -530,19 +539,41 @@ mod tests { client.enqueue(sample_log("one")); wait_until(|| client.throttled()).await; - // The flush run when a host's last session closes ignores the backoff, - // but the client stays in use, so a throttled batch is kept. + // The flush run when a host's last session closes doesn't post into an + // active throttle; the client stays in use, so the batch stays queued + // for the background flush and the backoff is not extended. client.flush_bounded().await; - assert_eq!(exporter.ids(), [vec!["one"], vec!["one"]]); + assert_eq!(exporter.ids(), [vec!["one"]]); assert_eq!(client.pending.lock().unwrap().len(), 1); assert_eq!( client.throttle.lock().unwrap().backoff, - INITIAL_THROTTLE_BACKOFF * 2 + INITIAL_THROTTLE_BACKOFF ); client.close().await; } + #[tokio::test] + async fn session_release_flush_requeues_when_it_gets_throttled() { + let exporter = ThrottlingExporter::new(1); + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 100, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let client = TelemetryClient::new(&config, Arc::new(exporter.clone())) + .expect("telemetry runtime should start"); + client.enqueue(sample_log("one")); + + client.flush_bounded().await; + + assert_eq!(exporter.ids(), [vec!["one"]]); + assert_eq!(client.pending.lock().unwrap().len(), 1); + assert!(client.throttled()); + client.close().await; + } + #[tokio::test] async fn flush_sends_backlog_in_bounded_posts() { let exporter = ThrottlingExporter::new(0); diff --git a/src/telemetry/databricks.rs b/src/telemetry/databricks.rs index 0a722198..818a7cb5 100644 --- a/src/telemetry/databricks.rs +++ b/src/telemetry/databricks.rs @@ -110,6 +110,7 @@ fn endpoint_url(host: &str, endpoint: TelemetryEndpoint) -> String { #[cfg(test)] mod tests { use super::*; + use std::time::Duration; #[test] fn endpoint_url_normalizes_host_and_endpoint() { @@ -146,6 +147,71 @@ mod tests { )); } + /// Export through a real `DatabricksHttpClient` (with its retry loop) + /// against a mock `/telemetry-ext` that always answers `status`. + async fn export_against(status: u16, overall_timeout: Duration) -> TelemetryExportResult { + use crate::auth::PersonalAccessToken; + use crate::client::retry::RetryConfigOverrides; + use crate::client::retry::{build_retry_configs, RequestCategory, RetryConfig}; + use crate::client::HttpClientConfig; + use std::collections::HashMap; + use wiremock::matchers::{method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/telemetry-ext")) + .respond_with(ResponseTemplate::new(status).insert_header("Retry-After", "1")) + .mount(&server) + .await; + let overrides = HashMap::from([( + RequestCategory::Telemetry, + RetryConfigOverrides { + min_wait: Some(Duration::from_millis(10)), + max_wait: Some(Duration::from_millis(10)), + overall_timeout: Some(overall_timeout), + max_retries: Some(2), + ..Default::default() + }, + )]); + let client = DatabricksHttpClient::new( + HttpClientConfig::default(), + build_retry_configs(&RetryConfig::default(), &overrides), + ) + .unwrap(); + client.set_auth_provider(Arc::new(PersonalAccessToken::new("token".to_string()))); + let exporter = DatabricksTelemetryExporter::new( + &server.uri(), + Arc::new(client), + TelemetryEndpoint::Authenticated, + ); + exporter + .export(TelemetryRequest { + upload_time: 1, + proto_logs: vec!["{}".to_string()], + }) + .await + } + + #[tokio::test] + async fn rate_limited_export_through_retry_loop_is_throttled() { + for status in [429, 503] { + // Retries exhausted, and retry budget exceeded before a retry. + for budget in [Duration::from_secs(10), Duration::from_millis(1)] { + let result = export_against(status, budget).await; + assert!( + matches!(result, Err(TelemetryExportError::Throttled(_))), + "HTTP {status}, budget {budget:?}: {result:?}" + ); + } + } + let result = export_against(500, Duration::from_secs(10)).await; + assert!( + matches!(result, Err(TelemetryExportError::Export(_))), + "{result:?}" + ); + } + #[test] fn build_export_request_sets_method_url_json_body_and_content_type() { let telemetry_request = TelemetryRequest { From 7fcd4522bfa75c01667e9a8bdfea9aae01739540 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 22:17:20 +0000 Subject: [PATCH 7/7] fix(telemetry): skip flush spawns while a background flush is draining Review follow-up. While a throttle backlog drains, the queue stays at or above batch_size, so every enqueue spawned a flush task that only failed to take the flush lock. A flag set for the length of a background flush now skips those spawns; the running flush re-checks the queue before it exits. Also correct two doc comments (the closing flush stops at its first failed post; the cap is mainly reached while throttled). Co-authored-by: Isaac Signed-off-by: Vu Anh Phung --- src/telemetry/client.rs | 56 +++++++++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 8 deletions(-) diff --git a/src/telemetry/client.rs b/src/telemetry/client.rs index 4f2c221a..3dd9501d 100644 --- a/src/telemetry/client.rs +++ b/src/telemetry/client.rs @@ -16,7 +16,7 @@ use super::exporter::{export_batch, TelemetryExportError, TelemetryExporter}; use super::models::TelemetryFrontendLog; use crate::config::TelemetryConfig; use std::collections::VecDeque; -use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use tokio::runtime::{Handle, Runtime}; @@ -34,8 +34,8 @@ const INITIAL_THROTTLE_BACKOFF: Duration = Duration::from_secs(1); const INITIAL_THROTTLE_BACKOFF: Duration = Duration::from_millis(200); const MAX_THROTTLE_BACKOFF: Duration = Duration::from_secs(30); /// Most events queued (at least one batch); past this the oldest are dropped. -/// Only reached while throttled. Sized for several seconds of backoff at ~1k -/// events/s (~14 MB). +/// Mainly reached while throttled (or behind a stuck export). Sized for +/// several seconds of backoff at ~1k events/s (~14 MB). #[cfg(not(test))] const MAX_PENDING_EVENTS: usize = 10_000; #[cfg(test)] @@ -56,6 +56,9 @@ pub(super) struct TelemetryClient { queue_count: AtomicUsize, /// Events dropped because the queue was full, not yet logged. dropped: AtomicUsize, + /// A background flush is running; it re-checks the queue before exiting, + /// so `enqueue` need not spawn another. + background_flushing: AtomicBool, flush_lock: tokio::sync::Mutex<()>, throttle: Mutex, state: AtomicU8, @@ -69,6 +72,15 @@ struct Throttle { backoff: Duration, } +/// Clears the flag when dropped, including if the flush is cancelled. +struct ClearOnDrop<'a>(&'a AtomicBool); + +impl Drop for ClearOnDrop<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + impl TelemetryClient { pub(super) fn new( config: &TelemetryConfig, @@ -93,6 +105,7 @@ impl TelemetryClient { pending: Mutex::new(VecDeque::new()), queue_count: AtomicUsize::new(0), dropped: AtomicUsize::new(0), + background_flushing: AtomicBool::new(false), flush_lock: tokio::sync::Mutex::new(()), throttle: Mutex::new(Throttle::default()), state: AtomicU8::new(STATE_ACTIVE), @@ -120,7 +133,10 @@ impl TelemetryClient { pending.len() }; - if count >= self.batch_size && !self.throttled() { + if count >= self.batch_size + && !self.background_flushing.load(Ordering::Acquire) + && !self.throttled() + { let client = Arc::clone(self); self.runtime_handle.spawn(async move { client.flush_once_if_idle().await; @@ -191,6 +207,8 @@ impl TelemetryClient { let Ok(_guard) = self.flush_lock.try_lock() else { return; }; + self.background_flushing.store(true, Ordering::Release); + let _flushing = ClearOnDrop(&self.background_flushing); // Keep going while a backlog left by throttling still fills a batch. loop { let delivered = self.export_once(true).await; @@ -200,10 +218,11 @@ impl TelemetryClient { } } - /// Session-release and close flush. Sends everything queued without - /// waiting out a backoff. While the client stays in use and is throttled, - /// the queue is left for the background flush after the backoff; once it - /// is closing, one attempt is made and a throttled batch is dropped. + /// Session-release and close flush. Sends everything queued, in bounded + /// posts, without waiting out a backoff. While the client stays in use and + /// is throttled, the queue is left for the background flush after the + /// backoff. Once it is closing, it stops at the first failed post and a + /// throttled batch is dropped. async fn flush_once_wait(self: &Arc) { let _guard = self.flush_lock.lock().await; let active = self.state.load(Ordering::Acquire) == STATE_ACTIVE; @@ -710,6 +729,27 @@ mod tests { assert_eq!(client.queue_count.load(Ordering::Acquire), 0); } + #[tokio::test] + async fn background_flush_flag_covers_the_running_flush() { + let config = TelemetryConfig { + enabled: Some(true), + batch_size: 1, + flush_interval: Duration::from_secs(60), + ..TelemetryConfig::default() + }; + let exporter = Arc::new(SlowThrottlingExporter::new(Duration::from_millis(100))); + let client = TelemetryClient::new(&config, exporter.clone()) + .expect("telemetry runtime should start"); + + client.enqueue(sample_log("one")); + wait_until(|| exporter.calls.load(Ordering::Acquire) == 1).await; + // Enqueues while the flush runs don't start more background flushes. + assert!(client.background_flushing.load(Ordering::Acquire)); + wait_until(|| !client.background_flushing.load(Ordering::Acquire)).await; + assert_eq!(exporter.calls.load(Ordering::Acquire), 1); + client.close().await; + } + #[tokio::test] async fn throttled_export_finishing_after_close_is_dropped() { let config = TelemetryConfig {