49. Observability and cost

The daemon of Parts VII and VIII writes four records of every turn and reads none of them back. This chapter reads them. It adds a viewer, a cost accountant and a latency reader over chapter 26’s trace format, a hash that lets the audit log vouch for a trace file, and the counters a running daemon serves.

From the daemon's trace file to a view, a cost and a latency, and back to a verdict On the left, inside a dashed boundary labelled what the daemon writes, the trace file traces/turn.jsonl holding five kinds of span: run, turn, model_call, tool_call and policy_decision. Below it, still inside the boundary, the audit log audit.jsonl, whose turn_end record names the trace file and carries its sha256 and line count; an arrow runs down from the trace file to the audit log when the turn closes, and an arrow runs back up labelled VerifyTraces with three verdicts: ok, edited, missing. Outside the boundary, on the right, three readers each take the trace file as input: the viewer, which prints the tree, the counts and the usage keyed on request hash and model; the cost reader, which prices model calls by provider, actor and effort and is fed by a price table, prices.json; and the latency reader, which prints p50 and p90 with their rank pairs and compares the sample size n with 299. what the daemon writes traces/<turn>.jsonl run turn model_call tool_call policy_decision audit.jsonl turn_end: file name, sha256, line count VerifyTraces: ok | edited | missing | … viewer tree, counts, usage keyed on request_hash and model cost lines by provider, actor, effort prices.json latency p50, p90 with their ranks; n against 299

Why this layer exists

A turn leaves four files. traces/<turn>.jsonl holds chapter 26’s spans. trials.jsonl holds chapter 37’s record of the turn with chapter 40’s Extra, the run configuration (so aec-eval report does not read it: the extra field is unknown to ReadTrials, and chapter 51’s aecd eval writes the chapter 37 shape separately). session.jsonl is the transcript, and the audit log of chapter 48 is the chain of what the daemon decided. They are faithful and nothing reads them: the questions a person puts to a daemon that has run for a week are answered by none of them directly.

  1. What did this run do? A tree, with counts that agree with chapter 26’s rules for what is counted.
  2. What did it cost, and under which provider, actor and effort? A price per call, summed.
  3. How long do its calls take, and what can a sample of that size say? Percentiles, and what an interval around a percentile needs before it exists at all.
  4. Is the file on disk the file the daemon closed? A hash on the audit log’s turn_end record.
  5. What is it doing now? Counters and gauges, scraped.

The course design’s rule “traces before observability” fixes the constraint: chapter 49 builds on chapter 26’s format and does not invent a second one. No span kind and no attribute on a span is added, and the daemon writes no new file. Every number below is a derived view of obs.Span lines, trials.jsonl and the audit log.

Prices are the reader’s. The course makes no claim about what any provider charges (spec §9); prices.json is a file the reader writes, and where this chapter prints a rate it is z.ai’s published page as read on 2026-10-26 UTC, named as a reading and never as a fact about today.

Mechanism

The viewer

Summarize reads one trajectory’s spans and returns the counts below. Each rule is one that chapter 26 fixed and a consumer can get wrong.

// Summary is what the viewer derives from one trajectory: the counts chapter
// 26's table defines (tool_call spans, not Stop.Calls; policy_decision spans
// counted apart, by name), the usage summed from the model_call spans, keyed
// on (request_hash, model) so a routed retry is not double-counted, and the
// durations of every span kind, for the latency section. It reads attrs and
// usage only, never a body, and never an attr a redaction moves (a
// provider's call id survives it; reason and error do not).
type Summary struct {
    Trace      string
    Status     string
    Stop       string
    Turns      int            // every turn span, the workers' included
    ModelCalls int            // every model_call span
    ToolCalls  int            // every tool_call span, rejected ones included
    Rejected   int            // result_kind == rejected
    Policy     map[string]int // policy_decision spans by name: policy, route, context
    Approvals  map[string]int // approval spans by decision
    Usage      Usage          // summed over distinct (request_hash, model) model_calls
    ByProvider map[string]Usage
    ByRole     map[string]Usage
    Durations  map[string][]time.Duration // by kind; the run's own duration under "run"
    Workers    int                        // run spans under a tool_call (chapter 45)
    Problem    string                     // Reconstruct's error, when the file is not a tree
}

// Summarize walks a trajectory. A trace that does not reconstruct is still
// summarised from its flat spans, with Problem set to Reconstruct's error
// and that error returned: a crashed run is shown, never hidden. A model_call
// whose cached share exceeds its prompt is malformed and is reported the same
// way (the span is still counted, its usage is not).
func Summarize(spans []Span) (Summary, error) { return summarize(spans) }

// RenderOptions selects what Render prints.
type RenderOptions struct {
    Bodies bool // print the body file names beside model calls
    Width  int  // the name column; 0 is 24
}

// Render writes the trajectory as an indented tree, one line per span in Seq
// order: seq, kind, name, status, duration, and the identity attrs of the
// table (request_hash and model for a model_call; tool, call_hash and
// result_kind for a tool_call; decision for the policy and approval kinds),
// then a totals block from Summarize. With a fixed clock every duration is
// 0ms and the output is byte-identical between runs (the lab's golden).
func Render(w io.Writer, spans []Span, opt RenderOptions) error { return render(w, spans, opt) }
  • Calls are tool_call spans, not the run’s calls attr. A rejected call has a span and is not counted in Stop.Calls; so does each call of a batch that max_tool_calls refused. The viewer counts spans and also counts how many were rejected, so the two numbers can be read against each other.
  • policy_decision spans are counted apart, by name. The daemon writes three kinds of them: context (chapter 31’s compactor, one per turn), route (chapter 28, one per turn) and policy (chapter 47’s gate, one per tool call it decides, marked or not). A single count would mix a per-turn fact with a per-call one.
  • Usage is keyed on (request_hash, model). Chapter 26’s rule: under a router, two calls to different models can share a request_hash, and both are real calls to be counted; a turn the loop sent twice, answered by the same model, shares both and is counted once in Summarize. cost.FromSpans does the opposite and keeps seq in the key, because a provider billed the re-send; the two totals differ by exactly the re-sent turns, and the chapter prints neither as “the” cost without saying which it is.
  • A model_call without usage is counted and adds nothing; a cached share above the prompt is malformed. Cached is a share of Prompt (chapter 29), so Cached > Prompt is a provider fault: the span is counted, its usage is not, an error is returned, and every well-formed line is still read.
  • A worker’s run span under a tool_call is counted in the file’s totals. Chapter 45’s workers write into the parent’s file; their turns and usage are the run’s, and Workers says how many there were.
  • A trace that does not reconstruct is shown, not hidden. Summarize calls Reconstruct; when it refuses, Problem carries its error, the counts still come from the flat spans, and Render prints problem: … before the lines in Seq order, unindented. Chapter 26 notes that a crashed run’s file has lines for the spans that ended and none for the run, that a file cannot say which call was running (chapter 40’s ledger can), and that this chapter says what it does with a refused trace: it shows what exists and names the gap. The Walkthrough removes the run line from the capture and shows it.

Render cuts hashes to 12 hex characters, as aecd audit tail does. The viewer reads attrs and usage and never a body file, and it never reads an attr a redaction moves: reason and error are rewritten under a secrets block, request_hash, model and the counts are not, so a redacted trace summarises to the same numbers.

When stdout is a terminal, aec-trace passes its output through internal/termtext, as chapter 42’s terminal filter does for the notifier and the job listings. The viewer prints a rejected call’s name, and a rejected call is one whose name the model chose; an escape sequence in it would otherwise be obeyed by the reader’s terminal. A pipe or a file gets the bytes unchanged, so the goldens and the lab see exactly what Render wrote.

The same fact had a second consequence in the writers. A rejected call’s span is named by the tool name the model chose, and a name can be anything, including a key-shaped string; until this chapter the redactors rewrote a span’s attrs and left its Name alone. Both trace-writing paths now redact Span.Name too: audit.RedactingWriter for the daemon’s traces and eval.redactSpans for the runner’s. The shallow redactor never touches a registered tool’s name (write_file is not secret-shaped), so no committed trace moved, and TestFixturesUnchangedByNameRedaction proves that for every trace under go/; a mutant that drops the line fails TestRedactingWriterRedactsName.

The cost of a run

internal/cost prices model_call spans through a table the reader writes.

// Price is one model's rates per million tokens, in Table.Currency. Reasoning
// is the rate for reasoning tokens when the provider bills them apart; 0
// means they are billed as Output (the OpenAI and z.ai convention, where
// completion_tokens includes them). Cached is the rate for the cached share
// of the prompt (Usage.Cached, a share of Prompt, chapter 29): the uncached
// share is Prompt - Cached at Input.
type Price struct {
    Input     float64 `json:"input"`
    Cached    float64 `json:"cached_input"`
    Output    float64 `json:"output"`
    Reasoning float64 `json:"reasoning,omitempty"`
}

// Table is prices.json: a currency, the date and source the reader took the
// rates from (a provider's pricing page; recorded, never fetched by the
// tool), and a rate per provider name (routes.json's keys) with an optional
// per-model override. A local provider has rate 0 unless the reader prices
// his own electricity; the chapter shows how.
type Table struct {
    Currency string           `json:"currency"`
    AsOf     string           `json:"as_of"`
    Source   string           `json:"source"`
    Provider map[string]Price `json:"providers"`
    Model    map[string]Price `json:"models,omitempty"`
}

