28. Provider routing

Why this layer exists

The reader’s stack already routes by role. The main assistant is a cloud model, with z.ai’s glm-5.3-flash behind it as the cloud fallback. Straylight’s ornith-1.5-35b-a3b is the local fallback and the model that subagents are delegated to, and it is also straylight’s vision model. Dixie’s ornith-1.5-9b-uncensored takes the auxiliary chores: approvals, page summaries, titles. These roles are read from the reader’s own notes on the fleet, paraphrased, not from Hermes’s configuration. In Hermes a role and its fallback are one table row: this role, this model, then these others in order. aec keeps two things apart that the row fuses. A role is a policy, the kind of model a request wants. A chain is the order in which providers that can serve the role are tried.

The split is forced by chapter 21. The registered route head was trained over five options, primary, delegation, vision, aux and local, and a registered choice may be asked only over a subset of its own options (chapter 21), so a sixth option called fallback cannot be something the gate picks. “Fallback” is the second entry of a chain. Chapter 22 listed the roles as primary, fallback, delegation, auxiliary and vision, and that sentence stays true: a fallback is still a model, now the next one in a chain.

This chapter builds the component that sits between the agent loop of chapter 26 and the clients of chapter 24. It filters the roles down to those the request may take, asks the registered route head to choose among them, walks the chosen role’s chain, and stops sending to a provider that is failing. Its governing rule is that the gate fails open. A wrong route costs a slower or poorer answer, so no failure of the gate, of its embedder or of its weights is ever a reason to refuse a request: every error takes the configured role, primary by default, with the request’s own restrictions still applied. Chapter 47’s security gate uses the same runtime and reads the same typed errors, and it fails closed: a doubtful answer there is a denial or a question to the reader. The two chapters differ in what an error means, so decide returns errors and makes no policy of its own; the caller maps them.

The component lives in aecd, in-process (chapter 40 constructs it with route.New), because a routing decision is a function call on the request path and a hop to another process would add its latency to every turn. aec-decide is the same runtime behind POST /v1/decide for clients that are not aecd, and it is what the chapter’s A/B drives. Three packages carry the chapter: internal/decide (2,230 lines without tests), the Go port of chapter 21’s runtime; internal/route (1,659 lines, of which chapter 40’s wake.go is 196), the roles, the breaker, the gate and the chain; and cmd/aec-decide (559 lines). Line counts were taken on straylight at the finished repository.

Mechanism

Roles, chains and eligibility

A provider is one model behind one OpenAI-compatible endpoint:

p=(client, model, local, vision), p = (\mathrm{client},\ \mathrm{model},\ \mathrm{local},\ \mathrm{vision}),

where local says its traffic stays on the reader’s machines and vision says it accepts image parts. A role rr has a chain Cr=(p1,…,pm)C_r = (p_1, \ldots, p_m), an ordered list of providers. A request is

q=(text, image, private, force), q = (\mathrm{text},\ \mathrm{image},\ \mathrm{private},\ \mathrm{force}),

and Force names a role and skips the gate. A provider may serve a request at all when

allowed(p,q)=¬(private∧¬local)∧¬(image∧¬vision). \mathrm{allowed}(p, q) = \neg(\mathrm{private} \wedge \neg\mathrm{local}) \wedge \neg(\mathrm{image} \wedge \neg\mathrm{vision}).

A role is eligible for the gate when three things hold. Vision is eligible only when the request has an image. For a private request, a role is eligible only when every provider in its chain is local. And some provider of the chain that allowed lets through has a breaker that admits a call. The second rule is stricter than the filter, and on purpose: primary is cloud-first by meaning, even though its second entry is local, so a private request is never offered primary. The filter is the second net, for the path where no one chose: a role that is reached by Force, or by failing open, still has its chain cut down by allowed. Two layers, because the first can be bypassed on purpose (a forced role) and the second cannot be skipped at all.

// allowed says whether a provider may serve a request at all: a private
// request only goes to a local provider, and a request with an image only
// to one that can see. This filter applies to every chain walk, the
// fail-open chain included, so failing open never sends private text to the
// cloud.
func allowed(p *Provider, req Request) bool {
    if req.Private && !p.Local {
        return false
    }
    if req.HasImage && !p.Vision {
        return false
    }
    return true
}

// allLocal reports a role whose every provider keeps traffic on the
// reader's machines.
func (r *Router) allLocal(role Role) bool {
    for _, name := range r.cfg.Roles[role].Chain {
        if p := r.providers[name]; p == nil || !p.Local {
            return false
        }
    }
    return true
}

// filteredChain is a role's chain as this request will walk it: the names of
// the providers `allowed` lets through, in order. Decision.Chain reports it,
// so a trace shows where a private request could go, not the whole role.
func (r *Router) filteredChain(role Role, req Request) Chain {
    out := Chain{}
    for _, p := range r.chain(role, req) {
        out = append(out, p.Name)
    }
    return out
}

// chain is a role's providers that the request allows, in order.
func (r *Router) chain(role Role, req Request) []*Provider {
    var out []*Provider
    for _, name := range r.cfg.Roles[role].Chain {
        if p := r.providers[name]; p != nil && allowed(p, req) {
            out = append(out, p)
        }
    }
    return out
}

// eligible is the roles the gate may choose among, sorted: vision only when
// the request has an image; for a private request only a role whose every
// provider is local (primary is cloud-first by meaning, whatever its
// fallback); and a role only when at least one allowed provider in its
// chain has a breaker that admits a call.
func (r *Router) eligible(req Request) []Role {
    var out []Role
    for _, role := range r.cfg.RoleNames() {
        if role == "vision" && !req.HasImage {
            continue
        }
        if req.Private && !r.allLocal(role) {
            continue
        }
        for _, p := range r.chain(role, req) {
            if p.breaker.Admits() {
                out = append(out, role)
                break
            }
        }
    }
    return out
}

The gate is asked only when two or more roles remain. One role is taken as single, with no gate call; none is a fail-open decision with ErrNoEligibleRole. (A router with PrivateSkipsGate set, which is how aecd builds its own, does not ask it of a private request either: see “Where private text goes”.) One further case is also single: an image with no text. decide refuses an empty state, and the image already says what is wanted, so the request goes to vision without calling the gate and without counting a gate error. The configuration is a file, routes.json, read by route.LoadConfig and held in the types below.

// Role is one of the registered route head's five options, in the order of
// heads.route.options in jev-lite.safetensors: primary, delegation, vision,
// aux, local. "fallback" is not a role: it is the order of a role's Chain.
type Role string

// Chain is a role's providers in fallback order.
type Chain []string

// RoleConfig is one role: its description, which the gate sends as the
// option's criteria text and which must equal the registered head's
// description byte for byte, and its Chain.
type RoleConfig struct {
    Description string `json:"description"`
    Chain       Chain  `json:"chain"`
}

// ProviderConfig is one model behind one OpenAI-compatible endpoint.
// APIKeyEnv names the variable holding the key; the value is read at start
// and never written anywhere.
type ProviderConfig struct {
    BaseURL   string `json:"base_url"`
    APIKeyEnv string `json:"api_key_env,omitempty"`
    Model     string `json:"model"`
    Local     bool   `json:"local"`
    Vision    bool   `json:"vision"`
}

// GateConfig is the routing gate. Weights is the path to jev-lite's weights
// file; Embedder the embedder server's root (http://dixie:11435, tether), the
// model name coming from the weights header (embedder.name); BudgetMS the
// time the gate may take before the request fails open (D7: 250); Disabled
// sends every request down FailOpen's chain with no gate call.
type GateConfig struct {
    Weights  string `json:"weights"`
    Embedder string `json:"embedder"`
    BudgetMS int    `json:"budget_ms"`
    Disabled bool   `json:"disabled"`
}

// Config is routes.json.
type Config struct {
    Providers map[string]ProviderConfig `json:"providers"`
    Roles     map[Role]RoleConfig       `json:"roles"`
    FailOpen  Role                      `json:"fail_open"`
    Gate      GateConfig                `json:"gate"`
}

const knownRoles = "primary, delegation, vision, aux, local"

// KnownRole reports whether a name is one of the registered route head's
// five options. Config refuses any other, whether or not the gate is enabled
// or its weights load, so a misspelt role cannot sit unnoticed behind a gate
// that always fails open.
func KnownRole(r Role) bool {
    switch r {
    case "primary", "delegation", "vision", "aux", "local":
        return true
    }
    return false
}

// noDuplicateKeys refuses a JSON object that repeats a key anywhere:
// encoding/json keeps the last silently, and a repeated provider or role
// would be a configuration the reader did not mean.
func noDuplicateKeys(raw []byte) error {
    dec := json.NewDecoder(bytes.NewReader(raw))
    var walk func() error
    walk = func() error {
        tok, err := dec.Token()
        if err != nil {
            return err
        }
        d, ok := tok.(json.Delim)
        if !ok {
            return nil
        }
        switch d {
        case '{':
            seen := map[string]bool{}
            for dec.More() {
                k, err := dec.Token()
                if err != nil {
                    return err
                }
                key, _ := k.(string)
                if seen[key] {
                    return fmt.Errorf("duplicate key %q", key)
                }
                seen[key] = true
                if err := walk(); err != nil {
                    return err
                }
            }
        case '[':
            for dec.More() {
                if err := walk(); err != nil {
                    return err
                }
            }
        }
        _, err = dec.Token() // the closing delimiter
        return err
    }
    return walk()
}

// DefaultBudgetMS is the gate's latency budget when the config gives none.
const DefaultBudgetMS = 250

// ParseConfig reads routes.json (encoding/json v1, unknown fields refused),
// fills the defaults (fail_open primary, budget_ms 250) and checks the
// references: every chain non-empty and naming configured providers, every
// role name non-empty, fail_open a configured role, and a gate with weights
// or disabled.
func ParseConfig(r io.Reader) (Config, error) {
    var cfg Config
    raw, err := io.ReadAll(io.LimitReader(r, 1<<20))
    if err != nil {
        return cfg, fmt.Errorf("routes: %w", err)
    }
    if err := noDuplicateKeys(raw); err != nil {
        return cfg, fmt.Errorf("routes: %w", err)
    }
    dec := json.NewDecoder(bytes.NewReader(raw))
    dec.DisallowUnknownFields()
    if err := dec.Decode(&cfg); err != nil {
        return cfg, fmt.Errorf("routes: %w", err)
    }
    if _, err := dec.Token(); err != io.EOF {
        return cfg, fmt.Errorf("routes: data after the config object")
    }
    if cfg.FailOpen == "" {
        cfg.FailOpen = "primary"
    }
    if cfg.Gate.BudgetMS == 0 {
        cfg.Gate.BudgetMS = DefaultBudgetMS
    }
    if len(cfg.Roles) == 0 {
        return cfg, fmt.Errorf("routes: no roles")
    }
    for role, rc := range cfg.Roles {
        if !KnownRole(role) {
            return cfg, fmt.Errorf("routes: role %q is not one of the route head's options (%s)", role, knownRoles)
        }
        if len(rc.Chain) == 0 {
            return cfg, fmt.Errorf("routes: role %q has an empty chain", role)
        }
        seen := map[string]bool{}
        for _, name := range rc.Chain {
            if _, ok := cfg.Providers[name]; !ok {
                return cfg, fmt.Errorf("routes: role %q names provider %q, which is not configured", role, name)
            }
            if seen[name] {
                return cfg, fmt.Errorf("routes: role %q lists provider %q twice", role, name)
            }
            seen[name] = true
        }
    }
    if _, ok := cfg.Roles[cfg.FailOpen]; !ok {
        return cfg, fmt.Errorf("routes: fail_open role %q is not configured", cfg.FailOpen)
    }
    for name, p := range cfg.Providers {
        if p.BaseURL == "" || p.Model == "" {
            return cfg, fmt.Errorf("routes: provider %q needs base_url and model", name)
        }
    }
    if !cfg.Gate.Disabled && cfg.Gate.Weights == "" {
        return cfg, fmt.Errorf("routes: gate.weights is required unless gate.disabled is true")
    }
    if cfg.Gate.BudgetMS < 0 {
        return cfg, fmt.Errorf("routes: gate.budget_ms must not be negative")
    }
    return cfg, nil
}

// LoadConfig is ParseConfig on a file.
func LoadConfig(path string) (Config, error) {
    f, err := os.Open(path)
    if err != nil {
        return Config{}, err
    }
    defer f.Close()
    return ParseConfig(f)
}

// RoleNames is the configured roles in sorted order.
func (c Config) RoleNames() []Role {
    out := make([]Role, 0, len(c.Roles))
    for r := range c.Roles {
        out = append(out, r)
    }
    sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
    return out
}

