Skip to main content
Back to all articles
AI Engineering 12 min readUpdated October 28, 2026

The Trace Says Your Agent Failed. It Doesn’t Say Why.

A production trace tells you what happened. It does not prove which prompt, model, retrieval snapshot, tool schema, policy, or dependency caused the failure. Freeze the incident, run controlled counterfactual replays, repeat stochastic variants, and turn attribution evidence into regression gates.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Failure Attribution#Counterfactual Replay#Observability#Evaluation#Incident Response#AgentOps#OpenTelemetry#TypeScript#Python#Production AI
On this page

At 9:42 AM, a production support agent approves a refund it should have escalated.

The incident channel fills immediately.

One engineer points at the prompt deployment from 9:10.

Another notices the model route changed yesterday.

A third says retrieval returned an older policy document.

Someone else finds a tool-schema rollout from the same morning.

The trace is detailed. It shows the exact sequence:

Text
user request→ account lookup→ policy retrieval→ model decision→ refund tool call→ guardrail result→ final response

Every span has timestamps.

Every tool call has arguments.

Every model generation has a version.

The team can reconstruct what happened.

But there is still one question the trace cannot answer by itself:

Text
Which component actually caused the failure?

Chronology is not attribution.

The component that changed most recently is not automatically the cause. The span closest to the failure is not automatically the cause. The model that emitted the bad decision may have been operating on stale evidence. The retrieval system may have returned stale evidence because the query changed. The query may have changed because the prompt changed. A policy check may have been correct but too late to prevent the side effect.

This is where I want something stronger than reading traces and forming opinions.

I want counterfactual replay.

Freeze the failed incident, change one controlled variable, replay the same workload in a sandbox, repeat enough times to measure stochastic behavior, and ask whether the probability or shape of the failure changes.

That does not magically give us perfect causality.

It gives us something much more useful than guesswork: attribution evidence.

A trace is evidence of execution, not proof of cause

Modern agent tracing is already extremely useful.

OpenAI's Agents SDK can record model generations, tool calls, handoffs, guardrails, and custom events inside traces and spans. OpenTelemetry similarly models operations as spans with timing, attributes, events, links, status, and parent-child relationships.

That is exactly what I want for observability.

A trace can tell me:

Text
what executedin what orderwith which inputsagainst which versionshow long each operation tookwhat each operation returnedwhere an error or bad decision appeared

But a trace usually observes one realized execution.

It does not tell me what would have happened if:

Text
the previous prompt had been usedthe previous model route had been usedthe retrieval snapshot had been differentthe tool schema had not changedthe policy version had been rolled backa flaky dependency had returned the same fixture reliably

Those are intervention questions.

And intervention questions require experiments.

This is the difference I keep in mind:

Text
trace:What happened in this run?​counterfactual replay:What changes when I alter one suspected cause while holding the rest as stable as possible?

Incident debugging becomes a controlled experiment

The production loop I want looks like this:

Counterfactual failure attribution loop for production AI agents

The important architectural shift is that incident response stops being:

Text
read trace→ choose most suspicious span→ patch it→ hope

and becomes:

Text
observe incident→ freeze reproducible evidence→ state competing hypotheses→ intervene on one variable→ replay repeatedly→ compare outcomes→ rank attribution evidence→ fix→ convert the incident into a regression gate

The trace is still essential.

It is the raw material for the experiment.

It just should not be confused with the experiment itself.

Freeze the incident before you start changing things

Counterfactual replay fails quickly if the incident cannot be reconstructed.

I want an immutable incident bundle that captures enough state to explain the exact production configuration.

For an agent system, that usually means more than the prompt.

TypeScript
type ComponentVersions = {  modelRoute: string;  promptVersion: string;  policyVersion: string;  retrievalSnapshot: string;  toolSchemas: Record<string, string>;  memorySnapshot?: string;  orchestrationVersion: string;};​type DependencyFixture = {  dependency: string;  requestHash: string;  response: unknown;  observedAt: string;};​type IncidentBundle = {  incidentId: string;  taskClass: string;  input: unknown;  trustedState: unknown;  components: ComponentVersions;  dependencyFixtures: DependencyFixture[];  observedFailure: string;  expectedInvariant: string;};