// Read decodes and checks a table: an unknown key, an empty currency, a
// table with no row, a negative or non-finite rate, or a key holding a
// control character or longer than 128 bytes is refused.
func Read(r io.Reader) (Table, error) {
    var t Table
    dec := json.NewDecoder(io.LimitReader(r, 1<<20))
    dec.DisallowUnknownFields()
    if err := dec.Decode(&t); err != nil {
        return Table{}, fmt.Errorf("prices: %w", err)
    }
    if strings.TrimSpace(t.Currency) == "" {
        return Table{}, errors.New("prices: currency is empty")
    }
    if len(t.Provider)+len(t.Model) == 0 {
        return Table{}, errors.New("prices: no provider or model row")
    }
    check := func(kind, key string, p Price) error {
        if !validKey(key) {
            return fmt.Errorf("prices: %s key %q is empty, too long or holds a control character", kind, key)
        }
        for name, v := range map[string]float64{"input": p.Input, "cached_input": p.Cached, "output": p.Output, "reasoning": p.Reasoning} {
            if v < 0 || math.IsNaN(v) || math.IsInf(v, 0) {
                return fmt.Errorf("prices: %s %s: %s rate %v is not a finite non-negative number", kind, key, name, v)
            }
        }
        return nil
    }
    for k, p := range t.Provider {
        if err := check("provider", k, p); err != nil {
            return Table{}, err
        }
    }
    for k, p := range t.Model {
        if err := check("model", k, p); err != nil {
            return Table{}, err
        }
    }
    return t, nil
}

// Of returns the price of one model call: the model's row if there is one,
// else the provider's, and ok false when neither exists (the caller reports
// an unpriced call, never prices it at 0). A cached share above the prompt
// is clamped to the prompt (FromSpans reports the span as malformed).
func (t Table) Of(provider, model string, u obs.Usage) (amount float64, ok bool) {
    p, found := t.Model[model]
    if !found {
        if p, found = t.Provider[provider]; !found {
            return 0, false
        }
    }
    cached := min(max(u.Cached, 0), max(u.Prompt, 0))
    amount = p.Input*float64(max(u.Prompt, 0)-cached) + p.Cached*float64(cached) + p.Output*float64(max(u.Completion, 0))
    if p.Reasoning > 0 {
        // Billed apart: the reasoning share leaves Output's count and takes its own rate.
        r := min(max(u.Reasoning, 0), max(u.Completion, 0))
        amount += (p.Reasoning - p.Output) * float64(r)
    }
    return amount / 1e6, true
}

Rates are per million tokens. A model’s row wins over its provider’s; a provider with no row, and a model with neither, is unpriced, never priced at zero: an unknown provider is a gap in the report and the amount is not added. A malformed table is refused when it is read.

One call. Let PP be the call’s prompt tokens, KK its cached share with 0≤K≤P0 \le K \le P, GG its completion tokens and R≤GR \le G the reasoning tokens inside GG. With rates pip_i, pcp_c, pop_o and prp_r per token (the table’s per-million rates divided by 10610^6),

c=pi(P−K)+pcK+poG. c \;=\; p_i\,(P - K) + p_c\,K + p_o\,G .

The uncached part of the prompt, P−KP - K, is billed at the input rate and the cached part at the cached rate. Reasoning tokens are part of GG and are billed at pop_o unless the provider bills them apart; then they move from one rate to the other, po(G−R)+prR=poG+(pr−po)Rp_o (G - R) + p_r R = p_o G + (p_r - p_o) R, and Of adds that second term. Of clamps KK into [0,P][0, P] so a faulty provider cannot make a prefix look better than the prompt it was part of; FromSpans reports the span as malformed in the same case, so the clamp never hides it.

// Line is one priced model call. Session and Turn are parsed from the trace
// id (<session>/<turn> under aecd; a runner's or cmd/aec's trace id is the
// Session with Turn 0); Actor comes from the audit log's model record that
// shares the span's request_hash and turn, Effort from the trial record;
// both are empty when FromSpans alone made the line.
type Line struct {
    Session     string
    Turn        int
    Seq         int
    Provider    string
    Model       string
    Role        string
    Actor       string
    Effort      string
    RequestHash string
    Usage       obs.Usage
    Amount      float64
    Priced      bool
}

// FromSpans prices every model_call span, keyed on (request_hash, model,
// seq): a retry inside the client (chapter 24's RetryPolicy) produces no
// second span, and a second span with the same hash and model is a second
// turn the provider billed, so it is a second line (Summarize counts the
// usage once; the two totals differ by exactly the re-sent turns). A span
// without usage is a line with Usage zero. A cached share above the prompt
// is an error, with every well-formed line still returned.
func FromSpans(spans []obs.Span, t Table) ([]Line, error) {
    var lines []Line
    var errs []error
    for i := range spans {
        sp := &spans[i]
        if sp.Kind != "model_call" {
            continue
        }
        var u obs.Usage
        if sp.Usage != nil {
            u = *sp.Usage
        }
        if u.Cached > u.Prompt {
            errs = append(errs, fmt.Errorf("cost: span %s (seq %d): cached %d exceeds prompt %d", sp.ID, sp.Seq, u.Cached, u.Prompt))
        }
        session, turn := splitTrace(sp.Trace)
        l := Line{Session: session, Turn: turn, Seq: sp.Seq, Provider: sp.Attrs["provider"], Model: sp.Attrs["model"],
            Role: sp.Attrs["role"], RequestHash: sp.Attrs["request_hash"], Usage: u}
        l.Amount, l.Priced = t.Of(l.Provider, l.Model, u)
        lines = append(lines, l)
    }
    return lines, errors.Join(errs...)
}

// FromRun prices a run directory: an aecd state directory (sessions/<id>/
// traces/<turn>.jsonl, trials.jsonl beside them, audit/ at the top when the
// daemon kept one) or an aec-eval run directory (trials.jsonl at the top,
// each trial naming its trace). The trial supplies Effort, and the provider
// where the span has none (a runner's trace: agent.providerName sees only
// *llm.Provider and *llm.Fake, and is frozen); the audit log's model records
// supply Actor. Files that cannot be read are named in problems and skipped;
// a directory that is neither shape is an error.
func FromRun(dir string, t Table) (lines []Line, problems []string, err error) {
    switch {
    case isDir(filepath.Join(dir, "sessions")):
        return fromDaemon(dir, t)
    case isFile(filepath.Join(dir, "trials.jsonl")):
        return fromEval(dir, t)
    }
    return nil, nil, fmt.Errorf("cost: %s is neither an aecd state directory (sessions/) nor an aec-eval run (trials.jsonl)", dir)
}

// Row is one aggregate: the group's key values in the order Aggregate was
// asked for them, the usage and amount summed over its lines, how many lines
// it holds and how many of them no table row priced.
type Row struct {
    Key      []string
    Usage    obs.Usage
    Amount   float64
    Lines    int
    Unpriced int
}

// Aggregate groups lines by the named fields (provider, model, role, actor,
// session, effort; none groups everything into one row) and returns the rows
// sorted by key. An unknown field name is a row key of "?" so a typo is
// visible, never silent.
func Aggregate(lines []Line, group ...string) []Row {
    byKey := map[string]*Row{}
    for _, l := range lines {
        key := make([]string, len(group))
        for i, g := range group {
            key[i] = field(l, g)
        }
        k := strings.Join(key, "\x00")
        r := byKey[k]
        if r == nil {
            r = &Row{Key: key}
            byKey[k] = r
        }
        addUsage(&r.Usage, l.Usage)
        r.Amount += l.Amount
        r.Lines++
        if !l.Priced {
            r.Unpriced++
        }
    }
    rows := make([]Row, 0, len(byKey))
    for _, r := range byKey {
        rows = append(rows, *r)
    }
    sort.Slice(rows, func(i, j int) bool { return strings.Join(rows[i].Key, "\x00") < strings.Join(rows[j].Key, "\x00") })
    return rows
}

// Trials prices trial records per candidate (provider@effort): the usage is
// each trial's own (the run span's, so a trial of several model calls is
// already summed), priced by the trial's provider and model. Chapter 38's
// matrix is the worked example.
func Trials(ts []eval.Trial, t Table) []Row {
    byKey := map[string]*Row{}
    for _, tr := range ts {
        r := byKey[tr.Candidate]
        if r == nil {
            r = &Row{Key: []string{tr.Candidate}}
            byKey[tr.Candidate] = r
        }
        u := obs.Usage{Prompt: tr.Usage.Prompt, Completion: tr.Usage.Completion, Reasoning: tr.Usage.Reasoning, Cached: tr.Usage.Cached}
        addUsage(&r.Usage, u)
        amount, ok := t.Of(tr.Provider, tr.Model, u)
        r.Amount += amount
        r.Lines++
        if !ok {
            r.Unpriced++
        }
    }
    rows := make([]Row, 0, len(byKey))
    for _, r := range byKey {
        rows = append(rows, *r)
    }
    sort.Slice(rows, func(i, j int) bool { return rows[i].Key[0] < rows[j].Key[0] })
    return rows
}

A runner’s model_call span carries no provider attr, so FromRun takes it from the trial. The audit log supplies Actor (principal, sched or peer:<id>), so a line answers “how much did the scheduler’s jobs cost” and “how much did the principal’s turns cost” from files that already exist. Trials prices chapter 37’s trials.jsonl per candidate, which is how chapter 38’s matrix is priced below.

A run. Chapter 26 derived the provider-reported prompt tokens over nn turns,

Pn=∑t=1npt=np1+∑s=1n−1(n−s)gs, P_n \;=\; \sum_{t=1}^{n} p_t \;=\; n\,p_1 + \sum_{s=1}^{n-1} (n - s)\, g_s ,

where ptp_t is turn tt’s prompt and gsg_s the tokens turn ss added to the history; I do not re-derive it. Without caching, the input cost is piPnp_i P_n, quadratic in nn for a constant gg. Chapter 29’s stable prefix changes the quadratic term’s rate. If the prefix held on every turn after the first, turn tt’s cached share is the previous prompt, Kt=pt−1K_t = p_{t-1} for t≥2t \ge 2 and K1=0K_1 = 0. Then

∑t=1nKt=∑t=2npt−1=∑t=1n−1pt=Pn−pn, \sum_{t=1}^{n} K_t \;=\; \sum_{t=2}^{n} p_{t-1} \;=\; \sum_{t=1}^{n-1} p_t \;=\; P_n - p_n ,

and the input cost of the run is