The lab’s file mirrors the reader’s roles with two substitutions. z.ai takes the place of the xAI model that Hermes uses, because xAI is not in the course’s provider set. z.ai serves two endpoints, a Coding Plan one (https://api.z.ai/api/coding/paas/v4, the default here) and a general pay-per-use one (https://api.z.ai/api/paas/v4); a Coding Plan key works only on the first, and AEC_ZAI_URL (or the route’s base_url) selects the other. The second substitution: straylight-35b is flagged as able to see, because straylight’s own vision aux is that model. Without the flag, an image request skipped it, and vision’s second chain entry was unreachable. The config reader refuses what could hide a mistake. It refuses a role that is not one of the head’s five options even when the gate is disabled, so a misspelt role cannot sit behind a gate that always fails open. It refuses a repeated chain entry, a duplicate JSON key and trailing JSON. And route.New refuses a role description that differs from the head’s by one byte, because the description is embedded: the gate sends aux: a small fast model for chores: titles, page summaries, extraction as the option’s text, and a trailing space produces a different vector than the one the head was trained against. Chapter 21’s exercise (c) shows the same edit failing at request time with SchemaMismatch; New catches it at start-up, and the per-request check remains for a config that bypasses New.

The gate and its budget

The question the gate asks is the registered route head over the eligible roles’ descriptions. Chapter 21 proved that a choice head’s softmax over a subset of its options is the full head’s answer conditioned on that subset, with one temperature for every subset size; this chapter relies on that and does not repeat it. What is new is that the gate’s latency TT is a random variable on the request path: one embeddings round trip, which includes the guard’s GET /v1/models (the fleet guard, below). The gate runs under a deadline bb, the budget, 250 ms by default, and two quantities say what bb trades.

The first is the probability that the gate falls open on time alone, P(T>b)P(T > b). The second is the expected time the gate costs a request, which is E[min(T,b)]E[\min(T, b)], because past bb the gate is abandoned. Chapter 27 derived the identity for a deadline: with S(t)=P(T>t)S(t) = P(T > t) the survival function of TT,

E[min(T,b)]=∫0bS(t)dt, E[\min(T, b)] = \int_0^b S(t)\,dt,

and P(the deadline fires)=S(b)P(\text{the deadline fires}) = S(b).

Two quantiles of TT bracket this without a model of its shape. SS is non-increasing. Below the median mm, S(t)≥12S(t) \ge \tfrac12, so E[min(T,b)]≥12min(m,b)E[\min(T, b)] \ge \tfrac12 \min(m, b). Above the 90th percentile qq, S(t)≤0.1S(t) \le 0.1, and below it S(t)≤1S(t) \le 1, so E[min(T,b)]≤q+0.1(b−q)E[\min(T, b)] \le q + 0.1\,(b - q) for b≥qb \ge q. The tail beyond qq can cost at most a tenth of the way to bb. A measurement made for this chapter timed TT for a batch of 1, 2 and 6 texts, the whole guarded call, from straylight to the embedder on dixie, 20 repeats after one warm-up (2026-10-02 01:23 PDT, llama.cpp b10964-b29c606, on straylight as the client, dixie as the host):

texts in the batch median (ms) 90th percentile (ms) E[min(T,250)]E[\min(T, 250)] lies in (ms)
1 30.26 66.78 15.1 to 85.1
2 46.45 80.59 23.2 to 97.5
6 94.15 115.16 47.1 to 128.6

The bounds are computed from the table’s two columns, not measured. The guard’s GET /v1/models alone is 7.72 ms at the median and 11.3 ms at the 90th percentile, inside every row, and it is the price of the fleet rule, paid on every request. The 90th percentile is taken as the lower rank, s[int(0.9(n-1))] of the sorted samples (the same rule embed_latency.py uses), which for 20 samples is index 17, the 18th smallest; so the table is a sample of 20 from one run and not a distribution. The rule set before measuring was to keep 250 ms if the six-text p90 came in under 125 ms. It did, by 9.84 ms, so the budget stays. The six-text row is the cold call. The gate embeds one text for the request plus one for each eligible option, 1+N1 + N texts, and the option texts never change, so the router keeps them: option vectors are cached by the sha256 of the text, and in steady state a gate call embeds one text. That row of the table is the first.

A second sample is the A/B below. aec-decide there has no cache, so every request embeds all the texts of the golden request, and the 63 requests after the first took 92.8 ms at the median, 124.0 ms at the 90th percentile and 143.1 ms at the maximum (straylight to dixie, 2026-10-02 04:31 PDT). None came near 250 ms.

If E[min(T,b)]E[\min(T, b)] is already between 15 and 130 ms, what is the budget for? For the tail. Without it, a hung embedder holds the request for the embedder client’s own timeout (30 s) and a slow one holds it for however long it takes; with it the gate adds at most bb to a request before the fallback chain starts, provided the embedder honours its context as HTTPEmbedder does; one that does not holds the request until it returns, and only then is its answer discarded. This is Dean and Barroso’s use of a deadline against a latency tail (“The Tail at Scale”, cited below). The budget buys nothing in accuracy: past bb the gate’s answer, if it arrives, is discarded. An embedder that ignores its context and answers at 800 ms, against a budget of 20 ms, yields ErrBudget, not a decision, and it is not cached either. Chapter 26 bounded a run by the sum of its providers’ budgets and said a router that falls back along a chain adds the budget of every provider it tries. This chapter adds one more term, bb, once per request.

The gate fails open on every error. The kinds are the six of chapter 21 and three of the router’s own:

kind (the kind label of aec_route_gate_errors_total) when
BadRequest the request the gate built is malformed: a bug in the gate
SchemaMismatch a role’s description or the instructions differ from the registered head’s
EmbedderUnavailable the embedder’s model is not loaded, the network failed, or the answer did not arrive
EmbedderMismatch the probe or card check failed, or the vectors have the wrong width
WeightsInvalid the weights file did not load; every request then fails open with that error
Uncalibrated the answer is not from a calibrated head; RequireCalibrated is the gate’s first act on an answer, and it is unreachable for the registered head by construction, but kept
budget the budget expired, or a late answer was discarded
unchecked no embedder check has run yet; after a failed check the gate returns that check’s own error, counted under its own kind (EmbedderMismatch or EmbedderUnavailable)
other the gate panicked; the panic is recovered inside the gate and nowhere else

Two of these rules are about trust. The gate is not asked until CheckEmbedder has passed once: chapter 21 ties the embedder to the weights by eight probe vectors and by the example scores of the embedding model’s card, and a router that asked the gate before that check would be routing with vectors from an embedder it could not name. After a later failing check, the gate shuts again. And the recover is inside gate(). decide parses weights and wire data that are not trusted, and a parser that reads untrusted bytes can panic on an input its tests never met; a bug there must cost a fail-open decision and not the daemon. A panic in a provider’s client is not covered, because that is the client’s bug.

// Route chooses a role. A forced role is taken as asked. With the gate
// disabled, every request takes the fail-open role. Otherwise the eligible
// roles are computed: none is fail_open (ErrNoEligibleRole), one is single
// with no gate call, two or more on a private request of a router with
// PrivateSkipsGate (aecd's) take the role named local, else the fail-open role,
// else the first eligible one, with no gate call (source private), and two or more otherwise are put to the
// registered route head over exactly those options, within the latency budget;
// any error kind, the budget expiring, or an uncalibrated answer fails open to
// cfg.FailOpen.
func (r *Router) Route(ctx context.Context, req Request) Decision {
    d := r.route(ctx, req)
    d.Chain = r.filteredChain(d.Role, req)
    r.metrics.Decisions.Inc(string(d.Role), d.Source)
    return d
}

func (r *Router) route(ctx context.Context, req Request) Decision {
    if req.Force != "" {
        if _, ok := r.cfg.Roles[req.Force]; !ok {
            return Decision{Role: r.cfg.FailOpen, Source: "fail_open", Err: fmt.Errorf("%w: %q", ErrUnknownRole, req.Force)}
        }
        return Decision{Role: req.Force, Source: "forced"}
    }
    if r.cfg.Gate.Disabled {
        return Decision{Role: r.cfg.FailOpen, Source: "disabled"}
    }
    roles := r.eligible(req)
    if req.HasImage && strings.TrimSpace(req.Text) == "" && containsRole(roles, "vision") {
        // An image with no text gives the gate nothing to read (decide refuses
        // an empty state), and the image already says what is wanted: vision,
        // with no gate call and no gate error counted.
        return Decision{Role: "vision", Source: "single"}
    }
    switch len(roles) {
    case 0:
        return Decision{Role: r.cfg.FailOpen, Source: "fail_open", Err: ErrNoEligibleRole}
    case 1:
        return Decision{Role: roles[0], Source: "single"}
    }
    if req.Private && r.PrivateSkipsGate {
        // A private request is not put to the gate (ruling 7f-E18): the gate's
        // embedder is sent the request text, and nothing but the operator's
        // routes file says that embedder is on the reader's machines. Every
        // eligible role is all-local, so the request takes one of them without
        // asking, in this order: the role named local when it is eligible (it
        // is the role a routes file describes for a request that must not leave
        // the reader's machines), else the fail-open role when it is eligible,
        // else the first in the sorted role names (ruling FU-5).
        if containsRole(roles, "local") {
            return Decision{Role: "local", Source: "private"}
        }
        if containsRole(roles, r.cfg.FailOpen) {
            return Decision{Role: r.cfg.FailOpen, Source: "private"}
        }
        return Decision{Role: roles[0], Source: "private"}
    }
    start := r.Clock()
    d, err := r.gate(ctx, req, roles)
    r.metrics.GateSeconds.Observe(r.Clock().Sub(start).Seconds())
    if err != nil {
        r.metrics.GateErrors.Inc(kindLabel(err))
        return Decision{Role: r.cfg.FailOpen, Source: "fail_open", Err: err}
    }
    return d
}

// gate asks the route head over the eligible roles.
func (r *Router) gate(ctx context.Context, req Request, roles []Role) (dec Decision, err error) {
    // decide parses untrusted weights and wire data; a bug there must cost a
    // fail-open decision, not the daemon. Only the gate is covered: a panic in
    // a provider's client is that client's bug.
    defer func() {
        if v := recover(); v != nil {
            dec, err = Decision{}, fmt.Errorf("route: the gate panicked: %v", v)
        }
    }()
    if r.model == nil {
        return Decision{}, r.loadErr
    }
    r.mu.Lock()
    passed, checkErr := r.passed, r.checkErr
    r.mu.Unlock()
    if !passed { // until CheckEmbedder passes, the gate is not asked
        if checkErr != nil {
            return Decision{}, checkErr
        }
        return Decision{}, ErrNotChecked
    }
    criteria := make(map[string]any, len(roles))
    for _, role := range roles {
        criteria[string(role)] = r.cfg.Roles[role].Description
    }
    input, err := canon.JSON(map[string]any{
        "state": req.Text,
        "questions": map[string]any{routeQID: map[string]any{
            "type": "choice", "instructions": r.question, "criteria": criteria}},
    })
    if err != nil {
        return Decision{}, err
    }
    budget := time.Duration(r.cfg.Gate.BudgetMS) * time.Millisecond
    gctx, cancel := context.WithTimeout(ctx, budget)
    defer cancel()
    start := r.Clock()
    resp, err := r.model.Decide(gctx, &cachedEmbedder{r}, input, "")
    if err != nil {
        if gctx.Err() != nil && ctx.Err() == nil {
            // Decide failed because the budget expired.
            return Decision{}, fmt.Errorf("%w after %s: %v", ErrBudget, budget, err)
        }
        return Decision{}, err
    }
    if r.Clock().Sub(start) > budget && ctx.Err() == nil {
        // An embedder that ignores its context answered after the budget: a
        // late answer is not used. This is read from the elapsed time, not
        // from the context's error, which a deadline firing just after a
        // timely answer would also set.
        return Decision{}, fmt.Errorf("%w after %s: the answer came in %s", ErrBudget, budget, r.Clock().Sub(start))
    }
    if err := decide.RequireCalibrated(resp); err != nil {
        return Decision{}, err
    }
    a := resp.Answers[routeQID]
    return Decision{Role: Role(a.Choice), Source: "gate", Calibrated: true, Probabilities: a.Probabilities}, nil
}

func containsRole(roles []Role, want Role) bool {
    for _, r := range roles {
        if r == want {
            return true
        }
    }
    return false
}

// kindLabel is the metric label for a gate error: the decide kind, budget,
// or other.
func kindLabel(err error) string {
    if errors.Is(err, ErrBudget) {
        return "budget"
    }
    if errors.Is(err, ErrNotChecked) {
        return "unchecked"
    }
    var de *decide.Error
    if errors.As(err, &de) {
        return de.Kind.String()
    }
    return "other"
}

The embedding cache is small and has one subtle rule. cachedEmbedder serves the option texts from the cache and sends everything else, the request’s text and every miss, in one batch. Only the texts of the configured roles are ever cached, so the request’s text, which may be private, is never written anywhere, and nothing is written to disk. The cache holds at most 64 vectors, is dropped when the weights’ version changes, and is dropped when an embedder check fails, because the embedder may have changed under it. The subtle rule is a generation counter. A gate call that is in flight when a check fails would, on returning, store its vectors from the embedder the check had just condemned. So every clear bumps a generation, a call stores only if the generation is unchanged since its own lookup, and a call that missed its budget stores nothing. The cache is also the reason the first row of the table above is the steady state.

// cachedEmbedder is the router's embedder as decide sees it: option texts
// from the cache, everything else (and every miss) from the router's
// embedder in one batch.
type cachedEmbedder struct{ r *Router }

func (ce *cachedEmbedder) Embed(ctx context.Context, texts []string) ([][]float32, error) {
    r, c := ce.r, ce.r.cache
    if c == nil {
        return r.embedder.Embed(ctx, texts)
    }
    version, dim := r.model.Version, r.model.Meta.Embedder.Dim
    keys := make([][32]byte, len(texts))
    out := make([][]float32, len(texts))
    var miss []string
    var missAt []int
    c.mu.Lock()
    if c.version != version {
        c.version, c.vecs, c.gen = version, map[[32]byte][]float32{}, c.gen+1
    }
    gen := c.gen
    for i, t := range texts {
        keys[i] = sha256.Sum256([]byte(t))
        if v, ok := c.vecs[keys[i]]; ok {
            out[i] = v
            continue
        }
        miss, missAt = append(miss, t), append(missAt, i)
    }
    c.mu.Unlock()
    if len(miss) == 0 {
        return out, nil
    }
    got, err := r.embedder.Embed(ctx, miss)
    if err != nil {
        return nil, err
    }
    if len(got) != len(miss) {
        return got, nil // decide reports the mismatch for the whole batch
    }
    if ctx.Err() != nil {
        return out, nil // an answer that missed its budget is used by no one and remembered by no one
    }
    c.mu.Lock()
    defer c.mu.Unlock()
    for j, i := range missAt {
        out[i] = got[j]
        if c.cacheOK[keys[i]] && c.gen == gen && len(c.vecs) < c.max && usable(got[j], dim) {
            c.vecs[keys[i]] = append([]float32(nil), got[j]...)
        }
    }
    return out, nil
}

// usable: only a vector of the right width with finite values is cached, so
// a bad answer is not remembered.
func usable(v []float32, dim int) bool {
    if len(v) != dim {
        return false
    }
    for _, x := range v {
        if f := float64(x); math.IsNaN(f) || math.IsInf(f, 0) {
            return false
        }
    }
    return true
}

Where private text goes

A private request means: the reader has said this text must not leave his machines. Three paths carry it. To a model: only a Local provider receives it, by the filter above on every walk, the fail-open walk included. A private request that fails open to primary therefore skips z.ai and tries the next entry, straylight-35b; if no local provider admits it, the answer is ErrNoProvider, not the cloud. The test for this, TestPrivateTextNeverReachesACloudProvider, plants a sentinel in the text and sends it down nine paths (the gate, a forced role, a forced role that does not exist, a disabled gate, a gate error, a gate budget, an unchecked gate, a private image and the cloud-first fail-open role), each through Complete and Stream, then again with every local breaker open, and requires zero calls to the cloud provider’s client. To the embedder: the router as the lab specifies it sends the request’s text to the gate’s embedder whenever two or more roles are eligible, private text included, because the embedder is how the gate reads it. That is a design consequence, and it is why New refuses a gate embedder whose host is not straylight, dixie (with their .ts.net forms), localhost or loopback, whenever the config names one, also when the caller passes an Embedder of its own: private text goes to the reader’s own embedder on dixie, through tether (TestTheGateEmbedderHostIsCheckedWhateverTheCaller shows the host check applying whether or not the caller passes an Embedder). aecd builds its router with none, or, when chapter 48’s audit log is on, with an auditing wrapper around the configured embedder, so the check applies at every start of the daemon. But the check proves a name and not a machine, and that the name is the reader’s is the routes file’s word, as local: true is, with no flag that says so. aecd therefore does not rest a private request on it. It sets Router.PrivateSkipsGate, and a private request with two or more eligible roles then takes the role named local when it is eligible, else the fail-open role when that is eligible, else the first eligible role by name, with source private: every eligible role is all-local, the gate is not asked and its embedder is sent nothing. TestAPrivateRequestIsNotPutToTheGateAndItsEmbedderIsSentNothing shows it, with the same request not private as one control and the lab’s router, which leaves the option false and gates a private request as the exercises below describe, as the other; TestPrivacyGateIsNotConsultedOnAPrivateRequest shows that the daemon’s router is built that way. The cost is that a private turn never gets the gate’s choice among local roles: it gets local, which the routes file describes as the role for a request that must not leave the reader’s machines, or the fail-open role, or the first by name. Whether the hosts are really his is an assertion the config makes, and there is one residual risk in how it makes it. The committed configs name hosts by their short MagicDNS names, dixie and straylight, and New accepts the bare name. If Tailscale is down, a short name can resolve through the local network’s search domain to a different host, and the guard’s check and the request would go to whatever answers there. Nothing in New can see that; full MagicDNS names (dixie.<tailnet>.ts.net) close it, at the price of a config tied to one tailnet. The risk is documented, not removed. To the cache: never; the request’s own text is not cached. All of this is a property of one request. That the next request of the same session is private too, that a private turn’s text in memory is not recalled by a turn that is not private, and which direct clients the daemon builds outside this router, are the daemon’s rules (chapters 40 and 45), and the router cannot see them.

The fleet guard

A local provider’s HTTP client has a different transport, and the fleet rule it enforces is chapter 26’s (a check of GET /v1/models for loaded immediately before every request that names a model, then ?autoload=false; chapter 24 states it for the client). What this chapter adds is the documentation at llama.cpp b29c606: the server’s README documents POST /v1/embeddings (line 1504 of tools/server/README.md), the per-request ?autoload=true|false (line 1795) and the status.value states of /v1/models (lines 1855 to 1866), which include loaded and sleeping. The source lines that make a request wake a sleeping model are the ones chapter 21 reads.

route.Guard is that rule as an http.RoundTripper, wrapped around the transport of a local provider’s client by route.Clients, with no switch to turn it off. Chapter 24’s client then needs no knowledge of the fleet. Four properties of the guard are worth stating. It reads the whole request body, up to 64 MiB, to find the model, and forwards exactly the bytes it read. It never forwards a shortened body: a cap that truncated the read but kept the original Content-Length would fail every large screenshot, and each failure would count against the provider’s breaker. A body over the cap is refused locally, and counts against no one. A POST to a model endpoint that names no model is refused, because a llama.cpp router might serve it with a default model it loads. The refusals, ErrNotLoaded, ErrBodyTooLarge and ErrNoModel, implement Permanent() bool, which chapter 24’s retry loop honours: the same request would be refused again, so it is attempted once, not three times with backoff over a body of up to 64 MiB. And the transport ignores the environment’s proxy settings, so HTTP_PROXY cannot send fleet traffic elsewhere.

// Guard is the fleet guard as an http.RoundTripper, for a local provider on
// one of the reader's llama.cpp routers: immediately before every request
// that names a model it reads GET /v1/models on the same server, refuses
// unless that model's status.value is exactly "loaded" (a sleeping model is
// not loaded, and a request would wake it), and sends the request with
// autoload=false. It wraps the transport of a provider's http.Client, so
// chapter 24's client needs no knowledge of the fleet. Cloud providers do
// not use it.
type Guard struct {
    Next http.RoundTripper // nil: http.DefaultTransport
    Max  int64             // the body cap; 0 means MaxBody
}

// ErrNotLoaded is the refusal.
type ErrNotLoaded struct {
    Model, Status string
}

func (e *ErrNotLoaded) Error() string {
    return fmt.Sprintf("fleet guard: %s is %q, not loaded; this client never loads a model", e.Model, e.Status)
}

// fleetTransport is the default transport without the environment's proxy
// settings, so fleet traffic cannot be redirected by HTTP_PROXY (lessons.md:
// the same trap as urllib's).
var fleetTransport = func() *http.Transport {
    t := http.DefaultTransport.(*http.Transport).Clone()
    t.Proxy = nil
    return t
}()

func (g *Guard) next() http.RoundTripper {
    if g.Next != nil {
        return g.Next
    }
    return fleetTransport
}

// MaxBody is the largest request body Guard will read to find the model: a
// screenshot as base64 is a few MiB, and a body is never forwarded shortened.
const MaxBody = 64 << 20

// ErrBodyTooLarge is a request body over MaxBody. Guard refuses it locally:
// the request is at fault, not the provider.
type ErrBodyTooLarge struct{ Limit int64 }

func (e *ErrBodyTooLarge) Error() string {
    return fmt.Sprintf("fleet guard: request body over %d bytes; refused locally, nothing sent", e.Limit)
}

// ErrNoModel is a POST to a model endpoint whose body and query name no
// model: a llama.cpp router might serve it with a default it loads, which
// this client never allows.
type ErrNoModel struct{ Path string }

func (e *ErrNoModel) Error() string {
    return fmt.Sprintf("fleet guard: POST %s names no model; refused locally, nothing sent", e.Path)
}

// modelOf reads the model a request names: the body's "model" for a POST,
// else the model query parameter. It consumes the whole body (up to MaxBody;
// more is ErrBodyTooLarge) and replaces req.Body, GetBody and ContentLength
// with the exact bytes, so what is forwarded is what was read.
func modelOf(req *http.Request, max int64) (string, error) {
    if req.Body != nil && req.Body != http.NoBody {
        raw, err := io.ReadAll(io.LimitReader(req.Body, max+1))
        if err != nil {
            return "", err
        }
        req.Body.Close()
        if int64(len(raw)) > max {
            return "", &ErrBodyTooLarge{Limit: max}
        }
        req.Body = io.NopCloser(bytes.NewReader(raw))
        req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(raw)), nil }
        req.ContentLength = int64(len(raw))
        var peek struct {
            Model string `json:"model"`
        }
        if json.Unmarshal(raw, &peek) == nil && peek.Model != "" {
            return peek.Model, nil
        }
    }
    return req.URL.Query().Get("model"), nil
}

