Skip to main content
The read/query half of the monitoring contract. Implement only if the backend has a read API. A read-incapable backend still exposes a reader object, but its methods raise MonitoringReadNotSupportedError on call (never a silent no-op). OpenTelemetry has no read/query standard — each backend invents its own read surface — so this face is the abstraction’s real value.

MonitoringReader

tai42_contract.monitoring.reader.MonitoringReader
Query totals/analytics and the runtime span window.

Members

metrics_capability

tai42_contract.monitoring.reader.MonitoringReader.metrics_capability
Declare which neutral measures and dimensions query_metrics serves. A pure capability declaration (no I/O), so a caller can tell a panel the backend cannot serve from one it served empty, WITHOUT issuing a query that swallows the difference. query_metrics raises MonitoringReadNotServedError for anything outside this set.

list_capability

tai42_contract.monitoring.reader.MonitoringReader.list_capability
Declare which sorts list_traces serves and which filters each sort cannot combine with. A pure capability declaration (no I/O), so a caller offers only the sorts and filter combinations the backend serves. list_traces raises MonitoringReadNotServedError for anything outside it.

max_page_size

tai42_contract.monitoring.reader.MonitoringReader.max_page_size
Declare the largest limit one list_traces call accepts. A pure declaration (no I/O). A limit above it raises ValueError.

query_metrics

tai42_contract.monitoring.reader.MonitoringReader.query_metrics
Totals / analytics screen — server-side aggregation. Aggregates the requested Measure set grouped by the requested Dimension set over the query window. A measure or dimension outside metrics_capability raises MonitoringReadNotServedError — never a silent zero. Parameters

list_spans_in_window

tai42_contract.monitoring.reader.MonitoringReader.list_spans_in_window
The smallest spans that ran in the half-open window [t0, t1). CONTRACT GUARANTEE: exactly one item per tool execution in the window. Every reader performs this tool-granularity selection — it is not an optional filter. A reader selects steps by the producers’ marker: an observation whose metadata tai42.step_role is grouping or sub_step is never an item; generations and events are never items. run scopes to a single run (one trace); None = all runs in the window. kind narrows WITHIN the tool-granularity set (never widens or overrides the guarantee). filter applies the neutral MonitoringFilter clauses (tags live here, not as a discrete param). order_by sorts the result; omitted ⇒ newest-first (start desc). An unserved order_by.field or filter clause raises MonitoringReadNotServedError. Parameters

get_trace

tai42_contract.monitoring.reader.MonitoringReader.get_trace
Fetch one COMPLETE trace (top-level attrs + every observation, with full input/output). Used for replay / evaluation / normalization. Always returns a trace or raises — never None. An absent trace raises TraceNotFoundError; a transient/backend failure (e.g. a timeout) propagates its error so the caller sees the failure and may retry. Distinct from list_spans_in_window (trimmed dashboard units). Parameters

get_observation

tai42_contract.monitoring.reader.MonitoringReader.get_observation
One observation of a trace, with its full input/output. An absent observation raises ObservationNotFoundError; an absent trace raises TraceNotFoundError; any other backend failure propagates. Parameters

list_traces

tai42_contract.monitoring.reader.MonitoringReader.list_traces
List run SUMMARIES matching the filters: one row per trace. Built from the backend’s list surface plus its batched aggregates — never a per-trace body. get_trace is the only body door. A malformed backend row fails the page loudly (never kept as a partial row nor silently skipped). from_timestamp / to_timestamp bound the trace timestamp to the half-open window [from, to); either may be omitted for an open end. filter applies the neutral MonitoringFilter clauses (tags live here, not as a discrete param). order_by sorts the result; omitted ⇒ newest-first (timestamp desc). The sortable fields and the filters each sort cannot combine with are declared by list_capability; a sort or combination outside it, or another unserved filter clause, raises MonitoringReadNotServedError. A read the backend serves only within a bound raises MonitoringReadTooBroadError past it. A limit above max_page_size() raises ValueError. Parameters

export_traces