pi(Pn−(Pn−pn))+pc(Pn−pn)=pipn+pc(Pn−pn)=pcPn+(pi−pc)pn. p_i \bigl(P_n - (P_n - p_n)\bigr) + p_c\,(P_n - p_n) \;=\; p_i\,p_n + p_c\,(P_n - p_n) \;=\; p_c\,P_n + (p_i - p_c)\,p_n .

Since pn=p1+∑s=1n−1gsp_n = p_1 + \sum_{s=1}^{n-1} g_s, the last form says: the quadratic term is paid at the cached rate, and only the final prompt’s worth of tokens is paid at the full rate. The hit is a hypothesis and the lab reads it: the capture’s cached_tokens per call against pt−1p_{t-1} is the Walkthrough’s first measurement. Chapter 26 measured the shortfall as a constant 4 tokens on dixie, and chapter 29 explains it as the template’s framing at the join; the same shortfall is what a different server and a different model show below.

What the provider billed and what the server did. With keep_bodies on, each model call’s response body holds llama-server’s timings, and aec-trace cost -bodies prints chapter 29’s reading of it (budget.ParseTimings, through cost.Timings) beside each call’s cached_tokens: cache_n is the prefix the slot reused, prompt_n the suffix it evaluated, predicted_n the tokens it decoded. The two cached numbers agree on the wire (chapter 29), and prompt_n + cache_n is the prompt. prompt_n is the compute a local call costs, and it is what this chapter does not price: the table prices what a provider bills, which is the whole prompt less its cached share, and a local server bills nothing. A cloud body has no timings; the command skips it and counts it.

The fleet’s price. A local call has a rate of zero in prices.json, and that is a statement about the table and not about the world. The electricity it uses is real, and this book measures none of it. If the reader meters his host, a call costs

Wτ3.6×106R, \frac{W\,\tau}{3.6 \times 10^{6}}\,R ,

for WW watts under load, τ\tau seconds of the call and RR per kilowatt-hour: WτW \tau is joules, and a kilowatt-hour is 3.6×1063.6 \times 10^{6} joules. The model_call durations in the timed capture below are the τ\taus, and WW and RR are the reader’s.

The z.ai 429. A z.ai key without balance answers 429; chapter 29 saw the general endpoint answer “Insufficient balance or no resource package” for this book’s key. The client treats 429 as transient (llm.StatusError.Transient, internal/llm/types.go:203) and retries up to Attempts, three by default (internal/llm/provider.go:22). The router then counts it as a provider fault and advances the chain (providerFault, internal/route/router.go:514). That is at most three requests to z.ai per model call before the fallback, visible as aec_provider_requests_total{provider="zai",code="429"} in the exposition below. It is right for a rate limit and wasteful for a permanent refusal; this chapter changes neither.

Latency: a worst case, a budget and what n can say

Chapter 26 derived the worst case of a run, TD+Ka+TdmaxT D + K a + T d_{\max} (22 800 s at the defaults), from the deadlines the loop enforces. It is a bound and not a budget: nobody plans against six hours. A budget is a percentile of measured durations, and the question is what nn measured durations can say about a percentile of the distribution they came from.

Let X1,…,XnX_1, \ldots, X_n be independent durations with a continuous distribution function, let ξp\xi_p be its pp-quantile (Pr(X<ξp)=p\Pr(X < \xi_p) = p) and let x(1)≤…≤x(n)x_{(1)} \le \ldots \le x_{(n)} be the sorted sample. Let N=#{i:Xi<ξp}N = \#\{i : X_i < \xi_p\}. Each XiX_i falls below ξp\xi_p independently with probability exactly pp, so N∼Binomial(n,p)N \sim \mathrm{Binomial}(n, p). Now:

  • x(j)≤ξpx_{(j)} \le \xi_p holds exactly when at least jj observations are at or below ξp\xi_p, which for a continuous distribution (no mass at ξp\xi_p) is N≥jN \ge j.
  • x(k)≥ξpx_{(k)} \ge \xi_p holds exactly when fewer than kk observations lie below ξp\xi_p, which is N≤k−1N \le k - 1.

So the event x(j)≤ξp≤x(k)x_{(j)} \le \xi_p \le x_{(k)} is j≤N≤k−1j \le N \le k - 1, and

Pr(x(j)≤ξp≤x(k))=∑i=jk−1(ni)pi(1−p)n−i. \Pr\bigl(x_{(j)} \le \xi_p \le x_{(k)}\bigr) \;=\; \sum_{i=j}^{k-1} \binom{n}{i}\, p^{i} (1-p)^{n-i} .

The right side depends on nn, pp, jj and kk and on nothing about the distribution. That is the whole content of “distribution-free”: there is no assumption of normality, no variance estimate, and the bounds are observed values; nothing is interpolated. Ties (durations in milliseconds tie) only help. Let A=#{Xi<ξp}∼Bin(n,p−)A = \#\{X_i < \xi_p\} \sim \mathrm{Bin}(n, p^-) with p−≤pp^- \le p and B=#{Xi≤ξp}∼Bin(n,p+)B = \#\{X_i \le \xi_p\} \sim \mathrm{Bin}(n, p^+) with p+≥pp^+ \ge p. The event is {B≥j}∩{A≤k−1}\{B \ge j\} \cap \{A \le k - 1\}, whose probability is at least 1−Pr(B<j)−Pr(A≥k)1 - \Pr(B < j) - \Pr(A \ge k), and that is at least the binomial sum at pp because a binomial count is stochastically increasing in its probability. The stated coverage is a lower bound.

The pair (1,n)(1, n) is the widest, and it contains every other pair’s event, so some pair reaches a level exactly when (1,n)(1, n) does. Its coverage drops the two end terms i=0i = 0 and i=ni = n:

Pr(x(1)≤ξp≤x(n))=1−pn−(1−p)n. \Pr\bigl(x_{(1)} \le \xi_p \le x_{(n)}\bigr) \;=\; 1 - p^{n} - (1-p)^{n} .

Both subtracted terms fall as nn grows, so the coverage is increasing and the least nn reaching 95% can be found by bisection, which MinNForQuantile does. In exact rational arithmetic on wntrmute (TestQuantileIntervalBinomial recomputes the coverage with math/big on straylight):

pp least nn coverage at n−1n-1 coverage at nn
0.50 6 0.937500 0.968750
0.90 29 0.947665 0.952899
0.95 59 0.948953 0.951505
0.99 299 0.949963 0.950464

A run of 40 model calls has a 95% interval for the median and for p90 and has none for p99: a p99 of model-call latency from a hundred calls is a number with no distribution-free bound at all, and the chapter will not print one without saying so. For a budget the one-sided question is the natural one, and the same sum answers it: the largest observation is at or above ξp\xi_p with probability 1−pn1 - p^n, which reaches 0.95 at n=5,29,59,299n = 5, 29, 59, 299 for the four pp above.

// QuantileInterval is a distribution-free confidence interval for the p-th
// quantile from n sorted observations: the order statistics x(j) and x(k)
// with j < k chosen so that P(x(j) <= xi_p <= x(k)) >= level, where the
// probability is a binomial tail in p alone (chapter 49 derives it: the count
// of observations below xi_p is Binomial(n, p)). Among the pairs that reach
// level it takes the narrowest (k - j smallest), then the one with the most
// coverage, then the lowest j. It returns the interval and the 1-based ranks
// j and k, and NaN bounds with ranks 0 when no pair of ranks reaches level
// (n too small for that p: for p = 0.99 and level 0.95 the smallest n is
// 299), when the sample is not sorted, or when p or level is outside (0, 1).
// It never interpolates: the bounds are observed values.
func QuantileInterval(sorted []float64, p, level float64) (iv Interval, j, k int) {
    n := len(sorted)
    iv = nanInterval(level)
    if n < 2 || !(p > 0 && p < 1) || badLevel(level) || !sort.Float64sAreSorted(sorted) {
        return iv, 0, 0
    }
    // pmf[i] = P(N = i), N ~ Binomial(n, p); cum[i] = P(N <= i), cum[-1] = 0.
    cum := make([]float64, n+1)
    acc := 0.0
    for i := 0; i <= n; i++ {
        acc += math.Exp(logChoose(n, i) + float64(i)*math.Log(p) + float64(n-i)*math.Log1p(-p))
        cum[i] = acc
    }
    cover := func(j, k int) float64 { // P(j <= N <= k-1)
        c := cum[k-1]
        if j > 0 {
            c -= cum[j-1]
        }
        return c
    }
    bestJ, bestK, bestC := 0, 0, 0.0
    for width := 1; width < n && bestK == 0; width++ {
        for jj := 1; jj+width <= n; jj++ {
            if c := cover(jj, jj+width); c >= level && c > bestC {
                bestJ, bestK, bestC = jj, jj+width, c
            }
        }
    }
    if bestK == 0 {
        return iv, 0, 0
    }
    return Interval{Lo: sorted[bestJ-1], Hi: sorted[bestK-1], Level: level}, bestJ, bestK
}

// MinNForQuantile is the smallest n at which QuantileInterval can bound the
// p-th quantile at level with the extreme order statistics x(1) and x(n):
// the least n with 1 - p^n - (1-p)^n >= level. It is 0 when p or level is
// outside (0, 1), and when no n up to 2^40 reaches level (a p so close to 0
// or 1 that 1-p rounds to 1 needs more observations than exist). The
// function of n is increasing, so the least n is found by bisection.
func MinNForQuantile(p, level float64) int {
    if !(p > 0 && p < 1) || badLevel(level) {
        return 0
    }
    reaches := func(n int) bool {
        return 1-math.Pow(p, float64(n))-math.Pow(1-p, float64(n)) >= level
    }
    const top = 1 << 40
    if !reaches(top) {
        return 0
    }
    lo, hi := 1, top // reaches(hi), and the answer is in [lo, hi]
    for lo < hi {
        mid := lo + (hi-lo)/2
        if reaches(mid) {
            hi = mid
        } else {
            lo = mid + 1
        }
    }
    return lo
}

