跪拜 Guibai
← Back to the summary

Agent Harness I7: Event Streams, Span Trees, and pass^k for Reproducible Evaluations

Agent Harness Engineering (I7): Observability and Evaluation — Turning Runs into Reproducible Readings

1. The failure scene

Once a harness has run a single time, it's easy to treat it as "working": the log has turns, tool calls, and a final answer that looks reasonable. Counting that one pass as the accuracy rate is the same as using a single sample to represent the whole distribution.

Concretely: a tool that reads a metric occasionally returns 42 on a 503, and at other times fails outright. A single run will most likely see completed and record one pass. Running the same fixed script four times gives a true result of 2/4:

suite: harness-smoke (repeats=4)
  retry-budget: rate=1.00 (4/4) pass^k=True
  no-progress: rate=1.00 (4/4) pass^k=True
  flaky-tool: rate=0.50 (2/4) pass^k=False
  pass^k=0.667 CI95=[0.208, 0.939]

One pass and 0.667 are not the same conclusion. Worse, if you only look at the last round, it might happen to land in the passing half.

What I7 needs to add is not "print the logs" but three things:

2. Design

2.1 Events are the single source of truth

I1–I6 have already embedded events in the first six layers: run, turn, model, tool, retry, context, stop. I7 doesn't invent a second set of instrumentation; it does three steps: restore events into spans, aggregate spans into metrics, and export events unchanged as a transcript.

This constraint must be written in stone: every number that appears in metrics must be traceable to a source in the event stream. Otherwise it's "metric defined but not wired" — the dashboard is pretty, but no path produces it.

2.2 Span tree: the structure of a run

Spans are generated according to runtime nesting:

span parent purpose
invoke_agent harness none whole run, with stop_reason, usage
harness.turn run one model call and its tools
gen_ai.chat turn one model call
harness.context turn one context preparation/compaction
execute_tool <name> turn one tool call

Names align with OpenTelemetry GenAI conventions, but readers aren't required to set up a collector first; once names and attributes are stable, connecting OTLP later is just a matter of swapping the exporter.

2.3 Metrics: only what can be derived from events

Metrics are grouped into four categories:

No "subjective model quality" is introduced — that's not in the event stream. It belongs to a judge, not to runtime metrics; mixed together, metrics lose interpretability.

2.4 Transcript: a replayable raw record

The transcript is JSONL, one event per line, preserving timestamp, turn, type, and data. It doesn't aim for human readability; it aims for two things: when problems occur, replay by timeline; when switching to a different evaluator, the instrumentation doesn't change.

2.5 Fixture: turning a run into a distribution

A fixture consists of four parts: a task, scripted model responses, an executor factory, and assertions. The executor factory receives the trial number, so the same case can inject different failures across rounds to test pass^k, rather than hiding randomness inside the model.

The pass^k algorithm is straightforward: run the same case k times, and the case passes only if all k runs pass; the suite pass^k is passed cases / total cases. Then use the Wilson interval for a confidence range — with few samples, both 0/1 and 1/1 have wide intervals and can't be treated as stable conclusions.

2.6 Regression gate: compare to baseline, not to memory

The baseline stores three things: suite definition hash, repeats, and per-case pass rate. A new result first compares the hash and repeats; if they differ, it's evaluation drift; then compare per-case pass rates; if any metric drops, the regression gate rejects.

3. Implementation

The code for this article is in nano-harness, corresponding to modules src/nano_harness/observability.py / src/nano_harness/eval.py.

3.1 span

build_spans only reads events, it doesn't call back into the runtime. Each span records span_id, parent_id, name, kind, start/end times, and attributes:

@dataclass(frozen=True)
class Span:
    span_id: str
    parent_id: str | None
    name: str
    kind: str
    start: float
    end: float
    attributes: dict[str, Any]

Run is the root, turn hangs under run, model/context/tool hang under turn. Tool calls pair tool_call and tool_result via call_id; if no pairing is found, fall back to event time so spans are never lost.

3.2 Metrics

collect_metrics counts from the same batch of events: turns, tool_calls, tool_attempts, retries, tool_errors, compactions, stop_reason, usage. Tool retry counts come from the tool_retry event, not from caller arguments; so even if someone bypasses the loop and executes a tool directly, metrics don't drift.

3.3 transcript

def transcript(events):
    return "\n".join(
        json.dumps(event.to_dict(), ensure_ascii=False, sort_keys=True)
        for event in events
    ) + "\n"

One line per JSON, in write order. timestamp comes from the event itself; evaluation replay doesn't need to guess time.

3.4 Fixture and pass^k