tai42_contract.monitoring.reader.MonitoringReader.export_traces
The run summaries list_traces would page through, in its order, in one read. Returns at most max_rows + 1 rows; more than max_rows means more runs match. Same window, filter, sort and errors as list_traces; a bound the backend cannot read past raises MonitoringReadTooBroadError. Parameters The write/emit half of the monitoring contract. FAIL-SAFE INVARIANT The EMIT methods (open_span, start_span, record_span, create_event, update_current_span, trace_attributes) and the Span-handle methods (Span.update, Span.set_trace_metadata, Span.end) catch their own errors — they MUST NOT raise into application code. A monitoring outage cannot be allowed to break a run, so call sites need NO try/except around them. Fail-safe never means silent: every caught failure is logged at ERROR and counted in export_health().records_failed. (The one precondition that DOES raise is record_span with no trace_id — a caller bug, not a backend outage.) The module-level attribute_run helper composes writer over trace_attributes, inheriting that method’s guarantee. The NON-emit methods are NOT fail-safe and propagate errors loudly: flush / shutdown (fork-safety must not be silently skipped) and disable (a backend may legitimately no-op it — doing nothing successfully — but a real FAILURE inside it must raise, never be swallowed). current_trace_id() / current_span_id() / is_recording() / export_health() are queries: they never raise. MASKING A writer renders every SecretValue found anywhere in a record’s input, output or metadata as SECRET_PLACEHOLDER; callers never mask for monitoring. RESERVED MARKERS A recorded value holds a one-key object whose key starts with RESERVED_KEY_PREFIX only where the writer rendered a marker (a {"$tai42_ref": …} reference, the {"$tai42_unrecorded": true} statement, the writer’s own byte-string and unencodable forms). A user value carrying such an object is refused by the writer, so a marker read back from a backend is never user data. AMBIENT vs EXPLICIT context trace_context is OPTIONAL. None = emit into the CURRENT (ambient) context — what the no-handle sites use (plain functions with no trace handle). An explicit TraceContext is passed only when one is held (e.g. a downstream/parent span held by a run driver).

RUN_ATTRIBUTION_TRACE_NAME

tai42_contract.monitoring.writer.RUN_ATTRIBUTION_TRACE_NAME

RUN_VERSION_METADATA_KEY

tai42_contract.monitoring.writer.RUN_VERSION_METADATA_KEY

MonitoringWriter

tai42_contract.monitoring.writer.MonitoringWriter
Emit traces/spans/events, report export health, and manage lifecycle. Every backend implements this face.

Members

open_span

tai42_contract.monitoring.writer.MonitoringWriter.open_span
Open a span (started at start_time, else now) and return its handle; Span.end records it. activate=True makes the span the current span of the calling context until end(), or until a use_span / use_trace_context block it was activated in is left; then the innermost activation still live in that context is current again, whatever order spans end in (end() must run in the same context). model / model_parameters carry generation-span detail. Under an active disable() block the handle is a no-op one. Parameters

use_span

tai42_contract.monitoring.writer.MonitoringWriter.use_span
Make span, opened by this writer, the current span of the calling context for the block. The span is not ended on exit; the span current before the block is current again after it. Enter and exit the block in the same context. A span that never opened (the no-op span of a disabled writer or a failed open) leaves the current span unchanged. A span this writer did not open is a record failure: it is logged and counted, and the current span is unchanged. Parameters

use_trace_context

tai42_contract.monitoring.writer.MonitoringWriter.use_trace_context
Make the span trace_context names the current span of the calling context for the block. The named span is the parent of every span started in the block and the one current_trace_id / current_span_id report; it is not this writer’s to end, so update_current_span amends nothing under it. When it already is the current span nothing changes. The span current before the block is current again after it; enter and exit the block in the same context. A context naming no valid span is a record failure: it is logged and counted, and the current span is unchanged. Parameters

start_span

tai42_contract.monitoring.writer.MonitoringWriter.start_span
Open an activated span for the duration of the block, yielding its handle. Equals open_span(activate=True) with end() on exit; calling end() inside the block is a caller bug. model_parameters is open-time only; model and usage can be amended later via Span.update. Parameters

record_span

tai42_contract.monitoring.writer.MonitoringWriter.record_span
Record an already-closed span with EXPLICIT start / end times. For a span whose execution window cannot be timed live in-process — work that ran across a pause and is reported afterwards. trace_context.trace_id is REQUIRED — the explicit-time path has no ambient context to fall back to, so a missing trace_id RAISES (a caller bug); parent_span_id nests the span. Parameters

