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.
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
| Package | Import path | Tier | What it is for |
|---|---|---|---|
| Usage receipts | recohut_kit.usage | core (module) | UsageReceipt and DetailedUsageReceipt; append_receipt writes a locked JSONL row |
| Latency | recohut_kit.latency | core | LatencyFact, LatencyRecorder, SQLite and SQLAlchemy stores, ASGI timing middleware, OpenTelemetry and Prometheus readers |
| Phoenix | recohut_kit.phoenix | core | Version-aware server handle, project-scoped tracing, PydanticAI and OpenAI instrumentation, span annotations, datasets, UI links |
| Telemetry | recohut_kit.telemetry | core (module) | tracer_provider and OpenTelemetry.record_receipt: model.usage spans and token counters on caller-owned providers |
| Monitoring | recohut_kit.monitoring | catalog | Windowed metric observations, baselines and anomaly rules, a metric catalogue, configuration comparison, prompt-growth guard, RAG triage |
| Spend guard | recohut_kit.spend_guard | catalog | Prices receipts, detects identical-request loops, spikes, drift and projected burn; per-job circuit breaker |
| Agent operations | recohut_kit.agents.operations | catalog | Operational events, canary and budget decisions, signed provenance, casefiles, privacy classification |
| Phoenix evaluation bridge | recohut_kit.evals.phoenix | evaluation owner | Writes evaluation results to Phoenix; documented in Evaluation |
Modules inside recohut_kit.latency:
| Module | Main names | What it does |
|---|---|---|
latency.contracts | LatencyFact, LatencyKind, LatencyStatus, CacheState | The validated fact. Kinds are request, answer, model, tool, judge, browser |
latency.recording | LatencyRecorder, Measurement | A timing scope on a monotonic clock that records exactly one fact |
latency.storage | SQLiteLatencyStore, SQLAlchemyLatencyStore, LatencyStore | Idempotent append and filtered listing |
latency.asgi | LatencyMiddleware | Times each request on an ASGI app, including failures |
latency.otel | OTelLatencyMetrics, fact_from_span, latency_span_processor | Turn facts into OpenTelemetry metrics, or spans into facts |
latency.prometheus | PrometheusClient, Cohort, LatencyWindow | Read latency windows and trends from a Prometheus server |
latency.trace_link | current_trace_ids, with_trace | Stamp the active span's trace and span ids onto a fact |
Modules inside recohut_kit.phoenix:
| Module | Main names | What it does |
|---|---|---|
phoenix.server | PhoenixEndpoint, supports_decision_spans, probe_decision_support | Connect to a running server, read its version, check whether DECISION spans are stored |
phoenix.tracing | PhoenixTracing, instrument_pydantic_ai, instrument_openai | One tracing object is one Phoenix project, on its own tracer provider |
phoenix.annotations | SpanAnnotation, log_annotations, read_annotations | Typed annotations written to spans and read back |
phoenix.datasets | DatasetRow, create_or_get_dataset, run_experiment | Dataset and experiment helpers |
phoenix.links | link builders | Deep 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.
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 10store.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.
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).
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 providersmy_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.
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 downWith 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.
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_openUnknown 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 to | Use |
|---|---|
| Keep a durable record of how long each step took, without a server | latency with SQLiteLatencyStore |
| Time every HTTP request on an ASGI service | latency.asgi.LatencyMiddleware |
| Record tokens and elapsed time per model call | usage.UsageReceipt with append_receipt |
| Look at a run's spans in a UI | phoenix.PhoenixTracing |
| Put receipt token counts on spans and metrics | telemetry.OpenTelemetry |
| Read latency percentiles from Prometheus | latency.prometheus.PrometheusClient |
| Annotate spans with scores or labels | phoenix.annotations |
| Detect metric drift against a baseline | monitoring.baselines |
| Stop scheduled jobs from burning credits | spend_guard |
| Track incidents, canaries and budgets for an operated agent | agents.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
Nonewhen unobserved. Aggregations must treatNoneas 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_idraisesValueError. - 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_msmeasures 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_idandspan_idmust 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.usagespan records the observed duration as an attribute. It does not surround the HTTP request. - Receipt files are private.
append_receiptcreates the file with mode 0600 and takes a local advisory lock. It enforces no budget or quota. - Phoenix needs extras and a server.
PhoenixTracingimports OpenTelemetry and OpenInference when you construct it.PhoenixEndpoint.connectneeds a reachable server. Importingrecohut_kit.phoenixitself needs neither; names load on first use. - Extras can conflict. The
agents-phoenixextra conflicts withphoenix,evals-phoenix,telemetryanddecision-judge. Check the extras you combine inpyproject.tomlbefore installing them together. - DECISION spans depend on the server version.
supports_decision_spansis a version check only: supported from 20.23.0, unsupported up to 20.16.0, unknown between.probe_decision_supportwrites 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_providerto 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