The bundle should make questions like these answerable:

Text
Which model route handled the decision?Which exact prompt revision did it see?Which policy revision was active?Which retrieval index or document snapshot produced the evidence?Which tool schema was presented to the model?Which memory state was visible?Which feature flags were enabled?Which external responses materially influenced the run?

If those values live only in today's application configuration, you do not have a reproducible incident.

You have a story about one.

Version everything that can alter agent behavior

A production agent is not just a model.

Its behavior is a function of a large configuration surface:

Text
behavior = f(  task,  prompt,  model,  model parameters,  retrieval data,  tool definitions,  policies,  memory,  orchestration,  external systems,  runtime randomness)

That is why “the model made a mistake” is usually an incomplete incident statement.

Maybe it did.

But if the model received the wrong tool contract, stale policy evidence, poisoned memory, or an inconsistent external response, changing the model may merely hide the failure.

For attribution, every behaviorally relevant component should have an identity.

I like trace metadata such as:

JSON
{  "agent_version": "refund-agent@41",  "prompt_version": "refund-decision@19",  "model_route": "reasoning-primary@2026-09",  "policy_version": "refund-policy@8",  "retrieval_snapshot": "support-index@2026-10-05T08:00Z",  "tool_schema_bundle": "payments-tools@5",  "orchestration_version": "workflow@27"}

The exact names do not matter.

The recoverability does.

Exact replay and counterfactual replay are different tools

I use two separate concepts.

Exact replay

Try to reconstruct the same incident under the same relevant conditions.

The question is:

Text
Can I reproduce the failure?

Counterfactual replay

Start from the frozen incident, deliberately change one suspected factor, and compare the outcome.

The question is:

Text
Does the failure change when I intervene on this component?

Those should not be conflated.

Temporal's replay model is a useful distributed-systems analogy: deterministic workflow state can be reconstructed from recorded Event History, while external or nondeterministic operations belong outside the deterministic replay path. Agent replay needs the same discipline, but LLM calls themselves are often stochastic and external systems may not be safely replayable.

So for agent incident analysis I usually want:

Text
frozen inputs and state+versioned component configuration+recorded or virtualized dependency fixtures+sandboxed side effects+intentional live model calls when measuring stochastic behavior

That is not a byte-for-byte deterministic replay.

It is a controlled experiment over a reconstructed incident.

First establish whether the failure reproduces

Before blaming a component, replay the baseline.

Suppose the production failure was:

Text
agent issued refund without required escalation

Run the frozen baseline 20 times in a safe environment.

Imagine this result:

Text
16 failures / 20 runsp(fail | baseline) = 0.80

That tells me something important.

The incident is not a one-in-a-million token sample. Under the reconstructed conditions, failure is common.

Now imagine instead:

Text
1 failure / 20 runsp(fail | baseline) = 0.05

That is a very different debugging problem.

Before testing prompt rollbacks and model changes, I would ask whether:

Text
production state was reconstructed correctlydependency fixtures are faithfulimportant hidden context is missingthe failure was dominated by randomnessan external condition no longer exists

A counterfactual experiment is only as good as its baseline reconstruction.

One replay is weak evidence for a stochastic agent

This is where conventional deterministic debugging instincts can mislead us.

If I run the old prompt once and it succeeds, I have not proven the new prompt caused the failure.

Maybe both prompts succeed 70% of the time.

Maybe the successful run was luck.

So I want repetitions.

For each intervention:

Text
run N timesclassify each trajectorymeasure failure ratemeasure important trajectory changesrecord latency and cost

The quantity I care about during triage is often a simple intervention effect:

Text
baseline_failure_rate = p0intervention_failure_rate = p1​attribution_delta = p0 - p1

If:

Text
p0 = 0.80p1 = 0.15

then:

Text
attribution_delta = 0.65

That is strong evidence that the intervention matters.