func (g *Guard) RoundTrip(req *http.Request) (*http.Response, error) {
    max := g.Max
    if max <= 0 {
        max = MaxBody
    }
    model, err := modelOf(req, max)
    if err != nil {
        return nil, err
    }
    if model == "" {
        if req.Method == http.MethodPost && (strings.HasSuffix(req.URL.Path, "/chat/completions") || strings.HasSuffix(req.URL.Path, "/embeddings") || strings.HasSuffix(req.URL.Path, "/completions")) {
            return nil, &ErrNoModel{Path: req.URL.Path}
        }
        return g.next().RoundTrip(req) // names no model: /health, /v1/models, /props
    }
    base := *req.URL
    base.Path = "/v1/models"
    base.RawQuery, base.Fragment = "", ""
    if i := strings.Index(req.URL.Path, "/v1/"); i >= 0 {
        base.Path = req.URL.Path[:i] + "/v1/models"
    }
    lreq, err := http.NewRequestWithContext(req.Context(), http.MethodGet, base.String(), nil)
    if err != nil {
        return nil, err
    }
    lresp, err := g.next().RoundTrip(lreq)
    if err != nil {
        return nil, fmt.Errorf("fleet guard: %w", err)
    }
    defer lresp.Body.Close()
    if lresp.StatusCode != http.StatusOK {
        return nil, fmt.Errorf("fleet guard: GET /v1/models: %s", lresp.Status)
    }
    var list struct {
        Data []struct {
            ID     string `json:"id"`
            Status struct {
                Value string `json:"value"`
            } `json:"status"`
        } `json:"data"`
    }
    if err := json.NewDecoder(io.LimitReader(lresp.Body, 1<<20)).Decode(&list); err != nil {
        return nil, fmt.Errorf("fleet guard: %w", err)
    }
    status := ""
    for _, m := range list.Data {
        if m.ID == model {
            status = m.Status.Value
        }
    }
    if status != "loaded" {
        return nil, &ErrNotLoaded{Model: model, Status: status}
    }
    q, _ := url.ParseQuery(req.URL.RawQuery)
    q.Set("autoload", "false")
    req2 := req.Clone(req.Context())
    req2.URL.RawQuery = q.Encode()
    return g.next().RoundTrip(req2)
}

route.Clients builds an llm.Provider for every configured provider and returns (map, error). For a provider whose config names an api_key_env, it refuses to build a client when that variable is unset or empty, naming the variable and never its value: a keyless client would send no credential and receive a 401 from z.ai on every call. The provider named zai takes its base URL from AEC_ZAI_URL when that variable is set (a proxy, or a loopback server in a test) and from the config otherwise. A live run with the lab’s config therefore needs ZAI_API_KEY set, or a config without z.ai.

// New builds a Router from a parsed config and the clients for its providers
// (every configured provider needs one). With a gate, it loads the weights:
// a file that fails to load does not stop the router (the gate then fails
// open on every request with that error, as the design says), but a loaded
// head is checked against the config at once: every role must be one of the
// head's options and every description must equal the head's byte for byte
// (D13), else New refuses. e nil means the fleet embedder at
// cfg.Gate.Embedder, guarded, named by the weights header. New does not
// call the embedder: Check or Run does.
func New(cfg Config, clients map[string]llm.Client, e decide.Embedder, reg *obs.Registry) (*Router, error) {
    r := &Router{cfg: cfg, providers: map[string]*Provider{}, embedder: e, Clock: time.Now}
    if reg == nil {
        reg = obs.NewRegistry()
    }
    r.metrics = NewMetrics(reg)
    for name, pc := range cfg.Providers {
        c, ok := clients[name]
        if !ok || c == nil {
            return nil, fmt.Errorf("route: provider %q has no client", name)
        }
        r.providers[name] = &Provider{Name: name, Client: c, Model: pc.Model, Local: pc.Local, Vision: pc.Vision,
            breaker: &Breaker{Clock: func() time.Time { return r.Clock() }}}
        r.metrics.BreakerOpen.Set(0, name)
    }
    if cfg.Gate.Disabled {
        return r, nil
    }
    if e == nil || cfg.Gate.Embedder != "" {
        if err := fleetHost(cfg.Gate.Embedder); err != nil {
            return nil, fmt.Errorf("route: gate.embedder: %w", err)
        }
    }
    m, err := decide.Load(cfg.Gate.Weights)
    if err != nil {
        r.loadErr = err
        return r, nil
    }
    head := m.Meta.Heads[routeQID]
    if head == nil || head.Type != "choice" {
        return nil, fmt.Errorf("route: %s has no registered choice head %q", cfg.Gate.Weights, routeQID)
    }
    for _, role := range cfg.RoleNames() {
        want, ok := decide.Description(head, string(role))
        if !ok {
            return nil, fmt.Errorf("route: role %q is not an option of the registered %s head (%s)", role, routeQID, strings.Join(head.Options, ", "))
        }
        if got := cfg.Roles[role].Description; got != want {
            return nil, fmt.Errorf("route: role %q's description differs from the registered head's:\n config %q\n head   %q", role, got, want)
        }
    }
    r.model, r.question = m, head.Instructions
    r.cache = newOptionCache(cfg, maxCacheEntries)
    if r.embedder == nil {
        he, err := decide.NewHTTPEmbedder(m, cfg.Gate.Embedder, nil)
        if err != nil { // a header that names no embedder: the gate fails open with it
            r.model, r.loadErr = nil, err
            return r, nil
        }
        r.embedder = he
    }
    return r, nil
}

// Clients builds an llm.Provider for every configured provider, reading each
// key from the named environment variable (keys are held in memory only). A
// local provider's client goes through Guard: the fleet rule holds for every
// request aecd sends, with no switch. The provider named zai takes its base
// URL from AEC_ZAI_URL when that is set, else from the config.
func Clients(cfg Config) (map[string]llm.Client, error) {
    return ClientsWith(cfg, os.LookupEnv)
}

// ClientsWith is Clients with the variable lookup given: chapter 48's
// credential broker hands the keys it read at start, so a key is read once
// and the daemon can say which variables it holds. Everything else is
// Clients': the z.ai URL override, the guard on a local provider, and the
// refusal naming the variable and never its value.
func ClientsWith(cfg Config, lookup func(string) (string, bool)) (map[string]llm.Client, error) {
    out := make(map[string]llm.Client, len(cfg.Providers))
    for name, pc := range cfg.Providers {
        p := &llm.Provider{Name: name, BaseURL: pc.BaseURL}
        if name == "zai" {
            // AEC_ZAI_URL overrides the z.ai base URL, as the doctor and the
            // capture tool read it: a proxy, or a loopback server in a test.
            if u := os.Getenv("AEC_ZAI_URL"); u != "" {
                p.BaseURL = u
            }
        }
        if pc.APIKeyEnv != "" {
            // A key the config names but the environment lacks would send no
            // credential and fail every call with a 401: refuse at start-up,
            // naming the variable and never its value.
            key, ok := lookup(pc.APIKeyEnv)
            if !ok || key == "" {
                return nil, fmt.Errorf("route: provider %q: api_key_env %s is not set", name, pc.APIKeyEnv)
            }
            p.APIKey = key
        }
        if pc.Local {
            p.HTTP = &http.Client{Transport: &Guard{}}
        }
        out[name] = p
    }
    return out, nil
}

The chain and the breaker

Complete and Stream walk the chosen role’s chain: the first allowed provider whose breaker admits the call gets it, with call.Model set to that provider’s model name. What the walk does on an error depends on whose fault the error is.

error whose fault the walk
transport error, timeout, a client-side deadline, 408, 504 and every other 5xx, 429 the provider’s advance, count against its breaker
401 the provider’s: no change to the request cures a missing or expired key, only another provider advance, count
a 400 whose message begins model not found, model is not loaded or model does not fit the memory budget the provider’s: chapter 22’s router refusing this model; the request is fine advance, count
a 3xx, or a 200 whose body is an error envelope the provider’s: chapter 24’s client refuses redirects and does not accept an error body as a completion advance, count
ErrNotLoaded from the guard the provider’s (the model is not there), labelled not_loaded advance, count
any other 4xx (403 included, which some providers use for a policy specific to the request) the request’s return at once; the provider answered, so the breaker records a success
the guard’s ErrBodyTooLarge or ErrNoModel the request’s, refused before it left return at once, release the probe slot, count nothing
the Anthropic adapter’s EncodeError neither: the adapter could not express the history and sent nothing advance, count nothing
a cancelled context the caller’s return at once, release the probe slot
an error after the first streamed byte the consumer’s (chapter 24’s rule) not seen by the walk

The three permanent 400s are text, not codes, in pool.go of chapter 22’s router (lines 246, 274, 399 and 402 build them), so the match is by prefix: the wire message names the model and, for the budget refusal, the byte counts. The row for the Anthropic adapter is the carry from chapters 24 and 25: if a chain fails over mid-session to the Anthropic adapter and the history holds a call that chapter 25 rejected, the adapter’s encoder refuses the whole request. Nothing was sent, so nothing is the provider’s fault; the walk advances and counts nothing against it, and with nothing left it returns ErrNoProvider wrapping the encode error. A request fault that returns at once still calls Success() on the breaker, which resets the count and closes a half-open breaker: the provider answered. That is a choice, recorded in DECISIONS.md.

// permanentRefusals are aec-router's three 400 messages (pool.go): the
// request is fine, this router cannot serve this model, so another provider
// may. The wire text is longer than the constant (it names the model and
// the budget), hence the prefix match.
var permanentRefusals = []string{"model not found", "model is not loaded", "model does not fit the memory budget"}

// unsent reports an error from an adapter that refused the request before
// sending any of it (the Anthropic adapter's *EncodeError).
func unsent(err error) bool {
    var u interface{ Unsent() bool }
    return errors.As(err, &u) && u.Unsent()
}

