10A.12 Evaluating Multi-Agent Systems and Validating User Simulators

ProductionLesson 12 of 1228,007 words9 parts
Module 10A · 0 of 12 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12

A multi-agent system can pass every per-agent test and still fail its users, because most of its failures live between the agents: a triage agent hands a refund to the wrong specialist, a summary drops the order number on the way, a worker's wrong figure sails past a verifier that only checks the format, and the whole run costs four times what one agent would have. The same lesson applies to the other instrument this lesson covers. Conversational agents are increasingly scored against user simulators (a second model playing the customer), and an agent's score under simulation is only as trustworthy as the simulator. 08D.3 taught how to build multi-agent systems and explicitly left "the formal metrics" to this module; 10A.7 built the single-agent harness and named simulator pitfalls in one bullet list. This lesson goes the rest of the way: how to grade handoffs, how to find which agent caused a failure, how to measure what the orchestration costs, how to compare honestly against one agent, and how to prove a user simulator measures what you think it measures. The running code is two new stdlib files, evalkit/mas_eval.py and evalkit/sim_validation.py, so everything runs with no API keys, and every output below was actually computed by that code, on synthetic fixtures with planted faults; no number in this lesson's outputs describes a real system or real users.

What you'll learn

  • Why a multi-agent system needs a fourth evaluation level, interaction, on top of system, agent and trajectory checks, and how the MAST failure taxonomy turns failed traces into countable categories
  • What a multi-agent trace must record before any of this works, and how to convert 08D.3's event log and 11A.1's JSONL spans into a per-agent trace without losing who did what
  • Handoff correctness in full: routing as a confusion matrix that includes "should not hand off" and "escalate to a human", handoff timing, context-transfer completeness graded on what the receiving agent actually saw, delegation-brief checks, ping-pong and longer loops, return paths and human escalation
  • Per-agent failure attribution: blame versus root cause, what the research says about LLM judges as attributors (the Who&When numbers and the 2025–2026 follow-ups), counterfactual replay, whether a fix is sufficient or necessary for success (and why the words flip when you talk about the fault), ablation and Shapley credit, and how to validate an attributor against human labels and trivial baselines
  • Orchestration overhead: the token multiplier, coordination versus work tokens, critical path versus total compute, effective parallelism and the latency speed-up over a single agent, redundancy across agents, recovery overhead, cost per successful task, all as p50/p95 distributions computed from traces
  • The single-agent baseline: equal-budget comparisons, stronger baselines (self-consistency, majority vote), the ablation ladder, paired statistics, slices by task structure, the Pareto view, and what the controlled studies found
  • Validating user simulators: realism against real transcripts with a noise floor, discriminability, goal and persona fidelity, leakage with unhelpful-user and no-user controls, termination, the sim-to-real gap, and the decisive test, predictive validity, plus panels, versioning and how many human conversations you need
  • The benchmarks, datasets and tools in this space as of November 2026, and what each one does and does not check

What you don't need

  • API keys. mas_eval.py, sim_validation.py and their demos are pure standard library and run against scripted systems and synthetic conversations. The one adapter that would wrap a live system is marked illustrative.
  • How to build a multi-agent system. Architectures, delegation prompts, artefact stores and the orchestrator–subagent build are 08D.3; this lesson assumes you have one, or a trace of one.
  • How simulators generate conversations. Personas, the two-model loop and the simulator's own failure table are 10A.2, Part 13; this lesson owns validating them.
  • Judge validation, paired statistics and the single-agent harness. They are 10A.5, 10A.8 and 10A.7; this lesson reuses their code by name and does not repeat it.

Setup

The samples need only Python 3.11+: no packages, no keys.

bash
uv init evalkit --bare --python 3.13 && cd evalkit   # first time only; skip if you did 10A.1
mkdir -p evalkit                                      # the package directory

This lesson adds four files to the evalkit package, beside agent_eval.py, compare.py and judge_validation.py inside the package directory: mas_eval.py (the multi-agent graders), mas_eval_demo.py (two fixtures with planted faults), sim_validation.py (the simulator checks) and sim_validation_demo.py (three simulators against a set of stand-in "real" conversations). They import their siblings flat (from agent_eval import ...), exactly like 10A.7's demo, so run them from inside the package directory or by path: python3 evalkit/mas_eval_demo.py handoffs. They need agent_eval.py from 10A.7, 2.4, compare.py from 10A.8, 4.1 and judge_validation.py from 10A.5, Part 10; 10A.10's Appendix A shows the whole tree. mas_eval.py and mas_eval_demo.py are printed in five sections and sim_validation.py in three, each where its topic is taught; each section's first lines say which file it belongs to, and pasting the sections in order gives the complete file that produced every output in this lesson.


What you must be able to do after this lesson#

  • Explain the interaction level of evaluation for multi-agent systems
  • Record a per-agent trace that shows who did what
  • Score handoffs with a routing confusion matrix and a context-transfer check
  • Separate blame from root cause when attributing a failure to an agent
  • Measure orchestration overhead such as the token multiplier
  • Compare a multi-agent system with an equal-budget single-agent baseline
  • Validate a user simulator against real transcripts

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Every agent passes its own tests, so why does the system fail?" 1.2 Four levels of evaluation
"Which of the seven agents broke this run?" Part 4: Per-agent failure attribution
"Just ask an LLM to read the trace and find the bad step." 4.2 What the research says
"The specialist keeps asking the customer for the order number again." 3.4 Context transfer
"The bots keep passing the ticket back and forth." 3.6 Loops and ping-pong
"Our multi-agent version beat the single agent by 30%." Part 6: The single-agent baseline
"Multi-agent is faster because it runs in parallel." 5.4 Critical path, total compute and speed-up
"What does the orchestration actually cost us?" Part 5: Orchestration overhead
"The simulator says the new agent is better. Ship it?" 7.12 Predictive validity
"Our agent scores 85% with simulated users." 7.11 The sim-to-real gap
"The simulated users sound realistic to me." 7.5 Realism and 7.6 Discriminability
"The provider updated the model behind our simulator; do we care?" 7.14 Panels, versioning and drift

Part 1: Why multi-agent systems need their own evaluation layer#

1.1 What changes when there is more than one agent#

A multi-agent system (MAS) is any system in which more than one model-driven agent works on the same task: an orchestrator and its subagents, a triage agent and specialists that take over the conversation, a generator and a critic, a debate, a pipeline of agents (08D.3, Part 2 catalogues them). Everything 10A.7 taught still applies to each agent and to the system's end state. Three things are new.

  1. Failures live on the edges. Information crosses an agent boundary as a handoff payload, a delegation brief or a returned result. Each crossing can lose a field, distort a value, go to the wrong agent, arrive at the wrong moment or never come back. A per-agent test fed a perfect input cannot see any of this, because the bug is in the input it never receives.
  2. Blame becomes a question. When a single agent fails, its trajectory is the place to look. When seven agents fail together, the agent whose output was visibly wrong (usually the last one) is often not the one that caused the failure. Finding the cause is a measurement problem with its own methods and its own error rate.
  3. Cost and latency are properties of the organisation. The token bill multiplies across agents, coordination tokens compete with work tokens, and wall-clock depends on the slowest branch of a fan-out, not the sum of all branches. None of this is visible from one agent's trajectory.

1.2 Four levels of evaluation: system, agent, interaction, organisation#

10A.7's four levels (outcome, trajectory, step, safety) still grade one agent's run. A multi-agent system adds a second axis: whose behaviour you are grading.

Level Unit graded Example metrics Owned by
System One task run, end to end Success, pass^k, end-state checks, cost and latency per task 10A.7 (run_agent_suite, pass_hat_k)
Agent One agent's sub-run, given a brief Worker correctness on a canned brief, its tool precision/recall, its budget adherence 10A.7's graders applied per agent (2.2 shows how)
Interaction An edge: a handoff, delegation, return or message Routing accuracy, timing, context-transfer completeness, loops, dropped results, escalation This lesson, Part 3
Organisation The team's behaviour as a whole Overhead, redundancy, termination, verification coverage, the comparison with one agent This lesson, Parts 4 to 6
flowchart TB
    subgraph sys ["System level: did the task succeed, at what cost?"]
        direction LR
        O["Orchestrator"] -->|"brief"| W1["Worker 1"]
        O -->|"brief"| W2["Worker 2"]
        W1 -->|"result"| V["Verifier"]
        W2 -->|"result"| V
        V -->|"verified findings"| S["Synthesiser"]
    end
    A["Agent level:<br/>each node on a canned input"] -.-> W1
    I["Interaction level:<br/>each arrow - right target, right time,<br/>complete payload, came back, was used"] -.-> V
    G["Organisation level:<br/>overhead, redundancy, attribution,<br/>versus one agent at equal budget"] -.-> sys

The rule that follows from the table: a multi-agent eval suite that grades only the system level tells you that it fails, a suite that adds the agent level tells you which components are weak in isolation, and only the interaction and organisation levels tell you why the team fails and whether the team was worth building.

1.3 How multi-agent systems fail: MAST as a labelling codebook#

The most useful published study of how multi-agent systems fail is MAST, the Multi-Agent System failure Taxonomy, from "Why Do Multi-Agent LLM Systems Fail?" (Cemri et al., UC Berkeley and collaborators; arXiv 2503.13657, first posted March 2025, version 3 October 2025; a NeurIPS 2025 spotlight poster). 08D.3, 1.4 introduced it; here is what an evaluator needs from it.

The authors built the taxonomy from 150+ traces with six experts, reached inter-annotator agreement of Cohen's kappa 0.88, then annotated 1,642 traces from seven frameworks (MetaGPT, ChatDev, HyperAgent, AppWorld, AG2/MathChat, Magentic-One, OpenManus) running GPT-4-family, Claude 3.7 Sonnet, Qwen2.5-Coder-32B-Instruct and CodeLlama-7b models. The result is 14 failure modes in three categories. The prevalences below are from version 3 of the paper (share of failure annotations in MAST-Data):

Category Mode Prevalence (v3)
FC1 System design FM-1.1 Disobey task specification 11.8%
FM-1.2 Disobey role specification 1.5%
FM-1.3 Step repetition 15.7%
FM-1.4 Loss of conversation history 2.80%
FM-1.5 Unaware of termination conditions 12.4%
FC2 Inter-agent misalignment FM-2.1 Conversation reset 2.20%
FM-2.2 Fail to ask for clarification 6.80%
FM-2.3 Task derailment 7.40%
FM-2.4 Information withholding 0.85%
FM-2.5 Ignored other agent's input 1.90%
FM-2.6 Reasoning-action mismatch 13.2%
FC3 Task verification FM-3.1 Premature termination 6.20%
FM-3.2 No or incomplete verification 8.20%
FM-3.3 Incorrect verification 9.10%