It is not automatically proof that the changed component is the sole root cause.

But now the team has quantitative evidence instead of a timestamp argument.

Build an intervention matrix

For a failed incident, I usually start with the smallest plausible component rollbacks.

Controlled counterfactual intervention matrix

The table behind that diagram could look like this:

ReplayChanged componentFailure rateDelta vs baseline
BaselineNone0.80—
APrompt v19 → v180.15+0.65
BModel route M2 → M10.76+0.04
CRetrieval R13 → R120.71+0.09
DTool schema T5 → T40.79+0.01
EPolicy P8 → P70.77+0.03

I would not write the postmortem yet as:

Text
Root cause: prompt v19

I would write:

Text
Prompt v19 is the strongest single-factor causal candidate.Rolling only that component back reduced the reproduced failure ratefrom 80% to 15% under the frozen incident workload.

Then I would test interactions.

That wording is more precise and more defensible.

One-factor-at-a-time is triage, not a complete causal model

Changing one variable at a time is a very useful first pass.

It is also incomplete.

Agent components interact.

A prompt can fail only with a specific tool schema.

A model route can fail only against a particular retrieval style.

A policy can expose a weakness only when memory contains an old state.

So after a strong candidate appears, I test the important pairs.

For example:

Text
prompt v18 + tool schema T5prompt v19 + tool schema T4prompt v18 + retrieval R13prompt v19 + retrieval R12

Suppose the results are:

Text
v19 + T5 → 80% failurev18 + T5 → 15% failurev19 + T4 → 18% failurev18 + T4 → 12% failure

Now the story is more interesting.

The failure may be a prompt × tool-schema interaction, not a prompt-only defect.

That matters operationally.

If you fix only the prompt, a future prompt revision can rediscover the same interface weakness.

A stronger remediation might include:

Text
tool schema clarification+prompt constraint+regression case covering their interaction

Type the intervention instead of mutating random config

I do not want incident responders hand-editing environment variables during attribution.

Define interventions explicitly.

TypeScript
type ReplayIntervention = {  name: string;  patch: Partial<ComponentVersions>;};​type ReplayResult = {  intervention: string;  repetition: number;  failed: boolean;  failureClass?: string;  trajectoryHash?: string;  latencyMs: number;  costUsd: number;};​async function runIntervention(  incident: IncidentBundle,  intervention: ReplayIntervention,  repetitions: number,): Promise<ReplayResult[]> {  const components = {    ...incident.components,    ...intervention.patch,  };​  const results: ReplayResult[] = [];​  for (let i = 0; i < repetitions; i += 1) {    const replay = await runInReplaySandbox({      incident,      components,      sideEffects: "virtualized",    });​    results.push({      intervention: intervention.name,      repetition: i + 1,      failed: replay.failed,      failureClass: replay.failureClass,      trajectoryHash: replay.trajectoryHash,      latencyMs: replay.latencyMs,      costUsd: replay.costUsd,    });  }​  return results;}

The important line is not the loop.

It is this:

TypeScript
sideEffects: "virtualized"

Production incident replay should not issue real refunds, send real emails, delete real infrastructure, or mutate customer state.

A replay environment should record intended effects, simulate them, or route them to sandbox resources.

Never “reproduce” a dangerous write against production

A consequential agent failure is exactly when I want less trust, not more.

If the original incident was:

Text
agent transferred funds to the wrong destination

the replay must not answer causality by transferring funds again.

I prefer a side-effect adapter:

TypeScript
type IntendedEffect = {  tool: string;  arguments: unknown;  riskTier: "low" | "medium" | "high" | "critical";};​class ReplayEffectSink {  private readonly effects: IntendedEffect[] = [];​  record(effect: IntendedEffect) {    this.effects.push(effect);​    return {      sandboxed: true,      syntheticResult: "accepted_for_replay",    };  }​  all() {    return [...this.effects];  }}

Now the experiment can still answer:

Text
Did the agent attempt the prohibited write?With what arguments?At which decision point?Under which intervention?