// providerFault classifies an error from a client: true when the provider
// is at fault and the chain should advance; false when the request is at
// fault and must be returned at once. A cancelled context is neither: the
// caller gave up (walk handles it first). Provider faults: a transport
// error or timeout (408, 504 and a client-side deadline included), any 5xx,
// 429, one of the router's permanent refusals (a 400), a redirect (llm
// refuses to follow one, so a 3xx means the endpoint is misconfigured) and
// a 200 whose body is an error envelope (the answer is not a completion).
// A 401 is a provider fault too: no change to the request cures it, only
// another provider (a missing or expired key), so the chain advances and
// the breaker counts it. Request faults: every other 4xx, 403 included
// (some providers use it for a policy specific to the request).
func providerFault(err error) (fault bool, code string) {
    var se *llm.StatusError
    if errors.As(err, &se) {
        code = strconv.Itoa(se.Status)
        switch {
        case se.Status >= 500 || se.Status == 429 || se.Status == 408 || se.Status == 401:
            return true, code
        case se.Status < 400:
            if se.Status == 200 {
                code = "200_error"
            }
            return true, code
        case se.Status == 400:
            for _, p := range permanentRefusals {
                if strings.HasPrefix(se.Message, p) {
                    return true, code
                }
            }
        }
        return false, code
    }
    var nl *ErrNotLoaded
    if errors.As(err, &nl) {
        return true, "not_loaded"
    }
    return true, "transport"
}

// localRefusal reports an error from this package's own transport: the
// request was refused before it left (Guard: too large, or naming no model).
func localRefusal(err error) bool {
    var big *ErrBodyTooLarge
    var nom *ErrNoModel
    return errors.As(err, &big) || errors.As(err, &nom)
}

// setGauge sets aec_breaker_open from the breaker's state after an outcome.
func (r *Router) setGauge(p *Provider) {
    v := 0.0
    if p.breaker.State() != "closed" {
        v = 1
    }
    r.metrics.BreakerOpen.Set(v, p.Name)
}

// errNoResponse is a client that returned neither a response nor an error:
// a provider fault, not a panic.
var errNoResponse = errors.New("route: the provider returned neither a response nor an error")

// Complete walks the decision's chain: the first allowed provider whose
// breaker admits the call gets it, with call.Model set to its model; a
// provider fault advances to the next; a request fault returns at once;
// every provider exhausted is ErrNoProvider (wrapping the last fault).
func (r *Router) Complete(ctx context.Context, req Request, call llm.Request) (*llm.Response, Decision, error) {
    d := r.Route(ctx, req)
    resp, err := walk(ctx, r, &d, req, func(p *Provider) (any, error) {
        call.Model = p.Model
        resp, err := p.Client.Complete(ctx, call)
        if err == nil && resp == nil {
            err = errNoResponse
        }
        return resp, err
    })
    if err != nil {
        return nil, d, err
    }
    return resp.(*llm.Response), d, nil
}

// Stream is Complete with llm.Stream. An error after the first streamed byte
// belongs to the consumer and never advances the chain: the stream has been
// handed over.
func (r *Router) Stream(ctx context.Context, req Request, call llm.Request) (llm.Stream, Decision, error) {
    d := r.Route(ctx, req)
    s, err := walk(ctx, r, &d, req, func(p *Provider) (any, error) {
        call.Model = p.Model
        s, err := p.Client.Stream(ctx, call)
        if err == nil && s == nil {
            err = errNoResponse
        }
        return s, err
    })
    if err != nil {
        return nil, d, err
    }
    return s.(llm.Stream), d, nil
}

// walk tries the decision's chain and records the provider that answered in
// d.Provider (the loop names its model_call span by it).
func walk(ctx context.Context, r *Router, d *Decision, req Request, send func(p *Provider) (any, error)) (any, error) {
    var last error
    for _, p := range r.chain(d.Role, req) {
        tk, admitted := p.breaker.Take()
        if !admitted {
            r.metrics.ProviderRequests.Inc(p.Name, "skipped")
            continue
        }
        out, err := send(p)
        if err == nil {
            d.Provider, d.Model = p.Name, p.Model
            p.breaker.Success()
            r.setGauge(p)
            r.metrics.ProviderRequests.Inc(p.Name, "200")
            return out, nil
        }
        if ctx.Err() != nil {
            p.breaker.Release(tk) // the caller gave up; the provider's record is unchanged
            r.setGauge(p)
            return nil, ctx.Err()
        }
        if unsent(err) {
            // The adapter refused the request before sending it (Anthropic's
            // encode, on a history it cannot express): the provider was not
            // tried, so nothing is counted against it; the next provider may
            // take the request.
            p.breaker.Release(tk)
            r.setGauge(p)
            r.metrics.ProviderRequests.Inc(p.Name, "unsent")
            last = err
            continue
        }
        if localRefusal(err) {
            // This client refused the request itself (a body over the cap, a
            // request naming no model): no provider saw it, none is at fault,
            // and no other provider would take it either.
            p.breaker.Release(tk)
            r.setGauge(p)
            r.metrics.ProviderRequests.Inc(p.Name, "refused")
            return nil, err
        }
        fault, code := providerFault(err)
        r.metrics.ProviderRequests.Inc(p.Name, code)
        if !fault {
            p.breaker.Success() // the provider answered; the request was wrong
            r.setGauge(p)
            return nil, err
        }
        p.breaker.Fail(tk)
        r.setGauge(p)
        last = err
    }
    if last != nil {
        return nil, fmt.Errorf("%w: %v", ErrNoProvider, last)
    }
    return nil, ErrNoProvider
}

The breaker has three states and four transitions.

  • Closed admits every call and counts consecutive provider faults. After FF of them (5 by default) it opens.
  • Open admits nothing for the cooldown cc (30 s).
  • After cc it is half-open, and admits exactly one call, the probe. The probe’s success closes the breaker; its failure reopens it for another cc.
  • A success in any state closes it and resets the count.

The probe is a ticket. Take returns it to the one call that was granted the half-open slot, and only that ticket’s Fail or Release touches the slot. The reason is that LLM calls are long, and routinely outlive a 30 s cooldown (chapter 24’s retries alone allow a wait of up to MaxWait, also 30 s). A call admitted while the breaker was closed can finish while a probe is in flight. If its failure were allowed to reopen the breaker, it would restart the cooldown on a stale outcome; if its Release freed the slot, a second probe would run beside the first, which is the burst the half-open state exists to prevent. With a ticket, a late failure from an ordinary call while the breaker is open is ignored, and a late call that does not hold the probe cannot free it. A probe slot that is taken and then abandoned (the caller cancelled, or the adapter refused to send) is given back with Release, or the provider would be refused forever.

// Breaker is one provider's circuit breaker. Closed, it admits every call
// and counts consecutive faults; after Failures of them it opens and admits
// nothing for Cooldown; then it is half-open and admits exactly one probe,
// closing on the probe's success and reopening (for another Cooldown) on its
// failure. A success in any state closes it. Defaults: 5 faults, 30 s.
//
// The probe is a ticket: Take returns it to the one call that was granted
// the half-open slot, and only that ticket's Fail or Release touches the
// slot. A call admitted before the breaker opened, finishing while a probe
// is in flight, can neither free the slot nor restart the cooldown.
type Breaker struct {
    Failures int
    Cooldown time.Duration
    Clock    func() time.Time

    mu          sync.Mutex
    consecutive int
    openedAt    time.Time
    open        bool
    probeID     uint64 // the in-flight probe's ticket, 0 when none
    lastID      uint64
}

// Ticket is what Take returns: the proof that a call holds the probe slot.
// The zero Ticket is an ordinary call.
type Ticket struct{ probeID uint64 }

// Probe reports whether the ticket holds the half-open slot.
func (t Ticket) Probe() bool { return t.probeID != 0 }

const (
    DefaultFailures = 5
    DefaultCooldown = 30 * time.Second
)

func (b *Breaker) now() time.Time {
    if b.Clock != nil {
        return b.Clock()
    }
    return time.Now()
}

func (b *Breaker) failures() int {
    if b.Failures > 0 {
        return b.Failures
    }
    return DefaultFailures
}

func (b *Breaker) cooldown() time.Duration {
    if b.Cooldown > 0 {
        return b.Cooldown
    }
    return DefaultCooldown
}

// Take reports whether a call may go to the provider now, and returns the
// ticket: a probe ticket when this call was granted the half-open slot.
func (b *Breaker) Take() (Ticket, bool) {
    b.mu.Lock()
    defer b.mu.Unlock()
    if !b.open {
        return Ticket{}, true
    }
    if b.probeID != 0 {
        return Ticket{}, false
    }
    if b.now().Sub(b.openedAt) >= b.cooldown() {
        b.lastID++
        b.probeID = b.lastID // half-open: this one call is the probe
        return Ticket{b.probeID}, true
    }
    return Ticket{}, false
}

// Admit is Take without the ticket, for a caller with one call in flight at
// a time: its Failure and Release are taken to be the probe's.
func (b *Breaker) Admit() bool {
    _, ok := b.Take()
    return ok
}

// Success records a call that reached the provider and was answered.
func (b *Breaker) Success() {
    b.mu.Lock()
    defer b.mu.Unlock()
    b.consecutive, b.open, b.probeID = 0, false, 0
}

// Release gives back the probe slot a call held when it ended without
// telling the breaker anything about the provider (the caller cancelled, or
// the adapter refused the request before sending it). The breaker stays
// open and the next Take grants a new probe. A ticket that is not the
// current probe's does nothing.
func (b *Breaker) Release(t Ticket) {
    b.mu.Lock()
    defer b.mu.Unlock()
    if t.probeID != 0 && t.probeID == b.probeID {
        b.probeID = 0
    }
}

// Fail records a provider fault by the call the ticket was issued to. The
// probe's failure reopens the breaker for another cooldown; a failure of an
// ordinary call while the breaker is open is stale (the call began before it
// opened) and is ignored; a probe ticket that is no longer current is too.
func (b *Breaker) Fail(t Ticket) {
    b.mu.Lock()
    defer b.mu.Unlock()
    if t.probeID != 0 {
        if t.probeID == b.probeID {
            b.openedAt, b.probeID = b.now(), 0
        }
        return
    }
    if b.open {
        return
    }
    b.consecutive++
    if b.consecutive >= b.failures() {
        b.open, b.openedAt, b.probeID = true, b.now(), 0
    }
}

// Failure is Fail for a caller with one call in flight at a time (Admit's
// pair): while open, it is the probe's failure.
func (b *Breaker) Failure() {
    b.mu.Lock()
    id := b.probeID
    b.mu.Unlock()
    b.Fail(Ticket{id})
}

// State is "closed", "open" or "half_open" (open and cooled down, so the next
// Take grants a probe, or a probe is in flight).
func (b *Breaker) State() string {
    b.mu.Lock()
    defer b.mu.Unlock()
    switch {
    case !b.open:
        return "closed"
    case b.probeID != 0 || b.now().Sub(b.openedAt) >= b.cooldown():
        return "half_open"
    }
    return "open"
}

// Admits reports whether Take would grant a call, without taking the probe.
func (b *Breaker) Admits() bool { return b.State() != "open" && !b.probingNow() }

func (b *Breaker) probingNow() bool {
    b.mu.Lock()
    defer b.mu.Unlock()
    return b.probeID != 0
}

What the defaults buy is arithmetic, and a model is enough. Take a provider that is down for DD seconds, with requests arriving at rate λ\lambda, a call to it failing after tot_o seconds. Without a breaker every one of the λD\lambda D requests goes to the dead provider and waits tot_o. With one, there are two regimes, and the code gives the same numbers as the formulas below.

Fast faults (a refused connection returns at once). The FF-th fault lands at (F−1)/λ(F-1)/\lambda, the breaker opens, and from then on it admits one probe per cooldown, each of which fails at once and reopens it. With o=(F−1)/λo = (F-1)/\lambda the instant it opens, the first probe comes one cooldown later, at o+co + c, and the later ones every cc, each strictly before DD. Requests that reach the provider: F+⌈(D−o−c)/c⌉F + \lceil (D - o - c)/c \rceil. For D=600D = 600, λ=2\lambda = 2, F=5F = 5, c=30c = 30, o=2o = 2 that is 5+⌈568/30⌉=5+19=245 + \lceil 568/30 \rceil = 5 + 19 = 24 against 1,200.

Timeouts. The FF-th failure does not land until (F−1)/λ+to(F-1)/\lambda + t_o, and every request that arrived before it was admitted, since the breaker was closed: λ((F−1)/λ+to)=(F−1)+λto\lambda\,((F-1)/\lambda + t_o) = (F-1) + \lambda t_o of them, 64 for to=30t_o = 30. The breaker opens at o=(F−1)/λ+too = (F-1)/\lambda + t_o, which is 32 s here. After that a probe holds the slot for tot_o before failing, and the cooldown starts again from its failure, so the cycle is c+toc + t_o seconds, not cc. Probes begin at o+c+k(c+to)o + c + k(c + t_o) for k=0,1,…k = 0, 1, \ldots, each strictly before DD, so there are ⌈(D−o−c)/(c+to)⌉=⌈538/60⌉=9\lceil (D - o - c)/(c + t_o) \rceil = \lceil 538/60 \rceil = 9 of them. The total is 64+9=7364 + 9 = 73, and each waits 30 s, 2,190 s against 36,000 s. The counts depend on one tie convention: arrivals land exactly on failure instants, and the model records a failure due at an arrival’s instant before it serves the arrival, which is also what “the requests that arrived before it” assumes. Serve the arrival first and the counts become 74 requests and 2,220 s.

The numbers above come from running the committed Breaker with a fake clock over exactly that arrival pattern (talos): 24 requests reach the provider in the fast regime, and 73 in the timeout regime with 30 s timeouts, which wait 36 min 30 s in total where no breaker would wait 10 h. It is a model with deterministic arrivals and a provider that is entirely dead, and not a measurement of any provider. It shows two things the one-line formula F+⌈D/c⌉F + \lceil D/c \rceil would hide: a breaker does not help the requests already in flight when it opens, and a slow failure makes both the opening and every probe cost the full timeout.

The runtime in Go

internal/decide is chapter 21’s runtime in Go, to parity with the committed goldens. It reads the weights file with encoding/binary and encoding/json v1 (the pin is a choice: encoding/json/v2 builds on straylight’s go1.27.0 and talos’s go1.27.1, and writes 1.5 for 1.50, and the goldens encode v1’s UseNumber and SetEscapeHTML(false) semantics, chapter 21). It parses a request from its JSON text with a token-stream parser, so that repeated keys and number literals are seen, validates it in chapter 21’s order, builds the one embeddings batch, computes the choice, score and noul heads in float64 from float32 weights, and returns a typed answer or one of the six error kinds.

// Load reads and checks a weights file. Every rule of the Produces block is
// checked here, so a malformed file fails at start-up and never on a request.
func Load(path string) (*Model, error) {
    raw, err := os.ReadFile(path)
    if err != nil {
        return nil, invalid("%v", err)
    }
    return loadBytes(raw)
}