// BucketQuantile estimates the q-th quantile from a cumulative histogram
// (chapter 23's exposition: ascending upper bounds, counts at or below each,
// the last bound +Inf) by linear interpolation inside the bucket that holds
// rank ceil(q*count); Prometheus's histogram_quantile interpolates at the
// rank q*count instead, and takes the first bucket's lower edge as 0 only
// when its bound is above 0, so the two agree on the bucket and differ inside
// it by less than the bucket's width. The error against the nearest-rank
// quantile of the raw sample is bounded by that bucket's width, which
// chapter 23 derives (both lie in the same bucket). The lower edge of the first
// bucket is 0; a rank in the +Inf bucket returns the last finite
// bound. Malformed input (lengths that differ, bounds not ascending, a last
// bound that is not +Inf, counts that decrease, an empty histogram, q outside
// [0, 1]) is NaN.
func BucketQuantile(bounds []float64, cumulative []uint64, q float64) float64 {
    nb := len(bounds)
    if nb == 0 || nb != len(cumulative) || !math.IsInf(bounds[nb-1], 1) || math.IsNaN(q) || q < 0 || q > 1 {
        return math.NaN()
    }
    for i := 1; i < nb; i++ {
        if !(bounds[i] > bounds[i-1]) || cumulative[i] < cumulative[i-1] {
            return math.NaN()
        }
    }
    total := cumulative[nb-1]
    if total == 0 {
        return math.NaN()
    }
    rank := uint64(math.Ceil(q * float64(total)))
    if rank < 1 {
        rank = 1
    }
    b := sort.Search(nb, func(i int) bool { return cumulative[i] >= rank })
    if b == nb-1 { // the +Inf bucket
        if nb == 1 {
            return math.NaN()
        }
        return bounds[nb-2]
    }
    lower, prev := 0.0, uint64(0)
    if b > 0 {
        lower, prev = bounds[b-1], cumulative[b-1]
    }
    count := cumulative[b] - prev
    return lower + (bounds[b]-lower)*float64(rank-prev)/float64(count)
}

The narrowest pair is usually not (1,n)(1, n). At the smallest nn for the median it is, (1,6)(1, 6). At n=29n = 29 for p90 it is (21,29)(21, 29) (coverage 0.951349), and at n=299n = 299 for p99 it is (289,299)(289, 299) (0.950206): when pp is near 1 the lower end of the interval can sit well inside the sample, because NN is concentrated near npnp. Two more pairs, from the same script: the median at n=24n = 24 is (7,17)(7, 17) with coverage 0.956715, and at n=40n = 40 it is (14,27)(14, 27) with coverage 0.961523. The neighbouring pair of the same width, (13,26)(13, 26), covers only 0.951360, which is why the narrowest-then-most-coverage rule picks the centred one. The point of a tail is Dean and Barroso’s (2013). A request that must collect answers from 100 independent servers is slower than one server’s p99 whenever any one of them is, which has probability 1−0.99100=0.63401 - 0.99^{100} = 0.6340; their figure is “63% of user requests will take more than one second” for a one-second p99. They name the hedged request as the remedy: send the request to a second replica after a short delay and take whichever answers first. A daemon with one model has no replica to hedge to; its tail is the model’s own, and the remedy is the budget and the knowledge of how well a budget is known.

From buckets. The daemon cannot keep every duration forever. Chapter 23 derives the interpolation histogram_quantile performs and shows that the interpolated estimate and the raw nearest-rank quantile lie in the same bucket, so they differ by less than its width. BucketQuantile interpolates at rank ⌈qn⌉\lceil q n \rceil where Prometheus uses qnq n; the two ranks fall in the same bucket, so chapter 23’s bound holds for both. On the daemon’s thirteen bounds (0.05 to 600 seconds, the proxy’s), a quantile that falls in the 30–60 s bucket is known to 30 s. That is the division of labour: aecd_turn_seconds says which bucket, and the trace says how long. A rank in the +Inf bucket returns the last finite bound, as Prometheus does, and the first bucket’s lower edge is 0.

Mean of percentiles. The tail is not additive across windows. Two windows of 100 durations: {1×98, 100, 100}\{1 \times 98,\ 100,\ 100\} and {1×100}\{1 \times 100\}. With nearest rank (index ⌈0.99⋅100⌉−1=98\lceil 0.99 \cdot 100 \rceil - 1 = 98, the 99th smallest) the first window’s p99 is 100 and the second’s is 1, and their mean is 50.5. The pooled 200 values have 198 ones, and index ⌈0.99⋅200⌉−1=197\lceil 0.99 \cdot 200 \rceil - 1 = 197 is the 198th smallest: 1. The mean of the windows’ p99s, 50.5, is not the p99 of anything, and a dashboard that averages them shows a tail that the pooled data does not have (TestPooledVersusMeanOfP99 pins this).

Trace integrity

Chapter 48’s Verify proves, relative to an anchored head at sequence ss, that every record at or before ss is as written. This chapter extends it to a file the log does not contain. The daemon’s turn_end record carries three more attrs: trace, the base name of the file it hashed (<turn>.jsonl, or the name the daemon gave a crashed turn’s file when it moved it aside); trace_sha256, the sha256 of that file’s bytes; and trace_lines, its newline count.

// hashWriter sits innermost around the trace file: every byte the file
// accepts also goes into a sha256, and newlines are counted, so the hash is
// of exactly the bytes on disk, redacted bytes included (the redacting
// writer is outside it, as chapter 48 nests them). With an audit log,
// Close syncs the file before closing it, so the turn_end record, which the
// log fsyncs, never outlives the bytes it names; without one no record names
// them and nothing is synced. Bytes a failed write did not take are not
// hashed: n is the file's count. A late worker's tracer may still write
// while turnEnd reads the sum (chapter 45), so both take the mutex.
type hashWriter struct {
    f     *os.File
    sync  bool
    mu    sync.Mutex
    h     hash.Hash
    lines int
}

func newHashWriter(f *os.File, sync bool) *hashWriter {
    return &hashWriter{f: f, sync: sync, h: sha256.New()}
}

func (w *hashWriter) Write(p []byte) (int, error) {
    w.mu.Lock()
    defer w.mu.Unlock()
    n, err := w.f.Write(p)
    if n > 0 {
        w.h.Write(p[:n])
        w.lines += bytes.Count(p[:n], []byte{'\n'})
    }
    return n, err
}

// Close syncs (with an audit log) then closes; the first error wins.
func (w *hashWriter) Close() error {
    var serr error
    if w.sync {
        serr = w.f.Sync()
    }
    cerr := w.f.Close()
    if serr != nil {
        return serr
    }
    return cerr
}

// Sum is the hex sha256 of the bytes written so far and their line count.
func (w *hashWriter) Sum() (string, int) {
    w.mu.Lock()
    defer w.mu.Unlock()
    return hex.EncodeToString(w.h.Sum(nil)), w.lines
}

Under a secrets block the hash is of the redacted bytes, because the hash writer sits inside chapter 48’s redacting writer. Close syncs the file for the audit log’s reason: Append fsyncs each line, so without a sync on the trace the record could outlive the bytes it names after a power cut, and VerifyTraces would report edited on the daemon’s own file. The sync is one fsync per turn. No test observes it. A SIGKILL leaves the page cache in place, so a killed daemon’s file is complete whether or not the sync ran, and a mutant that removes Sync survives every test that can be written offline. That the sync happens rests on the code you see above and on reading it, as chapter 40 said of the ledger’s fsync.

// TraceVerdict is one trace file against the turn_end record of its turn.
type TraceVerdict struct {
    Session string
    Turn    int
    Path    string // relative to the sessions directory
    Verdict string // ok | edited | missing | unrecorded | unreadable
    Seq     uint64 // the turn_end record's seq, 0 when unrecorded
}

// VerifyTraces reads a verified log (Verify first; a chain that does not
// verify makes every verdict meaningless) and the sessions directory, and
// returns one verdict per turn_end record plus one per trace file no record
// names, in (session, turn, path) order. It reads hashes and never text.
//
// A record's turn has the candidates traces/<turn>.jsonl and every
// traces/<turn>.jsonl.<why>-<k> the daemon moved aside (an unanswered turn's
// trace is renamed before its record is written, chapter 40): the verdict is
// ok when a candidate's sha256 equals the record's trace_sha256, missing when
// there is no candidate, edited otherwise. A record that carries the attr
// trace (the file name it hashed: <turn>.jsonl, or the moved name of an
// unanswered turn) is checked against that file alone, so a copy renamed into
// another candidate's place does not stand for it; a record without the attr
// (written before it) is checked against every candidate. A trace file no
// record names, and a record from before the hash attrs existed, is
// unrecorded. A candidate that is not a regular file (a symlink) is
// unreadable and never followed, and so is a traces directory that is not a
// directory. trace_lines is recorded for the reader and not checked: once the
// sha256 matches it adds nothing, and when it does not the file is edited
// whatever its length.
func VerifyTraces(logDir, sessionsDir string) ([]TraceVerdict, error) {
    if _, _, err := Verify(logDir, "", nil); err != nil {
        return nil, fmt.Errorf("audit: traces: the log does not verify: %w", err)
    }
    records, err := turnEnds(logDir) // session -> turn -> the turn_end records
    if err != nil {
        return nil, err
    }
    sessions, err := os.ReadDir(sessionsDir)
    if err != nil {
        return nil, err
    }
    var out []TraceVerdict
    seenSession := map[string]bool{}
    for _, se := range sessions {
        if !se.IsDir() {
            continue
        }
        sid := se.Name()
        seenSession[sid] = true
        files := map[int][]string{} // turn -> candidate names
        tdir := filepath.Join(sessionsDir, sid, "traces")
        if fi, lerr := os.Lstat(tdir); lerr == nil && !fi.IsDir() {
            return nil, fmt.Errorf("audit: traces: %s is not a directory (a symlink is never followed)", filepath.ToSlash(filepath.Join(sid, "traces")))
        }
        ents, err := os.ReadDir(tdir)
        if err != nil && !os.IsNotExist(err) {
            return nil, err
        }
        for _, e := range ents {
            if turn, ok := traceTurn(e.Name()); ok {
                files[turn] = append(files[turn], e.Name())
            }
        }
        turns := map[int]bool{}
        for t := range files {
            turns[t] = true
        }
        for t := range records[sid] {
            turns[t] = true
        }
        var order []int
        for t := range turns {
            order = append(order, t)
        }
        sort.Ints(order)
        for _, turn := range order {
            cands := files[turn]
            sort.Strings(cands)
            hashes := map[string]string{} // name -> sha256, or "" when unreadable
            for _, c := range cands {
                hashes[c] = fileSHA(filepath.Join(sessionsDir, sid, "traces", c))
            }
            used := map[string]bool{} // candidates a verdict has named
            rel := func(name string) string { return filepath.ToSlash(filepath.Join(sid, "traces", name)) }
            rs := records[sid][turn]
            for _, r := range rs {
                out = append(out, judge(sid, turn, r, cands, hashes, used))
            }
            for _, c := range cands {
                if !used[c] && (len(rs) == 0 || claimed(rs)) {
                    v := TraceVerdict{Session: sid, Turn: turn, Path: rel(c), Verdict: "unrecorded"}
                    if hashes[c] == "" {
                        v.Verdict = "unreadable"
                    }
                    out = append(out, v)
                }
            }
        }
    }
    for sid, turns := range records {
        if seenSession[sid] {
            continue
        }
        for turn, rs := range turns {
            for _, r := range rs {
                v := TraceVerdict{Session: sid, Turn: turn, Seq: r.seq, Verdict: "missing", Path: filepath.ToSlash(filepath.Join(sid, "traces", strconv.Itoa(turn)+".jsonl"))}
                if r.sha == "" {
                    v.Verdict = "unrecorded"
                }
                out = append(out, v)
            }
        }
    }
    sort.SliceStable(out, func(i, j int) bool {
        a, b := out[i], out[j]
        if a.Session != b.Session {
            return a.Session < b.Session
        }
        if a.Turn != b.Turn {
            return a.Turn < b.Turn
        }
        if a.Path != b.Path {
            return a.Path < b.Path
        }
        return a.Seq < b.Seq
    })
    return out, nil
}