without reproducing the harm.

This is closely related to the retry rule from clean retry forks: uncertain or consequential effects need explicit system semantics, not optimistic model reasoning.

Build the same attribution runner in Python

The pattern is language-independent.

Python
from dataclasses import dataclass, replacefrom typing import Any​​@dataclass(frozen=True)class Components:    model_route: str    prompt_version: str    policy_version: str    retrieval_snapshot: str    tool_schema_bundle: str    orchestration_version: str​​@dataclass(frozen=True)class IncidentBundle:    incident_id: str    input: Any    trusted_state: Any    components: Components    observed_failure: str​​@dataclass(frozen=True)class Intervention:    name: str    changes: dict[str, str]​​@dataclass(frozen=True)class ReplayResult:    intervention: str    failed: bool    failure_class: str | None    latency_ms: int    cost_usd: float​​def apply_intervention(    components: Components,    intervention: Intervention,) -> Components:    return replace(        components,        **intervention.changes,    )​​def failure_rate(results: list[ReplayResult]) -> float:    if not results:        raise ValueError("results cannot be empty")​    failures = sum(result.failed for result in results)    return failures / len(results)​​def attribution_delta(    baseline: list[ReplayResult],    intervention: list[ReplayResult],) -> float:    return failure_rate(baseline) - failure_rate(intervention)

Again, the math is simple.

The hard engineering work is making the experiment controlled enough that the number means something.

Preserve dependency responses when they matter

External systems create a major attribution trap.

Imagine the incident depends on:

Text
CRM responsepricing APIpolicy databasesearch resultsfeature flag servicerate-limit responsethird-party payment state

If your replay talks to today's live dependency, you may not be replaying the same incident at all.

So I distinguish between two modes.

Fixture mode

Return the recorded production response.

Use this when the goal is to isolate agent-component behavior.

Text
same CRM responsesame retrieved evidencesame feature flag valuesame tool result

Live-control mode

Call an external dependency intentionally because the dependency itself is one of the hypotheses.

Use this when the question is:

Text
Did the dependency cause the incident?

Those modes should be explicit in the experiment record.

Otherwise a team can think it tested the model while an external response silently changed underneath it.

Compare trajectories, not only final answers

Final failure rate is necessary but not sufficient.

Two interventions can both “succeed” while taking very different paths.

I want to compare:

Text
tool sequenceretrieval queriesselected evidenceguardrail decisionsescalation behaviorside-effect attemptsloop countlatencycost

Suppose both prompt v18 and v19 produce a correct final answer during a replay.

But v19 does this:

Text
wrong refund attempt→ guardrail blocks it→ recovery→ correct escalation

while v18 does this:

Text
recognize missing authorization→ escalate directly

Those are not equally healthy trajectories.

That is why this article complements trajectory evaluation.

Trajectory evals ask whether an execution path is acceptable.

Counterfactual attribution asks which controlled change alters the bad path.

Failure classification should be stable across replays

Do not let each replay invent a different definition of “failed.”

Define the incident invariant first.

For example:

Text
Invariant:Any refund > $500 without fraud-clearance evidencemust require human approval before a write is attempted.

Then a replay fails if:

Text
refund_amount > 500AND fraud_clearance != validatedAND write_attempted == true

That is much stronger than:

Text
LLM judge says this run seems unsafe

An LLM evaluator can still help classify nuanced trajectories, but the highest-risk invariants should be deterministic whenever possible.

Rank hypotheses by evidence, not by confidence language

After the experiments, I want an attribution report that separates observation from interpretation.

For example:

JSON
{  "incidentId": "inc_2048",  "baselineFailureRate": 0.80,  "candidates": [    {      "component": "prompt_version",      "from": "v19",      "to": "v18",      "failureRate": 0.15,      "delta": 0.65,      "interpretation": "strong_candidate"    },    {      "component": "retrieval_snapshot",      "from": "R13",      "to": "R12",      "failureRate": 0.71,      "delta": 0.09,      "interpretation": "weak_single_factor_effect"    }  ],  "interactionTestsRequired": [    "prompt_version x tool_schema_bundle"  ]}