Four things to take from it as an evaluator:

  • Use it as a codebook, not a leaderboard. When you read failed traces (10A.1's error analysis), label each with a MAST code (plus your own codes for anything MAST does not cover, such as a plain factual error by one worker). Counting codes tells you whether to invest in role specs, handoff contracts or verification. Part 4 adds which agent to which mode.
  • Most modes are organisational. Step repetition, ignoring termination conditions, derailment and verification gaps are design and coordination failures. A stronger model fixes some of them; a better handoff contract, a termination rule or a real verifier fixes more. The authors' own interventions on ChatDev with GPT-4o show both the potential and the limit: an improved role specification and workflow raised task success by 9.4%, adding a high-level task-objective verification step raised it by 15.6% on their ProgramDev set, and they note that completion stayed low and "more sophisticated fixes" are needed.
  • The LLM annotator is a judge, so 10A.5 applies. MAST ships an LLM annotator (OpenAI o1, few-shot) that agreed with humans at accuracy 0.94, recall 0.77, precision 0.833, F1 0.80 and kappa 0.77; zero-shot, kappa fell to 0.58. A kappa of 0.77 is good for counting modes across hundreds of traces and not good enough to label any single trace without review: exactly 10A.5, 3.11's distinction between aggregate and per-item use.
  • The percentages describe 2024–2025 frameworks and models. Treat them as a prior for what to look for, not as the distribution you will find. Your own labelled sample is the only distribution that matters for your system.

Newer taxonomies exist for agent traces in general. TRAIL (Patronus AI; arXiv 2505.08638) groups errors into reasoning, planning and execution errors, with 148 human-annotated traces from GAIA and SWE-Bench covering single- and multi-agent runs; its best model at publication, Gemini-2.5-pro, scored 11% at locating the errors. Use whichever codebook fits your failures, keep it versioned like a rubric, and measure inter-annotator agreement on it before you trust the counts.

1.4 Tracing is the prerequisite#

Every metric in Parts 3 to 6 is computed from a trace. If the trace does not say who handed what to whom, what the receiver actually saw and what came back, the interaction level is invisible and attribution becomes guesswork. 08D.3, 3.8 set the design rules and 11A.1, 2.4 owns span design; the evaluation requirements on top of them are:

The trace must record... ...because this metric needs it
A span per agent run, with the agent's name, nested under the system run Every per-agent metric; keeping agent identity when you convert spans
Each handoff, delegation and escalation as its own span with to, the turn, and the payload sent Routing confusion matrix, timing, ping-pong
The payload seen by the receiver, after any input filter or summary Context-transfer completeness (Part 3.4)
The delegation brief (or its hash plus a pointer to the text) Brief fidelity (Part 3.5)
Each returned result, linked to its delegation, with status, ids of artefacts and sources, and protocol state Return path: orphaned, non-terminal and dropped results (Part 3.7)
Each agent's inputs and context, not only its outputs Attribution: a judge or a human cannot locate a cause it cannot see
A role tag on every model call: work or coordination Coordination ratio (Part 5.3)
Tokens, cost, start and end time per span Token multiplier, critical path, cost per success (Part 5)
A replayable record of every model call (10A.8's CallCache) Counterfactual replay (Part 4.4)

The inputs row is not a nicety. TraceElephant ("Seeing the Whole Elephant", arXiv 2604.22708, accepted at ACL 2026) built an attribution benchmark with full execution traces and reproducible environments and found that giving attributors the agents' inputs and context, not only their outputs, improved attribution accuracy by up to 76% over partial observation.

What the frameworks give you for free, as of November 2026:

  • OpenAI Agents SDK tracing emits a handoff_span for each handoff, whose data (HandoffSpanData) carries exactly from_agent and to_agent, alongside agent_span, generation_span, function_span and guardrail_span (tracing docs, span data reference). That is the routing confusion matrix's raw material. It does not record what an input filter removed, so log the post-filter payload yourself.
  • OpenTelemetry GenAI conventions (status: Development; maintained in semantic-conventions-genai, see 11A.1, 3.2) define invoke_agent spans when an LLM drives control flow, invoke_workflow when the application does, and agent attributes such as gen_ai.agent.name, which must be low cardinality. Their guidance "Do not combine tool lists across child agents, handoffs, or steps" is the same per-agent discipline this lesson needs.
  • 10A.7's trace adapter flattens the tree. 10A.7, 10.4's trajectories_from_spans builds one Trajectory per trace, which is right for a single agent and loses agent identity for many. Part 2's trace_from_spans keeps it.

1.5 What earlier lessons covered, and what this lesson adds#

Topic Already covered (link, not repeated) Added here
Architectures, the four taxes, field data 08D.3, Parts 1–2 The metrics that measure each tax
Handoff mechanics and their failure modes 08D.3, 2.2 Graders for routing, timing, transfer, loops, return path, escalation
Error topology, typed boundaries 08D.3, 3.6 Attribution methods and how to validate them
Cost accounting rules ("match total tokens") 08D.3, 3.7 Overhead metrics, equal-budget protocol, Pareto
The eval ladder and Anthropic's eval advice 08D.3, 3.9 Code for every rung, extended in 9.2
Single-agent harness, pass^k, trace grading 10A.7 Per-agent trajectories, interaction graders
Simulator mechanics and their failure table 10A.2, Part 13, 10A.6, 6.3, 10A.7, 6.1 Seven validity checks with metrics and code
Judges as instruments; paired statistics 10A.5, 10A.8 The same logic applied to attributors and simulators
Offline-to-online alignment; simulator probes 10A.9, 1.3, 10A.9, 3.5 Predictive validity of a simulator
Memory and multi-session evaluation 10A.11 (10A.11 uses simulators to drive sessions; this lesson is where you validate them)

Part 2: The multi-agent trace#

2.1 The schema: AgentSpan and MASTrace#

Everything in mas_eval.py reads one data structure. An AgentSpan is one unit of work or communication owned by one agent: an agent run, a model call, a tool call, a handoff, a delegation, a returned result, a decision. A MASTrace is one run of the system on one task: a list of spans that forms a tree through parent_id, plus the final answer and whether the run succeeded.

Five fields carry most of the weight:

  • agent: who owns the span. Every per-agent number is a group-by on this field.
  • kind: what the span is. Handoffs and escalations move control (TRANSFER_KINDS); delegations are calls that should come back; returns close a delegation.
  • role: "work" or "coordination". Planning, briefs, routing, verification and synthesis re-reads are coordination; searching, reading and acting are work. You set the tag when you instrument, because no code can infer it reliably afterwards, and you publish the policy with any coordination ratio you report.
  • attrs: the payloads. For a handoff: to, turn, payload_sent and payload_seen. For a return: of (the delegation's span id), artefacts, sources and an A2A-style state. For an agent run in a replayable system: step (its global output index), input and output.
  • status: the 08D.3 status vocabulary (ok | partial | error | timeout | budget_exhausted | cancelled), so error handling is countable.

MASTrace.route() returns the active-agent sequence (the entry agent, then the target of every control transfer), which is what ping-pong detection reads. tokens(role=...) and cost() roll up the tree.

2.2 Adapters: from event logs and JSONL spans#

You will rarely write AgentSpans by hand; your system already logs something. Two adapters cover the formats this path uses:

  • trace_from_events reads 08D.3's TraceEvent log (trace_id, parent_id, agent, kind, detail, ts; pass dataclasses.asdict(e) for each event). 08D.3 gives every agent run its own trace_id and points children at it with parent_id, so an agent_start/agent_end pair becomes one agent_run span, model_call events keep their token counts, and delegation events keep the target agent and status. 08D.3 logs each delegation once, after the worker returns, with the worker's status; the adapter therefore emits a paired return span for every delegation (status ok or partial maps to the A2A state TASK_STATE_COMPLETED, errors, timeouts and exhausted budgets to TASK_STATE_FAILED), otherwise 3.7's return-path check would call every delegation orphaned. Three honest limits remain: TraceEvent carries a timestamp but no duration, so model and tool calls become zero-length spans (critical-path numbers then come from the agent runs); 08D.3 logs the brief's hash, not what the worker saw, so context-transfer grading needs the extra logging from 1.4; and 08D.3 logs a worker's sources as a count, so checking for dropped results needs the source and artefact ids logged too. The lead's model calls are tagged coordination by default (coordination_agents={"lead"}); change the set to match your own policy.
  • trace_from_spans reads 11A.1's JSONL records (an envelope of trace_id, span_id, parent_span_id, kind, start_ms, duration_ms, status, plus attrs; 11A.1, 2.6). It takes the agent from attrs["gen_ai.agent.name"] (the OpenTelemetry attribute) or attrs["agent"], and inherits it from the parent span when a child does not repeat it, which is how a model call inside an agent run stays that agent's. Handoff targets come from attrs["handoff.to"]. Unlike 10A.7's trajectories_from_spans, it never merges agents into one trajectory.

Then to_trajectories(trace) goes the other way: it builds one 10A.7 Trajectory per agent, so every 10A.7 metric (tool_call_prf, redundant_calls, loop_detected, within_budget's inputs) runs per agent without new code. That is the agent level of 1.2 for free.

2.3 Gold annotations for multi-agent tasks#

The interaction graders compare a trace with a gold annotation: what a careful human says should have happened at each decision point. Two dataclasses hold it.

  • HandoffGold, one per decision point: expected (a tuple of acceptable targets, primary first, including NONE when the right move is not to hand off and HUMAN when it is to escalate), source (the agent that decides), window (the earliest and latest acceptable turn) and required (the fields, with their gold values, that must reach the receiver).
  • MASTaskGold, one per task: its decision points, should_escalate, source_facts (what the sender legitimately knew, for catching invented fields), decisive (the agent and step that caused a failure, for failed fixtures) and a slice.

How to annotate well, in the order that pays off:

  1. Write the acceptable set, not one label. A refund question about a damaged item may be correctly handled by returns or by billing under your policy. A single gold label turns a policy ambiguity into a false error.
  2. Always include NONE decision points. If no task in the suite should stay with the first agent, you cannot see unnecessary handoffs, which are a cost and latency problem even when the final answer is right.
  3. Annotate the window from the information, not the clock. The earliest acceptable turn is the first turn at which the receiver's required fields are available (the order number, the device model); the latest is your policy's patience.
  4. List required fields the receiver cannot work without, with their values. "Order id and amount" is checkable; "enough context" is not.
  5. Double-annotate a sample. Have two people label 30–50 tasks independently and compute Cohen's kappa on the routing labels with 10A.5's cohens_kappa. If the annotators disagree, your routing policy is ambiguous, and the agent cannot be graded fairly against it until you fix the policy.

The alignment rule (_aligned) is deliberately simple: decision point i is matched with the i-th transfer made by its source agent. That fits routers and triage flows. For free-form conversations where a handoff can happen at any turn, annotate the turn and align by turn instead.

2.4 mas_eval.py, section 1: the trace, adapters and gold types#

python
"""evalkit/mas_eval.py — evaluate multi-agent systems.

Stdlib only. Lesson 10A.12 adds this file to the evalkit package. It covers
the four things a single-agent harness (agent_eval.py, 10A.7) cannot see:

  * the multi-agent trace      AgentSpan / MASTrace, adapters from 08D.3's
                               TraceEvent log and 11A.1's JSONL spans, and
                               to_trajectories() so every 10A.7 grader runs
                               per agent
  * handoff correctness        routing confusion matrix (with NONE and HUMAN),
                               timing, context transfer on what the receiver
                               actually saw, brief checklist, ping-pong,
                               return path, escalation
  * failure attribution        counterfactual replay over an injectable
                               SystemFn, ablation and Shapley credit, judge
                               strategies behind a seam, trivial baselines,
                               attributor accuracy
  * overhead and baselines     token multiplier, coordination ratio, critical
                               path, speed-up, redundancy, cost per success,
                               equal-budget check, paired comparison, Pareto

Every model call stays behind a seam (SystemFn, OracleFn, AttribJudge), so
the whole file runs with scripted fakes and no keys.
"""
from __future__ import annotations

import itertools
import math
import random
import statistics
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from typing import Any, Callable

from agent_eval import Grade, StepRecord, Trajectory, percentile, wilson_interval
from compare import (bootstrap_mean_ci, paired_bootstrap_ci, paired_diffs,
                     paired_effect_size, sign_flip_permutation_p)
from judge_validation import cohens_kappa, confusion_counts

NONE, HUMAN = "NONE", "HUMAN"              # "no handoff" and "escalate to a person"
TRANSFER_KINDS = ("handoff", "escalation")  # control moves to the target
MESSAGE_KINDS = ("handoff", "escalation", "delegation", "return")
A2A_TERMINAL = {"TASK_STATE_COMPLETED", "TASK_STATE_FAILED",
                "TASK_STATE_CANCELED", "TASK_STATE_REJECTED"}


# ---------------------------------------------------------------------------
# 1. The multi-agent trace
# ---------------------------------------------------------------------------

@dataclass
class AgentSpan:
    """One unit of work or communication, owned by one agent.

    kind: agent_run | model_call | tool_call | handoff | delegation |
          return | decision | escalation
    role: "work" or "coordination" — tag it when you instrument; the
          coordination ratio is only as honest as this tag.
    attrs carries the kind-specific payload:
      handoff/escalation/delegation: to, turn, payload_sent, payload_seen, brief
      return:     of (the delegation span_id), artefacts, sources, state
      tool_call:  tool, args or args_hash
      agent_run:  step (global output index), output, input
    """
    span_id: str
    parent_id: str | None
    agent: str
    kind: str
    start_s: float = 0.0
    end_s: float = 0.0
    role: str = "work"
    tokens_in: int = 0
    tokens_out: int = 0
    cost_usd: float = 0.0
    status: str = "ok"         # ok | partial | error | timeout | budget_exhausted | cancelled
    attrs: dict = field(default_factory=dict)

    @property
    def duration_s(self) -> float:
        return max(0.0, self.end_s - self.start_s)

    @property
    def tokens(self) -> int:
        return self.tokens_in + self.tokens_out


@dataclass
class MASTrace:
    """One run of a (multi-)agent system on one task: a tree of spans."""
    trace_id: str
    task_id: str
    system: str                       # "mas-v3", "sas-baseline", ...
    spans: list[AgentSpan] = field(default_factory=list)
    final_answer: str = ""
    success: bool | None = None
    status: str = "ok"                # run-level: ok | error | timeout | budget_exhausted

    def agents(self) -> list[str]:
        seen: dict[str, None] = {}
        for s in self.spans:
            seen.setdefault(s.agent, None)
        return list(seen)

    def by_agent(self) -> dict[str, list[AgentSpan]]:
        out: dict[str, list[AgentSpan]] = defaultdict(list)
        for s in self.spans:
            out[s.agent].append(s)
        return dict(out)

    def children(self, span_id: str) -> list[AgentSpan]:
        return [s for s in self.spans if s.parent_id == span_id]

    def handoffs(self, kinds: tuple[str, ...] = ("handoff", "delegation",
                                                  "escalation")) -> list[AgentSpan]:
        return sorted((s for s in self.spans if s.kind in kinds),
                      key=lambda s: (s.attrs.get("turn", 0), s.start_s))

    def route(self) -> list[str]:
        """Active-agent sequence: entry agent, then each control transfer."""
        runs = sorted((s for s in self.spans if s.kind == "agent_run"),
                      key=lambda s: s.start_s)
        entry = runs[0].agent if runs else (self.spans[0].agent if self.spans else "")
        return [entry] + [h.attrs.get("to", "?") for h in self.handoffs(TRANSFER_KINDS)]

    def tokens(self, role: str | None = None) -> int:
        return sum(s.tokens for s in self.spans if role is None or s.role == role)

    def cost(self) -> float:
        return sum(s.cost_usd for s in self.spans)


def trace_from_events(events: list[dict], *, task_id: str, system: str,
                      coordination_agents: frozenset[str] = frozenset({"lead"})
                      ) -> MASTrace:
    """Build a MASTrace from 08D.3's TraceEvent log (dicts with trace_id,
    parent_id, agent, kind, detail, ts — use dataclasses.asdict on each).

    08D.3 gives every agent run its own trace_id and points children at it via
    parent_id, so an agent_start/agent_end pair becomes one agent_run span.
    TraceEvent has a timestamp but no duration, so model and tool calls get
    zero-length spans; critical-path numbers come from the agent_run spans.
    Model calls made by `coordination_agents` (the lead plans, delegates and
    synthesises) are tagged role="coordination" — a convention, so publish it.

    08D.3 emits ONE delegation event, after the worker has returned, carrying
    the worker's status. So each delegation also becomes a paired `return`
    span (state mapped to A2A terms) — without it, return_path() would call
    every delegation orphaned. 08D.3 logs `sources` as a count, not ids, so
    dropped-result checks need the ids logged as well.
    """
    spans: list[AgentSpan] = []
    open_runs: dict[str, AgentSpan] = {}
    root_id = ""
    for i, ev in enumerate(events):
        kind, d, ts = ev["kind"], ev.get("detail") or {}, float(ev["ts"])
        sid, parent, agent = ev["trace_id"], ev.get("parent_id"), ev["agent"]
        if kind == "system_run":
            root_id = sid
        elif kind == "agent_start":
            span = AgentSpan(sid, parent, agent, "agent_run", ts, ts,
                             attrs={"task": d.get("task", ""), "model": d.get("model")})
            open_runs[sid] = span
            spans.append(span)
        elif kind == "agent_end":
            span = open_runs.pop(sid, None)
            if span is not None:
                span.end_s, span.status = ts, d.get("status", "ok")
        elif kind == "model_call":
            spans.append(AgentSpan(
                f"{sid}:{i}", sid, agent, "model_call", ts, ts,
                role="coordination" if agent in coordination_agents else "work",
                tokens_in=int(d.get("input_tokens") or 0),
                tokens_out=int(d.get("output_tokens") or 0),
                attrs={"tool_calls": d.get("tool_calls", [])}))
        elif kind == "tool_call":
            spans.append(AgentSpan(
                f"{sid}:{i}", sid, agent, "tool_call", ts, ts,
                status="error" if d.get("is_error") else "ok",
                attrs={"tool": d.get("name", "?")}))
        elif kind == "delegation":
            did, status = f"{sid}:{i}", d.get("status", "ok")
            spans.append(AgentSpan(
                did, sid, agent, "delegation", ts, ts, role="coordination",
                status=status,
                attrs={"to": d.get("agent", "?"), "subtask": d.get("subtask"),
                       "brief_sha": d.get("brief_sha")}))
            spans.append(AgentSpan(
                f"{did}:ret", sid, d.get("agent", "?"), "return", ts, ts,
                role="coordination", status=status,
                attrs={"of": did, "state": _A2A_STATE.get(status, "TASK_STATE_FAILED"),
                       "sources_count": d.get("sources")}))
        elif kind in ("decision", "warning"):
            spans.append(AgentSpan(f"{sid}:{i}", sid, agent, kind, ts, ts,
                                   role="coordination", attrs=dict(d)))
    for span in open_runs.values():          # started, never ended: orphaned
        span.status = "orphaned"
    return MASTrace(trace_id=root_id or task_id, task_id=task_id,
                    system=system, spans=spans)


_A2A_STATE = {"ok": "TASK_STATE_COMPLETED", "partial": "TASK_STATE_COMPLETED",
              "error": "TASK_STATE_FAILED", "timeout": "TASK_STATE_FAILED",
              "budget_exhausted": "TASK_STATE_FAILED", "cancelled": "TASK_STATE_CANCELED"}

_KIND_MAP = {"llm": "model_call", "tool": "tool_call", "agent": "agent_run",
             "handoff": "handoff", "delegation": "delegation",
             "escalation": "escalation", "return": "return"}


def trace_from_spans(records: list[dict], *, system: str,
                     agent_keys: tuple[str, ...] = ("gen_ai.agent.name", "agent")
                     ) -> dict[str, MASTrace]:
    """Build MASTraces from 11A.1's JSONL span records (envelope + attrs).

    Unlike 10A.7's trajectories_from_spans(), which flattens a trace into one
    Trajectory, this keeps agent identity: a span's agent is the first of
    `agent_keys` found in attrs, else its parent's agent. Kinds map through
    _KIND_MAP; a span whose gen_ai.operation.name is invoke_agent counts as
    an agent_run. Handoff targets come from attrs["handoff.to"].
    """
    by_trace: dict[str, list[dict]] = defaultdict(list)
    for r in records:
        by_trace[r["trace_id"]].append(r)
    out: dict[str, MASTrace] = {}
    for tid, recs in by_trace.items():
        recs.sort(key=lambda r: r.get("start_ms", 0.0))     # parents start first
        agent_of: dict[str, str] = {}
        spans: list[AgentSpan] = []
        task_id = tid
        for r in recs:
            a = r.get("attrs") or {}
            task_id = a.get("task_id", task_id)
            agent = next((a[k] for k in agent_keys if a.get(k)), None) \
                or agent_of.get(r.get("parent_span_id") or "", "unknown")
            agent_of[r["span_id"]] = agent
            kind = _KIND_MAP.get(r.get("kind", ""), r.get("kind", "other"))
            if a.get("gen_ai.operation.name") == "invoke_agent":
                kind = "agent_run"
            attrs = dict(a)
            if "handoff.to" in a:
                attrs["to"] = a["handoff.to"]
            if "tool.name" in a:
                attrs["tool"] = a["tool.name"]
            if "tool.args_hash" in a:
                attrs["args_hash"] = a["tool.args_hash"]
            start = float(r.get("start_ms", 0.0)) / 1000
            spans.append(AgentSpan(
                r["span_id"], r.get("parent_span_id"), agent, kind,
                start, start + float(r.get("duration_ms", 0.0)) / 1000,
                role=a.get("role", "work"),
                tokens_in=int(a.get("total_input_tokens",
                                    a.get("gen_ai.usage.input_tokens", 0)) or 0),
                tokens_out=int(a.get("output_tokens",
                                     a.get("gen_ai.usage.output_tokens", 0)) or 0),
                cost_usd=float(a.get("cost_usd") or 0.0),
                status=r.get("status", "ok"), attrs=attrs))
        out[tid] = MASTrace(trace_id=tid, task_id=task_id, system=system, spans=spans)
    return out


def to_trajectories(trace: MASTrace) -> dict[str, Trajectory]:
    """One 10A.7 Trajectory per agent, so tool_call_prf, no_repeat_calls,
    loop_detected and within_budget run per agent with no new code."""
    out: dict[str, Trajectory] = {}
    for agent, spans in trace.by_agent().items():
        tools = [s for s in spans if s.kind == "tool_call"]
        steps = [StepRecord(seq=i, tool=s.attrs.get("tool", "?"),
                            args=s.attrs.get("args") or {"args_hash": s.attrs.get("args_hash")},
                            status=s.status if s.status in ("ok", "error", "denied") else "error",
                            latency_s=s.duration_s)
                 for i, s in enumerate(tools)]
        out[agent] = Trajectory(
            task_id=trace.task_id, agent=agent, steps=steps,
            wall_s=sum(s.duration_s for s in spans if s.kind == "agent_run"),
            tokens_in=sum(s.tokens_in for s in spans),
            tokens_out=sum(s.tokens_out for s in spans),
            cost_usd=sum(s.cost_usd for s in spans))
    return out


# ---------------------------------------------------------------------------
# 1b. Gold annotations for multi-agent tasks
# ---------------------------------------------------------------------------

@dataclass
class HandoffGold:
    """One decision point: where control should (or should not) move."""
    expected: tuple[str, ...]                  # acceptable targets, primary first;
                                               # include NONE / HUMAN where right
    source: str | None = None                  # agent that decides (None = any)
    window: tuple[int, int] | None = None      # earliest/latest acceptable turn
    required: dict = field(default_factory=dict)   # field -> gold value to transfer
    types: dict = field(default_factory=dict)      # field -> expected type (schema_valid)


@dataclass
class MASTaskGold:
    task_id: str
    handoffs: list[HandoffGold] = field(default_factory=list)
    should_escalate: bool = False
    source_facts: dict = field(default_factory=dict)   # facts the sender legitimately had
    decisive: tuple[str, int] | None = None            # (agent, step) for failed fixtures
    slice_: str = "all"


def _aligned(trace: MASTrace, gold: MASTaskGold) -> list[AgentSpan | None]:
    """Positional alignment: decision point i <-> the i-th transfer made by
    its source agent. Good for routers; for free-form chats annotate turns."""
    transfers = trace.handoffs(TRANSFER_KINDS)
    used: set[str] = set()
    out: list[AgentSpan | None] = []
    for g in gold.handoffs:
        match = next((h for h in transfers if h.span_id not in used
                      and (g.source is None or h.agent == g.source)), None)
        if match is not None:
            used.add(match.span_id)
        out.append(match)
    return out

2.5 The adapters on real logs#

The first section of the demo builds a tiny 08D.3-style event log (a lead plans, two workers search, the lead synthesises) and three 11A.1-style JSONL spans (triage hands off to billing), converts both, and runs a 10A.7 metric per agent:

python
"""mas_eval_demo.py — the fixtures behind lesson 10A.12's real output.

    python3 mas_eval_demo.py trace        # Part 2: adapters + per-agent trajectories
    python3 mas_eval_demo.py handoffs     # Part 3: support-desk swarm, planted faults
    python3 mas_eval_demo.py attribution  # Part 4: research pipeline, planted root causes
    python3 mas_eval_demo.py overhead     # Part 5: overhead from the same traces
    python3 mas_eval_demo.py baseline     # Part 6: single- vs multi-agent, 40 paired tasks
    python3 mas_eval_demo.py              # all of the above

Everything is scripted and seeded: no model, no keys, same output every run.
Numbers describe these fixtures only, never real systems.
"""
from __future__ import annotations

import hashlib
import random
import statistics
import sys
from dataclasses import dataclass

from agent_eval import pass_hat_k, percentile, redundant_calls, tool_call_prf
from mas_eval import (HUMAN, NONE, PASSTHROUGH, AgentSpan, HandoffGold, MASTaskGold,
                      MASTrace, ablation_credit, attribution_accuracy, attribution_report,
                      brief_fidelity, candidate_points, compare_systems,
                      context_transfer_suite, counterfactual_attribution, critical_path, cycles,
                      equal_budget_check, escalation_prf, first_step_attributor,
                      handoff_grade, handoff_timing, judge_attribution, last_step_attributor,
                      fix_necessity_check, overhead, overhead_summary, pareto_front, pingpong,
                      random_attributor, repeated_delegations, return_path,
                      routing_confusion, rule_attributor,
                      shapley_credit, to_trajectories, trace_from_events, trace_from_spans)

IN_PRICE, OUT_PRICE = 2e-6, 8e-6   # fixture prices per token, not any provider's


def _h(*parts: object) -> str:
    return hashlib.sha256("|".join(map(str, parts)).encode()).hexdigest()[:10]


# ===========================================================================
# Part 2 — adapters: 08D.3 TraceEvent log and 11A.1 JSONL spans
# ===========================================================================

def demo_trace() -> None:
    # A tiny 08D.3-shaped log: lead plans, delegates twice, synthesises.
    def ev(tid, pid, who, kind, ts, **detail):
        return dict(trace_id=tid, parent_id=pid, agent=who, kind=kind, detail=detail, ts=ts)
    events = [
        ev("run-1", None, "system", "system_run", 0.0, question="EU heat-pump grants"),
        ev("lead-1", "run-1", "lead", "agent_start", 0.0, task="EU heat-pump grants"),
        ev("lead-1", "lead-1", "lead", "model_call", 1.2, input_tokens=2100, output_tokens=380),
        ev("lead-1", "lead-1", "lead", "decision", 1.2, subtasks=["de", "fr"]),
        ev("w1", "lead-1", "worker-1", "agent_start", 1.3, task="Germany"),
        ev("w2", "lead-1", "worker-2", "agent_start", 1.3, task="France"),
        ev("w1", "w1", "worker-1", "tool_call", 2.0, name="web_search", is_error=False),
        ev("w2", "w2", "worker-2", "tool_call", 2.1, name="web_search", is_error=False),
        ev("w2", "w2", "worker-2", "tool_call", 2.9, name="web_search", is_error=True),
        ev("w1", "w1", "worker-1", "model_call", 3.1, input_tokens=4200, output_tokens=410),
        ev("w2", "w2", "worker-2", "model_call", 3.6, input_tokens=5100, output_tokens=390),
        ev("w1", "w1", "worker-1", "agent_end", 3.1, status="ok"),
        ev("w2", "w2", "worker-2", "agent_end", 3.6, status="partial"),
        ev("lead-1", "lead-1", "lead", "delegation", 3.6, agent="worker-1", subtask="de", status="ok"),
        ev("lead-1", "lead-1", "lead", "delegation", 3.6, agent="worker-2", subtask="fr", status="partial"),
        ev("lead-1", "lead-1", "lead", "model_call", 5.0, input_tokens=6900, output_tokens=720),
        ev("lead-1", "lead-1", "lead", "agent_end", 5.0, status="ok"),
    ]
    t = trace_from_events(events, task_id="R-demo", system="research@v1")
    print("from 08D.3 TraceEvents:", t.agents())
    for a, spans in t.by_agent().items():
        kinds = ",".join(sorted({s.kind for s in spans}))
        print(f"  {a:9s} spans={len(spans)} tokens={sum(s.tokens for s in spans):5d}  kinds={kinds}")
    print(f"  coordination tokens {t.tokens('coordination')} of {t.tokens()}")
    rp = return_path(t)
    print(f"  return_path: delegations={rp['delegations']} orphaned={rp['orphaned']} "
          f"non_terminal={rp['non_terminal']}")
    for agent, traj in to_trajectories(t).items():
        if traj.steps:
            print(f"  10A.7 tool_call_prf for {agent}: {tool_call_prf(traj)}")

    # 11A.1 JSONL envelope + attrs, with the OTel agent-name attribute.
    recs = [
        {"trace_id": "tr_a1", "span_id": "s1", "parent_span_id": None, "name": "invoke_agent triage",
         "kind": "agent", "start_ms": 0, "duration_ms": 900, "status": "ok",
         "attrs": {"gen_ai.agent.name": "triage", "gen_ai.operation.name": "invoke_agent",
                   "task_id": "T-demo"}},
        {"trace_id": "tr_a1", "span_id": "s2", "parent_span_id": "s1", "name": "chat",
         "kind": "llm", "start_ms": 10, "duration_ms": 700, "status": "ok",
         "attrs": {"total_input_tokens": 1500, "output_tokens": 60, "cost_usd": 0.00048}},
        {"trace_id": "tr_a1", "span_id": "s3", "parent_span_id": "s1", "name": "handoff",
         "kind": "handoff", "start_ms": 720, "duration_ms": 5, "status": "ok",
         "attrs": {"handoff.to": "billing", "turn": 1}},
        {"trace_id": "tr_a1", "span_id": "s4", "parent_span_id": None, "name": "invoke_agent billing",
         "kind": "agent", "start_ms": 730, "duration_ms": 2100, "status": "ok",
         "attrs": {"gen_ai.agent.name": "billing", "gen_ai.operation.name": "invoke_agent"}},
        {"trace_id": "tr_a1", "span_id": "s5", "parent_span_id": "s4", "name": "orders_get",
         "kind": "tool", "start_ms": 900, "duration_ms": 120, "status": "ok",
         "attrs": {"tool.name": "orders_get", "tool.args_hash": "9c1e"}},
    ]
    t2 = trace_from_spans(recs, system="support@v2")["tr_a1"]
    print("from 11A.1 JSONL spans:", t2.task_id, "route", t2.route(),
          "agents", {a: len(s) for a, s in t2.by_agent().items()})

Run it with python3 mas_eval_demo.py trace.

Output10 lines
=== trace ===
from 08D.3 TraceEvents: ['lead', 'worker-1', 'worker-2']
  lead      spans=6 tokens=10100  kinds=agent_run,decision,delegation,model_call
  worker-1  spans=4 tokens= 4610  kinds=agent_run,model_call,return,tool_call
  worker-2  spans=5 tokens= 5490  kinds=agent_run,model_call,return,tool_call
  coordination tokens 10100 of 20200
  return_path: delegations=2 orphaned=[] non_terminal=[]
  10A.7 tool_call_prf for worker-1: {'calls': 1, 'by_tool': {'web_search': 1}}
  10A.7 tool_call_prf for worker-2: {'calls': 2, 'by_tool': {'web_search': 2}}
from 11A.1 JSONL spans: T-demo route ['triage', 'billing'] agents {'triage': 3, 'billing': 2}

Read it in four steps. The 08D.3 log became three agents with their own token totals, and half of the tokens are tagged coordination because the lead's planning and synthesis calls are. Each delegation came with its paired return span, so return_path finds two delegations and no orphans. 10A.7's tool_call_prf ran per agent with no reference, which reports call counts: worker-2 made two searches, one of which errored, so you would now look at its recovery_rate per agent. The JSONL spans kept agent identity through inheritance (the chat span named no agent and still landed in triage), and the route is triage -> billing.


Part 3: Handoff correctness#

3.1 What a handoff has to get right#

A handoff moves control of the conversation from one agent to another (08D.3, 2.2); a delegation asks another agent for a result and expects it back; an escalation hands control to a person. All three are edges in the trace, and each edge can fail in seven distinct ways. Grading "did it pick the right agent?" covers one of them.

Property The question Grader in mas_eval.py Typical failure
Routing Did control go to an acceptable target, including "nobody" and "a human"? routing_confusion A damaged-item refund goes to billing, which improvises a returns policy
Timing Did it happen at the right moment? handoff_timing Handing off before the order number is known; dragging a billing chat through triage for six turns
Context transfer Did the receiver get every required field, with the right values, and nothing invented? context_transfer, context_transfer_suite An input filter strips the order number; a summary rewrites 84.50 as 48.50
Brief fidelity Did a delegation brief carry the objective, format, tools, boundaries and the user's constraints? brief_fidelity "Budget under £500" never reaches the worker
Loops Did control bounce or cycle between agents, or the same brief go out again and again? pingpong, cycles, repeated_delegations billing → returns → billing → returns; triage → billing → returns → triage
Return path Did every delegation come back, finish, and get used? return_path A result is computed and never reaches the answer; a task is left waiting for input
Escalation Did the cases that need a person reach one, with context, and only those? escalation_prf A legal threat stays with the bot; every mildly annoyed customer is escalated
sequenceDiagram
    participant U as User
    participant T as Triage agent
    participant F as Input filter or summary
    participant B as Billing agent
    U->>T: Refund of 84.50 for A-1005 has not arrived
    T->>F: handoff to billing with payload_sent
    Note over F: routing, timing and payload_sent are graded here
    F->>B: payload_seen, possibly trimmed or rewritten
    Note over B: context transfer is graded on payload_seen
    B-->>U: answer, or asks again for what was lost

3.2 Routing as classification#

Routing is a multi-class classification problem, so grade it like one (10A.3 owns the metrics). The prediction at each decision point is the target of the aligned transfer, or NONE if there was none; the gold is the acceptable set from 2.3. routing_confusion returns:

  • Accuracy: share of decision points routed to an acceptable target.
  • The confusion matrix over every target, including NONE and HUMAN. Rows are gold, columns are predictions. Off-diagonal mass shows which specialist steals which traffic, which is what you fix (usually a description overlap between two specialists' handoff tools; 08A.6 owns tool descriptions).
  • Per-class precision and recall. Read recall per target: a rare route (escalation, a niche specialist) can have recall 0.5 while overall accuracy looks fine, because class imbalance hides it.
  • Cohen's kappa against gold, computed with 10A.5's cohens_kappa. Accuracy rewards always picking the most common specialist; kappa does not.
  • False-handoff rate: among decision points where NONE was acceptable, how often the agent handed off anyway (an unnecessary hop costs a model call, latency and a context transfer that can lose data).
  • Missed-handoff rate: among decision points that needed a handoff, how often it never happened (the generalist that keeps everything).

When a point has several acceptable targets and the prediction is one of them, it counts on the diagonal of that target; when it is none of them, it counts in the row of the primary target. Put the target you would choose first in the tuple.

3.3 Handoff timing#

A handoff to the right agent at the wrong time is still a failure. handoff_timing compares each aligned handoff's turn with the gold window and labels it:

  • premature: before the earliest acceptable turn, typically before the information the receiver needs is collected (the specialist must ask again, or guesses);
  • late: after the latest acceptable turn (the user repeats themselves to the wrong agent);
  • missing: no handoff where one was required;
  • on time: inside the window.

It also reports the mean offset from the window, so a router that is consistently one turn early shows as a bias rather than as scattered errors. Timing errors often trace back to the handoff tool's description ("call this when the user mentions billing" fires on the first mention; "call this once you have the order number and the billing question" waits).

3.4 Context transfer: grade what the receiver saw#

Context-transfer completeness asks whether the receiving agent got what it needs. The key word is got. Frameworks deliberately trim context at handoffs: OpenAI's Agents SDK lets each handoff carry an input_filter that receives and returns HandoffInputData (remove_all_tools, from agents.extensions.handoff_filters, strips tool items, for example) and offers an opt-in nest_handoff_history setting that compacts the history into a summary; LangChain's handoff guidance recommends passing only the triggering message and its tool result; Inspect AI's handoff() passes the history through content_only() and offers remove_tools and last_message filters (framework details in 3.11). Each is a place where a field can disappear on purpose. So the grader reads payload_seen, the payload after any filter or summary, and only falls back to payload_sent with an explicit warning, because a sent payload can be perfect while the receiver sees nothing.

For one handoff, context_transfer(seen, required, source_facts=...) reports three numbers and three lists:

Metric Definition Catches
Field recall required fields present in seen / required fields Dropped identifiers (the "telephone game")
Value fidelity present required fields with the right value / present required fields; undefined (None) when no required field arrived, so a dropped field counts once, against recall A summary that rewrites 84.50 as 48.50, the wrong order number
Hallucinated-field rate fields in seen the sender had no basis for, or whose value differs from what the sender knew / fields in seen A sender that invents a fact the user never gave, or changes one it did
missing, wrong, invented The field names behind each number What to fix

Values are compared after a light normalisation (case, whitespace, thousands separators). Dates, currencies and units need the stronger normalisers of 10A.3. When the payload is free text rather than fields, you need an extractor first and then a claim-matching judge, which must itself be validated against human labels as in 10A.5 before its recall numbers mean anything. Schema validity (does the payload have every declared field with the declared type, as an Agents SDK input_type or an A2A data part would require?) is checked by schema_valid(seen, types) from the types declared on each HandoffGold. It is worth having, but a 100% schema pass rate says nothing about whether the values are right: the demo's T05 is schema-valid and carries the wrong amount.

context_transfer_suite runs the checks over every aligned handoff that has required fields and reports each mean with a bootstrap interval from 10A.8's bootstrap_mean_ci and its own n, because value fidelity and schema validity are not defined on every handoff.

3.5 Delegation briefs#

A delegation brief is the handoff payload of an orchestrator–subagent system. Anthropic's guidance, summarised in 08D.3, 3.1, names four elements a brief needs: an objective, an output format, guidance on tools and sources, and clear task boundaries. brief_fidelity checks two things cheaply:

  • Element presence, with keyword cues for each of the four elements (elements_score is the share present). Cues are crude by design; adjust them to your prompt template.
  • Constraint recall: the share of the user's constraints (an order number, a budget, a date range, "EU only") that survive into the brief, with the lost ones listed. This catches the most expensive brief failure: a worker that does excellent work on the wrong problem because the constraint that mattered stayed in the orchestrator's context.

Presence is not correctness. Whether the objective is the right objective, or whether two briefs overlap (the duplicated-work failure in 08D.3, 3.10), needs a judge with a rubric. Write the rubric per 10A.4 and validate it per 10A.5 before you report its numbers.

3.6 Loops and ping-pong#

Ping-pong is control bouncing back and forth: A → B → A. pingpong(trace) counts every A → B → A triple in the route, reports the chain length, and flags runs over a max_handoffs budget. It corresponds to MAST's step repetition (FM-1.3) and conversation reset (FM-2.1) at the interaction level, and 08D.3's run_swarm caps it with max_handoffs for exactly this reason.

One exception matters: in a supervisor architecture (08D.3, 2.3) every worker returns control to the supervisor by design, so worker → supervisor → worker is the normal shape, not a loop. Pass supervisor="name" and those triples are excluded; only peer-to-peer bounces count. Without the exception, a healthy supervisor system reports a ping-pong on every run (Exercise 2 shows it).

Two-agent bounces are only the simplest loop. Two more checks cover the rest:

  • cycles(trace, max_len=4) finds any agent that comes back after one to max_len − 1 other agents, so a three-agent cycle (triage → billing → returns → triage) is caught even though pingpong sees no A → B → A triple in it. Each cycle is reported once, with how often it repeated.
  • repeated_delegations(trace, min_repeat=3) counts delegations with the same sender, target and brief (hash or text). An orchestrator that re-sends one brief three times never shows in route(), because delegations are calls rather than transfers of control; 08D.3, 3.5 names exactly this loop.

The max_handoffs budget is the backstop for anything the pattern checks miss.

3.7 Return path: orphaned, unfinished and dropped results#

Delegations are promises: the worker will come back with a result and the orchestrator will use it. return_path(trace) checks all three halves of the promise.

  • Orphaned: a delegation with no matching return span. The worker hung, crashed without reporting, or was cancelled without the cancellation propagating (08D.3, 3.4). Orphans are also cost leaks: they may still be spending tokens.
  • Non-terminal: a return whose protocol state is not final. The A2A specification (version 1.0.0 is the latest release as of November 2026; specification) gives tasks four terminal states, TASK_STATE_COMPLETED, TASK_STATE_FAILED, TASK_STATE_CANCELED and TASK_STATE_REJECTED, and two interrupted ones, TASK_STATE_INPUT_REQUIRED and TASK_STATE_AUTH_REQUIRED, besides SUBMITTED and WORKING. A delegated task still INPUT_REQUIRED when the run ends is work the system forgot about.
  • Dropped: an ok result whose artefact or source ids never reach the final answer. 08D.3's AgentResult already carries sources and artefacts, so checking ids is exact and free; pass your own uses(final_answer, return_span) function when results are free text and you need a judge. This is the "lost context" row of 08D.3's failure gallery and MAST's "ignored other agent's input" (FM-2.5).

3.8 Escalation to a human#

Escalation is the handoff with the highest cost on both sides: a missed escalation can be a policy or legal failure; a needless one costs a person's time and teaches users to demand a human. escalation_prf treats it as a binary classifier over tasks (should_escalate against "a transfer to HUMAN happened") and reports recall with a Wilson interval, precision, the true-negative rate, the field recall of the context the human received, and the mean turns to escalation. Report both error types with what each costs you, and weight the decision on recall for the safety-relevant slice. 08D.3, Part 5 owns how escalation and takeover work; this is how you measure them.

3.9 mas_eval.py, section 2: the handoff graders#

Besides the graders above, this section has schema_valid, cycles and repeated_delegations. handoff_grade at the end bundles the per-trace checks into one 10A.7 Grade, so a handoff check can sit in a task's grader list next to state_is and within_budget.

python
# ---------------------------------------------------------------------------
# evalkit/mas_eval.py, section 2 of 5 (append after section 1)
# 2. Handoff graders
# ---------------------------------------------------------------------------

def routing_confusion(golds: list[MASTaskGold], traces: dict[str, MASTrace],
                      *, labels: list[str] | None = None) -> dict:
    """Routing as classification. Prediction = target of the aligned transfer,
    or NONE. Correct if it is in the gold set; the matrix row is the primary
    gold target (or the predicted one when it is also acceptable)."""
    gold_l, pred_l, errors = [], [], []
    for g in golds:
        for i, (hg, h) in enumerate(zip(g.handoffs, _aligned(traces[g.task_id], g))):
            pred = h.attrs.get("to", "?") if h else NONE
            ok = pred in hg.expected
            gold_l.append(pred if ok else hg.expected[0])
            pred_l.append(pred)
            if not ok:
                errors.append({"task": g.task_id, "point": i,
                               "gold": list(hg.expected), "pred": pred})
    labels = labels or sorted(set(gold_l) | set(pred_l))
    matrix = confusion_counts(gold_l, pred_l, labels)
    per_class = {}
    for lab in labels:
        tp = matrix[lab][lab]
        col = sum(matrix[r][lab] for r in labels)
        row = sum(matrix[lab].values())
        p = tp / col if col else float("nan")
        r = tp / row if row else float("nan")
        f1 = 2 * p * r / (p + r) if col and row and (p + r) else float("nan")
        per_class[lab] = {"precision": p, "recall": r, "f1": f1, "support": row}
    none_pts = [(gl, pl) for gl, pl, g in zip(gold_l, pred_l, _flat_points(golds))
                if NONE in g.expected]
    need_pts = [(gl, pl) for gl, pl, g in zip(gold_l, pred_l, _flat_points(golds))
                if NONE not in g.expected]
    n = len(gold_l)
    return {
        "n": n,
        "accuracy": sum(a == b for a, b in zip(gold_l, pred_l)) / n if n else float("nan"),
        "kappa": cohens_kappa(gold_l, pred_l) if len(set(gold_l)) > 1 else float("nan"),
        "labels": labels, "matrix": matrix, "per_class": per_class,
        "false_handoff_rate": (sum(p != NONE for _, p in none_pts) / len(none_pts)
                               if none_pts else None),
        "missed_handoff_rate": (sum(p == NONE for _, p in need_pts) / len(need_pts)
                                if need_pts else None),
        "errors": errors,
    }


def _flat_points(golds: list[MASTaskGold]) -> list[HandoffGold]:
    return [hg for g in golds for hg in g.handoffs]


def handoff_timing(golds: list[MASTaskGold], traces: dict[str, MASTrace]) -> dict:
    """premature / late / missing / on_time against annotated turn windows."""
    counts = Counter()
    offsets, detail = [], []
    for g in golds:
        for i, (hg, h) in enumerate(zip(g.handoffs, _aligned(traces[g.task_id], g))):
            if hg.window is None:
                continue
            lo, hi = hg.window
            if h is None:
                if NONE not in hg.expected:
                    counts["missing"] += 1
                    detail.append((g.task_id, i, "missing", None))
                continue
            turn = int(h.attrs.get("turn", 0))
            label = "premature" if turn < lo else "late" if turn > hi else "on_time"
            counts[label] += 1
            offsets.append(turn - min(max(turn, lo), hi))
            if label != "on_time":
                detail.append((g.task_id, i, label, turn))
    return {**{k: counts.get(k, 0) for k in ("on_time", "premature", "late", "missing")},
            "mean_offset": statistics.fmean(offsets) if offsets else 0.0,
            "detail": detail}


def _norm(v: Any) -> str:
    return " ".join(str(v).strip().lower().replace(",", "").split())


def context_transfer(seen: dict, required: dict, *, source_facts: dict | None = None,
                     normalise: Callable[[Any], str] = _norm) -> dict:
    """Grade ONE handoff payload as the receiver saw it (after any input filter).

    field_recall      required fields present / required fields
    value_fidelity    present required fields with the right value / present
                      required fields; None when nothing required arrived (a
                      dropped field is a recall failure, not a fidelity one)
    hallucinated_rate fields the sender had no basis for, or whose value
                      differs from what the sender knew / fields seen
                      (only when source_facts is given)
    """
    present = [k for k in required if k in seen]
    wrong = [k for k in present if normalise(seen[k]) != normalise(required[k])]
    invented = []
    if source_facts is not None:
        invented = [k for k in seen if k not in source_facts
                    or (k not in required and normalise(seen[k]) != normalise(source_facts[k]))]
    return {
        "field_recall": len(present) / len(required) if required else 1.0,
        "value_fidelity": (len(present) - len(wrong)) / len(present) if present else None,
        "hallucinated_rate": len(invented) / len(seen) if seen else 0.0,
        "missing": [k for k in required if k not in seen],
        "wrong": wrong, "invented": invented,
    }


def schema_valid(seen: dict, types: dict[str, type]) -> dict:
    """Does the payload have every declared field with the declared type?
    Valid says nothing about whether the VALUES are right."""
    errors = [f"{k}: missing" for k in types if k not in seen]
    errors += [f"{k}: {type(seen[k]).__name__} not {t.__name__}"
               for k, t in types.items() if k in seen and not isinstance(seen[k], t)]
    return {"valid": not errors, "errors": errors}


def context_transfer_suite(golds: list[MASTaskGold], traces: dict[str, MASTrace],
                           *, seed: int = 0) -> dict:
    """context_transfer over every aligned handoff that has required fields.
    Reads payload_seen; falls back to payload_sent and says so — a sent payload
    can look perfect while the filter downstream strips it. Each metric is
    averaged over the handoffs where it is defined, with its own n."""
    rows = []
    for g in golds:
        for hg, h in zip(g.handoffs, _aligned(traces[g.task_id], g)):
            if not hg.required or h is None:
                continue
            seen = h.attrs.get("payload_seen")
            fallback = seen is None
            seen = seen if not fallback else h.attrs.get("payload_sent", {})
            ct = context_transfer(seen, hg.required, source_facts=g.source_facts or None)
            if hg.types:
                ct["schema_valid"] = schema_valid(seen, hg.types)["valid"]
            rows.append({"task": g.task_id, "to": h.attrs.get("to"),
                         "graded_on": "sent (no payload_seen!)" if fallback else "seen", **ct})
    if not rows:
        return {"n": 0, "rows": []}
    out = {"n": len(rows), "rows": rows}
    for key in ("field_recall", "value_fidelity", "hallucinated_rate", "schema_valid"):
        vals = [float(r[key]) for r in rows if r.get(key) is not None]
        if vals:
            m, lo, hi = bootstrap_mean_ci(vals, iters=2000, seed=seed)
            out[key] = (round(m, 3), round(lo, 3), round(hi, 3), len(vals))
    return out


DEFAULT_BRIEF_ELEMENTS: dict[str, tuple[str, ...]] = {
    # Anthropic's four delegation-brief elements (08D.3 3.1), as cheap keyword cues.
    "objective": ("objective", "goal", "find", "determine"),
    "output_format": ("return", "format", "output", "respond with"),
    "tool_guidance": ("use ", "search", "tool", "source"),
    "boundaries": ("do not", "don't", "out of scope", "only", "stop when"),
}


def brief_fidelity(brief: str, *, constraints: list[str],
                   elements: dict[str, tuple[str, ...]] = DEFAULT_BRIEF_ELEMENTS) -> dict:
    """Checklist over a delegation brief: are the four elements present, and
    did the user's constraints survive into it? Presence only — whether the
    brief is *right* needs a judge validated per 10A.5."""
    text = brief.lower()
    has = {name: any(cue in text for cue in cues) for name, cues in elements.items()}
    kept = [c for c in constraints if c.lower() in text]
    return {"elements": has, "elements_score": sum(has.values()) / len(has),
            "constraint_recall": len(kept) / len(constraints) if constraints else 1.0,
            "lost_constraints": [c for c in constraints if c not in kept]}


def pingpong(trace: MASTrace, *, supervisor: str | None = None,
             max_handoffs: int = 4) -> dict:
    """A->B->A bounces in the route. In a supervisor pattern, returns to the
    supervisor are the design, not a loop: pass supervisor= to exclude them."""
    r = trace.route()
    cycles = []
    for i in range(len(r) - 2):
        if r[i] == r[i + 2] and r[i] != r[i + 1] and supervisor not in (r[i], r[i + 1]):
            cycles.append((r[i], r[i + 1]))
    chain = len(r) - 1
    return {"pingpong": len(cycles), "chain_len": chain,
            "over_budget": chain > max_handoffs, "cycles": cycles, "route": r}


def cycles(trace: MASTrace, *, supervisor: str | None = None,
           max_len: int = 4) -> dict:
    """Loops of any length in the route, not only A->B->A: an agent that
    comes back after 1 to max_len-1 other agents (triage -> billing ->
    returns -> triage is a 3-cycle). Each cycle is reported once, rotated to
    a canonical form. Supervisor returns are excluded, as in pingpong()."""
    r = [a for a in trace.route() if a != supervisor]
    found: dict[tuple, int] = {}
    for j in range(len(r)):
        for i in range(j - 2, max(0, j - max_len) - 1, -1):   # nearest repeat first
            seg = r[i:j]
            if r[i] == r[j] and len(set(seg)) == len(seg):
                k = seg.index(min(seg))
                canon = tuple(seg[k:] + seg[:k])
                found[canon] = found.get(canon, 0) + 1
                break
    return {"cycles": [{"agents": list(c), "length": len(c), "repeats": n}
                       for c, n in found.items()],
            "longest": max((len(c) for c in found), default=0)}


def repeated_delegations(trace: MASTrace, *, min_repeat: int = 3) -> list[dict]:
    """The same brief sent to the same agent again and again: a delegation
    loop that never shows in route(), because delegations are calls, not
    transfers of control. Keyed on (sender, target, brief hash or text)."""
    c = Counter((s.agent, s.attrs.get("to"), s.attrs.get("brief_sha") or s.attrs.get("brief"))
                for s in trace.spans if s.kind == "delegation")
    return [{"from": a, "to": t, "times": n} for (a, t, _), n in c.items() if n >= min_repeat]


def _default_uses(final_answer: str, ret: AgentSpan) -> float:
    ids = list(ret.attrs.get("artefacts", [])) + list(ret.attrs.get("sources", []))
    if not ids:
        return 1.0                          # nothing checkable: don't flag
    return sum(i in final_answer for i in ids) / len(ids)


def return_path(trace: MASTrace, *,
                uses: Callable[[str, AgentSpan], float] = _default_uses) -> dict:
    """Did every delegation come back, end in a terminal state, and get used?

    orphaned      delegations with no matching return span
    non_terminal  returns whose A2A state is not terminal (still WORKING,
                  INPUT_REQUIRED, AUTH_REQUIRED ...)
    dropped       ok returns whose ids (artefacts/sources) never reach the
                  final answer — uses() returns the share of ids found
    """
    dels = [s for s in trace.spans if s.kind == "delegation"]
    rets = {s.attrs.get("of"): s for s in trace.spans if s.kind == "return"}
    orphaned = [d.span_id for d in dels if d.span_id not in rets]
    non_terminal, dropped, coverage = [], [], {}
    for of, ret in rets.items():
        state = ret.attrs.get("state")
        if state is not None and state not in A2A_TERMINAL:
            non_terminal.append((of, state))
            continue
        if ret.status == "ok":
            cov = uses(trace.final_answer, ret)
            coverage[of] = cov
            if cov == 0:
                dropped.append(of)
    return {"delegations": len(dels), "orphaned": orphaned,
            "non_terminal": non_terminal, "dropped": dropped, "coverage": coverage}


def escalation_prf(golds: list[MASTaskGold], traces: dict[str, MASTrace]) -> dict:
    """Escalation to a human as a binary classifier, plus what the human got."""
    tp = fp = fn = tn = 0
    ctx, turns, missed = [], [], []
    for g in golds:
        t = traces[g.task_id]
        esc = [h for h in t.handoffs(TRANSFER_KINDS) if h.attrs.get("to") == HUMAN]
        pred = bool(esc)
        if g.should_escalate and pred:
            tp += 1
            turns.append(int(esc[0].attrs.get("turn", 0)))
            req = next((hg.required for hg in g.handoffs if HUMAN in hg.expected), {})
            if req:
                ctx.append(context_transfer(esc[0].attrs.get("payload_seen", {}), req)["field_recall"])
        elif g.should_escalate:
            fn += 1
            missed.append(g.task_id)
        elif pred:
            fp += 1
        else:
            tn += 1
    rec = tp / (tp + fn) if tp + fn else float("nan")
    prec = tp / (tp + fp) if tp + fp else float("nan")
    return {"tp": tp, "fp": fp, "fn": fn, "tn": tn, "recall": rec, "precision": prec,
            "tnr": tn / (tn + fp) if tn + fp else float("nan"),
            "recall_ci": wilson_interval(tp, tp + fn),
            "context_recall": statistics.fmean(ctx) if ctx else None,
            "turns_to_escalation": statistics.fmean(turns) if turns else None,
            "missed": missed}


def handoff_grade(gold: MASTaskGold, trace: MASTrace, *,
                  supervisor: str | None = None, max_handoffs: int = 4) -> Grade:
    """All per-trace handoff checks as one 10A.7 Grade, for grader lists."""
    reasons: list[str] = []
    for i, (hg, h) in enumerate(zip(gold.handoffs, _aligned(trace, gold))):
        pred = h.attrs.get("to", "?") if h else NONE
        if pred not in hg.expected:
            reasons.append(f"point {i}: routed to {pred}, expected {list(hg.expected)}")
        if h is not None and hg.window is not None:
            turn, (lo, hi) = int(h.attrs.get("turn", 0)), hg.window
            if not lo <= turn <= hi:
                reasons.append(f"point {i}: handoff at turn {turn}, window {lo}-{hi}")
        if h is not None and hg.required:
            ct = context_transfer(h.attrs.get("payload_seen", {}), hg.required)
            if ct["missing"] or ct["wrong"]:
                reasons.append(f"point {i}: missing={ct['missing']} wrong={ct['wrong']}")
    pp = pingpong(trace, supervisor=supervisor, max_handoffs=max_handoffs)
    if pp["pingpong"] or pp["over_budget"]:
        reasons.append(f"route {'->'.join(pp['route'])}")
    rp = return_path(trace)
    if rp["orphaned"] or rp["non_terminal"] or rp["dropped"]:
        reasons.append(f"return path: orphaned={rp['orphaned']} "
                       f"non_terminal={rp['non_terminal']} dropped={rp['dropped']}")
    escalated = any(h.attrs.get("to") == HUMAN for h in trace.handoffs(TRANSFER_KINDS))
    if gold.should_escalate != escalated:
        reasons.append(f"escalation: expected {gold.should_escalate}, got {escalated}")
    return Grade(name="handoffs", passed=not reasons,
                 score=1.0 if not reasons else 0.0, reasons=reasons)

3.10 The support-desk fixture#

Fixture A is a support desk with a triage agent, three specialists (billing, returns, tech), two helper agents reached by delegation (ledger, diagnostics) and a human queue. Fourteen tasks, most with a planted fault:

Task Planted fault Which grader should catch it
T03, T07 Damaged-item refund routed to billing (gold: returns) routing_confusion
T04 The handoff filter drops order_id context_transfer: field recall
T05 A summary rewrites the amount 84.50 as 48.50 context_transfer: value fidelity
T06 Tech handoff at turn 1, before device details (window 2–3) handoff_timing: premature
T08 billing ↔ returns bounce on an ambiguous exchange pingpong
T10 A legal threat stays with the bot escalation_prf, routing (HUMAN row)
T11 The ledger result never reaches the answer; the brief lost "VAT" return_path: dropped; brief_fidelity
T12 A diagnostics task left TASK_STATE_INPUT_REQUIRED return_path: non-terminal
T14 A closing "thanks" routed to billing (gold: NONE) routing_confusion: false handoff
T01, T02, T09, T13 None (controls, including a correct escalation) Nothing should fire
python
# ===========================================================================
# mas_eval_demo.py, section 2 of 5 (append after section 1)
# Part 3 — Fixture A: a support-desk handoff swarm with planted faults
# ===========================================================================

class TraceBuilder:
    """Small helper that writes the spans a real tracer would emit."""

    def __init__(self, task_id: str, system: str = "support-swarm@v2"):
        self.t = MASTrace(trace_id=f"tr-{task_id}", task_id=task_id, system=system)
        self.clock = 0.0
        self.n = 0

    def _id(self) -> str:
        self.n += 1
        return f"{self.t.task_id}-s{self.n}"

    def run(self, agent: str, secs: float = 1.0, tin: int = 900, tout: int = 120) -> str:
        sid = self._id()
        self.t.spans.append(AgentSpan(sid, None, agent, "agent_run", self.clock,
                                      self.clock + secs))
        self.t.spans.append(AgentSpan(self._id(), sid, agent, "model_call", self.clock,
                                      self.clock + secs * 0.9, tokens_in=tin, tokens_out=tout,
                                      cost_usd=tin * IN_PRICE + tout * OUT_PRICE))
        self.clock += secs
        return sid

    def handoff(self, src: str, dst: str, turn: int, sent: dict,
                seen: dict | None = None) -> None:
        kind = "escalation" if dst == HUMAN else "handoff"
        self.t.spans.append(AgentSpan(self._id(), None, src, kind, self.clock, self.clock,
                                      role="coordination",
                                      attrs={"to": dst, "turn": turn, "payload_sent": sent,
                                             "payload_seen": sent if seen is None else seen}))

    def delegate(self, src: str, dst: str, brief: str, artefacts: list[str],
                 state: str = "TASK_STATE_COMPLETED") -> None:
        did = self._id()
        self.t.spans.append(AgentSpan(did, None, src, "delegation", self.clock, self.clock,
                                      role="coordination", attrs={"to": dst, "brief": brief}))
        self.run(dst, 0.8)
        self.t.spans.append(AgentSpan(self._id(), None, dst, "return", self.clock, self.clock,
                                      role="coordination",
                                      attrs={"of": did, "artefacts": artefacts, "state": state}))

    def done(self, answer: str, success: bool) -> MASTrace:
        self.t.final_answer, self.t.success = answer, success
        return self.t


def support_fixture() -> tuple[list[MASTaskGold], dict[str, MASTrace]]:
    golds: list[MASTaskGold] = []
    traces: dict[str, MASTrace] = {}

    def add(gold: MASTaskGold, trace: MASTrace) -> None:
        golds.append(gold)
        traces[gold.task_id] = trace

    def simple(tid: str, dst: str, expected: tuple, order: str, *, turn: int = 1,
               window=(1, 2), seen: dict | None = None, extra: dict | None = None,
               answer: str = "Done.", ok: bool = True) -> None:
        req = {"order_id": order, **(extra or {})}
        b = TraceBuilder(tid)
        b.run("triage")
        b.handoff("triage", dst, turn, dict(req), seen)
        b.run(dst, 1.6)
        types = {k: str for k in req}                      # the handoff's declared schema
        add(MASTaskGold(tid, [HandoffGold(expected, "triage", window, req, types)],
                        source_facts=dict(req)), b.done(answer, ok))

    simple("T01", "billing", ("billing",), "A-1001")                     # control
    simple("T02", "returns", ("returns",), "A-1002")                     # control
    simple("T03", "billing", ("returns",), "A-1003", ok=False)           # F1 misroute
    simple("T04", "billing", ("billing",), "A-1004", seen={}, ok=False)  # F2 filter drops order_id
    simple("T05", "billing", ("billing",), "A-1005", extra={"amount": "84.50"},
           seen={"order_id": "A-1005", "amount": "48.50"}, ok=False)    # F3 summary rewrites amount
    simple("T06", "tech", ("tech",), "A-1006", turn=1, window=(2, 3))    # F8 premature
    simple("T07", "billing", ("returns",), "A-1007", ok=False)           # F1 misroute again

    # F4 ping-pong: an ambiguous exchange bounces billing <-> returns.
    b = TraceBuilder("T08")
    b.run("triage")
    req = {"order_id": "A-1008"}
    b.handoff("triage", "billing", 1, req)
    for turn, (src, dst) in enumerate([("billing", "returns"), ("returns", "billing"),
                                        ("billing", "returns")], start=2):
        b.run(src, 1.2)
        b.handoff(src, dst, turn, req)
    b.run("returns", 1.4)
    add(MASTaskGold("T08", [HandoffGold(("returns", "billing"), "triage", (1, 2), req)],
                    source_facts=req), b.done("Exchange arranged.", True))

    # Control: a question triage should answer itself (expected NONE).
    b = TraceBuilder("T09")
    b.run("triage")
    add(MASTaskGold("T09", [HandoffGold((NONE,), "triage")]), b.done("We open 9-17.", True))

    # F5 missed escalation: legal threat stays with the bot.
    b = TraceBuilder("T10")
    b.run("triage")
    req10 = {"order_id": "A-1010"}
    b.handoff("triage", "returns", 1, req10)
    b.run("returns", 2.0)
    add(MASTaskGold("T10", [HandoffGold(("returns",), "triage", (1, 2), req10),
                            HandoffGold((HUMAN,), "returns", (2, 3),
                                        {"order_id": "A-1010", "reason": "legal threat"})],
                    should_escalate=True, source_facts={**req10, "reason": "legal threat"}),
        b.done("I have processed your refund request.", False))

    # F6 dropped return: the ledger result never reaches the answer.
    b = TraceBuilder("T11")
    b.run("triage")
    req11 = {"order_id": "A-1011"}
    b.handoff("triage", "billing", 1, req11)
    b.run("billing", 1.0)
    brief11 = "Find the ledger entry for order A-1011 and return its entry id. Use the ledger tool only."
    b.delegate("billing", "ledger", brief11, ["LEDGER-77"])
    b.run("billing", 1.0)
    add(MASTaskGold("T11", [HandoffGold(("billing",), "triage", (1, 2), req11)],
                    source_facts=req11),
        b.done("Your invoice is correct as issued.", False))

    # F7 non-terminal delegation: diagnostics left waiting for input.
    b = TraceBuilder("T12")
    b.run("triage", 1.0)
    req12 = {"order_id": "A-1012"}
    b.run("triage", 1.0)
    b.handoff("triage", "tech", 2, req12)
    b.run("tech", 1.0)
    b.delegate("tech", "diagnostics", "Run line diagnostics for the router on A-1012.",
               ["DIAG-5"], state="TASK_STATE_INPUT_REQUIRED")
    add(MASTaskGold("T12", [HandoffGold(("tech",), "triage", (2, 3), req12)],
                    source_facts=req12),
        b.done("Diagnostics are running; we'll be in touch. Ref DIAG-5.", False))

    # Control: an explicit request for a person, escalated with context.
    b = TraceBuilder("T13")
    b.run("triage")
    req13 = {"order_id": "A-1013", "summary": "wants a person"}
    b.handoff("triage", HUMAN, 1, req13)
    add(MASTaskGold("T13", [HandoffGold((HUMAN,), "triage", (1, 2), {"order_id": "A-1013"})],
                    should_escalate=True, source_facts=req13),
        b.done("Connecting you to a colleague.", True))

    # F9 false handoff: a closing "thanks" gets routed to billing.
    b = TraceBuilder("T14")
    b.run("triage")
    b.handoff("triage", "billing", 1, {})
    b.run("billing", 0.6)
    add(MASTaskGold("T14", [HandoffGold((NONE,), "triage")]), b.done("You're welcome!", True))
    return golds, traces


def demo_handoffs() -> None:
    golds, traces = support_fixture()
    labels = ["billing", "returns", "tech", HUMAN, NONE]
    rc = routing_confusion(golds, traces, labels=labels)
    print(f"routing: n={rc['n']} accuracy={rc['accuracy']:.2f} kappa={rc['kappa']:.2f} "
          f"false_handoff={rc['false_handoff_rate']:.2f} missed={rc['missed_handoff_rate']:.2f}")
    print("gold \\ pred  " + " ".join(f"{l:>7s}" for l in labels))
    for g in labels:
        print(f"{g:11s}  " + " ".join(f"{rc['matrix'][g][p]:7d}" for p in labels))
    for lab in labels:
        pc = rc["per_class"][lab]
        if pc["support"]:
            print(f"  {lab:8s} recall={pc['recall']:.2f} precision={pc['precision']:.2f} "
                  f"support={pc['support']}")
    print("  errors:", [(e["task"], e["gold"], e["pred"]) for e in rc["errors"]])

    tm = handoff_timing(golds, traces)
    print(f"timing: on_time={tm['on_time']} premature={tm['premature']} late={tm['late']} "
          f"missing={tm['missing']} detail={tm['detail']}")

    ct = context_transfer_suite(golds, traces)
    print(f"context transfer over {ct['n']} handoffs (mean, 95% CI, n):")
    for key in ("field_recall", "value_fidelity", "schema_valid"):
        print(f"  {key:15s} {ct[key]}")
    for r in ct["rows"]:
        if r["missing"] or r["wrong"]:
            print(f"  {r['task']} -> {r['to']}: missing={r['missing']} wrong={r['wrong']} "
                  f"(graded on {r['graded_on']})")

    print("brief T11:", brief_fidelity(
        traces["T11"].handoffs(("delegation",))[0].attrs["brief"],
        constraints=["A-1011", "VAT"]))

    for tid in ("T08", "T01"):
        pp = pingpong(traces[tid], max_handoffs=3)
        print(f"pingpong {tid}: {pp['pingpong']} over_budget={pp['over_budget']} "
              f"route={'->'.join(pp['route'])}")
    # Loops pingpong cannot see: a three-agent cycle, and the same brief
    # delegated over and over (delegations never appear in the route).
    b = TraceBuilder("X1")
    b.run("triage")
    for turn, (src, dst) in enumerate([("triage", "billing"), ("billing", "returns"),
                                        ("returns", "triage"), ("triage", "billing")], 1):
        b.handoff(src, dst, turn, {})
    loop3 = b.done("...", False)
    print(f"X1 route {'->'.join(loop3.route())}: pingpong={pingpong(loop3)['pingpong']} "
          f"cycles={cycles(loop3)['cycles']}")
    b = TraceBuilder("X2")
    b.run("billing")
    for _ in range(3):
        b.delegate("billing", "ledger", "Find the ledger entry for A-2002.", ["LEDGER-9"])
    print(f"X2 repeated_delegations: {repeated_delegations(b.done('...', False))}")

    for tid in ("T11", "T12"):
        rp = return_path(traces[tid])
        print(f"return_path {tid}: orphaned={rp['orphaned']} non_terminal={rp['non_terminal']} "
              f"dropped={rp['dropped']}")

    esc = escalation_prf(golds, traces)
    print(f"escalation: recall={esc['recall']:.2f} (95% CI {esc['recall_ci'][0]:.2f}-"
          f"{esc['recall_ci'][1]:.2f}) precision={esc['precision']:.2f} "
          f"context_recall={esc['context_recall']} missed={esc['missed']}")

    print("per-task handoff grade (failures only):")
    for g in golds:
        gr = handoff_grade(g, traces[g.task_id], max_handoffs=3)
        if not gr.passed:
            print(f"  {g.task_id}: " + " | ".join(gr.reasons))

Run it with python3 mas_eval_demo.py handoffs.

Output40 lines
=== handoffs ===
routing: n=15 accuracy=0.73 kappa=0.64 false_handoff=0.50 missed=0.08
gold \ pred  billing returns    tech   HUMAN    NONE
billing            5       0       0       0       0
returns            2       2       0       0       0
tech               0       0       2       0       0
HUMAN              0       0       0       1       1
NONE               1       0       0       0       1
  billing  recall=1.00 precision=0.62 support=5
  returns  recall=0.50 precision=1.00 support=4
  tech     recall=1.00 precision=1.00 support=2
  HUMAN    recall=0.50 precision=1.00 support=2
  NONE     recall=0.50 precision=0.50 support=2
  errors: [('T03', ['returns'], 'billing'), ('T07', ['returns'], 'billing'), ('T10', ['HUMAN'], 'NONE'), ('T14', ['NONE'], 'billing')]
timing: on_time=11 premature=1 late=0 missing=1 detail=[('T06', 0, 'premature', 1), ('T10', 1, 'missing', None)]
context transfer over 12 handoffs (mean, 95% CI, n):
  field_recall    (0.917, 0.75, 1.0, 12)
  value_fidelity  (0.955, 0.864, 1.0, 11)
  schema_valid    (0.857, 0.571, 1.0, 7)
  T04 -> billing: missing=['order_id'] wrong=[] (graded on seen)
  T05 -> billing: missing=[] wrong=['amount'] (graded on seen)
brief T11: {'elements': {'objective': True, 'output_format': True, 'tool_guidance': True, 'boundaries': True}, 'elements_score': 1.0, 'constraint_recall': 0.5, 'lost_constraints': ['VAT']}
pingpong T08: 2 over_budget=True route=triage->billing->returns->billing->returns
pingpong T01: 0 over_budget=False route=triage->billing
X1 route triage->billing->returns->triage->billing: pingpong=0 cycles=[{'agents': ['billing', 'returns', 'triage'], 'length': 3, 'repeats': 2}]
X2 repeated_delegations: [{'from': 'billing', 'to': 'ledger', 'times': 3}]
return_path T11: orphaned=[] non_terminal=[] dropped=['T11-s6']
return_path T12: orphaned=[] non_terminal=[('T12-s8', 'TASK_STATE_INPUT_REQUIRED')] dropped=[]
escalation: recall=0.50 (95% CI 0.09-0.91) precision=1.00 context_recall=1.0 missed=['T10']
per-task handoff grade (failures only):
  T03: point 0: routed to billing, expected ['returns']
  T04: point 0: missing=['order_id'] wrong=[]
  T05: point 0: missing=[] wrong=['amount']
  T06: point 0: handoff at turn 1, window 2-3
  T07: point 0: routed to billing, expected ['returns']
  T08: route triage->billing->returns->billing->returns
  T10: point 1: routed to NONE, expected ['HUMAN'] | escalation: expected True, got False
  T11: return path: orphaned=[] non_terminal=[] dropped=['T11-s6']
  T12: return path: orphaned=[] non_terminal=[('T12-s8', 'TASK_STATE_INPUT_REQUIRED')] dropped=[]
  T14: point 0: routed to billing, expected ['NONE']

How to read it:

  • Routing: accuracy 0.73 with kappa 0.64 over 15 decision points. The matrix shows where it goes wrong: two returns cases landed in billing (returns recall 0.50), one HUMAN case stayed with the bot (HUMAN recall 0.50) and one NONE case was handed off (false-handoff rate 0.50, from two NONE points). Billing's recall is a perfect 1.00 and its precision 0.62: billing is absorbing other teams' traffic, which is the fix to make (sharpen the returns and billing descriptions).
  • Timing found the premature tech handoff in T06 and listed T10's escalation as missing, so the same miss shows from two angles.
  • Context transfer: field recall 0.917 over 12 handoffs, value fidelity 0.955 over the 11 handoffs where any required field arrived (T04's dropped order_id counts once, against recall), and schema validity 6 of 7 on the handoffs with a declared schema. The rows name the two broken handoffs, and T05 shows the limit of schema checks: valid types, wrong amount. Notice the intervals: with 12 handoffs the 95% interval on field recall runs from 0.75 to 1.0, so a suite this size can show that fields are lost and where, not a precise rate.
  • The brief for T11 has all four elements and still lost the user's VAT constraint: constraint recall 0.5. A presence checklist alone would have passed it.
  • Ping-pong counted two bounces on T08 and flagged the run over a three-handoff budget, while the control T01 is clean. The two extra traces show what pingpong cannot see: X1's three-agent cycle has no A → B → A triple (pingpong=0) and cycles finds it, and X2's three identical briefs to the ledger agent are caught by repeated_delegations.
  • Return path found the dropped ledger result (T11) and the task left waiting for input (T12).
  • Escalation recall is 0.50 with a 95% interval of 0.09 to 0.91 on two positive cases. That interval is the honest headline: two escalation tasks cannot measure an escalation rate. Build a dedicated escalation slice of 30 or more cases before you report the number.
  • The per-task grade lists exactly the planted faults and leaves the four controls alone, which is the self-test a grader set should pass before you trust it on a real system (10A.7, 5.5).

3.11 What the frameworks let you grade#

Framework mechanics change fast, so this is awareness, checked against the official pages in November 2026; 08D.3, 6.3 covers the frameworks themselves.

Framework or protocol How a handoff appears What you can grade from it directly What you must add
OpenAI Agents SDK (handoffs) A tool the model calls, named transfer_to_<agent_name> by default; handoff() takes input_type (validated arguments), input_filter, on_handoff, is_enabled Routing and timing from handoff_span (from_agent, to_agent); schema validity via input_type payload_seen after the filter. Per-handoff filters override RunConfig.handoff_input_filter; filters are not supported with server-managed conversations; tool input guardrails do not apply to handoffs, so authorisation checks belong in on_handoff
LangChain / LangGraph (handoffs) A tool returning Command(goto=..., update=..., graph=Command.PARENT); the active agent lives in state. The prebuilt langgraph-swarm package (repository) exposes create_swarm and create_handoff_tool and records the current agent under active_agent in state; langgraph-supervisor is no longer actively maintained, and LangChain's migration guide recommends the subagents pattern (create_agent with workers wrapped as tools) The route from state transitions (active_agent changes in a swarm; tool calls to wrapped workers in the subagents pattern, which grade as delegations) The tool must also emit a ToolMessage with the matching tool_call_id or the history is malformed; log which context strategy (full, filtered, summarised) each agent receives
Inspect AI (multi-agent) handoff() exposes a transfer_to_<name> tool; the receiver sees history minus system messages, and its output passes through content_only() (taught in 10B.14, Part 9) The sample transcript shows each agent's work No multi-agent-specific scorers: write them (this file's graders port directly)
A2A (spec 1.0.0) Tasks and messages between agents, with contextId, taskId, artifacts, history Return path from task states (terminal versus interrupted) Whether the artifacts were used downstream
OpenTelemetry GenAI (conventions, Development status) invoke_agent / invoke_workflow spans with gen_ai.agent.name Agent identity across vendors Handoff payloads are not part of the conventions: put them in your own attributes

To measure multi-agent runs with tooling, see 10B.5, Part 13 (DeepEval nested agent spans and a handoff metric) and, as an optional follow-up, 10B.14, Part 9 (Inspect handoffs and agents as tools). These are tooling follow-ups: the concepts stay here.


Part 4: Per-agent failure attribution#

4.1 Blame, symptom, root cause and the decisive error#

When a multi-agent run fails, someone will ask "which agent broke it?". Three different answers hide in that question, and confusing them sends teams to fix the wrong agent.

  • The symptom is where the failure becomes visible: the synthesiser's answer is missing Poland's figure; the billing agent quotes the wrong amount. It is usually late in the run, often the last step.
  • The root cause is where the failure entered: the planner never created a subtask for Poland; the handoff summary rewrote the amount.
  • The decisive error is the operational definition evaluators use: the earliest agent-and-step whose correction would have turned the failed run into a successful one. EMFA ("Error-Propagation Modeling for Failure Attribution", arXiv 2610.11600, October 2026) states it in exactly these terms, and Who&When's annotators labelled the "decisive error step" the same way.

Errors move through a multi-agent system in three ways, and each one fools a naive reader of the trace differently:

  • Propagation: one agent's wrong output becomes the next agent's input, so the error appears in every later step. The last agent that repeats it looks guilty.
  • Amplification: agents build on each other's mistakes. Kim et al.'s controlled study ("Towards a Science of Scaling Agent Systems", arXiv 2512.08296, version 3, April 2026) measured trace-level error amplification relative to a single agent in its overhead table: 17.2× for independent agents, 7.8× decentralised, 5.1× hybrid and 4.4× centralised. The abstract of version 3 no longer quotes these multipliers; they remain in the body table. Treat them as numbers for that study's benchmarks, and note the direction: architectures with a central verifier contain errors better.
  • Masking: a later agent hides the error, so the run succeeds by luck this time and fails next time, or a verifier "fixes" a symptom while the cause stays. Masking is why one failed run is weak evidence and why Part 4 replays runs several times.

4.2 What the research says about attribution#

The reference point is Who&When ("Which Agent Causes Task Failures and When?", Zhang et al., arXiv 2505.00212; ICML 2025, PMLR 267). The authors collected failure logs from 127 multi-agent systems: algorithm-generated teams (CaptainAgent on AG2 with GPT-4o, 126 tasks from GAIA and AssistantBench) and the hand-crafted Magentic-One system (58 tasks), 184 annotated failure tasks in total. Three experts labelled, for each failure, the responsible agent, the decisive error step and a reason, over three rounds; 15–30% of annotations were marked uncertain in the second round, and annotation took roughly 23–31 hours per annotator. Even careful humans find this hard.

They tested three ways of asking an LLM to attribute a failure:

  • All-at-once: give the judge the whole log and ask which agent and which step.
  • Step-by-step: walk the log forward, asking at each step whether this is the decisive error, and stop at the first yes.
  • Binary search: ask which half of the log contains the error, then recurse.

The abstract's headline is that the best method reached 53.5% accuracy at identifying the responsible agent and 14.2% at the decisive step, some methods scored below random, and reasoning models (OpenAI o1, DeepSeek R1) were not consistently better. The per-subset numbers with GPT-4o as the judge (Table 1 of the paper; "with ground truth" means the judge was told the task's correct final answer):

Method Metric Algorithm-generated, with GT Hand-crafted, with GT Algorithm-generated, without GT Hand-crafted, without GT
Random Agent 29.10 12.00 29.10 12.00
Random Step 19.06 4.16 19.06 4.16
All-at-once Agent 54.33 55.17 51.12 53.44
All-at-once Step 12.50 5.26 13.53 3.51
Step-by-step Agent 35.20 34.48 26.02 32.75
Step-by-step Step 25.51 7.02 15.31 8.77
Binary search Agent 44.13 51.72 30.11 36.21
Binary search Step 23.98 6.90 16.59 6.90

The patterns that generalise:

  • All-at-once is best at "which agent" in every column; step-by-step is best at "which step" in three of the four (binary search edges it on algorithm-generated logs without ground truth, 16.59 against 15.31). A hybrid (all-at-once picks the agent, then step-by-step within that agent's actions) tied all-at-once on agent accuracy (57.02) and was best at step accuracy (12.28) on the hand-crafted set, at the highest cost: about 149,177 tokens against 17,106 for all-at-once, 34,659 for binary search and 87,720 for step-by-step (the paper's Table 3).
  • Long logs defeat every method. On the long Magentic-One logs, step accuracy (3.5–8.8%) is close to random (4.16%), and step accuracy falls to near zero on logs of 93–130 steps.
  • Knowing the right answer helps only a little. Compare the "with GT" and "without GT" columns.
  • Reasoning models did not reliably help. On the hand-crafted set (averaged over the with- and without-ground-truth settings, the paper's default for this comparison), all-at-once agent/step accuracy was 54.31/4.39 for GPT-4o, 41.38/10.34 for o1 and 56.90/3.45 for R1.
  • A tolerance changes the picture. Counting a prediction within ±k steps as correct raised all-at-once step accuracy from 12.07% at ±1 to 43.10% at ±5. A step-level number without its tolerance is unreadable.

Work since then has pushed step accuracy up by intervening rather than only reading, though nothing is reliable yet. As of November 2026:

Method Source Idea Reported result (on Who&When unless stated)
A2P (Abduct, Act, Predict) arXiv 2509.10401, Sep 2025 One pass of causal reasoning: hypothesise the hidden cause, propose the minimal fix, predict whether the failure resolves Step accuracy 47.46% against 16.67% baseline (algorithm-generated) and 29.31% against 12.07% (hand-crafted)
AgenTracer arXiv 2509.03312; ICLR 2026 poster Labels failed trajectories with counterfactual replay and programmed fault injection, then trains an 8B attributor with reinforcement learning Reports that frontier reasoning models are "generally below 10%" at pinpointing agent and step; AgenTracer-8B beats Gemini-2.5-Pro and Claude-4-Sonnet by up to 18.18%
FAMAS arXiv 2509.13782, Sep 2025 Spectrum-based fault localisation from software engineering: re-run the failed task many times, score each agent and action by how often it is active in failing versus passing runs Outperforms all 12 baselines it compares
CDC-MAS arXiv 2509.08682, Sep 2025 Causal inference plus Shapley values to assign blame to agents; counterfactual simulation to check fixes Up to 36.2% step accuracy on Who&When and TRAIL
AgentLocate ("Who Broke the System?") arXiv 2607.07989; to appear at COLM 2026 Judge plus independent evaluator checks, confidence-aware aggregation, light fine-tuning The abstract gives no numbers
EMFA arXiv 2610.11600, Oct 2026 Models how errors cascade and loop; verifies hypotheses counterfactually +3.45 points (hand-crafted) and +4.40 points (algorithm-generated) over the previous best step accuracy
TraceElephant arXiv 2604.22708; ACL 2026 A benchmark with full traces and reproducible environments Full traces (inputs and context) improve attribution by up to 76% over partial ones

And one result every reader of these tables needs. "Structural Baselines Matter for Agent Failure Detection and Attribution" (Naagarajan and Streif, arXiv 2610.16661, October 2026) shows that a rule that always names the last step is correct 67–96% of the time on some labelled sets, without reading the run, because of how the labels were written; on failures where replay confirms the decisive step, the same rule falls to near chance. Failing runs are also longer, which a length-blind metric rewards. The authors recommend that automatic monitors rank runs for human review rather than replace it. The lesson for you: an attributor's accuracy means nothing until you compare it with trivial baselines on labels you trust, which is 4.7.

4.3 Rule- and contract-based attribution#

The cheapest attributor is the one you get from typed boundaries. If every agent's output passes a contract check when it is produced (a schema, a coverage rule, a range check), the earliest output that broke its contract is a strong candidate for the decisive error. 08D.3's design rule, "make every agent boundary a typed, fallible interface" (08D.3, 3.6), is what makes this possible: a status enum and a checkable payload at every edge.

rule_attributor(trace) returns the earliest agent run whose status is not ok or whose attrs["contract_ok"] is False, and abstains (returns None) when no contract fired. Examples of contracts that catch real failures:

  • Plan coverage: every entity in the question has a subtask (catches a planner that drops one).
  • Result shape: a worker's result has a value and at least one source per claim (catches empty or unsupported results).
  • Synthesis completeness: every verified finding id appears in the answer (catches a synthesiser that drops one; it is the same check as return_path's dropped results).
  • Numeric sanity: a figure is within a plausible range for its unit.

Rules are exact when they fire and silent when they don't: a worker's plausible-but-wrong figure passes every shape check. Use them first because they are free, and use the methods below for what they cannot see.

4.4 Counterfactual replay#

Counterfactual replay answers the counterfactual question directly: fix one agent's output, re-run everything after it, and see whether the outcome changes. If fixing the planner's plan turns the failure into a success, the planner made a decisive error. If fixing the synthesiser changes nothing, it did not.

The procedure, for one failed run:

  1. Enumerate candidate points in step order. Agent boundaries (each agent's output), not every token or tool call, keep the cost linear in the number of agents; candidate_points(trace) returns (agent, step) pairs from the agent runs that carry a step.
  2. Measure the baseline: replay the run with no change n_replays times and record the success rate. For a hard failure it is 0; for a flaky one it is not, and that matters in step 4.
  3. For each candidate, earliest first: replace that point's output with an oracle output (the correct one), replay everything upstream exactly as recorded, run everything downstream fresh n_replays times, and record the success rate.
  4. The replay flip rate is the success rate with the fix minus the baseline. The decisive error is the earliest point whose fix removes at least a fraction tau of the remaining failure: flip ≥ tau × (1 − baseline). With a hard failure that is simply flip ≥ tau; with a flaky one (baseline 0.6), a fix at tau = 0.5 must lift success to at least 0.8.
  5. Stop at the first decisive point (later points that also flip are missed catches, such as a verifier that should have caught the error) or, if none flips, report "no single decisive point" and move to 4.5: the run probably has two or more independent faults.
flowchart TD
    A["Failed run, recorded with CallCache"] --> B["Candidate points in step order:<br/>agent boundaries"]
    B --> C["Baseline: replay unchanged n times"]
    C --> D{"Next candidate"}
    D --> E["Upstream: replay from cache<br/>(same outputs, free)"]
    E --> F["At the point: substitute the oracle output"]
    F --> G["Downstream: run fresh n times"]
    G --> H{"Fix removes at least tau<br/>of the failure?"}
    H -- "yes" --> I["Decisive error = this point<br/>(earliest flip)"]
    H -- "no" --> D
    D -- "no candidates left" --> J["No single decisive point:<br/>suspect several faults,<br/>use Shapley credit"]

Four engineering details decide whether this works:

  • Where the oracle comes from. In order of trust: a gold annotation (the correct plan, the correct figure), a human-written fix, or a stronger model's output. A stronger model's output is a candidate correction, not ground truth; if you use one, say so in the report, because "the stronger model fixed it" and "the correct output fixed it" are different claims.
  • Replay requires recording. Upstream determinism comes from replaying the recorded model calls. 10A.8's CallCache (10A.8, 4.2) keys each call on its function, model, parameters and payload, so it does most of the work for you: upstream calls have the same payload as the recording and hit the cache, while every downstream call sees the changed output in its payload, misses, and runs live. Keep 10A.8's warning in mind: a warm cache makes repeats identical, so make sure downstream calls really are fresh, or your n_replays measure nothing.
  • How many replays. With n_replays = 5, a flip rate is measured in steps of 0.2, enough to separate "always fixes it" from "never does". Use more for flaky failures and when two candidates have similar flip rates, and report the replay count, because cost is candidates × replays.
  • Cost control. Boundaries only; stop at the first decisive point; and for long runs, search instead of scanning: replace all outputs from step k onwards with oracles to learn whether the decisive point is before or after k, then halve. That is Who&When's binary search with an intervention in place of a judgement (Exercise 3).

Two questions about a fix: sufficient and necessary. This lesson talks about fixes, because that is what an engineer acts on.

  • Fixing a point is sufficient for success when fixing it alone flips the run. That is the replay test above.
  • Fixing a point is necessary for success when the run still fails with every other point fixed and this one left broken. fix_necessity_check measures it, with the same tau rule relative to the baseline.

The causal literature (Pearl's probabilities of necessity and sufficiency; Halpern and Pearl's actual causation) talks about the fault instead, and the words swap. If fixing the fault alone flips the run, the fault is a but-for (necessary) cause of the failure. If the run fails even with everything else correct, the fault is sufficient on its own to cause it. Both framings describe the same measurements, so always say "fix" or "fault" when you use either word. When fixing a point is sufficient but not necessary for success, something else (usually a verifier) could also have rescued the run, and you have two places to invest. The demo shows exactly this.

The SystemFn seam makes all of this testable without keys: (task_id, overrides, seed) -> MASTrace, where overrides maps (agent, step) to a forced output. A scripted system implements it directly (Part 4's fixture does). A live system needs a thin adapter that routes every model call through one function; the sketch below shows the shape and is illustrative, since it needs your own orchestrator and keys. Two cautions. Record the production run you are attributing (or capture its calls into the cache from the trace), not a fresh run: a fresh run may not reproduce the failure. And ordering by step index treats parallel siblings with a larger index (worker-3 when you fix worker-2) as downstream, so they are re-sampled; that is harmless but costs replays, and recording dependency edges in the trace avoids it.

python
# live_system_fn.py — ILLUSTRATIVE: wraps YOUR orchestrator; needs keys to run.
from typing import Any, Callable

from mas_eval import MASTrace, SystemFn
from runner import CallCache, cached_call


def make_system_fn(run_system: Callable[..., MASTrace],
                   live_call: Callable[[str, list[dict]], Any],
                   cache: CallCache, *, model: str, record: bool = False) -> SystemFn:
    """run_system(task_id, call_model) must send EVERY model call through
    call_model(agent, step, messages) and return a MASTrace whose agent_run
    spans carry attrs['step']. record=True fills the cache: use it on the
    failed run you are attributing (or load that run's calls into the cache
    from its trace). Then build a second SystemFn with record=False for the
    interventions, which replays upstream calls from the cache."""

    def system(task_id: str, overrides: dict, seed: int) -> MASTrace:
        first = min((step for _, step in overrides), default=None)

        def call_model(agent: str, step: int, messages: list[dict]) -> Any:
            if (agent, step) in overrides:
                return overrides[(agent, step)]        # the oracle's output
            if record or (first is not None and step < first):
                # record mode fills the cache; replay mode reads it upstream
                return cached_call(cache, fn=f"{agent}@{step}", model=model,
                                   params={}, payload=messages,
                                   call=lambda: live_call(agent, messages))
            # downstream, or the no-fix baseline: a fresh live sample.
            # `seed` cannot make a hosted model deterministic; it only labels
            # the replay, so n_replays gives n independent samples.
            return live_call(agent, messages)

        return run_system(task_id, call_model)

    return system

4.5 Ablation and Shapley credit#

Counterfactual replay explains one run. Two related methods give suite-level credit per agent.

  • Ablation credit (ablation_credit) replaces one agent everywhere in the suite and measures the change in success rate. With mode="oracle", the agent is replaced by its oracle: "how much would a perfect version of this agent buy us?", which ranks where to invest. With mode="passthrough", it is replaced by a stub with the same interface that does nothing: "does this agent earn its place?". A verifier whose removal changes nothing is either redundant or checking the wrong thing (MAST's incorrect verification, FM-3.3). Replace rather than delete: deleting an agent usually breaks the interface and measures the crash, not the agent.
  • Shapley credit (shapley_credit) answers the question single-point replay cannot: what if two faults interact? Define v(C) as the success rate when every point in coalition C is replaced by its oracle. An agent's Shapley credit is its average marginal contribution v(C ∪ {agent}) − v(C) over all orders in which the fixes could be added. Two properties make it the right tool for interacting faults: credits are shared fairly between agents that only matter together, and they sum to v(all fixed) − v(none fixed). CDC-MAS uses Shapley values for exactly this blame split.

The cost is the catch. Exact Shapley needs every coalition: 2ⁿ of them, each replayed several times.

Agents (n) Coalitions (2ⁿ) Replays at 3 per coalition
4 16 48
6 64 192
8 256 768
12 4,096 12,288

Up to about six points, compute it exactly; beyond that, pass n_perm to sample random orders (permutation sampling), and report the number of permutations. Read Shapley credit as credit for fixing, which is what an engineering team needs to prioritise. It is not a moral judgement of "fault", and it depends on what you chose as the oracle.

4.6 LLM-judge attribution#

Sometimes you cannot replay: a production trace from a system you cannot re-run, a third-party agent, an environment you cannot reset. Then a judge reading the trace is what you have. judge_attribution(trace, judge, strategy=...) implements Who&When's three strategies over an AttribJudge seam ((question, log) -> verdict) and returns the verdict and the number of judge calls:

  • "all_at_once": one call; best at the agent; cheapest.
  • "step_by_step": up to one call per step; best at the step; the most calls, and long logs make each call long too. If the judge flags no step it abstains by default; falling back to the last step would quietly turn "found nothing" into the last-step baseline of 4.7.
  • "binary_search": about log₂(steps) calls; in between.

log_of(trace) builds what the judge reads, one row per agent output, with the agent's input as well as its output, following TraceElephant's finding. A live judge turns the question and the log into a prompt and parses a structured verdict (10A.4 owns judge prompts and 03.4 structured output). A starting prompt for the all-at-once question:

text
You are auditing a FAILED run of a multi-agent system.

Task given to the system:
{task}

Correct final answer (if known):
{ground_truth_or_"unknown"}

Run log, one row per agent output, in order. Each row has the step number,
the agent, what the agent RECEIVED, and what it PRODUCED:
{log_rows}

Find the decisive error: the EARLIEST step whose output, if it had been
correct, would most likely have let the run succeed. The agent whose output
is visibly wrong at the end is often repeating an earlier mistake; trace the
mistake back to where it first entered. If several independent errors were
each necessary for the failure, say so.

Return JSON: {"agent": "<name>", "step": <int>, "reason": "<one sentence>",
"multiple_faults": <true|false>, "confidence": "low|medium|high"}

Use a judge attributor to rank and triage failed runs for human review, to label failure modes at scale (as MAST's annotator does), and as a hypothesis generator for replay when replay is possible. Do not report its per-run verdicts as facts until you have measured its accuracy as in the next section, and expect the Who&When pattern: decent at the agent, weak at the step, worse on long logs.

4.7 Validating the attributor#

An attributor is a measuring instrument, so 10A.5's loop applies unchanged: build a labelled set, measure agreement, compare against baselines, read the disagreements.

  1. Gold labels. Sample failed runs, stratified by task type and run length. Have at least two people label the decisive agent, step and MAST mode independently; compute Cohen's kappa on the agent labels and report it, since Who&When's experts marked 15–30% of their labels uncertain in the second annotation round. Where you can replay, prefer replay-confirmed labels: the human proposes, replay confirms. Naagarajan and Streif's result is the reason.
  2. Accuracy with intervals. attribution_accuracy(pred, gold, tolerance=k) reports agent accuracy and step accuracy within ±k steps, each with a Wilson interval, and counts abstentions separately. Always report k = 0 and one small k.
  3. Trivial baselines, always. last_step_attributor, first_step_attributor and random_attributor cost nothing. An attributor that does not clearly beat "always the last step" on your labels is measuring your label-writing habits, not your system.
  4. Fault injection as a positive control. Plant known faults (drop a field from a handoff, corrupt one worker's figure, make the planner skip a subtask, make the verifier approve everything) and check that the attributor finds each one at the planted point. AgenTracer's programmed fault injection is the published precedent; it is the multi-agent version of 10A.5's canary judgements and 10A.7's grader self-tests.
  5. Read the disagreements. Where the attributor and the humans disagree, read the trace: often the attributor found a real second fault, and the label set needs a "multiple faults" option.

4.8 Reporting where failures come from#

The output of attribution is a distribution, not a list of verdicts: what share of failed runs trace back to each agent, and to each failure mode. attribution_report(attrib, modes=...) reports counts, shares and Wilson intervals per agent, plus counts per mode (MAST codes or your own). Three habits keep it honest:

  • Report counts next to shares. "40% of failures come from the planner" is 4 of 10 runs, with an interval from about 17% to 69%.
  • Keep "unattributed" as its own row. Runs with no single decisive point are a finding (several interacting faults), not noise to drop.
  • Cross the two axes. Agent × mode is where action lives: "planner, disobeys task specification" means fix the planning prompt or add a coverage contract; "worker-2, incorrect verification downstream" means fix the verifier, not the worker.

4.9 mas_eval.py, section 3: attribution#

python
# ---------------------------------------------------------------------------
# evalkit/mas_eval.py, section 3 of 5 (append after section 2)
# 3. Failure attribution
# ---------------------------------------------------------------------------

SystemFn = Callable[[str, dict, int], MASTrace]
"""(task_id, overrides, seed) -> MASTrace. overrides maps (agent, step) to a
forced output for that point. The system must be replayable: same seed and
same overrides give the same trace (record/replay with runner.CallCache for a
live system; ScriptedModel for a fake). The seam only injects overrides."""

OracleFn = Callable[[str, str, int], Any]
"""(task_id, agent, step) -> the correct output at that point: a gold
annotation, a human-written fix, or a stronger model's output."""

PASSTHROUGH = "__passthrough__"   # override meaning "this agent does nothing"


def candidate_points(trace: MASTrace) -> list[tuple[str, int]]:
    """Agent boundaries in step order: every agent_run that produced an
    output carries attrs['step']. Boundaries, not every token, keep replay
    cost linear in the number of agent outputs."""
    pts = sorted((s.attrs["step"], s.agent) for s in trace.spans
                 if s.kind == "agent_run" and "step" in s.attrs)
    return [(a, st) for st, a in pts]


def _success_rate(system: SystemFn, task_id: str, overrides: dict,
                  n: int, seed: int) -> float:
    return sum(bool(system(task_id, overrides, seed + r).success) for r in range(n)) / n


def counterfactual_attribution(task_id: str, system: SystemFn, oracle: OracleFn,
                               candidates: list[tuple[str, int]], *,
                               n_replays: int = 5, tau: float = 0.5, seed: int = 0,
                               stop_at_first: bool = True) -> dict:
    """Replace one point's output with the oracle's, replay downstream
    n_replays times, and measure the replay flip rate:

        flip(a, s) = P(success | fix (a, s)) - P(success | no fix)

    The decisive error is the EARLIEST point whose fix removes at least `tau`
    of the remaining failure probability: flip >= tau * (1 - base). (With a
    hard failure, base = 0 and that is simply flip >= tau; with a flaky one,
    base = 0.6, a fix must lift success to at least 0.8 at tau = 0.5.)
    Later points that also flip are missed catches (a verifier that should
    have caught it), not the origin. No single point flipping is a finding
    too: suspect two or more independent faults (use shapley_credit).
    """
    base = _success_rate(system, task_id, {}, n_replays, seed)
    flips, decisive, used = [], None, n_replays
    for a, s in candidates:
        rate = _success_rate(system, task_id, {(a, s): oracle(task_id, a, s)},
                             n_replays, seed)
        used += n_replays
        flips.append({"agent": a, "step": s, "success_rate": rate,
                      "flip_rate": round(rate - base, 3)})
        if decisive is None and base < 1 and rate - base >= tau * (1 - base):
            decisive = (a, s)
            if stop_at_first:
                break
    return {"task": task_id, "baseline_success": base, "flips": flips,
            "decisive": decisive, "replays_used": used}


def fix_necessity_check(task_id: str, system: SystemFn, oracle: OracleFn,
                        point: tuple[str, int], candidates: list[tuple[str, int]], *,
                        n_replays: int = 5, tau: float = 0.5, seed: int = 0) -> dict:
    """Fix every candidate EXCEPT `point` and replay. If the run still fails
    (the other fixes do not remove at least tau of the failure, the same rule
    as counterfactual_attribution), fixing `point` is NECESSARY for success:
    in causal terms the fault alone is sufficient to cause the failure. If
    the run now succeeds, something else (usually a verifier) can recover, so
    fixing `point` is not the only remedy.

    Mind the direction of the words: the replay test in
    counterfactual_attribution shows that fixing a point is SUFFICIENT for
    success, which makes the fault a but-for (necessary) cause of the
    failure. Say "fix" or "fault" every time you use them."""
    base = _success_rate(system, task_id, {}, n_replays, seed)
    others = {(a, s): oracle(task_id, a, s) for a, s in candidates if (a, s) != point}
    rate = _success_rate(system, task_id, others, n_replays, seed)
    recovered = base < 1 and rate - base >= tau * (1 - base)
    return {"point": point, "baseline_success": base,
            "success_with_others_fixed": rate, "fix_necessary": not recovered}


def ablation_credit(task_ids: list[str], system: SystemFn, oracle: OracleFn,
                    agents: list[str], *, mode: str = "oracle",
                    n_replays: int = 3, seed: int = 0) -> dict[str, dict]:
    """Suite-level credit per agent: success with the agent replaced by its
    oracle (mode="oracle": how much would fixing it buy?) or by a pass-through
    stub with the same interface (mode="passthrough": does it earn its place?).
    delta = with - base, averaged over tasks."""
    out: dict[str, dict] = {}
    base_rates = {t: _success_rate(system, t, {}, n_replays, seed) for t in task_ids}
    for agent in agents:
        rates = []
        for t in task_ids:
            pts = [p for p in candidate_points(system(t, {}, seed)) if p[0] == agent]
            ov = {p: (oracle(t, *p) if mode == "oracle" else PASSTHROUGH) for p in pts}
            rates.append(_success_rate(system, t, ov, n_replays, seed))
        base = statistics.fmean(base_rates.values())
        out[agent] = {"base": round(base, 3), "with": round(statistics.fmean(rates), 3),
                      "delta": round(statistics.fmean(rates) - base, 3)}
    return out


def shapley_credit(task_id: str, system: SystemFn, oracle: OracleFn,
                   points: list[tuple[str, int]], *, n_replays: int = 3,
                   n_perm: int | None = None, seed: int = 0) -> dict:
    """Shapley credit for FIXING each point: v(C) = success rate when every
    point in coalition C is replaced by its oracle output. Exact over 2^n
    coalitions when n_perm is None; permutation sampling otherwise. The
    credits sum to v(all fixed) - v(none fixed) (the efficiency property)."""
    cache: dict[frozenset, float] = {}

    def v(coal: frozenset) -> float:
        if coal not in cache:
            ov = {p: oracle(task_id, *p) for p in coal}
            cache[coal] = _success_rate(system, task_id, ov, n_replays, seed)
        return cache[coal]

    n = len(points)
    phi = {p: 0.0 for p in points}
    if n_perm is None:
        for p in points:
            rest = [q for q in points if q != p]
            for k in range(n):
                w = math.factorial(k) * math.factorial(n - k - 1) / math.factorial(n)
                for c in itertools.combinations(rest, k):
                    cs = frozenset(c)
                    phi[p] += w * (v(cs | {p}) - v(cs))
    else:
        rng = random.Random(seed)
        for _ in range(n_perm):
            order = points[:]
            rng.shuffle(order)
            cs: frozenset = frozenset()
            for p in order:
                phi[p] += (v(cs | {p}) - v(cs)) / n_perm
                cs = cs | {p}
    return {"credit": {f"{a}@{s}": round(x, 3) for (a, s), x in phi.items()},
            "v_none": v(frozenset()), "v_all": v(frozenset(points)),
            "coalitions_evaluated": len(cache), "replays_used": len(cache) * n_replays}


# -- judge-based attribution (Who&When's three strategies, behind a seam) -----

AttribJudge = Callable[[str, list[dict]], dict]
"""(question, log) -> parsed verdict. question is one of
     "who_and_when"            -> {"agent": str, "step": int}
     "is_error:<k>"            -> {"error": bool}   (log = steps 0..k)
     "in_first_half:<lo>:<hi>" -> {"first": bool}   (log = steps lo..hi)
A live judge builds a prompt from the question and log and parses structured
output (10A.4); validate it on human labels (10A.5) before trusting it."""


def log_of(trace: MASTrace) -> list[dict]:
    """The step log a judge reads: one row per agent output, in order. Include
    inputs, not only outputs — TraceElephant (ACL 2026) found full traces
    improve attribution accuracy by up to 76% over outputs alone."""
    rows = sorted((s for s in trace.spans if s.kind == "agent_run" and "step" in s.attrs),
                  key=lambda s: s.attrs["step"])
    return [{"step": s.attrs["step"], "agent": s.agent,
             "input": s.attrs.get("input", ""), "output": s.attrs.get("output", "")}
            for s in rows]


def judge_attribution(trace: MASTrace, judge: AttribJudge, *,
                      strategy: str = "all_at_once", fallback: str = "abstain") -> dict:
    """all_at_once: one call over the whole log. step_by_step: walk forward,
    stop at the first step the judge flags; if it flags none, ABSTAIN by
    default (fallback="last" would quietly turn "found nothing" into the
    last-step baseline). binary_search: halve the range the judge says holds
    the error. Returns the verdict and the call count."""
    log = log_of(trace)
    if not log:
        return {"agent": None, "step": None, "calls": 0}
    if strategy == "all_at_once":
        v = judge("who_and_when", log)
        return {"agent": v.get("agent"), "step": v.get("step"), "calls": 1}
    if strategy == "step_by_step":
        for k, row in enumerate(log):
            if judge(f"is_error:{k}", log[:k + 1]).get("error"):
                return {"agent": row["agent"], "step": row["step"], "calls": k + 1}
        if fallback == "last":
            return {"agent": log[-1]["agent"], "step": log[-1]["step"], "calls": len(log)}
        return {"agent": None, "step": None, "calls": len(log)}
    if strategy == "binary_search":
        lo, hi, calls = 0, len(log) - 1, 0
        while lo < hi:
            mid = (lo + hi) // 2
            calls += 1
            if judge(f"in_first_half:{lo}:{mid}", log[lo:hi + 1]).get("first"):
                hi = mid
            else:
                lo = mid + 1
        return {"agent": log[lo]["agent"], "step": log[lo]["step"], "calls": calls}
    raise ValueError(f"unknown strategy {strategy!r}")


# -- trivial baselines and accuracy -------------------------------------------

def last_step_attributor(trace: MASTrace) -> tuple[str, int]:
    pts = candidate_points(trace)
    return pts[-1] if pts else ("?", -1)


def first_step_attributor(trace: MASTrace) -> tuple[str, int]:
    pts = candidate_points(trace)
    return pts[0] if pts else ("?", -1)


def random_attributor(trace: MASTrace, seed: int = 0) -> tuple[str, int]:
    pts = candidate_points(trace)
    return random.Random(f"{trace.trace_id}:{seed}").choice(pts) if pts else ("?", -1)


def rule_attributor(trace: MASTrace, *,
                    violated: Callable[[AgentSpan], bool] | None = None
                    ) -> tuple[str, int] | None:
    """Earliest agent output that broke a checkable contract: a non-ok status
    or a failed schema/contract check recorded as attrs['contract_ok']=False.
    Cheap and exact when contracts are typed (08D.3 3.6); silent otherwise."""
    violated = violated or (lambda s: s.status != "ok"
                            or s.attrs.get("contract_ok") is False)
    for s in sorted((s for s in trace.spans if s.kind == "agent_run" and "step" in s.attrs),
                    key=lambda s: s.attrs["step"]):
        if violated(s):
            return (s.agent, s.attrs["step"])
    return None


def attribution_accuracy(pred: dict[str, tuple[str, int] | None],
                         gold: dict[str, tuple[str, int]], *,
                         tolerance: int = 0) -> dict:
    """Agent-level and step-level accuracy over the failed runs both sides
    labelled, as Who&When defines them: the agent must match; the step index
    must fall within ±tolerance (steps are global, so step 0 = first output).
    Abstentions (None) count as wrong and are reported separately. Wilson
    95% intervals on both."""
    ids = sorted(set(gold) & set(pred))
    pred = {i: (None if pred[i] is None or pred[i][0] is None else pred[i]) for i in ids}
    abst = sum(pred[i] is None for i in ids)
    ag = sum(pred[i] is not None and pred[i][0] == gold[i][0] for i in ids)
    st = sum(pred[i] is not None and abs(pred[i][1] - gold[i][1]) <= tolerance
             for i in ids)
    n = len(ids)
    return {"n": n, "abstained": abst,
            "agent_acc": ag / n if n else float("nan"), "agent_ci": wilson_interval(ag, n),
            "step_acc": st / n if n else float("nan"), "step_ci": wilson_interval(st, n)}


def attribution_report(attrib: dict[str, tuple[str, int] | None],
                       modes: dict[str, str] | None = None) -> dict:
    """Where failures come from: share of failed runs per agent and per
    failure mode (e.g. MAST codes), with Wilson intervals. Small n: read the
    counts, not just the percentages."""
    n = len(attrib)
    by_agent = Counter(p[0] if p else "unattributed" for p in attrib.values())
    out = {"n": n, "by_agent": {a: {"count": c, "share": round(c / n, 3),
                                    "ci": tuple(round(x, 3) for x in wilson_interval(c, n))}
                                for a, c in by_agent.most_common()}}
    if modes:
        by_mode = Counter(modes.get(t, "unlabelled") for t in attrib)
        out["by_mode"] = {m: {"count": c, "share": round(c / n, 3)}
                          for m, c in by_mode.most_common()}
    return out

4.10 The research-pipeline fixture#

Fixture B is a small research system in 08D.3's vocabulary: a planner splits "grant levels for Germany, France and Poland" into subtasks, three workers search in parallel, a verifier checks their figures and can re-delegate a flagged subtask once, and a synthesiser writes the answer. The run succeeds only if the answer contains all three correct figures. The system is a pure SystemFn: same task, overrides and seed give the same trace, and the synthesiser drops a finding 3% of the time so that replays are not trivially identical. Sixteen tasks, with planted faults:

Fault Tasks Planted root cause What should find it
Plan omission R01, R05, R14 The planner skips Poland Replay: planner; contract: plan coverage
Worker error, format-only verifier R02, R06 Worker-2's figure is wrong; the verifier checks format, not values Replay: worker-2
Worker error, format-only verifier R16 Worker-1's figure is wrong Replay: worker-1
Two independent faults R03, R07 Worker-1 and worker-3 both wrong No single point; Shapley splits credit
Synthesis drop R04, R13 The synthesiser always drops France Replay: synthesiser; contract: completeness
Caught but not fixed R09 Worker-2 wrong; a truthful verifier flags it; the retry succeeds half the time Replay: worker-2 (a flaky failure)
Overhead only R10, R11 A slow worker; two workers repeating one search Part 5
None R08, R12, R15 Controls Nothing

The gold labels are the planted root causes (for two-fault runs, the earliest one, which is what a human annotator would usually write). The judge row uses a stand-in judge with a planted 50% accuracy, because no model runs here; it exercises the three strategies' plumbing and call counts, and says nothing about any real model.

python
# ===========================================================================
# mas_eval_demo.py, section 3 of 5 (append after section 2)
# Part 4 — Fixture B: a research pipeline with planted root causes
# ===========================================================================

AGENTS = ["planner", "worker-1", "worker-2", "worker-3", "verifier", "synthesiser"]
STEP = {a: i for i, a in enumerate(AGENTS)}
SUBTASKS = ["DE", "FR", "PL"]
FAULTS = {   # task -> planted fault; the verifier is format-only where noted
    "R01": "plan_omit", "R02": "worker2_wrong", "R03": "two_faults", "R04": "synth_drop",
    "R05": "plan_omit", "R06": "worker2_wrong", "R07": "two_faults", "R08": None,
    "R09": "worker2_wrong_caught", "R10": None, "R11": None, "R12": None,
    "R13": "synth_drop", "R14": "plan_omit", "R15": None, "R16": "worker1_wrong",
}
FORMAT_ONLY = {"worker2_wrong", "two_faults", "worker1_wrong"}
GOLD_DECISIVE = {"plan_omit": ("planner", 0), "worker2_wrong": ("worker-2", 2),
                 "worker2_wrong_caught": ("worker-2", 2), "worker1_wrong": ("worker-1", 1),
                 "two_faults": ("worker-1", 1), "synth_drop": ("synthesiser", 5)}
MAST_MODE = {"plan_omit": "FM-1.1 disobey task specification",
             "worker2_wrong": "FM-3.3 incorrect verification",
             "worker1_wrong": "FM-3.3 incorrect verification",
             "worker2_wrong_caught": "other: worker error, retry failed",
             "two_faults": "FM-3.3 incorrect verification",
             "synth_drop": "FM-2.5 ignored other agent's input"}


def gold_figure(task: str, sub: str) -> int:
    return 1000 + int(_h(task, sub), 16) % 9000


def oracle(task: str, agent: str, step: int):
    """The correct output at each point (the fixture's gold)."""
    if agent == "planner":
        return list(SUBTASKS)
    if agent.startswith("worker-"):
        sub = SUBTASKS[int(agent[-1]) - 1]
        return {sub: gold_figure(task, sub)}
    return "truthful" if agent == "verifier" else "exact"


def research_system(task: str, overrides: dict, seed: int, *,
                    faults: dict[str, str | None] = FAULTS) -> MASTrace:
    """Scripted orchestrator: planner -> 3 parallel workers -> verifier
    (may re-delegate) -> synthesiser. Replayable: same task, overrides and
    seed give the same trace. `overrides` maps (agent, step) to an output."""
    fault = faults[task]
    rng = random.Random(f"{task}:{seed}")
    t = MASTrace(trace_id=f"{task}:{seed}:{_h(sorted(map(str, overrides.items())))}",
                 task_id=task, system="research-mas@v3")
    t.spans.append(AgentSpan("root", None, "orchestrator", "agent_run", 0.0, 0.0))
    clock = 0.0

    def agent_run(agent: str, start: float, secs: float, calls: list[tuple[int, int]],
                  role: str, output, inp: str, tools: list[str] = ()) -> AgentSpan:
        sid = f"{agent}-run"
        sp = AgentSpan(sid, "root", agent, "agent_run", start, start + secs,
                       attrs={"step": STEP[agent], "output": output, "input": inp})
        t.spans.append(sp)
        dt = secs / (len(calls) + len(tools) or 1)
        cur = start
        for j, q in enumerate(tools):
            t.spans.append(AgentSpan(f"{sid}-tool{j}", sid, agent, "tool_call", cur, cur + dt,
                                     attrs={"tool": "web_search", "args_hash": _h(q)}))
            cur += dt
        for j, (tin, tout) in enumerate(calls):
            t.spans.append(AgentSpan(f"{sid}-llm{j}", sid, agent, "model_call", cur, cur + dt,
                                     role=role, tokens_in=tin, tokens_out=tout,
                                     cost_usd=tin * IN_PRICE + tout * OUT_PRICE))
            cur += dt
        return sp

    def ov(agent: str, default):
        return overrides.get((agent, STEP[agent]), default)

    # 1. planner
    plan = list(SUBTASKS) if fault not in ("plan_omit",) else SUBTASKS[:2]
    plan = ov("planner", plan)
    if plan == PASSTHROUGH:
        plan = SUBTASKS[:1]
    sp = agent_run("planner", clock, 1.5, [(2400, 420)], "coordination", plan,
                   "question: grant levels for DE, FR, PL")
    sp.attrs["contract_ok"] = set(SUBTASKS) <= set(plan)   # code check: plan covers the question
    clock = 1.6
    # 2. workers in parallel
    findings: dict[str, int] = {}
    ends = []
    for i, sub in enumerate(plan[:3], start=1):
        w = f"worker-{i}"
        t.spans.append(AgentSpan(f"del-{w}", "root", "planner", "delegation", clock, clock,
                                 role="coordination", attrs={"to": w, "subtask": sub}))
        val = gold_figure(task, sub)
        if (fault in ("worker2_wrong", "worker2_wrong_caught") and i == 2) or \
           (fault == "two_faults" and i in (1, 3)) or (fault == "worker1_wrong" and i == 1):
            val += 400                                   # a plausible wrong figure
        out = ov(w, {sub: val})
        if out == PASSTHROUGH:
            out = {}
        secs = 9.0 if (task == "R10" and i == 3) else 2.0 + 0.3 * i
        query = f"{sub} heat pump grant 2026" if not (task == "R11" and i == 2) \
            else f"{plan[0]} heat pump grant 2026"         # R11: worker-2 repeats worker-1's search
        agent_run(w, clock, secs, [(3000, 300), (5200, 480)], "work", out,
                  f"brief: grant level for {sub}", tools=[query])
        findings.update(out)
        ends.append(clock + secs)
    clock = max(ends) + 0.1
    # 3. verifier (truthful checks figures against a reference; format-only doesn't)
    mode = "format_only" if fault in FORMAT_ONLY else "truthful"
    mode = ov("verifier", mode)
    flagged = [s for s, v in findings.items() if v != gold_figure(task, s)] \
        if mode == "truthful" else []
    agent_run("verifier", clock, 1.0, [(4200, 200)], "coordination",
              {"mode": mode if mode != PASSTHROUGH else "skipped", "flagged": flagged},
              f"findings: {findings}")
    clock += 1.0
    for s in flagged:                                     # re-delegate flagged subtasks once
        w = f"worker-{SUBTASKS.index(s) + 1}"
        fixed = rng.random() < 0.5
        if fixed:
            findings[s] = gold_figure(task, s)
        t.spans.append(AgentSpan(f"retry-{w}", "root", w, "model_call", clock, clock + 2.0,
                                 tokens_in=5200, tokens_out=480, attrs={"retry": True},
                                 cost_usd=5200 * IN_PRICE + 480 * OUT_PRICE,
                                 status="ok" if fixed else "error"))
        clock += 2.0
    # 4. synthesiser: "faithful" drops a finding 3% of the time (noise),
    #    "drops_FR" is the planted fault (R04, R13), "exact" is the oracle.
    style = ov("synthesiser", "drops_FR" if fault == "synth_drop" else "faithful")
    kept = {}
    for s, v in sorted(findings.items()):
        if (style == "drops_FR" and s == "FR") or (style == "faithful" and rng.random() < 0.03):
            continue
        kept[s] = v
    answer = "; ".join(f"{s}: EUR {v}" for s, v in sorted(kept.items()))
    sp = agent_run("synthesiser", clock, 1.5, [(6000, 700)], "coordination", answer,
                   f"verified findings: {findings}")
    sp.attrs["contract_ok"] = kept == findings           # code check: nothing dropped
    clock += 1.5
    t.spans[0].end_s = clock
    t.final_answer = answer
    t.success = all(f"{s}: EUR {gold_figure(task, s)}" in answer for s in SUBTASKS)
    return t


class NoisyOracleJudge:
    """A STAND-IN for an LLM attribution judge with a planted accuracy: it
    knows the gold step but answers correctly only with probability
    `accuracy`, else names the last step. Real judge accuracy must be
    measured (Who&When); this only exercises the strategies' plumbing."""

    def __init__(self, gold: dict[str, tuple[str, int]], accuracy: float, seed: int = 0):
        self.gold, self.acc, self.seed, self.task = gold, accuracy, seed, ""

    def __call__(self, question: str, log: list[dict]) -> dict:
        g = self.gold[self.task]
        right = random.Random(f"{self.task}:{question}:{self.seed}").random() < self.acc
        if question == "who_and_when":
            return {"agent": g[0], "step": g[1]} if right else \
                {"agent": log[-1]["agent"], "step": log[-1]["step"]}
        if question.startswith("is_error:"):
            k = log[-1]["step"]
            return {"error": (k == g[1]) if right else k == 5}
        lo, mid = map(int, question.split(":")[1:])
        steps = [r["step"] for r in log]
        first = g[1] in steps[: mid - lo + 1]
        return {"first": first if right else False}


def demo_attribution() -> None:
    runs = {t: research_system(t, {}, seed=0) for t in FAULTS}
    failed = {t: r for t, r in runs.items() if not r.success}
    print(f"suite: {len(runs)} tasks, {len(failed)} failed at seed 0: {sorted(failed)}")

    print("counterfactual replay (earliest point whose fix flips the outcome):")
    cf_pred, total_replays = {}, 0
    for t, tr in failed.items():
        res = counterfactual_attribution(t, research_system, oracle, candidate_points(tr),
                                         n_replays=5, tau=0.5)
        cf_pred[t] = res["decisive"]
        total_replays += res["replays_used"]
        flips = " ".join(f"{f['agent']}@{f['step']}:{f['flip_rate']:+.1f}" for f in res["flips"])
        print(f"  {t} ({FAULTS[t]}): base={res['baseline_success']:.1f} -> "
              f"decisive={res['decisive']}  [{flips}]")
    print(f"  replays used: {total_replays}")

    nc = fix_necessity_check("R02", research_system, oracle, ("worker-2", 2),
                             candidate_points(runs["R02"]))
    print(f"fix necessity R02 worker-2: success with every OTHER point fixed = "
          f"{nc['success_with_others_fixed']:.1f} (baseline {nc['baseline_success']:.1f}) "
          f"-> fixing worker-2 necessary={nc['fix_necessary']}")

    sh = shapley_credit("R03", research_system, oracle, candidate_points(runs["R03"]),
                        n_replays=4)
    print(f"shapley R03 (two faults): {sh['credit']}")
    print(f"  v(none)={sh['v_none']:.2f} v(all)={sh['v_all']:.2f} "
          f"coalitions={sh['coalitions_evaluated']} replays={sh['replays_used']}")

    ab = ablation_credit(sorted(FAULTS), research_system, oracle, ["verifier"],
                         mode="passthrough", n_replays=3)
    print(f"ablation (verifier -> pass-through), whole suite: {ab}")
    ab2 = ablation_credit(sorted(FAULTS), research_system, oracle, AGENTS,
                          mode="oracle", n_replays=3)
    print("ablation (agent -> oracle), whole suite:",
          {a: v["delta"] for a, v in ab2.items()})

    gold = {t: GOLD_DECISIVE[FAULTS[t]] for t in failed}
    preds: dict[str, dict] = {"counterfactual": cf_pred}
    preds["rule (contract)"] = {t: rule_attributor(tr) for t, tr in failed.items()}
    preds["baseline: last step"] = {t: last_step_attributor(tr) for t, tr in failed.items()}
    preds["baseline: first step"] = {t: first_step_attributor(tr) for t, tr in failed.items()}
    preds["baseline: random"] = {t: random_attributor(tr) for t, tr in failed.items()}
    print(f"attributor accuracy on {len(failed)} failed runs (gold = planted root cause):")

    def show(name: str, p: dict) -> None:
        a0 = attribution_accuracy(p, gold, tolerance=0)
        a1 = attribution_accuracy(p, gold, tolerance=1)
        print(f"  {name:22s} agent={a0['agent_acc']:.2f} (CI {a0['agent_ci'][0]:.2f}-"
              f"{a0['agent_ci'][1]:.2f})  step={a0['step_acc']:.2f}  "
              f"step±1={a1['step_acc']:.2f}  abstained={a0['abstained']}")

    for name, p in preds.items():
        show(name, p)
    print("judge strategies (STAND-IN judge with a planted 50% accuracy: this checks the")
    print("plumbing and the call counts, not any model):")
    judge = NoisyOracleJudge(gold, accuracy=0.5)
    for strategy in ("all_at_once", "step_by_step", "binary_search"):
        p, calls = {}, 0
        for t, tr in failed.items():
            judge.task = t
            v = judge_attribution(tr, judge, strategy=strategy)
            p[t], calls = (v["agent"], v["step"]), calls + v["calls"]
        show(f"judge:{strategy} ({calls} calls)", p)
    rep = attribution_report(cf_pred, modes={t: MAST_MODE[FAULTS[t]] for t in failed})
    print("where failures come from (counterfactual):")
    for a, v in rep["by_agent"].items():
        print(f"  {a:13s} {v['count']}  share={v['share']:.2f}  CI {v['ci']}")
    for m, v in rep["by_mode"].items():
        print(f"  {m:36s} {v['count']}")

Run it with python3 mas_eval_demo.py attribution.

Output41 lines
=== attribution ===
suite: 16 tasks, 11 failed at seed 0: ['R01', 'R02', 'R03', 'R04', 'R05', 'R06', 'R07', 'R09', 'R13', 'R14', 'R16']
counterfactual replay (earliest point whose fix flips the outcome):
  R01 (plan_omit): base=0.0 -> decisive=('planner', 0)  [planner@0:+1.0]
  R02 (worker2_wrong): base=0.0 -> decisive=('worker-2', 2)  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+1.0]
  R03 (two_faults): base=0.0 -> decisive=None  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+0.0 worker-3@3:+0.0 verifier@4:+0.2 synthesiser@5:+0.0]
  R04 (synth_drop): base=0.0 -> decisive=('synthesiser', 5)  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+0.0 worker-3@3:+0.0 verifier@4:+0.0 synthesiser@5:+1.0]
  R05 (plan_omit): base=0.0 -> decisive=('planner', 0)  [planner@0:+1.0]
  R06 (worker2_wrong): base=0.0 -> decisive=('worker-2', 2)  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+1.0]
  R07 (two_faults): base=0.0 -> decisive=None  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+0.0 worker-3@3:+0.0 verifier@4:+0.4 synthesiser@5:+0.0]
  R09 (worker2_wrong_caught): base=0.6 -> decisive=('worker-2', 2)  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+0.4]
  R13 (synth_drop): base=0.0 -> decisive=('synthesiser', 5)  [planner@0:+0.0 worker-1@1:+0.0 worker-2@2:+0.0 worker-3@3:+0.0 verifier@4:+0.0 synthesiser@5:+1.0]
  R14 (plan_omit): base=0.0 -> decisive=('planner', 0)  [planner@0:+1.0]
  R16 (worker1_wrong): base=0.0 -> decisive=('worker-1', 1)  [planner@0:+0.0 worker-1@1:+0.8]
  replays used: 245
fix necessity R02 worker-2: success with every OTHER point fixed = 0.6 (baseline 0.0) -> fixing worker-2 necessary=False
shapley R03 (two faults): {'planner@0': 0.0, 'worker-1@1': 0.354, 'worker-2@2': 0.0, 'worker-3@3': 0.354, 'verifier@4': 0.229, 'synthesiser@5': 0.062}
  v(none)=0.00 v(all)=1.00 coalitions=64 replays=256
ablation (verifier -> pass-through), whole suite: {'verifier': {'base': 0.333, 'with': 0.312, 'delta': -0.021}}
ablation (agent -> oracle), whole suite: {'planner': 0.188, 'worker-1': 0.062, 'worker-2': 0.167, 'worker-3': 0.0, 'verifier': 0.146, 'synthesiser': 0.125}
attributor accuracy on 11 failed runs (gold = planted root cause):
  counterfactual         agent=0.82 (CI 0.52-0.95)  step=0.82  step±1=0.82  abstained=2
  rule (contract)        agent=0.45 (CI 0.21-0.72)  step=0.45  step±1=0.45  abstained=6
  baseline: last step    agent=0.18 (CI 0.05-0.48)  step=0.18  step±1=0.18  abstained=0
  baseline: first step   agent=0.27 (CI 0.10-0.57)  step=0.27  step±1=0.55  abstained=0
  baseline: random       agent=0.09 (CI 0.02-0.38)  step=0.09  step±1=0.09  abstained=0
judge strategies (STAND-IN judge with a planted 50% accuracy: this checks the
plumbing and the call counts, not any model):
  judge:all_at_once (11 calls) agent=0.64 (CI 0.35-0.85)  step=0.64  step±1=0.64  abstained=0
  judge:step_by_step (47 calls) agent=0.55 (CI 0.28-0.79)  step=0.55  step±1=0.55  abstained=3
  judge:binary_search (23 calls) agent=0.36 (CI 0.15-0.65)  step=0.36  step±1=0.45  abstained=0
where failures come from (counterfactual):
  planner       3  share=0.27  CI (0.097, 0.566)
  worker-2      3  share=0.27  CI (0.097, 0.566)
  unattributed  2  share=0.18  CI (0.051, 0.477)
  synthesiser   2  share=0.18  CI (0.051, 0.477)
  worker-1      1  share=0.09  CI (0.016, 0.377)
  FM-3.3 incorrect verification        5
  FM-1.1 disobey task specification    3
  FM-2.5 ignored other agent's input   2
  other: worker error, retry failed    1

How to read it:

  • Replay found every single-fault root cause. The plan omissions point at the planner at step 0 with a flip of +1.0; the worker errors point at the worker, not at the synthesiser that displayed the wrong number. R09, the flaky failure (baseline 0.6), is attributed to worker-2 because the fix lifts success to 1.0, which removes all of the remaining failure even though the raw flip is only +0.4. That is the reason the rule is relative to the baseline.
  • The two-fault runs have no decisive point, correctly. No single fix flips R03 or R07; only the verifier comes near (+0.2 and +0.4), because a truthful verifier would catch both errors and the re-delegation sometimes repairs them. Shapley credit on R03 splits the blame evenly between worker-1 and worker-3 (0.354 each), gives the verifier 0.229 for the recovery it could have provided, and the credits sum to v(all) − v(none) = 1.0. The synthesiser's small 0.062 is its 3% random drop showing through.
  • Fix necessity: fixing worker-2 is sufficient for success in R02 but not necessary. With every other point fixed, including a truthful verifier, the run succeeds 60% of the time, which clears the tau rule from a baseline of 0. In causal terms, worker-2's error is a but-for cause of this failure but not sufficient on its own to cause it. The worker made the error, and the verifier is a second place to fix it.
  • Ablation shows the verifier earning almost nothing on this suite: replacing it with a pass-through changes the success rate by −0.021. That is the signature of a verifier that checks the wrong thing. The oracle ablation ranks where perfect agents would pay: planner (+0.188), worker-2 (+0.167), verifier (+0.146).
  • The accuracy table is the most important block. Replay is right on 9 of 11 failed runs (0.82) and abstains on the two runs that genuinely have two faults. The contract rule is right whenever a contract fires (5 of 11) and abstains on the rest. The "last step" baseline scores 0.18, because only the synthesis drops really are last-step faults. On this fixture the baseline is weak; Naagarajan and Streif show that on some real labelled sets it is very strong, which is why you run it on your labels.
  • The judge strategies used 11, 47 and 23 calls for the same 11 runs, and step-by-step abstained on 3 runs where the stand-in judge flagged nothing. The accuracies come from the planted 50% and tell you nothing about a real judge; the call counts are the transferable part, and they mirror Who&When's cost ordering.
  • The report puts planner and worker-2 first (3 runs each) and keeps the two two-fault runs visible as "unattributed". The mode counts show the verification problem dominating (5 runs coded FM-3.3), and one run coded "other": a worker's plain factual error is not a MAST mode, which is why your codebook needs your own codes as well.

4.11 Which attribution method when#

Situation Use Cost Watch out for
Typed boundaries with checkable contracts rule_attributor first Free Silent on plausible-but-wrong content; abstains rather than guesses
You can replay the system (recorded calls, resettable world) counterfactual_attribution, then fix_necessity_check on the result Candidates × replays Needs an oracle per point; downstream must really be fresh
A run with no single decisive point shapley_credit over the agents involved 2ⁿ coalitions × replays; sample permutations beyond about 6 Credit is for fixing, relative to your oracle
Deciding which agent to improve across a suite ablation_credit (oracle mode) Agents × tasks × replays Replace, don't delete
Deciding whether an agent should exist ablation_credit (pass-through mode) Same A pass-through stub must keep the interface
No replay possible (production trace, third-party system) judge_attribution, all-at-once for the agent, step-by-step or hybrid for the step 1 to n judge calls per run Who&When accuracy levels; validate against human labels and the last-step baseline before reporting
Labelling failure modes at scale A MAST-style judge annotator, validated with kappa One call per trace Good for counts, not for single-trace verdicts
Any attributor, before trusting it attribution_accuracy against gold, with last_step_attributor and random_attributor alongside Labelling time Label artefacts; report ±k tolerance and abstentions

Part 5: Orchestration overhead#

Deep-dive

5.1 What the field reports#

Orchestration overhead is everything a multi-agent system spends on being a team rather than doing the task: planning, briefing, routing, waiting, verifying, re-reading other agents' results, and repeating work. 08D.3, 1.2 called it the coordination tax; this part measures it. Three published sources set the priors.

  • Anthropic ("How we built our multi-agent research system", 13 June 2025, engineering post) reports that agents use about 4× the tokens of chat interactions and their multi-agent research system about 15×; that in their BrowseComp analysis token usage alone explained 80% of the performance variance, and token usage, the number of tool calls and the model choice together explained 95%; and that parallelism cut research time by up to 90% for complex queries.
  • Kim et al. (version 3, April 2026) published the most complete overhead table, from 260 configurations with tools, prompts and compute standardised (aggregates over their benchmarks; T is reasoning turns per trial):
Architecture Turn overhead O% Turns T Coordination efficiency Ec Success per 1K tokens (their normalisation) Success
Single agent 0% 7.2 0.466 67.7 0.466
Independent 58% 11B.1 0.234 42.4 0.370
Decentralised 263% 26.1 0.132 23.9 0.477
Centralised 285% 27.7 0.120 21.5 0.463
Hybrid 515% 44.3 0.074 13A.6 0.452

They also fit turn growth as T = 2.72 × (n + 0.5)^1.724 for n agents (R² = 0.974): turns grow faster than the number of agents.

  • LangChain's multi-agent overview (docs) publishes its own illustrative call and token counts for the same work under different patterns; for a multi-domain request: subagents about 5 calls and 9K tokens, handoffs 7+ calls and 14K+ tokens, skills 3 calls and 15K tokens, a router 5 calls and 9K tokens. These are the vendor's own example figures, not measurements of your system; their value is showing that the same task's overhead depends on the pattern.

Two lessons from the table before any code. First, the multi-agent rows spend 3–6× the turns of the single agent for similar success (0.452–0.477 against 0.466), so overhead is not a rounding error. Second, the metrics have precise definitions that differ between papers (Kim et al. even define redundancy two different ways), so state your definition every time you report an overhead number.

5.2 The overhead metrics#

All of these are computed from the trace by overhead(trace, baseline=...) and overhead_summary(runs, baseline_runs=...):

Metric Definition What it tells you
Token multiplier tokens of the multi-agent run ÷ tokens of a single-agent run on the same task (paired per task) The bill for being a team; compare with the field priors above
Turn overhead O% (model calls of the MAS − model calls of the single agent) ÷ single-agent model calls × 100, Kim et al.'s definition with "turns" as model calls How much more reasoning the coordination costs
Coordination ratio coordination-tagged tokens ÷ all tokens How much of the bill is talking about the work rather than doing it
Total compute time sum of model-call and tool-call durations What you pay for in API or GPU time
Critical-path latency wall-clock of the run; the chain of agent runs that set it What the user waits for
Effective parallelism total compute ÷ critical path Average concurrency of the run; near 1 means it ran mostly in sequence. Not a speed-up over anything
Latency speed-up vs baseline single-agent critical path ÷ multi-agent critical path, paired per task (p50 and worst case) What the user gains in wall-clock against the alternative; below 1 means slower
Message density inter-agent messages (handoffs, delegations, returns) ÷ model calls Chattiness; Kim et al.'s c
Cross-agent redundancy tool calls repeating an earlier (tool, arguments) made by a different agent ÷ all tool calls Duplicated work between agents
Recovery tokens tokens in spans that errored, timed out or were retries The hidden cost of error handling
Cost per successful task total cost of all runs ÷ successful runs The number finance cares about; failed runs' cost is included
Successes per 1M tokens success rate ÷ (mean tokens per run ÷ 1,000,000) Output per unit of spend, for comparing architectures
Failure-to-budget share failed runs that ended budget_exhausted or timeout ÷ failed runs Whether the system fails by running out rather than by being wrong

5.3 Work tokens and coordination tokens#

The coordination ratio is only as honest as the role tag on each model call, and no code can infer the tag reliably afterwards. Decide the policy, apply it when you instrument, and print it beside the number. A policy that works for orchestrator systems:

  • Coordination: planning and decomposition, delegation briefs, routing decisions, handoff payload construction, verification and critique, synthesis calls that re-read other agents' results, and any call whose only purpose is to decide what another agent should do.
  • Work: calls that search, read, compute, call domain tools or write the deliverable from the agent's own context.

The synthesiser is the hard case: it does real work (writing the answer) on inputs that exist only because the work was split. Tag it consistently, whichever way you choose. A single agent has coordination too (its planning calls), so if you compare coordination ratios across architectures, tag both systems with the same policy.

5.4 Critical path, total compute and speed-up#

Parallel agents do not make a run cheaper; at best they make it faster. Two numbers separate the two claims:

  • Total compute time adds up every model and tool call. Running workers in parallel does not reduce it; coordination increases it.
  • Critical-path latency is the wall-clock the user experiences: the chain of work that could not overlap. In a fan-out, it runs through the slowest worker, so one straggler sets the latency of the whole run.

critical_path(trace) returns the wall-clock and the chain of agent runs that set it. Traces rarely record dependency edges, so it uses the standard heuristic: start from the run that finished last, then repeatedly step back to the run that finished latest before the current one started. The chain is built from leaf agent runs, so when workers nest under a lead's run (as in 08D.3's logs) the lead's own planning and synthesis time counts in the wall-clock but does not appear as a link in the chain.

Two ratios answer two different questions, and they are easy to confuse:

  • Effective parallelism (total compute ÷ critical path) is the run's average concurrency. 1.0 means nothing overlapped; 3.0 means, on average, three calls were in flight. It says nothing about whether the system is faster than the alternative.
  • Latency speed-up versus the baseline (the single agent's critical path ÷ the multi-agent critical path, paired per task) is what the user gains. This is the number behind claims such as Anthropic's "cut research time by up to 90%". Report its median and its worst case: a straggler can make the multi-agent system slower than one agent on some tasks.

5.5 Redundancy, chattiness and recovery#

  • Cross-agent redundancy. 10A.7's redundant_calls counts repeated identical calls within one trajectory. Two workers issuing the same search are invisible to it, because each worker's own trajectory has no repeats. overhead keys every tool call on (tool, arguments or argument hash) and counts repeats made by a different agent than the first caller. If you only log argument hashes (11A.1 recommends hashes for privacy), identical calls still have identical hashes, so the check works. Overlapping briefs are the usual cause (08D.3, 3.10).
  • Message density. A rising number of inter-agent messages per model call, with flat quality, is coordination growing for its own sake.
  • Recovery overhead. Retries, re-delegations and branches that ran out of budget are real spend. Tag retry spans when you emit them (attrs["retry"] = True) so they are countable.
  • Failure-to-budget conversion. Yang and Shi's user-serving study (see 6.7) reports that their multi-agent systems turned other failures into budget exhaustion and inaction. If a growing share of your failures end in budget_exhausted, the team is spending its budget coordinating rather than failing fast.

5.6 Distributions, not means, and cost per success#

Report each overhead metric as a p50 and a p95, with 10A.7's percentile (overhead_summary does this). Means hide the runaway tail that multi-agent systems are prone to: one run that spawned too many workers, one loop. And report cost per successful task, not per run: a system that fails half the time pays for its failures, so its cost per success is double its cost per run (10A.7, 6.3 makes the same argument for single agents).

5.7 mas_eval.py, section 4: overhead#

python
# ---------------------------------------------------------------------------
# evalkit/mas_eval.py, section 4 of 5 (append after section 3)
# 4. Orchestration overhead
# ---------------------------------------------------------------------------

def critical_path(trace: MASTrace) -> dict:
    """Wall-clock of the run and the chain of agent runs that set it.

    Traces rarely record dependency edges, so use the standard heuristic:
    start from the agent run that finished last, then repeatedly step back to
    the run that finished latest before the current one started (its likely
    predecessor). Parallel siblings that finished earlier are off the path —
    which is exactly why one slow worker sets the latency of the whole fan-out.

    The chain is built from LEAF agent runs: when workers nest under a lead's
    run (08D.3 logs), the lead's own planning and synthesis time is inside its
    parent span and does not appear as a link in the chain, though it still
    counts in `seconds`.
    """
    if not trace.spans:
        return {"seconds": 0.0, "chain": []}
    seconds = max(s.end_s for s in trace.spans) - min(s.start_s for s in trace.spans)
    parents = {s.parent_id for s in trace.spans if s.kind == "agent_run"}
    runs = [s for s in trace.spans if s.kind == "agent_run" and s.span_id not in parents]
    if not runs:
        return {"seconds": round(seconds, 3), "chain": []}
    node = max(runs, key=lambda s: s.end_s)
    chain = [node]
    while True:
        prev = [r for r in runs if r.end_s <= node.start_s + 1e-9 and r is not node]
        if not prev:
            break
        node = max(prev, key=lambda s: s.end_s)
        chain.append(node)
    return {"seconds": round(seconds, 3),
            "chain": [f"{s.agent}({s.duration_s:.1f}s)" for s in reversed(chain)]}


def critical_path_s(trace: MASTrace) -> float:
    return critical_path(trace)["seconds"]


def overhead(trace: MASTrace, *, baseline: MASTrace | None = None) -> dict:
    """Per-run overhead numbers, all computed from the span tree.

    total_compute_s  sum of model and tool call durations (what you pay for)
    parallelism      total_compute_s / critical_path_s: effective parallelism
                     (average concurrency); near 1 means mostly sequential.
                     It is NOT a speed-up over anything.
    redundancy       tool calls repeating an earlier (tool, args) made by a
                     DIFFERENT agent / all tool calls (state your definition:
                     Kim et al. use two different ones)
    recovery_tokens  tokens in spans that errored, timed out or were retries
    token_multiplier, turn_overhead_pct, latency_speedup  only with a
                     single-agent baseline; latency_speedup = baseline
                     critical path / this run's critical path (>1 = faster)
    """
    calls = [s for s in trace.spans if s.kind in ("model_call", "tool_call")]
    model_calls = [s for s in trace.spans if s.kind == "model_call"]
    tools = sorted((s for s in trace.spans if s.kind == "tool_call"), key=lambda s: s.start_s)
    first_by: dict[tuple, str] = {}
    dup = 0
    for s in tools:
        key = (s.attrs.get("tool"), s.attrs.get("args_hash") or str(s.attrs.get("args")))
        if key in first_by and first_by[key] != s.agent:
            dup += 1
        first_by.setdefault(key, s.agent)
    total = trace.tokens()
    coord = trace.tokens("coordination")
    cp = critical_path_s(trace)
    compute = sum(s.duration_s for s in calls)
    messages = sum(1 for s in trace.spans if s.kind in MESSAGE_KINDS)
    out = {
        "tokens": total, "coord_tokens": coord,
        "coordination_ratio": round(coord / total, 3) if total else 0.0,
        "total_compute_s": round(compute, 3), "critical_path_s": cp,
        "parallelism": round(compute / cp, 2) if cp else None,
        "model_calls": len(model_calls), "messages": messages,
        "message_density": round(messages / len(model_calls), 3) if model_calls else 0.0,
        "redundancy": round(dup / len(tools), 3) if tools else 0.0,
        "recovery_tokens": sum(s.tokens for s in trace.spans
                               if s.status in ("error", "timeout", "budget_exhausted")
                               or s.attrs.get("retry")),
        "cost_usd": round(trace.cost(), 6),
        "per_agent_tokens": {a: sum(s.tokens for s in ss)
                             for a, ss in trace.by_agent().items()},
    }
    if baseline is not None:
        bt = baseline.tokens()
        bturns = sum(1 for s in baseline.spans if s.kind == "model_call")
        out["token_multiplier"] = round(total / bt, 2) if bt else None
        out["turn_overhead_pct"] = round((len(model_calls) - bturns) / bturns * 100, 1) \
            if bturns else None
        bcp = critical_path_s(baseline)
        out["latency_speedup"] = round(bcp / cp, 2) if cp else None
    return out


def _dist(xs: list[float]) -> dict:
    xs = [x for x in xs if x is not None]
    if not xs:
        return {"p50": None, "p95": None, "mean": None, "min": None, "max": None}
    return {"p50": round(percentile(xs, 50), 3), "p95": round(percentile(xs, 95), 3),
            "mean": round(statistics.fmean(xs), 3),
            "min": round(min(xs), 3), "max": round(max(xs), 3)}


def overhead_summary(runs: list[MASTrace],
                     baseline_runs: list[MASTrace] | None = None) -> dict:
    """Distributions (p50/p95, not just means) over many runs, plus the
    success-normalised economics. Failed runs' cost is included in cost per
    success — that is the point of the metric."""
    per = [overhead(t) for t in runs]
    n_ok = sum(bool(t.success) for t in runs)
    fails = [t for t in runs if not t.success]
    mean_tok = statistics.fmean(p["tokens"] for p in per) if per else 0
    out = {
        "runs": len(runs), "success_rate": round(n_ok / len(runs), 3) if runs else None,
        "tokens": _dist([p["tokens"] for p in per]),
        "critical_path_s": _dist([p["critical_path_s"] for p in per]),
        "parallelism": _dist([p["parallelism"] for p in per]),
        "coordination_ratio": _dist([p["coordination_ratio"] for p in per]),
        "redundancy": _dist([p["redundancy"] for p in per]),
        "cost_per_success": round(sum(t.cost() for t in runs) / n_ok, 5) if n_ok else None,
        "successes_per_1m_tokens": round((n_ok / len(runs)) / (mean_tok / 1e6), 2)
        if runs and mean_tok else None,
        "failure_to_budget_share": round(
            sum(t.status in ("budget_exhausted", "timeout") for t in fails) / len(fails), 3)
        if fails else None,
    }
    if baseline_runs:
        base = {t.task_id: t for t in baseline_runs}
        mult = [t.tokens() / base[t.task_id].tokens() for t in runs
                if t.task_id in base and base[t.task_id].tokens()]
        out["token_multiplier"] = _dist(mult)
        out["latency_speedup"] = _dist([critical_path_s(base[t.task_id]) / critical_path_s(t)
                                        for t in runs if t.task_id in base
                                        and critical_path_s(t)])
    return out

5.8 Overhead on the research fixture#

The demo re-runs Fixture B with the correctness faults switched off (so the runs are healthy) except R09, whose worker error is caught and retried, which creates recovery overhead. R10 keeps its slow worker-3 and R11 its duplicated search. Each of the 16 tasks runs under ten seeds, against a single-agent baseline (one agent doing the three searches in sequence). The prices are fixture constants, not any provider's, and the single agent's success rate is a fixture value too: Part 6 does the quality comparison properly.

python
# ===========================================================================
# mas_eval_demo.py, section 4 of 5 (append after section 3)
# Part 5 — overhead from the same traces
# ===========================================================================

def sas_system(task: str, seed: int) -> MASTrace:
    """Single-agent baseline for the same task: one agent, sequential."""
    rng = random.Random(f"sas:{task}:{seed}")
    t = MASTrace(trace_id=f"sas-{task}:{seed}", task_id=task, system="research-sas@v1")
    t.spans.append(AgentSpan("solo-run", None, "solo", "agent_run", 0.0, 0.0,
                             attrs={"step": 0}))
    clock = 0.0
    calls = [(1200, 200)] + [(3400, 320)] * 3 + [(4800, 600)]
    for j, (tin, tout) in enumerate(calls):
        if 1 <= j <= 3:
            t.spans.append(AgentSpan(f"solo-tool{j}", "solo-run", "solo", "tool_call",
                                     clock, clock + 0.7,
                                     attrs={"tool": "web_search", "args_hash": _h(task, j)}))
            clock += 0.7
        t.spans.append(AgentSpan(f"solo-llm{j}", "solo-run", "solo", "model_call", clock,
                                 clock + 1.6, tokens_in=tin, tokens_out=tout,
                                 cost_usd=tin * IN_PRICE + tout * OUT_PRICE))
        clock += 1.6
    t.spans[0].end_s = clock
    t.success = rng.random() < 0.85            # fixture value, not a finding
    t.final_answer = "..."
    return t


def demo_overhead() -> None:
    # Healthy runs: correctness faults switched off; the overhead faults stay
    # (R10's straggler worker and R11's duplicated search are built in).
    # R09 keeps its caught-and-retried worker error: recovery overhead.
    healthy = {t: ("worker2_wrong_caught" if t == "R09" else None) for t in FAULTS}
    mas = [research_system(t, {}, seed=s, faults=healthy) for s in range(10) for t in FAULTS]
    sas = [sas_system(t, seed=s) for s in range(10) for t in FAULTS]
    by = {t.task_id: t for t in mas[:len(FAULTS)]}
    base = {t.task_id: t for t in sas[:len(FAULTS)]}
    for tid in ("R08", "R10", "R11", "R09"):
        o = overhead(by[tid], baseline=base[tid])
        cp = critical_path(by[tid])
        print(f"{tid}: tokens={o['tokens']} x{o['token_multiplier']} vs SAS, "
              f"coord={o['coordination_ratio']:.2f}, compute={o['total_compute_s']}s, "
              f"critical_path={o['critical_path_s']}s, "
              f"parallelism={o['parallelism']}, latency_speedup_vs_SAS={o['latency_speedup']}, "
              f"redundancy={o['redundancy']}, "
              f"recovery_tokens={o['recovery_tokens']}, turn_overhead={o['turn_overhead_pct']}%")
    for tid in ("R08", "R10"):
        print(f"critical path {tid}: {' -> '.join(critical_path(by[tid])['chain'])}")
    print("per-agent tokens R09:", overhead(by["R09"])["per_agent_tokens"])
    s_mas = overhead_summary(mas, baseline_runs=sas)
    s_sas = overhead_summary(sas)
    for name, s in (("MAS", s_mas), ("SAS", s_sas)):
        print(f"{name}: success={s['success_rate']} tokens p50/p95={s['tokens']['p50']}/"
              f"{s['tokens']['p95']} critical_path p50/p95={s['critical_path_s']['p50']}/"
              f"{s['critical_path_s']['p95']}s cost/success=${s['cost_per_success']} "
              f"successes/1M tok={s['successes_per_1m_tokens']}")
    print(f"MAS token multiplier p50/p95 = {s_mas['token_multiplier']['p50']}/"
          f"{s_mas['token_multiplier']['p95']}, coordination ratio p50 = "
          f"{s_mas['coordination_ratio']['p50']}, effective parallelism p50 = "
          f"{s_mas['parallelism']['p50']}")
    ls = s_mas["latency_speedup"]
    print(f"MAS latency speed-up vs SAS (paired per task): p50 = {ls['p50']}, "
          f"worst = {ls['min']} (below 1 = slower than the single agent)")
    per_agent = to_trajectories(by["R11"])
    print("R11 per-agent redundant_calls (10A.7):",
          {a: redundant_calls(tr)["redundant"] for a, tr in per_agent.items() if tr.steps},
          "vs cross-agent redundancy:", overhead(by["R11"])["redundancy"])

Run it with python3 mas_eval_demo.py overhead.

Output13 lines
=== overhead ===
R08: tokens=40860 x2.28 vs SAS, coord=0.34, compute=11.8s, critical_path=7.1s, parallelism=1.66, latency_speedup_vs_SAS=1.42, redundancy=0.0, recovery_tokens=0, turn_overhead=80.0%
R10: tokens=40860 x2.28 vs SAS, coord=0.34, compute=17.9s, critical_path=13.2s, parallelism=1.36, latency_speedup_vs_SAS=0.77, redundancy=0.0, recovery_tokens=0, turn_overhead=80.0%
R11: tokens=40860 x2.28 vs SAS, coord=0.34, compute=11.8s, critical_path=7.1s, parallelism=1.66, latency_speedup_vs_SAS=1.42, redundancy=0.333, recovery_tokens=0, turn_overhead=80.0%
R09: tokens=46540 x2.59 vs SAS, coord=0.30, compute=13.8s, critical_path=9.1s, parallelism=1.52, latency_speedup_vs_SAS=1.11, redundancy=0.0, recovery_tokens=5680, turn_overhead=100.0%
critical path R08: planner(1.5s) -> worker-3(2.9s) -> verifier(1.0s) -> synthesiser(1.5s)
critical path R10: planner(1.5s) -> worker-3(9.0s) -> verifier(1.0s) -> synthesiser(1.5s)
per-agent tokens R09: {'orchestrator': 0, 'planner': 2820, 'worker-1': 8980, 'worker-2': 14660, 'worker-3': 8980, 'verifier': 4400, 'synthesiser': 6700}
MAS: success=0.925 tokens p50/p95=40860/46540 critical_path p50/p95=7.1/13.2s cost/success=$0.11305 successes/1M tok=22.44
SAS: success=0.838 tokens p50/p95=17960/17960 critical_path p50/p95=10.1/10.1s cost/success=$0.0555 successes/1M tok=46.63
MAS token multiplier p50/p95 = 2.275/2.591, coordination ratio p50 = 0.341, effective parallelism p50 = 1.66
MAS latency speed-up vs SAS (paired per task): p50 = 1.423, worst = 0.765 (below 1 = slower than the single agent)
R11 per-agent redundant_calls (10A.7): {'worker-1': 0, 'worker-2': 0, 'worker-3': 0} vs cross-agent redundancy: 0.333

How to read it:

  • The multiplier. A healthy run spends 2.28× the single agent's tokens and makes 80% more model calls; R09's retry pushes it to 2.59× and 100%. A third of every healthy run's tokens are coordination (planner, verifier, synthesiser under this fixture's tagging policy).
  • Parallelism bought less than it seems. R08's workers overlap, so the critical path (7.1 s) is shorter than the total compute (11.8 s): an effective parallelism of 1.66 with three parallel workers, because planning, verification and synthesis are sequential. Against the single agent's 10.1 s, the user-facing latency speed-up is 1.42. The chain shows the slowest worker on the path.
  • One straggler sets the latency. In R10, worker-3 takes 9 seconds; the critical path jumps to 13.2 s, the chain names worker-3, and the latency speed-up falls to 0.77: on this task the multi-agent system is slower than the single agent. Across the suite, p50 critical path is 7.1 s and p95 is 13.2 s, and the paired latency speed-up is 1.42 at the median and 0.77 in the worst case: exactly the straggler pattern.
  • Redundancy is only visible across agents. In R11 10A.7's per-agent redundant_calls finds nothing in any worker, while the cross-agent redundancy is 0.333: one of three searches repeated another worker's.
  • Recovery has a price. R09's retry adds 5,680 tokens of recovery spend, all attributed to worker-2 in the per-agent breakdown.
  • Success-normalised economics. On these fixture numbers the multi-agent system costs about twice as much per successful task as the single agent ($0.113 against $0.056) and produces about half the successes per million tokens (22.4 against 46.6). The quality side of that trade is Part 6's job.

Part 6: The single-agent baseline#

6.1 Why every multi-agent claim needs one#

"Our multi-agent system beats a single agent by X%" is the most common claim in this space, and usually the least supported. The best-known number is Anthropic's: their research system (Claude Opus 4 as lead, Claude Sonnet 4 subagents) outperformed single-agent Claude Opus 4 by 90.2% on their internal research evaluation. The same post reports that token usage alone explained 80% of the performance variance on BrowseComp. Put those two facts together and the 90.2% could be mostly more tokens, not more agents: the multi-agent system spent roughly 15× the tokens of chat, and the single agent it was compared with was not given the same budget. That does not make the result wrong. Anthropic is explicit that multi-agent systems suit valuable, heavily parallel, breadth-first tasks; it makes the number a statement about their system at their spend, not about architectures. 08D.3, 3.7 stated the rule in one line, "match total tokens"; this part turns it into a protocol.

The question a baseline answers is narrow and useful: at the same model, the same tools and the same budget, does splitting the work across agents produce better outcomes, and on which tasks? Without the baseline you are measuring spend, not architecture.

6.2 Designing the comparison#

An equal-budget baseline is a single-agent configuration given the same resources as the multi-agent system. The protocol, as a checklist:

  1. Same model for the single agent as the multi-agent system's strongest role, or report both if roles use different models.
  2. Same tools: the single agent gets the union of all agents' tools (watch tool-count effects, 10A.7, 7.5).
  3. Same instructions where possible: the single agent's prompt is the union of the agents' role instructions, so you compare organisation, not prompt quality.
  4. Same budget, in tokens and in iterations. Kim et al. matched the total reasoning-token budget (a mean of 4,800 tokens per trial) and tool-call access, and matched the maximum total iterations, so the single agent got proportionally more reasoning rounds than each individual agent. equal_budget_check refuses a verdict when mean tokens differ by more than a tolerance (10% by default).
  5. Same tasks, paired. Every task runs under both systems, so per-task difficulty cancels out (10A.8, 2.3).
  6. Several runs per task and pass^k next to the mean: a debate or an ensemble can raise the average while making the system less dependable, or the reverse (10A.7, 5.1).
  7. Slices by task structure, declared in advance: decomposable or parallel tasks, sequential tasks, tool-heavy tasks. The sign of the difference can flip between them.
  8. Pre-register the metric, the slices, the budget, the tolerance and the stopping rule before you run (10A.10's pre-registered launch criteria). Yang and Shi pre-registered their comparison and kept a public change log, which is why their negative result is credible.

When the systems cannot be budget-matched (the multi-agent system is designed to spend more), the honest claim is "better at higher cost", reported with the cost ratio and a cost-normalised view (6.6).

6.3 Stronger baselines than "one agent"#

A single agent run once is a weak control, because the cheapest way to turn extra budget into accuracy is not to split the work but to sample more. Three baselines cost the same as a multi-agent system and often match it:

  • Self-consistency / best-of-n: run the single agent n times and take the majority answer (or the best by a verifier). Give it the multi-agent system's token budget by choosing n.
  • Majority vote without debate: if your multi-agent system is a debate, run the same agents independently and vote. Choi, Zhu and Li ("Debate or Vote", arXiv 2508.17536, NeurIPS 2025 spotlight) found across seven NLP benchmarks that majority voting alone accounts for most of the gains credited to debate, and model debate as a martingale over beliefs: debate alone does not improve expected correctness.
  • Heterogeneous ensembles: Zhang et al.'s position paper ("Stop Overvaluing Multi-Agent Debate", arXiv 2502.08788) evaluated five debate methods on nine benchmarks with four foundation models, found that debate often fails to beat chain-of-thought and self-consistency despite using more compute, criticised weak baselines and inconsistent setups, and found that mixing different models consistently helped. If your multi-agent system's gain disappears when you compare it with a same-cost ensemble of different models, the gain was diversity, not orchestration.

For debate-style systems, two cheap diagnostics from the traces show whether the rounds of discussion do anything: the switch balance (how many agents change from a correct to an incorrect answer between rounds, against how many change from incorrect to correct) and the early-agreement rate (how often every agent agrees in the first round, after which debate cannot change the vote). If correct→incorrect switches are as common as incorrect→correct ones, the debate is persuasion or conformity, not error correction, which is what Choi et al.'s martingale result predicts on average.

6.4 The ablation ladder#

Ablations tell you which part of the multi-agent design earns its cost. Each rung is a paired comparison on the same tasks:

Rung Change What a difference means
(a) The full multi-agent system The reference
(b) Remove the verifier or critic (pass-through stub) The verifier's contribution; zero means it checks the wrong thing
(c) Replace debate with independent voting Whether the conversation adds anything beyond voting (Choi et al.); read it with the switch balance and early-agreement rate
(d) Run the parallel workers sequentially Separates the latency gain from parallelism from the quality gain from decomposition
(e) Collapse into one agent with all prompts and tools, at equal budget The value of splitting at all
(f) Same model everywhere versus different models per role Whether diversity, not structure, is doing the work
(g) Swap the orchestrator's model How much depends on the lead (Anthropic: small changes to the lead change all subagents' behaviour)

Run the rungs that correspond to claims you intend to make. A design decision with no rung behind it is an assumption.

6.5 The statistics#

The comparison uses 10A.8's compare.py unchanged, wrapped by compare_systems(scores_a, scores_b, slices=..., cost_a=..., cost_b=...):

  • paired_diffs gives per-task differences (B − A) on the shared tasks;
  • paired_bootstrap_ci gives a 95% interval on the mean difference;
  • sign_flip_permutation_p gives a two-sided p-value;
  • paired_effect_size gives a paired effect size, so a "significant" but tiny difference is visible as tiny;
  • the same block runs per slice, because averages hide slices with opposite signs.

Three cautions from 10A.8, Part 2: with slices and ablation rungs you are making many comparisons, so correct for them or treat the slice results as exploratory (10A.8, 2.6); check the minimum detectable effect before you run, since 20 tasks per slice detect only large effects (10A.8, 2.4); and when tasks come in groups (several tasks from one customer or one document), use the cluster bootstrap (10A.8, 2.7).

6.6 The cost-normalised view and the Pareto frontier#

A comparison that reports only quality hides half the decision. Report, for every variant:

  • quality (success rate, pass^k), cost per successful task, successes per million tokens;
  • p95 latency (critical path), because parallel systems often win here while losing on cost;
  • and the Pareto frontier: the variants that no other variant beats on every axis at once (02.8 introduced the idea for reasoning settings). pareto_front(points, keys=...) returns the non-dominated names; change keys to see the frontier for the axes your product cares about.

An iso-budget curve makes the equal-budget idea visual: plot success against budget for both architectures (the single agent at budget B via more steps or more samples; the multi-agent system at budget B via fewer or smaller agents) and compare at equal B. If the curves cross, the answer to "which is better?" depends on how much you are willing to spend, which is a product decision, not an evaluation result.

6.7 What the evidence says, and when the multi-agent system wins#

As of November 2026, the controlled evidence points one way, with clear exceptions:

Source Setup Finding
Kim et al., "Towards a Science of Scaling Agent Systems" (arXiv 2512.08296, v3 April 2026) 260 configurations, 6 benchmarks, 3 model families, 5 architectures; tools, prompts and token budgets matched Relative to a single agent, from +80.8% (decomposable financial reasoning, centralised coordination) to −70.0% (sequential planning); a capability-saturation effect: once the single agent's baseline passes roughly 45%, adding agents tends to hurt (their regression boundary); tool-heavy tasks pay more overhead; their model picks the best architecture for 87% of held-out configurations
Gao et al., "Single-agent or Multi-agent Systems? Why Not Both?" (arXiv 2505.18286) Frontier models of 2025 The multi-agent advantage shrinks as single models get stronger; a hybrid cascade between the two improves accuracy by 1.1–12% while cutting deployment cost by up to 20%
Wang et al., "Rethinking the Bounds of LLM Reasoning: Are Multi-Agent Discussions the Key?" (arXiv 2402.18272) Discussion methods against a strongly prompted single agent A single agent with strong prompts performs nearly as well as the best discussion; discussion won only when the prompt had no demonstrations
Zhang et al., "Stop Overvaluing Multi-Agent Debate" 5 debate methods, 9 benchmarks, 4 models Debate often fails to beat chain-of-thought and self-consistency; heterogeneous models help
Choi et al., "Debate or Vote" (NeurIPS 2025 spotlight) 7 NLP benchmarks Voting explains most of debate's gains
Yang and Shi, "Does Multi-Agent Collaboration Pay When Agents Serve Users?" (arXiv 2610.27655, preprint, October 2026) τ²-bench airline, retail and telecom; 6 models from 3 families; about 7,950 simulated conversations; pre-registered Under a fixed simulated user the multi-agent system was worse in 12 of 13 valid cells and tied in the 13th (weighted mean −28 points, 95% CI −44 to −12); without a budget ceiling it at best drew level at 5.5× the single agent's tokens; it did not reduce wrongful database writes and converted failures into budget exhaustion and inaction; its only gain appeared under a second simulator. One validity bar was unmet (the planner never saw the tool schemas). A single, not yet peer-reviewed preprint
Cognition, "Don't Build Multi-Agents" (Walden Yan, 12 June 2025, post) Engineering experience with coding agents Share full context and traces, because actions carry implicit decisions; default to a single-threaded agent
Anthropic (13 June 2025) Production research system +90.2% on breadth-first research at about 15× chat tokens; poor fit where agents must share context or depend on each other, and most coding tasks are less parallelisable than research

Note the last row of Yang and Shi: changing the user simulator changed the conclusion of an architecture comparison. That is a direct bridge to Part 7: when your comparison runs on simulated users, the simulator is part of the measurement.

From all of this, the cases where a multi-agent system wins honestly share a structure:

  • the task decomposes into independent parts (breadth-first research, parallel data gathering, multi-domain requests);
  • the work overflows one context window, so isolation is the point;
  • independent verification is valuable and the verifier uses a different model or different evidence;
  • different roles genuinely need different permissions or tools;
  • and the task's value justifies a multiple of the single-agent cost, or the parallelism buys a latency the product needs.

Show it honestly by publishing the equal-budget comparison, the strongest same-cost baseline (usually self-consistency), the slice table, pass^k, the cost per success and the Pareto view, together.

6.8 mas_eval.py, section 5, and the comparison demo#

python
# ---------------------------------------------------------------------------
# evalkit/mas_eval.py, section 5 of 5 (append after section 4)
# 5. Single-agent baseline comparison
# ---------------------------------------------------------------------------

def equal_budget_check(tokens_a: list[float], tokens_b: list[float], *,
                       tol: float = 0.10) -> dict:
    """Refuse an architecture verdict when B spent more than tol more (or
    less) than A: then you measured spend, not architecture."""
    ma, mb = statistics.fmean(tokens_a), statistics.fmean(tokens_b)
    gap = abs(mb - ma) / ma if ma else float("inf")
    ok = gap <= tol
    return {"mean_a": round(ma, 1), "mean_b": round(mb, 1), "ratio_b_over_a": round(mb / ma, 2),
            "gap": round(gap, 3), "equal_budget": ok,
            "verdict": "comparable" if ok else
            f"NOT budget-matched (B/A = {mb / ma:.2f}x): report 'at higher cost' or re-run matched"}


def compare_systems(scores_a: dict[str, float], scores_b: dict[str, float], *,
                    cost_a: dict[str, float] | None = None,
                    cost_b: dict[str, float] | None = None,
                    slices: dict[str, str] | None = None,
                    iters: int = 10_000, seed: int = 0) -> dict:
    """Paired comparison of B against A on the SAME tasks (10A.8's compare.py):
    mean difference b - a with a bootstrap CI, a sign-flip permutation p-value
    and a paired effect size, overall and per slice (the sign can flip
    between slices, and an average can hide both)."""
    def block(ids: list[str]) -> dict:
        a = {i: scores_a[i] for i in ids}
        b = {i: scores_b[i] for i in ids}
        d = paired_diffs(a, b)
        m, lo, hi = paired_bootstrap_ci(d, iters=iters, seed=seed)
        return {"n": len(d), "mean_a": round(statistics.fmean(a.values()), 3),
                "mean_b": round(statistics.fmean(b.values()), 3),
                "diff": round(m, 3), "ci": (round(lo, 3), round(hi, 3)),
                "p": round(sign_flip_permutation_p(d, iters=iters, seed=seed), 4),
                "effect_d": round(paired_effect_size(d), 2)}

    shared = sorted(set(scores_a) & set(scores_b))
    out = {"overall": block(shared)}
    if slices:
        for name in sorted(set(slices[i] for i in shared)):
            out[name] = block([i for i in shared if slices[i] == name])
    if cost_a and cost_b:
        ca = sum(cost_a[i] for i in shared)
        cb = sum(cost_b[i] for i in shared)
        sa = sum(scores_a[i] for i in shared)
        sb = sum(scores_b[i] for i in shared)
        out["cost"] = {"cost_ratio_b_over_a": round(cb / ca, 2) if ca else None,
                       "cost_per_success_a": round(ca / sa, 5) if sa else None,
                       "cost_per_success_b": round(cb / sb, 5) if sb else None}
    return out


def pareto_front(points: list[dict],
                 keys: tuple[tuple[str, str], ...] = (("quality", "max"), ("cost", "min"),
                                                      ("p95_latency", "min"))) -> list[str]:
    """Names of the non-dominated variants. A variant is dominated when another
    is at least as good on every key and strictly better on one."""
    def better_eq(x: dict, y: dict) -> bool:
        return all((x[k] >= y[k]) if d == "max" else (x[k] <= y[k]) for k, d in keys)

    def strictly(x: dict, y: dict) -> bool:
        return any((x[k] > y[k]) if d == "max" else (x[k] < y[k]) for k, d in keys)

    return [p["name"] for p in points
            if not any(better_eq(q, p) and strictly(q, p) for q in points if q is not p)]

The demo compares four variants on 40 paired tasks (20 decomposable "breadth" tasks, 20 "sequential" ones), four trials each: a single agent (SAS), the same single agent with self-consistency over four samples (about the multi-agent token budget), the multi-agent system (MAS) and the MAS without its verifier. The success probabilities and token levels are fixture parameters chosen to resemble the published pattern (a gain on decomposable tasks, a loss on sequential ones); they are not measurements.

python
# ===========================================================================
# mas_eval_demo.py, section 5 of 5 (append after section 4)
# Part 6 — single- vs multi-agent on 40 paired tasks
# ===========================================================================

@dataclass
class VariantSpec:
    name: str
    tokens: int          # mean tokens per trial
    lift_breadth: float  # success-probability shift vs SAS, decomposable tasks
    lift_seq: float      # ... sequential tasks
    latency: float       # p50 seconds; breadth tasks get parallel speed-up if parallel
    parallel: bool


VARIANTS = [
    VariantSpec("SAS", 21_000, 0.00, 0.00, 38.0, False),
    VariantSpec("SAS+SC@4 (equal budget)", 84_000, 0.08, 0.08, 41.0, False),
    VariantSpec("MAS", 86_000, 0.18, -0.16, 24.0, True),
    VariantSpec("MAS no-verifier", 74_000, 0.17, -0.18, 22.0, True),
]


def run_variant(v: VariantSpec, task: str, difficulty: float, slice_: str, k: int = 4):
    p = min(0.97, max(0.02, 0.78 - 0.55 * difficulty +
                      (v.lift_breadth if slice_ == "breadth" else v.lift_seq)))
    rng = random.Random(f"{v.name}:{task}")
    wins = sum(rng.random() < p for _ in range(k))
    tok = [int(v.tokens * rng.uniform(0.8, 1.25)) for _ in range(k)]
    lat = v.latency * (0.6 if (v.parallel and slice_ == "breadth") else
                       1.25 if v.parallel else 1.0) * rng.uniform(0.7, 1.6)
    return wins, k, tok, lat


def demo_baseline() -> None:
    rng = random.Random(7)
    tasks = {f"B{i:02d}": ("breadth", rng.random()) for i in range(1, 21)}
    tasks |= {f"S{i:02d}": ("sequential", rng.random()) for i in range(1, 21)}
    slices = {t: s for t, (s, _) in tasks.items()}
    res = {}
    for v in VARIANTS:
        scores, tokens, lats, cost, phk = {}, [], [], {}, []
        for t, (s, d) in tasks.items():
            wins, k, tok, lat = run_variant(v, t, d, s)
            scores[t] = wins / k
            tokens += tok
            lats.append(lat)
            cost[t] = sum(tok) / k * 4e-6               # fixture blended price per token
            phk.append(pass_hat_k(k, wins, k))
        res[v.name] = dict(scores=scores, tokens=tokens, lats=lats, cost=cost,
                           pass_hat_4=statistics.fmean(phk))
    for name, r in res.items():
        print(f"{name:26s} success={statistics.fmean(r['scores'].values()):.3f} "
              f"pass^4={r['pass_hat_4']:.3f} tokens/trial={statistics.fmean(r['tokens']):,.0f}")

    print("\nMAS vs SAS (the comparison most decks show):")
    print(" ", equal_budget_check(res["SAS"]["tokens"], res["MAS"]["tokens"]))
    c = compare_systems(res["SAS"]["scores"], res["MAS"]["scores"], slices=slices,
                        cost_a=res["SAS"]["cost"], cost_b=res["MAS"]["cost"])
    for k in ("overall", "breadth", "sequential"):
        print(f"  {k:10s} {c[k]}")
    print(f"  cost: {c['cost']}")

    print("\nMAS vs SAS+SC@4 (equal budget):")
    print(" ", equal_budget_check(res["SAS+SC@4 (equal budget)"]["tokens"], res["MAS"]["tokens"]))
    c2 = compare_systems(res["SAS+SC@4 (equal budget)"]["scores"], res["MAS"]["scores"],
                         slices=slices)
    for k in ("overall", "breadth", "sequential"):
        print(f"  {k:10s} {c2[k]}")

    print("\nablation: MAS without the verifier vs MAS:")
    c3 = compare_systems(res["MAS"]["scores"], res["MAS no-verifier"]["scores"])
    print(f"  overall {c3['overall']}")

    pts = []
    for name, r in res.items():
        pts.append({"name": name, "quality": round(statistics.fmean(r["scores"].values()), 3),
                    "cost": round(statistics.fmean(r["cost"].values()), 4),
                    "p95_latency": round(percentile(r["lats"], 95), 1)})
    print("\nPareto view (quality up, cost down, p95 latency down):")
    for p in pts:
        print(f"  {p}")
    print("  non-dominated:", pareto_front(pts))
    print("  quality+cost only:", pareto_front(pts, keys=(("quality", "max"), ("cost", "min"))))


if __name__ == "__main__":
    which = sys.argv[1] if len(sys.argv) > 1 else "all"
    for name, fn in (("trace", demo_trace), ("handoffs", demo_handoffs),
                     ("attribution", demo_attribution), ("overhead", demo_overhead),
                     ("baseline", demo_baseline)):
        if which in ("all", name):
            print(f"=== {name} ===")
            fn()

Run it with python3 mas_eval_demo.py baseline.

Output29 lines
=== baseline ===
SAS                        success=0.569 pass^4=0.150 tokens/trial=21,376
SAS+SC@4 (equal budget)    success=0.594 pass^4=0.150 tokens/trial=85,898
MAS                        success=0.569 pass^4=0.200 tokens/trial=88,166
MAS no-verifier            success=0.531 pass^4=0.200 tokens/trial=77,192

MAS vs SAS (the comparison most decks show):
  {'mean_a': 21376.0, 'mean_b': 88165.6, 'ratio_b_over_a': 4.12, 'gap': 3.125, 'equal_budget': False, 'verdict': "NOT budget-matched (B/A = 4.12x): report 'at higher cost' or re-run matched"}
  overall    {'n': 40, 'mean_a': 0.569, 'mean_b': 0.569, 'diff': 0.0, 'ci': (-0.119, 0.113), 'p': 1.0, 'effect_d': 0.0}
  breadth    {'n': 20, 'mean_a': 0.55, 'mean_b': 0.688, 'diff': 0.138, 'ci': (0.0, 0.275), 'p': 0.1008, 'effect_d': 0.43}
  sequential {'n': 20, 'mean_a': 0.588, 'mean_b': 0.45, 'diff': -0.138, 'ci': (-0.3, 0.025), 'p': 0.1726, 'effect_d': -0.35}
  cost: {'cost_ratio_b_over_a': 4.12, 'cost_per_success_a': 0.15034, 'cost_per_success_b': 0.62007}

MAS vs SAS+SC@4 (equal budget):
  {'mean_a': 85898.2, 'mean_b': 88165.6, 'ratio_b_over_a': 1.03, 'gap': 0.026, 'equal_budget': True, 'verdict': 'comparable'}
  overall    {'n': 40, 'mean_a': 0.594, 'mean_b': 0.569, 'diff': -0.025, 'ci': (-0.125, 0.075), 'p': 0.7127, 'effect_d': -0.08}
  breadth    {'n': 20, 'mean_a': 0.65, 'mean_b': 0.688, 'diff': 0.037, 'ci': (-0.087, 0.15), 'p': 0.6993, 'effect_d': 0.13}
  sequential {'n': 20, 'mean_a': 0.537, 'mean_b': 0.45, 'diff': -0.087, 'ci': (-0.237, 0.062), 'p': 0.3454, 'effect_d': -0.25}

ablation: MAS without the verifier vs MAS:
  overall {'n': 40, 'mean_a': 0.569, 'mean_b': 0.531, 'diff': -0.037, 'ci': (-0.144, 0.062), 'p': 0.5625, 'effect_d': -0.11}

Pareto view (quality up, cost down, p95 latency down):
  {'name': 'SAS', 'quality': 0.569, 'cost': 0.0855, 'p95_latency': 58.0}
  {'name': 'SAS+SC@4 (equal budget)', 'quality': 0.594, 'cost': 0.3436, 'p95_latency': 63.2}
  {'name': 'MAS', 'quality': 0.569, 'cost': 0.3527, 'p95_latency': 45.4}
  {'name': 'MAS no-verifier', 'quality': 0.531, 'cost': 0.3088, 'p95_latency': 41.7}
  non-dominated: ['SAS', 'SAS+SC@4 (equal budget)', 'MAS', 'MAS no-verifier']
  quality+cost only: ['SAS', 'SAS+SC@4 (equal budget)']

How to read it:

  • The headline comparison is invalid as stated. MAS spends 4.12× the single agent's tokens, so equal_budget_check refuses the verdict. Overall the difference is exactly 0.0, which would be reported as "no effect", yet the slices disagree: +0.138 on breadth tasks and −0.138 on sequential ones, each with an interval that touches zero (20 tasks per slice detect only large effects). The average hid two opposite effects.
  • At equal budget the strong baseline wins or ties. Against self-consistency at the same budget (gap 2.6%), the MAS is −0.025 overall with an interval from −0.125 to +0.075: no evidence the extra agents beat extra samples, and a slight lead for the MAS only on breadth tasks.
  • The verifier ablation shows no measurable contribution (−0.037, interval −0.144 to +0.062): either it is checking the wrong thing or the suite is too small to see it. Part 4's ablation found the first on Fixture B; here it is a prompt to look.
  • pass^4 is low for everything (0.15–0.20) because per-task success is around 0.55; the MAS's slightly higher pass^4 is the kind of difference you check with more trials before believing.
  • The Pareto view depends on the axes. With latency included all four variants are non-dominated (the two MAS variants are fastest at p95 because of parallelism; the single agent is cheapest). With quality and cost only, the single agent and self-consistency form the frontier and the MAS is dominated. So the honest summary is: "the MAS buys p95 latency and a possible gain on breadth tasks, at about 4× the cost and a possible loss on sequential tasks." That is a product decision you can now make with the numbers in front of you.

Part 7: Validating user simulators#

Deep-dive

7.1 The simulator is a measuring instrument#

A user simulator is a model (or a script) that plays the customer while your agent plays itself; 10A.2, Part 13 builds one, and Anthropic's agent-evaluation guide notes that conversational agents "often require a second LLM to simulate the user" (Demystifying evals for AI agents, 9 January 2026). Once you score agents with it, the simulator is no longer test data. It is part of the measuring instrument, exactly like an LLM judge: every agent score you report is "the agent's behaviour as elicited by this simulator". If the simulator volunteers every fact, an agent that never asks clarifying questions looks perfect. If it never gives up, an agent that wastes the user's time looks patient. If it differs between two runs, your A/B test measures the simulator.

10A.5 taught how to validate one instrument against human ground truth. The same loop applies here, with users in place of labels:

Judge validation (10A.5) Simulator validation (this part)
Human labels are the reference Real users' conversations, and real users' outcomes with the same agents, are the reference
Agreement (kappa, TPR/TNR) Realism of behaviour distributions; discriminability
Bias structure (lenient or strict) Sim-to-real gap: easier or harder than real users, per slice
Ranking fidelity (does the judge pick the same winner?) Predictive validity: does the simulator rank agent variants the way real users do?
Canary items with known verdicts Positive controls (a simulator you know is bad) and negative controls (an unhelpful user, no user)
Judge versioning, re-validation on change Simulator versioning, re-validation when its model, prompt or settings change

The idea is older than LLMs. Spoken-dialogue research faced it in the 2000s: Schatzmann, Georgila and Young (SIGdial 2005, ACL Anthology) found there were no established criteria for evaluating simulations and that simple statistics were still enough to tell synthetic dialogues from real ones, which is today's discriminability test. Jason Williams (IEEE ASRU 2007, Microsoft Research) treated a simulation as a predictor of dialogue-system performance and scored it by the divergence (Cramér–von Mises) between the distributions of per-dialogue scores obtained with real and simulated users, which is today's predictive validity in its simplest form. Ai and Litman (ACL-08: HLT, ACL Anthology) reported that automatic measures predicted how human judges ranked simulations better than they predicted the judges' absolute ratings, and Pietquin and Hastie (The Knowledge Engineering Review, 2013) surveyed the metrics and noted that no metric had been commonly adopted. Balog and Zhai's book on user simulation for information access (arXiv 2306.08550) lists the desiderata that frame this part: validity (behaving consistently with observations of real users), interpretability, that a simulation "does not need to be perfect in order to be useful", that relative comparison is a weaker requirement than measuring absolute utility, and sensitivity (the ability to distinguish systems).

7.2 The evidence: how simulated users differ from real ones#

The 2024–2026 research is consistent: LLM-simulated users are useful, measurably different from people, and not trustworthy by default.

  • The benchmark authors audit their own simulators. τ²-bench (Barres et al., arXiv 2506.07982, June 2025) simulates the user with gpt-4.1, gives the simulated user its own tools acting on a separate user database (a mocked phone in the telecom domain), and has the user act only when asked, so its behaviour is tightly coupled to state. Two annotators per conversation then labelled simulator errors:

    Domain Conversations audited Critical errors (prevent task completion) Benign errors Any error
    Airline 100 13 (13%) 34 (34%) 47%
    Retail 50 6 (12%) 14 (28%) 40%
    Telecom 50 3 (6%) 5 (10%) 16%

    The tool-grounded telecom domain has the lowest error rate: constraining the simulator with state and tools made it more reliable. τ²-bench also has a No-User mode (the agent gets the ticket and controls all tools), which isolates reasoning from communication: moving from No-User to the default dual-control mode lowered pass^1 by 18% for gpt-4.1 and 25% for o4-mini.

  • Simulators create an "easy mode". "Mind the Sim2Real Gap in User Simulation for Agentic Tasks" (Zhou et al., arXiv 2603.11245, first posted March 2026, version 2 July 2026; listed for COLM 2026) ran 451 human participants on 165 τ-bench tasks (495 sessions) and compared 31 LLM simulators. Their User-Sim Index (USI, 0–100) averages distributional overlap on communication style, information pattern, clarification and error reaction, plus outcome calibration and evaluative alignment. The human inter-annotator ceiling is 92.7 (version 2; version 1 reported 92.9); the best simulator (DeepSeek-V3.1) reaches 76.0. Agents succeeded 63.6% of the time with human users and, with most general-purpose simulators, more often (up to 77.8%). GPT-4o as a user was polite in 49.0% of turns against 15.3% for humans, wrote short turns 1.0% of the time against 29.0%, and changed strategy in 19.1% of turns against 8.4%. Simulated feedback skews positive too: rating the interactions afterwards, as the human participants did, an LLM evaluator (GPT-5.1) overestimated the AI assistant's human-likeness by 55% and its overall score by 18% of the rating scale relative to the humans' ratings. Higher general capability did not reliably make a better simulator. And the task reward itself disagreed with people: humans judged 70.6% of reward-0 interactions successful and about a third of reward-1 interactions unsuccessful or partial, so validate the outcome grader too (10A.5).

  • The simulator model changes the score, unevenly. "Lost in Simulation" (Seshadri et al., arXiv 2601.17087) ran a user study in the US, India, Kenya and Nigeria on τ-Bench retail: agent success shifted by up to 9 percentage points depending only on which LLM played the user; simulated users underestimated agents on hard tasks and overestimated them on moderate ones; and they were least effective as proxies for speakers of African American Vernacular English and Indian English, with larger calibration errors for those groups.

  • Distributions differ by family and facet. Mehri et al. (arXiv 2605.07847, 2026) clustered user behaviours from real and simulated conversations into discrete distributions and measured the divergence for 24 simulators on coding and writing tasks: large gaps varying by model family, scale and behaviour facet; most simulators resembled each other more than they resembled people; and mixing behaviourally complementary simulators moved the distribution closer to real users.

  • Leakage inflates scores. Zhu, Huang and Sang (arXiv 2403.16416) re-examined simulator-based evaluation of conversational recommenders and found data leakage in conversation histories and simulator replies inflating results, and success depending more on the history than on the simulator's responses.

  • Control conditions separate the simulator's effect. "LLMs Get Lost In Multi-Turn Conversation" (Laban et al., arXiv 2505.06120) split instructions into shards revealed one per turn by a simulated user and measured a 39% average drop from single-turn to multi-turn. To rule out the simulator's rephrasing as the cause, they added a CONCAT condition (all shards rephrased, in one turn), which retained 95.1% of single-turn performance, and they manually inspected several hundred simulated conversations (simulator, classifier or extractor errors under 5%; errors disfavouring the assistant under 2%).

Two practical conclusions. First, none of the popular simulation tools validates its simulator against real users (Part 8.3; τ-bench 2.0's post-hoc judges score the interaction, not the simulator's agreement with people), so validation is yours to do. Second, the published work gives you the method but not a number to borrow: Zhou et al. explicitly do not report whether simulator-based agent rankings match human rankings. Predictive validity is a test you must run on your own agents and users.

7.3 The validity checks at a glance#

Check Question Metric Function
Turn-level realism Do simulated users behave like real ones, feature by feature? Jensen–Shannon divergence per feature against a real-vs-real noise floor realism_report
Discriminability Can a detector tell simulated conversations from real ones? AUC (and separability = max(AUC, 1 − AUC)) discriminability
Goal fidelity and persona consistency Does the simulator pursue its persona's goal with its persona's facts? Invented-fact rate, off-goal rate goal_fidelity, fidelity_summary
Leakage Does it volunteer hidden facts before the agent asks? Unprompted-reveal rate against the real rate leakage_rate
Controls Is the task gradable only through interaction? What does communication cost? Unhelpful-user success (should be ≈ 0); no-user success control_success
Termination Does it end conversations the way people do? End-reason distributions; loop rate termination_report
Difficulty calibration Is it easier or harder than real users, overall and per slice? Sim-to-real gap with a paired bootstrap interval difficulty_gap
Predictive validity Does it rank agent variants as real users do? Spearman, Kendall's tau with a bootstrap interval, pairwise and ship-decision agreement predictive_validity
Panel spread How much does the agent's score depend on which simulator? Per-variant min–max band; rank agreement between simulators simulator_panel
Error audit How often does the simulator make errors that change the outcome? Critical and benign rates with Wilson intervals audit_rates
flowchart TD
    A["Real transcripts on the same task mix<br/>(privacy-scrubbed production logs)"] --> B["Realism report with noise floor"]
    A --> C["Discriminability AUC,<br/>with a known-bad simulator as positive control"]
    D["Simulated conversations"] --> B
    D --> C
    D --> E["Fidelity, leakage, termination"]
    F["Controls: unhelpful user, no user"] --> G["Is the task testing interaction?"]
    H["Human study: K variants, same tasks"] --> I["Sim-to-real gap per slice"]
    H --> J["Predictive validity:<br/>rank and decision agreement"]
    B --> K{"Validity card"}
    C --> K
    E --> K
    G --> K
    I --> K
    J --> K
    K -- "pass" --> L["Freeze and version the simulator;<br/>use it for relative comparisons"]
    K -- "warn" --> M["Fix the persona cards or the model;<br/>re-run the same checks"]
    M --> D
    L -.->|"model, prompt or settings change"| D

7.4 The data: conversations and behaviour features#

sim_validation.py works on two dataclasses. A Turn has a role, text and metadata: user turns record which hidden facts they revealed, the facts they stated (key to value) and their intent; agent turns record what they asked_for. A Conversation has its source ("real" or "sim:<name>@<version>"), task, persona card (goal and facts, as in 10A.2, 13.2), turns, outcome, how it ended and a slice. For real conversations you get the metadata from your annotation or an extractor; for simulated ones, have the simulator report it, since you control its prompt.

The realism checks compare behaviour features of the user side. default_features computes seven bucketed features per conversation, mirroring the families in Zhou et al.: words per user turn, short-turn rate, politeness rate, question rate (style and clarification), the share of hidden facts given in the first turn (information pattern), the number of user turns and how the conversation ended (shape). Two rules about features:

  • The features decide the verdict. A simulator can match seven features and differ wildly on an eighth you did not measure. Publish the feature list with every realism result, and add features for the behaviours your agent depends on (corrections, frustration markers, language switching).
  • Bucket them. Distributions over a few categories are robust with tens of conversations; raw continuous values need far more data for the same divergence estimate.

js_divergence is the Jensen–Shannon divergence of 10A.9, 5.2: symmetric, 0 for identical distributions, at most ln 2 ≈ 0.693. It is defined again in this file because 10A.9's version lives in the stand-alone script drift_stats.py, not in a package module; the formula is identical.

7.5 Turn-level realism against a noise floor#

The trap with divergence between small samples is that it is never zero, even between two samples of the same population. A JS of 0.05 might mean "different" or "small sample". So realism_report compares like with like: in each of 200 bootstrap rounds it splits the real conversations into two disjoint halves A and B and draws a simulated sample S the size of a half, then records JS(A, B) (what sampling noise alone produces) and JS(A, S) (the gap you are testing). A feature is flagged when the mean JS(A, S) exceeds both the 95th percentile of JS(A, B), the noise floor, and a minimum effect (min_js, 0.02 by default).

Output · from the run in 7.1611 lines
-- 1. realism (JS / real-vs-real noise floor p95; FLAG = JS above both the floor and 0.02) --
feature                    sim_eager@v1        sim_grounded@v1       sim_impatient@v1
words_per_turn         0.297/0.051 FLAG       0.028/0.051            0.202/0.051 FLAG
short_turn_rate        0.000/0.000            0.007/0.000            0.038/0.000 FLAG
polite_rate            0.133/0.068 FLAG       0.027/0.068            0.123/0.068 FLAG
question_rate          0.076/0.063 FLAG       0.022/0.063            0.051/0.063     
first_turn_info        0.246/0.067 FLAG       0.044/0.067            0.073/0.067 FLAG
user_turns             0.042/0.037 FLAG       0.007/0.037            0.042/0.037 FLAG
ended_by               0.025/0.049            0.009/0.049            0.071/0.049 FLAG
polite_rate real={'0': 0.68, '0-25%': 0.02, '25-50%': 0.18, '>50%': 0.12}
            eager={'0': 0.29, '25-50%': 0.2, '>50%': 0.51}

Read the columns as "JS / noise floor"; FLAG means the JS is above both the floor and the minimum effect of 0.02. The eager simulator is flagged on length, politeness, questions, first-turn information and conversation length; its politeness distribution shows why (51% of its conversations are polite in more than half the turns, against 12% of real ones), the same pattern Zhou et al. measured for GPT-4o. The impatient simulator is flagged on almost everything. The grounded simulator is within the floor on all seven features. Look at its short-turn row, though: JS 0.007 against a floor of exactly 0.000. Real users in this sample never write turns of three words or fewer, so every real-vs-real split has JS = 0, and any simulated short turn at all would clear that floor. That is a degenerate noise floor, and it is why realism_report also requires a minimum effect (min_js=0.02 by default) before it flags; smoothing the distributions with a small pseudo-count is the other common guard. Without the guard, this row would be flagged for a difference of a few conversations.

Two cautions about what the flag means. It is a screening rule, not a test with a known error rate: comparing a mean JS with the 95th percentile of the null makes false flags rarer than 5% per feature, not equal to it. If you need a per-feature test, compare JS(A, S) with the null distribution of JS(A, S′), where S′ is drawn from the real data at the same size, report a p-value, and correct for the number of features (10A.8, 2.6). Either way, act on the pattern across features, not on one flag.

When you want a test rather than a threshold for one numeric feature (mean words per turn, say), permutation_two_sample(xs, ys) gives a two-sided permutation p-value for a difference in means between real and simulated conversations: shuffle the pooled values, re-split, and count how often the gap is at least as large as observed. The same test applied to per-conversation outcome scores under real and simulated users of the same agent is the modern form of Williams's score-distribution check.

7.6 Discriminability: can anything tell them apart?#

If a detector can tell simulated conversations from real ones, the simulator differs in ways that may matter. discriminability(real, sim, detector) computes the AUC of any "how simulated does this look?" score, with simulated conversations as positives, using the Mann–Whitney form (the probability that a random simulated conversation scores above a random real one, ties counting half). 0.5 means indistinguishable.

Three details make the check meaningful:

  • Below 0.5 is also distinguishable. An AUC of 0.23 means the simulator differs in the opposite direction from the one the detector looks for (the impatient simulator is less polite and terser than real users). The check therefore uses separability = max(AUC, 1 − AUC).
  • Run a positive control. A detector that cannot catch a known-bad simulator proves nothing when it fails to catch yours. The demo's sim_dump simulator reveals everything, at length, politely; the detector must score it near 1.
  • Prefer a simple detector you can read, then a trained or LLM one. A feature rule tells you why conversations look simulated. An LLM judge asked "was this written by a person?" is itself an unvalidated instrument (Zhou et al. found LLM raters inflating interaction-quality ratings well above people's); if you use one, validate it on labelled pairs first (10A.5).
Output6 lines
-- 2. discriminability (AUC, sim = positive) --
  sim_eager@v1       AUC=0.897  separability=0.897
  sim_grounded@v1    AUC=0.566  separability=0.566
  sim_impatient@v1   AUC=0.232  separability=0.768
  positive control   AUC=0.975  separability=0.975
  real vs real       AUC=0.499  separability=0.501

The real-versus-real AUC of 0.499 confirms the detector is not biased by the split; the positive control at 0.975 confirms it can see a bad simulator; the grounded simulator at 0.566 is close to indistinguishable on these features.

7.7 Goal fidelity, persona consistency and invented facts#

A simulator must pursue its persona's goal with its persona's facts. goal_fidelity(conversation) compares every fact the simulated user stated with the persona card and lists invented facts (a key the card does not have, or a different value), and counts persona breaks (turns whose intent is not the persona's goal). An invented order number is the most damaging simulator error there is: the agent then "fails" on an order that never existed, and the failure is charged to the agent. fidelity_summary gives the invented-fact rate per conversation with a Wilson interval, and the off-goal rate.

Persona consistency over long conversations (temperament, language, stated constraints) needs a judge when it cannot be read from metadata; 10A.7's list of simulator pitfalls names persona drift as one to test for (10A.7, 6.1). Validate that judge on a small labelled set before using its numbers.

7.8 Leakage and the two controls#

Leakage is the simulator handing the agent what it was supposed to work for. 10A.2, 13.4 lists "leaks the goal" among simulator failures; here it becomes a number. leakage_rate(conversations, hidden_keys=...) counts hidden facts the user volunteered before the agent asked for them, as a share of all hidden facts. Compare it with the real rate, not with zero: real users front-load too (in the fixture, 34% of facts arrive unprompted from real users). The problem is a simulator far above the real rate, because it removes exactly the clarifying skill you wanted to measure.

Two control conditions tell you what the task and the simulator are really testing:

  • The unhelpful-user control. Run the agent against a scripted user that answers "I don't know" to everything, on tasks that require information from the user. Success should be near zero. Any task that succeeds is a finding: the agent can get the answer elsewhere (a lookup tool, the task prompt), or the grader is broken. Either way, that task does not test interaction. control_success(results) reports the rate with a Wilson interval and lists the suspects.
  • The no-user control (τ²-bench's No-User mode). Give the agent every fact and no user. Its success is the ceiling for the task without communication; the difference from success under a simulator is the communication cost that simulator imposes. A simulator with almost no communication cost is suspiciously easy.
Output11 lines
-- 3. leakage (facts volunteered before the agent asked) --
  real               0.339  CI (0.274, 0.411)
  sim_eager@v1       0.836  CI (0.794, 0.871)
  sim_grounded@v1    0.4  CI (0.351, 0.451)
  sim_impatient@v1   0.228  CI (0.187, 0.274)
-- 6. controls (production agent v2) --
  unhelpful user: {'rate': 0.033, 'ci': (0.006, 0.167), 'succeeded': ['U07']}
  no-user (all facts given): rate=0.867 CI (0.794, 0.916)
  with sim_eager@v1       rate=0.825  communication cost=+0.042
  with sim_grounded@v1    rate=0.750  communication cost=+0.117
  with sim_impatient@v1   rate=0.500  communication cost=+0.367

The eager simulator volunteers 84% of hidden facts against 34% for real users, and accordingly imposes almost no communication cost (0.042). The unhelpful-user control succeeds on exactly one task, U07, which is the planted task where the agent can look the facts up itself: a task that does not test interaction and should be removed from a clarification suite or graded differently.

7.9 Termination behaviour#

People abandon conversations; simulators often do not. A simulator that never gives up lets an agent that wastes turns still succeed eventually, which is "easy mode" through patience. termination_report(real, sim) compares the end-reason distributions (agent finished, user gave up, turn limit, loop) with a JS divergence and reports loop rates (the same user message three or more times, the infinite-loop failure in 10A.2's simulator table).

Output10 lines
-- 4. termination --
  real               {'agent_end': 0.933, 'gave_up': 0.067}
  sim_eager@v1       {'agent_end': 1.0}  JS=0.024
  sim_grounded@v1    {'agent_end': 0.9, 'gave_up': 0.1}  JS=0.002
  sim_impatient@v1   {'agent_end': 0.658, 'gave_up': 0.342}  JS=0.062
-- 5. fidelity (invented facts, off-goal turns) --
  sim_eager@v1       {'n': 120, 'invented_rate': 0.042, 'invented_ci': (0.018, 0.094), 'off_goal_rate': 0.083}
  sim_grounded@v1    {'n': 120, 'invented_rate': 0.0, 'invented_ci': (0.0, 0.031), 'off_goal_rate': 0.0}
  sim_impatient@v1   {'n': 120, 'invented_rate': 0.0, 'invented_ci': (0.0, 0.031), 'off_goal_rate': 0.0}
  example sim:sim_eager@v1:v2:U02:2: {'pursued': True, 'invented': [('item', 'something else')], 'persona_breaks': 0}

The eager simulator never gives up (100% agent-ended against 6.7% abandonment for real users) and invents a fact in 4% of conversations; the impatient one gives up five times as often as real users.

7.10 sim_validation.py, sections 1 and 2: realism, discriminability, fidelity, leakage and termination#

python
"""evalkit/sim_validation.py — validate a user simulator before trusting it.

Stdlib only. Lesson 10A.12. A user simulator is a measuring instrument: an
agent's score under simulation is only as good as the simulator's agreement
with real users. This file measures that agreement the way 10A.5 measures a
judge's agreement with human labels:

  realism            per-feature distributions of user behaviour, real vs
                     simulated, as Jensen-Shannon divergence against a
                     real-vs-real noise floor
  discriminability   can a detector tell simulated from real? (AUC)
  fidelity           goal pursuit, invented facts, persona breaks
  leakage            facts volunteered before the agent asked; unhelpful-user
                     and no-user controls
  termination        how conversations end (goal met, gave up, max turns, loop)
  calibration        sim-to-real success gap per task and per slice
  predictive         do agent variants RANK the same under the simulator as
                     under real users? (Spearman, Kendall, pairwise and
                     ship-decision agreement, bootstrap over tasks)
  panel and audit    spread across simulator models; human-audited error rates

js_divergence is defined here (same formula as 10A.9's stand-alone
drift_stats.py, which is a script, not a package module). Spearman and
Kendall come from judge_validation.py (10A.5); paired statistics
from compare.py (10A.8); Wilson intervals from agent_eval.py (10A.7).
"""
from __future__ import annotations

import math
import random
import re
import statistics
from collections import Counter
from dataclasses import dataclass, field
from itertools import combinations
from typing import Callable

from agent_eval import wilson_interval
from compare import paired_bootstrap_ci, paired_diffs
from judge_validation import kendall_tau_b, spearman


# ---------------------------------------------------------------------------
# data
# ---------------------------------------------------------------------------

@dataclass
class Turn:
    role: str                                   # "user" | "agent"
    text: str
    meta: dict = field(default_factory=dict)
    # user turns: {"revealed": [fact keys], "stated": {key: value}, "intent": str}
    # agent turns: {"asked_for": [fact keys]}


@dataclass
class Conversation:
    conv_id: str
    source: str                  # "real" | "sim:<name>@<version>"
    task_id: str
    persona: dict                # card (10A.2, 13.2): goal, facts, temperament, ...
    turns: list[Turn]
    outcome: bool | None = None  # agent success as the world graded it
    ended_by: str = "agent_end"  # agent_end | gave_up | max_turns | loop
    slice_: str = "all"

    def user_turns(self) -> list[Turn]:
        return [t for t in self.turns if t.role == "user"]


FeatureFn = Callable[[Conversation], dict[str, str]]

POLITE = re.compile(r"\b(please|thanks|thank you|appreciate|kindly|sorry)\b", re.I)


def _bucket(x: float, edges: list[float], labels: list[str]) -> str:
    for e, lab in zip(edges, labels):
        if x <= e:
            return lab
    return labels[-1]


def default_features(conv: Conversation) -> dict[str, str]:
    """Bucketed, per-conversation features of the USER side. Publish your
    feature list with any realism verdict: the features decide the verdict.
    These mirror the families in Zhou et al. (2026): style (length,
    politeness, short turns), information pattern (what arrives in turn 1),
    clarification (questions back) and conversation shape (length, ending)."""
    uts = conv.user_turns()
    if not uts:
        return {"ended_by": conv.ended_by}
    words = [len(t.text.split()) for t in uts]
    facts = conv.persona.get("facts", {})
    first = set(uts[0].meta.get("revealed", []))
    share_first = len(first & set(facts)) / len(facts) if facts else 0.0
    rate = lambda pred: sum(1 for t in uts if pred(t)) / len(uts)
    four = [0.0, 0.25, 0.5]
    four_l = ["0", "0-25%", "25-50%", ">50%"]
    return {
        "words_per_turn": _bucket(statistics.fmean(words), [3, 8, 15], ["1-3", "4-8", "9-15", "16+"]),
        "short_turn_rate": _bucket(rate(lambda t: len(t.text.split()) <= 3), four, four_l),
        "polite_rate": _bucket(rate(lambda t: bool(POLITE.search(t.text))), four, four_l),
        "question_rate": _bucket(rate(lambda t: "?" in t.text), four, four_l),
        "first_turn_info": _bucket(share_first, [0.0, 0.5, 0.99], ["none", "some", "most", "all"]),
        "user_turns": _bucket(len(uts), [2, 4, 6], ["1-2", "3-4", "5-6", "7+"]),
        "ended_by": conv.ended_by,
    }


def distribution(convs: list[Conversation], feature: str,
                 features: FeatureFn = default_features) -> dict[str, float]:
    c = Counter(features(cv).get(feature, "n/a") for cv in convs)
    n = sum(c.values())
    return {k: v / n for k, v in c.items()}


def js_divergence(p: dict[str, float], q: dict[str, float]) -> float:
    """Jensen-Shannon divergence (natural log): symmetric, 0 for identical
    distributions, at most ln 2 = 0.693. Same formula as 10A.9's
    drift_stats.py; defined here so the package has no script dependency."""
    keys = set(p) | set(q)
    m = {k: (p.get(k, 0.0) + q.get(k, 0.0)) / 2 for k in keys}

    def kl(a: dict[str, float]) -> float:
        return sum(a[k] * math.log(a[k] / m[k]) for k in keys if a.get(k, 0.0) > 0)

    return 0.5 * kl(p) + 0.5 * kl(q)


# ---------------------------------------------------------------------------
# realism and discriminability
# ---------------------------------------------------------------------------

def realism_report(real: list[Conversation], sim: list[Conversation], *,
                   features: FeatureFn = default_features, n_boot: int = 200,
                   min_js: float = 0.02, seed: int = 0) -> dict:
    """Per feature: JS(real, sim) against the real-vs-real noise floor.

    JS between two small samples is never 0, even from the same population,
    so compare like with like: in each bootstrap round draw two disjoint
    halves of the real set (A, B) and a sim sample the size of a half (S).
    noise = JS(A, B) is what sampling alone produces; js = JS(A, S) is the
    gap you are testing. Flag a feature when mean(js) exceeds BOTH p95(noise)
    and an absolute minimum effect `min_js`.

    This is a screening rule, not a test with a known error rate. The
    minimum guards against a degenerate floor: when a feature never varies
    in the real sample, every real-vs-real split gives JS = 0 and any
    simulated difference, however tiny, would clear it. For a per-feature
    p-value, compare JS(A, S) with the null distribution of JS(A, S'), with
    S' drawn from real data at the same size, and correct for the number of
    features (10A.8, 2.6)."""
    rng = random.Random(seed)
    names = list(features(real[0]))
    noise = {f: [] for f in names}
    gap = {f: [] for f in names}
    half = len(real) // 2
    for _ in range(n_boot):
        r = real[:]
        rng.shuffle(r)
        a, b = r[:half], r[half:2 * half]
        s = [sim[rng.randrange(len(sim))] for _ in range(half)]
        for f in names:
            pa = distribution(a, f, features)
            noise[f].append(js_divergence(pa, distribution(b, f, features)))
            gap[f].append(js_divergence(pa, distribution(s, f, features)))
    out = {}
    for f in names:
        floor = sorted(noise[f])[int(0.95 * (n_boot - 1))]
        js = statistics.fmean(gap[f])
        out[f] = {"js": round(js, 3), "noise_p95": round(floor, 3),
                  "flag": js > max(floor, min_js),
                  "real": {k: round(v, 2) for k, v in sorted(distribution(real, f, features).items())},
                  "sim": {k: round(v, 2) for k, v in sorted(distribution(sim, f, features).items())}}
    return out


def permutation_two_sample(xs: list[float], ys: list[float], *, iters: int = 10_000,
                           seed: int = 0) -> float:
    """Two-sided permutation p-value for 'do xs and ys have the same mean?'
    (unpaired: different conversations). Shuffle the pooled values, re-split,
    count how often the mean gap is at least the observed one."""
    rng = random.Random(seed)
    obs = abs(statistics.fmean(xs) - statistics.fmean(ys))
    pooled, n = xs + ys, len(xs)
    hits = 0
    for _ in range(iters):
        rng.shuffle(pooled)
        if abs(statistics.fmean(pooled[:n]) - statistics.fmean(pooled[n:])) >= obs - 1e-12:
            hits += 1
    return (hits + 1) / (iters + 1)


def auc_mann_whitney(pos: list[float], neg: list[float]) -> float:
    """P(score of a random positive > score of a random negative), ties 0.5.
    0.5 = the detector cannot tell the groups apart; 1.0 = perfectly."""
    if not pos or not neg:
        return float("nan")
    wins = sum((p > q) + 0.5 * (p == q) for p in pos for q in neg)
    return wins / (len(pos) * len(neg))


def discriminability(real: list[Conversation], sim: list[Conversation],
                     detector: Callable[[Conversation], float]) -> dict:
    """AUC of a 'how simulated does this look?' detector, sim = positive.
    An AUC far BELOW 0.5 is just as distinguishable (the simulator differs in
    the other direction), so the check uses separability = max(AUC, 1 - AUC).
    Run it on a known-bad simulator too: a detector that cannot catch the
    positive control proves nothing when it fails to catch yours."""
    auc = auc_mann_whitney([detector(c) for c in sim], [detector(c) for c in real])
    return {"auc": round(auc, 3), "separability": round(max(auc, 1 - auc), 3),
            "n_real": len(real), "n_sim": len(sim)}
python
# ---------------------------------------------------------------------------
# evalkit/sim_validation.py, section 2 of 3 (append after section 1)
# fidelity, leakage, controls, termination
# ---------------------------------------------------------------------------

def goal_fidelity(conv: Conversation) -> dict:
    """Did the simulated user pursue the persona's goal with the persona's
    facts? invented = facts stated that the card does not contain (or with a
    different value): the agent then 'fails' on a world that never existed."""
    facts = conv.persona.get("facts", {})
    goal = conv.persona.get("goal")
    invented, breaks = [], 0
    for t in conv.user_turns():
        for k, v in t.meta.get("stated", {}).items():
            if facts.get(k) != v:
                invented.append((k, v))
        if t.meta.get("intent") not in (None, goal):
            breaks += 1
    return {"pursued": breaks == 0, "invented": invented, "persona_breaks": breaks}


def fidelity_summary(convs: list[Conversation]) -> dict:
    g = [goal_fidelity(c) for c in convs]
    inv = sum(1 for x in g if x["invented"])
    off = sum(1 for x in g if not x["pursued"])
    return {"n": len(convs),
            "invented_rate": round(inv / len(convs), 3),
            "invented_ci": tuple(round(v, 3) for v in wilson_interval(inv, len(convs))),
            "off_goal_rate": round(off / len(convs), 3)}


def leakage_rate(convs: list[Conversation], *, hidden_keys: set[str]) -> dict:
    """Share of hidden facts the user volunteered BEFORE the agent asked for
    them. Compare with the real rate, not with zero: some real users
    front-load too. The danger is a simulator far above the real rate."""
    leaked = total = 0
    for c in convs:
        asked: set[str] = set()
        present = set(c.persona.get("facts", {})) & hidden_keys
        total += len(present)
        done: set[str] = set()
        for t in c.turns:
            if t.role == "agent":
                asked |= set(t.meta.get("asked_for", []))
            else:
                for k in t.meta.get("revealed", []):
                    if k in present and k not in done:
                        done.add(k)
                        leaked += k not in asked
    return {"leak_rate": round(leaked / total, 3) if total else 0.0,
            "ci": tuple(round(v, 3) for v in wilson_interval(leaked, total)),
            "leaked": leaked, "facts": total}


def control_success(results: dict[str, bool]) -> dict:
    """Success rate of a control condition (unhelpful user, no-user) with a
    Wilson interval and the tasks that succeeded — for the unhelpful-user
    control those tasks are the suspects (they leak the answer elsewhere)."""
    k, n = sum(results.values()), len(results)
    return {"rate": round(k / n, 3) if n else None,
            "ci": tuple(round(v, 3) for v in wilson_interval(k, n)),
            "succeeded": sorted(t for t, ok in results.items() if ok)}


def termination_report(real: list[Conversation], sim: list[Conversation]) -> dict:
    """How conversations end, real vs sim: a simulator that never gives up
    lets persistent-but-bad agents pass."""
    def dist(cs: list[Conversation]) -> dict[str, float]:
        c = Counter(x.ended_by for x in cs)
        return {k: round(v / len(cs), 3) for k, v in sorted(c.items())}

    def loops(cs: list[Conversation]) -> float:
        n = 0
        for x in cs:
            texts = Counter(t.text for t in x.user_turns())
            n += any(v >= 3 for v in texts.values())
        return round(n / len(cs), 3)

    pr, ps = dist(real), dist(sim)
    return {"real": pr, "sim": ps, "js": round(js_divergence(pr, ps), 3),
            "loop_rate_real": loops(real), "loop_rate_sim": loops(sim)}

7.11 Difficulty calibration and the sim-to-real gap#

The sim-to-real gap is the agent's success under the simulator minus its success with real users, on the same tasks. difficulty_gap(sim_success, human_success, slices=...) computes it per task (paired, with 10A.8's paired_diffs) and reports the mean with a bootstrap interval, overall and per slice. Positive means the simulator is easier than real users.

Report it per slice because the gap is rarely uniform: Seshadri et al. found simulators underestimating agents on hard tasks and overestimating them on moderate ones, and miscalibrated differently for different user populations. Population slices (language variety, age group, accessibility needs, the regions you serve) belong in this table when your users differ; a simulator calibrated on one population can be badly wrong for another, which makes simulator calibration a fairness question as well as an accuracy one (10A.10, 6.2).

A known, stable gap is not fatal. If the simulator is consistently 0.10 easier and ranks agents correctly, you can use it for comparisons and report absolute numbers with the gap stated. An unknown gap means every absolute number you publish from the simulator is unanchored.

Output4 lines
-- 8. difficulty calibration: sim - human, paired over tasks (production agent v2) --
  sim_eager@v1       overall +0.117 CI (-0.033, 0.275)   easy +0.167   hard +0.067
  sim_grounded@v1    overall +0.108 CI (-0.025, 0.25)   easy +0.100   hard +0.117
  sim_impatient@v1   overall -0.175 CI (-0.3, -0.058)   easy -0.050   hard -0.300

7.12 Predictive validity: the decisive test#

Everything so far checks whether the simulator looks right. Predictive validity checks whether it decides right: if you evaluate several agent variants with the simulator and with real users, do they come out in the same order, and would you make the same ship decisions? This is the same question 10A.9, 1.3 asks of offline metrics ("does offline predict online?") and 10A.5, 1.2 asks of judges ("does the judge pick the same winner?"), and it is the property Balog and Zhai call sensitivity and Williams called predicting system performance.

The design:

  1. Choose K agent variants that differ in ways you care about (a prompt change, a model change, a policy change). K ≥ 5, because rank statistics over few items take only a handful of values: with K = 3, Kendall's tau can only be ±1 or ±1/3.
  2. Run every variant on the same tasks with real users (a human study, or a controlled slice of production traffic) and with the simulator.
  3. predictive_validity(sim_scores, human_scores, threshold=..., per_task=...) reports:
    • Spearman and Kendall's tau-b between the simulator's and humans' mean scores per variant (10A.5's spearman and kendall_tau_b);
    • pairwise agreement: the share of variant pairs for which both pick the same winner;
    • decision agreement: the share of variants on the same side of your ship threshold;
    • a bootstrap interval for tau, resampling tasks, when you pass per-task scores;
    • the mean gap, because rank correlation hides a uniform offset;
    • a warning when K < 5.
Output6 lines
-- 9. predictive validity (ship threshold 0.60) --
  sim_eager@v1       spearman=+0.46 tau=+0.32 CI (-0.316, 0.6) pairwise=0.67 decisions=0.40   sim order: v5 > v1 > v2 > v3 > v4
  sim_grounded@v1    spearman=+0.97 tau=+0.95 CI (0.105, 1.0) pairwise=1.00 decisions=1.00   sim order: v2 > v5 > v1 > v4 > v3
  sim_impatient@v1   spearman=+0.20 tau=+0.10 CI (-0.2, 0.8) pairwise=0.56 decisions=0.80   sim order: v2 > v4 > v3 > v1 > v5
  human              order: v2 > v5 > v1 = v4 > v3
  with only 3 variants: {'k_variants': 3, 'spearman': 0.5, 'kendall_tau_b': 0.333, 'pairwise_agreement': 0.667, 'mean_gap': 0.25, 'warning': 'K=3 variants: rank statistics are coarse; use K >= 5'}

The grounded simulator matches the human order except that the humans tie v1 and v4 (0.467 each; the human line prints v1 = v4), which is why tau-b is 0.95 rather than 1.0; every untied pair and every ship decision agrees. The eager simulator puts v5, the slow careful agent, first, ahead of the production agent v2, because a user who never gives up never punishes its extra confirmation turn; real users put v2 clearly first (0.70 against 0.48). It also ranks v3, the agent that guesses instead of asking, above v4, because a user who volunteers every fact makes guessing harmless. And it would have shipped v1, v3 and v5, all of which real users place below the threshold: decision agreement 0.40. The impatient simulator's order is close to unrelated to the humans' (tau 0.10). Notice the interval on the grounded simulator's tau: 0.105 to 1.0 with 30 tasks. Even a good simulator needs a larger human study before its ranking is established rather than plausible, which is why the validity card in 7.15 gates on the interval's lower bound, not on the point estimate. And the three-variant line shows the coarse values K = 3 allows.

7.13 How many human conversations do you need?#

No published number answers this for your product, so compute it from the precision you need:

  • For a success rate, the 95% Wilson half-width at about 70% success is roughly ±0.16 with 30 conversations, ±0.11 with 60, ±0.08 with 120, ±0.06 with 240 and ±0.04 with 480 (the demo prints these from wilson_interval). To see a sim-to-real gap of 0.10 per variant you need on the order of a few hundred human conversations per variant, or a paired design (same tasks under both), which difficulty_gap uses and which narrows the interval considerably.
  • For predictive validity, the unit is the variant, and the precision comes from both K and the tasks per variant: bootstrap tau over tasks (as predictive_validity does) and keep adding tasks until the interval excludes the values that would change your decision.
  • Verified reference points for scale: τ²-bench audited 50–100 simulated conversations per domain with two annotators; Zhou et al. used 451 participants on 165 tasks (495 sessions); Laban et al. inspected several hundred simulated conversations by hand.

Production traffic is the cheapest source of real conversations, with privacy handled as in 10A.9, 6.4 and Module 12. For predictive validity you also need several agent variants exposed to real users, which an online experiment provides (10A.9, Part 4): every A/B test you run is a free predictive-validity data point for your simulator, if you also run both arms under the simulator.

7.14 Simulator panels, versioning, seeds and drift#

  • Use a panel, report a band. Score each agent with two or more simulators (different models, or different persona mixes) and report the agent's score as the min–max band across them. Seshadri et al. saw up to 9 points of movement from the user model alone; Yang and Shi saw an architecture comparison change its conclusion under a second simulator. simulator_panel reports each variant's band and the rank agreement between simulators. Mehri et al.'s finding that mixing complementary simulators moves the distribution closer to real users suggests the panel can also be the simulator.
  • Version the simulator like the agent. Record the model id, the prompt (or its hash), the persona set, the sampling settings and the seed policy with every result, and treat any change as a new instrument that needs re-validation, exactly like a judge change in 10A.5, 6.4. A provider updating the model behind an alias can move every agent score overnight with no change to the agent; keep a small frozen validation set (real conversations plus the known-bad positive control) and re-run the realism and discriminability checks on a schedule.
  • Separate simulator noise from agent noise. Re-run the same agent with several simulator seeds and the same simulator with several agent seeds; if the score varies more across simulator seeds, more agent trials will not help (the variance decomposition idea of 10A.5, 7.3).
  • Audit simulator errors by hand. Following τ²-bench, have two people label a sample of simulated conversations for simulator errors, critical (would prevent task completion) or benign, and report the rates with intervals (audit_rates). Exclude or re-run conversations with critical simulator errors before scoring the agent, and say how many you excluded.
  • Online, simulators are diagnostics. Scheduled simulator probes against production (10A.9, 3.5) tell you that conversation quality moved; they are not a release gate unless the simulator has passed predictive validity for that kind of change.
Output12 lines
-- 10. simulator panel (each variant's score as a band) --
  v1: {'min': 0.175, 'max': 0.842, 'spread': 0.667}
  v2: {'min': 0.525, 'max': 0.817, 'spread': 0.292}
  v3: {'min': 0.208, 'max': 0.625, 'spread': 0.417}
  v4: {'min': 0.358, 'max': 0.508, 'spread': 0.15}
  v5: {'min': 0.042, 'max': 0.925, 'spread': 0.883}
  rank agreement between simulators: {'sim_eager@v1 vs sim_grounded@v1': 0.4, 'sim_eager@v1 vs sim_impatient@v1': -0.6, 'sim_grounded@v1 vs sim_impatient@v1': 0.0}

-- 11. human audit of 50 simulated conversations each (tau2-bench style) --
  sim_eager@v1       critical=0.04 CI (0.011, 0.135)  benign=0.04
  sim_grounded@v1    critical=0.0 CI (0.0, 0.071)  benign=0.0
  sim_impatient@v1   critical=0.0 CI (0.0, 0.071)  benign=0.0

The panel bands are wide (v5's score runs from 0.04 to 0.93 depending on the simulator), and the simulators barely agree with each other on rankings (tau from −0.6 to 0.4), which is what "the simulator is part of the measurement" looks like in numbers. The audit finds critical errors (invented facts) in 4% of the eager simulator's conversations.

7.15 sim_validation.py, section 3: calibration, predictive validity, panels and the validity card#

validity_card turns the reports into one screen per simulator with PASS or WARN per check. The decisive check has a third state: it passes only when the lower bound of tau's bootstrap interval clears the threshold, and reads PROVISIONAL when the point estimate clears it but the interval does not, because 7.13's rule is to keep adding tasks until the interval excludes the values that would change your decision. The thresholds in its signature (separability ≤ 0.7, |gap| ≤ 0.10, tau ≥ 0.6, invented facts ≤ 2%, leakage within 10 points of the real rate) are example policies, not standards: set your own before you run the checks, and write them down.

python
# ---------------------------------------------------------------------------
# evalkit/sim_validation.py, section 3 of 3 (append after section 2)
# calibration and predictive validity
# ---------------------------------------------------------------------------

def difficulty_gap(sim_success: dict[str, float], human_success: dict[str, float], *,
                   slices: dict[str, str] | None = None, seed: int = 0) -> dict:
    """Sim-to-real gap = sim success - human success on the SAME tasks
    (paired), with a bootstrap CI, overall and per slice. Positive = the
    simulator is easier than real users ('easy mode')."""
    def block(ids: list[str]) -> dict:
        d = paired_diffs({i: human_success[i] for i in ids}, {i: sim_success[i] for i in ids})
        m, lo, hi = paired_bootstrap_ci(d, iters=5000, seed=seed)
        return {"n": len(d), "gap": round(m, 3), "ci": (round(lo, 3), round(hi, 3))}

    shared = sorted(set(sim_success) & set(human_success))
    out = {"overall": block(shared)}
    for name in sorted(set((slices or {}).get(i, "all") for i in shared)) if slices else []:
        out[name] = block([i for i in shared if slices[i] == name])
    return out


def _pairwise_agreement(a: dict[str, float], b: dict[str, float]) -> float:
    pairs = list(combinations(sorted(a), 2))
    agree = sum((a[x] > a[y]) == (b[x] > b[y]) for x, y in pairs
                if a[x] != a[y] and b[x] != b[y])
    counted = sum(1 for x, y in pairs if a[x] != a[y] and b[x] != b[y])
    return agree / counted if counted else float("nan")


def predictive_validity(sim_scores: dict[str, float], human_scores: dict[str, float], *,
                        threshold: float | None = None,
                        per_task: tuple[dict, dict] | None = None,
                        n_boot: int = 1000, seed: int = 0) -> dict:
    """The decisive test: does the simulator RANK agent variants the way real
    users do? sim_scores / human_scores map variant -> mean success.

    spearman, kendall_tau_b   rank agreement across the K variants
    pairwise_agreement        share of variant pairs with the same winner
    decision_agreement        share of variants on the same side of the
                              ship threshold (if given)
    ci                        bootstrap over TASKS when per_task =
                              (sim[variant][task], human[variant][task])
    With K < 5 variants, rank statistics take only a few coarse values
    (K = 3: Kendall's tau is ±1 or ±1/3), so treat them as anecdotes.
    """
    vs = sorted(set(sim_scores) & set(human_scores))
    s = [sim_scores[v] for v in vs]
    h = [human_scores[v] for v in vs]
    out = {"k_variants": len(vs),
           "spearman": round(spearman(s, h), 3),
           "kendall_tau_b": round(kendall_tau_b(s, h), 3),
           "pairwise_agreement": round(_pairwise_agreement(sim_scores, human_scores), 3),
           "mean_gap": round(statistics.fmean(a - b for a, b in zip(s, h)), 3)}
    if threshold is not None:
        out["decision_agreement"] = round(statistics.fmean(
            (sim_scores[v] >= threshold) == (human_scores[v] >= threshold) for v in vs), 3)
    if len(vs) < 5:
        out["warning"] = f"K={len(vs)} variants: rank statistics are coarse; use K >= 5"
    if per_task is not None:
        sim_t, hum_t = per_task
        tasks = sorted(set.intersection(*(set(sim_t[v]) & set(hum_t[v]) for v in vs)))
        rng = random.Random(seed)
        taus = []
        for _ in range(n_boot):
            pick = [tasks[rng.randrange(len(tasks))] for _ in tasks]
            ms = [statistics.fmean(sim_t[v][t] for t in pick) for v in vs]
            mh = [statistics.fmean(hum_t[v][t] for t in pick) for v in vs]
            tau = kendall_tau_b(ms, mh)
            if tau == tau:                       # skip NaN (all tied)
                taus.append(tau)
        taus.sort()
        out["kendall_ci"] = (round(taus[int(0.025 * len(taus))], 3),
                             round(taus[min(len(taus) - 1, int(0.975 * len(taus)))], 3))
    return out


def simulator_panel(scores_by_sim: dict[str, dict[str, float]]) -> dict:
    """The same agent variants scored by several simulators: report each
    variant's score as a band (min-max), and how often the simulators agree
    with each other on rankings."""
    sims = sorted(scores_by_sim)
    variants = sorted(set.intersection(*(set(scores_by_sim[s]) for s in sims)))
    bands = {v: {"min": round(min(scores_by_sim[s][v] for s in sims), 3),
                 "max": round(max(scores_by_sim[s][v] for s in sims), 3),
                 "spread": round(max(scores_by_sim[s][v] for s in sims)
                                 - min(scores_by_sim[s][v] for s in sims), 3)}
             for v in variants}
    taus = {f"{a} vs {b}": round(kendall_tau_b([scores_by_sim[a][v] for v in variants],
                                               [scores_by_sim[b][v] for v in variants]), 3)
            for a, b in combinations(sims, 2)}
    return {"bands": bands, "rank_agreement": taus}


def audit_rates(labels: dict[str, str]) -> dict:
    """tau2-bench-style human audit of simulator errors per conversation:
    'critical' (prevents task completion), 'benign', or 'none'."""
    n = len(labels)
    c = Counter(labels.values())
    return {lab: {"count": c.get(lab, 0), "rate": round(c.get(lab, 0) / n, 3),
                  "ci": tuple(round(v, 3) for v in wilson_interval(c.get(lab, 0), n))}
            for lab in ("critical", "benign", "none")} | {"n": n}


def validity_card(name: str, *, realism: dict, disc: dict, leak: dict, real_leak: dict,
                  term: dict, fidelity: dict, gap: dict, pv: dict,
                  max_auc: float = 0.7, max_gap: float = 0.10, min_tau: float = 0.6) -> str:
    """One screen per simulator. The thresholds are team choices — write
    them down before you run the check (pre-registration, 10A.10). The
    decisive check is gated on the LOWER bound of tau's bootstrap interval:
    PASS only when even the pessimistic end clears min_tau."""
    flags = [f for f, r in realism.items() if r["flag"]]
    lines = [f"simulator {name}"]

    def row(ok: bool, text: str) -> None:
        lines.append(f"  [{'PASS' if ok else 'WARN'}] {text}")

    row(not flags, f"realism: {len(realism) - len(flags)}/{len(realism)} features within "
                   f"noise floor" + (f"; flagged {flags}" if flags else ""))
    row(disc["separability"] <= max_auc,
        f"discriminability AUC {disc['auc']}, separability {disc['separability']} "
        f"(limit {max_auc})")
    row(leak["leak_rate"] <= real_leak["leak_rate"] + 0.10,
        f"leakage {leak['leak_rate']} vs real {real_leak['leak_rate']}")
    row(term["js"] <= 0.05, f"termination JS {term['js']} (sim {term['sim']})")
    row(fidelity["invented_rate"] <= 0.02, f"invented facts in {fidelity['invented_rate']:.0%} "
                                           f"of conversations")
    g = gap["overall"]
    row(abs(g["gap"]) <= max_gap, f"sim-to-real gap {g['gap']:+.3f} CI {g['ci']}")
    lo = (pv.get("kendall_ci") or (float("-inf"),))[0]
    if lo >= min_tau:
        status, verdict = "PASS", "usable for ranking variants"
    elif pv["kendall_tau_b"] >= min_tau:
        status, verdict = "PROVISIONAL", (f"provisionally usable for ranking (lower CI bound "
                                          f"{lo} < {min_tau}: extend the human study)")
    else:
        status, verdict = "WARN", "NOT validated for ranking"
    lines.append(f"  [{status}] predictive validity: tau {pv['kendall_tau_b']} CI "
                 f"{pv.get('kendall_ci')}, pairwise {pv['pairwise_agreement']}, "
                 f"decisions {pv.get('decision_agreement')}")
    lines.append(f"  verdict: {verdict}; absolute scores need the gap correction"
                 if abs(g["gap"]) > max_gap else f"  verdict: {verdict}")
    return "\n".join(lines)

7.16 The demo: three simulators, five agents and a human study#

The fixture is a returns-and-refunds desk with 30 tasks (half "easy" with two hidden facts, half "hard" with four). The "real" users are a synthetic stand-in for production transcripts: a seeded mixture of patient, impatient and front-loading personas, including honest slips (a wrong postcode now and then). Three simulators have planted behaviour: sim_eager@v1 (front-loads, polite, verbose, never gives up, occasionally invents a fact), sim_grounded@v1 (a persona mixture built to match the real distribution) and sim_impatient@v1 (terse, gives up after two turns); sim_dump is the positive control. Five agent variants differ in how they get information: v1 asks one fact at a time, v2 (the production agent) asks for everything at once, v3 guesses instead of asking, v4 is weak at the final action, and v5 is careful but adds a confirmation turn. The human study runs every variant on every task twice. None of these numbers describes real users or real simulators.

python
"""sim_validation_demo.py — validate three user simulators against "real" users.

    python3 sim_validation_demo.py            # every check, one simulator per card

The "real" conversations are SYNTHETIC STAND-INS for production transcripts
(a seeded mixture of human-like personas), so the whole demo runs with no
keys and prints the same numbers every time. Each simulator has planted
behaviour; the point is to watch the checks find it. No number here is a
finding about real users or real simulators.
"""
from __future__ import annotations

import random
import statistics
from dataclasses import dataclass

from agent_eval import wilson_interval
from sim_validation import (Conversation, Turn, audit_rates, control_success,
                            default_features, difficulty_gap, discriminability,
                            fidelity_summary, goal_fidelity, leakage_rate,
                            predictive_validity, realism_report, simulator_panel,
                            termination_report, validity_card)

ITEMS = ["kettle", "blender", "lamp", "backpack", "monitor", "headphones"]
REASONS = ["arrived damaged", "wrong size", "stopped working", "not as described"]
GOALS = ["refund", "return", "replacement"]
FILLER = ("I bought this a while ago and I need some help with the order I placed "
          "last week because it is not what I expected at all").split()


def make_tasks(n: int = 30) -> dict[str, dict]:
    rng = random.Random(3)
    tasks = {}
    for i in range(1, n + 1):
        hard = i % 2 == 0
        facts = {"order_id": f"A-{1000 + i}", "item": rng.choice(ITEMS)}
        if hard:
            facts |= {"reason": rng.choice(REASONS), "postcode": f"N{rng.randint(1, 9)} {rng.randint(1, 9)}AB"}
        tasks[f"U{i:02d}"] = {"goal": rng.choice(GOALS), "facts": facts,
                              "slice": "hard" if hard else "easy",
                              "leaky": i == 7}   # U07: the agent can look the facts up itself
    return tasks


@dataclass(frozen=True)
class UserStyle:
    name: str
    reveal_first: float      # P(volunteer each fact in the opening turn)
    answer: float            # P(answer an asked-for fact)
    patience: int            # user turns before giving up
    polite: float            # P(a turn carries a politeness marker)
    words: tuple[int, int]   # filler words per turn
    question: float          # P(the user asks something back)
    invent: float = 0.0      # P(a stated fact has the wrong value): for a person an honest
                             # slip, for a simulator an error against its persona card
    drift: float = 0.0       # P(a turn wanders off the persona's goal)


HUMANS = [(UserStyle("patient", 0.25, 0.85, 6, 0.20, (3, 12), 0.15, invent=0.03), 0.5),
          (UserStyle("impatient", 0.30, 0.75, 2, 0.05, (1, 5), 0.10, invent=0.03), 0.3),
          (UserStyle("front-loader", 0.90, 0.90, 5, 0.25, (8, 20), 0.05, invent=0.03), 0.2)]

SIMULATORS = {
    "sim_eager@v1": [(UserStyle("eager", 0.85, 1.0, 99, 0.60, (10, 22), 0.02,
                                invent=0.02, drift=0.05), 1.0)],
    "sim_grounded@v1": [(UserStyle("g-patient", 0.30, 0.85, 6, 0.25, (3, 12), 0.12, invent=0.01), 0.5),
                        (UserStyle("g-impatient", 0.30, 0.80, 2, 0.10, (1, 6), 0.10, invent=0.01), 0.3),
                        (UserStyle("g-front", 0.85, 0.90, 5, 0.30, (8, 18), 0.05, invent=0.01), 0.2)],
    "sim_impatient@v1": [(UserStyle("terse", 0.20, 0.80, 2, 0.00, (1, 3), 0.05), 1.0)],
}
POSITIVE_CONTROL = [(UserStyle("dump", 1.0, 1.0, 99, 1.0, (25, 30), 0.0), 1.0)]
UNHELPFUL = UserStyle("unhelpful", 0.0, 0.0, 99, 0.0, (2, 2), 0.0)


@dataclass(frozen=True)
class AgentVariant:
    name: str
    ask: float       # P(ask for a missing fact rather than guess)
    batch: bool      # ask for every missing fact in one turn
    act: float       # P(correct action once it has every fact)
    confirm: bool    # adds a confirmation turn before acting


VARIANTS = [AgentVariant("v1", 0.95, False, 0.90, False),
            AgentVariant("v2", 0.95, True, 0.86, False),    # the production agent
            AgentVariant("v3", 0.35, True, 0.92, False),    # guesses instead of asking
            AgentVariant("v4", 0.90, True, 0.62, False),    # weak at the action itself
            AgentVariant("v5", 0.95, False, 0.95, True)]    # careful but slow


def _pick(mix, rng):
    r, acc = rng.random(), 0.0
    for style, w in mix:
        acc += w
        if r <= acc:
            return style
    return mix[-1][0]


def converse(agent: AgentVariant, style: UserStyle, task_id: str, task: dict,
             rng: random.Random, source: str, conv_id: str) -> Conversation:
    facts, goal = task["facts"], task["goal"]
    known = set(facts) if task["leaky"] else set()
    wrong: set[str] = set()
    turns: list[Turn] = []
    n_user = 0

    def user_say(keys: list[str]) -> None:
        nonlocal n_user
        n_user += 1
        stated = {}
        for k in keys:
            v = facts[k]
            if rng.random() < style.invent:
                v = v + "9" if k in ("order_id", "postcode") else "something else"
            stated[k] = v
        intent = "change address" if rng.random() < style.drift else goal
        lo, hi = style.words
        words = FILLER[: rng.randint(lo, hi)] if style.name != "unhelpful" else ["I", "don't", "know."]
        parts = (["Thanks,"] if rng.random() < style.polite else []) + words
        if style.name != "unhelpful" and n_user == 1:
            parts += [f"I'd like a {goal}."]
        parts += [f"{k.replace('_', ' ')} {v}" for k, v in stated.items()]
        if rng.random() < style.question:
            parts.append("Is that possible?")
        turns.append(Turn("user", " ".join(parts),
                          {"revealed": list(keys), "stated": stated, "intent": intent}))
        known.update(stated)
        wrong.update(k for k, v in stated.items() if v != facts[k])

    user_say([k for k in facts if rng.random() < style.reveal_first])
    confirmed, outcome, ended = False, False, "max_turns"
    for _ in range(10):
        missing = sorted(set(facts) - known)
        if not missing or rng.random() > agent.ask:
            if agent.confirm and not missing and not confirmed:
                confirmed = True
                turns.append(Turn("agent", "Just to confirm the details before I act?",
                                  {"asked_for": []}))
                if n_user >= style.patience:
                    ended = "gave_up"
                    break
                user_say([])
                continue
            outcome = not missing and not wrong and rng.random() < agent.act
            turns.append(Turn("agent", "Done: I have processed that for you.", {}))
            ended = "agent_end"
            break
        ask = missing if agent.batch else missing[:1]
        turns.append(Turn("agent", f"Could you give me your {', '.join(ask)}?",
                          {"asked_for": ask}))
        if n_user >= style.patience:
            ended = "gave_up"
            break
        user_say([k for k in ask if rng.random() < style.answer])
    if style.name == "unhelpful" and ended == "max_turns":
        ended = "loop"
    persona = {"goal": goal, "facts": facts, "temperament": style.name}
    return Conversation(conv_id, source, task_id, persona, turns, outcome, ended, task["slice"])


def run(agent, mix, tasks, reps, source, seed) -> list[Conversation]:
    out = []
    for tid, task in tasks.items():
        for r in range(reps):
            rng = random.Random(f"{source}:{agent.name}:{tid}:{r}:{seed}")
            out.append(converse(agent, _pick(mix, rng), tid, task, rng, source,
                                f"{source}:{agent.name}:{tid}:{r}"))
    return out


def per_task(convs: list[Conversation]) -> dict[str, float]:
    by: dict[str, list[bool]] = {}
    for c in convs:
        by.setdefault(c.task_id, []).append(bool(c.outcome))
    return {t: statistics.fmean(v) for t, v in by.items()}


def detector(c: Conversation) -> float:
    """A cheap 'looks simulated' score: politeness, front-loading, length."""
    f = default_features(c)
    rank = {"0": 0, "0-25%": 1, "25-50%": 2, ">50%": 3, "none": 0, "some": 1, "most": 2, "all": 3,
            "1-3": 0, "4-8": 1, "9-15": 2, "16+": 3}
    return rank[f["polite_rate"]] + rank[f["first_turn_info"]] + rank[f["words_per_turn"]]


def main() -> None:
    tasks = make_tasks()
    hidden = {"order_id", "item", "reason", "postcode"}
    prod = VARIANTS[1]
    real = run(prod, HUMANS, tasks, 2, "real", seed=1)                 # 60 "production" chats
    sims = {name: run(prod, mix, tasks, 4, f"sim:{name}", seed=2)
            for name, mix in SIMULATORS.items()}
    dump = run(prod, POSITIVE_CONTROL, tasks, 2, "sim:dump", seed=2)
    print(f"real conversations: {len(real)}; per simulator: {len(next(iter(sims.values())))}")

    print("\n-- 1. realism (JS / real-vs-real noise floor p95; FLAG = JS above both the floor and 0.02) --")
    reports = {name: realism_report(real, convs, n_boot=200) for name, convs in sims.items()}
    feats = list(next(iter(reports.values())))
    print(f"{'feature':16s} " + " ".join(f"{n:>22s}" for n in reports))
    for f in feats:
        cells = []
        for n in reports:
            r = reports[n][f]
            cells.append(f"{r['js']:.3f}/{r['noise_p95']:.3f}{' FLAG' if r['flag'] else '     '}")
        print(f"{f:16s} " + " ".join(f"{c:>22s}" for c in cells))
    r = reports["sim_eager@v1"]["polite_rate"]
    print(f"polite_rate real={r['real']}\n            eager={r['sim']}")

    print("\n-- 2. discriminability (AUC, sim = positive) --")
    disc = {n: discriminability(real, c, detector) for n, c in sims.items()}
    for n, d in disc.items():
        print(f"  {n:18s} AUC={d['auc']}  separability={d['separability']}")
    pc = discriminability(real, dump, detector)
    print(f"  positive control   AUC={pc['auc']}  separability={pc['separability']}")
    half = len(real) // 2
    rr = discriminability(real[:half], real[half:], detector)
    print(f"  real vs real       AUC={rr['auc']}  separability={rr['separability']}")

    print("\n-- 3. leakage (facts volunteered before the agent asked) --")
    real_leak = leakage_rate(real, hidden_keys=hidden)
    leaks = {n: leakage_rate(c, hidden_keys=hidden) for n, c in sims.items()}
    print(f"  real               {real_leak['leak_rate']}  CI {real_leak['ci']}")
    for n, lk in leaks.items():
        print(f"  {n:18s} {lk['leak_rate']}  CI {lk['ci']}")

    print("\n-- 4. termination --")
    terms = {n: termination_report(real, c) for n, c in sims.items()}
    print(f"  real               {terms['sim_eager@v1']['real']}")
    for n, t in terms.items():
        print(f"  {n:18s} {t['sim']}  JS={t['js']}")

    print("\n-- 5. fidelity (invented facts, off-goal turns) --")
    fids = {n: fidelity_summary(c) for n, c in sims.items()}
    for n, fs in fids.items():
        print(f"  {n:18s} {fs}")
    bad = next(c for c in sims["sim_eager@v1"] if goal_fidelity(c)["invented"])
    print(f"  example {bad.conv_id}: {goal_fidelity(bad)}")

    print("\n-- 6. controls (production agent v2) --")
    unh = {tid: converse(prod, UNHELPFUL, tid, t, random.Random(f"u:{tid}"), "ctl", tid).outcome
           for tid, t in tasks.items()}
    print(f"  unhelpful user: {control_success(unh)}")
    nouser = {f"{tid}#{r}": random.Random(f"n:{tid}:{r}").random() < prod.act
              for tid in tasks for r in range(4)}       # agent gets every fact, no user
    nu = control_success(nouser)
    print(f"  no-user (all facts given): rate={nu['rate']} CI {nu['ci']}")
    for n, c in sims.items():
        rate = statistics.fmean(bool(x.outcome) for x in c)
        print(f"  with {n:18s} rate={rate:.3f}  communication cost={nu['rate'] - rate:+.3f}")

    print("\n-- 7. human study: 5 variants x 30 tasks x 2 sessions = 300 conversations --")
    human = {v.name: per_task(run(v, HUMANS, tasks, 2, "human", seed=5)) for v in VARIANTS}
    simres = {n: {v.name: per_task(run(v, mix, tasks, 4, f"sim:{n}", seed=6)) for v in VARIANTS}
              for n, mix in SIMULATORS.items()}
    hmean = {v: statistics.fmean(s.values()) for v, s in human.items()}
    print("  variant   human  " + "  ".join(f"{n:>16s}" for n in simres))
    for v in hmean:
        k = round(hmean[v] * 60)
        lo, hi = wilson_interval(k, 60)
        print(f"  {v:7s} {hmean[v]:.3f} ({lo:.2f}-{hi:.2f}) " +
              "  ".join(f"{statistics.fmean(simres[n][v].values()):16.3f}" for n in simres))

    print("\n-- 8. difficulty calibration: sim - human, paired over tasks (production agent v2) --")
    slices = {t: d["slice"] for t, d in tasks.items()}
    gaps = {n: difficulty_gap(simres[n]["v2"], human["v2"], slices=slices) for n in simres}
    for n, g in gaps.items():
        print(f"  {n:18s} overall {g['overall']['gap']:+.3f} CI {g['overall']['ci']}   "
              f"easy {g['easy']['gap']:+.3f}   hard {g['hard']['gap']:+.3f}")

    print("\n-- 9. predictive validity (ship threshold 0.60) --")
    pvs = {}
    for n in simres:
        smean = {v: statistics.fmean(s.values()) for v, s in simres[n].items()}
        pvs[n] = predictive_validity(smean, hmean, threshold=0.60,
                                     per_task=(simres[n], human), n_boot=1000)
        p = pvs[n]
        order_s = " > ".join(sorted(smean, key=smean.get, reverse=True))
        print(f"  {n:18s} spearman={p['spearman']:+.2f} tau={p['kendall_tau_b']:+.2f} "
              f"CI {p['kendall_ci']} pairwise={p['pairwise_agreement']:.2f} "
              f"decisions={p['decision_agreement']:.2f}   sim order: {order_s}")
    order = sorted(hmean, key=hmean.get, reverse=True)
    shown = order[0]
    for prev, v in zip(order, order[1:]):
        shown += (" = " if hmean[v] == hmean[prev] else " > ") + v
    print(f"  {'human':18s} order: {shown}")
    three = {v: hmean[v] for v in ("v1", "v2", "v3")}
    s3 = {v: statistics.fmean(simres["sim_eager@v1"][v].values()) for v in three}
    print(f"  with only 3 variants: {predictive_validity(s3, three)}")

    print("\n-- 10. simulator panel (each variant's score as a band) --")
    panel = simulator_panel({n: {v: statistics.fmean(s.values()) for v, s in simres[n].items()}
                             for n in simres})
    for v, b in panel["bands"].items():
        print(f"  {v}: {b}")
    print(f"  rank agreement between simulators: {panel['rank_agreement']}")

    print("\n-- 11. human audit of 50 simulated conversations each (tau2-bench style) --")
    for n, c in sims.items():
        labels = {}
        for x in c[:50]:
            gf = goal_fidelity(x)
            labels[x.conv_id] = "critical" if gf["invented"] else \
                "benign" if gf["persona_breaks"] else "none"
        a = audit_rates(labels)
        print(f"  {n:18s} critical={a['critical']['rate']} CI {a['critical']['ci']}  "
              f"benign={a['benign']['rate']}")

    print("\n-- 12. how many human conversations? Wilson 95% half-width of a success rate --")
    for n in (30, 60, 120, 240, 480):
        lo, hi = wilson_interval(round(0.7 * n), n)
        print(f"  n={n:3d} at 70% success: +/-{(hi - lo) / 2:.3f}")

    print("\n-- validity cards --")
    for n in sims:
        print(validity_card(n, realism=reports[n], disc=disc[n], leak=leaks[n],
                            real_leak=real_leak, term=terms[n], fidelity=fids[n],
                            gap=gaps[n], pv=pvs[n]))


if __name__ == "__main__":
    main()

Run it with python3 sim_validation_demo.py.

Output114 lines
real conversations: 60; per simulator: 120

-- 1. realism (JS / real-vs-real noise floor p95; FLAG = JS above both the floor and 0.02) --
feature                    sim_eager@v1        sim_grounded@v1       sim_impatient@v1
words_per_turn         0.297/0.051 FLAG       0.028/0.051            0.202/0.051 FLAG
short_turn_rate        0.000/0.000            0.007/0.000            0.038/0.000 FLAG
polite_rate            0.133/0.068 FLAG       0.027/0.068            0.123/0.068 FLAG
question_rate          0.076/0.063 FLAG       0.022/0.063            0.051/0.063     
first_turn_info        0.246/0.067 FLAG       0.044/0.067            0.073/0.067 FLAG
user_turns             0.042/0.037 FLAG       0.007/0.037            0.042/0.037 FLAG
ended_by               0.025/0.049            0.009/0.049            0.071/0.049 FLAG
polite_rate real={'0': 0.68, '0-25%': 0.02, '25-50%': 0.18, '>50%': 0.12}
            eager={'0': 0.29, '25-50%': 0.2, '>50%': 0.51}

-- 2. discriminability (AUC, sim = positive) --
  sim_eager@v1       AUC=0.897  separability=0.897
  sim_grounded@v1    AUC=0.566  separability=0.566
  sim_impatient@v1   AUC=0.232  separability=0.768
  positive control   AUC=0.975  separability=0.975
  real vs real       AUC=0.499  separability=0.501

-- 3. leakage (facts volunteered before the agent asked) --
  real               0.339  CI (0.274, 0.411)
  sim_eager@v1       0.836  CI (0.794, 0.871)
  sim_grounded@v1    0.4  CI (0.351, 0.451)
  sim_impatient@v1   0.228  CI (0.187, 0.274)

-- 4. termination --
  real               {'agent_end': 0.933, 'gave_up': 0.067}
  sim_eager@v1       {'agent_end': 1.0}  JS=0.024
  sim_grounded@v1    {'agent_end': 0.9, 'gave_up': 0.1}  JS=0.002
  sim_impatient@v1   {'agent_end': 0.658, 'gave_up': 0.342}  JS=0.062

-- 5. fidelity (invented facts, off-goal turns) --
  sim_eager@v1       {'n': 120, 'invented_rate': 0.042, 'invented_ci': (0.018, 0.094), 'off_goal_rate': 0.083}
  sim_grounded@v1    {'n': 120, 'invented_rate': 0.0, 'invented_ci': (0.0, 0.031), 'off_goal_rate': 0.0}
  sim_impatient@v1   {'n': 120, 'invented_rate': 0.0, 'invented_ci': (0.0, 0.031), 'off_goal_rate': 0.0}
  example sim:sim_eager@v1:v2:U02:2: {'pursued': True, 'invented': [('item', 'something else')], 'persona_breaks': 0}

-- 6. controls (production agent v2) --
  unhelpful user: {'rate': 0.033, 'ci': (0.006, 0.167), 'succeeded': ['U07']}
  no-user (all facts given): rate=0.867 CI (0.794, 0.916)
  with sim_eager@v1       rate=0.825  communication cost=+0.042
  with sim_grounded@v1    rate=0.750  communication cost=+0.117
  with sim_impatient@v1   rate=0.500  communication cost=+0.367

-- 7. human study: 5 variants x 30 tasks x 2 sessions = 300 conversations --
  variant   human      sim_eager@v1   sim_grounded@v1  sim_impatient@v1
  v1      0.467 (0.35-0.59)            0.842             0.583             0.175
  v2      0.700 (0.57-0.80)            0.817             0.808             0.525
  v3      0.367 (0.26-0.49)            0.625             0.358             0.208
  v4      0.467 (0.35-0.59)            0.508             0.433             0.358
  v5      0.483 (0.36-0.61)            0.925             0.592             0.042

-- 8. difficulty calibration: sim - human, paired over tasks (production agent v2) --
  sim_eager@v1       overall +0.117 CI (-0.033, 0.275)   easy +0.167   hard +0.067
  sim_grounded@v1    overall +0.108 CI (-0.025, 0.25)   easy +0.100   hard +0.117
  sim_impatient@v1   overall -0.175 CI (-0.3, -0.058)   easy -0.050   hard -0.300

-- 9. predictive validity (ship threshold 0.60) --
  sim_eager@v1       spearman=+0.46 tau=+0.32 CI (-0.316, 0.6) pairwise=0.67 decisions=0.40   sim order: v5 > v1 > v2 > v3 > v4
  sim_grounded@v1    spearman=+0.97 tau=+0.95 CI (0.105, 1.0) pairwise=1.00 decisions=1.00   sim order: v2 > v5 > v1 > v4 > v3
  sim_impatient@v1   spearman=+0.20 tau=+0.10 CI (-0.2, 0.8) pairwise=0.56 decisions=0.80   sim order: v2 > v4 > v3 > v1 > v5
  human              order: v2 > v5 > v1 = v4 > v3
  with only 3 variants: {'k_variants': 3, 'spearman': 0.5, 'kendall_tau_b': 0.333, 'pairwise_agreement': 0.667, 'mean_gap': 0.25, 'warning': 'K=3 variants: rank statistics are coarse; use K >= 5'}

-- 10. simulator panel (each variant's score as a band) --
  v1: {'min': 0.175, 'max': 0.842, 'spread': 0.667}
  v2: {'min': 0.525, 'max': 0.817, 'spread': 0.292}
  v3: {'min': 0.208, 'max': 0.625, 'spread': 0.417}
  v4: {'min': 0.358, 'max': 0.508, 'spread': 0.15}
  v5: {'min': 0.042, 'max': 0.925, 'spread': 0.883}
  rank agreement between simulators: {'sim_eager@v1 vs sim_grounded@v1': 0.4, 'sim_eager@v1 vs sim_impatient@v1': -0.6, 'sim_grounded@v1 vs sim_impatient@v1': 0.0}

-- 11. human audit of 50 simulated conversations each (tau2-bench style) --
  sim_eager@v1       critical=0.04 CI (0.011, 0.135)  benign=0.04
  sim_grounded@v1    critical=0.0 CI (0.0, 0.071)  benign=0.0
  sim_impatient@v1   critical=0.0 CI (0.0, 0.071)  benign=0.0

-- 12. how many human conversations? Wilson 95% half-width of a success rate --
  n= 30 at 70% success: +/-0.156
  n= 60 at 70% success: +/-0.113
  n=120 at 70% success: +/-0.081
  n=240 at 70% success: +/-0.058
  n=480 at 70% success: +/-0.041

-- validity cards --
simulator sim_eager@v1
  [WARN] realism: 2/7 features within noise floor; flagged ['words_per_turn', 'polite_rate', 'question_rate', 'first_turn_info', 'user_turns']
  [WARN] discriminability AUC 0.897, separability 0.897 (limit 0.7)
  [WARN] leakage 0.836 vs real 0.339
  [PASS] termination JS 0.024 (sim {'agent_end': 1.0})
  [WARN] invented facts in 4% of conversations
  [WARN] sim-to-real gap +0.117 CI (-0.033, 0.275)
  [WARN] predictive validity: tau 0.316 CI (-0.316, 0.6), pairwise 0.667, decisions 0.4
  verdict: NOT validated for ranking; absolute scores need the gap correction
simulator sim_grounded@v1
  [PASS] realism: 7/7 features within noise floor
  [PASS] discriminability AUC 0.566, separability 0.566 (limit 0.7)
  [PASS] leakage 0.4 vs real 0.339
  [PASS] termination JS 0.002 (sim {'agent_end': 0.9, 'gave_up': 0.1})
  [PASS] invented facts in 0% of conversations
  [WARN] sim-to-real gap +0.108 CI (-0.025, 0.25)
  [PROVISIONAL] predictive validity: tau 0.949 CI (0.105, 1.0), pairwise 1.0, decisions 1.0
  verdict: provisionally usable for ranking (lower CI bound 0.105 < 0.6: extend the human study); absolute scores need the gap correction
simulator sim_impatient@v1
  [WARN] realism: 1/7 features within noise floor; flagged ['words_per_turn', 'short_turn_rate', 'polite_rate', 'first_turn_info', 'user_turns', 'ended_by']
  [WARN] discriminability AUC 0.232, separability 0.768 (limit 0.7)
  [PASS] leakage 0.228 vs real 0.339
  [WARN] termination JS 0.062 (sim {'agent_end': 0.658, 'gave_up': 0.342})
  [PASS] invented facts in 0% of conversations
  [WARN] sim-to-real gap -0.175 CI (-0.3, -0.058)
  [WARN] predictive validity: tau 0.105 CI (-0.2, 0.8), pairwise 0.556, decisions 0.8
  verdict: NOT validated for ranking; absolute scores need the gap correction

The validity cards summarise the story. The eager simulator fails almost everything and, most importantly, would have shipped the wrong agents. The grounded simulator passes realism (all seven features), discriminability (separability 0.57), leakage, termination and fidelity, and its point estimate for ranking is strong (tau 0.95, every decision agreeing). But the card marks predictive validity PROVISIONAL, because the lower end of tau's interval is 0.105: thirty tasks with two sessions each cannot yet rule out a weak ranking. It also warns on the gap: about 0.11 easier than real users for the production agent, with an interval that includes zero (−0.025 to 0.25), so its absolute numbers need the gap stated. That is the realistic state of a good simulator after a first human study: promising for comparing agents, not yet established, and not to be used for scoring one.


Part 8: Benchmarks, datasets and tools (awareness)#

Reference

Everything in this part was checked on the official pages in November 2026. Names and features change quickly; scores are deliberately not quoted, because a benchmark score without its date, harness and model version is not information.

8.1 Multi-agent failure benchmarks and datasets#

Resource What it contains What it is good for Where
MAST-Data (Cemri et al.) Over a thousand annotated multi-agent traces from seven frameworks with the 14 MAST modes; an LLM-annotated full set and a human-labelled set; the LLM annotator pipeline Learning the codebook; validating your own failure-mode annotator against human labels Hugging Face mcemri/MAD (files MAD_full_dataset.json, MAD_human_labelled_dataset.json); repository
Who&When (Zhang et al., ICML 2025) 184 failure logs (126 algorithm-generated, 58 from Magentic-One) with the responsible agent, decisive step and reason Benchmarking an attributor, with the trivial baselines of 4.7 alongside Hugging Face Kevin355/Who_and_When; code with `inference.py --method all_at_once
TRAIL (Patronus AI) 148 human-annotated traces (GAIA, SWE-Bench; single- and multi-agent) with a reasoning / planning / execution error taxonomy Error localisation in long traces Hugging Face PatronusAI/TRAIL (gated; evaluation-only)
MultiAgentBench / MARBLE (Zhu et al., arXiv 2503.01935) Collaboration and competition scenarios scored on task completion and milestone-based KPIs; compares star, chain, tree and graph coordination topologies and strategies such as group discussion and cognitive planning Measuring coordination quality, not only outcomes The paper and its MARBLE code
TraceElephant (arXiv 2604.22708, ACL 2026) Full execution traces with reproducible environments Attribution methods that need replay The paper
τ²-bench (arXiv 2506.07982) Dual-control customer-service tasks with a tool-using simulated user and a No-User mode A ready-made environment for single- versus multi-agent comparisons with a user in the loop (Yang and Shi used it) sierra-research/tau2-bench; its current releases are covered in 10A.7, 7.1

Two cautions apply to all of them. Their failure distributions describe the frameworks and models of the year they were collected, and their labels carry the artefacts Naagarajan and Streif warned about. Use them to learn methods and to sanity-check an attributor; build your own labelled set from your own traces before you trust any number about your system.

8.2 Tracing support for handoffs#

The framework table is in 3.11: OpenAI Agents SDK handoff_span (from_agent, to_agent), LangGraph Command transitions, Inspect AI transcripts, A2A task states and OpenTelemetry's invoke_agent / invoke_workflow spans. None of them records the post-filter payload or tags coordination versus work for you; those two attributes are the instrumentation this lesson asks you to add.

8.3 Simulation tooling#

Several evaluation tools now generate simulated conversations. As of November 2026 none of them validates its simulator against real users; they produce conversations, and validating them is the job of Part 7.

Tool What it provides (from its documentation) How it maps onto sim_validation.py
LangSmith / openevals (multi-turn simulation) from openevals.simulators import run_multiturn_simulation, create_llm_simulated_user; run_multiturn_simulation(app=..., user=..., max_turns=..., trajectory_evaluators=[...]) with an optional stopping_condition (Python only); the simulated user takes a system prompt, a model string and optional fixed_responses; the app receives one message and a thread_id and keeps its own history Convert each returned trajectory to a Conversation; fixed_responses is a convenient way to build the unhelpful-user control
DeepEval (conversation simulator) from deepeval.simulator import ConversationSimulator with ConversationalGolden and Persona from deepeval.dataset; simulate(conversational_goldens=..., max_user_simulations=10); a stopping_controller; by default a simulation stops when the golden's expected_outcome is achieved (opened up in 10B.6, Part 7 and validated in Part 8 there) Goldens map to persona cards; check the stop rule with termination_report, since "stop when the outcome is achieved" can hide abandonment
τ-bench 2.0 tau2 judges (tau2-bench; see 10A.7, 7.1) Post-hoc LLM judges run after a benchmark run; the README says they score "naturalness, speech fidelity, tool use and language-specific checks" and "do not change the task reward", and introduces them as judges "for how the agent speaks" A per-conversation quality check, not a validation of the simulator against real users. Where you point judges at the simulated user's side, they map to goal_fidelity and audit_rates, and the judges themselves need 10A.5 validation
MLflow (conversation simulation) from mlflow.genai.simulators import ConversationSimulator, generate_test_cases; test cases with goal (required), persona, simulation_guidelines, context, expectations; max_turns defaults to 10; marked experimental in MLflow 3.10.0; generate_test_cases builds cases from existing sessions Building cases from real sessions gives you matched real and simulated sets for realism_report and difficulty_gap

Install any of them by package name only (uv add openevals, uv add deepeval, uv add mlflow) and check the current documentation for the exact signatures before you build on them; this lesson's code does not depend on any of them.


Part 9: Putting it together#

9.1 Decision table: which check answers which question#

Question Metric evalkit function Cost When to run
Does the router pick the right specialist, and know when not to hand off? Accuracy, per-class recall, kappa, false and missed handoff rates routing_confusion Free once traces exist CI, every change to a specialist's description or the router prompt
Does it hand off at the right moment? Premature, late, missing handoff_timing Free CI
Does the receiver get what it needs? Field recall, value fidelity, hallucinated-field rate (on payload_seen) context_transfer_suite Free (fields); a validated judge for free text CI; every change to an input filter or summary prompt
Do delegation briefs carry the constraints? Element presence, constraint recall brief_fidelity (+ a validated judge) Free (+ judge calls) CI on fixtures; sampled in production
Does control bounce or loop? Ping-pong count, cycles, repeated delegations, chain length over budget pingpong, cycles, repeated_delegations Free CI and production monitoring
Do results come back and get used? Orphaned, non-terminal, dropped return_path Free CI and production monitoring
Does it escalate the right cases, with context? Recall (with interval), precision, context recall escalation_prf Free CI on a dedicated escalation slice of 30+ cases
Which agent caused this failure? Decisive point by replay flip rate; whether that fix is also necessary counterfactual_attribution, fix_necessity_check Candidates × replays On failed runs, nightly or during triage
Two faults at once? Shapley credit shapley_credit 2ⁿ × replays On runs with no single decisive point
Which agent should we improve, or remove? Ablation credit (oracle / pass-through) ablation_credit Agents × tasks × replays Before a redesign
No replay possible? Judge attribution, validated judge_attribution, attribution_accuracy with baselines 1 to n judge calls per run Triage of production traces
Where do failures come from overall? Shares per agent and per mode, with intervals attribution_report Free after attribution Weekly review
What does the orchestration cost? Token multiplier, coordination ratio, critical path, effective parallelism, latency speed-up vs one agent, redundancy, cost per success (p50/p95) overhead, overhead_summary Free from traces Nightly and on every architecture change
Is the team worth it? Equal-budget paired comparison, slices, pass^k, Pareto equal_budget_check, compare_systems, pareto_front A full suite per variant Before adopting or extending a multi-agent design
Can we trust the simulator to rank variants? Realism, discriminability, fidelity, leakage, controls, termination, gap, predictive validity sim_validation.py, validity_card A human study (the expensive part) plus simulated runs Before first use; again on any simulator change

9.2 The multi-agent eval ladder, extended#

08D.3, 3.9 proposed a four-rung ladder. With this lesson's tools each rung has concrete checks:

flowchart TB
    R1["1. CI on every change:<br/>scripted agents and fixtures;<br/>handoff graders, return path,<br/>grader self-tests with planted faults"]
    R2["2. Replay of recorded runs:<br/>CallCache record and replay;<br/>counterfactual attribution on failures;<br/>attributor checked against baselines"]
    R3["3. Nightly live suite:<br/>pass^k, overhead p50 and p95,<br/>equal-budget single-agent comparison,<br/>sliced by task structure"]
    R4["4. Before launch or a simulator change:<br/>simulator validity card;<br/>small human study for predictive validity"]
    R5["5. Production:<br/>sampled traces graded with the same functions;<br/>attribution on failures;<br/>simulator probes as diagnostics only"]
    R1 --> R2 --> R3 --> R4 --> R5
    R5 -.->|"failed traces become fixtures"| R1

Rung 1 is cheap and catches regressions in the coordination logic; rung 2 explains failures without paying for new model calls upstream; rung 3 measures reliability, cost and the value of the architecture; rung 4 is where you earn the right to trust simulated-user numbers; rung 5 closes the loop (10A.9, and Module 11A for the tracing and monitoring platforms). 10A.8's tiered suites decide which rung runs on which trigger.

9.3 Assembling the files#

The lesson printed four files in sections. To build them, paste the sections in order into one file each:

File Sections, in order Where printed
evalkit/mas_eval.py 1 (trace, adapters, gold), 2 (handoffs), 3 (attribution), 4 (overhead), 5 (baselines) 2.4, 3.9, 4.9, 5.7, 6.8
evalkit/mas_eval_demo.py 1 (adapters demo), 2 (support desk), 3 (research pipeline), 4 (overhead), 5 (baseline and __main__) 2.5, 3.10, 4.10, 5.8, 6.8
evalkit/sim_validation.py 1 (data, realism, discriminability), 2 (fidelity, leakage, controls, termination), 3 (calibration, predictive validity, panel, card) 7.10, 7.15
evalkit/sim_validation_demo.py One block 7.16

Each section after the first starts with a comment naming its file and position. The files import agent_eval, compare and judge_validation flat, like the other demo-style files in the package (10A.10, Appendix A), and use nothing outside the standard library. Every Output: block in this lesson came from running exactly these files with Python 3.14 on the fixtures shown (any Python 3.11+ gives the same numbers); they are seeded, so you will get the same numbers.


Realistic failures, what you see, the signal that catches them and where to look. Rows 1–15 are multi-agent failures; rows 16–23 are simulator failures.

# Failure What you see Detection signal Where
1 Triage sends a damaged-item refund to billing instead of returns Billing improvises a returns policy Off-diagonal mass in the routing matrix; returns recall below 1 3.2
2 An input filter strips tool items, and the order number with them The specialist asks the user again, or guesses Field recall below 1 on order_id; extra clarification turns right after handoffs 3.4
3 A handoff summary rewrites 84.50 as 48.50 The wrong refund is issued Value fidelity below 1; wrong=["amount"] 3.4
4 Billing and returns bounce an ambiguous request; or triage, billing and returns pass it round in a circle; or the orchestrator re-sends one brief Four or more handoffs; a frustrated user; spend with no progress Ping-pong count ≥ 1; a cycle from cycles; repeated_delegations; chain over the handoff budget 3.6
5 Handoff before identity or device details are collected The specialist lacks required fields Handoff turn before the window 3.3
6 A legal threat stays with the bot Policy breach Escalation recall below 1 on the escalation slice 3.8
7 A worker's result never reaches the synthesis The answer misses a sub-question An ok return whose ids are absent from the final answer 3.7
8 A delegated task is left WORKING or INPUT_REQUIRED Orphaned work; a cost leak Non-terminal state, or no return span, at run end 3.7
9 The planner omits a subtask, every time Every worker looks fine; the answer is incomplete Replay: fixing the plan flips the outcome; fixing workers does not; plan-coverage contract fails 4.4
10 A worker's wrong figure passes the verifier and the synthesiser repeats it A judge blames the synthesiser (the last step) Replay flips on the worker's output; the last-step baseline disagrees 4.4, 4.7
11 The verifier checks format, not truth (MAST FM-3.3) High verifier pass rate, wrong answers Pass-through ablation changes nothing; planted faults go uncaught 4.5
12 "The multi-agent system wins by 30%" at 6× the tokens A victory slide Equal-budget check fails; same-budget self-consistency matches it 6.2, 6.3
13 Gains on research tasks, losses on sequential ones, flat on average "No effect" Slice table shows opposite signs 6.5
14 Two workers run the same searches Cost up, no quality gain Cross-agent redundancy > 0 while per-agent redundant_calls is 0 5.5
15 Median latency fine, p95 terrible Users time out on some requests p95 ≫ p50 critical path; one worker on the chain in slow runs 5.4
16 The simulator front-loads every fact in its first turn The agent never needs to ask; scores inflate Leakage far above the real rate; first-turn information flagged 7.8, 7.5
17 The simulator is too polite and cooperative ("easy mode") Simulated success well above human success Positive sim-to-real gap; politeness above the noise floor 7.11
18 The simulator never gives up Slow or rambling agents still pass No "gave up" in its end reasons; longer conversations than real 7.9
19 The simulator ranks agent B above A; real users prefer A The wrong variant ships Low Kendall's tau; pairwise and decision disagreement 7.12
20 The provider silently updates the simulator's model Agent scores jump overnight with no agent change The frozen validation set drifts; the simulator version changed 7.14
21 The simulator invents an order number not on its persona card The agent "fails" on an order that never existed Invented facts > 0; critical errors in the audit 7.7
22 An unhelpful user still lets the agent succeed on "user-dependent" tasks The task or grader leaks the answer Unhelpful-user control well above 0; the succeeding tasks listed 7.8
23 Simulated users are miscalibrated for one user population A fairness blind spot The sim-to-real gap differs by population slice 7.11

What this means for you#

Treat a multi-agent system as an organisation and grade it like one: each member on its own job, each handoff as a contract, and the team against the cheapest alternative that could do the same work. Instrument first, because none of it is measurable without per-agent spans, post-filter payloads, role tags and replayable calls. When something fails, intervene before you interpret: replaying a run with one output fixed tells you more than any reading of the log, and any attributor you do use must beat "always the last step" on labels you trust. Never report a multi-agent win without an equal-budget single-agent baseline, a slice table and the cost per success. And before you let a user simulator choose between agent versions, show that it ranks versions the way real users do; until then, its numbers are a diagnostic, not a decision.


Common misconceptions#

Misconception Reality
"If every agent passes its unit evals, the system works." Most multi-agent failures are interaction failures: MAST's inter-agent misalignment and verification categories plus termination problems. Grade the edges, not just the nodes.
"Handoff correctness means picking the right agent." Routing is one of seven properties. Timing, context transfer (on what the receiver saw), brief fidelity, loops, return path and escalation fail independently.
"The agent whose output is wrong is the one to blame." That is the symptom. The decisive error is the earliest point whose correction flips the outcome; a synthesiser repeating a worker's wrong number is a missed catch, not the origin.
"An LLM judge can read the trace and tell us which agent failed." In Who&When the best method found the agent 53.5% and the step 14.2% of the time; reasoning models did not reliably help; long logs defeat every method. Intervene with replay where you can and validate any judge on human labels.
"High attribution accuracy on a benchmark means the attributor works." Always picking the last step scores 67–96% on some labelled sets and near chance on replay-confirmed ones (Naagarajan and Streif). Compare every attributor with trivial baselines on your own labels.
"Overhead is just the token bill." It is also critical-path latency, coordination share, redundancy across agents, recovery spend and failures that end in budget exhaustion, reported at p50 and p95.
"Parallel agents make the system cheaper." Parallelism reduces wall-clock at best; total compute stays the same or grows with coordination. Report both, the effective parallelism between them, and the latency speed-up against a single agent, including its worst case (a straggler can make the team slower than one agent).
"Multi-agent beats single-agent; Anthropic showed +90%." That comparison was not token-matched, and token usage explained 80% of variance in Anthropic's own analysis. Controlled studies find gains on decomposable tasks, losses on sequential ones, a shrinking advantage with stronger models, and debate gains largely explained by voting.
"A single run of one agent is the baseline." The fair baseline gets the same model, tools and budget, and the strongest same-cost alternative (self-consistency, voting) is the one to beat.
"A realistic-sounding simulator is a valid simulator." Validity is measured: behaviour distributions against real data, discriminability, and above all predictive validity. Impressions are biased: in Zhou et al., an LLM rating the interactions overestimated the assistant's human-likeness by 55% relative to people's ratings.
"A stronger model makes a better user simulator." Zhou et al. found general capability did not reliably predict simulator quality; the best simulator scored 76.0 against a human ceiling of 92.7 (version 2 of the paper).
"Simulated users are harder than real ones, so their scores are conservative." Usually the reverse ("easy mode": 77.8% against 63.6% in Zhou et al.), and the error depends on task difficulty and on the user population.
"The simulator doesn't matter if every agent faces the same one." The user model alone moved success by up to 9 points (Seshadri et al.), rankings can change, and Yang and Shi's architecture conclusion changed under a second simulator. Use a panel and check predictive validity.
"Zero simulator errors is the bar." τ²-bench measured simulator errors in 16–47% of audited conversations, 6–13% critical, in a carefully built benchmark. Measure the rate, exclude critical ones, report it.
"We validated the simulator once." Simulators drift with model updates and prompt edits. Version them and re-validate on every change, like judges and agents.

Key takeaways#

  • A multi-agent system adds two evaluation levels: interaction (every handoff, delegation and return) and organisation (overhead, attribution, the comparison with one agent). MAST's 14 modes are a codebook for labelling failures, and most of them are organisational.
  • The trace is the precondition. Per-agent spans, handoff payloads as sent and as seen, briefs, return states, work/coordination tags, inputs as well as outputs, and replayable calls. trace_from_events and trace_from_spans keep agent identity; to_trajectories runs 10A.7's graders per agent.
  • Handoff correctness is a confusion matrix that includes NONE and HUMAN, plus timing windows, context transfer graded on payload_seen, brief constraint recall, ping-pong with a supervisor exception plus longer cycles and repeated delegations, return paths against A2A terminal states, and escalation recall with an interval.
  • Attribution: separate symptom, root cause and decisive error. Rules first, counterfactual replay where you can re-run (with "sufficient" and "necessary" stated for the fix or the fault, since the words swap), Shapley credit when faults interact, ablation for suite-level investment, judges only when you cannot replay, and every attributor validated against human labels and the last-step baseline.
  • Overhead is a distribution of token multipliers, coordination ratios, critical paths, effective parallelism, latency speed-ups against one agent, cross-agent redundancy and recovery spend, normalised by success. One straggler sets the latency of a fan-out.
  • The single-agent baseline has the same model, tools and budget; self-consistency and voting are the baselines to beat; slices by task structure, pass^k, cost per success and the Pareto view travel with every claim.
  • A user simulator is an instrument. Check realism against a noise floor, discriminability with a positive control, fidelity, leakage with unhelpful-user and no-user controls, termination, the sim-to-real gap per slice, and decisively predictive validity across at least five agent variants, judged on the lower end of its interval, not the point estimate. Version it, use a panel, audit its errors.

Terms introduced in this lesson#

Term Meaning
Interaction level Evaluation of the edges between agents (handoffs, delegations, returns), as opposed to the system's outcome or one agent's work
AgentSpan / MASTrace A unit of work or communication owned by one agent / one run of a multi-agent system as a tree of such spans
Coordination tokens Tokens spent deciding, briefing, routing, verifying or re-reading other agents' results, tagged role="coordination" at instrumentation time
Routing confusion matrix Gold target against chosen target over decision points, including NONE (should not hand off) and HUMAN (should escalate)
False-handoff rate / missed-handoff rate Handoffs made where none was needed / handoffs not made where one was
Handoff timing Whether a handoff happened inside its annotated turn window: premature, late, missing or on time
Context-transfer completeness Whether the receiving agent got every required field with the right value, measured by field recall, value fidelity and hallucinated-field rate on the post-filter payload
payload_seen The handoff payload as the receiver actually saw it, after any input filter or summary
Constraint recall (briefs) Share of the user's constraints that survive into a delegation brief
Ping-pong Control bouncing between two agents (A → B → A), excluding returns to a declared supervisor
Cycle (route) / repeated delegation An agent coming back after one or more other agents (A → B → C → A) / the same brief sent to the same agent again and again
Return path Whether every delegation came back, ended in a terminal state and had its result used
Decisive error The earliest agent-and-step whose correction would turn a failed run into a successful one
Counterfactual replay Fixing one point's output with an oracle, replaying upstream from a recording and re-running downstream to see whether the outcome changes
Replay flip rate Success rate with a point fixed minus the baseline success rate, over several replays
Fix sufficiency / fix necessity (attribution) Fixing a point is sufficient for success when fixing it alone flips a failed run, and necessary when the run still fails with every other point fixed. In causal terms the first makes the fault a but-for (necessary) cause of the failure, and the second makes the fault sufficient on its own
Ablation credit The change in suite success when one agent is replaced by its oracle or by a pass-through stub
Shapley credit An agent's average marginal contribution to success over all orders of fixing, splitting credit fairly between interacting faults
Who&When A benchmark of 184 multi-agent failure logs labelled with the responsible agent and decisive step
Token multiplier A multi-agent run's tokens divided by a single agent's on the same task
Turn overhead (O%) Extra model calls of a multi-agent system relative to a single agent, as a percentage
Critical path The chain of work that sets a run's wall-clock; in a fan-out it runs through the slowest branch
Effective parallelism Total compute time divided by critical-path latency: the run's average concurrency, not a speed-up over anything
Latency speed-up (vs baseline) The single agent's critical path divided by the multi-agent critical path on the same task; below 1 means slower
Cross-agent redundancy Tool calls repeating an earlier identical call made by a different agent, as a share of all tool calls
Equal-budget baseline A single-agent configuration with the same model, tools, token budget and iterations as the multi-agent system
Ablation ladder A sequence of paired comparisons that removes or replaces one design element at a time
Sim-to-real gap Agent success under a simulator minus success with real users on the same tasks
Noise floor (realism) The divergence two halves of the real data show from each other, used as the threshold for flagging a simulator
Discriminability / separability How well a detector separates simulated from real conversations (AUC) / max(AUC, 1 − AUC)
Leakage rate (simulator) Share of hidden facts a simulated user volunteers before the agent asks
Unhelpful-user control A scripted user who answers "I don't know"; agent success against it should be near zero
No-user control Running the agent with every fact and no user, to measure the communication cost a simulator imposes
Predictive validity Whether a simulator ranks agent variants, and makes ship decisions, the way real users do
Simulator panel Several simulators scoring the same agents, reported as a band per agent
Validity card A one-screen PASS/PROVISIONAL/WARN summary of a simulator's validation checks against pre-registered thresholds

Exercises#

All exercises run without keys, using the files from this lesson.

  1. A new planted fault. In support_fixture, add a task whose handoff payload drops customer_tier (add it to required). Which grader catches it, what is the new field recall, and does handoff_grade name the field?
  2. The supervisor exception. Build a three-turn trace for a supervisor pattern (supervisor → billing → supervisor → returns → supervisor). Run pingpong with and without supervisor="supervisor" and explain the false positive.
  3. Binary-search replay. Write bisect_attribution(task_id, system, oracle, candidates) that fixes all points from position k onwards to learn which half contains the decisive point, and recurses. Compare its replay count with counterfactual_attribution on Fixture B's failed runs.
  4. Shapley versus ablation. Compute exact Shapley credit for R07 over its six points, then the single-point flips. Explain in two sentences why single-point replay found no decisive point and Shapley still assigns credit.
  5. A stricter flip rule. Re-run the attribution demo with tau=0.8 and n_replays=10. Which attributions change, and why does R09 behave differently from R02? Then run fix_necessity_check on R16's decisive point and state the result twice, once about the fix and once about the fault.
  6. Your own attributor. Write an attributor that names the first agent whose output differs from the oracle's, run it through attribution_accuracy with the three baselines, and report it at tolerance 0 and 1.
  7. Refusing the claim. In the baseline demo, give SAS+SC@4 a third of its tokens and re-run equal_budget_check against the MAS. Then write the one-sentence claim the numbers support.
  8. A Pareto question. Add a fifth variant to VARIANTS ("MAS sequential", same quality as MAS, higher latency, same cost). Is it on the frontier? Which ablation rung from 6.4 does it represent?
  9. A population slice. In sim_validation_demo.py, add a terse "dialect B" human persona used on a third of the tasks, mark those tasks with a slice, and compute difficulty_gap per slice for each simulator. Which simulator is miscalibrated for the new slice?
  10. The positive control. Remove the politeness term from detector and re-run. Does the positive control still score near 1? What does that tell you about relying on one feature?
  11. Three variants. Run predictive_validity on every subset of three variants under sim_grounded@v1. How many distinct tau values appear, and why does the lesson ask for K ≥ 5?
  12. Simulator drift. Add sim_grounded@v2 with polite=0.55 and reveal_first=0.6 for the patient persona, and produce its validity card. Which checks catch the drift, and which do not?

Check yourself#

  1. What does the interaction level of evaluation grade that the system and agent levels cannot?
  2. Name the three MAST categories and give one mode from each. Why should you treat the prevalences as a prior rather than an expectation?
  3. Why must context transfer be graded on payload_seen rather than payload_sent?
  4. Why does a routing confusion matrix need NONE and HUMAN columns, and why is worker → supervisor → worker not counted as ping-pong?
  5. What are the three ways a delegation can fail on its return path?
  6. Distinguish symptom, root cause and decisive error, with one example.
  7. Summarise Who&When's headline accuracies and two patterns from its results.
  8. Why is "always the last step" an essential baseline for any attributor?
  9. Describe counterfactual replay in five steps. Why must the downstream calls be fresh while the upstream calls are replayed?
  10. What does it mean when no single point's fix flips a failed run, and what do you compute next?
  11. Why can parallel agents lower p50 latency and still have a worse p95?
  12. List the conditions of an equal-budget single-agent baseline, and name a stronger baseline than a single run.
  13. What does predictive validity measure for a user simulator, and why is it the decisive check?
  14. Why is an AUC of 0.23 in a discriminability test not good news?
  15. What do the unhelpful-user and no-user controls each tell you?

Further resources#

Tooling follow-ups

Multi-agent failures and attribution

Single versus multi-agent, and overhead

Handoffs, protocols and tracing

User simulators

In this path: 08D.3 (building multi-agent systems), 10A.2, Part 13 (building simulators), 10A.5 (instrument validation), 10A.7 (the agent harness), 10A.8 (paired statistics and replay), 10A.9 (online signals), 10A.11 (memory and multi-session evaluation, which drives sessions with the simulators validated here).


← 10A.11: Evaluating Agent Memory and Context Management | Module 10A overview | Module 10B: Eval Frameworks →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close