Cases, checks, and suite execution:

@dataclass(frozen=True)
class EvalCase:
    name: str
    task: str
    responses: tuple[ModelResponse, ...]
    executor_factory: Callable[[int], Any]
    checks: tuple[Check, ...]
    config: RunConfig = field(default_factory=RunConfig)

run_suite runs each case k times and counts successes; suite pass^k is passed cases / total, with a 95% confidence range via the Wilson interval.

3.5 Regression gate

The baseline is a JSON: suite name, evaluation set hash, repeats, pass^k, and per-case pass rate. Comparison first checks hash and repeats, then goes per-case over pass rate:

report = compare_to_baseline(current, baseline)
if not report.passed:
    raise SystemExit(report.to_dict())

The regression report lists regressions, improvements, and aggregate_delta, so CI can directly see which case dropped.

4. Verification

The following readings come from a local venv (requires-python >=3.11, venv 3.12.7).

Three fixtures, each run 4 times:

suite: harness-smoke (repeats=4)
  retry-budget: rate=1.00 (4/4) pass^k=True
  no-progress: rate=1.00 (4/4) pass^k=True
  flaky-tool: rate=0.50 (2/4) pass^k=False
  pass^k=0.667 CI95=[0.208, 0.939]

flaky-tool fails not because "the answer is wrong" but because tool_errors appears in the event stream:

failed: flaky-tool 0 ('no_tool_errors',)

In a single run, the retry case metrics are:

turns=2 tool_calls=1 tool_attempts=3 retries=2 tool_errors=0
stop_reason=completed

The span tree shows directly that the retry happens inside the tool span:

span-0001 invoke_agent harness parent=None
span-0002 harness.turn parent=span-0001
span-0003 gen_ai.chat parent=span-0002
span-0004 execute_tool read_metric parent=span-0002
span-0005 harness.turn parent=span-0001
span-0006 gen_ai.chat parent=span-0005

The regression gate compares a baseline of "all 1.0" to the current result:

{'passed': False, 'drift': False, 'aggregate_delta': -0.333,
 'regressions': ['flaky-tool'], 'improvements': []}

Hash unchanged, repeats unchanged, drift is False; flaky-tool dropped from 1.0 to 0.5, so the regression gate rejects. That's more reliable than "this looks fine."

First and last lines of transcript (timestamp varies per run, shown as … placeholder):

{"data": {"task": "read the metric"}, "timestamp": …, "turn": 0, "type": "run_started"}
{"data": {"reason": "answer", "stop_reason": "completed", "tool_attempts": 3, "tool_calls": 1, "usage": {"completion_tokens": 0, "prompt_tokens": 0}}, "timestamp": …, "turn": 2, "type": "run_finished"}

5. Migration

To attach I7 to an existing harness, you don't need to change the loop:

  1. Emit events at existing run boundaries: run start/end, turn start, model response, tool call/result, context preparation. Events contain only facts, not evaluations.
  2. Use build_spans and collect_metrics to consume events; first attach one run and verify metrics match manual counts.
  3. Write 3–5 fixtures, covering the paths most likely to regress first: tool retries, turn budget, context compaction, permission denials.
  4. Run with k=3–5 to create a baseline; store the baseline JSON with the suite hash; in CI run the same set and compare passed, not single-run output.
  5. Mask the transcript; tokens and emails in tool output are replaced before writing to disk.

Migration acceptance criteria: delete one event, and metrics should lose one number; change one assertion, and the regression gate should point to which case failed. If that can't be done, the observation layer is still just logs.

6. Boundaries

Terminology

Term Explanation
span a measurable unit of work in a run, with parent-child relationships
transcript the event stream saved in time order, JSONL
fixture an evaluation case with fixed task, responses, executor, and assertions
pass^k proportion of cases where all k runs pass
Wilson interval confidence interval for binomial proportion with small samples
evaluation set hash stable digest of fixture definitions, used to detect drift

References

[^1]: OpenTelemetry, Semantic conventions for generative AI — https://opentelemetry.io/docs/specs/semconv/gen-ai/ [^2]: Yao et al., τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains(arXiv 2406.12045) — https://arxiv.org/abs/2406.12045 [^3]: EleutherAI, lm-evaluation-harness — https://github.com/EleutherAI/lm-evaluation-harness [^4]: nano-harness 观测与评测实现 — https://github.com/QingyaFan/nano-harness/blob/main/src/nano_harness/observability.py


This article is licensed under CC BY-NC-SA 4.0. Reproduce with author and original link.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

cheerfunfun

Questions about agent harness, feel free to chat~