Notice what is missing:

Text
"The prompt definitely caused it."

The output says what was changed and how the observed failure rate moved.

Engineers can audit that.

Confidence needs sample size, not adjectives

I would not label an attribution “high confidence” merely because the delta looks large after three runs.

For important incidents, the experiment report should preserve:

Text
number of repetitionsfailure countsuccess countrun-to-run variancemodel parametersreplay environment version

For example:

Text
baseline: 16 / 20 failuresprompt rollback: 3 / 20 failures

is more informative than:

Text
prompt rollback worked much better

For severe or ambiguous incidents, you can add confidence intervals or a Bayesian comparison rather than relying only on the point estimate.

The key principle is simple:

stochastic systems need statistical incident evidence.

When attribution remains unresolved

Sometimes every replay tells a messy story.

You may see:

Text
baseline failure rate: 0.35prompt rollback: 0.28model rollback: 0.31retrieval rollback: 0.26policy rollback: 0.34

No component has a large single-factor effect.

That is not a failed experiment.

It is evidence that the incident may be:

Text
interaction-drivenrare stochastic behaviormissing replay stateexternal-dependency drivendata-quality relatedmisclassified by the evaluator

“Unresolved” is a valid production state.

It is much safer than forcing a root-cause label because a postmortem template requires one.

Distinguish necessary, sufficient, and contributing causes

This vocabulary helps incident reviews.

A component can be:

Necessary in the observed setup

When it is removed, the failure disappears.

Sufficient under the replay conditions

Introducing it into an otherwise safe configuration reliably produces the failure.

Contributing

Changing it reduces failure probability but does not eliminate the failure.

Correlated

It appears near the incident but controlled interventions do not materially change the result.

That is a much better language for complex agent systems than:

Text
root cause = model

Many agent incidents are system failures, not component failures.

Use replays to test competing explanations

A healthy incident review should start with more than one hypothesis.

For example:

Text
H1: Prompt v19 weakened the escalation instruction.H2: Retrieval R13 omitted a required policy clause.H3: Tool schema T5 made refund execution appear reversible.H4: Model route M2 over-weighted the tool description.H5: The policy guardrail ran after the side-effect decision.

Each hypothesis should imply an intervention.

If a hypothesis cannot produce a test, it may be too vague.

Good:

Text
If prompt v19 is causal, replaying with v18 while holding theother incident components fixed should materially reduce the failure rate.

Weak:

Text
The model got confused.

The first can be challenged.

The second mostly ends discussion.

Counterfactual replay should be part of your incident platform

I would expose this as a first-class operation, not a collection of one-off notebooks.

Something like:

TypeScript
const experiment = await attribution.run({  incidentId: "inc_2048",  repetitions: 20,  interventions: [    {      name: "prompt-rollback",      patch: { promptVersion: "refund-decision@18" },    },    {      name: "model-rollback",      patch: { modelRoute: "reasoning-primary@prev" },    },    {      name: "retrieval-rollback",      patch: { retrievalSnapshot: "support-index@R12" },    },  ],});

And the result should link back to:

Text
original traceincident bundleexperiment configurationall replay tracesevaluator versionattribution summaryfix commit / config changeregression fixture

Now the postmortem is reproducible.

A future engineer can rerun the evidence instead of trusting a paragraph written under incident pressure.

Observability needs attribution metadata

If you want to debug this way later, collect the right metadata now.

At minimum I want every production agent trace to expose:

Text
agent versionmodel route/versionprompt versionpolicy versionretrieval snapshot/index versiontool schema versionsmemory/checkpoint versionfeature flagsworkflow/orchestration versionrisk tiertenant/workload segmentexperiment/release cohort

OpenTelemetry's model of spans, attributes, events, links, and status gives you a standard foundation for that kind of telemetry. OpenAI's Agents SDK tracing similarly records agent runs and important model/tool/guardrail events.

The application still has to decide which business and version metadata makes an incident reproducible.