create_event

tai42_contract.monitoring.writer.MonitoringWriter.create_event
Record a point-in-time event carrying input / output. Returns the event’s RecordId so a producer can reference its values; None when disabled, when the writer records nothing, or when the record failed. Parameters

update_current_span

tai42_contract.monitoring.writer.MonitoringWriter.update_current_span
Amend the CURRENT span without opening a new one. Targets the span of the nearest enclosing activated open_span / start_span. metadata is MERGED key-wise into the metadata given so far (a later value for a key wins). Per-generation token/cost is recorded via Span.update. Parameters

trace_attributes

tai42_contract.monitoring.writer.MonitoringWriter.trace_attributes
Set trace-level name/tags/metadata on every span started inside the block. user_id / session_id set the backend’s native identity dimensions when supplied; None leaves each unset. A ROOT version is carried inside metadata under RUN_VERSION_METADATA_KEY (not a discrete parameter) so a backend without a native version dimension keeps it as ordinary metadata. Parameters

current_trace_id

tai42_contract.monitoring.writer.MonitoringWriter.current_trace_id
The active ambient trace id, or None if no trace is active. Used to gate conditional emits (if writer.current_trace_id():) so none fire outside a trace.

current_span_id

tai42_contract.monitoring.writer.MonitoringWriter.current_span_id
The current span’s id (16 lower-hex), or None when no span is current.

is_recording

tai42_contract.monitoring.writer.MonitoringWriter.is_recording
Whether this writer records anything; False lets producers skip all recording work.

export_health

tai42_contract.monitoring.writer.MonitoringWriter.export_health
A snapshot of everything this writer could not deliver; no I/O. Counted per PROCESS: a forked child’s counters start at zero, so a child never re-counts what its parent counted.

set_health_listener

tai42_contract.monitoring.writer.MonitoringWriter.set_health_listener
Install (None removes) the listener called with export_health() after every flush. The writer calls listener(self.export_health()) at the end of EVERY flush() and shutdown(), on the calling thread, after that call’s export and drop accounting completed. A raising listener is logged at ERROR and does not fail the flush. A writer that records nothing stores the listener and never calls it. Parameters

disable

tai42_contract.monitoring.writer.MonitoringWriter.disable
Suppress emission within the block. Every recording method honors it. A backend that never emits may no-op it; an emitting backend may not.

flush

tai42_contract.monitoring.writer.MonitoringWriter.flush
Deliver (or count as failed) every ended record, then call the health listener.

shutdown

tai42_contract.monitoring.writer.MonitoringWriter.shutdown
Tear the exporter down so the next use rebuilds clean (fork-safety), then call the health listener. Must fully evict the underlying pipeline, not merely flush — a forked child inherits dead background threads otherwise.

attribute_run

tai42_contract.monitoring.writer.attribute_run
Return the context manager that stamps attribution on the ambient trace for the WRAPPED block. A free function composing writer over MonitoringWriter.trace_attributes, kept off the Protocol so structural writers conform without inheriting it. The caller ENTERS the returned manager AROUND the whole run so the run’s spans are created INSIDE the attribution scope. It RETURNS the manager rather than entering it — a one-shot enter/exit here would tear the scope down before any span exists and silently no-op the stamp. It does NOT gate on MonitoringWriter.current_trace_id. A stamp deposited BEFORE any trace is open is NOT lost: trace_attributes is context-scoped — a conforming backend writes the attributes into the ambient context and lifts them onto the trace ROOT when a span is subsequently opened inside the scope. Short-circuiting to a nullcontext when current_trace_id() is None therefore DROPS the attribution on the common case — a door that deposits then opens the run’s first span — so there is no such guard. This helper is NOT itself fail-safe against a non-conforming writer: it CALLS trace_attributes here, so a writer whose signature omits these keywords raises a TypeError at THIS call — before any enter/exit guard inside the writer could run — and a writer that raises on enter/exit surfaces likewise. A caller that must not be broken by a monitoring-writer fault guards entering the returned manager (the skeleton run seams do, logging the fault and continuing the run unattributed). Parameters