func loadBytes(raw []byte) (*Model, error) {
    if len(raw) < 8 {
        return nil, invalid("shorter than the 8-byte header length")
    }
    n := binary.LittleEndian.Uint64(raw[:8])
    if n > maxHeader || 8+n > uint64(len(raw)) {
        return nil, invalid("header length %d does not fit the file", n)
    }
    if !utf8.Valid(raw[8:8+n]) || loneSurrogateEscape(raw[8:8+n]) {
        return nil, invalid("header is not valid UTF-8 text, or has a lone surrogate escape")
    }
    hv, err := parse(raw[8 : 8+n])
    if err != nil {
        return nil, invalid("header is not JSON: %v", err)
    }
    header, ok := hv.(*object)
    if !ok {
        return nil, invalid("header is not an object")
    }
    md, ok := header.m["__metadata__"].(*object)
    if !ok {
        return nil, invalid("header has no __metadata__ object")
    }
    ms, ok := md.m["jev_lite"].(string)
    if !ok {
        return nil, invalid("__metadata__ has no jev_lite string")
    }
    if loneSurrogateEscape([]byte(ms)) {
        return nil, invalid("jev_lite metadata has a lone surrogate escape")
    }
    mv, err := parse([]byte(ms))
    if err != nil {
        return nil, invalid("jev_lite metadata is not JSON: %v", err)
    }
    metaObj, ok := mv.(*object)
    if !ok {
        return nil, invalid("jev_lite metadata is not an object")
    }
    if fv, ok := asInt(metaObj.m["format_version"]); !ok || fv != formatVersion {
        return nil, invalid("format_version %v, expected %d", plain(metaObj.m["format_version"]), formatVersion)
    }
    // The tensor table, in order of begin offset.
    type entry struct {
        name   string
        shape  []int
        lo, hi int
    }
    var entries []entry
    for name, ev := range header.m {
        if name == "__metadata__" {
            continue
        }
        e, ok := ev.(*object)
        if !ok {
            return nil, invalid("%s: tensor entry is not an object", name)
        }
        if dt, _ := asStr(e.m["dtype"]); dt != "F32" {
            return nil, invalid("%s: only F32 tensors", name)
        }
        shapeV, ok := e.m["shape"].([]any)
        if !ok {
            return nil, invalid("%s: shape must be a list", name)
        }
        shape := make([]int, len(shapeV))
        for i, s := range shapeV {
            d, ok := asInt(s)
            if !ok || d < 0 {
                return nil, invalid("%s: only F32 tensors with integer shapes", name)
            }
            shape[i] = d
        }
        offs, ok := e.m["data_offsets"].([]any)
        if !ok || len(offs) != 2 {
            return nil, invalid("%s: data_offsets must be [begin, end]", name)
        }
        lo, ok1 := asInt(offs[0])
        hi, ok2 := asInt(offs[1])
        if !ok1 || !ok2 {
            return nil, invalid("%s: data_offsets must be [begin, end]", name)
        }
        entries = append(entries, entry{name, shape, lo, hi})
    }
    // By begin, then end: a zero-length tensor (heads.route.Wf, [5, 0]) shares
    // its begin with the tensor after it and must sort first. The Python
    // reader sorts by (begin, end) too; sorting by begin alone would rely on
    // the header's name order, which a Go map does not have.
    sort.Slice(entries, func(i, j int) bool {
        if entries[i].lo != entries[j].lo {
            return entries[i].lo < entries[j].lo
        }
        return entries[i].hi < entries[j].hi
    })
    buf := raw[8+n:]
    tensors := make(map[string]*tensor, len(entries))
    expect := 0
    var probeBytes []byte
    for _, e := range entries {
        size, fits := byteSize(e.shape)
        if !fits || e.lo != expect || e.hi < e.lo || uint64(e.hi-e.lo) != size || e.hi > len(buf) {
            return nil, invalid("%s: offsets %d..%d leave a hole or overlap", e.name, e.lo, e.hi)
        }
        data := make([]float32, int(size/4))
        for i := range data {
            data[i] = math.Float32frombits(binary.LittleEndian.Uint32(buf[e.lo+4*i:]))
            if f := float64(data[i]); math.IsNaN(f) || math.IsInf(f, 0) {
                return nil, invalid("%s: a NaN or infinite value", e.name)
            }
        }
        tensors[e.name] = &tensor{shape: e.shape, data: data}
        if e.name == "embedder.probes" {
            probeBytes = buf[e.lo:e.hi]
        }
        expect = e.hi
    }
    if expect != len(buf) {
        return nil, invalid("%d bytes after the last tensor", len(buf)-expect)
    }
    meta, err := checkMeta(metaObj, tensors)
    if err != nil {
        return nil, err
    }
    probes := tensors["embedder.probes"]
    if probes == nil || len(probes.shape) != 2 || probes.shape[0] != len(meta.Embedder.Probes) || probes.shape[1] != meta.Embedder.Dim {
        return nil, invalid("embedder.probes missing or not (n_probes, dim)")
    }
    sum := sha256.Sum256(raw)
    psum := sha256.Sum256(probeBytes)
    return &Model{Version: hex.EncodeToString(sum[:])[:16], Embedder: hex.EncodeToString(psum[:])[:16],
        Meta: *meta, tensors: tensors}, nil
}
// object is a parsed JSON object that remembers whether a key occurred twice
// (the last value wins, as Go's and Python's decoders both keep it). The
// request rules refuse a repeated option name or noul key, which a decode
// into a map could not see, so the request is parsed from the token stream.
type object struct {
    m   map[string]any
    dup bool
}

// parse reads one JSON value from text with json.Decoder: UseNumber keeps
// every number as its literal text, the decoder replaces a lone surrogate
// escape and an invalid UTF-8 byte inside a string with U+FFFD in keys and
// values alike, and anything after the value (a second Decode that does not
// return io.EOF) is BadRequest. Objects come back as *object, arrays as
// []any, numbers as json.Number.
func parse(text []byte) (any, error) {
    dec := json.NewDecoder(bytes.NewReader(text))
    dec.UseNumber()
    v, err := parseValue(dec, 0)
    if errors.Is(err, errTooDeep) {
        return nil, errf(BadRequest, "", "nested more than %d deep", maxDepth)
    }
    if err != nil {
        return nil, errf(BadRequest, "", "not JSON: %v", err)
    }
    if _, err := dec.Token(); err != io.EOF {
        return nil, errf(BadRequest, "", "data after the request")
    }
    return v, nil
}

// errTooDeep is parse's refusal of a document that nests more than maxDepth containers inside its
// top-level one. parseValue's depth is the number of containers that enclose the value being read.
var errTooDeep = errors.New("nested too deep")

func parseValue(dec *json.Decoder, depth int) (any, error) {
    tok, err := dec.Token()
    if err != nil {
        return nil, err
    }
    switch t := tok.(type) {
    case json.Delim:
        switch t {
        case '{':
            if depth > maxDepth {
                return nil, errTooDeep
            }
            o := &object{m: map[string]any{}}
            for dec.More() {
                k, err := dec.Token()
                if err != nil {
                    return nil, err
                }
                key := k.(string) // the decoder guarantees a string key here
                v, err := parseValue(dec, depth+1)
                if err != nil {
                    return nil, err
                }
                if _, seen := o.m[key]; seen {
                    o.dup = true
                }
                o.m[key] = v
            }
            _, err := dec.Token() // the closing brace
            return o, err
        case '[':
            if depth > maxDepth {
                return nil, errTooDeep
            }
            a := []any{}
            for dec.More() {
                v, err := parseValue(dec, depth+1)
                if err != nil {
                    return nil, err
                }
                a = append(a, v)
            }
            _, err := dec.Token()
            return a, err
        }
        return nil, io.ErrUnexpectedEOF
    default:
        return tok, nil // string, json.Number, bool or nil
    }
}

// plain turns a parsed tree into the maps and slices canon.JSON encodes.
func plain(v any) any {
    switch t := v.(type) {
    case *object:
        m := make(map[string]any, len(t.m))
        for k, x := range t.m {
            m[k] = plain(x)
        }
        return m
    case []any:
        a := make([]any, len(t))
        for i, x := range t {
            a[i] = plain(x)
        }
        return a
    }
    return v
}

The places where a Go reader of chapter 21’s text goes wrong are few, and each has a test.

  • The tensor table is sorted by (begin, end). Two tensors share a begin when a zero-length tensor precedes another: heads.route.Wf has shape [5,0][5, 0] and begins where heads.route.alpha begins, at buffer offset 398,276 of jev-lite.safetensors (file byte 405,364) and 141,252 of the golden weights (file byte 148,244). Chapter 21’s Python reader sorts by (begin, end) too. A sort by begin alone would pass in Python, where a stable sort keeps the header’s order and the writer listed the tensors by name, and fail in Go, where a map has no order: it rejects the committed file on some runs and not others. Of the 16 tensors in each committed file, Wf is the only one with a zero dimension.
  • Floats come out of stable forms. log1p for log(1+e−∣x∣)\log(1 + e^{-|x|}), the shifted softmax, ordered thresholds built as a running sum of softplus gaps, all as in chapter 21’s Mechanism. The numerics are in one listing.
  • Questions are taken in sorted order, and a choice’s options in sorted order of their names, because Go reads them from maps, which have no order, and the embeddings batch must come out the same on every run.
  • The loader refuses what it cannot read. A choice head’s criteria values are the option descriptions, which are embedded, so each must be a string; a feature_spec_version other than 1 is a feature extractor this code does not implement. Both are WeightsInvalid at load in Go and in Python, and the weights goldens carry a small valid choice head and the three bad files.
  • A reply that is not numbers is the wrong embedder. An embedding value that is a string, a null, an object or a boolean is EmbedderMismatch, as Python classifies it; only a reply that is not JSON at all is EmbedderUnavailable. A null is not read as 0.
  • A nesting limit of 64 on the whole request document and on the weights header, enforced by both implementations before validation, because a recursive parser’s depth is otherwise the attacker’s choice (chapter 21 states the limit and the mechanism).
  • The embedder’s fingerprint and its check. The weights name the embedder they were trained against, honcho-embed here, with a stored set of probe vectors and the example scores of the embedding model’s card. CheckEmbedder re-embeds the probes and requires every cosine to reach the header’s probe_threshold (0.998118 in the committed file), then embeds the card’s queries and documents and requires every score within tolerance of the card’s. Both are written as passes, so a NaN fails them, and a header without a card check is WeightsInvalid: a check skipped for missing data is not a check. Run repeats it on an interval, and aec-decide uses an hour and refuses requests with a 503 for as long as its last check has failed.
// logSigmoid is log σ(t) = min(t, 0) − log1p(exp(−|t|)): no overflow and no
// log(0) for any finite t.
func logSigmoid(t float64) float64 { return math.Min(t, 0) - math.Log1p(math.Exp(-math.Abs(t))) }

// softplus is log(1 + e^t) = max(t, 0) + log1p(exp(−|t|)).
func softplus(t float64) float64 { return math.Max(t, 0) + math.Log1p(math.Exp(-math.Abs(t))) }

// softmax is exp(z − max z) / Σ exp(z − max z).
func softmax(z []float64) []float64 {
    m := math.Inf(-1)
    for _, x := range z {
        m = math.Max(m, x)
    }
    p := make([]float64, len(z))
    var s float64
    for i, x := range z {
        p[i] = math.Exp(x - m)
        s += p[i]
    }
    for i := range p {
        p[i] /= s
    }
    return p
}

func dot(a, b []float64) float64 {
    var s float64
    for i := range a {
        s += a[i] * b[i]
    }
    return s
}
// choiceScores is s_o = α (e_q·e_o) + (U e_q)·(V e_o) + b_o + Wf_o·f for each
// option o, with rows of b and Wf chosen by idx (each option's position in
// the head's options). U and V are [r, d] row-major; Wf is [K, n_f].
func (m *Model) choiceScores(h *Head, eq []float64, eo [][]float64, idx []int, f []float64) []float64 {
    alpha := m.vec(h.Tensors["alpha"])[0]
    u, v := m.tensors[h.Tensors["U"]], m.tensors[h.Tensors["V"]]
    b, wf := m.vec(h.Tensors["b"]), m.tensors[h.Tensors["Wf"]]
    r, d := u.shape[0], u.shape[1]
    nf := wf.shape[1]
    ueq := make([]float64, r) // U e_q
    for i := 0; i < r; i++ {
        var s float64
        for j := 0; j < d; j++ {
            s += float64(u.data[i*d+j]) * eq[j]
        }
        ueq[i] = s
    }
    out := make([]float64, len(eo))
    for k, e := range eo {
        s := alpha * dot(eq, e)
        for i := 0; i < r; i++ { // (U e_q)_i (V e_o)_i
            var ve float64
            for j := 0; j < d; j++ {
                ve += float64(v.data[i*d+j]) * e[j]
            }
            s += ueq[i] * ve
        }
        s += b[idx[k]]
        for j := 0; j < nf; j++ {
            s += float64(wf.data[idx[k]*nf+j]) * f[j]
        }
        out[k] = s
    }
    return out
}

// ordinalThresholds is θ_0 = c, θ_k = θ_{k−1} + softplus(δ_k) + 1e-4: ordered
// by construction for any δ.
func ordinalThresholds(c float64, delta []float64) []float64 {
    theta := make([]float64, len(delta)+1)
    theta[0] = c
    for k, d := range delta {
        theta[k+1] = theta[k] + softplus(d) + 1e-4
    }
    return theta
}

