flowchart TB
A[Agent and tools<br/>instrumented events] --> B[Collector<br/>validate and minimize]
B --> C[Restricted evidence store<br/>retention and access]
B --> Q[Privacy or integrity failures<br/>quarantine and alert]
C --> D[Eligible sampling frame<br/>version and completeness]
D --> E[Probability sample<br/>population estimates]
D --> F[Risk sample<br/>incident discovery]
E --> G[Deterministic checks and<br/>calibrated judge or reviewer]
F --> G
G --> H[Versioned decisions<br/>pass, fail, insufficient]
H --> I[Metrics, triage and response]
I --> J[Reviewed, safe regression case]
Chapter 14. Production Trace Evaluation: Collection, Privacy, and Decisions
Juniper tells a customer that a return is complete. The operations dashboard reports a successful response, but the order system shows that the return was never recorded. A trace connecting the request, tool call, response, and authoritative state can reveal the discrepancy; a response alone cannot. That same trace might also contain an email address, an order identifier, or a customer’s account details, so the team must decide what evidence it needs before it collects and distributes the record.
This chapter builds the path from an observed interaction to an evaluation decision. Chapter 16 describes a shared service architecture for evaluation, while the production-monitoring chapter covers monitoring strategy. Chapter 17 takes reviewed failures into the data flywheel. The accompanying Python example uses only invented events, has no network or external model calls, and performs no actions against an environment. It demonstrates the decision flow, not a production-ready privacy, tracing, or authorization system.
The pipeline and its contracts
Before instrumenting an agent, define the decision, population, permitted purpose, and evidence needed. For a return workflow, one claim might be: “The agent acts within the customer’s authority and accurately reports the resulting order state.” Its oracle must come from an authorized policy and an independently captured system-of-record outcome, not just the agent’s assertion. A trace can establish what was recorded; it cannot establish that an unobserved action never occurred.
In a real deployment, the collection boundary must apply approved controls before persistence and export, including at agents, SDKs, exporters, queues, and exception logs where applicable. A collector cannot undo sensitive data already written upstream. Privacy or integrity failures need a bounded, access-controlled response: reject or quarantine according to policy, alert an owner, and do not silently count the event as a successful evaluation. The diagram does not imply a particular vendor or require the same storage for every step.
Define what a trace must contain
Use an episode or user task as the evaluation unit and maintain stable links among its spans. A useful production contract might contain the following fields; whether a field may be collected depends on the documented purpose and access rules.
| Field | Role | Collection rule |
|---|---|---|
| Tenant, trace, span, and parent IDs | Join one authorized interaction and its steps | Generate opaque identifiers; avoid customer identifiers in IDs and restrict linkability. |
| Event type, time, duration, and status | Order operations and detect missing or failed steps | Define clock, schema version, and late-arrival handling. |
| Agent, model, prompt, tool, policy, and evaluator versions | Interpret and compare evidence | Record approved version references, not credentials or dynamic customer content. |
| Tool name, authorization decision, and bounded result | Evaluate attempted actions and policy enforcement | Capture only necessary, approved attributes; distinguish a request from an executed action. |
| Final response and relevant state evidence | Assess the communicated result and authoritative outcome | Prefer minimized content or protected evidence references; retain provenance and collection time. |
| Sampling, consent or other applicable permission, and retention metadata | Govern downstream use | Record the applicable basis and eligibility, inclusion probability, policy version, and expiry. |
A sample trace might contain a request span trace-1-root, a tool span trace-1-tool, an outcome span trace-1-state, and a response span trace-1-reply, all attached to the request. The outcome needs an independently collected state observation; a model saying “done” is not that observation. Distributed instrumentation also needs an explicit rule for retries, duplicate delivery, partial spans, clock skew, asynchronous outcomes, and the window after which late evidence is reconciled. A delayed or missing state observation is unknown, not a failed or successful transaction by default.
The runnable fixture deliberately uses a smaller schema: trace_id, span_id, parent_id, kind, and an allowlisted attributes dictionary. It leaves out timestamps, actual OTel exporters, version capture, durable storage, and real access enforcement. OpenTelemetry GenAI conventions can provide shared names in an implementation, but pin the chosen version and assess every content attribute against the privacy policy [1].
A production-oriented event contract
The following illustrative JSON is a proposed envelope, not an OTel wire-format example or a fixture emitted by the lab. Its values are synthetic. Version references must be derived from trusted instrumentation, and the result reference must be checked against an authorized source.
{
"schema_version": "trace-event-v1",
"tenant_ref": "tenant-synthetic-1",
"trace_id": "trace-synthetic-1",
"span_id": "span-synthetic-tool",
"parent_span_id": "span-synthetic-request",
"event_type": "tool.execution",
"observed_at": "2026-01-15T12:00:00Z",
"duration_ms": 41,
"agent_version": "agent-v2",
"policy_version": "returns-v3",
"tool_version": "returns-tool-v4",
"authorization_decision": "allow",
"execution_status": "completed",
"evidence_ref": "synthetic://state-observation-1",
"privacy_policy_version": "minimize-v1"
}In an implementation, validate required fields and allowed values before routing an event. Partition storage by tenant and purpose, preserve the schema version, and maintain an access-controlled mapping from a trace to its evidence and evaluation records. Give each event an idempotency key scoped to its producer and tenant; verify duplicate payloads before collapsing them, and investigate conflicts rather than silently choosing one. At a declared cutoff, finalize the trace as complete or incomplete; a late event should trigger a versioned amendment or re-evaluation under an explicit policy, not overwrite the original decision invisibly.
For each evaluation job, record at least the trace and evidence versions, sampling-frame and selection version, inclusion probability when known, privacy policy, rubric, evaluator and model versions, component results, final decision, reason codes, and review status. Store references rather than copying raw content into ordinary metric labels or alert messages. A deletion workflow must find and handle all permitted derivatives through that lineage, including an evaluation result that itself contains personal information.
Privacy policy before collection
Document data categories, allowed uses, lawful or otherwise authorized collection and review, permitted recipients, jurisdictions, retention, and deletion with the appropriate privacy and legal owners. Consent is not the only possible legal basis, nor does the lab establish that any particular basis applies. Collect the minimum needed for the specific evaluation, and use synthetic cases when real interactions are unnecessary.
| Stage | Required design decision and check |
|---|---|
| Collection | Identify sensitive fields and sources, disable unneeded capture, and test that secrets and personal data do not leak through exception logs, SDKs, or exporter buffers. |
| Storage and transport | Encrypt in transit and at rest; use tenant- and purpose-scoped authorization, audit access, and set explicit retention and expiry. Do not treat opaque IDs as proof of anonymity. |
| Reviewer access | Give trained reviewers only the context required for their task; record authorization and access, restrict exports, and provide a route for reporting unexpected sensitive data. |
| Judge inputs | Minimize and redact before a judge sees content, including prompts and attachments. Approve external processors, regions, use, retention, and model-provider terms; a judge is another data recipient. |
| Retention and deletion | Define expiry, deletion requests, legal holds, and verification across primary stores, queues, caches, backups, and replicas. Backup expiry may be delayed; document and verify that delay rather than claiming immediate erasure. |
| Derived artifacts | Track trace-to-label, evaluation result, embedding, report, dataset, and regression-case lineage. Propagate deletion or approved replacement where required; isolate sealed holdouts and prevent unauthorized training use. |
Redaction and pseudonymization reduce exposure but do not automatically anonymize data. Quasi-identifiers, rare events, links, or reversible mappings may still identify someone. Detectors can miss names, secrets, unusual formats, or non-text content, and over-redaction can remove evidence a grader needs. Measure both missed detections and unnecessary removal using approved test sets, use layered controls appropriate to the data, and mark an evaluation insufficient when necessary context is unavailable. A hash or HMAC is not encryption or a blanket privacy exemption.
Runnable walkthrough: collect, sample, and evaluate
From the repository root, install the companion package as described in Appendix F, then run:
python code\ch23\lab_production_trace_pipeline.py
python -m unittest discover -s code\tests -p "test_production_traces.py" -vThe lab constructs five synthetic traces in memory. It never writes raw or sanitized traces to disk, queries an order system, calls a model, or performs a replay. The full implementation is code\bookkit\production_traces.py; its data classes are:
Span(trace_id, span_id, parent_id, kind, attributes)
Trace(trace_id, risk, spans, errors)
Sample(trace, stream, inclusion_probability)For example, the following is the fixture’s input for one task. The values are invented, and state_ok stands in for an independently observed state assertion rather than a live lookup:
spans = [
Span("trace-1", "trace-1-root", None, "request", {}),
Span("trace-1", "trace-1-tool", "trace-1-root",
"tool", {"authorized": True}),
Span("trace-1", "trace-1-state", "trace-1-root",
"outcome", {"state_ok": True}),
Span("trace-1", "trace-1-reply", "trace-1-root",
"response", {"text": "Order resolved."}),
]
trace = collect_trace("trace-1", "routine", spans)In the script, fixture constructs those records for each example, collect_trace validates and sanitizes them, and sample_traces returns two lists of Sample objects. evaluate produces a decision dictionary for each selected sample. The example runs these stages synchronously and in memory; the production architecture needs durable queues, identity, authorization, retries, and stores with the separate guarantees described above.
1. Ingest and enforce the declared fixture policy
The fixture policy accepts only the four span kinds and their explicitly allowed fields. A request has no attributes; a tool carries a Boolean authorized; an outcome carries a Boolean state_ok; and a response carries text. Identifiers are restricted to a small synthetic character set. Unknown fields, invalid IDs, and duplicate span IDs produce explicit errors rather than being ignored. The collector removes email-shaped text from response content before returning the sanitized trace; if the redactor raises an exception or an email-shaped string remains, it discards that response and reports redaction_failed without returning the rejected text or exception message.
This is an intentionally narrow email-pattern demonstration, not general PII detection or proof of anonymity. Arbitrary names, secrets, URLs, other sensitive formats, and unsafe identifiers can pass this toy policy. Do not deploy it on real traces. A production collector needs comprehensive policy enforcement, trusted identity and outcome sources, schema and payload limits, secure transport, tested deletion, and independent monitoring of every collection path.
2. Establish two separate sampling streams
sample_traces sorts the eligible synthetic frame by ID and takes a seeded simple random sample without replacement. With five traces and a sample of three, each trace has inclusion probability \(3/5=0.6\). The seed makes this fixture reproducible; production sampling also needs an approved sampling frame, reproducible selection protocol, and access controls. The high-risk queue independently selects all traces marked high and records no probability. A trace can occur in both streams: do not combine the two lists into one population estimate.
A probability sample can support estimates for its defined eligible frame if inclusion probabilities and missingness are handled appropriately. It cannot cover interactions never collected or excluded from that frame without further assumptions. A risk queue is useful for finding and prioritizing severe failures, but its raw failure rate does not estimate prevalence. Keep privacy-rejected or otherwise unavailable observations in frame-level coverage accounting where permitted; excluding them silently can bias conclusions.
For a real job, first freeze the eligible frame and its eligibility rules for a specified window; record total eligible, collected, rejected, and unavailable counts separately. Next select the probability sample and record the selection method and per-case probability. Then create a separate risk queue using documented risk indicators, including how missing indicators are handled. Finally, join each selected case to its trace version and approved evidence. A privacy rejection may prevent grading, but it should remain visible in aggregate coverage statistics without preserving prohibited content.
3. Grade the observed evidence
evaluate checks for the four required kinds, duplicate IDs, and parent relationships, then evaluates two separate signals:
- The deterministic fixture check fails if a recorded tool action is unauthorized or a recorded outcome has
state_ok=False. In production, validate that the authorization and state observations come from trusted sources, apply the correct policy version, and distinguish an attempted action that was denied from an unauthorized action that actually occurred. This lab’sauthorized=Falserepresents a violation, not a safely blocked attempt. - The illustrative “judge” is a fixed lookup:
Order resolved.maps to pass andUnclear response.maps to fail. Other text is insufficient evidence. This is not an LLM judge, a claim of correctness, or a calibrated rubric; it merely demonstrates a separate result and abstention.
Each result carries the trace ID, sampling stream and inclusion probability, policy and evaluator versions, both component results, final decision, and error codes. A known deterministic or judge failure takes precedence over missing evidence. Otherwise, a pass requires both checks to pass and the required evidence to be intact; missing or conflicting evidence, redaction failure, or judge abstention produces insufficient evidence, never a success-shaped default. Preserve separate safety gates and triage confirmed critical failures immediately, even when other evidence is incomplete.
For example, the program’s trace-1 result contains "deterministic": "pass", "judge": "pass", "decision": "pass", "stream": "probability", and "inclusion_probability": 0.6. It also records "privacy_policy": "synthetic-email-v1", "deterministic_version": "synthetic-state-v1", "judge_version": "fixture-lookup-v1", and an empty errors list. A production record should additionally identify its actual evidence, rubric, schema, policy, and model versions, as well as a reason and adjudication status. Never interpret this fixture’s synthetic policy version as approval to process customer data.
For an actual model judge, define the construct, rubric, permissible inputs, evidence requirements, abstention rules, and cost and latency limits. Calibrate on independently adjudicated examples, measure errors by relevant slice, test prompt injection in the evidence, and monitor judge version and drift. A judge’s confidence or agreement with another model is not an authoritative outcome; human review and deterministic checks have their own limitations too.
4. Read the results without overstating them
The supplied seed produces this output:
probability sample: n=3
trace-1: deterministic=pass, judge=pass, decision=pass, p=0.6
trace-2: deterministic=pass, judge=fail, decision=fail, p=0.6
trace-4: deterministic=pass, judge=insufficient_evidence, decision=insufficient_evidence, p=0.6
decisions: {'fail': 1, 'insufficient_evidence': 1, 'pass': 1}
risk sample: n=2
trace-3: deterministic=fail, judge=pass, decision=fail, p=None
trace-4: deterministic=pass, judge=insufficient_evidence, decision=insufficient_evidence, p=None
decisions: {'fail': 1, 'insufficient_evidence': 1}
The fixture shows one pass, one observed failure, and one unresolved case in the probability sample. It does not show a real-world failure rate, and the unresolved case must not be dropped or counted as a pass. For a real report, define the eligible population and time window, show sample sizes and unknowns, use design-appropriate weighting and uncertainty intervals, and investigate nonresponse or missing evidence. The risk sample overlaps the probability sample and is for investigation, not an additional independent denominator.
5. Route decisions and protect the evidence lifecycle
A confirmed unauthorized action should enter the established incident process with its owner, severity, containment, and restricted evidence reference. A judge disagreement may need adjudication rather than an automatic rollback. An incomplete trace should create a collector, exporter, or evidence-quality investigation; monitor missingness and latency by tenant and slice. Preserve evaluator, rubric, policy, sampling, and schema versions so later changes do not silently rewrite history.
After review, a case becomes a regression fixture only if its expected behavior and oracle are defensible and its use is authorized. Replace sensitive values with synthetic ones where feasible, verify that the failure remains reproducible, and record provenance and limitations. Never replay a production trace against live tools or repeat its writes merely to evaluate it. Use a sandbox, mock, or read-only replay with side effects disabled and a separately verified environment.
Worked implementation: one interaction from trace to regression
The following companion case takes the design one step further than the introductory lab. It carries a fictional return through a versioned, multi-span record, collection, sampling, evaluation, simulated review, alert routing, and creation of a synthetic regression record. The original observation and all results are invented: there is no real customer, live tool, external judge, reviewer, notification, or protected data. The example uses SQLite to make the intermediate records inspectable, not to claim that SQLite provides production access control.
Run the case in memory first, then optionally create a new file in an existing directory:
python code\ch23\lab_trace_to_decision.py
python code\ch23\lab_trace_to_decision.py --database trace-demo.sqlite
python -m unittest discover -s code\tests -p "test_trace_case_study.py" -vThe file option creates the named file exclusively and refuses to overwrite an existing one. It leaves the file for inspection; use a different name for each run. The file contains synthetic data only. The default uses an in-memory database, which disappears when the process ends. The implementation is code\bookkit\trace_case_study.py and uses the existing collector and evaluator described above. All five tables are created and populated in one transaction; an insertion failure rolls it back.
A complete synthetic event sequence
Each event carries a trace ID, tenant reference, span and parent IDs, timestamp, duration, and the same schema, agent, model, prompt, tool, policy, evidence, and privacy version references. The table shows trace-5 before collection; its email is an invented input, not a customer’s address. The state_ok field stands in for a trusted, independently collected observation.
| Span | Parent | Kind and permitted attributes | Classification and handling |
|---|---|---|---|
trace-5-root |
none | request; no attributes | Operational metadata; retain only under the approved purpose. |
trace-5-tool |
trace-5-root |
tool; authorized=True |
An allowed action, not evidence that the desired state change happened. |
trace-5-state |
trace-5-root |
outcome; state_ok=False |
Synthetic system-of-record evidence that the desired state was absent. |
trace-5-reply |
trace-5-root |
response; Order resolved. synthetic@example.test |
Content may contain personal data; the fixture collector replaces the address with [EMAIL]. |
The permitted schema does not send arbitrary request attributes to evaluators. The actual privacy classification of IDs, timestamps, state references, and content depends on context: even metadata may be identifying. The toy email expression is not adequate for real PII, and version and tenant fields in the synthetic generator are constants rather than authenticated production metadata.
The frame also contains trace-4, whose outcome span is deliberately missing. Its final response cannot substitute for state evidence, so it receives insufficient evidence. If an event arrives later in a real system, preserve the original decision and create a versioned amendment or re-evaluation; do not silently rewrite history. In the case study the raw fixture is constructed in memory, projected into the existing collector, and only accepted, sanitized span attributes are written to the traces table. There is no upstream SDK or exporter in this example.
Sampling and minimum inputs for each evaluator
The frozen synthetic frame has five eligible traces. A simple random sample without replacement of three, with seed zero, selects trace-4, trace-5, and trace-1, each with inclusion probability \(3/5\). The risk queue separately selects the two high-risk traces. trace-4 appears in both queues; results are stored with distinct stream identifiers, and the queues are not pooled for population estimation.
The deterministic evaluator sees the tool authorization and state fields and uses the predeclared synthetic rule: an unauthorized action or absent desired state is a failure; missing required evidence is unknown. A real system must establish whether the recorded decision concerned a blocked attempt or an executed action, and whether state came from an authorized system of record. The example’s trace-5 tool was authorized but its state check failed.
The illustrative judge sees only the sanitized response field and uses a fixed lookup; the additional text in trace-5 causes it to abstain. A real judge adapter should receive only the approved evidence necessary for its rubric, return a versioned structured verdict and reason or abstention, validate its output, and be qualified against independent adjudication. Before sending any content to an external provider, obtain the applicable privacy and security approvals. This exercise does not contact a provider or establish that a judge is calibrated.
For trace-5, the deterministic failure takes precedence over judge abstention. The resulting record includes trace_id, stream, inclusion probability, component verdicts, decision and error codes, along with synthetic schema, policy, evaluator, rubric, and frame versions. The database uses (trace_id, stream) as the evaluation key so the risk and probability results cannot accidentally overwrite each other. In a real service, include trace and evidence versions, selection identifiers, timing, outcome provenance, and an append-only re-evaluation or amendment strategy; protect the database and record authorized access.
Interpret the probability sample and its unknown
The three sampled decisions are one pass, one fail, and one unknown. Each selected case has weight \(1/0.6=5/3\), and the eligible frame has \(N=5\). If the unknown is not a failure, the Horvitz–Thompson estimate is \((5/3)/5=1/3\); if it is a failure, the corresponding estimate is \((10/3)/5=2/3\). These are bounds on the sample-based estimate under the two possible unknown labels, not a confidence interval and not the observed-case failure rate \(1/2\).
Sampling variability is separate. The program enumerates possible finite-population failure counts using the hypergeometric distribution, inverts two-sided 95% tests for each possible unknown label, and takes the union. For this deliberately tiny frame the resulting conservative interval is \([0.2,0.8]\). It assumes simple random sampling without replacement from the declared five-case frame and that known labels are correct; it allows the one unresolved label to be either outcome. It says nothing about uncollected interactions, label error, a different sampling design, or the real world. With a larger production frame, specify the design and uncertainty method in advance, keep privacy and missing-evidence coverage visible, and obtain statistical review before using an estimate for a consequential decision.
The reproducible output includes:
probability: trace-4 insufficient_evidence p=0.6
probability: trace-5 fail p=0.6
probability: trace-1 pass p=0.6
summary: {'population': 5, 'sample': 3, 'failures': 1, 'unknown': 1, 'weighted_fail_lower': 0.3333333333333333, 'weighted_fail_upper': 0.6666666666666666, 'exact_95_population_interval': (0.2, 0.8)}
Review, alert, and regression lineage
The case study records a simulated reviewer confirming the synthetic state mismatch, a high-severity alert marked queued-not-delivered, and a regression fixture containing only a synthetic task and Boolean expected and observed state. No person is contacted and no alert is sent. The mock-only replay compares those Boolean values and reproduces the failure without calling an agent or tool; changing the observed value to True makes that mock check pass. This reproduces the fixture’s state predicate, not the behavior of a live agent.
To inspect the stored case after the file-backed run, use Python’s SQLite client with the file you created:
import sqlite3
from contextlib import closing
with closing(sqlite3.connect("trace-demo.sqlite")) as db:
for table in ("traces", "evaluations", "reviews", "alerts", "regression_cases"):
print(table, db.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0])
print(db.execute(
"SELECT payload FROM evaluations WHERE trace_id = ? AND stream = ?",
("trace-5", "probability"),
).fetchone()[0])The table names in this query are fixed examples, not untrusted input. The output contains five sanitized trace records, five evaluation records across the two streams, and one each for review, alert, and regression. To make this a real operating workflow, add a restricted review application, authenticated reviewers, a verified notification transport with delivery and acknowledgement, and a governed approval step before a case enters the regression dataset. Maintain trace-to-derived-record lineage and propagate applicable deletion requests; the toy database has no identity, encryption, retention, access auditing, or deletion service.
Testing and production hardening
The companion tests exercise successful grading; redaction failure and exception handling; missing and invalid parent spans; duplicate IDs; judge failure and abstention; failure precedence; rejected extra attributes; and separate sampling streams. They also verify that rejected synthetic content is not returned in a trace. Add representative test cases for false-positive and false-negative detection, multilingual and multimodal content, secrets, malformed payloads, and identifiers before choosing a real privacy system. Test deletion and access denial through every downstream store, reviewer interface, external processor, and backup policy—not just the collector.
For a production implementation, also test late and out-of-order events, identical and conflicting retries, idempotent result writes, broken correlation, partial traces, missing state outcomes, sampling-frame loss, evaluator timeouts, judge drift, and alert delivery. Define whether to deduplicate known identical events or quarantine conflicts; the teaching collector conservatively reports every duplicate ID. Instrument coverage and pipeline health independently, with explicit owners and SLOs. If required observations or privacy safeguards fail, pause affected automated decisions or label them insufficient until the control is restored.
Chapter takeaways
- Start with a decision, trusted oracle, eligible population, and authorized data use—not a request to log everything.
- Treat collection, redaction, sampling, grading, reporting, and deletion as linked contracts with independently observable failures.
- Keep representative and risk-focused review streams distinct; record unknowns and do not infer production prevalence from targeted cases.
- Preserve evaluator versions and component results, and never turn incomplete evidence or an uncalibrated judge into a pass.
- Use synthetic fixtures and side-effect-free replay; only reviewed, authorized, privacy-safe cases enter the data flywheel.