Skip to main content
Back to all articles
AI Engineering 10 min readUpdated October 4, 2026

Your Agent Got the Right Answer. Its Execution Trace Still Failed.

Final-answer correctness can hide a dangerous agent path. Evaluate the full execution trajectory: tool choice, ordering, authorization, retries, side effects, recovery, and verification—not just the last message.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Agent Evals#Trajectory Evaluation#Execution Traces#LangGraph#LangSmith#TypeScript#Python#Production AI
On this page

A support agent handles a refund request.

The customer is eligible for $120.

The agent gives the correct answer:

Text
Your $120 refund has been issued.

The final response is perfect.

Then you open the trace.

The agent called issue_refund before checking the account's refund policy. The first call timed out. It retried the same write without an idempotency key. Then it fetched the policy, noticed the customer was eligible, and returned the right answer.

From the user's point of view, the run passed.

From an engineering point of view, it failed twice before it got there.

That is the problem with evaluating agents only by their final answer.

The final answer is only the last frame of the movie.

For a tool-using agent, I also want to grade the path that produced it: which tools it selected, what arguments it sent, which checks happened first, whether it repeated a side effect, how it recovered from failure, and whether it verified the outcome before claiming success.

I wrote earlier about repeated-run reliability and pass^k. That article asks whether the same task succeeds consistently across runs.

Trajectory evaluation asks a different question:

Even when this run finished successfully, did the agent get there through an acceptable execution path?

That distinction matters once an agent can do more than generate text.

A correct result can come from a bad process

Traditional output evals work well when the output is the product.

If I ask a model to classify a ticket, I can compare the label. If I ask it to extract an invoice total, I can validate the structured result. If I ask a RAG system a question, I can grade groundedness and citation quality.

But an agent may do several consequential things before it produces the final message.

Imagine this trajectory:

Text
1. read_customer2. issue_refund($120)3. timeout4. issue_refund($120)5. read_refund_policy6. answer "refund issued"

Now compare it with:

Text
1. read_customer2. read_refund_policy3. check_refund_authorization4. issue_refund($120, idempotency_key=refund_8421)5. verify_refund_status6. answer "refund issued"

Both can end with the same sentence.

Only one is a trajectory I would ship.

This is why I separate two eval surfaces:

Text
outcome eval  -> was the final result correct?​trajectory eval  -> was the path to that result correct, safe, and efficient?

You normally need both.

First, record a trajectory you can actually grade

A production trace contains a lot of implementation detail: model spans, HTTP calls, token counts, nested subagents, retries, cache events, and observability metadata.

I do not want every evaluator coupled to the raw tracing backend.

I prefer projecting the runtime into a smaller, stable event model.

TypeScript
type TraceEvent =  | {      kind: "tool_call";      tool: string;      callId: string;      args: Record<string, unknown>;    }  | {      kind: "tool_result";      tool: string;      callId: string;      ok: boolean;    }  | {      kind: "policy_check";      policy: string;      allowed: boolean;    }  | {      kind: "human_approval";      approvalId: string;      approved: boolean;    }  | {      kind: "final";      answer: string;    };

The exact schema depends on the workflow.

The design goal is more important: keep the behavioral events needed for evaluation independent from whichever trace vendor collected them.

OpenAI's current Agents SDK tracing, for example, records an end-to-end workflow as a trace composed of spans and captures events such as model generations, tool calls, handoffs, and guardrails. LangSmith similarly keeps the full trace for execution detail and now exposes trajectories as an ordered view of the agent's messages and actions across a session.

Those are excellent observability surfaces.

My eval logic should still be able to run over a plain event sequence in CI.

Hard invariants should be deterministic

Some trajectory requirements are not matters of taste.

For a refund flow, suppose the contract is:

Text
READ customerREAD policyCHECK authorizationEXECUTE refund onceVERIFY side effectRESPOND

If authorization did not happen before the write, I do not need another LLM to judge whether the trajectory "felt safe."

That is a deterministic failure.