VerifyTraces verifies the chain first (a log that does not verify gives no verdict at all) and then returns one verdict per turn_end record and one per trace file no record names:

verdict means
ok the file named by the record has the record’s sha256
edited the file is there and its hash differs: changed, truncated, appended to, or replaced after the turn closed
missing the record names a file and there is none
unrecorded a trace file no record names, or a record from before the attrs existed (no hash to check)
unreadable the candidate is not a regular file, or cannot be read; a symlink is never followed

The per-record decision is judge, next to the listing in traces.go. A record that carries trace is checked against that file alone. The first version of this check matched a record against every file of its turn, and one mv defeated it: the real trace moved to a moved-aside name, a forged <turn>.jsonl put in its place, and the verdicts read ok and unrecorded. With the name in the record the forged file is edited and the real one is orphaned. A record without the attr (a log written before it) is still searched over the turn’s candidates.

What a verdict proves. ok says the file now on disk is byte for byte the file the daemon hashed when it closed the turn, relative to the audit chain’s anchor: it is as strong as the record is, and a record after the anchored head is itself unanchored (chapter 48’s rewrite-and-re-chain). edited says that something changed it, with no claim of who. What neither says is that the turn’s content was honest: a daemon, or anything with its authority, writes what it likes and the hash follows. A forgery that stays a valid tree passes Reconstruct (chapter 26 states this limit: a span moved to another turn, an edited attr), and a consistent forgery is exactly what the hash is for. Both commands that print verdicts take -head SEQ:HASH for the anchor; without it the verdict is relative to the log’s own tail.

What the hash changed about determinism. Chapter 48 observed that under -deterministic two runs of one session in two directories write the same audit log. From this chapter on that holds only when no span names a path under the state directory. A turn’s trace is now hashed on its turn_end record, and a span that carries the temp directory’s name (an approved outward write’s reason is write_file outside the workspace: <absolute path>) makes the hash differ between two directories. The two tests that compared two runs, labs/ch48’s fixture and the daemon’s TestAuditFeed, were moved off the dependence by writing to /dev/null, a path that does not vary, rather than repaired; the approval’s reason was not changed, because the tool that writes it belongs to Part VII. The capture below names no absolute path in any span (a call’s path argument is workspace-relative and spans carry hashes of calls, not their arguments), which is what TestFixtureCarriesNothingOfTheRun holds the deterministic fixture to.

The oversight line. The audit log beside traces/ also records what the gate and the human did. aec-trace oversight reads it, per day: the turn_end records (turns), the policy records by decision (allow, deny, ask: how often the gate decided and how), the approval records by answer (how often an approver was asked: the principal, chapter 42’s unattended approver, or a client approver such as chapter 53’s loop) and the tool records (outward calls that ran). The oversight cost of a day is the asks an approver answered (a person’s only when the approver was one) and the denials the gate made, set against the turns. It reads kinds, decisions and times, never a subject or a hash, and it does not verify the chain: aec-trace check and aecd audit verify do.

The daemon’s metrics

The daemon now registers its own families on the registry route.New has always filled, so one exposition holds chapter 28’s aec_route_* and aec_provider_requests_total, aec_breaker_open, and these:

// daemonMetrics are the daemon's own families, registered on the registry
// route.New already fills (chapter 28's aec_route_* and aec_provider_*), in
// this order. Counters are fed by the turn's span seam (every ended span
// passes a second SpanWriter whose sink returns no record), the gate's
// OnDecision hook, the scheduler's Run hook and the notifier; gauges are set
// when the registry is read. Every label value is bounded: an actor is
// principal, sched or peer:<id>; a provider or role is a routes.json name;
// a tool name comes from the registry (a rejected or filtered call, whose
// name the model chose, is counted under "-"); a job name is aecd.json's.
type daemonMetrics struct {
    turns     *obs.Counter   // aecd_turns_total{actor,status}
    turnSecs  *obs.Histogram // aecd_turn_seconds{actor}, secondsBuckets
    tokens    *obs.Counter   // aecd_tokens_total{provider,role,type}: prompt (whole), cached (its share), completion (whole), reasoning (its share)
    toolCalls *obs.Counter   // aecd_tool_calls_total{tool,result}
    policy    *obs.Counter   // aecd_policy_total{tier,decision}
    approvals *obs.Counter   // aecd_approvals_total{decision}
    sessions  *obs.Gauge     // aecd_sessions
    busy      *obs.Gauge     // aecd_sessions_busy
    jobs      *obs.Gauge     // aecd_jobs{state}: scheduled, suspended, quarantined
    jobRuns   *obs.Counter   // aecd_job_runs_total{job,stop}
    notices   *obs.Counter   // aecd_notices_total{kind,outcome}: sent, queued, failed, suppressed
    poolRun   *obs.Gauge     // aecd_pool_running
    poolWait  *obs.Gauge     // aecd_pool_waiting
    poolDone  *obs.Counter   // aecd_pool_completed_total (the delta since the last read)
    poolArea  *obs.Counter   // aecd_pool_area_seconds (the delta since the last read)
    auditSeq  *obs.Gauge     // aecd_audit_seq
    embeds    *obs.Counter   // aecd_embed_texts_total{host}

    mu           sync.Mutex
    lastDone     int
    lastAreaSecs float64
}

The counters read the same spans as the audit records, through a second audit.SpanWriter whose sink writes none (chapter 48’s seam). A job name, the one label an operator writes, is limited by sched to [A-Za-z0-9_-]. The names of the daemon’s turn and chapter 26’s turn collide. aecd_turns_total counts the daemon’s turns: one send is one turn and one trace file. The loop’s turn spans inside it are model rounds, and the turn_end record’s turns attr counts those.

Chapter 22’s aec-router serves its own aec_router_* families (chapter 23) on its own /metrics. The daemon neither reads nor re-serves them, and the capture ran against llama.cpp’s router directly, so none appear below; a stack that runs aec-router is scraped at both endpoints.

Two ways to read the daemon’s text. aecd metrics calls daemon/metrics on the control socket, which needs the daemon’s uid. aecd serve -metrics 127.0.0.1:PORT also serves GET /metrics for a scraper that wants HTTP. The listener is off unless the flag is given; Open refuses an address that is not loopback; it answers GET /metrics and nothing else, so every other method and path is a 404; and it refuses a request whose Host is not a loopback name on its own port, which is what a page rebound by DNS to 127.0.0.1 cannot send. Nothing is counted per connection or per request, so a connection that sends HEAD / and a TLS hello, as Kyle’s desktop plugin does to every new loopback listener, changes no byte of the next scrape. daemon/status lists workers in flight (Status.Workers; aecd status prints workers: N and a worker: line each, with the id chapter 45’s report uses as the name of the worker’s run span) and the pool’s counters. The daemon learns a start from the per-turn id source it hands the delegate, the first thing Run asks for, and an end from the worker’s ended run span; a turn’s end clears what is left, since a late worker’s spans can be lost (chapter 45). A daemon with no pool prints neither line.

The four golden signals of Google’s SRE book are covered by what is already here: latency by aecd_turn_seconds, traffic by aecd_turns_total, errors by its status label (and aecd_tool_calls_total), saturation by aecd_pool_waiting and aecd_sessions_busy. The daemon counts policy decisions by tier and decision (aecd_policy_total), which chapter 47’s gate emits and the oversight line reads from the log.

The GenAI conventions, mapped

OpenTelemetry’s GenAI semantic conventions (the repository at commit 9ffc7e0, dated 2026-10-21, status Development on its pages) are the industry’s format for this data. The mapping from this book’s spans:

