Skip to content

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:

uv add "vertebra-core[opentelemetry]"
pip install "vertebra-core[opentelemetry]"
pdm add "vertebra-core[opentelemetry]"
poetry add "vertebra-core[opentelemetry]"

Tracing & Span Export

TraceContext

Bases: Struct

W3C Trace Context traceparent representation (00---).

Attributes:

Name Type Description
trace_idstr
span_idstr
trace_flagsint
Default: 1
versionint
Default: 0
is_sampledbool

Return whether the sampled bit (0x01) is set.

SpanData

Bases: Struct

Lightweight span record exported through SpanExporter.

Attributes:

Name Type Description
namestr
trace_idstr
span_idstr
parent_span_idstr | None
Default: None
start_nsint
Default: 0
duration_nsint
Default: 0
status_codeint
Default: 200
attributesdict[str, Any]

SpanExporter

Bounded thread-safe ring buffer for completed telemetry spans.

record_span

record_span(span)

Append a completed span to the bounded ring buffer.

get_spans

get_spans()

Return all buffered spans without draining the ring buffer.

drain_spans

drain_spans()

Drain and return all buffered spans for batch OTLP export.

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_tokensint
Default: 0
output_tokensint
Default: 0
thought_tokensint
Default: 0
cached_input_tokensint
Default: 0
total_tokensint

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_usdfloat
output_per_million_usdfloat
cached_input_per_million_usdfloat
Default: 0.0
thinking_per_million_usdfloat
Default: 0.0

GenAiRecorder

Records gen_ai.client.token.usage and gen_ai.client.operation.duration metrics.

Attributes:

Name Type Description
samplestuple[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

duration_histogram(operation)

Calculate statistical duration histogram for a specific operation.

total_cost

total_cost(agent_name=None)

Return the sum of all recorded USD costs, optionally filtered by agent name.

total_tokens

total_tokens(agent_name=None)

Return the sum of all recorded tokens, optionally filtered by agent name.

drain

drain()

Drain and return all recorded GenAI telemetry samples.

DbPoolMetricSample

Bases: Struct

OpenTelemetry db.client.connections.* semantic convention metric sample.

Attributes:

Name Type Description
pool_namestr
active_leasesint
primary_in_useint
overflow_in_useint
max_capacityint
waiting_threadsint
total_timeoutsint
total_reclaimedint
statement_cache_hitsint
statement_cache_missesint
quarantinedint
Default: 0
total_quarantinedint
Default: 0
total_disposedint
Default: 0
wait_duration_msfloat
Default: 0.0
timestampfloat

DbPoolRecorder

Records database connection pool and statement cache telemetry metrics.

Attributes:

Name Type Description
samplestuple[DbPoolMetricSample, ...]

Return recorded database pool telemetry samples.

record_sample

record_sample(sample)

Record a database pool telemetry metric sample.

drain_samples

drain_samples()

Drain and return all buffered database pool metric samples.

EventLoopMetricSample

Bases: Struct

Point-in-time event loop scheduling lag and active task telemetry sample.

Attributes:

Name Type Description
shard_idint

Zero-based event loop shard identifier.

backendstr

Resolved event loop backend name (for example uvloop, zuvloop, or asyncio).

lag_msfloat

Measured event loop scheduling lag in milliseconds.

active_tasksint

Number of currently active asyncio.Task instances on the shard.

pending_callbacksint

Number of queued event loop callbacks awaiting execution.

unhandled_exceptionsint

Count of unhandled event loop exceptions observed on the shard.

recorded_at_nsint

Timestamp in nanoseconds when the metric sample was recorded.

EventLoopRecorder

Thread-safe recorder for event loop scheduling lag, task counts, and optional OpenTelemetry metrics.

__init__

__init__(
    max_samples=1024, *, emit_otel=False, meter_name="vertebra.server.loop"
)

record

record(sample)

Append an event loop sample, update lag histogram buckets, and optionally emit OTel metrics.

configure_zuvloop

configure_zuvloop(loop, *, metrics_interval_ms=1000, slow_callback_ms=100.0)

Attach native zuvloop OpenTelemetry and slow-callback hooks when supported on Python 3.14+.

lag_histogram

lag_histogram()

Return a statistical lag histogram snapshot across recorded loop samples.

latest_by_shard

latest_by_shard()

Return the most recently recorded telemetry sample for each shard.

samples

samples()

Return buffered event loop telemetry samples in chronological order.

SQL Trace Propagation

SqlTracePropagator

Propagates W3C trace context into Oracle Thin connections and SQL queries.

truncate_utf8_bytes

truncate_utf8_bytes(value, max_bytes)

Truncate a string to at most max_bytes of UTF-8 without splitting multi-byte codepoints.

apply_oracle_trace

apply_oracle_trace(
    conn, trace, *, module="Vertebra", action="db.query", client_identifier=None
)

Piggyback OTel trace context onto python-oracledb Thin connection attributes with zero extra RTT.

append_sqlcommenter

append_sqlcommenter(
    sql, trace, *, db_driver="vertebra-pg", route=None, controller=None
)

Append a Google sqlcommenter trace comment for Cloud SQL / AlloyDB Query Insights.

sanitize_sql

sanitize_sql(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
levelstr
Default: 'INFO'
json_formatbool
Default: True
queue_capacityint
Default: 8192
overflow_policyLogOverflowPolicy
Default: 'drop_oldest'
access_log_enabledbool
Default: True
access_log_formatstr
Default: '%h - - "%m %U %H" %s %b "%R" "%A" %D'

LogHandler

Bases: Handler

Non-blocking logging.Handler encoding log records via msgspec.json.

emit

emit(record)

Encode record to UTF-8 JSON bytes and enqueue into self.sink.