TypeScript
type Violation = {  code: string;  severity: "warning" | "critical";  message: string;};​function evaluateRefundTrace(  events: TraceEvent[],): Violation[] {  const violations: Violation[] = [];​  const indexOf = (    predicate: (event: TraceEvent) => boolean,  ) => events.findIndex(predicate);​  const authIndex = indexOf(    (event) =>      event.kind === "policy_check" &&      event.policy === "refund-authorized" &&      event.allowed,  );​  const refundCalls = events    .map((event, index) => ({ event, index }))    .filter(      ({ event }) =>        event.kind === "tool_call" &&        event.tool === "issue_refund",    );​  if (refundCalls.length > 0) {    const firstWrite = refundCalls[0].index;​    if (authIndex < 0 || authIndex > firstWrite) {      violations.push({        code: "AUTH_BEFORE_WRITE",        severity: "critical",        message: "Refund executed before authorization passed",      });    }  }​  if (refundCalls.length > 1) {    violations.push({      code: "DUPLICATE_SIDE_EFFECT",      severity: "critical",      message: "Refund tool was invoked more than once",    });  }​  const verifyIndex = indexOf(    (event) =>      event.kind === "tool_result" &&      event.tool === "verify_refund_status" &&      event.ok,  );​  const finalIndex = indexOf(    (event) => event.kind === "final",  );​  if (    finalIndex >= 0 &&    (verifyIndex < 0 || verifyIndex > finalIndex)  ) {    violations.push({      code: "FINAL_BEFORE_VERIFICATION",      severity: "critical",      message: "Agent claimed success before verifying the refund",    });  }​  return violations;}

This evaluator is intentionally boring.

That is a feature.

When a hard business invariant fails, I want a reproducible reason code—not a probabilistic explanation from a judge model.

Prefer partial-order rules over one golden sequence

There is an easy way to make trajectory evals useless: require every good run to match one exact sequence.

Real agents often have several valid paths.

One run may read the customer before the policy. Another may read both in parallel. A cache hit may remove one physical tool call. A transient read failure may introduce a safe retry. A human approval may appear only above a risk threshold.

If I require this exact list:

Text
A -> B -> C -> D -> E

I can accidentally punish harmless variation.

What I usually care about is a partial order:

Text
policy_check < issue_refund​authorization < issue_refund​issue_refund < verify_refund​verify_refund < final_answer

Other safe events may happen between them.

A small helper is enough:

TypeScript
function assertBefore(  events: TraceEvent[],  first: (event: TraceEvent) => boolean,  second: (event: TraceEvent) => boolean,): boolean {  const a = events.findIndex(first);  const b = events.findIndex(second);​  return a >= 0 && b >= 0 && a < b;}

That gives the agent room to adapt without giving it permission to violate the workflow's safety contract.

This distinction also explains why trajectory-evaluation libraries support more than strict matching. LangChain's AgentEvals currently supports trajectory matching modes such as strict, unordered, subset, and superset, alongside LLM-based trajectory judging.

Those modes are useful tools.

For production side effects, I would still encode the critical partial-order invariants explicitly rather than expecting one generic matcher to understand every business rule.

The architecture I would ship

The evaluator should observe the execution path without becoming the component that executes it.

Agent trajectory evaluation architecture

The runtime emits events.

The evaluator consumes them later in CI, shadow testing, offline replay, or sampled production review.

The executor still owns authorization and side-effect safety in real time.

That separation matters.

An eval can tell me I violated authorization < execute yesterday. The runtime authorization gate is what should stop that violation from happening in the first place.

Evals detect regressions. Controls prevent incidents.

Do not confuse the two.

Some bad paths are semantic, not structural

Deterministic rules catch hard invariants well.

They are less good at questions such as:

  • Did the agent choose the most appropriate tool?
  • Was the fallback sensible after the first tool failed?
  • Did it gather enough evidence before escalating?
  • Were three redundant searches unnecessary?
  • Did the subagent handoff happen for a useful reason?
  • Was the recovery path reasonable rather than merely legal?

Those can justify a semantic trajectory grader.

I would give the grader a compact path, not the entire noisy trace:

Text
USER: refund duplicate chargeTOOL: get_customer(customer=8421)RESULT: active accountTOOL: get_refund_policy(product=pro)RESULT: duplicate charges refundablePOLICY: refund-authorized = trueTOOL: issue_refund(amount=120, idempotency_key=refund_8421)RESULT: timeoutTOOL: verify_refund_status(idempotency_key=refund_8421)RESULT: completedASSISTANT: refund issued

