Skip to Content
Recodocs

Observability

The layer that records what a run did and what it cost: usage receipts, latency facts, OpenTelemetry spans, Phoenix traces, monitoring windows and spend control.

9 min read

When someone asks why an agent answered incorrectly or cost more than expected, a transcript alone rarely settles it. Tracing shows the events inside a particular run; measurement records comparable timing, cost and outcome facts. Spans can go to a trace backend, while append-only facts and receipts work in the application's own store without a server or vendor library at import, including tests and CI.

Three pieces form the core owner. recohut_kit.usage defines the receipt for one model call. recohut_kit.latency defines an immutable timing fact and stores it. recohut_kit.phoenix sends traces to a Phoenix server, with recohut_kit.telemetry as the shared OpenTelemetry plumbing. Two rules run through all of them: providers are caller-owned and the kit never sets the global tracer provider, and an unknown value stays None, never zero.

The layer records and reports. It does not decide whether a result is good (see Evaluation) and it does not enforce safety rules (see Guardrails).

Owners

PackageImport pathTierWhat it is for
Usage receiptsrecohut_kit.usagecore (module)UsageReceipt and DetailedUsageReceipt; append_receipt writes a locked JSONL row
Latencyrecohut_kit.latencycoreLatencyFact, LatencyRecorder, SQLite and SQLAlchemy stores, ASGI timing middleware, OpenTelemetry and Prometheus readers
Phoenixrecohut_kit.phoenixcoreVersion-aware server handle, project-scoped tracing, PydanticAI and OpenAI instrumentation, span annotations, datasets, UI links
Telemetryrecohut_kit.telemetrycore (module)tracer_provider and OpenTelemetry.record_receipt: model.usage spans and token counters on caller-owned providers
Monitoringrecohut_kit.monitoringcatalogWindowed metric observations, baselines and anomaly rules, a metric catalogue, configuration comparison, prompt-growth guard, RAG triage
Spend guardrecohut_kit.spend_guardcatalogPrices receipts, detects identical-request loops, spikes, drift and projected burn; per-job circuit breaker
Agent operationsrecohut_kit.agents.operationscatalogOperational events, canary and budget decisions, signed provenance, casefiles, privacy classification
Phoenix evaluation bridgerecohut_kit.evals.phoenixevaluation ownerWrites evaluation results to Phoenix; documented in Evaluation

Modules inside recohut_kit.latency:

ModuleMain namesWhat it does
latency.contractsLatencyFact, LatencyKind, LatencyStatus, CacheStateThe validated fact. Kinds are request, answer, model, tool, judge, browser
latency.recordingLatencyRecorder, MeasurementA timing scope on a monotonic clock that records exactly one fact
latency.storageSQLiteLatencyStore, SQLAlchemyLatencyStore, LatencyStoreIdempotent append and filtered listing
latency.asgiLatencyMiddlewareTimes each request on an ASGI app, including failures
latency.otelOTelLatencyMetrics, fact_from_span, latency_span_processorTurn facts into OpenTelemetry metrics, or spans into facts
latency.prometheusPrometheusClient, Cohort, LatencyWindowRead latency windows and trends from a Prometheus server
latency.trace_linkcurrent_trace_ids, with_traceStamp the active span's trace and span ids onto a fact

Modules inside recohut_kit.phoenix:

ModuleMain namesWhat it does
phoenix.serverPhoenixEndpoint, supports_decision_spans, probe_decision_supportConnect to a running server, read its version, check whether DECISION spans are stored
phoenix.tracingPhoenixTracing, instrument_pydantic_ai, instrument_openaiOne tracing object is one Phoenix project, on its own tracer provider
phoenix.annotationsSpanAnnotation, log_annotations, read_annotationsTyped annotations written to spans and read back
phoenix.datasetsDatasetRow, create_or_get_dataset, run_experimentDataset and experiment helpers
phoenix.linkslink buildersDeep links into the Phoenix UI

How the pieces fit

For a single incident, follow the trace. For a repeated problem, compare measured facts across runs. Both are useful: a trace explains one example, while measurement tells whether it is a pattern.

The two halves share ids. A LatencyFact has trace_id and span_id fields, and latency.trace_link.with_trace fills them from the active OpenTelemetry span, so a stored timing can be matched to its trace.

Worked examples

Record a timing fact

LatencyRecorder.measure returns a context manager. On exit it writes one immutable fact. An exception marks the fact failed, a cancelled task marks it cancelled, and a normal exit marks it completed.

record_latency.py
import tempfile
import time
from pathlib import Path

from recohut_kit.latency import LatencyRecorder, SQLiteLatencyStore

store = SQLiteLatencyStore(Path(tempfile.mkdtemp()) / "latency.db")
store.create_schema()                       # schema creation is an explicit host action
recorder = LatencyRecorder(store.append)