this book OpenTelemetry GenAI
model_call a gen_ai.client.inference span, named chat <model>, kind CLIENT (INTERNAL for a model in the same process); gen_ai.request.model is the loop’s model, gen_ai.response.model the span’s model attr
usage.prompt_tokens gen_ai.usage.input_tokens, which “SHOULD include all types of input tokens, including cached tokens”, as Prompt does
usage.cached_tokens gen_ai.usage.cache_read.input_tokens, “included in” the input tokens, as Cached is
usage.completion_tokens gen_ai.usage.output_tokens; reasoning_tokens is gen_ai.usage.reasoning.output_tokens, also “included in” the output
finish_reason gen_ai.response.finish_reasons (an array there)
tool_call execute_tool <name>; gen_ai.tool.name is tool, and gen_ai.tool.call.id is call_id, “if and only if the model or provider supplied” one
run invoke_agent
turn none
policy_decision, approval none: the well-known operation names are chat, embeddings, execute_tool, invoke_agent, invoke_workflow, plan, retrieval and the memory operations among others, and none covers a decision or an approval

Their rule that a retried request’s span “SHOULD cover the duration of the logical operation with all retries” matches chapter 24’s client, which produces one span per call with the retries inside it. The convention is mapped here and not adopted, for three reasons: the course design permits one format; an exporter is a dependency, and the course’s Go is standard library only; and the attrs this book keys on, request_hash and call_hash, have no counterpart. A reader who exports can write the mapping in a dozen lines from the table. Against OpenTelemetry’s Tracing API (chapter 26’s link) the format differs in four ways: per-file counter ids and seq instead of 128-bit trace and span ids, no context propagation between processes, one file per run, and no sampling.

Walkthrough

One task went to one model twice. The task, written for the book: Three files are to be written in the workspace: a.txt with the line “alpha”, b.txt with the line “beta”, c.txt with the two lines “gamma” and “bees again”. Write them, then search the workspace for the word bees, then answer with the names of the files that contain it and how many lines each of the three files has. The model was straylight’s ornith-1.5-35b-a3b, through its llama.cpp router. The daemon was an aecd on straylight beside its model. The task invites a command to count lines, so the capture’s daemon was configured to run nothing the model chose. Its aecd.json carries a rule that denies every terminal call ("pattern": "terminal:"), no secrets block (so the trace shows real attrs), and max_turns 8; every aecd send used -approve deny. Before any daemon started, aecd policy check on a terminal call exited 3, a denial, from the same configuration. The run the viewer prints below is the first of two, on the fixed clock (aecd serve -deterministic); the second, on the real clock with keep_bodies, supplies the durations. Both are committed under go/labs/ch49/testdata. The bodies are not.

The fleet’s state. The model was asleep. The capture read GET /v1/models before anything else and printed its bound, at most 16 completions (max_turns 8, two runs) plus one to wake the model, with a /v1/models read before each by route.Guard and at most one POST /models/load:

straylight http://straylight:11434/v1/models: ornith-1.5-35b-a3b status=sleeping

The load route answered 400, and the completion that woke the model answered 200 (the script cut its body at 200 characters):