Instrumentation is not the same as an incident model.

The metrics I would put on the attribution system

A counterfactual replay platform should have its own reliability metrics.

I would track:

Text
incident reproduction ratemedian time to reproducible incidentmedian time to attribution candidateunresolved attribution ratereplay count per incidentintervention effect sizeinteraction-test ratereplay-control driftsandbox side-effect escape attemptsreplay costreplay latencyregression-fixture conversion raterecurrence after attributed fix

Two metrics deserve special attention.

Incident reproduction rate

If production failures cannot be reproduced at all, your trace/version/fixture capture is incomplete.

Regression-fixture conversion rate

If incidents get investigated but never become durable tests, your organization is paying repeatedly for the same knowledge.

Attribution should feed your eval set

Once you have strong attribution evidence, turn the incident into a permanent fixture.

For example:

JSON
{  "case": "refund_requires_fraud_clearance",  "source": "production_incident_inc_2048",  "required_invariants": [    "no_refund_write_before_clearance_or_human_approval"  ],  "required_slices": [    "high_value_refund",    "stale_retrieval_risk",    "tool_schema_change"  ]}

This is where failure attribution connects to a living eval suite.

The production incident should become part of the evidence that future versions must survive.

Otherwise you can diagnose the exact same failure again six months later.

And because eval data itself ages, this fixture should also participate in your broader eval-set lifecycle rather than becoming an immortal, context-free golden example.

Attribution should affect release gates

Suppose prompt v19 is strongly implicated.

A weak remediation is:

Text
roll back prompt v19

A stronger remediation is:

Text
1. roll back v192. create a regression fixture from the incident3. add an evaluator for the violated invariant4. run it across prompt/model/tool combinations that matter5. block release when the invariant regresses

The incident now improves the deployment system.

That is the outcome I want from production failures.

Not just a fix.

A new control.

This also improves SLO operations

Failure attribution becomes especially valuable when an SLO burns unexpectedly.

Your reliability system might tell you:

Text
high-risk action correctness SLO is burning at 6x

That is the operational signal.

It does not tell you which component to roll back.

Counterfactual replay can help rank the likely causes.

That closes a useful loop with agent SLOs and error budgets:

Text
SLO detects reliability degradation→ traces identify affected incidents→ counterfactual replay attributes likely causes→ remediation changes component/policy→ regression gate prevents recurrence→ SLO confirms production recovery

That is much stronger than watching a dashboard turn red and asking which team deployed last.

What I would not do

I would not call the latest deployment the root cause because it happened first in the timeline.

I would not call the model the root cause merely because the model emitted the bad action.

I would not treat a single successful rollback replay as proof.

I would not replay consequential writes against production to “see if the bug happens again.”

I would not change prompt, model, retrieval, and tool schema simultaneously and then claim attribution.

I would not use today's live dependencies while pretending the experiment held external conditions constant.

I would not ignore component interactions after a strong one-factor candidate appears.

I would not let an LLM write a confident root-cause narrative that is stronger than the experiment evidence.

I would not delete the original failed trace after finding a fix.

And I would not close an incident without asking whether the failure should now exist as a regression fixture.

The incident rule I would keep

For a production AI-agent failure, I want five artifacts:

Text
1. the original trace2. an immutable incident bundle3. explicit competing hypotheses4. repeated controlled replay results5. a regression fixture tied to the remediation

The workflow becomes:

Text
trace the failure→ freeze the incident→ reproduce the baseline→ intervene on one component→ repeat→ compare failure probability and trajectory→ test important interactions→ classify attribution evidence→ remediate→ gate future releases

The key mental model is this:

Observability tells you what the system did. Attribution asks what would have changed the outcome.

Production agents are too stochastic and too composed of interacting parts for “the suspicious-looking span” to be a sufficient root-cause method.

If we can freeze the evidence, control the intervention, repeat the replay, and measure the difference, incident response becomes an engineering discipline instead of a debate.

That is the standard I want for agent systems that are allowed to take real actions.

References

KEEP READING

Related engineering notes