// ordinalLogProbs returns u_k = (θ_k − η)/T and log p_k for the K levels:
// log p_0 = logσ(u_0), log p_{K−1} = logσ(−u_{K−2}), and between them
// log p_k = logσ(u_k) + logσ(−u_{k−1}) + log(−expm1(−(u_k − u_{k−1}))).
func ordinalLogProbs(theta []float64, eta, T float64) (u, logp []float64) {
    u = make([]float64, len(theta))
    for k, th := range theta {
        u[k] = (th - eta) / T
    }
    K := len(theta) + 1
    logp = make([]float64, K)
    logp[0] = logSigmoid(u[0])
    logp[K-1] = logSigmoid(-u[K-2])
    for k := 1; k < K-1; k++ {
        logp[k] = logSigmoid(u[k]) + logSigmoid(-u[k-1]) + math.Log(-math.Expm1(-(u[k] - u[k-1])))
    }
    return u, logp
}
// Decide parses input (the request's JSON text), validates it, embeds every
// text it needs in one batch, and answers every question. workspace is the
// security heads' notion of "inside"; "" means /workspace.
func (m *Model) Decide(ctx context.Context, e Embedder, input []byte, workspace string) (*Response, error) {
    if workspace == "" {
        workspace = "/workspace"
    }
    req, err := parse(input)
    if err != nil {
        return nil, err
    }
    state, questions, err := validate(req)
    if err != nil {
        return nil, err
    }
    var texts []string
    seen := map[string]bool{}
    need := func(t string) string {
        if !seen[t] {
            seen[t] = true
            texts = append(texts, t)
        }
        return t
    }
    qids := sortedKeys(questions)
    plans := make([]*qplan, 0, len(qids))
    for _, qid := range qids {
        q := questions[qid]
        p := &qplan{q: q, head: m.Meta.Heads[qid]}
        if p.head != nil {
            if p.names, err = registered(p.head, qid, q); err != nil {
                return nil, err
            }
        }
        p.qt = need(queryText(q.Instructions, state))
        switch {
        case q.Type == "choice":
            for _, n := range sortedKeys(q.Choice) {
                p.opts = append(p.opts, need(optionText(n, q.Choice[n])))
            }
        case q.Type == "score" && p.head == nil:
            for k, lvl := range q.Score {
                p.opts = append(p.opts, need(optionText(strconv.Itoa(k), lvl)))
            }
        case q.Type == "noul" && p.head == nil:
            c := map[string]string{"true": defaultNoul["true"], "false": defaultNoul["false"]}
            for k, v := range q.Noul {
                c[k] = v
            }
            p.opts = append(p.opts, need(optionText("true", c["true"])), need(optionText("false", c["false"])))
        }
        plans = append(plans, p)
    }
    vecs, err := m.embed(ctx, e, texts, m.Meta.Embedder.Dim)
    if err != nil {
        return nil, err
    }
    V := make(map[string][]float64, len(texts))
    for i, t := range texts {
        V[t] = vecs[i]
    }
    resp := &Response{Model: ModelID{Weights: m.Version, Embedder: m.Embedder}, Answers: map[string]*Answer{}}
    for i, p := range plans {
        qid := qids[i]
        eq := V[p.qt]
        x := eq
        var f []float64
        if p.head != nil && p.head.Features == "call" {
            call, ok := req.(*object).m["state"].(*object)
            name, okn := call.callName()
            args, oka := call.callArgs()
            if !ok || !okn || !oka {
                return nil, errf(BadRequest, qid, "this question reads the state as a tool call {name, arguments}")
            }
            ct, err := canon.CallText(name, plain(args))
            if err != nil {
                return nil, errf(BadRequest, qid, "call text: %v", err)
            }
            fs := FStruct(name, plain(args).(map[string]any), workspace)
            f = append(fs[:], FHash(string(ct), HashDim)...)
            x = append(append([]float64(nil), eq...), f...)
        }
        eo := make([][]float64, len(p.opts))
        for k, t := range p.opts {
            eo[k] = V[t]
        }
        var a *Answer
        switch {
        case p.q.Type == "choice" || (p.q.Type == "score" && p.head == nil):
            var z []float64
            if p.head != nil {
                idx := make([]int, len(p.names))
                for k, n := range p.names {
                    idx[k] = indexOf(p.head.Options, n)
                }
                T := p.head.Temperature
                if t, ok := p.head.TemperatureBySize[strconv.Itoa(len(p.names))]; ok {
                    T = t
                }
                z = m.choiceScores(p.head, eq, eo, idx, f)
                for k := range z {
                    z[k] /= T
                }
            } else {
                z = make([]float64, len(eo))
                for k, e := range eo {
                    z[k] = m.Meta.ZeroShot.Alpha * dot(eq, e)
                }
            }
            prob := softmax(z)
            if p.q.Type == "choice" {
                keys := sortedKeys(p.q.Choice)
                best := 0
                for k := range prob {
                    if prob[k] > prob[best] {
                        best = k
                    }
                }
                a = &Answer{Type: "choice", Choice: keys[best], Probabilities: map[string]float64{}, Calibrated: p.head != nil,
                    Logits: z, Decision: keys[best]}
                for k, n := range keys {
                    a.Probabilities[n] = prob[k]
                }
            } else {
                a = scoreAnswer(prob, p.q.Score, false)
                a.Logits = z
            }
        case p.q.Type == "score":
            w := m.vec(p.head.Tensors["w"])
            theta := ordinalThresholds(m.vec(p.head.Tensors["c"])[0], m.vec(p.head.Tensors["delta"]))
            u, logp := ordinalLogProbs(theta, dot(w, x), p.head.Temperature)
            prob := make([]float64, len(logp))
            for k, lp := range logp {
                prob[k] = math.Exp(lp)
            }
            a = scoreAnswer(prob, p.q.Score, true)
            a.Logits = u
        default: // noul
            var z float64
            if p.head != nil {
                w, b := m.vec(p.head.Tensors["w"]), m.vec(p.head.Tensors["b"])[0]
                z = (dot(w, x) + b) / p.head.Temperature
            } else {
                zs := m.Meta.ZeroShot
                z = zs.AlphaZ*(dot(eq, eo[0])-dot(eq, eo[1])) + zs.BetaZ
            }
            pr := math.Exp(logSigmoid(z))
            a = &Answer{Type: "noul", Noul: &pr, Calibrated: p.head != nil, Logits: []float64{z}, Decision: pr > 0.5}
        }
        resp.Answers[qid] = a
    }
    return resp, nil
}

// scoreAnswer: score (the expected level), level (the median), probabilities,
// at_least and legend; Decision is the median index.
func scoreAnswer(p []float64, levels []string, calibrated bool) *Answer {
    K := len(p)
    cum := make([]float64, K)
    var expected float64
    for k := range p {
        expected += float64(k) * p[k]
        cum[k] = p[k]
        if k > 0 {
            cum[k] += cum[k-1]
        }
    }
    med := K - 1
    for k := range cum {
        if cum[k] >= 0.5 {
            med = k
            break
        }
    }
    a := &Answer{Type: "score", Score: &expected, Level: levels[med], Probabilities: map[string]float64{},
        AtLeast: map[string]float64{}, Legend: map[string]string{}, Calibrated: calibrated, Decision: med}
    for k := range p {
        ks := strconv.Itoa(k)
        a.Probabilities[ks] = p[k]
        a.Legend[ks] = levels[k]
        if k > 0 {
            a.AtLeast[ks] = 1 - cum[k-1]
        }
    }
    return a
}
// Embedder is one /v1/embeddings batch: tether on dixie :11435 or its router at :11434 (chapter 51 deploys the latter),
// a record's own vectors in the golden tests, a hashed n-gram stand-in in
// unit tests.
type Embedder interface {
    Embed(ctx context.Context, texts []string) ([][]float32, error)
}

// HTTPEmbedder is the fleet embedder behind an OpenAI-compatible
// /v1/embeddings. It is fleet-guarded, with no way to turn the guard off:
// immediately before every batch it reads GET /v1/models and refuses
// (EmbedderUnavailable) unless Model's status.value is exactly "loaded", and
// it sends the batch with ?autoload=false. A sleeping model is not loaded.
type HTTPEmbedder struct {
    BaseURL string // ".../v1" is not implied: give the server root, e.g. http://dixie:11435
    Model   string // honcho-embed
    HTTP    *http.Client
}

// fleetTransport ignores the environment's proxy settings, so a request to
// the embedder reaches the host its URL names and no other.
var fleetTransport = func() *http.Transport {
    t := http.DefaultTransport.(*http.Transport).Clone()
    t.Proxy = nil
    return t
}()

// NewHTTPEmbedder is the embedder for a loaded model: it speaks to the model the weights name
// (the header's embedder.name, "honcho-embed" for the real artefact, which is what /v1/models lists),
// so a request cannot be embedded by a model the weights were not trained against. A header with no
// name is WeightsInvalid.
func NewHTTPEmbedder(m *Model, baseURL string, client *http.Client) (*HTTPEmbedder, error) {
    if m == nil || m.Meta.Embedder.Name == "" {
        return nil, invalid("the weights name no embedder (embedder.name is empty)")
    }
    return &HTTPEmbedder{BaseURL: baseURL, Model: m.Meta.Embedder.Name, HTTP: client}, nil
}

// noRedirect makes a 3xx the response, so a POST body is never resent to another host.
func noRedirect(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }

func (e *HTTPEmbedder) client() *http.Client {
    if e.HTTP != nil {
        c := *e.HTTP
        c.CheckRedirect = noRedirect
        if c.Transport == nil {
            // A caller's client with no transport of its own would use
            // http.DefaultTransport, which reads HTTP_PROXY and would hand
            // the request, body included, to whatever the environment names
            // (chapter 48; embedding.HTTP was hardened the same way).
            c.Transport = fleetTransport
        }
        return &c
    }
    return &http.Client{Timeout: 30 * time.Second, Transport: fleetTransport, CheckRedirect: noRedirect}
}

// Loaded reads /v1/models and reports Model's status; it is the guard.
func (e *HTTPEmbedder) Loaded(ctx context.Context) error {
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.BaseURL+"/v1/models", nil)
    if err != nil {
        return errf(EmbedderUnavailable, "", "%v", err)
    }
    resp, err := e.client().Do(req)
    if err != nil {
        return errf(EmbedderUnavailable, "", "%v", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return errf(EmbedderUnavailable, "", "GET /v1/models: %s", resp.Status)
    }
    var list struct {
        Data []struct {
            ID     string `json:"id"`
            Status struct {
                Value string `json:"value"`
            } `json:"status"`
        } `json:"data"`
    }
    if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&list); err != nil {
        return errf(EmbedderUnavailable, "", "GET /v1/models: %v", err)
    }
    for _, m := range list.Data {
        if m.ID == e.Model {
            if m.Status.Value != "loaded" {
                return errf(EmbedderUnavailable, "", "%s is %q, not loaded; this client never loads a model", e.Model, m.Status.Value)
            }
            return nil
        }
    }
    return errf(EmbedderUnavailable, "", "%s is not in /v1/models", e.Model)
}

func (e *HTTPEmbedder) Embed(ctx context.Context, texts []string) ([][]float32, error) {
    if err := e.Loaded(ctx); err != nil {
        return nil, err
    }
    body, _ := json.Marshal(map[string]any{"model": e.Model, "input": texts})
    req, err := http.NewRequestWithContext(ctx, http.MethodPost, e.BaseURL+"/v1/embeddings?autoload=false", bytes.NewReader(body))
    if err != nil {
        return nil, errf(EmbedderUnavailable, "", "%v", err)
    }
    req.Header.Set("Content-Type", "application/json")
    resp, err := e.client().Do(req)
    if err != nil {
        return nil, errf(EmbedderUnavailable, "", "%v", err)
    }
    defer resp.Body.Close()
    if resp.StatusCode != http.StatusOK {
        return nil, errf(EmbedderUnavailable, "", "POST /v1/embeddings: %s", resp.Status)
    }
    var out struct {
        Data []struct {
            Index     int        `json:"index"`
            Embedding []*float64 `json:"embedding"`
        } `json:"data"`
    }
    if err := json.NewDecoder(io.LimitReader(resp.Body, 64<<20)).Decode(&out); err != nil {
        var te *json.UnmarshalTypeError
        if errors.As(err, &te) { // a reply that is JSON but not numbers: the embedder is the wrong thing
            return nil, errf(EmbedderMismatch, "", "embedder returned a value that is not a number: %v", err)
        }
        return nil, errf(EmbedderUnavailable, "", "POST /v1/embeddings: %v", err)
    }
    if len(out.Data) != len(texts) {
        return nil, errf(EmbedderMismatch, "", "embedder returned %d vectors for %d texts", len(out.Data), len(texts))
    }
    vecs := make([][]float32, len(texts))
    for _, d := range out.Data {
        if d.Index < 0 || d.Index >= len(texts) || vecs[d.Index] != nil {
            return nil, errf(EmbedderMismatch, "", "embedder returned index %d: indices must be 0..%d, each once", d.Index, len(texts)-1)
        }
        row := make([]float32, len(d.Embedding))
        for j, x := range d.Embedding {
            if x == nil {
                return nil, errf(EmbedderMismatch, "", "embedder returned a null where a number belongs")
            }
            if math.Abs(*x) > math.MaxFloat32 {
                return nil, errf(EmbedderMismatch, "", "embedder returned a value outside float32")
            }
            row[j] = float32(*x)
        }
        vecs[d.Index] = row
    }
    return vecs, nil
}
// CheckEmbedder is the load-time and hourly check: (a) re-embed the probe
// texts as one batch and require every cosine with the stored vectors to be
// at least the header's probe_threshold (a zero vector matches nothing);
// (b) embed the card check's queries and documents as one batch and require
// every query-document cosine within tolerance of the card's. Both are
// written as passes, so a NaN fails them. A header without a card check is
// WeightsInvalid here: a check skipped for missing data is not a check.
func (m *Model) CheckEmbedder(ctx context.Context, e Embedder) error {
    em := &m.Meta.Embedder
    live, err := m.embed(ctx, e, em.Probes, em.Dim)
    if err != nil {
        return err
    }
    stored := m.tensors["embedder.probes"]
    for i, v := range live {
        s := make([]float64, em.Dim)
        for j := range s {
            s[j] = float64(stored.data[i*em.Dim+j])
        }
        nv, ns := math.Sqrt(dot(v, v)), math.Sqrt(dot(s, s))
        cos := math.Inf(-1)
        if nv > 0 && ns > 0 {
            cos = dot(v, s) / (nv * ns)
        }
        if !(cos >= em.ProbeThreshold) {
            return errf(EmbedderMismatch, "", "probe %d cosine %.6f below %g", i, cos, em.ProbeThreshold)
        }
    }
    if em.Card == nil {
        return invalid("no embedder.card_check: the weights cannot tie the embedder to its reference")
    }
    nq := len(em.Card.Queries)
    all, err := m.embed(ctx, e, append(append([]string(nil), em.Card.Queries...), em.Card.Documents...), em.Dim)
    if err != nil {
        return err
    }
    for i := 0; i < nq; i++ {
        for j := range em.Card.Documents {
            score := dot(all[i], all[nq+j])
            if !(math.Abs(score-em.Card.Expected[i][j]) <= em.Card.Tolerance) {
                return errf(EmbedderMismatch, "", "card score [%d][%d] %.4f differs from %.4f by more than %g",
                    i, j, score, em.Card.Expected[i][j], em.Card.Tolerance)
            }
        }
    }
    return nil
}

Parity is the committed goldens, within the Produces block’s tolerance of ∣got−want∣≤10−9(1+∣want∣)|\mathrm{got} - \mathrm{want}| \le 10^{-9}(1 + |\mathrm{want}|) for floats and exactly for strings, decisions and calibrated: 64 vector records (97 questions), 71 interface records, 101 feature records and 24 weights records. The mutation passes in the Walkthrough are the evidence that the tests can tell a wrong runtime from a right one; four of the decide mutants (the log1p form, the >= in the median rule, the chain_count cap and the tie-break) are killed only by a direct test, because the goldens reject near ties (margins under 10−610^{-6}) and avoid extreme values.

The head’s own numbers. The route head in the committed jev-lite.safetensors carries its calibration in the header. It was trained by chapter 21’s train_student.py on straylight (4 seconds, 169 training rows) over honcho-embed vectors captured on dixie on 2026-09-30, and the numbers are printed as they are: temperature T=1.0159T = 1.0159; on the n=68n = 68 held-out rows, NLL 0.7515, Brier 0.3258, adaptive ECE 0.2366, top-label accuracy 0.7941, and agreement with the teacher 0.8676. The header’s ECE of 0.2366 is large, and its direction is not the one a first reading guesses. py/data/decisions/route_reliability.py (run from py/, on talos) asks the committed weights the full five-option question for each of the 68 held-out rows and reproduces the header’s ECE to four places, then splits the rows by the confidence the head reported. The mean top-label confidence is 0.635 and the accuracy 0.7941, so on average the head is underconfident by 16 points. By band:

reported confidence rows mean confidence right
[0.0, 0.4) 12 0.366 2 of 12
[0.4, 0.6) 14 0.487 10 of 14
[0.6, 0.8) 26 0.683 26 of 26
[0.8, 0.9) 9 0.868 9 of 9
[0.9, 1.0] 7 0.918 7 of 7

Above 0.6 the head was right on all 42 rows, whatever number it reported; it is overconfident only below 0.4, where it was right on 2 of 12 against a stated 0.37. Chapter 20’s equal-mass reliability table, ten bins of about seven rows with a 95% bootstrap band on each accuracy:

