diff --git a/src/client/sea.rs b/src/client/sea.rs index e2f28ef0..a4515b91 100644 --- a/src/client/sea.rs +++ b/src/client/sea.rs @@ -26,6 +26,7 @@ use crate::kernel_error::{Error, Result}; use crate::klog::{debug, warn}; use crate::metadata::sql::SqlCommandBuilder; use crate::reader::ResultReaderFactory; +use crate::telemetry::ExecutionResultFormat; use crate::types::cloudfetch::CloudFetchLink; use crate::types::sea::{ CreateSessionRequest, CreateSessionResponse, ExecuteParams, ExecuteStatementRequest, @@ -542,6 +543,31 @@ impl SeaRestTransport { }) } + fn telemetry_result_format(response: &ExecuteResponse) -> ExecutionResultFormat { + let Some(result) = response.result.as_ref() else { + return ExecutionResultFormat::FormatUnspecified; + }; + if result + .external_links + .as_ref() + .is_some_and(|links| !links.is_empty()) + { + ExecutionResultFormat::ExternalLinks + } else if result.inline_arrow_data.is_some() { + ExecutionResultFormat::InlineArrow + } else { + ExecutionResultFormat::FormatUnspecified + } + } + + fn telemetry_is_compressed(response: &ExecuteResponse) -> bool { + response + .manifest + .as_ref() + .and_then(|manifest| manifest.result_compression.as_deref()) + .is_some_and(|codec| !codec.is_empty()) + } + /// Execute a SQL statement end-to-end: call API → poll → create reader. /// /// Shared implementation for both user queries (`ExecuteStatement`) and @@ -626,10 +652,14 @@ impl SeaRestTransport { // cleaned up (status.state=Closed) AND expose // num_modified_rows / display_message / etc. without a second // GetStatementStatus round-trip. + let telemetry_result_format = Self::telemetry_result_format(&response); + let telemetry_is_compressed = Self::telemetry_is_compressed(&response); Ok(ExecuteResult { statement_id: response.statement_id, reader, manifest: response.manifest, + telemetry_result_format, + telemetry_is_compressed, status: response.status, }) } @@ -919,10 +949,14 @@ impl Transport for SeaRestTransport { return Err(e); } }; + let telemetry_result_format = Self::telemetry_result_format(&r); + let telemetry_is_compressed = Self::telemetry_is_compressed(&r); Ok(DirectOutcome::Completed(ExecuteResult { statement_id: r.statement_id, reader, manifest: r.manifest, + telemetry_result_format, + telemetry_is_compressed, status: r.status, })) } @@ -944,10 +978,14 @@ impl Transport for SeaRestTransport { StatementOutcome::Done(r) => { let reader_factory = self.reader_factory()?; let reader = reader_factory.create_reader(&r.statement_id, &r).await?; + let telemetry_result_format = Self::telemetry_result_format(&r); + let telemetry_is_compressed = Self::telemetry_is_compressed(&r); Ok(Some(ExecuteResult { statement_id: r.statement_id, reader, manifest: r.manifest, + telemetry_result_format, + telemetry_is_compressed, status: r.status, })) } diff --git a/src/client/transport.rs b/src/client/transport.rs index d5141ca5..783b1bc1 100644 --- a/src/client/transport.rs +++ b/src/client/transport.rs @@ -26,6 +26,7 @@ use crate::kernel_error::Result; use crate::reader::ResultReader; +use crate::telemetry::ExecutionResultFormat; use crate::types::cloudfetch::CloudFetchLink; use crate::types::sea::{ExecuteParams, ResultManifest, StatementStatus}; use async_trait::async_trait; @@ -97,6 +98,8 @@ pub(crate) struct ExecuteResult { pub statement_id: String, pub reader: Box, pub manifest: Option, + pub telemetry_result_format: ExecutionResultFormat, + pub telemetry_is_compressed: bool, /// Terminal status the server reported in its final response. /// /// `status.state == Closed` means the server has already cleaned @@ -122,6 +125,8 @@ impl std::fmt::Debug for ExecuteResult { .field("statement_id", &self.statement_id) .field("reader", &"") .field("manifest", &self.manifest) + .field("telemetry_result_format", &self.telemetry_result_format) + .field("telemetry_is_compressed", &self.telemetry_is_compressed) .field("status", &self.status) .finish() } diff --git a/src/reader/cloudfetch/link_fetcher.rs b/src/reader/cloudfetch/link_fetcher.rs index 68c633f6..53664e01 100644 --- a/src/reader/cloudfetch/link_fetcher.rs +++ b/src/reader/cloudfetch/link_fetcher.rs @@ -1141,6 +1141,8 @@ mod tests { statement_id: "mock-statement".to_string(), reader: Box::new(EmptyReader::new(StdArc::new(Schema::empty()))), manifest: None, + telemetry_result_format: crate::telemetry::ExecutionResultFormat::FormatUnspecified, + telemetry_is_compressed: false, status: StatementStatus { state: StatementState::Succeeded, error: None, diff --git a/src/session.rs b/src/session.rs index bbc58f90..802fdb8e 100644 --- a/src/session.rs +++ b/src/session.rs @@ -166,6 +166,15 @@ impl SessionInner { &self.runtime_handle } + pub(crate) fn statement_telemetry_observer( + &self, + statement_type: crate::telemetry::StatementType, + operation_type: OperationType, + ) -> crate::telemetry::StatementTelemetry { + self.telemetry + .statement_observer(statement_type, operation_type) + } + /// Initiate the fire-and-forget server-side `DeleteSession` now, /// idempotently. Flips `closed` first (via a compare-and-swap) so at /// most one delete is ever spawned — a later `Drop` (or a second @@ -1777,10 +1786,15 @@ mod is_open_tests { use super::*; use crate::telemetry::test_support::CapturingTelemetryExporter; use crate::telemetry::{TelemetryExportResult, TelemetryExporter, TelemetryRequest}; + use arrow_array::{Int64Array, RecordBatch}; + use arrow_ipc::writer::StreamWriter; + use arrow_schema::{DataType, Field, Schema}; + use base64::{engine::general_purpose::STANDARD, Engine}; + use serde_json::json; use serde_json::Value; use std::future::Future; use std::pin::Pin; - use wiremock::matchers::{method, path}; + use wiremock::matchers::{method, path, path_regex}; use wiremock::{Mock, MockServer, ResponseTemplate}; /// `Session::is_open` reports true for a freshly-opened session and @@ -2015,6 +2029,160 @@ mod is_open_tests { .expect("telemetry export failure must be fail-open"); } + #[tokio::test] + async fn statement_execute_success_exports_terminal_statement_event() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-stmt-success").await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + succeeded_inline_body("stmt-telemetry-success", &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-stmt-success", telemetry).await; + + let mut stmt = session.statement(); + stmt.spec().sql("SELECT 1 AS n"); + let _exec = stmt.execute().await.expect("execute succeeds"); + 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_log = &statement_log["entry"]["sql_driver_log"]; + assert_eq!(sql_log["session_id"], "sess-telemetry-stmt-success"); + assert_eq!(sql_log["sql_statement_id"], "stmt-telemetry-success"); + assert_eq!( + sql_log["sql_operation"]["statement_type"], "SQL", + "statement telemetry should classify user SQL" + ); + assert_eq!(sql_log["sql_operation"]["execution_result"], "INLINE_ARROW"); + assert_eq!(sql_log["sql_operation"]["is_compressed"], false); + assert_eq!( + sql_log["sql_operation"]["operation_detail"]["is_internal_call"], + false + ); + assert!( + sql_log["operation_latency_ms"].as_i64().unwrap_or_default() >= 0, + "statement event should include operation latency" + ); + } + + #[tokio::test] + async fn statement_execute_failure_exports_sanitized_error_without_sql_text() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-stmt-failure").await; + mount_close_any_statement(&server).await; + mount_execute( + &server, + failed_body( + "stmt-telemetry-failure", + "syntax failure near secret_token", + "42000", + ), + ) + .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-stmt-failure", telemetry).await; + + let mut stmt = session.statement(); + stmt.spec().sql("SELECT secret_token FROM sensitive_table"); + let err = match stmt.execute().await { + Ok(_) => panic!("execute should fail"), + Err(err) => err, + }; + assert_eq!(err.sql_state.as_deref(), Some("42000")); + 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 encoded = serde_json::to_string(&statement_log).expect("json stringify"); + assert!( + !encoded.contains("SELECT secret_token FROM sensitive_table"), + "statement telemetry must not include SQL text" + ); + let error_info = &statement_log["entry"]["sql_driver_log"]["error_info"]; + assert_eq!(error_info["stack_trace"], "42000"); + assert!( + error_info["error_name"].is_string(), + "sanitized error category should be present" + ); + } + + #[tokio::test] + async fn async_statement_status_and_await_records_poll_count() { + let server = MockServer::start().await; + mount_session_create_delete(&server, "sess-telemetry-async").await; + mount_close_any_statement(&server).await; + mount_execute(&server, running_body("stmt-telemetry-async")).await; + mount_status( + &server, + "stmt-telemetry-async", + succeeded_inline_body("stmt-telemetry-async", &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-async", telemetry).await; + + let mut stmt = session.statement(); + 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 _again = async_exec.fetch_result().await.expect("fetch succeeds"); + session.close().await.expect("close succeeds"); + + let async_statement_logs = exported_logs(&exporter) + .into_iter() + .filter(|log| operation_type(log) == Some("EXECUTE_STATEMENT_ASYNC")) + .collect::>(); + assert_eq!( + async_statement_logs.len(), + 1, + "repeated terminal async calls should finalize telemetry once" + ); + let statement_log = &async_statement_logs[0]; + let detail = &statement_log["entry"]["sql_driver_log"]["sql_operation"]["operation_detail"]; + assert_eq!( + statement_log["entry"]["sql_driver_log"]["sql_statement_id"], + "stmt-telemetry-async" + ); + assert!( + detail["n_operation_status_calls"] + .as_i64() + .unwrap_or_default() + >= 2, + "status() plus await_result() should record status polls" + ); + assert!( + detail["operation_status_latency_millis"] + .as_i64() + .unwrap_or_default() + >= 0 + ); + } + async fn telemetry_test_session( server: &MockServer, expected_session_id: &str, @@ -2053,6 +2221,127 @@ mod is_open_tests { .await; } + async fn mount_close_any_statement(server: &MockServer) { + Mock::given(method("DELETE")) + .and(path_regex(r"^/api/2\.0/sql/statements/.+")) + .respond_with(ResponseTemplate::new(200).set_body_string("{}")) + .mount(server) + .await; + } + + async fn mount_execute(server: &MockServer, body: String) { + Mock::given(method("POST")) + .and(path("/api/2.0/sql/statements")) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; + } + + async fn mount_status(server: &MockServer, statement_id: &str, body: String) { + Mock::given(method("GET")) + .and(path(format!("/api/2.0/sql/statements/{statement_id}"))) + .respond_with(ResponseTemplate::new(200).set_body_string(body)) + .mount(server) + .await; + } + + fn exported_logs(exporter: &CapturingTelemetryExporter) -> Vec { + exporter + .requests() + .into_iter() + .flat_map(|request| request.proto_logs) + .map(|log| serde_json::from_str(&log).expect("valid frontend log json")) + .collect() + } + + fn operation_type(log: &Value) -> Option<&str> { + log["entry"]["sql_driver_log"]["sql_operation"]["operation_detail"]["operation_type"] + .as_str() + } + + fn int64_batch(name: &str, values: Vec) -> RecordBatch { + let schema = + std::sync::Arc::new(Schema::new(vec![Field::new(name, DataType::Int64, false)])); + RecordBatch::try_new(schema, vec![std::sync::Arc::new(Int64Array::from(values))]) + .expect("valid batch") + } + + fn arrow_ipc_bytes(batch: &RecordBatch) -> Vec { + let mut buf = Vec::new(); + { + let mut writer = StreamWriter::try_new(&mut buf, &batch.schema()).unwrap(); + writer.write(batch).unwrap(); + writer.finish().unwrap(); + } + buf + } + + fn succeeded_inline_body(statement_id: &str, batch: &RecordBatch) -> String { + let ipc = arrow_ipc_bytes(batch); + let attachment = STANDARD.encode(&ipc); + 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(); + + 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": ipc.len() as i64, + "truncated": false, + }, + "result": { + "chunk_index": 0, + "row_offset": 0, + "row_count": batch.num_rows() as i64, + "byte_count": ipc.len() as i64, + "attachment": attachment, + }, + }) + .to_string() + } + + fn running_body(statement_id: &str) -> String { + json!({ + "statement_id": statement_id, + "status": { "state": "RUNNING" }, + }) + .to_string() + } + + fn failed_body(statement_id: &str, message: &str, sql_state: &str) -> String { + json!({ + "statement_id": statement_id, + "status": { + "state": "FAILED", + "sql_state": sql_state, + "error": { + "error_code": "INVALID_PARAMETER_VALUE", + "message": format!("{message}. SQLSTATE: {sql_state}"), + } + }, + }) + .to_string() + } + #[derive(Debug)] struct FailingTelemetryExporter; diff --git a/src/statement/executed_async.rs b/src/statement/executed_async.rs index c8a01309..40d1c747 100644 --- a/src/statement/executed_async.rs +++ b/src/statement/executed_async.rs @@ -52,6 +52,7 @@ use crate::result_stream::ResultStream; use crate::session::SessionInner; use crate::statement::handle::ExecutedStatementHandle; use crate::statement::validity::ValidityFlag; +use crate::telemetry::StatementTelemetry; use crate::types::sea::StatementState; use async_trait::async_trait; use std::sync::atomic::{AtomicBool, Ordering}; @@ -218,6 +219,7 @@ pub struct ExecutedAsyncStatement { /// don't `.await` and the poll loop releases the lock before /// every network round-trip. latest_status: Arc>, + statement_telemetry: StatementTelemetry, } impl ExecutedAsyncStatement { @@ -242,6 +244,7 @@ impl ExecutedAsyncStatement { valid: ValidityFlag, closed: Arc, initial_status: crate::types::sea::StatementStatus, + statement_telemetry: StatementTelemetry, ) -> Self { Self { session, @@ -251,6 +254,7 @@ impl ExecutedAsyncStatement { // The submitting handle owns the statement lifecycle. owning: true, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + statement_telemetry, } } @@ -283,6 +287,7 @@ impl ExecutedAsyncStatement { closed: Arc::new(AtomicBool::new(true)), owning: false, latest_status: Arc::new(std::sync::Mutex::new(initial_status)), + statement_telemetry: StatementTelemetry::noop(), } } @@ -375,11 +380,14 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); async { self.valid.check()?; + let status_started = std::time::Instant::now(); let response = self .session .transport() .statement_status(&self.statement_id) .await?; + self.statement_telemetry + .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field accessors // reflect what THIS handle has observed (instead of the // stale initial-submit snapshot). @@ -443,11 +451,14 @@ impl ExecutedAsyncStatement { loop { self.valid.check()?; + let status_started = std::time::Instant::now(); let response = self .session .transport() .statement_status(&self.statement_id) .await?; + self.statement_telemetry + .record_poll(status_started.elapsed()); // Cache the wire status so the extended-field // accessors reflect THIS poll's observation — not the // initial-submit snapshot that's now stale by minutes. @@ -457,7 +468,13 @@ impl ExecutedAsyncStatement { if let Some(g) = cancel_guard.take() { g.defuse(); } - return self.materialise_result().await; + 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; } StatementStatus::Failed(e) => { // Server already decided this is terminal — no @@ -465,6 +482,7 @@ impl ExecutedAsyncStatement { if let Some(g) = cancel_guard.take() { g.defuse(); } + self.statement_telemetry.finalize(Some(&e)); return Err(e); } StatementStatus::Cancelled => { @@ -482,10 +500,10 @@ impl ExecutedAsyncStatement { let error = Error::cancelled() .message(format!("Statement {} was cancelled", self.statement_id)) .with_query_id(&self.statement_id); - return Err(crate::kernel_error::carry_extended_status( - error, - &response.status, - )); + let error = + crate::kernel_error::carry_extended_status(error, &response.status); + self.statement_telemetry.finalize(Some(&error)); + return Err(error); } StatementStatus::Pending | StatementStatus::Running => { if start.elapsed() > cfg.poll_timeout { @@ -494,10 +512,12 @@ impl ExecutedAsyncStatement { // so the server stops charging DBUs on the // now-orphaned query when we return — same // policy as a caller-initiated future drop. - return Err(Error::timeout().message(format!( + let error = Error::timeout().message(format!( "Statement {} did not reach a terminal state within {:?}", self.statement_id, cfg.poll_timeout - ))); + )); + self.statement_telemetry.finalize(Some(&error)); + return Err(error); } tokio::time::sleep(cfg.poll_interval).await; } @@ -518,7 +538,13 @@ impl ExecutedAsyncStatement { let span = self.session.log_span().clone(); async { self.valid.check()?; - self.materialise_result().await + let result = self.materialise_result().await; + if let Err(error) = &result { + self.statement_telemetry.finalize(Some(error)); + } else { + self.statement_telemetry.finalize(None); + } + result } .instrument(span) .await @@ -537,6 +563,10 @@ impl ExecutedAsyncStatement { .await? { Some(result) => { + self.statement_telemetry.on_result_metadata( + result.telemetry_result_format, + result.telemetry_is_compressed, + ); // If the server already auto-closed the statement // (`state == Closed`), pre-set the shared `closed` flag so // this handle's `close()` / `Drop` — and `invalidate_prior` diff --git a/src/statement/mutable.rs b/src/statement/mutable.rs index 0102aa74..95bc29bb 100644 --- a/src/statement/mutable.rs +++ b/src/statement/mutable.rs @@ -64,6 +64,7 @@ use crate::statement::executed_async::ExecutedAsyncStatement; use crate::statement::params::{named_typed_value_to_sea_parameter, typed_value_to_sea_parameter}; use crate::statement::spec::{deserialize_query_tags, ResultFormat, StatementSpec}; use crate::statement::validity::ValidityFlag; +use crate::telemetry::{OperationType, StatementTelemetry, StatementType}; use crate::types::sea::{ExecuteParams, QueryTag, StatementState}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; @@ -325,7 +326,9 @@ impl Statement { // canceller retained across a re-execute can't target the prior // query during the handoff (see `reset_inflight_slot`). self.reset_inflight_slot(); - async { + let telemetry = self.statement_telemetry(OperationType::ExecuteStatement); + let telemetry_for_body = telemetry.clone(); + let result = async { self.invalidate_prior().await; let (sql, mut exec_params) = self.prepare_for_dispatch(None)?; @@ -351,6 +354,11 @@ impl Statement { .transport() .execute_statement(self.session.session_id(), &sql, &exec_params) .await?; + telemetry_for_body.on_statement_submitted(&result.statement_id); + telemetry_for_body.on_result_metadata( + result.telemetry_result_format, + result.telemetry_is_compressed, + ); cancel_state.observe(&result.statement_id); guard.defuse(); @@ -380,17 +388,23 @@ impl Statement { status.num_modified_rows = crate::statement::dml_count::read_dml_affected_rows(&mut result_stream).await?; } - Ok(ExecutedStatement::new( + let executed = ExecutedStatement::new( Arc::clone(&self.session), result.statement_id, valid, result_stream, closed, status, - )) + ); + telemetry_for_body.finalize(None); + Ok(executed) } .instrument(span) - .await + .await; + if let Err(error) = &result { + telemetry.finalize(Some(error)); + } + result } /// Submit-and-return. `wait_timeout=0s`; no direct results. Same @@ -406,7 +420,9 @@ impl Statement { // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). self.reset_inflight_slot(); - async { + let telemetry = self.statement_telemetry(OperationType::ExecuteStatementAsync); + let telemetry_for_body = telemetry.clone(); + let result = async { self.invalidate_prior().await; let (sql, exec_params) = self.prepare_for_dispatch(Some("0s"))?; @@ -421,6 +437,7 @@ impl Statement { .transport() .submit_statement(self.session.session_id(), &sql, &exec_params) .await?; + telemetry_for_body.on_statement_submitted(&response.statement_id); cancel_state.observe(&response.statement_id); guard.defuse(); @@ -446,10 +463,15 @@ impl Statement { // values immediately even before the caller drives // the first poll. response.status, + telemetry_for_body, )) } .instrument(span) - .await + .await; + if let Err(error) = &result { + telemetry.finalize(Some(error)); + } + result } /// directResults execute — the Thrift/JDBC model. @@ -484,7 +506,9 @@ impl Statement { // Clear the shared in-flight-id slot before the first `.await` // (see `reset_inflight_slot`). self.reset_inflight_slot(); - async { + let telemetry = self.statement_telemetry(OperationType::ExecuteStatement); + let telemetry_for_body = telemetry.clone(); + let result = async { self.invalidate_prior().await; // `prepare_for_dispatch(None)` leaves `wait_timeout` / `on_wait_timeout` // UNSET, so `execute_statement_direct` sends ExecuteStatement with no @@ -523,6 +547,11 @@ impl Statement { let valid = ValidityFlag::new(); match outcome { DirectOutcome::Completed(result) => { + telemetry_for_body.on_statement_submitted(&result.statement_id); + telemetry_for_body.on_result_metadata( + result.telemetry_result_format, + result.telemetry_is_compressed, + ); cancel_state.observe(&result.statement_id); guard.defuse(); let already_closed = result.status.state == StatementState::Closed; @@ -531,16 +560,19 @@ impl Statement { self.last_valid = Some(valid.clone()); self.last_closed = Some(Arc::clone(&closed)); let result_stream = ResultStream::from_reader(result.reader).await?; - Ok(DirectStatement::Completed(ExecutedStatement::new( + let executed = ExecutedStatement::new( Arc::clone(&self.session), result.statement_id, valid, result_stream, closed, result.status, - ))) + ); + telemetry_for_body.finalize(None); + Ok(DirectStatement::Completed(executed)) } DirectOutcome::Running(resp) => { + telemetry_for_body.on_statement_submitted(&resp.statement_id); cancel_state.observe(&resp.statement_id); guard.defuse(); // Still running — start the closed flag false (the server @@ -556,12 +588,22 @@ impl Statement { valid, closed, resp.status, + telemetry_for_body, ))) } } } .instrument(span) - .await + .await; + if let Err(error) = &result { + telemetry.finalize(Some(error)); + } + result + } + + fn statement_telemetry(&self, operation_type: OperationType) -> StatementTelemetry { + self.session + .statement_telemetry_observer(StatementType::Sql, operation_type) } /// Explicit close. Cancels and closes any executed handle this diff --git a/src/telemetry/mod.rs b/src/telemetry/mod.rs index 85ff146d..78f920ca 100644 --- a/src/telemetry/mod.rs +++ b/src/telemetry/mod.rs @@ -27,6 +27,7 @@ mod exporter; mod manager; mod models; mod runtime; +mod statement; #[cfg(test)] pub(crate) mod test_support; @@ -34,7 +35,8 @@ pub(crate) mod test_support; #[cfg(test)] pub(crate) use exporter::{TelemetryExportError, TelemetryExportResult, TelemetryExporter}; pub use models::DriverSystemConfiguration; -pub(crate) use models::OperationType; #[cfg(test)] pub(crate) use models::TelemetryRequest; +pub(crate) use models::{ExecutionResultFormat, OperationType, StatementType}; pub(crate) use runtime::TelemetryRuntime; +pub(crate) use statement::StatementTelemetry; diff --git a/src/telemetry/runtime.rs b/src/telemetry/runtime.rs index 4cb038f2..26dda67e 100644 --- a/src/telemetry/runtime.rs +++ b/src/telemetry/runtime.rs @@ -18,9 +18,10 @@ use super::manager::{TelemetryClientLease, TelemetryClientManager}; use super::models::{ unix_time_millis, DriverAuthFlow, DriverAuthMech, DriverConnectionParameters, DriverErrorInfo, DriverMode, DriverSystemConfiguration, FrontendLogContext, FrontendLogEntry, HostDetails, - OperationDetail, OperationType, OssSqlDriverTelemetryLog, SqlExecutionEvent, - TelemetryClientContext, TelemetryFrontendLog, + OperationDetail, OperationType, OssSqlDriverTelemetryLog, ResultLatency, SqlExecutionEvent, + StatementType, TelemetryClientContext, TelemetryFrontendLog, }; +use super::statement::{StatementTelemetry, StatementTelemetryContext}; use crate::client::DatabricksHttpClient; use crate::config::{AuthConfig, ConnectionConfig, TelemetryConfig}; use crate::kernel_error::Error as KernelError; @@ -84,6 +85,18 @@ impl TelemetryRuntime { pub(crate) fn connection(&self) -> Arc { Arc::clone(&self.connection) } + + pub(crate) fn statement_observer( + &self, + statement_type: StatementType, + operation_type: OperationType, + ) -> StatementTelemetry { + if self.connection.session().is_some() { + StatementTelemetry::new(Arc::clone(&self.connection), statement_type, operation_type) + } else { + StatementTelemetry::noop() + } + } } pub(crate) trait ConnectionTelemetry: Send + Sync { @@ -96,6 +109,13 @@ pub(crate) trait ConnectionTelemetry: Send + Sync { error: Option<&KernelError>, ); + fn emit_statement_operation( + &self, + context: StatementTelemetryContext, + elapsed: Duration, + error: Option<&KernelError>, + ); + fn finish<'a>(&'a self) -> Pin + Send + 'a>>; } @@ -124,6 +144,14 @@ impl ConnectionTelemetry for NoOpConnectionTelemetry { ) { } + fn emit_statement_operation( + &self, + _context: StatementTelemetryContext, + _elapsed: Duration, + _error: Option<&KernelError>, + ) { + } + fn finish<'a>(&'a self) -> Pin + Send + 'a>> { Box::pin(async {}) } @@ -177,6 +205,64 @@ impl RealConnectionTelemetry { }), } } + + fn build_statement_log( + &self, + context: StatementTelemetryContext, + elapsed: Duration, + error: Option<&KernelError>, + ) -> TelemetryFrontendLog { + let event_id = self.next_event_id.fetch_add(1, Ordering::Relaxed); + TelemetryFrontendLog { + workspace_id: self.session.workspace_id, + frontend_log_event_id: format!("{}-{event_id}", self.session.session_id), + context: Some(FrontendLogContext { + client_context: Some(TelemetryClientContext { + user_agent: Some(format!( + "{}/{}", + env!("CARGO_PKG_NAME"), + env!("CARGO_PKG_VERSION") + )), + }), + timestamp_millis: unix_time_millis(), + }), + entry: Some(FrontendLogEntry { + sql_driver_log: Some(OssSqlDriverTelemetryLog { + session_id: Some(self.session.session_id.clone()), + sql_statement_id: context.statement_id, + system_configuration: Some(self.session.system_configuration.clone()), + driver_connection_params: Some(self.session.connection_params.clone()), + auth_type: Some(self.session.auth_type.clone()), + sql_operation: Some(SqlExecutionEvent { + statement_type: Some(context.statement_type), + is_compressed: context.is_compressed, + execution_result: context.result_format, + retry_count: context.retry_count, + result_latency: Some(ResultLatency { + result_set_ready_latency_millis: context + .first_batch_latency + .map(duration_millis), + result_set_consumption_latency_millis: context + .consumption_latency + .map(duration_millis), + }), + operation_detail: Some(OperationDetail { + n_operation_status_calls: Some(context.poll_count), + operation_status_latency_millis: Some(duration_millis( + context.poll_latency, + )), + operation_type: Some(context.operation_type), + is_internal_call: Some(context.is_internal_call), + }), + ..Default::default() + }), + error_info: error.map(sanitize_error), + operation_latency_ms: Some(duration_millis(elapsed)), + ..Default::default() + }), + }), + } + } } impl ConnectionTelemetry for RealConnectionTelemetry { @@ -195,6 +281,17 @@ impl ConnectionTelemetry for RealConnectionTelemetry { .enqueue(self.build_operation_log(operation_type, elapsed, error)); } + fn emit_statement_operation( + &self, + context: StatementTelemetryContext, + elapsed: Duration, + error: Option<&KernelError>, + ) { + self.lease + .client() + .enqueue(self.build_statement_log(context, elapsed, error)); + } + fn finish<'a>(&'a self) -> Pin + Send + 'a>> { Box::pin(async move { self.lease.release().await; diff --git a/src/telemetry/statement.rs b/src/telemetry/statement.rs new file mode 100644 index 00000000..b47de428 --- /dev/null +++ b/src/telemetry/statement.rs @@ -0,0 +1,183 @@ +// Copyright (c) 2026 Databricks, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::models::{ExecutionResultFormat, OperationType, StatementType}; +use super::runtime::ConnectionTelemetry; +use crate::kernel_error::Error as KernelError; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +#[derive(Clone)] +pub(crate) struct StatementTelemetry { + observer: Arc, +} + +impl StatementTelemetry { + pub(crate) fn noop() -> Self { + Self { + observer: Arc::new(NoOpObserver), + } + } + + pub(super) fn new( + connection: Arc, + statement_type: StatementType, + operation_type: OperationType, + ) -> Self { + Self { + observer: Arc::new(TelemetryObserver::new( + connection, + statement_type, + operation_type, + )), + } + } + + pub(crate) fn on_statement_submitted(&self, statement_id: &str) { + self.observer.on_statement_submitted(statement_id); + } + + pub(crate) fn on_result_metadata( + &self, + result_format: ExecutionResultFormat, + is_compressed: bool, + ) { + self.observer + .on_result_metadata(result_format, is_compressed); + } + + pub(crate) fn record_poll(&self, elapsed: Duration) { + self.observer.record_poll(elapsed); + } + + pub(crate) fn finalize(&self, error: Option<&KernelError>) { + self.observer.finalize(error); + } +} + +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 finalize(&self, error: Option<&KernelError>); +} + +#[derive(Debug, Clone)] +pub(crate) struct StatementTelemetryContext { + pub statement_id: Option, + pub statement_type: StatementType, + pub operation_type: OperationType, + pub result_format: Option, + pub is_compressed: Option, + pub retry_count: Option, + pub is_internal_call: bool, + pub poll_count: i32, + pub poll_latency: Duration, + pub first_batch_latency: Option, + pub consumption_latency: Option, +} + +struct TelemetryObserver { + connection: Arc, + state: Mutex, + finalized: AtomicBool, +} + +struct StatementTelemetryState { + started_at: Instant, + context: StatementTelemetryContext, +} + +impl TelemetryObserver { + fn new( + connection: Arc, + statement_type: StatementType, + operation_type: OperationType, + ) -> Self { + Self { + connection, + state: Mutex::new(StatementTelemetryState { + started_at: Instant::now(), + context: StatementTelemetryContext { + statement_id: None, + statement_type, + operation_type, + result_format: None, + is_compressed: None, + retry_count: Some(0), + is_internal_call: false, + poll_count: 0, + poll_latency: Duration::ZERO, + first_batch_latency: None, + consumption_latency: None, + }, + }), + finalized: AtomicBool::new(false), + } + } +} + +impl StatementOperationObserver for TelemetryObserver { + fn on_statement_submitted(&self, statement_id: &str) { + if let Ok(mut state) = self.state.lock() { + state.context.statement_id = Some(statement_id.to_string()); + } + } + + fn on_result_metadata(&self, result_format: ExecutionResultFormat, is_compressed: bool) { + if let Ok(mut state) = self.state.lock() { + state.context.result_format = Some(result_format); + state.context.is_compressed = Some(is_compressed); + } + } + + fn record_poll(&self, elapsed: Duration) { + if let Ok(mut state) = self.state.lock() { + state.context.poll_count = state.context.poll_count.saturating_add(1); + state.context.poll_latency += elapsed; + } + } + + fn finalize(&self, error: Option<&KernelError>) { + if self.finalized.swap(true, Ordering::AcqRel) { + return; + } + + let Some((context, elapsed)) = self + .state + .lock() + .ok() + .map(|state| (state.context.clone(), state.started_at.elapsed())) + else { + return; + }; + + self.connection + .emit_statement_operation(context, elapsed, error); + } +} + +#[derive(Debug)] +struct NoOpObserver; + +impl StatementOperationObserver for NoOpObserver { + 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 finalize(&self, _error: Option<&KernelError>) {} +}