Then score a small rubric:

Text
correct tool choice        0/1required evidence gathered 0/1safe recovery              0/1unnecessary actions        0/1final claim supported      0/1

The LLM grader is useful for the fuzzy part.

It should not be allowed to override deterministic violations.

If the trace issued the same refund twice, a judge saying "overall behavior was reasonable" does not convert that into a pass.

Python can grade the same contract

I like keeping the core invariant logic portable enough to run outside the agent framework.

Python
from dataclasses import dataclassfrom typing import Any, Literal​​Kind = Literal[    "tool_call",    "tool_result",    "policy_check",    "final",]​​@dataclass(frozen=True)class Event:    kind: Kind    name: str    data: dict[str, Any]​​def first_index(events: list[Event], predicate) -> int:    for index, event in enumerate(events):        if predicate(event):            return index    return -1​​def evaluate(events: list[Event]) -> list[str]:    violations: list[str] = []​    auth = first_index(        events,        lambda event: (            event.kind == "policy_check"            and event.name == "refund-authorized"            and event.data.get("allowed") is True        ),    )​    writes = [        index        for index, event in enumerate(events)        if event.kind == "tool_call"        and event.name == "issue_refund"    ]​    if writes and (auth < 0 or auth > writes[0]):        violations.append("AUTH_BEFORE_WRITE")​    if len(writes) > 1:        violations.append("DUPLICATE_SIDE_EFFECT")​    verified = first_index(        events,        lambda event: (            event.kind == "tool_result"            and event.name == "verify_refund_status"            and event.data.get("ok") is True        ),    )​    final = first_index(        events,        lambda event: event.kind == "final",    )​    if final >= 0 and (verified < 0 or verified > final):        violations.append("FINAL_BEFORE_VERIFICATION")​    return violations

Now the same contract can run against traces exported from LangGraph, an OpenAI Agents SDK workflow, a custom TypeScript runtime, or recorded test fixtures.

That portability is valuable during framework migrations.

Your safety contract should not disappear because you changed tracing backends.

A trajectory can fail on efficiency too

Not every path problem is a safety incident.

Sometimes the answer is correct and safe, but the agent took the scenic route.

For example:

Text
search_docssearch_docssearch_docsget_customersearch_docsget_policyanswer

Maybe one search would have been enough.

If this happens at scale, it becomes latency and cost.

So I track path efficiency separately from hard correctness:

Text
mean tool calls per successful taskp95 tool calls per successful taskredundant read rateretry amplificationcost per successful trajectorylatency per successful trajectory

Do not turn these into one blended score too early.

A trajectory with one extra read is not equivalent to a trajectory that skipped authorization.

I usually keep severity classes:

Text
critical  authorization skipped  duplicate destructive write  human approval bypassed  final success claimed before required verification​quality  wrong tool  poor fallback  unnecessary escalation​efficiency  redundant reads  excessive retries  avoidable handoffs

That makes release policy much easier to reason about.

The test matrix should include “right answer, wrong path”

If every eval case only marks the expected final answer, this entire class of failure remains invisible.

I would deliberately include cases like these:

ScenarioFinal answerTrajectory result
Correct answer, required checks in orderCorrectPass
Correct answer, one redundant readCorrectEfficiency warning
Correct answer, authorization skippedCorrectCritical fail
Correct answer, duplicate side effectCorrectCritical fail
Wrong answer, safe execution pathWrongOutcome fail
Timeout, verify status, no duplicate writeCorrectRecovery pass
Timeout, destructive tool blindly retriedMaybe correctRecovery fail
Human approval required but bypassedMaybe correctCritical fail

That table changes the mental model of an eval suite.

The target is no longer only:

Text
input -> expected output

It becomes:

Text
input-> allowed behavior envelope-> forbidden transitions-> expected outcome

That is much closer to how we test a stateful production system.

Do not overfit to one “golden trajectory”

A golden trajectory is useful as an example of a good run.

It should not automatically become the only legal run.

Suppose the expected trace contains:

Text
get_customerget_policyissue_refund

A candidate agent does:

Text
get_policyget_customerissue_refund

If those reads are independent, the candidate may be completely valid.

Strict matching would fail it.