with recorder.measure(
    observation_id="o1", run_id="r1", agent_id="helpdesk", kind="request", operation="ticket"
):
    time.sleep(0.01)

with recorder.measure(
    observation_id="o2", run_id="r1", agent_id="helpdesk", kind="model",
    operation="draft", model="model-a",
) as timing:
    timing.first_chunk()                    # mark the first delivered chunk
    time.sleep(0.01)

try:
    with recorder.measure(
        observation_id="o3", run_id="r1", agent_id="helpdesk", kind="tool", operation="lookup"
    ):
        raise RuntimeError("upstream timeout")
except RuntimeError:
    pass

for fact in store.list(run_id="r1"):        # newest first
    print(fact.observation_id, fact.kind, fact.status, round(fact.duration_ms))
# o3 tool failed 0
# o2 model completed 10
# o1 request completed 10

store.append returns True for a new fact and False when the identical fact already exists. Appending a different payload under an existing observation_id raises ValueError, because facts are immutable. store.list filters by run_id, session_id and kind and has a limit of 1000 by default.

Record a usage receipt

A receipt is metadata only. It holds no prompt, response, credential or personal data. None token counts mean the provider did not report them.

usage_receipt.py
import tempfile
from pathlib import Path

from recohut_kit.usage import UsageReceipt, append_receipt

receipt = UsageReceipt(
    request_id="q1",
    model="model-a",
    billing_route="codex",            # codex, api_key, aws, local or databricks
    prompt_version="v1",
    request_sha256="ab",
    status="completed",               # completed, failed or cache_hit
    input_tokens=10,
    output_tokens=None,               # unknown stays None
    elapsed_ms=15,
)
log = Path(tempfile.mkdtemp()) / "usage.jsonl"
append_receipt(log, receipt)          # appended under a local advisory lock, file mode 0600
print(log.read_text())
# {"billing_route":"codex","elapsed_ms":15,"input_tokens":10,... "output_tokens":null,...}

DetailedUsageReceipt adds cache_read_tokens, cache_write_tokens and reasoning_tokens, each None when the provider did not report it. Strict typed records that accept only a plain UsageReceipt need usage.plain_receipt(receipt).

Send receipts and spans to OpenTelemetry

OpenTelemetry.create builds a tracer provider and a meter provider that you own, then record_receipt emits one model.usage span and token counters per receipt. It needs the telemetry extra (opentelemetry-sdk).

otel_receipts.py
from recohut_kit.telemetry import OpenTelemetry

otel = OpenTelemetry.create(
    scope="helpdesk",                                   # an explicit scope is required
    resource_attributes={"service.name": "helpdesk"},   # passed through disclose() first
    span_processors=(my_span_processor,),               # your exporter pipeline
    metric_readers=(my_metric_reader,),
)
otel.record_receipt(receipt)    # span "model.usage" plus recohut.model.* counters
otel.close()                    # shuts down both providers

my_span_processor and my_metric_reader are the OpenTelemetry objects for your own collector. The counters are recohut.model.calls, recohut.model.input_tokens and recohut.model.output_tokens. A token count that is None adds nothing to its counter; it never adds zero.

Trace a PydanticAI agent in Phoenix

PhoenixEndpoint.connect reads health and version from a running server and raises if either is missing. PhoenixTracing is one Phoenix project. This needs the phoenix extra and a reachable server, so it is shown without output.

phoenix_tracing.py
from recohut_kit.phoenix import PhoenixEndpoint, PhoenixTracing, instrument_pydantic_ai

endpoint = PhoenixEndpoint.connect("http://localhost:6006")
tracing = PhoenixTracing(endpoint, "helpdesk")          # one object is one Phoenix project

instrument_pydantic_ai(tracing, agent)                  # native PydanticAI spans to this project
try:
    result = agent.run_sync("How many vacation days do I get?")
finally:
    tracing.shutdown()                                  # uninstrument, flush, shut down

With an agent argument, instrument_pydantic_ai instruments that agent. Without one, it applies to every PydanticAI agent in the process. include_content=False is the default, so message content stays out of spans unless you ask for it. instrument_openai(tracing) binds the OpenInference OpenAI instrumentor to the same provider; it patches the openai module for the whole process, and shutdown removes the patch.

Stop a runaway scheduled job

SpendGuard prices each receipt with a price table you supply, watches for identical requests, and trips a per-job breaker. Only a named human can reset it; the automation names are refused. The clock is an argument, so the rules are deterministic.

spend_guard.py
from datetime import date, datetime, timedelta, timezone
from zoneinfo import ZoneInfo

from recohut_kit.spend_guard import (
    BreakerOpen, BreakerResetRefused, LoopPolicy, ModelPrice, PriceTable, SpendGuard,
)
from recohut_kit.usage import UsageReceipt