bin   n  mean conf  accuracy     lo     hi
  1   7      0.352     0.000  0.000  0.000
  2   7      0.393     0.286  0.000  0.571
  3   7      0.470     0.857  0.571  1.000
  4   7      0.560     0.857  0.571  1.000
  5   7      0.626     1.000  1.000  1.000
  6   7      0.671     1.000  1.000  1.000
  7   7      0.736     1.000  1.000  1.000
  8   7      0.811     1.000  1.000  1.000
  9   6      0.889     1.000  1.000  1.000
 10   6      0.921     1.000  1.000  1.000

The consequence for the spans is the opposite of the cautious reading. A recorded 0.68 has meant “right every time” on this held-out set, so a threshold read off the recorded probability (discard routes below 0.8, say) would throw away good routes, and the gap is in the first digit, not the second. Seven rows to a bin leave the bands wide, and the set is small: the table says which way the head is off, not by how much on other data. Chapter 21’s per-subset table is the more relevant one for a gate that asks over three or four roles: the same head’s adaptive ECE on held-out rows is 0.0400 for subsets of 2, 0.1201 for 3, 0.1843 for 4 and 0.2366 for the full 5 (272, 408, 272 and 68 held-out answers). The same script prints the baseline. The intended role is primary for 18 of the 68 held-out rows, so sending everything to primary is right on 18 (0.2647), where the head is right on 54 (0.7941). That settles the comparison on this held-out set, and says nothing more: the rows are the course’s synthetic prompts, not the reader’s traffic. A constant rule is right on exactly the share of requests whose proper role is primary, so the gate beats it on real traffic only if its accuracy there exceeds that share, and where most requests really are primary it may not. The operational number to watch is how often fail_open appears in aec_route_decisions_total, because every such decision is the fixed rule.

One request through the routing gate Four stages from top to bottom. The request carries text, an optional image, a private flag and an optional forced role. Eligibility applies three rules: vision only with an image, a private request only where every provider of the role is local, and some breaker must admit. In the example the request has no image and is private, so vision and primary are struck out, leaving aux, delegation and local. The gate asks the registered route head over those three roles with one embeddings batch under a budget of 250 milliseconds; the embedding comes from honcho-embed on dixie, through tether, and the answer comes back. The chosen role, aux, has a chain of two providers, dixie-9b then straylight-9b, each with a breaker showing closed; the first provider's answer leaves the chain at the right. Two failure arrows: any gate error of any kind, the budget or an uncalibrated answer, takes a dashed arrow from the gate to a pill reading fail-open, primary's chain, filtered for the request, and a second dashed arrow from that pill into the chain box, where the filtered chain is walked; a provider fault takes a dotted arrow from the first provider to the second. Request text image? private? force? Eligibility vision only with an image private: every provider local some breaker admits struck: no image, a private request vision primary aux delegation local Gate route over the three eligible roles one embeddings batch budget 250 ms honcho-embed on dixie, through tether the chosen role: aux any error kind · budget · uncalibrated fail-open: primary's chain, filtered for the request Chain: in order, first provider that answers dixie-9b breaker closed straylight-9b breaker closed provider fault answer

Walkthrough

The parity tests. On talos (go1.27.1), 2026-10-02:

=== RUN   TestGoldensReplay
--- PASS: TestGoldensReplay (0.01s)
=== RUN   TestInterfaceGoldens
--- PASS: TestInterfaceGoldens (0.00s)
=== RUN   TestFeatureGoldens
--- PASS: TestFeatureGoldens (0.02s)
PASS
ok      aec/internal/decide    0.033s

go test -count=1 -run 'TestGoldensReplay|TestInterfaceGoldens|TestFeatureGoldens' -v ./internal/decide. cmd/aec-decide adds TestGoldensThroughTheWire, which posts the same 64 records to the HTTP handler with each record’s own vectors standing in for the embedder, and requires the 97 decisions and every calibrated flag to match the golden answer.

What the mutation passes show. Each is a run of the package’s tests against one plausible bug at a time, on a scratch copy of go/, on talos. For decide, 22 of 22 mutants were killed:

# the bug tests that fail
1 ordinal thresholds not ordered (thetak = theta{k-1} + delta_k) TestGoldensReplay, TestStableNumerics
2 T applied twice (choice) TestGoldensReplay
2b T applied twice (score) TestGoldensReplay
3 SetEscapeHTML left on TestFeatureGoldens, TestInterfaceGoldens
4 zero-length tensor rejected TestAChangedRegisteredSchemaIsAnErrorNotAFallback, TestChoiceTieBreak and 17 more
4b tensor table sorted by begin only TestAChangedRegisteredSchemaIsAnErrorNotAFallback, TestChoiceTieBreak and 12 more
5 lone surrogate escape refused, not replaced TestGoldensReplay, TestInterfaceGoldens and 1 more
6 log1p replaced by log(1+x) TestStableNumerics
7 median rule > instead of >= TestScoreViews
8 at_least[k] = 1 - F_k TestGoldensReplay, TestScoreViews
9 FNV prime off by two TestFeatureGoldens, TestGoldensReplay and 2 more
10 n-grams over bytes instead of runes TestFeatureGoldens, TestHashEmbedderPassesTheGoldenChecks and 1 more
11 chain_count not capped at 8 TestFeatureEdges
12 repeated keys not detected TestInterfaceGoldens
13 x = [f ; e_q] instead of [e_q ; f] TestGoldensReplay
14 embedding vectors not unit-normalised TestGoldensReplay
15 blank() checks ASCII whitespace only TestFeatureEdges, TestInterfaceGoldens
16 b indexed by subset position TestGoldensReplay
17 choice tie-break takes the last maximum TestChoiceTieBreak
18 a space after Query: TestGoldensReplay
19 questions validated in map order TestInterfaceGoldens, TestValidateNamesTheFirstSortedQuestion
20 wrapper options not skipped TestFeatureGoldens

Mutant 4b depends on map order and so on chance, and was killed in both passes; one pass is not evidence that an intermittent mutant is dead. For internal/route and the llm retry rule, 60 of 60 were killed, grouped here by the property they attack:

property mutants count
which errors advance the chain (a 4xx that advances, a request fault that counts, a 401 or a 408 or a redirect taken as the request’s, refusals matched exactly, cancelled calls advancing, a local refusal counted) R1, R10, R11, R12, N5, N6, F5, F16, F25 9
privacy and eligibility (private text to the cloud, a mixed chain eligible, vision without an image, one eligible role still gated, an image-only request gated) R2, R6, R7, R9, F15 5
the breaker and its probe tickets (opens late, half-open admits all, release by a non-holder, stale failure restarts the cooldown, an unsent release missing, the gauge stale) R3, R4, N7, N8, F4, F4b, X3, F8 8
the gate (budget ignored, description drift unchecked, uncalibrated accepted, asked before the check, a failed check leaves it open, embedder named by the caller, a panic escaping, a late answer accepted) R5, R8, R13, N1, N2, N9, F2, F7 8
the Anthropic adapter’s refusal (counted against the breaker, taken as transport) N3, N4 2
the guard (an 8 MiB cap, a truncated body, a model-less POST passed, each refusal retried) F1, F1b, F17, G5, G6, G7 6
config and accessors (duplicate keys, duplicate entries, trailing JSON, unknown role with the gate off, embedder host unchecked or prefix-matched, accessors returning live state) F10, F11, F12, F13, F14, F14b, F18, F18b 8
clients and responses (the model not set per provider, nil responses, an unset key accepted) R14, F9, F9b, F6 4
the embedding cache (never stores, survives a weights change, stores the request’s text, unbounded, wrong width, a failed check keeps it, a store ignores the generation, a check that does not clear, a late answer cached) F19, F20, F21, F22, F23, F24, G1, G2, G3 9
the retry loop in llm (a permanent error retried) G4 1

Two of these need a particular test. The budget multiplied by 1,000 passes any test that simply waits, in this case for 250 s, so only TestTheBudgetBoundsTheGate, which bounds the gate’s wall time, kills it. And a failed check that leaves the gate open is invisible to a test whose embedder has the wrong width, because that embedder fails every request anyway; it takes an embedder with the right width and the wrong text.

The server starting, on straylight against dixie’s tether (2026-10-02 04:31 PDT; the binary is built on straylight, the server runs in the foreground of an ssh session under timeout 2400 and is stopped when the session ends):

aec-decide: weights py/data/decisions/jev-lite.safetensors (9dddfd5c43b6cd5d), embedder honcho-embed at http://dixie:11435, probes 8 x 1024
aec-decide: embedder check passed
aec-decide: listening on 127.0.0.1:8427

One request on the wire, from a script on straylight to a server started the same way, no proxy, no redirects (04:17 PDT, 2026-10-02). The question is the route head asked over three roles. The request:

{"state": "can you summarise this page for me and give it a title?", "questions": {"route": {"type": "choice", "instructions": "Which of the reader's model roles should handle this request?", "criteria": {"primary": "the main assistant: conversation, questions and short tasks", "aux": "a small fast model for chores: titles, page summaries, extraction", "local": "an on-premises model: the request contains private data that must not leave the reader's machines"}}}}

The status and the response:

200
{
 "answers": {
  "route": {
   "calibrated": true,
   "choice": "aux",
   "probabilities": {
    "aux": 0.9429440897769101,
    "local": 0.01052316928818246,
    "primary": 0.04653274093490745
   },
   "type": "choice"
  }
 },
 "model": {
  "embedder": "14e08cf5d572e18f",
  "weights": "9dddfd5c43b6cd5d"
 }
}

The two ids in model are the weights’ version and the embedder’s fingerprint; a span that records them can say which model made a decision. The same request with chapter 21’s exercise (c) edit, a trailing space after extraction in the aux description, returned:

409
{"error":{"kind":"SchemaMismatch","qid":"route","message":"does not match its registered schema"}}

and the 409 never reached the embedder, because validation precedes embedding. That is the status table of the wire: a malformed request is 422 (BadRequest), a registered question that does not match is 409, an embedder that is unavailable or does not match the weights is 503, a request with more than 64 questions is 422 before anything is embedded, a body over 2 MiB is 413 and a wrong method is 405. While the last embedder check failed every /v1/decide is a 503 carrying the check’s kind (EmbedderMismatch, or EmbedderUnavailable for anything untyped), until a later check passes; /health stays up. The check runs before the server listens, on by default, and every hour after (-check=false is for a stand-in embedder). The server also cuts a client that stalls: a read timeout of 30 s, an idle timeout of 2 min and the header timeout of 10 s, so a client that sends headers and a part of a body cannot hold a handler for ever. Uncalibrated and WeightsInvalid are 500 if they ever appear, because they are not a client’s error: the first is a gate’s refusal and does not come out of Decide, and the second stops the server from starting.

The A/B against laya-serve. Both servers and the client ran on straylight, with nothing touching the fleet’s llama.cpp or whisper services. aec-decide reached tether on dixie through the guarded embedder only. laya-serve ran on the CPU with one checkpoint (english) preloaded and 8 threads, bound to 127.0.0.1:8428, in the foreground under timeout, never detached, and the run ended with both ports and both processes confirmed gone. The 64 goldens’ requests were posted one at a time to each. Laya’s reply has no level and rounds its probabilities to four decimals; its score is an expected value (agent.py in the installed 0.3.22 reads round(exp_score, 4) and round(float(v), 4)). So the harness compares decisions: the choice name; for a score, the median level index computed from each side’s probabilities (for Laya the rounded ones); for a noul, the answer at p>12p > \tfrac12.

A/B on 64 golden requests, client straylight, 2026-10-02 04:31:40 PDT
  aec-decide http://127.0.0.1:8427: 64 answered, 0 errors
  laya-serve http://127.0.0.1:8428: 50 answered, 14 refused
  type     questions laya answered decide=stand-in   laya=stand-in  laya=decide
  choice          40            40              22              21           18
  score           27            13              22               4            3
  noul            30            30              29              13           12
  latency, median (ms) over the records laya answered, after the first: laya-serve 240.3 (its own inference 239.0), aec-decide 101.9
  aec-decide over all 63 records after the first: 92.8
  first request (ms): aec-decide 96.0, laya-serve 198.5

The table is a comparison and not a parity check, and the “stand-in” column says why. The goldens’ answers were generated by chapter 21’s stand-in weights over a hashed n-gram embedder, not by jev-lite.safetensors over honcho-embed. Of the 97 questions, 61 are on the registered heads (route, approve, risk, urgency) and 36 are ad hoc (tone, polite, question, topic), which jev-lite answers zero-shot. decide=stand-in is therefore the agreement of two different trained models on the same inputs, 22 of 40, 22 of 27 and 29 of 30, and nothing in it says the Go runtime is right or wrong. That is what the goldens’ replay and TestGoldensThroughTheWire are for, and they pass: each record’s own vectors go through the same code and come out as the golden decisions.

What the table does say is bounded. Laya refused 14 of the 64 requests with HTTP 400 and answered 50, all with the english checkpoint (the model field of every answered response’s routing object). All 14 refusals are the requests whose state is a JSON object containing a lone surrogate escape: laya’s serve.py (lines 716 to 719) answers 400 “request body contains an unpaired surrogate escape”, because Python cannot encode a lone surrogate to UTF-8, while jev-lite replaces it as Go’s decoder does. Neither is wrong; they are different contracts, and chapter 21 states the replacement. Those 14 requests carry 14 score questions and nothing else, so the score row is laya’s 13 answered out of 27, and laya=decide is 18 of 40 on choice, 3 of 13 on score and 12 of 30 on noul. The two models agree less with each other than decide does with the stand-in on choice (18 against 22 of 40), and that is a statement about two models trained on different data for different jobs: Laya’s english checkpoint was neither trained nor audited here, and jev-lite is four registered heads trained on 169, 174, 188 and 188 rows of the course’s synthetic set, labelled by a teacher model (chapter 21), plus a zero-shot path for everything else. It is not a statement about either runtime.

The latencies have a path each. aec-decide’s is straylight to dixie and back per request, the guard’s GET included, with all the texts of the golden request embedded in one batch and no cache. Laya’s is straylight’s CPU, 8 threads. Medians exclude the first request on both sides; Laya’s are over its 49 answered requests after the first, since a refusal takes a millisecond or two and carries no inference time, and aec-decide’s is given both over all 63 requests after the first (92.8 ms) and over exactly the 49 that Laya answered (101.9 ms), so the two sides are compared on the same records. Laya’s own X-Inference-Time-Ms is 239.0 ms of its 240.3.