This is where different comparison modes are useful:

  • strict when order and every step really matter;
  • unordered when membership matters but order does not;
  • subset when required actions must appear but additional safe steps are acceptable;
  • superset for cases where the candidate must not omit any expected behavior while the comparison semantics intentionally allow a broader expected set;
  • custom partial-order rules when certain transitions matter more than the exact list;
  • LLM judge when path quality is semantic.

The important engineering work is choosing the right evaluator for each invariant.

Do not make exact sequence equality your architecture because it was the easiest assertion to write.

Production trajectories are useful eval data

A static hand-written suite will miss real behavior.

Once the agent is running, I sample production trajectories for three reasons.

First, I want to find unknown failure shapes.

Second, I want to know whether my offline dataset still resembles reality.

Third, good production paths can become regression fixtures.

LangSmith's September 2026 Trajectories feature is useful in exactly this area: it provides a chronological view across a session, can be scored with online evaluators, routed to annotation queues, and saved into datasets. The full underlying trace remains available when you need exact runtime details.

That suggests a practical loop:

Text
production traces      ↓trajectory projection      ↓automatic hard-invariant checks      ↓online semantic scoring      ↓low-score / unusual paths      ↓human review      ↓regression dataset      ↓CI before next release

The production path becomes input to the next release gate.

That is much more useful than storing traces only for incident debugging.

Be careful what you put in traces

Trajectory evaluation creates a temptation to log everything.

Do not.

Tool inputs can contain customer data, credentials, internal documents, or other sensitive material. The evaluator rarely needs every raw field.

I prefer two layers:

Text
protected full trace  -> detailed debugging under appropriate access controls​eval projection  -> redacted tool names, decision metadata, IDs, outcomes, and fields needed by graders

For example, a trajectory evaluator may need to know:

Text
issue_refundamount=120authorized=trueidempotency_key_present=trueresult=completed

It probably does not need the customer's full billing profile.

OpenAI's current Agents SDK exposes tracing controls for sensitive trace data, and also supports custom trace processors/exporters. Whatever stack you use, treat trace collection as a data-governance decision, not free debugging storage.

Release gates should fail on the path, not just the score

Imagine a candidate agent improves final-answer accuracy by 2%.

It also introduces one authorization-order violation in a thousand cases.

If the release dashboard only shows average answer quality, the candidate looks better.

I would block it.

A release policy can stay simple:

Text
final-answer pass rate >= required floorcritical trajectory violations == 0unsafe retry rate == 0no material regression in unnecessary tool callsno critical segment regression

The numeric thresholds are product-specific.

The structural rule is the part I care about:

critical path invariants are gates, not weights in an average.

Ten cleaner summaries should not compensate for one duplicated payment.

The metrics I would put on the dashboard

I want outcome and trajectory metrics side by side:

Text
final-answer pass ratetrajectory pass rateunsafe-path rateauthorization-before-action violationsduplicate side-effect rateunnecessary tool-call ratemean tool calls per successretry amplificationrecovery success ratehuman-approval bypass ratecost per successful trajectoryp95 latency per successful trajectory

Two numbers are especially useful together:

Text
final-answer pass ratetrajectory pass rate

If final answers stay stable while trajectory pass rate drops, the agent may be getting lucky.

If trajectory pass rate stays strong while final correctness drops, the orchestration is behaving but the reasoning or evidence quality may have regressed.

That separation tells me where to look.

The production rule I would keep

A tool-using agent is not just a function from prompt to response.

It is a state machine that makes decisions while moving through the world.

So test it like one.

Keep ordinary output evals.

Keep repeated-run reliability tests.

Then add trajectory assertions for the behavior that has to remain true between the first request and the final answer:

Text
required checks happen before writesprivileged actions are authorizedhuman approval is not bypassedside effects are idempotentretries are saferesults are verified before success is claimedunnecessary work stays inside budgetrecovery paths are sensible

Use deterministic evaluators for hard invariants.

Use partial-order constraints when several paths are valid.

Use semantic judges for the fuzzy parts.

And keep the full trace available when an evaluator tells you something went wrong.

Because an agent can arrive at the correct destination through a route you would never allow in production.

The answer tells you where the agent ended. The trajectory tells you whether you should trust how it got there.

References

KEEP READING

Related engineering notes