From 9c29453c71c508325feadd0739edb4ceb2e6d81a Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Wed, 19 Aug 2026 22:36:32 +0000 Subject: [PATCH] feat(telemetry): add result stream metrics Signed-off-by: Jay Xiao --- src/reader/cloudfetch/streaming_provider.rs | 82 +++++++- src/reader/mod.rs | 24 +++ src/reader/post_processor/mod.rs | 6 +- src/result_stream.rs | 109 ++++++++++- src/session.rs | 205 +++++++++++++++++++- src/statement/executed_async.rs | 5 +- src/statement/mutable.rs | 6 +- src/telemetry/mod.rs | 2 +- src/telemetry/runtime.rs | 3 +- src/telemetry/statement.rs | 79 +++++++- 10 files changed, 501 insertions(+), 20 deletions(-) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 4de607eb..d26ac6ad 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,67 @@ 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, + 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), + 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, elapsed: std::time::Duration) { + let millis = elapsed.as_millis().try_into().unwrap_or(i64::MAX); + let _ = self.initial_chunk_latency_ms.compare_exchange( + -1, + millis, + Ordering::AcqRel, + Ordering::Acquire, + ); + self.slowest_chunk_latency_ms + .fetch_max(millis, Ordering::AcqRel); + self.sum_chunks_download_time_ms + .fetch_add(millis, 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); + 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: Some(std::time::Duration::from_millis( + self.slowest_chunk_latency_ms.load(Ordering::Acquire) as u64, + )), + sum_chunks_download_time: Some(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 +321,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 +342,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 +441,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 +627,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 +829,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(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 +922,14 @@ impl StreamingCloudFetchProvider { } } + pub(crate) fn metrics(&self) -> Option { + let snapshot = self.metrics.snapshot(); + snapshot + .total_chunks_iterated + .is_some_and(|count| count > 0) + .then_some(snapshot) + } + /// Refresh presigned-URL links for `chunk_index` and every /// subsequent chunk whose download is still pending or in flight. /// @@ -1504,6 +1581,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..1202e300 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::{ChunkMetrics, StatementTelemetry}; use arrow_array::cast::AsArray; use arrow_array::types::{ Date32Type, Date64Type, Decimal128Type, Decimal256Type, DecimalType, Float32Type, Float64Type, @@ -484,6 +485,57 @@ 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(batch) => self.telemetry.record_result_batch(batch.num_rows()), + } + } + + fn finish(&mut self, metrics: Option, error: Option<&Error>) { + if self.finalized { + return; + } + if let Some(metrics) = metrics { + self.telemetry.record_chunk_metrics(ChunkMetrics { + 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, + }); + } + if !self.consumed_recorded { + self.telemetry.record_result_consumed(); + self.consumed_recorded = true; + } + self.telemetry.finalize(error); + self.finalized = true; + } +} + +impl Drop for ResultStreamTelemetry { + fn drop(&mut self) { + self.finish(None, None); + } } /// Fire-and-forget `CloseStatement`-on-Drop for a server statement that @@ -539,6 +591,7 @@ impl ResultStream { current_row_idx: 0, exhausted: false, close_guard: None, + telemetry: None, }) } @@ -569,6 +622,10 @@ impl ResultStream { Ok(stream) } + pub(crate) fn attach_telemetry(&mut self, telemetry: StatementTelemetry) { + self.telemetry = Some(ResultStreamTelemetry::new(telemetry)); + } + /// 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 +659,41 @@ 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 { + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), None); + } return Ok(None); } - match self.reader.next_batch().await? { - Some(rb) => { + match self.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; + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), None); + } Ok(None) } + Err(e) => { + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), Some(&e)); + } + Err(e) + } } } @@ -734,6 +809,7 @@ impl ResultStream { OwnedBatchIter { reader: self.reader, prefetched, + telemetry: self.telemetry, done: false, } } @@ -751,6 +827,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 +839,9 @@ impl Iterator for OwnedBatchIter { return None; } if let Some(batch) = self.prefetched.take() { + if let Some(telemetry) = &self.telemetry { + telemetry.record_batch(&ResultBatch::Arrow(batch.clone())); + } return Some(Ok(batch)); } // Runtime-aware blocking poll: uses block_in_place + the @@ -772,19 +852,38 @@ 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_batch(&ResultBatch::Arrow(batch.clone())); + } + Some(Ok(batch)) + } Ok(None) => { self.done = true; + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), None); + } None } Err(e) => { self.done = true; + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), Some(&e)); + } Some(Err(e)) } } } } +impl Drop for OwnedBatchIter { + fn drop(&mut self) { + if let Some(telemetry) = &mut self.telemetry { + telemetry.finish(self.reader.metrics(), None); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/session.rs b/src/session.rs index 802fdb8e..b668ccdd 100644 --- a/src/session.rs +++ b/src/session.rs @@ -1786,6 +1786,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}; @@ -2050,7 +2051,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) @@ -2149,7 +2152,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"); @@ -2183,6 +2192,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, @@ -2319,6 +2468,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 40d1c747..58a2d2be 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -471,8 +471,6 @@ impl ExecutedAsyncStatement { let result = self.materialise_result().await; if let Err(error) = &result { self.statement_telemetry.finalize(Some(error)); - } else { - self.statement_telemetry.finalize(None); } return result; } @@ -541,8 +539,6 @@ impl ExecutedAsyncStatement { let result = self.materialise_result().await; if let Err(error) = &result { self.statement_telemetry.finalize(Some(error)); - } else { - self.statement_telemetry.finalize(None); } result } @@ -581,6 +577,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 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/mod.rs b/src/telemetry/mod.rs index 78f920ca..8a3b862d 100644 --- a/src/telemetry/mod.rs +++ b/src/telemetry/mod.rs @@ -39,4 +39,4 @@ pub use models::DriverSystemConfiguration; pub(crate) use models::TelemetryRequest; pub(crate) use models::{ExecutionResultFormat, OperationType, StatementType}; pub(crate) use runtime::TelemetryRuntime; -pub(crate) use statement::StatementTelemetry; +pub(crate) use statement::{ChunkMetrics, StatementTelemetry}; diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 26dda67e..eed7d1a3 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; @@ -246,6 +246,7 @@ impl RealConnectionTelemetry { .consumption_latency .map(duration_millis), }), + 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 b47de428..83c2da96 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, rows: usize) { + self.observer.record_result_batch(rows); + } + + 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,33 @@ 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, rows: usize); + 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 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 +123,9 @@ pub(crate) struct StatementTelemetryContext { pub poll_latency: Duration, pub first_batch_latency: Option, pub consumption_latency: Option, + pub result_batch_count: i32, + pub result_row_count: i64, + pub chunk_metrics: Option, } struct TelemetryObserver { @@ -122,6 +161,9 @@ impl TelemetryObserver { poll_latency: Duration::ZERO, first_batch_latency: None, consumption_latency: None, + result_batch_count: 0, + result_row_count: 0, + chunk_metrics: None, }, }), finalized: AtomicBool::new(false), @@ -150,6 +192,31 @@ impl StatementOperationObserver for TelemetryObserver { } } + fn record_result_batch(&self, rows: usize) { + if let Ok(mut state) = self.state.lock() { + if state.context.first_batch_latency.is_none() { + state.context.first_batch_latency = Some(state.started_at.elapsed()); + } + state.context.result_batch_count = state.context.result_batch_count.saturating_add(1); + state.context.result_row_count = state + .context + .result_row_count + .saturating_add(rows.try_into().unwrap_or(i64::MAX)); + } + } + + fn record_result_consumed(&self) { + if let Ok(mut state) = self.state.lock() { + state.context.consumption_latency = Some(state.started_at.elapsed()); + } + } + + 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 +246,15 @@ impl StatementOperationObserver for NoOpObserver { fn record_poll(&self, _elapsed: Duration) {} + fn record_result_batch(&self, _rows: usize) {} + + 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) +}