The metrics a gate decision leaves. The lab’s TestGateFailsOpen runs two fail-open decisions with a 20 ms budget and an embedder that never answers once the check has passed, one public and one private, and prints the registry (talos, 2026-10-02):

        # HELP aec_route_decisions_total Routing decisions, by role taken and how it was chosen (gate, forced, single, fail_open, disabled).
        # TYPE aec_route_decisions_total counter
        aec_route_decisions_total{role="primary",source="fail_open"} 2
        # HELP aec_route_gate_seconds Time the routing gate took, embedding included, successful or not.
        # TYPE aec_route_gate_seconds histogram
        aec_route_gate_seconds_bucket{le="0.01"} 0
        aec_route_gate_seconds_bucket{le="0.025"} 2
        aec_route_gate_seconds_bucket{le="0.05"} 2
        aec_route_gate_seconds_bucket{le="0.1"} 2
        aec_route_gate_seconds_bucket{le="0.25"} 2
        aec_route_gate_seconds_bucket{le="0.5"} 2
        aec_route_gate_seconds_bucket{le="1"} 2
        aec_route_gate_seconds_bucket{le="2"} 2
        aec_route_gate_seconds_bucket{le="+Inf"} 2
        aec_route_gate_seconds_sum 0.040506053
        aec_route_gate_seconds_count 2
        # HELP aec_route_gate_errors_total Gate failures that fell open, by decide error kind, or budget when the latency budget expired.
        # TYPE aec_route_gate_errors_total counter
        aec_route_gate_errors_total{kind="budget"} 2
        # HELP aec_provider_requests_total Requests sent to a provider, by HTTP status, transport for no answer, or skipped when its breaker was open.
        # TYPE aec_provider_requests_total counter
        aec_provider_requests_total{provider="straylight-35b",code="200"} 1
        aec_provider_requests_total{provider="zai",code="200"} 1
        # HELP aec_breaker_open 1 while a provider's circuit breaker is open or half-open.
        # TYPE aec_breaker_open gauge
        aec_breaker_open{provider="dixie-9b"} 0
        aec_breaker_open{provider="straylight-35b"} 0
        aec_breaker_open{provider="straylight-9b"} 0
        aec_breaker_open{provider="straylight-vl8b"} 0
        aec_breaker_open{provider="zai"} 0

Both decisions were the fail-open role’s, both gate errors were the budget, and both gate times landed in the 25 ms bucket (the sum, 40.5 ms, is wall-clock and differs on every run; the counts do not). The two requests after them went to different places: the public one to zai and the private one, whose chain was cut down by the filter, to straylight-35b. The metric names are aec_route_*, aec_provider_requests_total and aec_breaker_open; they do not collide with chapter 23’s aec_router_*, and every label value is bounded (a configured role, one of five sources, or private in a router that skips the gate for a private request, a decide kind or budget, unchecked or other, an HTTP status or one of transport, skipped, unsent, refused, not_loaded, 200_error, and a configured provider name). No request text reaches a label.

The live run. The lab’s TestLive, run from straylight with AEC_LIVE=dixie (05:18 PDT, 2026-10-02; the client is straylight and the one request went to dixie’s llama.cpp router on port 11434), through route.Guard:

=== RUN   TestLive
    lab_test.go:344: dixie-9b (ornith-1.5-9b-uncensored, role aux): "pong", finish "stop", in 1.537s
    lab_test.go:307: zai: skipped (AEC_LIVE=dixie)
--- PASS: TestLive (1.57s)
PASS
ok      aec/labs/ch28    1.570s

The test read /v1/models on dixie before it chose, and the guard read it again before the request, which it sent with ?autoload=false. Straylight’s models are not read at all under AEC_LIVE=dixie. Had ornith-1.5-9b-uncensored not been loaded, the line would have been ... is not loaded on http://dixie:11434/v1; skipped, and no request would have been sent. The test allows the model 256 tokens: the 9b spends its first tokens thinking, and with a limit of 8 it ended with an empty answer.

Exercises

(a) A caller writes Force: "research", a sixth role that no config can hold, on a public request against the lab config. Which role and chain does the request get, what do aec_route_decisions_total and aec_provider_requests_total show, what does the decision carry, and why is a misspelt force not an error return? Then say what making research gate-routable takes.

Answer

No config can hold the role: LoadConfig and New both refuse a role outside the head’s five options, so Force never finds it. route looks the forced role up in cfg.Roles; a miss is not an error return but a decision: role primary (the fail-open role), source fail_open, and Err set to route: the forced role is not configured: "research" (ErrUnknownRole). The gate is not asked, so no aec_route_gate_errors_total series appears. The chain is primary’s, [zai straylight-35b], and a public request goes to zai. A probe in a scratch copy of the lab (talos, 2026-10-02, a fake zai that answers) printed aec_route_decisions_total{role="primary",source="fail_open"} 1 and aec_provider_requests_total{provider="zai",code="200"} 1, and nothing else of the two families. So a misspelt force is not refused: it is a fail-open request that carries its reason in Decision.Err, which the route policy_decision span records. A caller that wants a typo to be an error has to check Err. A private request would be cut to straylight-35b by the same filter as any fail-open one. Making research gate-routable means a new option in the registered question, which means retraining the head (chapter 21’s train_student.py) and new goldens and a new schema_hash. The set of options is closed for the reason the subset rule needs it closed: the gate asks over a subset of the head’s own options and nothing else.

(b) The gate’s budget is set to the one-text median, 30.26 ms, and 100 gate decisions are run against the real embedder. About what fraction fails open, and what would aec_route_gate_errors_total{kind="budget"} show?

Answer

About half. The median is the value that TT exceeds with probability 12\tfrac12, so P(T>b)≈12P(T > b) \approx \tfrac12 at b=mb = m, and the deadline wraps Decide, whose embedder call includes the guard’s GET, so the guarded-call median is the right one to compare. A budget at the median turns the gate into a coin flip and fail_open into the common case, and the counter shows it at once: budget climbs in step with aec_route_decisions_total{source="fail_open"}. At 250 ms the same table says the six-text 90th percentile is 115.16 ms, so the fail-open rate on time alone is bounded by about a tenth even in the cold case, and the A/B’s 63 requests had a maximum of 143.1 ms.

(c) A provider is down for 300 s. Requests arrive at one per second and each call to the dead provider times out after 10 s. With the default breaker (F=5F = 5, c=30c = 30 s), how many requests reach it, and how many request-seconds are spent waiting, with and without the breaker? Derive it first, then check against the simulation described in the Mechanism.

Answer

The fifth failure lands at o=(F−1)/λ+to=4+10=14o = (F-1)/\lambda + t_o = 4 + 10 = 14 s, so the 14 requests that arrived at 0 to 13 s were all admitted (a failure due at 14 s is recorded before the arrival at 14 s). Each probe holds the slot 10 s and the cooldown restarts, so probes begin at o+c=44o + c = 44 s and then every c+to=40c + t_o = 40 s: 44, 84, 124, 164, 204, 244 and 284 s, which is ⌈(300−14−30)/40⌉=⌈6.4⌉=7\lceil (300 - 14 - 30)/40 \rceil = \lceil 6.4 \rceil = 7. The total is 21 requests and 210 s of waiting. Without the breaker all 300 requests reach it and wait 3,000 s. A simulation with the committed Breaker and a fake clock (talos) printed 21 requests and 3 min 30 s. The formula F+⌈D/c⌉F + \lceil D/c \rceil gives 15, which counts neither the requests already in flight when the breaker opened nor the timeout that every probe pays.

(d) A private request arrives while the embedder on dixie is unreachable (the connection is refused, so the embedder reports EmbedderUnavailable and does not run out the budget). With the lab config, give the exact increments to aec_provider_requests_total{provider,code} and aec_route_gate_errors_total{kind} that the request leaves, and the error Complete returns, in two cases: (i) the straylight-35b breaker is closed and the provider answers; (ii) the breaker is open. Which provider never appears in either family, and why?

Answer

The gate is asked in both cases (the eligible roles are aux, delegation and local, three, so there is no single shortcut) and fails open at once, so aec_route_gate_errors_total{kind="EmbedderUnavailable"} goes up by 1 and aec_route_decisions_total{role="primary",source="fail_open"} by 1 in both. The walk then runs over primary’s chain after the allowed filter, which has already dropped zai (not local) and leaves [straylight-35b]. (i) The breaker admits, the call goes out and is answered: aec_provider_requests_total{provider="straylight-35b",code="200"} +1 and Complete returns the answer, no error. (ii) Take refuses, so the walk records {provider="straylight-35b",code="skipped"} +1, the chain ends with no provider tried, and Complete returns ErrNoProvider (its message: route: every provider in the chain refused, failed or is open); nothing was sent anywhere. zai appears in neither, not even as skipped: a provider the filter removed is not in the walk, so no series is created for it, and the absence of a zai series is the evidence that the text never went near the cloud. I ran both cases in a scratch copy of the lab (talos, 2026-10-02) with an embedder that passes the start-up check and then returns EmbedderUnavailable, and the families held exactly those lines and no others (the gauge aec_breaker_open is not among them; the probe opened the breaker directly, and the gauge is set by the walk when a call ends). A hung embedder instead of a refused one would show kind="budget" after the budget, with the same provider lines. The lab’s TestGateFailsOpen prints the first case’s counters for a budget failure and TestEligibilityThroughRoute asserts the second case’s ErrNoProvider.

(e) The Go loader’s size check reads e.hi < e.lo || uint64(e.hi-e.lo) != size. The second clause compares the byte span to the shape’s byte count, so what does the first add? Build the smallest header that needs it, and say why the Python reader has no such clause.

Answer

The subtraction is done in signed integers and then converted: a span of −4-4 becomes 264−42^{64} - 4 as a uint64. A shape of [262−1][2^{62} - 1] has 4(262−1)=264−44(2^{62} - 1) = 2^{64} - 4 bytes, which fits in 64 bits, so byteSize reports it as fitting and the two numbers agree. A tensor with that shape and data_offsets [b,b−4][b, b - 4] at the end of the buffer passes e.lo != expect and e.hi > len(buf) too, and the loader would go on to make([]float32, 2^62 - 1). The committed case is byte_count_wraps_to_minus_four. Python’s integers do not wrap: hi - lo is −4-4 and 4 * math.prod(shape) is 264−42^{64} - 4, so hi - lo != 4 * math.prod(shape) refuses it alone. A plain [b, b - 4] entry with shape [0][0] does not need the clause, since 264−4≠02^{64} - 4 \neq 0; end_before_begin passes without it. I deleted the clause in a scratch copy of go/ (talos) and ran TestWeightsGoldens: only byte_count_wraps_to_minus_four fails, with Load panicked: runtime error: makeslice: len out of range.

(f) Laya rounds probabilities to four decimals and has no level, so the A/B takes the median from the rounded distribution. Construct a four-level distribution whose exact median differs from the median of its rounded probabilities, and say whether the goldens’ near-tie rejection protects the A/B.

Answer

Take p=(0.49996, 0.00007, 0.49997, 0)p = (0.49996,\ 0.00007,\ 0.49997,\ 0). The exact cumulative sums are F0=0.49996<12F_0 = 0.49996 < \tfrac12 and F1=0.50003≥12F_1 = 0.50003 \ge \tfrac12, so the median level is 1. Rounded to four decimals, p=(0.5000, 0.0001, 0.5000, 0)p = (0.5000,\ 0.0001,\ 0.5000,\ 0) and F0=0.5000≥12F_0 = 0.5000 \ge \tfrac12, so the median read from the rounded distribution is 0. Each rounding moves a probability by at most 5×10−55 \times 10^{-5}, so any cumulative sum within a few times that of 12\tfrac12 can cross. The goldens’ near-tie rejection (NEAR_TIE = 1e-6 in py/tinygpt/decide/goldens.py) rejects margins fifty times smaller, and in any case it is applied to the stand-in’s distributions, not to Laya’s, so it bears on Laya’s cumulative sums not at all. There is no protection: the A/B’s score agreement can include rounding flips, at most on the records where a cumulative sum lies within about 5×10−55 \times 10^{-5} per term of 12\tfrac12. That is one reason the harness compares decisions and the chapter draws no conclusion from the score row.

Lab

The mechanics are the earlier labs’: go/labs/ch28/lab.go declares Router, with Route, Complete, Stream, Providers and Check, and the New factory type, and checks at compile time that the reference (route.Router) and go/labs/ch28/mine have the same API. You write mine/route.go: New, Check, Route, Complete, Stream and Providers. Run

make lab CH=28 IMPL=mine

Provided: decide (so the runtime and its goldens are not part of the exercise), route.ParseConfig and route.LoadConfig, route.Breaker with its tickets, route.NewProvider (a Provider literal has no breaker, and the tests trip breakers through Providers(), so your New builds its providers with it), route.NewMetrics, the guard, and testdata/routes.json. That file is the reader’s Hermes roles with the two substitutions described in the Mechanism, and aecd (chapter 40) loads a file of this shape through route.LoadConfig and route.Clients, which guards every local provider. The five tests that run offline, on llm.Fake providers and a stand-in embedder that answers the gate against the golden weights:

  • TestTheConfigMirrorsHermes: the file has the head’s five roles with its exact descriptions and the chains the chapter describes, fail_open is primary, the budget is 250 ms, zai is the only non-local provider, and only straylight-vl8b and straylight-35b see. The unmodified config must build, and the same config with a trailing space on aux must be refused by New (D13).
  • TestEligibilityThroughRoute: what each request shape may be routed to. A text request has four eligible roles, not vision. An image request has four, not aux. A private request has three, not primary or vision. Tripping dixie-9b and straylight-9b leaves two; tripping straylight-35b too leaves a private image request one role, taken as single; and a private text request with every local breaker open is fail_open with ErrNoEligibleRole, and Complete returns ErrNoProvider without ever reaching zai.
  • TestGateFailsOpen: a budget that expires, the private fail-open chain with its cloud provider cut, the metrics shown in the Walkthrough, a disabled gate, and a weights file that does not load.
  • TestAFailedCheckShutsTheGate: an embedder with the right width and the wrong text fails the check; a request after it fails open to primary, uncalibrated, and the chain still walks.
  • TestChainAdvance: a 429 and one of the router’s refusals advance the chain with call.Model set per provider; a 422 returns at once and the next provider is not called; five faults open a single-provider chain’s breaker and its role leaves eligibility.

TestLive skips without AEC_LIVE. With AEC_LIVE=straylight or dixie it reads /v1/models on that host only and sends one guarded request to each of that host’s providers whose model is loaded at that moment, through a role whose chain is that provider alone, so the log names the provider that answered; it wakes nothing. zai runs only under AEC_LIVE=zai with ZAI_API_KEY set (checked by name). With AEC_IMPL=mine the starter fails each of the five offline tests with chapter 28 lab: not implemented and none panics. The reference takes 0.05 s on talos.

Further reading

  • Michael T. Nygard, Release It! Design and Deploy Production-Ready Software, 2nd edition, Pragmatic Bookshelf, 2018: the stability patterns that chains and breakers come from, and the book Fowler’s note credits for the circuit breaker.
  • Martin Fowler, CircuitBreaker, bliki, 6 March 2014: the three-state description that Breaker follows, including the half-open trial call.
  • Jeffrey Dean and Luiz André Barroso, The Tail at Scale, Communications of the ACM 56(2), 74–80, 2013: deadlines and hedging against latency tails; the gate’s budget is the deadline case.
  • The Qwen3-Embedding-0.6B model card: get_detailed_instruct, with no space after Query:, and the example scores that CheckEmbedder ties the embedder to.
  • llama.cpp, tools/server/README.md at b29c606: POST /v1/embeddings (line 1504), the per-request ?autoload=true|false (1795) and the status.value states of /v1/models (1855 to 1866), the three facts the guard rests on.
  • Laya, laya/serve.py at commit 6d942c9: the /v1/systemone server the A/B talks to, with its _has_lone_surrogate refusal. The A/B ran the 0.3.22 installed on straylight, whose serve.py was read there; the link is the upstream file at a pinned commit.

results matching ""

    No results matching ""