def receipt(number: int, request_sha256: str) -> UsageReceipt:
    return UsageReceipt(f"req-{number}", "model-x", "api_key", "summary:v1",
                        request_sha256, "completed", 1000, 100, 50)


prices = PriceTable(
    currency="USD", source="price list", as_of=date(2026, 10, 20),
    prices=(ModelPrice("api_key", "model-x", 100, 400),),   # minor units per million tokens
)
guard = SpendGuard(
    prices=prices, tz=ZoneInfo("UTC"),
    loop_policy=LoopPolicy(max_identical=3, window=timedelta(minutes=5)),
)
start = datetime(2026, 10, 14, tzinfo=timezone.utc)

states = []
for number in range(1, 4):
    at = start + timedelta(seconds=30 * number)
    guard.admit("nightly-summary", now=at)                  # raises BreakerOpen when open
    outcome = guard.record(receipt(number, "a" * 64), job_id="nightly-summary", at=at)
    states.append(outcome.breaker_state)
print(states, outcome.alert.evidence)
# ['closed', 'closed', 'open'] ('req-1', 'req-2', 'req-3')

try:
    guard.admit("nightly-summary", now=start + timedelta(minutes=2))
except BreakerOpen as refused:
    print(refused.rule_ids)                                 # ('loop.identical_request',)

try:
    guard.breaker("nightly-summary").reset(by="scheduler", now=start, note="auto")
except BreakerResetRefused:
    print("only a named person can reset")

guard.breaker("nightly-summary").reset(
    by="on-call-owner", now=start + timedelta(minutes=10), note="fixed upstream retry"
)
print(guard.breaker("nightly-summary").state)               # half_open

Unknown prices and unknown token counts stay unknown and are never priced as zero. The price table carries its source and as-of date and is labelled as caller-supplied prices, not reconciled billing.

Choosing between owners

You need toUse
Keep a durable record of how long each step took, without a serverlatency with SQLiteLatencyStore
Time every HTTP request on an ASGI servicelatency.asgi.LatencyMiddleware
Record tokens and elapsed time per model callusage.UsageReceipt with append_receipt
Look at a run's spans in a UIphoenix.PhoenixTracing
Put receipt token counts on spans and metricstelemetry.OpenTelemetry
Read latency percentiles from Prometheuslatency.prometheus.PrometheusClient
Annotate spans with scores or labelsphoenix.annotations
Detect metric drift against a baselinemonitoring.baselines
Stop scheduled jobs from burning creditsspend_guard
Track incidents, canaries and budgets for an operated agentagents.operations

Use the measurement half in tests and CI, where no trace server runs. Use the tracing half when a person needs to inspect a run.

Failure behaviour, limits and gotchas

  • Unknown is not zero. A receipt token count, a latency first-chunk time and a priced cost all stay None when unobserved. Aggregations must treat None as missing.
  • The kit never sets the global tracer provider. Every tracer and meter provider is built from objects you pass in, so the kit does not collide with your own OpenTelemetry setup.
  • Facts are immutable. Re-appending the same fact is a no-op. A different fact under the same observation_id raises ValueError.
  • Facts must be safe to store. Timing fields are declared metadata. The store rejects a fact that contains recognised sensitive data instead of masking it, so two identities never merge into one series.
  • first_chunk_ms measures delivery. It is the first chunk the owner observed. It is not provider time to first token and not browser rendering.
  • Trace ids come as a pair. trace_id and span_id must both be present or both be absent. They must be nonzero lowercase hexadecimal of 32 and 16 characters.
  • Receipt spans are emitted after completion. A model.usage span records the observed duration as an attribute. It does not surround the HTTP request.
  • Receipt files are private. append_receipt creates the file with mode 0600 and takes a local advisory lock. It enforces no budget or quota.
  • Phoenix needs extras and a server. PhoenixTracing imports OpenTelemetry and OpenInference when you construct it. PhoenixEndpoint.connect needs a reachable server. Importing recohut_kit.phoenix itself needs neither; names load on first use.
  • Extras can conflict. The agents-phoenix extra conflicts with phoenix, evals-phoenix, telemetry and decision-judge. Check the extras you combine in pyproject.toml before installing them together.
  • DECISION spans depend on the server version. supports_decision_spans is a version check only: supported from 20.23.0, unsupported up to 20.16.0, unknown between. probe_decision_support writes a test span and reads back what the server stored.
  • Only Phoenix and Prometheus readers ship. There is no built-in route to another trace backend. Use telemetry.tracer_provider to build a provider with your own exporter.
  • Spend guard is a rules engine. It makes no model call and chooses no action. It reports alerts and trips a breaker. Reset is human-only by design.

How is this page?

Last updated on