OpenTelemetry Spans, Metrics, SQL Propagation & Logging¶
vertebra.telemetry provides distributed tracing, GenAI token and cost metrics, database pool and event loop telemetry, SQL trace comment propagation, and structured JSON logging.
| Subsystem | Purpose |
|---|---|
| Tracing & Span Export | Propagate W3C traceparent contexts across HTTP, shared-memory rings, and worker lanes, and export OTLP spans. |
| GenAI & DB Pool Metrics | Record OpenTelemetry gen_ai.* token and cost metrics and db.client.connections.* pool gauges. |
| Event Loop Telemetry | Track per-shard scheduling lag histograms, active-task counts, zuvloop stats, and optional OpenTelemetry meters. |
| SQL Trace Propagation | Attach W3C traceparent comments or session variables to outbound SQL queries. |
| Structured Logging | Emit JSON or console logs enriched with trace_id and span_id. |
Install the optional opentelemetry extra to emit live opentelemetry.metrics instruments (vertebra.loop.lag_ms and vertebra.loop.active_tasks) from EventLoopRecorder:
Tracing & Span Export¶
TraceContext
¶
Bases: Struct
W3C Trace Context traceparent representation (00-
Attributes:
| Name | Type | Description |
|---|---|---|
trace_id | str | |
span_id | str | |
trace_flags | int | Default: 1 |
version | int | Default: 0 |
is_sampled | bool | Return whether the sampled bit (0x01) is set. |
SpanData
¶
Bases: Struct
Lightweight span record exported through SpanExporter.
Attributes:
| Name | Type | Description |
|---|---|---|
name | str | |
trace_id | str | |
span_id | str | |
parent_span_id | str | None | Default: None |
start_ns | int | Default: 0 |
duration_ns | int | Default: 0 |
status_code | int | Default: 200 |
attributes | dict[str, Any] |
SpanExporter
¶
Bounded thread-safe ring buffer for completed telemetry spans.
GenAI, Database Pool & Event Loop Metrics¶
GenAiUsage
¶
Bases: Struct
Token usage breakdown for a single model generation or aggregated turn.
Attributes:
| Name | Type | Description |
|---|---|---|
input_tokens | int | Default: 0 |
output_tokens | int | Default: 0 |
thought_tokens | int | Default: 0 |
cached_input_tokens | int | Default: 0 |
total_tokens | int | Return the sum of input, output, and reasoning tokens. |
ModelPricing
¶
Bases: Struct
Pricing rates in USD per million tokens.
Attributes:
| Name | Type | Description |
|---|---|---|
input_per_million_usd | float | |
output_per_million_usd | float | |
cached_input_per_million_usd | float | Default: 0.0 |
thinking_per_million_usd | float | Default: 0.0 |
GenAiRecorder
¶
Records gen_ai.client.token.usage and gen_ai.client.operation.duration metrics.
Attributes:
| Name | Type | Description |
|---|---|---|
samples | tuple[GenAiMetricSample, ...] | Return recorded GenAI telemetry samples. |
record_generation
¶
record_generation(
*,
model,
operation="chat",
input_tokens,
output_tokens,
duration_seconds,
thought_tokens=0,
cached_input_tokens=0,
usd_cost=None,
agent_name=None,
status="ok",
)
Record a model generation operation with token counts, latency, and cost.
duration_histogram
¶
Calculate statistical duration histogram for a specific operation.
total_cost
¶
Return the sum of all recorded USD costs, optionally filtered by agent name.
total_tokens
¶
Return the sum of all recorded tokens, optionally filtered by agent name.
DbPoolMetricSample
¶
Bases: Struct
OpenTelemetry db.client.connections.* semantic convention metric sample.
Attributes:
| Name | Type | Description |
|---|---|---|
pool_name | str | |
active_leases | int | |
primary_in_use | int | |
overflow_in_use | int | |
max_capacity | int | |
waiting_threads | int | |
total_timeouts | int | |
total_reclaimed | int | |
statement_cache_hits | int | |
statement_cache_misses | int | |
quarantined | int | Default: 0 |
total_quarantined | int | Default: 0 |
total_disposed | int | Default: 0 |
wait_duration_ms | float | Default: 0.0 |
timestamp | float |
DbPoolRecorder
¶
Records database connection pool and statement cache telemetry metrics.
Attributes:
| Name | Type | Description |
|---|---|---|
samples | tuple[DbPoolMetricSample, ...] | Return recorded database pool telemetry samples. |
EventLoopMetricSample
¶
Bases: Struct
Point-in-time event loop scheduling lag and active task telemetry sample.
Attributes:
| Name | Type | Description |
|---|---|---|
shard_id | int | Zero-based event loop shard identifier. |
backend | str | Resolved event loop backend name (for example |
lag_ms | float | Measured event loop scheduling lag in milliseconds. |
active_tasks | int | Number of currently active |
pending_callbacks | int | Number of queued event loop callbacks awaiting execution. |
unhandled_exceptions | int | Count of unhandled event loop exceptions observed on the shard. |
recorded_at_ns | int | Timestamp in nanoseconds when the metric sample was recorded. |
EventLoopRecorder
¶
Thread-safe recorder for event loop scheduling lag, task counts, and optional OpenTelemetry metrics.
record
¶
Append an event loop sample, update lag histogram buckets, and optionally emit OTel metrics.
configure_zuvloop
¶
Attach native zuvloop OpenTelemetry and slow-callback hooks when supported on Python 3.14+.
lag_histogram
¶
Return a statistical lag histogram snapshot across recorded loop samples.
latest_by_shard
¶
Return the most recently recorded telemetry sample for each shard.
SQL Trace Propagation¶
SqlTracePropagator
¶
Propagates W3C trace context into Oracle Thin connections and SQL queries.
truncate_utf8_bytes
¶
Truncate a string to at most max_bytes of UTF-8 without splitting multi-byte codepoints.
apply_oracle_trace
¶
Piggyback OTel trace context onto python-oracledb Thin connection attributes with zero extra RTT.
append_sqlcommenter
¶
Append a Google sqlcommenter trace comment for Cloud SQL / AlloyDB Query Insights.
sanitize_sql
¶
Collapse high-cardinality IN (...) and multi-row VALUES (...) lists for db.query.text.
Structured Logging¶
LoggingConfig
¶
Bases: Struct
Configuration for Vertebra's non-blocking structured and access logging.
Attributes:
| Name | Type | Description |
|---|---|---|
level | str | Default: 'INFO' |
json_format | bool | Default: True |
queue_capacity | int | Default: 8192 |
overflow_policy | LogOverflowPolicy | Default: 'drop_oldest' |
access_log_enabled | bool | Default: True |
access_log_format | str | Default: '%h - - "%m %U %H" %s %b "%R" "%A" %D' |