diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 4de607eb..3ea5a581 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -24,6 +24,7 @@ use crate::kernel_error::{Error, Result}; use crate::klog::{debug, error, info, warn}; use crate::reader::cloudfetch::chunk_downloader::ChunkDownloader; use crate::reader::cloudfetch::link_fetcher::ChunkLinkFetcher; +use crate::reader::ResultReaderMetrics; use crate::types::cloudfetch::{ ChunkEntry, ChunkState, CloudFetchConfig, DEFAULT_CHUNK_READY_TIMEOUT_SECS, }; @@ -32,7 +33,7 @@ use arrow_schema::SchemaRef; use arrow_select::concat::concat_batches; use dashmap::DashMap; use std::collections::VecDeque; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicI64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use tokio::sync::Notify; use tokio_util::sync::CancellationToken; @@ -168,6 +169,8 @@ pub struct StreamingCloudFetchProvider { // `Arc<...>` so spawned download tasks can hold their own clone // without keeping the whole provider alive past stream end. refresh_coordinator: Arc, + + metrics: Arc, } /// Coordinates concurrent batched link-refresh attempts. @@ -201,10 +204,90 @@ struct DownloadCtx { refresh_coordinator: Arc, cancel_token: CancellationToken, statement_id: Option>, + metrics: Arc, max_retries: u32, retry_delay: std::time::Duration, } +#[derive(Debug)] +struct CloudFetchMetrics { + total_chunks_present: Option, + total_chunks_iterated: AtomicI32, + chunks_downloaded: AtomicI32, + initial_chunk_latency_ms: AtomicI64, + slowest_chunk_latency_ms: AtomicI64, + sum_chunks_download_time_ms: AtomicI64, +} + +impl CloudFetchMetrics { + fn new(total_chunks_present: Option) -> Self { + Self { + total_chunks_present, + total_chunks_iterated: AtomicI32::new(0), + chunks_downloaded: AtomicI32::new(0), + initial_chunk_latency_ms: AtomicI64::new(-1), + slowest_chunk_latency_ms: AtomicI64::new(0), + sum_chunks_download_time_ms: AtomicI64::new(0), + } + } + + fn record_chunk_download(&self, chunk_index: i64, elapsed: std::time::Duration) { + let millis = elapsed.as_millis().try_into().unwrap_or(i64::MAX); + // `initial_chunk_latency` is the time to download chunk 0 + // specifically, not the first download to *complete*. Under + // concurrency the fastest/smallest chunk often finishes first, + // so a first-to-complete gate would report a misleading value. + // Gate strictly on `chunk_index == 0` to match the JDBC/C# + // drivers' `initialChunkLatency` semantic. + if chunk_index == 0 { + self.initial_chunk_latency_ms + .store(millis, Ordering::Release); + } + self.slowest_chunk_latency_ms + .fetch_max(millis, Ordering::AcqRel); + self.sum_chunks_download_time_ms + .fetch_add(millis, Ordering::AcqRel); + // Count completed downloads so `snapshot` can distinguish a + // real ~0ms download from "no download ever completed". Both + // `slowest`/`sum` atomics initialize to 0, so without this + // counter a stream dropped/errored before any download finished + // would report `Some(0)` — indistinguishable from a genuine + // 0ms download and skewing server-side latency aggregates. + self.chunks_downloaded.fetch_add(1, Ordering::AcqRel); + } + + fn record_chunk_iterated(&self) { + self.total_chunks_iterated.fetch_add(1, Ordering::AcqRel); + } + + fn snapshot(&self) -> ResultReaderMetrics { + let initial = self.initial_chunk_latency_ms.load(Ordering::Acquire); + let iterated = self.total_chunks_iterated.load(Ordering::Acquire); + // Only emit `slowest`/`sum` once at least one download has + // completed. Both atomics initialize to 0, so gating on this + // counter keeps a no-download snapshot reporting `None` rather + // than a misleading `Some(0)` — mirroring the `-1` sentinel / + // `None` treatment of `initial_chunk_latency` above. + let downloaded = self.chunks_downloaded.load(Ordering::Acquire) > 0; + ResultReaderMetrics { + total_chunks_present: self.total_chunks_present, + total_chunks_iterated: Some(iterated), + initial_chunk_latency: (initial >= 0) + .then(|| std::time::Duration::from_millis(initial as u64)), + slowest_chunk_latency: downloaded.then(|| { + std::time::Duration::from_millis( + self.slowest_chunk_latency_ms.load(Ordering::Acquire) as u64, + ) + }), + sum_chunks_download_time: downloaded.then(|| { + std::time::Duration::from_millis( + self.sum_chunks_download_time_ms.load(Ordering::Acquire) as u64, + ) + }), + } + } +} + impl std::fmt::Debug for StreamingCloudFetchProvider { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("StreamingCloudFetchProvider") @@ -261,6 +344,7 @@ impl StreamingCloudFetchProvider { config: CloudFetchConfig, link_fetcher: Arc, chunk_downloader: Arc, + total_chunks_present: Option, runtime_handle: tokio::runtime::Handle, ) -> Arc { let statement_id = link_fetcher.statement_id().map(Arc::from); @@ -281,6 +365,7 @@ impl StreamingCloudFetchProvider { runtime_handle, statement_id, refresh_coordinator: Arc::new(RefreshCoordinator::default()), + metrics: Arc::new(CloudFetchMetrics::new(total_chunks_present)), }); // Start background initialization that fetches links and schedules downloads @@ -379,6 +464,7 @@ impl StreamingCloudFetchProvider { // Move to next chunk let next_chunk = self.current_chunk_index.fetch_add(1, Ordering::Release) + 1; + self.metrics.record_chunk_iterated(); debug!( "Released chunk {}: chunks_in_memory={}/{}, consumer advancing to {}", @@ -564,6 +650,7 @@ impl StreamingCloudFetchProvider { refresh_coordinator: Arc::clone(&self.refresh_coordinator), cancel_token: self.cancel_token.clone(), statement_id: self.statement_id.clone(), + metrics: Arc::clone(&self.metrics), max_retries: self.config.max_retries, retry_delay: self.config.retry_delay, }; @@ -765,8 +852,13 @@ impl StreamingCloudFetchProvider { }; // Attempt download + let download_started = std::time::Instant::now(); match ctx.downloader.download(&link).await { - Ok(batches) => return Ok(batches), + Ok(batches) => { + ctx.metrics + .record_chunk_download(chunk_index, download_started.elapsed()); + return Ok(batches); + } Err(e) => { // Every completed download failure consumes the hard attempt // budget, even when its link became stale while in flight. @@ -853,6 +945,26 @@ impl StreamingCloudFetchProvider { } } + pub(crate) fn metrics(&self) -> Option { + let snapshot = self.metrics.snapshot(); + // Surface metrics whenever *any* datum was captured, not just + // once a chunk has been iterated (released from the buffer). + // `total_chunks_present` is known from the manifest at + // construction and `initial_chunk_latency` is stamped at + // chunk-0 download completion — both fire before the first + // `record_chunk_iterated`. Gating strictly on `iterated > 0` + // would drop this data for a stream that downloads but is + // dropped/errors before releasing any chunk, losing useful + // telemetry for partial/failed consumption. + let has_data = snapshot.total_chunks_present.is_some() + || snapshot + .total_chunks_iterated + .is_some_and(|count| count > 0) + || snapshot.initial_chunk_latency.is_some() + || snapshot.slowest_chunk_latency.is_some(); + has_data.then_some(snapshot) + } + /// Refresh presigned-URL links for `chunk_index` and every /// subsequent chunk whose download is still pending or in flight. /// @@ -1504,6 +1616,7 @@ mod tests { refresh_coordinator: Arc::new(RefreshCoordinator::default()), cancel_token: CancellationToken::new(), statement_id: None, + metrics: Arc::new(CloudFetchMetrics::new(Some(1))), max_retries: MAX_DOWNLOAD_ATTEMPTS, retry_delay: std::time::Duration::ZERO, }; diff --git a/src/reader/mod.rs b/src/reader/mod.rs index 5e0328de..02704873 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -38,6 +38,7 @@ use arrow_array::RecordBatch; use arrow_schema::{ArrowError, Field, Schema, SchemaRef}; use async_trait::async_trait; use std::sync::Arc; +use std::time::Duration; pub use cloudfetch::StreamingCloudFetchProvider as CloudFetchReader; @@ -469,6 +470,7 @@ impl ResultReaderFactory { self.config.clone(), link_fetcher, chunk_downloader, + total_chunk_count.and_then(|count| count.try_into().ok()), self.runtime_handle.clone(), ); @@ -590,6 +592,24 @@ pub trait ResultReader: Send + Sync { /// Get the next record batch, or None if end of results. async fn next_batch(&mut self) -> Result>; + + /// Optional reader-level metrics accumulated below `ResultStream`. + /// + /// CloudFetch overrides this to surface chunk download metrics into + /// statement telemetry. Inline/in-memory readers keep the default. + fn metrics(&self) -> Option { + None + } +} + +#[non_exhaustive] +#[derive(Debug, Clone, Copy, Default)] +pub struct ResultReaderMetrics { + pub total_chunks_present: Option, + pub total_chunks_iterated: Option, + pub initial_chunk_latency: Option, + pub slowest_chunk_latency: Option, + pub sum_chunks_download_time: Option, } /// Wrapper for StreamingCloudFetchProvider that implements ResultReader. @@ -612,6 +632,10 @@ impl ResultReader for CloudFetchResultReader { async fn next_batch(&mut self) -> Result> { self.provider.next_batch().await } + + fn metrics(&self) -> Option { + self.provider.metrics() + } } /// Reader for inline Arrow results. diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 7ace6520..8bcee62b 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -36,7 +36,7 @@ mod json; use crate::kernel_error::{Error, Result}; -use crate::reader::{ResultReader, ResultReaderAdapter}; +use crate::reader::{ResultReader, ResultReaderAdapter, ResultReaderMetrics}; use crate::types::sea::ResultManifest; use arrow_array::builder::StringBuilder; use arrow_array::{ArrayRef, RecordBatch}; @@ -240,6 +240,10 @@ impl ResultReader for ResultPostProcessor { None => Ok(Some(batch)), } } + + fn metrics(&self) -> Option { + self.inner.metrics() + } } /// Compare schemas by their field sequence including per-field diff --git a/src/result_stream.rs b/src/result_stream.rs index 79249879..678d0895 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -46,8 +46,9 @@ //! batch. use crate::kernel_error::{Error, Result}; -use crate::reader::ResultReader; +use crate::reader::{ResultReader, ResultReaderMetrics}; use crate::session::SessionInner; +use crate::telemetry::StatementTelemetry; use arrow_array::cast::AsArray; use arrow_array::types::{ Date32Type, Date64Type, Decimal128Type, Decimal256Type, DecimalType, Float32Type, Float64Type, @@ -439,7 +440,7 @@ pub struct ResultStream { /// directly. No `block_on` is performed anywhere on this path, so /// `ResultStream::next_batch` is safe to `.await` from any tokio /// runtime (including napi-rs's). - reader: Box, + reader: Option>, /// Cached schema. Filled in eagerly by /// [`ResultStream::from_reader`] (which is `async` because pulling @@ -484,6 +485,67 @@ pub struct ResultStream { /// owning `ExecutedStatement` (or its `Drop`) issues the close, so /// a second guard here would double-fire. close_guard: Option, + + telemetry: Option, +} + +struct ResultStreamTelemetry { + telemetry: StatementTelemetry, + finalized: bool, + consumed_recorded: bool, +} + +impl ResultStreamTelemetry { + fn new(telemetry: StatementTelemetry) -> Self { + Self { + telemetry, + finalized: false, + consumed_recorded: false, + } + } + + fn record_batch(&self, batch: &ResultBatch) { + match batch { + ResultBatch::Arrow(_) => self.record_result_batch(), + } + } + + fn record_result_batch(&self) { + self.telemetry.record_result_batch(); + } + + /// Finalize telemetry exactly once. + /// + /// `consumed` gates the consumption-latency stamp: it must be + /// `true` only on a terminal read path — the stream reaching its + /// natural end (`Ok(None)`) or erroring — and `false` on the + /// `Drop` path. `record_result_consumed` sets + /// `consumption_latency = started_at.elapsed()`, so stamping it on + /// a stream that was abandoned (or only partially read) and then + /// dropped would report caller think-time from statement start to + /// handle drop rather than the latency to actually consume the + /// result set, skewing `result_set_consumption_latency_millis`. + /// Chunk metrics and the terminal `finalize` still fire on every + /// path so a dropped stream is always reported. + fn finish( + &mut self, + metrics: Option, + error: Option<&Error>, + consumed: bool, + ) { + if self.finalized { + return; + } + if let Some(metrics) = metrics { + self.telemetry.record_chunk_metrics(metrics.into()); + } + if consumed && !self.consumed_recorded { + self.telemetry.record_result_consumed(); + self.consumed_recorded = true; + } + self.telemetry.finalize(error); + self.finalized = true; + } } /// Fire-and-forget `CloseStatement`-on-Drop for a server statement that @@ -532,13 +594,14 @@ impl ResultStream { pub(crate) async fn from_reader(reader: Box) -> Result { let schema = reader.schema().await?; Ok(Self { - reader, + reader: Some(reader), schema, current: None, prefetched: None, current_row_idx: 0, exhausted: false, close_guard: None, + telemetry: None, }) } @@ -569,6 +632,32 @@ impl ResultStream { Ok(stream) } + pub(crate) fn attach_telemetry(&mut self, telemetry: StatementTelemetry) { + self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); + } + + fn reader_metrics(&self) -> Option { + self.reader.as_ref().and_then(|reader| reader.metrics()) + } + + /// Finalize telemetry once, passing the reader's terminal metrics. + /// `reader` and `telemetry` are disjoint fields, so this borrows + /// cleanly under `&mut self`. `ResultStreamTelemetry::finish` is + /// idempotent, so redundant calls are no-ops. + /// + /// This is the **read-path** finalizer — it fires when the stream + /// reaches its natural end or errors, both of which count as + /// consuming the result set, so it always stamps consumption + /// latency. The `Drop` path calls `finish` directly with + /// `consumed = false` so an abandoned stream doesn't report + /// think-time as consumption latency. + fn finalize_telemetry(&mut self, error: Option<&Error>) { + let metrics = self.reader_metrics(); + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(metrics, error, true); + } + } + /// Result schema. Available before any batches have been pulled. /// Returns a cheap-clone `Arc` so callers can hold the /// schema independently of the stream (the FFI layer needs this @@ -602,23 +691,39 @@ impl ResultStream { if let Some(batch) = self.prefetched.take() { self.current = Some(batch); self.current_row_idx = 0; + if let (Some(telemetry), Some(batch)) = (&self.telemetry, self.current.as_ref()) { + telemetry.record_batch(batch); + } return Ok(self.current.as_ref()); } if self.exhausted { + self.finalize_telemetry(None); return Ok(None); } - match self.reader.next_batch().await? { - Some(rb) => { + let reader = self + .reader + .as_mut() + .expect("ResultStream reader is present until into_owned_batches consumes it"); + match reader.next_batch().await { + Ok(Some(rb)) => { self.current = Some(ResultBatch::Arrow(rb)); self.current_row_idx = 0; + if let (Some(telemetry), Some(batch)) = (&self.telemetry, self.current.as_ref()) { + telemetry.record_batch(batch); + } Ok(self.current.as_ref()) } - None => { + Ok(None) => { self.current = None; self.current_row_idx = 0; self.exhausted = true; + self.finalize_telemetry(None); Ok(None) } + Err(e) => { + self.finalize_telemetry(Some(&e)); + Err(e) + } } } @@ -633,9 +738,32 @@ impl ResultStream { /// terminal result at statement-construction time. pub(crate) async fn peek_first_batch(&mut self) -> Result> { if self.prefetched.is_none() && self.current.is_none() && !self.exhausted { - match self.reader.next_batch().await? { - Some(rb) => self.prefetched = Some(ResultBatch::Arrow(rb)), - None => self.exhausted = true, + let reader = self + .reader + .as_mut() + .expect("ResultStream reader is present until into_owned_batches consumes it"); + match reader.next_batch().await { + Ok(Some(rb)) => { + self.prefetched = Some(ResultBatch::Arrow(rb)); + // Stamp first-batch (result-set-ready) latency at fetch + // time, not when the caller later consumes the prefetched + // batch via `next_batch`. `record_result_batch` is + // idempotent (only stamps while unset), so the replay in + // `next_batch` is a no-op. This keeps + // `result_set_ready_latency_millis` reflecting when the + // result set became ready rather than the caller's + // think-time before the first `next_batch` pull. + if let (Some(telemetry), Some(batch)) = + (&self.telemetry, self.prefetched.as_ref()) + { + telemetry.record_batch(batch); + } + } + Ok(None) => self.exhausted = true, + Err(e) => { + self.finalize_telemetry(Some(&e)); + return Err(e); + } } } Ok(self.prefetched.as_ref()) @@ -726,19 +854,37 @@ impl ResultStream { /// while still letting in-memory readers iterate without a tokio /// runtime at all. Errors are surfaced once; subsequent calls /// after an `Err` keep returning `None`. - pub fn into_owned_batches(self) -> OwnedBatchIter { + pub fn into_owned_batches(mut self) -> OwnedBatchIter { // Preserve a peeked-but-not-yet-consumed first batch: it was // pulled from the reader, so it must be yielded ahead of the // reader's remaining batches or it would be silently dropped. - let prefetched = self.prefetched.map(|ResultBatch::Arrow(rb)| rb); + let prefetched = self.prefetched.take().map(|ResultBatch::Arrow(rb)| rb); OwnedBatchIter { - reader: self.reader, + reader: self + .reader + .take() + .expect("ResultStream reader is present until into_owned_batches consumes it"), prefetched, + telemetry: self.telemetry.take(), done: false, } } } +impl Drop for ResultStream { + fn drop(&mut self) { + // Drop is not a consumption path: the stream may have been + // abandoned before exhaustion (or never read at all), so pass + // `consumed = false` to avoid stamping caller think-time as + // consumption latency. `finish` still records chunk metrics + // and finalizes, so a dropped stream is always reported. + let metrics = self.reader_metrics(); + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(metrics, None, false); + } + } +} + /// Iterator over owned `RecordBatch`es produced by /// [`ResultStream::into_owned_batches`]. /// @@ -751,6 +897,7 @@ pub struct OwnedBatchIter { /// [`ResultStream::peek_first_batch`]); yielded before the reader's /// own batches so it isn't lost. prefetched: Option, + telemetry: Option, done: bool, } @@ -762,6 +909,9 @@ impl Iterator for OwnedBatchIter { return None; } if let Some(batch) = self.prefetched.take() { + if let Some(telemetry) = &self.telemetry { + telemetry.record_result_batch(); + } return Some(Ok(batch)); } // Runtime-aware blocking poll: uses block_in_place + the @@ -772,19 +922,46 @@ impl Iterator for OwnedBatchIter { // the nested-block_on panic from issue #19 on the sync // iterator path. match crate::util::runtime::block_on_current_runtime(self.reader.next_batch()) { - Ok(Some(batch)) => Some(Ok(batch)), + Ok(Some(batch)) => { + if let Some(telemetry) = &self.telemetry { + telemetry.record_result_batch(); + } + Some(Ok(batch)) + } Ok(None) => { self.done = true; + // Natural end of stream — the result set was fully + // consumed, so stamp consumption latency. + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), None, true); + } None } Err(e) => { self.done = true; + // Terminal error path also counts as consumption + // ending, so stamp consumption latency. + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), Some(&e), true); + } Some(Err(e)) } } } } +impl Drop for OwnedBatchIter { + fn drop(&mut self) { + // Drop without draining the iterator is not a consumption + // path (see `ResultStream`'s Drop): pass `consumed = false`. + // If iteration reached its natural end / error, `next` already + // finalized with `consumed = true` and this is a no-op. + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), None, false); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/session.rs b/src/session.rs index 1f990c85..b0a1ca90 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1851,6 +1851,7 @@ mod is_open_tests { use super::*; use crate::telemetry::test_support::CapturingTelemetryExporter; use crate::telemetry::{TelemetryExportResult, TelemetryExporter, TelemetryRequest}; + use crate::ResultBatch; use arrow_array::{Int64Array, RecordBatch}; use arrow_ipc::writer::StreamWriter; use arrow_schema::{DataType, Field, Schema}; @@ -2257,7 +2258,9 @@ mod is_open_tests { let mut stmt = session.statement(); stmt.spec().sql("SELECT 1 AS n"); - let _exec = stmt.execute().await.expect("execute succeeds"); + let mut exec = stmt.execute().await.expect("execute succeeds"); + assert!(exec.next_batch().await.expect("first batch").is_some()); + assert!(exec.next_batch().await.expect("stream exhausted").is_none()); session.close().await.expect("close succeeds"); let statement_log = exported_logs(&exporter) @@ -2278,8 +2281,8 @@ mod is_open_tests { "retry_count should be omitted until the transport reports a real value" ); assert!( - sql_log["sql_operation"].get("result_latency").is_none(), - "Phase 3 should not emit empty result latency placeholders" + sql_log["sql_operation"]["result_latency"].is_object(), + "consuming the result stream should record result latency" ); assert_eq!( sql_log["sql_operation"]["operation_detail"]["is_internal_call"], @@ -2364,7 +2367,13 @@ mod is_open_tests { stmt.spec().sql("SELECT 1 AS n"); let async_exec = stmt.submit().await.expect("submit succeeds"); let _ = async_exec.status().await.expect("status succeeds"); - let _stream = async_exec.await_result().await.expect("await succeeds"); + let mut stream = async_exec.await_result().await.expect("await succeeds"); + assert!(stream.next_batch().await.expect("first batch").is_some()); + assert!(stream + .next_batch() + .await + .expect("stream exhausted") + .is_none()); let _again = async_exec.fetch_result().await.expect("fetch succeeds"); session.close().await.expect("close succeeds"); @@ -2528,6 +2537,146 @@ mod is_open_tests { ); } + #[tokio::test] + async fn result_stream_exhaustion_exports_result_latency() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-result").await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + succeeded_inline_body("stmt-telemetry-result", &int64_batch("n", vec![1, 2, 3])), + ) + .await; + let exporter = CapturingTelemetryExporter::default(); + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(exporter.clone())); + let session = telemetry_test_session(&server, "sess-telemetry-result", telemetry).await; + + let mut stmt = session.statement(); + stmt.spec().sql("SELECT n FROM values"); + let mut exec = stmt.execute().await.expect("execute succeeds"); + let first = exec + .next_batch() + .await + .expect("first batch") + .expect("batch"); + let ResultBatch::Arrow(batch) = first; + assert_eq!(batch.num_rows(), 3); + assert!(exec.next_batch().await.expect("stream exhausted").is_none()); + session.close().await.expect("close succeeds"); + + let statement_log = exported_logs(&exporter) + .into_iter() + .find(|log| operation_type(log) == Some("EXECUTE_STATEMENT")) + .expect("statement event exported"); + let result_latency = + &statement_log["entry"]["sql_driver_log"]["sql_operation"]["result_latency"]; + assert!( + result_latency["result_set_ready_latency_millis"] + .as_i64() + .is_some(), + "first-batch latency should be recorded" + ); + assert!( + result_latency["result_set_consumption_latency_millis"] + .as_i64() + .is_some(), + "consumption latency should be recorded on exhaustion" + ); + } + + #[tokio::test] + async fn dropping_unexhausted_result_stream_finalizes_statement_telemetry() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-drop").await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + succeeded_inline_body("stmt-telemetry-drop", &int64_batch("n", vec![1])), + ) + .await; + let exporter = CapturingTelemetryExporter::default(); + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(exporter.clone())); + let session = telemetry_test_session(&server, "sess-telemetry-drop", telemetry).await; + + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let exec = stmt.execute().await.expect("execute succeeds"); + drop(exec); + session.close().await.expect("close succeeds"); + + let statement_log = exported_logs(&exporter) + .into_iter() + .find(|log| operation_type(log) == Some("EXECUTE_STATEMENT")) + .expect("statement event exported after drop"); + assert_eq!( + statement_log["entry"]["sql_driver_log"]["sql_statement_id"], + "stmt-telemetry-drop" + ); + } + + #[tokio::test] + async fn cloudfetch_consumption_exports_chunk_details() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-cloudfetch").await; + mount_close_any_statement(&server).await; + let batch = int64_batch("n", vec![1, 2]); + let ipc = arrow_ipc_bytes(&batch); + let chunk_path = "/cloud-fetch/stmt-telemetry-cloudfetch/chunk-0.arrow"; + Mock::given(method("GET")) + .and(path(chunk_path)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(ipc.clone())) + .mount(&server) + .await; + mount_execute( + &server, + succeeded_cloudfetch_body( + "stmt-telemetry-cloudfetch", + &batch, + &format!("{}{}", server.uri(), chunk_path), + ipc.len(), + ), + ) + .await; + let exporter = CapturingTelemetryExporter::default(); + let telemetry = TelemetryConfig { + enabled: true, + ..Default::default() + } + .with_exporter(std::sync::Arc::new(exporter.clone())); + let session = telemetry_test_session(&server, "sess-telemetry-cloudfetch", telemetry).await; + + let mut stmt = session.statement(); + stmt.spec().sql("SELECT n FROM cloudfetch"); + let mut exec = stmt.execute().await.expect("execute succeeds"); + assert!(exec.next_batch().await.expect("first batch").is_some()); + assert!(exec.next_batch().await.expect("stream exhausted").is_none()); + session.close().await.expect("close succeeds"); + + let statement_log = exported_logs(&exporter) + .into_iter() + .find(|log| operation_type(log) == Some("EXECUTE_STATEMENT")) + .expect("statement event exported"); + let sql_operation = &statement_log["entry"]["sql_driver_log"]["sql_operation"]; + assert_eq!(sql_operation["execution_result"], "EXTERNAL_LINKS"); + let chunk_details = &sql_operation["chunk_details"]; + assert_eq!(chunk_details["total_chunks_present"], 1); + assert_eq!(chunk_details["total_chunks_iterated"], 1); + assert!( + chunk_details["initial_chunk_latency_millis"] + .as_i64() + .is_some(), + "initial chunk latency should be recorded" + ); + } + async fn telemetry_test_session( server: &MockServer, expected_session_id: &str, @@ -2664,6 +2813,58 @@ mod is_open_tests { .to_string() } + fn succeeded_cloudfetch_body( + statement_id: &str, + batch: &RecordBatch, + chunk_url: &str, + byte_count: usize, + ) -> String { + let columns: Vec<_> = batch + .schema() + .fields() + .iter() + .enumerate() + .map(|(i, f)| { + json!({ + "name": f.name(), + "type_name": "BIGINT", + "type_text": "BIGINT", + "position": i as i32, + }) + }) + .collect(); + let expiration = (chrono::Utc::now() + chrono::Duration::hours(1)).to_rfc3339(); + + json!({ + "statement_id": statement_id, + "status": { "state": "SUCCEEDED" }, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": batch.num_columns() as i32, + "columns": columns, + }, + "total_chunk_count": 1, + "total_row_count": batch.num_rows() as i64, + "total_byte_count": byte_count as i64, + "truncated": false, + "result_compression": "", + }, + "result": { + "external_links": [{ + "external_link": chunk_url, + "expiration": expiration, + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": byte_count as i64, + "next_chunk_index": null, + }], + }, + }) + .to_string() + } + fn running_body(statement_id: &str) -> String { json!({ "statement_id": statement_id, diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index 156138a8..c3f12a0a 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -219,6 +219,9 @@ pub struct ExecutedAsyncStatement { /// every network round-trip. latest_status: Arc>, statement_telemetry: StatementTelemetry, + /// Set once result materialisation hands success finalization to + /// the returned `ResultStream`. + result_stream_owns_success_telemetry: AtomicBool, } impl ExecutedAsyncStatement { @@ -254,6 +257,7 @@ impl ExecutedAsyncStatement { owning: true, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry, + result_stream_owns_success_telemetry: AtomicBool::new(false), } } @@ -287,6 +291,7 @@ impl ExecutedAsyncStatement { owning: false, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), statement_telemetry: StatementTelemetry::noop(), + result_stream_owns_success_telemetry: AtomicBool::new(false), } } @@ -493,11 +498,7 @@ impl ExecutedAsyncStatement { if let Some(g) = cancel_guard.take() { g.defuse(); } - let result = self.materialise_result().await; - if result.is_ok() { - self.statement_telemetry.finalize(None); - } - return result; + return self.materialise_result().await; } StatementStatus::Failed(e) => { // Server already decided this is terminal — no @@ -559,11 +560,7 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); let result = async { self.valid.check()?; - let result = self.materialise_result().await; - if result.is_ok() { - self.statement_telemetry.finalize(None); - } - result + self.materialise_result().await } .instrument(span) .await; @@ -604,6 +601,7 @@ impl ExecutedAsyncStatement { self.closed.store(true, Ordering::Release); } let mut stream = ResultStream::from_reader(result.reader).await?; + stream.attach_telemetry(self.statement_telemetry.clone()); // SEA carries no row count on the async status either; for a // DML the count rides in the result set. Derive it once // (non-consuming) and record it onto the latest status so @@ -617,6 +615,8 @@ impl ExecutedAsyncStatement { } } } + self.result_stream_owns_success_telemetry + .store(true, Ordering::Release); Ok(stream) } None => { @@ -856,10 +856,16 @@ impl AsyncStatementCanceller { impl Drop for ExecutedAsyncStatement { fn drop(&mut self) { // Ensure submit-and-drop / status-only async statements still - // emit one terminal telemetry event. Handles consumed via - // await_result() / fetch_result() already finalized; the - // statement telemetry guard makes this idempotent. - self.statement_telemetry.finalize(None); + // emit one terminal telemetry event. Once a result stream has + // been returned, that stream owns success finalization so it can + // include result/chunk metrics even if this handle is dropped + // before the stream is consumed. + if !self + .result_stream_owns_success_telemetry + .load(Ordering::Acquire) + { + self.statement_telemetry.finalize(None); + } // `swap` (not `load`) so the shared `closed` flag — held by the // parent `Statement::last_closed` — reflects that Drop is now diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 95bc29bb..1903cc5c 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -378,6 +378,7 @@ impl Statement { self.last_closed = Some(Arc::clone(&closed)); let mut result_stream = ResultStream::from_reader(result.reader).await?; + result_stream.attach_telemetry(telemetry_for_body.clone()); // SEA puts no row count on the status envelope; for a DML it // returns the count as the result set. If the server didn't // already supply `num_modified_rows`, derive it from that @@ -396,7 +397,6 @@ impl Statement { closed, status, ); - telemetry_for_body.finalize(None); Ok(executed) } .instrument(span) @@ -559,7 +559,8 @@ impl Statement { self.last_statement_id = Some(result.statement_id.clone()); self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); - let result_stream = ResultStream::from_reader(result.reader).await?; + let mut result_stream = ResultStream::from_reader(result.reader).await?; + result_stream.attach_telemetry(telemetry_for_body.clone()); let executed = ExecutedStatement::new( Arc::clone(&self.session), result.statement_id, @@ -568,7 +569,6 @@ impl Statement { closed, result.status, ); - telemetry_for_body.finalize(None); Ok(DirectStatement::Completed(executed)) } DirectOutcome::Running(resp) => { diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 10d6b3fb..b5a12146 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -21,7 +21,7 @@ use super::models::{ OperationDetail, OperationType, OssSqlDriverTelemetryLog, ResultLatency, SqlExecutionEvent, StatementType, TelemetryClientContext, TelemetryFrontendLog, }; -use super::statement::{StatementTelemetry, StatementTelemetryContext}; +use super::statement::{ChunkMetrics, StatementTelemetry, StatementTelemetryContext}; use crate::client::DatabricksHttpClient; use crate::config::{AuthConfig, ConnectionConfig, TelemetryConfig}; use crate::kernel_error::Error as KernelError; @@ -251,6 +251,7 @@ impl RealConnectionTelemetry { execution_result: context.result_format, retry_count: context.retry_count, result_latency, + chunk_details: context.chunk_metrics.map(ChunkMetrics::into_details), operation_detail: Some(OperationDetail { n_operation_status_calls: Some(context.poll_count), operation_status_latency_millis: Some(duration_millis( diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs index c40030f7..4116141e 100644 --- a/src/telemetry/statement.rs +++ b/src/telemetry/statement.rs @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use super::models::{ExecutionResultFormat, OperationType, StatementType}; +use super::models::{ChunkDetails, ExecutionResultFormat, OperationType, StatementType}; use super::runtime::ConnectionTelemetry; use crate::kernel_error::Error as KernelError; use std::sync::atomic::{AtomicBool, Ordering}; @@ -62,6 +62,18 @@ impl StatementTelemetry { self.observer.record_poll(elapsed); } + pub(crate) fn record_result_batch(&self) { + self.observer.record_result_batch(); + } + + pub(crate) fn record_result_consumed(&self) { + self.observer.record_result_consumed(); + } + + pub(crate) fn record_chunk_metrics(&self, metrics: ChunkMetrics) { + self.observer.record_chunk_metrics(metrics); + } + pub(crate) fn finalize(&self, error: Option<&KernelError>) { self.observer.finalize(error); } @@ -71,9 +83,45 @@ pub(super) trait StatementOperationObserver: Send + Sync { fn on_statement_submitted(&self, statement_id: &str); fn on_result_metadata(&self, result_format: ExecutionResultFormat, is_compressed: bool); fn record_poll(&self, elapsed: Duration); + fn record_result_batch(&self); + fn record_result_consumed(&self); + fn record_chunk_metrics(&self, metrics: ChunkMetrics); fn finalize(&self, error: Option<&KernelError>); } +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct ChunkMetrics { + pub total_chunks_present: Option, + pub total_chunks_iterated: Option, + pub initial_chunk_latency: Option, + pub slowest_chunk_latency: Option, + pub sum_chunks_download_time: Option, +} + +impl From for ChunkMetrics { + fn from(metrics: crate::reader::ResultReaderMetrics) -> Self { + Self { + total_chunks_present: metrics.total_chunks_present, + total_chunks_iterated: metrics.total_chunks_iterated, + initial_chunk_latency: metrics.initial_chunk_latency, + slowest_chunk_latency: metrics.slowest_chunk_latency, + sum_chunks_download_time: metrics.sum_chunks_download_time, + } + } +} + +impl ChunkMetrics { + pub(crate) fn into_details(self) -> ChunkDetails { + ChunkDetails { + initial_chunk_latency_millis: self.initial_chunk_latency.map(duration_millis), + slowest_chunk_latency_millis: self.slowest_chunk_latency.map(duration_millis), + total_chunks_present: self.total_chunks_present, + total_chunks_iterated: self.total_chunks_iterated, + sum_chunks_download_time_millis: self.sum_chunks_download_time.map(duration_millis), + } + } +} + #[derive(Debug, Clone)] pub(crate) struct StatementTelemetryContext { pub statement_id: Option, @@ -87,6 +135,7 @@ pub(crate) struct StatementTelemetryContext { pub poll_latency: Duration, pub first_batch_latency: Option, pub consumption_latency: Option, + pub chunk_metrics: Option, } struct TelemetryObserver { @@ -97,6 +146,12 @@ struct TelemetryObserver { struct StatementTelemetryState { started_at: Instant, + /// Instant the first result batch became available (set once by + /// `record_result_batch`). Consumption latency is measured from + /// here, not from `started_at`, so it reflects time spent + /// iterating the result set rather than execution + polling + + /// result-ready time. + first_batch_at: Option, context: StatementTelemetryContext, } @@ -110,6 +165,7 @@ impl TelemetryObserver { connection, state: Mutex::new(StatementTelemetryState { started_at: Instant::now(), + first_batch_at: None, context: StatementTelemetryContext { statement_id: None, statement_type, @@ -122,6 +178,7 @@ impl TelemetryObserver { poll_latency: Duration::ZERO, first_batch_latency: None, consumption_latency: None, + chunk_metrics: None, }, }), finalized: AtomicBool::new(false), @@ -150,6 +207,41 @@ impl StatementOperationObserver for TelemetryObserver { } } + fn record_result_batch(&self) { + if let Ok(mut state) = self.state.lock() { + if state.context.first_batch_latency.is_none() { + let now = state.started_at.elapsed(); + state.context.first_batch_latency = Some(now); + // Anchor consumption timing to the moment the result set + // became ready, matching `result_set_consumption_latency` + // semantics (time to iterate the result set, not time + // since statement start). + state.first_batch_at = Some(state.started_at + now); + } + } + } + + fn record_result_consumed(&self) { + if let Ok(mut state) = self.state.lock() { + // Measure from when the first batch became available. If no + // batch was ever recorded (empty result, or errored before the + // first batch), there was nothing to consume, so report zero + // rather than statement start — the latter would conflate + // execution/polling time with consumption time. + let consumption = match state.first_batch_at { + Some(first_batch_at) => first_batch_at.elapsed(), + None => Duration::ZERO, + }; + state.context.consumption_latency = Some(consumption); + } + } + + fn record_chunk_metrics(&self, metrics: ChunkMetrics) { + if let Ok(mut state) = self.state.lock() { + state.context.chunk_metrics = Some(metrics); + } + } + fn finalize(&self, error: Option<&KernelError>) { if self.finalized.swap(true, Ordering::AcqRel) { return; @@ -179,5 +271,252 @@ impl StatementOperationObserver for NoOpObserver { fn record_poll(&self, _elapsed: Duration) {} + fn record_result_batch(&self) {} + + fn record_result_consumed(&self) {} + + fn record_chunk_metrics(&self, _metrics: ChunkMetrics) {} + fn finalize(&self, _error: Option<&KernelError>) {} } + +fn duration_millis(duration: Duration) -> i64 { + duration.as_millis().try_into().unwrap_or(i64::MAX) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::kernel_error::ErrorCode; + use crate::reader::test_utils::ErrorReader; + use crate::reader::{ResultReader, ResultReaderMetrics}; + use crate::result_stream::ResultStream; + use crate::telemetry::models::OperationType; + use crate::telemetry::runtime::{ConnectionTelemetry, TelemetrySessionContext}; + use arrow_array::RecordBatch; + use arrow_schema::Schema; + use async_trait::async_trait; + use std::future::Future; + use std::pin::Pin; + + #[derive(Default)] + struct CapturingConnectionTelemetry { + statement_events: Mutex>, + } + + struct CapturedStatementEvent { + context: StatementTelemetryContext, + error_code: Option, + error_message: Option, + } + + impl ConnectionTelemetry for CapturingConnectionTelemetry { + fn session(&self) -> Option> { + None + } + + fn emit_operation( + &self, + _operation_type: OperationType, + _elapsed: Duration, + _error: Option<&KernelError>, + ) { + } + + fn emit_statement_operation( + &self, + context: StatementTelemetryContext, + _elapsed: Duration, + error: Option<&KernelError>, + ) { + self.statement_events + .lock() + .expect("events mutex") + .push(CapturedStatementEvent { + context, + error_code: error.map(|e| e.code), + error_message: error.map(|e| e.message.clone()), + }); + } + + fn finish<'a>(&'a self) -> Pin + Send + 'a>> { + Box::pin(async {}) + } + } + + struct MetricsReader { + metrics: ResultReaderMetrics, + } + + #[async_trait] + impl ResultReader for MetricsReader { + async fn schema(&self) -> crate::Result { + Ok(Arc::new(Schema::empty())) + } + + async fn next_batch(&mut self) -> crate::Result> { + Ok(None) + } + + fn metrics(&self) -> Option { + Some(self.metrics) + } + } + + #[tokio::test] + async fn peek_first_batch_error_finalizes_statement_with_error_before_drop() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let reader = ErrorReader { + schema: Arc::new(Schema::empty()), + }; + let mut stream = ResultStream::from_reader(Box::new(reader)) + .await + .expect("schema succeeds"); + stream.attach_telemetry(telemetry); + + let error = match stream.peek_first_batch().await { + Ok(_) => panic!("peek should surface reader error"), + Err(error) => error, + }; + assert_eq!(error.code, ErrorCode::Internal); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!( + events.len(), + 1, + "peek error should finalize once; Drop must not overwrite it with success" + ); + let event = &events[0]; + assert_eq!(event.context.statement_type, StatementType::Sql); + assert_eq!(event.error_code, Some(ErrorCode::Internal)); + assert_eq!(event.error_message.as_deref(), Some("simulated read error")); + assert!( + event.context.consumption_latency.is_some(), + "failed consumption should still record result-consumption latency" + ); + } + + #[tokio::test] + async fn dropping_result_stream_finalizes_with_reader_metrics() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + let metrics = ResultReaderMetrics { + total_chunks_present: Some(5), + total_chunks_iterated: Some(2), + initial_chunk_latency: Some(Duration::from_millis(11)), + slowest_chunk_latency: Some(Duration::from_millis(29)), + sum_chunks_download_time: Some(Duration::from_millis(40)), + }; + let mut stream = ResultStream::from_reader(Box::new(MetricsReader { metrics })) + .await + .expect("schema succeeds"); + stream.attach_telemetry(telemetry); + + drop(stream); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1); + let event = &events[0]; + let chunk_metrics = event + .context + .chunk_metrics + .expect("drop should include reader metrics"); + assert_eq!(chunk_metrics.total_chunks_present, Some(5)); + assert_eq!(chunk_metrics.total_chunks_iterated, Some(2)); + assert_eq!( + chunk_metrics.initial_chunk_latency, + Some(Duration::from_millis(11)) + ); + assert_eq!( + chunk_metrics.slowest_chunk_latency, + Some(Duration::from_millis(29)) + ); + assert_eq!( + chunk_metrics.sum_chunks_download_time, + Some(Duration::from_millis(40)) + ); + assert!( + event.context.consumption_latency.is_none(), + "drop without consumption must NOT stamp consumption latency \ + (would report caller think-time, not time to consume the result set)" + ); + } + + #[test] + fn consumption_latency_is_measured_from_first_batch_not_statement_start() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + + // Simulate meaningful execution/polling/result-ready time before + // the first batch is available, then a much shorter consumption + // window after it. + std::thread::sleep(Duration::from_millis(40)); + telemetry.record_result_batch(); + std::thread::sleep(Duration::from_millis(5)); + telemetry.record_result_consumed(); + telemetry.finalize(None); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1); + let context = &events[0].context; + let first_batch = context + .first_batch_latency + .expect("first-batch latency recorded"); + let consumption = context + .consumption_latency + .expect("consumption latency recorded"); + // If consumption were measured from statement start it would be + // >= first_batch_latency. Anchored to the first batch, it only + // covers the post-ready window and is strictly smaller. + assert!( + consumption < first_batch, + "consumption latency ({consumption:?}) should exclude the \ + pre-first-batch execution/polling time ({first_batch:?})" + ); + } + + #[test] + fn consumption_latency_is_zero_when_no_batch_was_recorded() { + let connection = Arc::new(CapturingConnectionTelemetry::default()); + let telemetry = StatementTelemetry::new( + connection.clone(), + StatementType::Sql, + OperationType::ExecuteStatement, + ); + + // Empty result: execution/polling time elapses but no batch is ever + // recorded, so there is nothing to consume. + std::thread::sleep(Duration::from_millis(20)); + telemetry.record_result_consumed(); + telemetry.finalize(None); + + let events = connection.statement_events.lock().expect("events mutex"); + assert_eq!(events.len(), 1); + let context = &events[0].context; + assert!( + context.first_batch_latency.is_none(), + "no batch was recorded" + ); + assert_eq!( + context.consumption_latency, + Some(Duration::ZERO), + "with no batch recorded, consumption latency must be zero, not \ + statement lifetime" + ); + } +}