POST /models/load -> 400 {"error":{"code":400,"message":"model is already running","type":"invalid_request_error"}}
wake completion -> 200 {"choices":[{"finish_reason":"length","index":0,"message":{"role":"assistant","content":"","reasoning_content":"The"}}], …

The router counts a sleeping model as running, so loading it is refused, and one request that names it wakes it; the wake request was max_tokens 1 and one word. /v1/models then read loaded, and after the two runs it still did:

straylight http://straylight:11434/v1/models: ornith-1.5-35b-a3b status=loaded

The capture made 8 model requests against its bound of 17: the wake (1), the deterministic run’s four model calls and the timed run’s three. Each of the seven daemon requests went through the guard, which reads /v1/models before it and sends ?autoload=false. Nothing was unloaded. Both daemon processes were gone afterwards (kill -0 answered “no such process” for each pid) and neither state directory held a socket.

The viewer (aec-trace view, wntrmute, over the committed trace):

   1 run              multitool/1              ok             0ms prompt=4871 cached=3499 completion=436 reasoning=0 stop=final turns=4 calls=5
   2   turn             1                        ok             0ms
   3     policy_decision  context                  ok             0ms action=keep
   4     policy_decision  route                    ok             0ms source=disabled provider=local
   5     model_call       local                    ok             0ms prompt=1028 cached=0 completion=161 reasoning=0 request_hash=51aee5a39034 model=ornith-1.5-35b-a3b role=primary finish_reason=tool_calls
   6     tool_call        write_file               ok             0ms tool=write_file call_hash=15bf6ca39be4 result_kind=ok
   7     policy_decision  policy                   ok             0ms decision=allow
   8     tool_call        write_file               ok             0ms tool=write_file call_hash=35486f0b2d8e result_kind=ok
   9     policy_decision  policy                   ok             0ms decision=allow
  10     tool_call        write_file               ok             0ms tool=write_file call_hash=4c23d99fc87a result_kind=ok
  11     policy_decision  policy                   ok             0ms decision=allow
  12   turn             2                        ok             0ms
  13     policy_decision  context                  ok             0ms action=keep
  14     policy_decision  route                    ok             0ms source=disabled provider=local
  15     model_call       local                    ok             0ms prompt=1210 cached=1024 completion=49 reasoning=0 request_hash=b15571b5c33a model=ornith-1.5-35b-a3b role=primary finish_reason=tool_calls
  16     tool_call        search_files             ok             0ms tool=search_files call_hash=1415257d8d99 result_kind=ok
  17     policy_decision  policy                   ok             0ms decision=allow
  18   turn             3                        ok             0ms
  19     policy_decision  context                  ok             0ms action=keep
  20     policy_decision  route                    ok             0ms source=disabled provider=local
  21     model_call       local                    ok             0ms prompt=1273 cached=1206 completion=58 reasoning=0 request_hash=eac14b56276a model=ornith-1.5-35b-a3b role=primary finish_reason=tool_calls
  22     tool_call        terminal                 denied         0ms tool=terminal call_hash=a3c447f7c1c3 result_kind=denied
  23     policy_decision  policy                   ok             0ms decision=deny
  24   turn             4                        ok             0ms
  25     policy_decision  context                  ok             0ms action=keep
  26     policy_decision  route                    ok             0ms source=disabled provider=local
  27     model_call       local                    ok             0ms prompt=1360 cached=1269 completion=168 reasoning=0 request_hash=890c57fef055 model=ornith-1.5-35b-a3b role=primary finish_reason=stop
totals: status ok stop final turns 4 model_calls 4 tool_calls 5 rejected 0 workers 0
usage: prompt 4871 cached 3499 completion 436 reasoning 0 (distinct request_hash, model)
provider local: prompt 4871 cached 3499 completion 436 reasoning 0
policy_decision: context=4 policy=5 route=4
context: decisions 4 pruned 0 summarised 0
duration model_call: n 4 total 0ms max 0ms
duration policy_decision: n 13 total 0ms max 0ms
duration run: n 1 total 0ms max 0ms
duration tool_call: n 5 total 0ms max 0ms
duration turn: n 4 total 0ms max 0ms

The first column is seq, assigned when a span starts, so the run is 1 and the file’s own line order (spans are written when they end) is not the printed order. Four model rounds: three write_file calls in the first round’s batch (the model batched them), a search_files in the second, a terminal in the third, and the answer in the fourth. The terminal call is the viewer’s denial case: the tool_call has status denied and result_kind=denied, and the policy span beside it says decision=deny; the model read “denied: policy: the capture runs no model-chosen command on the host (ruling X9-10)” as its tool result (X9-10 is the working ruling, in this book’s records, that a capture’s daemon runs nothing the model chooses; the rule’s reason is committed as captured), and answered from the contents it had written. The run span’s calls=5 agrees with the five tool_call spans here; chapter 26’s point that they can differ needs a rejected call, and this run has none. reasoning=0 on every call does not mean the model did not reason: the transcript (session.jsonl) holds reasoning_content for each assistant turn. llama-server’s usage block carries no reasoning count, so those tokens are inside completion and Reasoning is 0, which the price table then bills as output.

A trace that is not a tree is shown with its problem. Removing the last line of the committed file (the run span, written last because it ends last) and viewing the 26 lines that remain, wntrmute:

problem: reconstruct: seq gap: want 1, got 2
   2 turn             1                        ok             0ms
   3 policy_decision  context                  ok             0ms action=keep
   …
  27 model_call       local                    ok             0ms prompt=1360 cached=1269 completion=168 reasoning=0 request_hash=890c57fef055 model=ornith-1.5-35b-a3b role=primary finish_reason=stop
totals: status - stop - turns 4 model_calls 4 tool_calls 5 rejected 0 workers 0

The tree is flat, with no indentation, the status and stop are - because the run line is the one that carries them, the counts are still the spans’ counts, and the command exits 1 after printing, naming the same error on stderr.

The cost (aec-trace cost, wntrmute, the committed table at the fleet’s zeros, then the same four lines under a second table that prices local at z.ai’s GLM-5.3-Flash reading of 2026-10-26, 0.15, 0.03 and 0.50 USD per million for input, cached input and output; TestCostOfTheRun builds that table):

provider  actor      effort   lines  prompt  cached  completion  reasoning  amount    unpriced
local     principal  default  4      4871    3499    436         0          0.000000  0
total 0.000000 USD (4 lines, 0 unpriced)
provider  lines  prompt  cached  completion  reasoning  amount    unpriced
local     4      4871    3499    436         0          0.000529  0
total 0.000529 USD (4 lines, 0 unpriced)

Four lines, one actor (principal), one effort (default). At the reading’s rates the run would have cost (1372⋅0.15+3499⋅0.03+436⋅0.50)/106=0.00052877(1372 \cdot 0.15 + 3499 \cdot 0.03 + 436 \cdot 0.50)/10^6 = 0.00052877 USD; with the cached share priced as ordinary input, (4871⋅0.15+436⋅0.50)/106=0.00094865(4871 \cdot 0.15 + 436 \cdot 0.50)/10^6 = 0.00094865 USD. Pricing the cached share at its own rate removes 44% of that cost, (0.00094865−0.00052877)/0.00094865=0.4426(0.00094865 - 0.00052877)/0.00094865 = 0.4426; TestCostOfTheRun computes both totals from the spans. The derivation predicts the hit: with P4=4871P_4 = 4871, p4=1360p_4 = 1360 and the cached rate 0.030.03,

pcPn+(pi−pc)pn=0.03⋅4871+0.12⋅1360=146.13+163.20=309.33 p_c P_n + (p_i - p_c)\,p_n \;=\; 0.03 \cdot 4871 + 0.12 \cdot 1360 \;=\; 146.13 + 163.20 \;=\; 309.33

micro-USD of input if the prefix held on every turn. The measurement is 310.77: the measured cached shares are 1024, 1206 and 1269, and each is 4 short of the previous prompt (1028, 1210, 1273), so 12⋅0.12=1.4412 \cdot 0.12 = 1.44 micro-USD more than the formula. The first call is cold, K1=0K_1 = 0, as the derivation said. The constant shortfall is the one chapter 26 measured on dixie; straylight’s 35b shows it too (TestCachedShareAgainstPrefix pins it for the committed run). The cached share of the prompt over the run is 71.8%.

The timed run’s first call shows a different number. Its prompt is also 1028 tokens and its cached share is 512, not zero, on a slot that had held the earlier run. The cause is not established: I did not locate where the two prompts part.

The same command priced chapter 38’s matrix, per candidate, wntrmute (aec-trace cost -prices prices.json -trials …/ch38/testdata/matrix/trials.jsonl):

candidate                   lines  prompt  cached  completion  reasoning  amount    unpriced
dixie-9b@default            120    92677   81217   14850       0          0.000000  0
dixie-9b@none               120    93423   86774   6346        0          0.000000  0
straylight-35b@budget:64    120    92123   82728   13293       0          0.000000  0
straylight-35b@default      120    92364   82798   15470       0          0.000000  0
straylight-35b@none         120    92763   88139   6240        0          0.000000  0
straylight-trinity@default  120    0       0       0           0          0.000000  0
zai@high                    60     31000   23808   6393        4350       0.004990  0
zai@low                     60     31000   23872   2035        134        0.002803  0
zai@max                     60     31000   26176   6424        4342       0.004721  0
total 0.012513 USD (900 lines, 0 unpriced)

Sixty trials of the cloud column cost half a cent at that reading at high; low cost 56% as much. The difference is nearly all output: 4358 fewer completion tokens (2035 against 6393; the reasoning tokens, 134 against 4350, are inside those counts) account for 99.6% of the 2186.7 micro-USD gap. The fleet rows are zero because the table says so, and straylight-trinity shows the other kind of zero: its 120 trials are errors with no usage, so they have nothing to price, which is different from a priced zero. The matrix’s z.ai rows bill reasoning inside the completion count, as the table’s reasoning rate of 0 means.

The latency (aec-trace latency, over the timed run’s state directory, committed as latency.txt):

model_call n=3
  p50 1.410s  no distribution-free interval at n=3 for p50 (needs n >= 6)
  p90 2.912s  no distribution-free interval at n=3 for p90 (needs n >= 29)
  p99 2.912s  no distribution-free interval at n=3 for p99 (needs n >= 299)
tool_call n=4
  p50 0.003s  no distribution-free interval at n=4 for p50 (needs n >= 6)
  p90 0.004s  no distribution-free interval at n=4 for p90 (needs n >= 29)
  p99 0.004s  no distribution-free interval at n=4 for p99 (needs n >= 299)
turn n=3
  p50 1.413s  no distribution-free interval at n=3 for p50 (needs n >= 6)
  p90 2.924s  no distribution-free interval at n=3 for p90 (needs n >= 29)
  p99 2.924s  no distribution-free interval at n=3 for p99 (needs n >= 299)
run n=1
  p50 5.401s  no distribution-free interval at n=1 for p50 (needs n >= 6)
  p90 5.401s  no distribution-free interval at n=1 for p90 (needs n >= 29)
  p99 5.401s  no distribution-free interval at n=1 for p99 (needs n >= 299)

This is the result of one capture: three model calls, 2.912 s, 1.059 s and 1.410 s, on straylight’s 35b; the point estimates are printed (nearest rank) and none has an interval, because 3 is below the 6 the median needs. Every line says so with the number it would need. Nothing here is a p50 of model-call latency; it is the median of three numbers. As the table says, to say p90 of this model’s call latency with 95% confidence, collect at least 29 calls, and for p99 at least 299. The tool_call durations (4.3, 3.5, 2.9 and 2.1 ms) are 0.2% of the run’s 5.401 s, and the three model calls are 99.6% of it. At this scale a latency budget is a budget for the model. TestLatencyIntervals asserts the three refusals on the committed durations and, on synthetic samples, the smallest sizes at which each interval exists.

The kept bodies give the server’s side (the body lines of aec-trace cost -bodies, run on straylight over the timed run, bodies.txt, which also starts with a three-line cost table):

multitool/1 seq=5 cached_tokens=512 cache_n=512 prompt_n=516 predicted_n=154
multitool/1 seq=15 cached_tokens=1024 cache_n=1024 prompt_n=193 predicted_n=49
multitool/1 seq=21 cached_tokens=1213 cache_n=1213 prompt_n=67 predicted_n=83
bodies: 3 calls with timings, 0 without

cached_tokens equals cache_n on all three calls, prompt_n + cache_n is the span’s prompt (516 + 512 = 1028, 193 + 1024 = 1217, 67 + 1213 = 1280), and predicted_n is the span’s completion count (154, 49, 83). Billed prompt tokens were 3525 and the server evaluated 776 of them, 22%. The 78% it did not evaluate is what the cached rate prices.

The oversight line (aec-trace oversight, the deterministic run’s log, oversight.txt, captured on straylight):

2026-10-01 turns=1 policy: allow=4 deny=1 ask=0 approvals: - tools=0

One day (the fixed clock’s), one turn, four decisions that allowed (the three writes and the search) and one that denied (terminal), no question put to a person and no outward call that ran. tools=0 is correct: tool records are outward calls (chapter 48), and every call here was inside the workspace. Chapter 48’s fixture, three turns on its own day, shows the other columns (aec-trace oversight go/labs/ch48/testdata -audit go/labs/ch48/testdata, wntrmute):

2026-10-01 turns=3 policy: allow=1 deny=1 ask=1 approvals: allow=1 tools=1

One call was asked about and approved, one denied, one allowed, and one outward call ran.

The metrics (aecd metrics, straylight, after the deterministic run; 18 of the exposition’s 36 series lines, with the # HELP and # TYPE lines left out. Omitted: the 14 aecd_turn_seconds_bucket lines (every one is 1), aecd_sessions_busy 0 and the three aecd_jobs{state=…} 0 gauges):

aec_route_decisions_total{role="primary",source="disabled"} 4
aec_provider_requests_total{provider="local",code="200"} 4
aec_breaker_open{provider="local"} 0
aecd_turns_total{actor="principal",status="ok"} 1
aecd_tokens_total{provider="local",role="primary",type="cached"} 3499
aecd_tokens_total{provider="local",role="primary",type="completion"} 436
aecd_tokens_total{provider="local",role="primary",type="prompt"} 4871
aecd_tokens_total{provider="local",role="primary",type="reasoning"} 0
aecd_tool_calls_total{tool="-",result="denied"} 1
aecd_tool_calls_total{tool="search_files",result="ok"} 1
aecd_tool_calls_total{tool="write_file",result="ok"} 3
aecd_policy_total{tier="none",decision="allow"} 3
aecd_policy_total{tier="rule",decision="allow"} 1
aecd_policy_total{tier="rule",decision="deny"} 1
aecd_turn_seconds_sum{actor="principal"} 0
aecd_turn_seconds_count{actor="principal"} 1
aecd_sessions 1
aecd_audit_seq 15

The exposition and the trace read the same spans: 4 provider requests with status 200 are the 4 model_call spans, the token counters are the run’s usage, and the - tool label is the denied terminal call (a denied call’s name is not trusted as a label). The three policy decisions with tier none are the writes (no rule matched, the tool’s own marking decided), the rule-tier allow is the search (a read inside the workspace) and the rule-tier deny is the configured terminal rule. aecd_turn_seconds_sum is 0 on a deterministic daemon, as it must be on a fixed clock. The capture had no worker and no pool, so none appears; TestStatusListsWorkers holds a worker in flight and shows the workers: N and worker: lines.

The verdicts (aecd audit verify -traces, straylight, over the deterministic state directory):

ok: head 15:6cdf8a7c4ae6eed04ea424dc4d204b1a4a4aaf68255fdad74be5d55a795a09ae (15 lines) key 98641e3227ccd415
trace multitool/1 ok multitool/traces/1.jsonl seq=15
traces: ok 1 edited 0 missing 0 unrecorded 0 unreadable 0

The record at seq 15 is the turn_end; its attrs are trace 1.jsonl, trace_lines 27 and trace_sha256 ad54291f…2100, the sha256 of the committed trace file and its 27 lines. The log has 16 lines once the daemon has shut down (the close record is the sixteenth). Then, in a copy of the state directory, one letter of the trace changed case (a single byte, 0x20 flipped), and the same command run again:

ok: head 16:82e51ff5ed18df061646ce6833f0f99d904e03c85d853260e4d062d588c7874b (16 lines) key 98641e3227ccd415
trace multitool/1 edited multitool/traces/1.jsonl seq=15
traces: ok 0 edited 1 missing 0 unrecorded 0 unreadable 0

It exited 1. The chain still verifies: the log was not touched. With the byte restored, the same command printed ok and exited 0. TestTraceVerdictsOnCapture does this on the committed files. Both pieces can be pinned to an anchor: aec-trace check DIR -head 15:6cdf… verifies the chain against the head an anchor published, then every trace, and exits 3 on an edited, missing or unreadable verdict.

Exercises

(a) The cached-prefix derivation assumed the prefix held on every turn after the first. Derive the input cost when it holds on even turns only and misses on odd turns, and say what the run’s cached_tokens sequence would look like. What would the capture’s prompts have cost at the dated reading?

Answer

With a hit on turns t=2,4,…t = 2, 4, \ldots and a miss on the odd turns (a different prefix, a restarted slot), Kt=pt−1K_t = p_{t-1} for even tt and Kt=0K_t = 0 for odd tt, so S=∑Kt=∑t evenpt−1=p1+p3+…S = \sum K_t = \sum_{t \text{ even}} p_{t-1} = p_1 + p_3 + \ldots The input cost is pi(Pn−S)+pcSp_i (P_n - S) + p_c S, and SS is a sum of about half the prompts, the smaller ones, so the saving is a smaller share of the quadratic term than the all-hits case, where S=Pn−pnS = P_n - p_n. The sequence of cached counts reads 0,p1,0,p3,0,…0, p_1, 0, p_3, 0, \ldots against the all-hits 0,p1,p2,p3,…0, p_1, p_2, p_3, \ldots. For the capture’s n=4n = 4 with KK equal to the previous prompt exactly, S=1028+1273=2301S = 1028 + 1273 = 2301 and the whole run (input and the 436 output tokens) is 0.000672530.00067253 USD, against 0.000527330.00052733 for the all-hits formula and 0.000948650.00094865 with no caching, all at the dated reading (arithmetic on wntrmute: (0.15⋅(4871−2301)+0.03⋅2301+0.50⋅436)/106(0.15 \cdot (4871 - 2301) + 0.03 \cdot 2301 + 0.50 \cdot 436)/10^6 for the first).

(b) A run has ten model calls. Give the narrowest 95% interval for the median from the binomial table by hand, and check it against the lab. What does an eleventh observation, larger than all ten, do to the claim about the same two order statistics?

Answer

For n=10n = 10, p=1/2p = 1/2 the counts (10i)\binom{10}{i} are 1,10,45,120,210,252,210,120,45,10,11, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1, over 210=10242^{10} = 1024. A pair (j,k)(j, k) covers ∑i=jk−1(10i)/1024\sum_{i=j}^{k-1}\binom{10}{i}/1024, and a narrower pair covers a subset of the terms of any wider pair that contains it. The best pairs of width 6, (2,8)(2, 8) and (3,9)(3, 9), cover 957/1024=0.9346957/1024 = 0.9346, which is below 0.95, so a width of 7 is the least that can. Of width 7, (1,8)(1, 8) and (3,10)(3, 10) cover 967/1024=0.9443967/1024 = 0.9443, and (2,9)(2, 9) covers 1002/1024=0.97851002/1024 = 0.9785: the pair is (2,9)(2, 9), the second smallest and the second largest. An eleventh observation above all ten leaves x(2)x_{(2)} and x(9)x_{(9)} at ranks 2 and 9, but now in a sample of 11 where the coverage is 1−79/2048=0.96141 - 79/2048 = 0.9614: the same two values claim less, and still more than 0.95. The lab’s QuantileInterval returns ranks (2,9)(2, 9) for both n=10n = 10 and n=11n = 11.

(c) Construct two windows of 100 durations whose mean of p99s is below the pooled p99 (the chapter’s example had it above), and say what a dashboard that averages windows is showing.

Answer

Take one window with 97 ones and 3 hundreds, and one with 100 ones. Nearest rank puts p99 at the 99th smallest: 100 in the first window (its 98th to 100th values are the hundreds) and 1 in the second, mean 50.5. The pooled 200 values have 197 ones and 3 hundreds, and p99 is the ⌈0.99⋅200⌉=198\lceil 0.99 \cdot 200 \rceil = 198th smallest: 100. The mean, 50.5, understates the pooled tail by half. In the chapter’s example the same three-line argument runs the other way. The mean of per-window quantiles is the quantile of nothing, and its error has no sign: it depends on how the tail is divided among windows. The remedy is to pool the counts: sum the buckets across windows and take one quantile of the sum, which is what sum by (le) before histogram_quantile does, with the bucket-width error bound derived above.

(d) A worker the loop abandoned (chapter 45) is still running when its turn closes, and its tracer writes one more span to the turn’s trace file after turnEnd has read the hash. What does VerifyTraces say about that turn, and does the span reach the file?

Answer

It says ok, and the span never reaches the file. The turn’s trace file is closed before turnEnd runs, and a write to a closed file takes zero bytes: hashWriter.Write hashes and counts only the bytes the file took, so the hash and the file stay equal. The late worker’s span is lost, which is the loss chapter 45 already states and which workersDone accounts for by clearing the worker from Status.Workers at the turn’s end. A verdict of edited here would be a false alarm about the daemon’s own file; the zero-byte rule prevents it, the mutex covers a write that lands while the sum is being read, and TestHashWriterLateWrite pins both.

(e) Map a policy_decision span named policy onto the GenAI conventions, or show there is nothing to map it onto, and say what an exporter would lose.

Answer

The conventions’ operation names cover model calls, tool execution, agent invocation and memory, and no entry stands for a decision made about a call before it runs. The nearest home is the execute_tool span of the same call, as extra attributes in a vendor namespace; that attaches the decision to the call it concerned but flattens a per-call record into attributes of another span, and for a denied call there may be no execution to attach it to, since the tool never ran. An exporter that maps only the standard attributes drops the tier, the rule and the reason, which are what chapter 47 and the oversight line use, and drops the route and context decisions entirely. The span tree it emits is shorter and answers cost and latency questions; it cannot answer why a call did not run.

Lab

make lab CH=49 IMPL=mine runs go/labs/ch49 against go/labs/ch49/mine/viewer.go; IMPL=ref runs it against this chapter’s packages. You write four pieces and the lab supplies the rest: Summarize (the counts of one trajectory: tool_call spans and not the run’s calls, usage summed once per distinct request_hash and model), Render (the indented tree and the totals block, byte-identical between runs under a fixed clock), Price (one call under a table: the model’s row if there is one, else the provider’s; unpriced when neither exists; the cached share at its own rate) and QuantileInterval (the narrowest pair of order statistics whose binomial coverage reaches the level, refusing when none does).

  • TestScriptedGolden: a scripted multi-tool turn on a real aecd child (chapter 40’s rig, on the fixed clock) renders to the committed golden, a second child’s render equals the first’s, and the counts and usage are the script’s own.
  • TestRenderGolden and TestSummarizeCounts: the committed capture’s trace renders to view.txt byte for byte, and its counts are written as constants read by hand from the 27 lines (four model calls, five tool calls, five policy spans, one of them a denial).
  • TestPriceExamples and TestCostOfTheRun: the worked prices (a cached call, the same call uncached, a model row over the provider row, an unknown provider not priced), and the capture priced at the fleet’s zeros and at the dated reading with and without the cached share.
  • TestLatencyIntervals: the timed run’s three durations refuse every quantile, the smallest sizes at which an interval exists are 6, 29 and 299, and the ranks there are (1,6)(1, 6), (21,29)(21, 29) and (289,299)(289, 299).

The reference alone is held to the checks that need more than the four pieces: TestMatrixPriced (chapter 38’s matrix per candidate through the reference’s cost.Trials), TestCachedShareAgainstPrefix (the 4-token shortfall of the three hits), TestTraceVerdictsOnCapture (the committed audit log verifies, the captured trace is ok, a copy with one changed byte is edited), TestOversightOfCapture, TestNoSecretsInTestdata and TestFixtureCarriesNothingOfTheRun (no path, socket, pid, port or time but the fixed clock’s in the deterministic fixtures). They run on the reference whichever IMPL is set.

Against the starter, AEC_IMPL=mine go test ./labs/ch49 fails six tests (TestScriptedGolden, TestPriceExamples, TestRenderGolden, TestSummarizeCounts, TestCostOfTheRun, TestLatencyIntervals), and the reference passes in under a second, both on wntrmute. Nothing re-runs the capture: the model’s answers vary between runs, so the labs read the committed files and pin what is in them, and the timed capture is structure and durations and is compared to nothing.

Further reading

  • Jeffrey Dean and Luiz André Barroso, The tail at scale, Communications of the ACM 56(2), 74-80 (February 2013): why the slowest component dominates at scale, the 63% figure for a hundred servers, and hedged requests.
  • Rob J. Hyndman and Yanan Fan, Sample quantiles in statistical packages, The American Statistician 50(4), 361-365 (November 1996): a comparison of the commonly implemented sample-quantile definitions and the recommendation of the median-unbiased estimator; this book’s nearest rank is chapter 38’s stated convention. Cited for what the abstract and the author’s page state; the full text was not read.
  • OpenTelemetry, semantic conventions for generative AI at commit 9ffc7e0 (2026-10-21): gen-ai-spans.md (the operation names and the execute-tool span) and client-inference.md (the inference span and its usage attributes); both are in Development.
  • Prometheus, docs/querying/functions.md at 76dce27: histogram_quantile, the same page chapter 23 cites, for the interpolation and the two edge rules.
  • Rob Ewaschuk, “Monitoring Distributed Systems”, chapter 6 of Site Reliability Engineering, first edition, edited by Betsy Beyer, Chris Jones, Jennifer Petoff and Niall Richard Murphy (Google; O’Reilly Media, 2016): the four golden signals.
  • Benjamin H. Sigelman, Luiz André Barroso, Mike Burrows, Pat Stephenson, Manoj Plakal, Donald Beaver, Saul Jaspan and Chandan Shanbhag, Dapper, a Large-Scale Distributed Systems Tracing Infrastructure, Google technical report (2010): the trace-and-span shape that chapter 26’s format follows, and where it differs: one file per run here, no sampling, no collector.
  • llama.cpp, tools/server/README.md at b29c606: the timings object (cache_n, prompt_n, predicted_n) and usage.prompt_tokens_details.cached_tokens.
  • z.ai, pricing, as read on 2026-10-26 UTC: the source of the dated reading in prices.json (GLM-5.3-Flash 0.15, 0.03 and 0.50 USD per million tokens for input, cached input and output). It is a reading and not a claim; read the page before pricing anything.

results matching ""

    No results matching ""