From 4a13c6d815d4d53fdfe8ea0f4dc5c2eeb176b26c Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Fri, 14 Aug 2026 05:43:19 +0000 Subject: [PATCH 1/4] docs: add kernel telemetry design Signed-off-by: Jay Xiao --- docs/designs/kernel-telemetry-design.md | 242 ++++++++++++------------ 1 file changed, 117 insertions(+), 125 deletions(-) diff --git a/docs/designs/kernel-telemetry-design.md b/docs/designs/kernel-telemetry-design.md index 1d5abb85..64e2a3e5 100644 --- a/docs/designs/kernel-telemetry-design.md +++ b/docs/designs/kernel-telemetry-design.md @@ -48,6 +48,100 @@ shell export path during this pass. The kernel spec is already mirrored in this repo. The local `~/databricks` checkout is the primary implementation/design reference for this plan. +## Open Question Answers + +### Expected Kernel Telemetry CUJ + +The primary customer user journey is: + +1. A wrapper opens a kernel `Session` with telemetry configuration. +2. The kernel creates a session telemetry context and a host-scoped telemetry + client. +3. The user executes statements, polls async statements, fetches result + streams, calls metadata methods, cancels/closes statement handles, and closes + the session. +4. The kernel emits telemetry events for terminal operations without exposing + telemetry mechanics to wrapper users. +5. Telemetry export is batched, non-blocking on hot paths, flushed on close, and + must never change driver correctness. + +The expected v0 event model is "one operation event per terminal kernel +operation", with statement execution as the anchor event: + + +| CUJ step | Kernel surface | Telemetry event | +| ---------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | +| Open connection | `Session::open` | Session create/open latency, config snapshot, auth type, transport mode (`SeaRest` in v0) | +| Execute sync statement | `Statement::execute` -> `ExecutedStatement` -> `ResultStream` | One statement event including execute latency, poll latency, result format, row/batch/chunk stats, final status/error | +| Submit async statement | `Statement::submit` | Submit event, followed by terminal event when `await_result`, `fetch_result`, `cancel`, or `close` reaches a terminal state | +| Poll async statement | `ExecutedAsyncStatement::status` / `await_result` | Poll count and total/slowest poll latency attached to the statement context | +| Fetch result | `ResultStream::next_batch` / row cursor | Result-ready latency, consumption latency, row count, batch count, CloudFetch chunk metrics | +| Metadata calls | `Metadata::{list_catalogs, list_schemas, ...}` | Metadata operation event with method-specific operation type and result stats | +| Cancel/close handle | `ExecutedStatementHandle::{cancel, close}` | Close/cancel operation latency and terminal disposition | +| Close session | `Session::close` / `Drop` | Best-effort close/delete latency plus telemetry flush-before-close | + + +This CUJ is kernel-first: language bindings should only translate user-facing +configuration into `TelemetryConfig` and surface any test hooks needed for +binding-level tests. + +### Do ADBC And JDBC Adhere To The Telemetry Design? + +ADBC is the better implementation/design to follow for kernel telemetry. + +The current ADBC implementation matches the shape the kernel needs: + +- `ConnectionTelemetry` owns connection/session-level telemetry and returns a +no-op implementation when telemetry is disabled or initialization fails. +- `TelemetrySessionContext` is created once per connection/session and shared +with statement contexts. +- `StatementTelemetryContext` is populated directly by lifecycle code and builds +the `OssSqlDriverTelemetryLog` proto. It captures statement id, statement +type, operation type, result format, compression, retry count, internal-call +flag, poll stats, first-batch/result-consumption latency, CloudFetch chunk +metrics, and sanitized error info. +- `IConnectionTelemetry.ExecuteWithMetadataTelemetry` wraps metadata calls with +the same statement context shape instead of treating metadata as a wrapper +concern. +- `EmitOperationTelemetry` records discrete operations such as create session, +delete session, close statement, and cancel statement. +- `TelemetryClientManager` shares one telemetry client per host with reference +counting. +- `TelemetryClient` queues events, flushes on batch size or timer, flushes on +close, coordinates concurrent flushes, and swallows telemetry failures. +- `DatabricksTelemetryExporter` serializes `TelemetryRequest { upload_time, proto_logs }` and posts to `/telemetry-ext` or `/telemetry-unauth` with retry. +- `CircuitBreakerTelemetryExporter` protects the telemetry endpoint. +- `FeatureFlagCache` and `FeatureFlagContext` cache all feature flags per host, +use server TTL, support negative caching on fetch failure, and merge remote +flags below local user properties. +- The SEA telemetry design introduces a small observer boundary so statement +classes call lifecycle methods such as `OnExecuteStarted`, +`OnStatementSubmitted`, `OnPollCompleted`, `OnFirstBatchReady`, +`OnConsumed`, `OnChunksDownloaded`, `OnError`, and `OnFinalized` without +depending directly on telemetry proto types. + +JDBC broadly adheres to the same backend contract, but should be a secondary +reference. It is useful for validating production semantics, but less suitable +as the kernel model because it relies on a per-connection collector plus some +thread-local attribution paths. The Rust kernel already has explicit +`SessionInner` and handle ownership, so it should follow ADBC's direct +session/context/observer shape and avoid thread-local telemetry state. + +Scoping notes for kernel telemetry: + + +| Area | ADBC reference | Kernel implication | +| ------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| Connection abstraction | `IConnectionTelemetry` with real/no-op implementations | Add a `TelemetryRuntime` / no-op runtime on `SessionInner` | +| Statement instrumentation | Observer lifecycle interface over direct `StatementTelemetryContext` | Add a Rust `StatementOperationObserver` trait so statement code is not coupled to export/proto code | +| Metadata operations | `ExecuteWithMetadataTelemetry` wraps metadata operations | Metadata should create operation contexts in the kernel, not in bindings | +| Discrete operations | `EmitOperationTelemetry` for create/delete/close/cancel | Session and handle lifecycle events should use the same event builder | +| Result consumption | Observer/decorator records first batch, consumed, chunk metrics | `ResultStream` should hold or call an observer context | +| Feature flags | Per-host cache, local properties win, negative TTL on failure | Implement host-scoped async cache; never block hot paths once cold-start policy is decided | +| Export | `TelemetryClientManager` + `TelemetryClient` + exporter + circuit breaker | Recreate this pipeline in Rust; do not invent wrapper-specific exporters | +| Proto alignment | Tests assert proto fields and JSON naming | Add Rust serialization/proto alignment tests before enabling export | + + ## Goals 1. Centralize telemetry in `src/telemetry` so it is a foundational kernel @@ -455,14 +549,7 @@ failures, and circuit-breaker-open states as non-fatal. ## Rollout Plan -Each phase should be independently deliverable and testable. Avoid landing a -large telemetry framework that cannot be exercised until later phases. The early -phases should produce real events through the same queue/exporter path that -later statement and metadata telemetry use. - -### Phase 1: Model And Serialization Contract - -Deliverable: +### Phase 1: Proto And Model Alignment - Add Rust models for the ADBC-compatible telemetry envelope: `TelemetryFrontendLog`, `FrontendLogContext`, `FrontendLogEntry`, @@ -470,74 +557,40 @@ Deliverable: - Decide whether to generate Rust from `~/databricks/csharp/src/Telemetry/Proto/sql_driver_telemetry.proto` or keep serde models aligned to the same field names. -- Add a test-only `TelemetryExporter` trait and in-memory capturing exporter so -later phases can be tested without live telemetry service access. - -Acceptance tests: - -- Proto/JSON alignment tests equivalent to ADBC's +- Add proto/JSON alignment tests equivalent to ADBC's `TelemetryProtoAlignmentTests`. -- Serialization preserves expected snake_case field names. -- `TelemetryRequest { upload_time, proto_logs }` matches the backend request -shape. - -### Phase 2: Connection Telemetry End-To-End +- Verify snake_case backend field names and endpoint request shape: +`TelemetryRequest { upload_time, proto_logs }`. -Deliverable: +### Phase 2: Core Connection Telemetry - Replace `src/telemetry/mod.rs` with `ConnectionTelemetry`, `NoOpConnectionTelemetry`, `TelemetrySessionContext`, config parsing, -event-building helpers, `TelemetryClient`, and test exporter injection. +event-building helpers, and test exporter injection. - Expand `TelemetryConfig` in `src/config.rs` with ADBC-compatible defaults. - Add `TelemetryRuntime` to `SessionInner`. - Wire `Session::open` to create connection telemetry after `create_session` returns, using no-op fallback on disabled telemetry, invalid config, or initialization failure. -- Emit create-session and delete-session operation events. -- Wire `Session::close` to enqueue delete-session telemetry and perform a -bounded flush through the same exporter path that production will use. -- Implement the minimal export pipeline required for this slice: in-memory -queue, batch-size flush, close-time flush, single-flush coordination, and -fail-open error swallowing. Defer timer flush, host-scoped sharing, feature -flags, and circuit breaker. - -Acceptance tests: - -- With telemetry disabled, `Session::open` and `Session::close` use no-op -telemetry and emit nothing. -- With telemetry enabled and a capturing exporter, opening and closing a mocked -session emits create-session and delete-session events. -- Close flushes pending connection events. -- Exporter failure does not change the result of `Session::open` or -`Session::close`. - -### Phase 3: Statement Execution Telemetry End-To-End +- Wire `Session::close` to emit delete-session telemetry and then perform a +bounded flush. -Deliverable: +### Phase 3: Observer Boundary And Statement Context - Add `StatementOperationObserver`, `TelemetryObserver`, `NoOpObserver`, and -`StatementTelemetryContext`. -- Add the ADBC field set needed for a statement terminal event: statement id, +optionally `SafeObserver`. +- Add `StatementTelemetryContext` with the ADBC field set: statement id, statement type, operation type, result format, compression, retry count, internal-call flag, poll count/latency, first-batch latency, consumption latency, chunk metrics, and sanitized error info. - Instrument `Statement::execute`, `submit`, and `execute_direct` using observer lifecycle calls. -- Instrument statement operation failures before a result stream is returned. +- Instrument `ExecutedStatementHandle::cancel` and `close` using discrete +operation telemetry. - Ensure observer finalization is idempotent. -Acceptance tests: - -- `SELECT 1` through a mocked transport emits one statement event. -- A failing SQL statement emits one error event with error category and no SQL -text or parameter values. -- Async submit/poll/await records poll count and latency in the terminal event. -- Repeated close/drop/finalize paths enqueue at most one terminal event. - ### Phase 4: ResultStream And CloudFetch Metrics -Deliverable: - - Add optional observer ownership to `ResultStream`. - Record first-batch-ready and consumed latencies from `ResultStream::next_batch` and stream exhaustion/drop. @@ -546,86 +599,27 @@ observer, matching ADBC's `OnChunksDownloaded` path. - Decide how `OwnedBatchIter` preserves observer finalization; it should not bypass result consumption telemetry. -Acceptance tests: - -- Multi-batch result consumption records row count, batch count, first-batch -latency, and consumption latency. -- CloudFetch chunk metrics merge into the statement terminal event. -- Dropping an unexhausted result stream finalizes best-effort without blocking. -- `OwnedBatchIter` preserves exactly-once finalization. - ### Phase 5: Metadata Lifecycle -Deliverable: - - Mirror ADBC's `ExecuteWithMetadataTelemetry` pattern in Rust. - Instrument every `Metadata::*` method with `statement_type = Metadata` and the corresponding operation type. - Attach the observer to metadata-owned bare `ResultStream`s so finalization happens on exhaustion/drop/error. -Acceptance tests: - -- Each metadata method maps to the expected operation type. -- A successful metadata call emits one terminal metadata event. -- A failed metadata call emits sanitized error telemetry. -- Metadata result streams finalize exactly once on exhaustion or drop. - -### Phase 6: Production Export Pipeline - -Deliverable: +### Phase 6: Export Pipeline - Implement host-scoped `TelemetryClientManager` with reference counting. -- Complete `TelemetryClient` with timer flush in addition to batch-size and -close-time flush. +- Implement `TelemetryClient` with a concurrent queue, approximate queue count, +batch-size flush, timer flush, close-time flush, single-flush coordination, +and fail-open behavior, matching ADBC. - Implement `DatabricksTelemetryExporter` for `/telemetry-ext` and `/telemetry-unauth`. - Implement retry with `max_retries` / `retry_delay`. -- Keep circuit breaker out of this phase; basic retry plus fail-open behavior is -enough to make the exporter independently shippable. - -Acceptance tests: - -- `TelemetryClientManager` shares clients per host and releases on last close. -- Export client batches on size, interval, and close. -- Export retries follow `max_retries` / `retry_delay`. -- Telemetry service failures are swallowed and do not affect kernel operations. - -### Phase 7: Binding Wiring - -Deliverable: - -- C ABI: expose telemetry config fields in the session-open config. -- PyO3/napi: map user-facing options to `TelemetryConfig`. -- Keep binding-specific telemetry collection out of scope unless a binding has -operations that never enter the kernel. - -Acceptance tests: - -- C ABI can enable/disable telemetry and configure batching/export knobs. -- PyO3/napi can enable/disable telemetry without changing existing session -behavior. -- Binding tests can inject or observe captured telemetry without calling the -live telemetry service. - -### Phase 8: Circuit Breaker Hardening - -Deliverable: - - Implement per-host circuit breaker with ADBC-compatible threshold/timeout semantics. -- Wrap the production exporter in `CircuitBreakerTelemetryExporter`. -- Expose circuit-breaker config through `TelemetryConfig`. - -Acceptance tests: - -- Circuit breaker opens after repeated export failures. -- While open, telemetry is dropped/fails open without attempting export. -- After timeout, the breaker allows a probe and closes on success. -### Phase 9: Feature Flags - -Deliverable: +### Phase 7: Feature Flags - Add `FeatureFlagCache` / `FeatureFlagContext` equivalents. - Cache all feature flags per host. @@ -635,14 +629,12 @@ Deliverable: is cold, warm it in the background unless product requirements demand a blocking first fetch. -Acceptance tests: +### Phase 8: Binding Wiring -- Local configuration wins over remote flags. -- Cache uses server TTL and negative TTL on failure. -- Feature flag fetch failure falls back to local config/defaults and does not -fail session open. -- New sessions observe refreshed cached values without mutating existing -session telemetry config. +- C ABI: expose telemetry config fields in the session-open config. +- PyO3/napi: map user-facing options to `TelemetryConfig`. +- Keep binding-specific telemetry collection out of scope unless a binding has +operations that never enter the kernel. ## Testing Strategy From 2078709181b5a3ca3528429347e4b7433d4753cc Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Fri, 14 Aug 2026 05:55:57 +0000 Subject: [PATCH 2/4] docs: refine telemetry rollout plan Signed-off-by: Jay Xiao --- docs/designs/kernel-telemetry-design.md | 148 ++++++++++++++++++++---- 1 file changed, 125 insertions(+), 23 deletions(-) diff --git a/docs/designs/kernel-telemetry-design.md b/docs/designs/kernel-telemetry-design.md index 64e2a3e5..2a0254b5 100644 --- a/docs/designs/kernel-telemetry-design.md +++ b/docs/designs/kernel-telemetry-design.md @@ -549,7 +549,14 @@ failures, and circuit-breaker-open states as non-fatal. ## Rollout Plan -### Phase 1: Proto And Model Alignment +Each phase should be independently deliverable and testable. Avoid landing a +large telemetry framework that cannot be exercised until later phases. The early +phases should produce real events through the same queue/exporter path that +later statement and metadata telemetry use. + +### Phase 1: Model And Serialization Contract + +Deliverable: - Add Rust models for the ADBC-compatible telemetry envelope: `TelemetryFrontendLog`, `FrontendLogContext`, `FrontendLogEntry`, @@ -557,40 +564,74 @@ failures, and circuit-breaker-open states as non-fatal. - Decide whether to generate Rust from `~/databricks/csharp/src/Telemetry/Proto/sql_driver_telemetry.proto` or keep serde models aligned to the same field names. -- Add proto/JSON alignment tests equivalent to ADBC's +- Add a test-only `TelemetryExporter` trait and in-memory capturing exporter so +later phases can be tested without live telemetry service access. + +Acceptance tests: + +- Proto/JSON alignment tests equivalent to ADBC's `TelemetryProtoAlignmentTests`. -- Verify snake_case backend field names and endpoint request shape: -`TelemetryRequest { upload_time, proto_logs }`. +- Serialization preserves expected snake_case field names. +- `TelemetryRequest { upload_time, proto_logs }` matches the backend request +shape. -### Phase 2: Core Connection Telemetry +### Phase 2: Connection Telemetry End-To-End + +Deliverable: - Replace `src/telemetry/mod.rs` with `ConnectionTelemetry`, `NoOpConnectionTelemetry`, `TelemetrySessionContext`, config parsing, -event-building helpers, and test exporter injection. +event-building helpers, `TelemetryClient`, and test exporter injection. - Expand `TelemetryConfig` in `src/config.rs` with ADBC-compatible defaults. - Add `TelemetryRuntime` to `SessionInner`. - Wire `Session::open` to create connection telemetry after `create_session` returns, using no-op fallback on disabled telemetry, invalid config, or initialization failure. -- Wire `Session::close` to emit delete-session telemetry and then perform a -bounded flush. +- Emit create-session and delete-session operation events. +- Wire `Session::close` to enqueue delete-session telemetry and perform a +bounded flush through the same exporter path that production will use. +- Implement the minimal export pipeline required for this slice: in-memory +queue, batch-size flush, close-time flush, single-flush coordination, and +fail-open error swallowing. Defer timer flush, host-scoped sharing, feature +flags, and circuit breaker. + +Acceptance tests: + +- With telemetry disabled, `Session::open` and `Session::close` use no-op +telemetry and emit nothing. +- With telemetry enabled and a capturing exporter, opening and closing a mocked +session emits create-session and delete-session events. +- Close flushes pending connection events. +- Exporter failure does not change the result of `Session::open` or +`Session::close`. -### Phase 3: Observer Boundary And Statement Context +### Phase 3: Statement Execution Telemetry End-To-End + +Deliverable: - Add `StatementOperationObserver`, `TelemetryObserver`, `NoOpObserver`, and -optionally `SafeObserver`. -- Add `StatementTelemetryContext` with the ADBC field set: statement id, +`StatementTelemetryContext`. +- Add the ADBC field set needed for a statement terminal event: statement id, statement type, operation type, result format, compression, retry count, internal-call flag, poll count/latency, first-batch latency, consumption latency, chunk metrics, and sanitized error info. - Instrument `Statement::execute`, `submit`, and `execute_direct` using observer lifecycle calls. -- Instrument `ExecutedStatementHandle::cancel` and `close` using discrete -operation telemetry. +- Instrument statement operation failures before a result stream is returned. - Ensure observer finalization is idempotent. +Acceptance tests: + +- `SELECT 1` through a mocked transport emits one statement event. +- A failing SQL statement emits one error event with error category and no SQL +text or parameter values. +- Async submit/poll/await records poll count and latency in the terminal event. +- Repeated close/drop/finalize paths enqueue at most one terminal event. + ### Phase 4: ResultStream And CloudFetch Metrics +Deliverable: + - Add optional observer ownership to `ResultStream`. - Record first-batch-ready and consumed latencies from `ResultStream::next_batch` and stream exhaustion/drop. @@ -599,27 +640,86 @@ observer, matching ADBC's `OnChunksDownloaded` path. - Decide how `OwnedBatchIter` preserves observer finalization; it should not bypass result consumption telemetry. +Acceptance tests: + +- Multi-batch result consumption records row count, batch count, first-batch +latency, and consumption latency. +- CloudFetch chunk metrics merge into the statement terminal event. +- Dropping an unexhausted result stream finalizes best-effort without blocking. +- `OwnedBatchIter` preserves exactly-once finalization. + ### Phase 5: Metadata Lifecycle +Deliverable: + - Mirror ADBC's `ExecuteWithMetadataTelemetry` pattern in Rust. - Instrument every `Metadata::*` method with `statement_type = Metadata` and the corresponding operation type. - Attach the observer to metadata-owned bare `ResultStream`s so finalization happens on exhaustion/drop/error. -### Phase 6: Export Pipeline +Acceptance tests: + +- Each metadata method maps to the expected operation type. +- A successful metadata call emits one terminal metadata event. +- A failed metadata call emits sanitized error telemetry. +- Metadata result streams finalize exactly once on exhaustion or drop. + +### Phase 6: Production Export Pipeline + +Deliverable: - Implement host-scoped `TelemetryClientManager` with reference counting. -- Implement `TelemetryClient` with a concurrent queue, approximate queue count, -batch-size flush, timer flush, close-time flush, single-flush coordination, -and fail-open behavior, matching ADBC. +- Complete `TelemetryClient` with timer flush in addition to batch-size and +close-time flush. - Implement `DatabricksTelemetryExporter` for `/telemetry-ext` and `/telemetry-unauth`. - Implement retry with `max_retries` / `retry_delay`. +- Keep circuit breaker out of this phase; basic retry plus fail-open behavior is +enough to make the exporter independently shippable. + +Acceptance tests: + +- `TelemetryClientManager` shares clients per host and releases on last close. +- Export client batches on size, interval, and close. +- Export retries follow `max_retries` / `retry_delay`. +- Telemetry service failures are swallowed and do not affect kernel operations. + +### Phase 7: Binding Wiring + +Deliverable: + +- C ABI: expose telemetry config fields in the session-open config. +- PyO3/napi: map user-facing options to `TelemetryConfig`. +- Keep binding-specific telemetry collection out of scope unless a binding has +operations that never enter the kernel. + +Acceptance tests: + +- C ABI can enable/disable telemetry and configure batching/export knobs. +- PyO3/napi can enable/disable telemetry without changing existing session +behavior. +- Binding tests can inject or observe captured telemetry without calling the +live telemetry service. + +### Phase 8: Circuit Breaker Hardening + +Deliverable: + - Implement per-host circuit breaker with ADBC-compatible threshold/timeout semantics. +- Wrap the production exporter in `CircuitBreakerTelemetryExporter`. +- Expose circuit-breaker config through `TelemetryConfig`. + +Acceptance tests: + +- Circuit breaker opens after repeated export failures. +- While open, telemetry is dropped/fails open without attempting export. +- After timeout, the breaker allows a probe and closes on success. -### Phase 7: Feature Flags +### Phase 9: Feature Flags + +Deliverable: - Add `FeatureFlagCache` / `FeatureFlagContext` equivalents. - Cache all feature flags per host. @@ -629,12 +729,14 @@ semantics. is cold, warm it in the background unless product requirements demand a blocking first fetch. -### Phase 8: Binding Wiring +Acceptance tests: -- C ABI: expose telemetry config fields in the session-open config. -- PyO3/napi: map user-facing options to `TelemetryConfig`. -- Keep binding-specific telemetry collection out of scope unless a binding has -operations that never enter the kernel. +- Local configuration wins over remote flags. +- Cache uses server TTL and negative TTL on failure. +- Feature flag fetch failure falls back to local config/defaults and does not +fail session open. +- New sessions observe refreshed cached values without mutating existing +session telemetry config. ## Testing Strategy From 6e187379580766dbd0882adcf7d39534c822eac8 Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Fri, 14 Aug 2026 06:00:46 +0000 Subject: [PATCH 3/4] docs: remove telemetry open question answers Signed-off-by: Jay Xiao --- docs/designs/kernel-telemetry-design.md | 94 ------------------------- 1 file changed, 94 deletions(-) diff --git a/docs/designs/kernel-telemetry-design.md b/docs/designs/kernel-telemetry-design.md index 2a0254b5..1d5abb85 100644 --- a/docs/designs/kernel-telemetry-design.md +++ b/docs/designs/kernel-telemetry-design.md @@ -48,100 +48,6 @@ shell export path during this pass. The kernel spec is already mirrored in this repo. The local `~/databricks` checkout is the primary implementation/design reference for this plan. -## Open Question Answers - -### Expected Kernel Telemetry CUJ - -The primary customer user journey is: - -1. A wrapper opens a kernel `Session` with telemetry configuration. -2. The kernel creates a session telemetry context and a host-scoped telemetry - client. -3. The user executes statements, polls async statements, fetches result - streams, calls metadata methods, cancels/closes statement handles, and closes - the session. -4. The kernel emits telemetry events for terminal operations without exposing - telemetry mechanics to wrapper users. -5. Telemetry export is batched, non-blocking on hot paths, flushed on close, and - must never change driver correctness. - -The expected v0 event model is "one operation event per terminal kernel -operation", with statement execution as the anchor event: - - -| CUJ step | Kernel surface | Telemetry event | -| ---------------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -| Open connection | `Session::open` | Session create/open latency, config snapshot, auth type, transport mode (`SeaRest` in v0) | -| Execute sync statement | `Statement::execute` -> `ExecutedStatement` -> `ResultStream` | One statement event including execute latency, poll latency, result format, row/batch/chunk stats, final status/error | -| Submit async statement | `Statement::submit` | Submit event, followed by terminal event when `await_result`, `fetch_result`, `cancel`, or `close` reaches a terminal state | -| Poll async statement | `ExecutedAsyncStatement::status` / `await_result` | Poll count and total/slowest poll latency attached to the statement context | -| Fetch result | `ResultStream::next_batch` / row cursor | Result-ready latency, consumption latency, row count, batch count, CloudFetch chunk metrics | -| Metadata calls | `Metadata::{list_catalogs, list_schemas, ...}` | Metadata operation event with method-specific operation type and result stats | -| Cancel/close handle | `ExecutedStatementHandle::{cancel, close}` | Close/cancel operation latency and terminal disposition | -| Close session | `Session::close` / `Drop` | Best-effort close/delete latency plus telemetry flush-before-close | - - -This CUJ is kernel-first: language bindings should only translate user-facing -configuration into `TelemetryConfig` and surface any test hooks needed for -binding-level tests. - -### Do ADBC And JDBC Adhere To The Telemetry Design? - -ADBC is the better implementation/design to follow for kernel telemetry. - -The current ADBC implementation matches the shape the kernel needs: - -- `ConnectionTelemetry` owns connection/session-level telemetry and returns a -no-op implementation when telemetry is disabled or initialization fails. -- `TelemetrySessionContext` is created once per connection/session and shared -with statement contexts. -- `StatementTelemetryContext` is populated directly by lifecycle code and builds -the `OssSqlDriverTelemetryLog` proto. It captures statement id, statement -type, operation type, result format, compression, retry count, internal-call -flag, poll stats, first-batch/result-consumption latency, CloudFetch chunk -metrics, and sanitized error info. -- `IConnectionTelemetry.ExecuteWithMetadataTelemetry` wraps metadata calls with -the same statement context shape instead of treating metadata as a wrapper -concern. -- `EmitOperationTelemetry` records discrete operations such as create session, -delete session, close statement, and cancel statement. -- `TelemetryClientManager` shares one telemetry client per host with reference -counting. -- `TelemetryClient` queues events, flushes on batch size or timer, flushes on -close, coordinates concurrent flushes, and swallows telemetry failures. -- `DatabricksTelemetryExporter` serializes `TelemetryRequest { upload_time, proto_logs }` and posts to `/telemetry-ext` or `/telemetry-unauth` with retry. -- `CircuitBreakerTelemetryExporter` protects the telemetry endpoint. -- `FeatureFlagCache` and `FeatureFlagContext` cache all feature flags per host, -use server TTL, support negative caching on fetch failure, and merge remote -flags below local user properties. -- The SEA telemetry design introduces a small observer boundary so statement -classes call lifecycle methods such as `OnExecuteStarted`, -`OnStatementSubmitted`, `OnPollCompleted`, `OnFirstBatchReady`, -`OnConsumed`, `OnChunksDownloaded`, `OnError`, and `OnFinalized` without -depending directly on telemetry proto types. - -JDBC broadly adheres to the same backend contract, but should be a secondary -reference. It is useful for validating production semantics, but less suitable -as the kernel model because it relies on a per-connection collector plus some -thread-local attribution paths. The Rust kernel already has explicit -`SessionInner` and handle ownership, so it should follow ADBC's direct -session/context/observer shape and avoid thread-local telemetry state. - -Scoping notes for kernel telemetry: - - -| Area | ADBC reference | Kernel implication | -| ------------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -| Connection abstraction | `IConnectionTelemetry` with real/no-op implementations | Add a `TelemetryRuntime` / no-op runtime on `SessionInner` | -| Statement instrumentation | Observer lifecycle interface over direct `StatementTelemetryContext` | Add a Rust `StatementOperationObserver` trait so statement code is not coupled to export/proto code | -| Metadata operations | `ExecuteWithMetadataTelemetry` wraps metadata operations | Metadata should create operation contexts in the kernel, not in bindings | -| Discrete operations | `EmitOperationTelemetry` for create/delete/close/cancel | Session and handle lifecycle events should use the same event builder | -| Result consumption | Observer/decorator records first batch, consumed, chunk metrics | `ResultStream` should hold or call an observer context | -| Feature flags | Per-host cache, local properties win, negative TTL on failure | Implement host-scoped async cache; never block hot paths once cold-start policy is decided | -| Export | `TelemetryClientManager` + `TelemetryClient` + exporter + circuit breaker | Recreate this pipeline in Rust; do not invent wrapper-specific exporters | -| Proto alignment | Tests assert proto fields and JSON naming | Add Rust serialization/proto alignment tests before enabling export | - - ## Goals 1. Centralize telemetry in `src/telemetry` so it is a foundational kernel From e6e5b285c3203fe7d9e984086c0a7818e03b7e1e Mon Sep 17 00:00:00 2001 From: Jay Xiao Date: Tue, 18 Aug 2026 04:25:43 +0000 Subject: [PATCH 4/4] docs: add telemetry design diagrams Signed-off-by: Jay Xiao --- docs/designs/kernel-telemetry-design.md | 192 +++++++++++++++++------- 1 file changed, 134 insertions(+), 58 deletions(-) diff --git a/docs/designs/kernel-telemetry-design.md b/docs/designs/kernel-telemetry-design.md index 1d5abb85..2c8de0cb 100644 --- a/docs/designs/kernel-telemetry-design.md +++ b/docs/designs/kernel-telemetry-design.md @@ -15,39 +15,6 @@ JDBC and the ADBC implementation. Binding crates and the C ABI configure telemetry through `TelemetryConfig`; they should not duplicate metric collection, batching, circuit breaking, or export logic. -## Inputs Reviewed - -- `docs/spec-v0.md`, the local mirror of the common kernel design. -- `src/telemetry/mod.rs`, currently a minimal reserved collector. -- `src/config.rs`, where public `TelemetryConfig` is currently empty and -exported at the crate root. -- `src/session.rs`, `src/statement/*`, `src/metadata_v0.rs`, and -`src/result_stream.rs`, which define the session-owned handle graph. -- ADBC implementation under `~/databricks`, especially: - - `csharp/doc/telemetry-design.md` - - `docs/designs/PECO-3022-sea-telemetry-integration-design.md` - - `docs/designs/fix-telemetry-gaps-design.md` - - `csharp/src/Telemetry/ConnectionTelemetry.cs` - - `csharp/src/Telemetry/IConnectionTelemetry.cs` - - `csharp/src/Telemetry/StatementTelemetryContext.cs` - - `csharp/src/Telemetry/TelemetrySessionContext.cs` - - `csharp/src/Telemetry/TelemetryClient.cs` - - `csharp/src/Telemetry/TelemetryClientManager.cs` - - `csharp/src/Telemetry/DatabricksTelemetryExporter.cs` - - `csharp/src/Telemetry/CircuitBreakerTelemetryExporter.cs` - - `csharp/src/FeatureFlagCache.cs` - - `csharp/src/FeatureFlagContext.cs` - - `csharp/src/Telemetry/Proto/sql_driver_telemetry.proto` - - telemetry unit/E2E tests under `csharp/test/*/Telemetry`. -- JDBC implementation under `~/databricks-jdbc` as a secondary reference for -production behavior that ADBC intentionally mirrors: endpoint shape, -feature-flag lineage, batching, circuit breaking, and close-time flush. - -The two Google Docs links in the request were not directly accessible from the -shell export path during this pass. The kernel spec is already mirrored in this -repo. The local `~/databricks` checkout is the primary implementation/design -reference for this plan. - ## Goals 1. Centralize telemetry in `src/telemetry` so it is a foundational kernel @@ -78,31 +45,38 @@ paths containing local secrets, or arbitrary connection strings. ## Proposed Architecture -``` -SessionConfig.telemetry - | - v -Session::open - | - +--> TelemetryManager::client_for_host(host) - | | - | +--> TelemetryClient (host-scoped queue, batch flush timer) - | +--> TelemetryExporter (HTTP POST) - | +--> CircuitBreaker - | - +--> TelemetrySessionContext - | - v -SessionInner { telemetry: Arc } - | - +--> Statement / Metadata obtain StatementOperationObserver - | - +--> TelemetryObserver owns StatementTelemetryContext - | - +--> ExecutedStatement / ExecutedAsyncStatement / ResultStream call observer lifecycle hooks - | - v -TelemetryClient.enqueue(TelemetryFrontendLog) +```mermaid +flowchart TD + config["SessionConfig.telemetry"] + open["Session::open"] + session["SessionInner
telemetry: Arc<TelemetryRuntime>"] + runtime["TelemetryRuntime
ConnectionTelemetry"] + context["TelemetrySessionContext"] + manager["TelemetryClientManager
one client per host"] + client["TelemetryClient
queue + batch flush"] + exporter["DatabricksTelemetryExporter
HTTP POST"] + breaker["CircuitBreakerTelemetryExporter"] + statement["Statement / Metadata"] + observer["StatementOperationObserver"] + operation_context["StatementTelemetryContext"] + result["ExecutedStatement / ExecutedAsyncStatement / ResultStream"] + event["TelemetryFrontendLog"] + + config --> open + open --> context + open --> manager + manager --> client + client --> breaker + breaker --> exporter + context --> runtime + client --> runtime + runtime --> session + session --> statement + statement --> observer + observer --> operation_context + operation_context --> result + result --> event + event --> client ``` ### Core Types @@ -251,6 +225,32 @@ attach the observer to the returned bare `ResultStream`. Because metadata returns a bare `ResultStream` with no executed handle, that stream owns finalization on exhaustion/drop/error. +```mermaid +sequenceDiagram + participant Caller + participant Session as Session::open / Session::close + participant SEA as SEA REST API + participant Runtime as TelemetryRuntime + participant Client as TelemetryClient + participant Exporter as TelemetryExporter + + Caller->>Session: open(config) + Session->>SEA: create_session + SEA-->>Session: session_id + Session->>Runtime: build(session_id, telemetry config) + Runtime->>Client: enqueue CREATE_SESSION + Client-->>Exporter: flush when batch policy fires + Session-->>Caller: Session + + Caller->>Session: close() + Session->>Runtime: emit DELETE_SESSION + Runtime->>Client: enqueue DELETE_SESSION + Runtime->>Client: bounded flush + Client-->>Exporter: export pending events + Session->>SEA: delete_session + Session-->>Caller: close result +``` + ### Event Emission Use deterministic, idempotent emission. Every real observer has an emitted flag. @@ -272,6 +272,27 @@ session delete telemetry. Do not emit on every batch. Batch-level and chunk-level metrics should be accumulated on the context and included in the terminal event. +```mermaid +sequenceDiagram + participant Statement + participant Observer as StatementOperationObserver + participant Handle as ExecutedStatement / ExecutedAsyncStatement + participant Stream as ResultStream + participant Client as TelemetryClient + + Statement->>Observer: on_execute_started + Statement->>Observer: on_statement_submitted(statement_id) + Statement-->>Handle: return executed handle + Handle-->>Stream: attach observer + Stream->>Observer: on_first_batch_ready + loop Each result batch + Stream->>Observer: accumulate batch and row counts + end + Stream->>Observer: on_consumed + Stream->>Observer: on_finalized + Observer->>Client: enqueue one terminal event +``` + ### Export Pipeline Match the ADBC production pattern: @@ -460,6 +481,28 @@ large telemetry framework that cannot be exercised until later phases. The early phases should produce real events through the same queue/exporter path that later statement and metadata telemetry use. +```mermaid +flowchart LR + p1["Phase 1
Models + test exporter"] + p2["Phase 2
Connection telemetry E2E"] + p3["Phase 3
Statement telemetry E2E"] + p4["Phase 4
ResultStream + CloudFetch metrics"] + p5["Phase 5
Metadata lifecycle"] + p6["Phase 6
Production export pipeline"] + p7["Phase 7
Binding wiring"] + p8["Phase 8
Circuit breaker hardening"] + p9["Phase 9
Feature flags"] + + p1 --> p2 + p2 --> p3 + p3 --> p4 + p3 --> p5 + p2 --> p6 + p6 --> p7 + p6 --> p8 + p8 --> p9 +``` + ### Phase 1: Model And Serialization Contract Deliverable: @@ -702,6 +745,39 @@ flaky. | Future transport modes need different fields | Non-exhaustive transport/result enums and protocol-neutral contexts; v0 records only `SeaRest` | +## Appendix: Inputs Reviewed + +- `docs/spec-v0.md`, the local mirror of the common kernel design. +- `src/telemetry/mod.rs`, currently a minimal reserved collector. +- `src/config.rs`, where public `TelemetryConfig` is currently empty and +exported at the crate root. +- `src/session.rs`, `src/statement/*`, `src/metadata_v0.rs`, and +`src/result_stream.rs`, which define the session-owned handle graph. +- ADBC implementation under `~/databricks`, especially: + - `csharp/doc/telemetry-design.md` + - `docs/designs/PECO-3022-sea-telemetry-integration-design.md` + - `docs/designs/fix-telemetry-gaps-design.md` + - `csharp/src/Telemetry/ConnectionTelemetry.cs` + - `csharp/src/Telemetry/IConnectionTelemetry.cs` + - `csharp/src/Telemetry/StatementTelemetryContext.cs` + - `csharp/src/Telemetry/TelemetrySessionContext.cs` + - `csharp/src/Telemetry/TelemetryClient.cs` + - `csharp/src/Telemetry/TelemetryClientManager.cs` + - `csharp/src/Telemetry/DatabricksTelemetryExporter.cs` + - `csharp/src/Telemetry/CircuitBreakerTelemetryExporter.cs` + - `csharp/src/FeatureFlagCache.cs` + - `csharp/src/FeatureFlagContext.cs` + - `csharp/src/Telemetry/Proto/sql_driver_telemetry.proto` + - telemetry unit/E2E tests under `csharp/test/*/Telemetry`. +- JDBC implementation under `~/databricks-jdbc` as a secondary reference for +production behavior that ADBC intentionally mirrors: endpoint shape, +feature-flag lineage, batching, circuit breaking, and close-time flush. + +The two Google Docs links in the request were not directly accessible from the +shell export path during this pass. The kernel spec is already mirrored in this +repo. The local `~/databricks` checkout is the primary implementation/design +reference for this plan. + ## Recommendation Follow the ADBC implementation in `~/databricks` as the primary design and