← Harness Engineering From First Principles

Multi-Model Routing Without Benchmark Leakage

Freeze routing rules before held-out evaluation and account for all model calls and selection costs.

A maintenance service can run a small local model, a hosted model with an allowance and a more expensive hosted model. The engineer proposes using the first model for easy work and escalating difficult cases. On a familiar benchmark the router looks excellent: it chooses the expensive model precisely when the cheaper one would fail. The immediate question is not how clever that rule is. It is how the router knew which cases were difficult before their answers were available.

Model routing is a control policy with an information boundary. It can use registered task features, admitted intermediate artifacts and qualified checks. It cannot use the final answer key, a future failure or a benchmark-specific mapping learned from confirmation results while claiming prospective performance. This chapter builds routing as another governed policy inside the common harness, with the full cost of deciding and escalating recorded.

Evidence status. Provisional technical draft. The task-routing demonstration D27-ROUTE-01 is implemented and executed (examples/pi-harness-lab/src/routing.ts; test/routing.test.ts, 12/12 pass offline): admission filtering, deterministic-first and free-before-paid preference, availability and quota skipping, unauthorized-fallback refusal, hard-budget enforcement, retry bounds, provider-failure vs wrong-result distinction, escalation envelopes, and reproducible decisions with journaled recommendation/admission receipts. Model names below are illustrative identities, not product recommendations; costs are scripted accounting units, not tariffs, and no quality or savings claim is made. Pi integration remains tied to the R02 inspected 1.6.0 artifact, not a newly qualified routing API. The sealed-corpus comparison (E27) is PROPOSED and remains EXPERIMENT PENDING.

27.1 The route is more than a model name

A route binds provider/model identity, effective generation settings, context construction, tool protocol, retry behavior and verification. Changing the model while retaining an incompatible prompt or tool surface is not a clean capability comparison. Changing the entire route is a legitimate system comparison if the bundle is declared and its effects are not attributed to model weights alone.

The simplest baseline uses one development-selected route for every eligible task. It is easy to reproduce and has no routing classifier cost. A stronger static baseline may map registered task classes to fixed routes, provided that mapping is chosen on development and frozen. Dynamic routing must beat the strongest reasonable such policy under the same authority and resource constraints, not merely beat an artificially expensive always-use-the-largest-model default.

Separate routing at admission from escalation after evidence arrives. An admission router sees the task and allowed pre-execution features. An escalation policy can see the first model’s draft and a check result, but has already paid for them. They answer different questions. A classifier that predicts difficulty before execution cannot be credited with information obtained only by generating and testing a candidate.

Record the actual sequence of route decisions. The manifest names the initial route; subsequent admitted changes create bounded child episodes or continuation steps with their own identities. Do not overwrite the manifest’s model field with whichever model produced the final text. That would erase both earlier spending and the policy’s decision path.

27.2 Define a route’s admissible domain before ranking it

Some constraints are hard eligibility conditions: required data locality, tool/schema compatibility, output requirements, effect restrictions, qualified context limits and available budget. A route outside those conditions cannot become permissible because its predicted quality is high. The selector ranks only after admission filters, just as history selection filters before similarity ranking.

A local model is not automatically qualified to execute local tools. Provider placement and effect authority are separate. A hosted model with strong benchmark scores is not automatically authorized to receive proprietary source. The host decides what data projection may leave its boundary under the actual task policy. Provider credentials remain in the configured gateway, not model-visible tool arguments.

Compatibility needs evidence. Register which tool schema version, context projection and structured output parser each route supports. If a route cannot produce the required evidence references, the choices are a qualified adaptation or refusal, not silently relaxing the evaluator. A route may be adequate for drafting a hypothesis and inadequate for the final task deliverable; record that narrower role.

The same applies to service availability. A quota failure can trigger a declared fallback only if the new route is independently eligible. An outage does not authorize sending protected data to another provider. If no admissible route remains, report blocked or incomplete execution under the task contract. Honest refusal is preferable to an unrecorded privacy, resource or evidence exception.

27.3 What a router may know

Use features whose availability can be established before the decision: task type, admitted file sizes, declared language, required tools, bounded source statistics and prior-only experience within the registered domain. Feature extraction itself has cost and a version. If a model reads the repository to produce a difficulty score, its requests and source exposure are part of routing, not free preprocessing.

Do not use hidden test outcomes, future repair counts, evaluator labels or task IDs that encode the preferred route. A route table memorizing benchmark instance IDs is a retrieved answer about model choice. New instance IDs on the same answer template do not repair that leak. Apply the family and dependency grouping method of Chapter 22 to the routing corpus as well as the experience store.

An escalation signal is an observed check under a declared procedure. Examples include invalid structured output, unsupported citations or a failed reproduction gate. Model confidence is an estimate that needs development calibration; it cannot be assumed to identify its own errors. A verifier from the same model family may share the mistaken premise. Record procedural, model, data and evaluator separation explicitly.

Feature omissions can be informative. If the router cannot establish the task class or estimate the input bound, it should use an admitted conservative fallback or abstain. Filling unknown fields with values that make a cheaper route look eligible biases both the decision and the later learning record. Missingness belongs in the evidence account.

27.4 Routing must survive its own budget checks

Every model request passes Chapter 17’s atomic reservation rule. The router cannot reserve the cheap call, wait for failure, and then assume the strong call will fit. The policy must declare whether it reserves an escalation envelope in advance or admits escalation only from remaining reconciled capacity. The first is conservative; the second can produce an explicitly incomplete route when headroom is exhausted.

Unknown usage is especially consequential across providers. If a timed-out first call may still be billed, retain its reservation and block exposed root admissions until safe reconciliation. Sending the same task to a second provider because the first did not answer can multiply unknown spend. An optional provider-side account cap is a different enforcement boundary and must be qualified independently.

Retries, context retransmission, verification and routing calls all count. If the second model receives a summary of the first model’s work, that summary is a derived claim with provenance requirements. If it receives the full context, account for retransmitted input. If it receives neither, it may repeat the investigation. The economic comparison should observe these alternatives rather than assume escalation is costless reuse.

Pin a model per admitted episode as the simple proposed integration. Pi performs its existing execution inside that episode. This avoids assuming that changing a model field halfway through a session preserves conversation semantics or tool compatibility. A future mid-session switch requires a separately verified public interface and a test of its effective behavior against the pinned Pi artifact.

27.5 A small routing contract

// Implemented in examples/pi-harness-lab/src/routing.ts (D27-ROUTE-01, executed).
interface RouteDecision {
  taskId: string;
  policyId: string;             // frozen policy identity
  policyDigest: string;         // digest of the frozen policy
  featureDigest: string;        // digest of the pre-decision features used
  selectedRouteId: string | null;
  phase: "admission" | "escalation";
  triggerEvidenceRefs: string[]; // check receipts that triggered escalation
  budgetReservationId: string | null;  // Rule P hold, or null when refused
  decision: "ADMITTED" | "REFUSED" | "UNKNOWN";
  reason: string;
}

The host computes the admitted route from the frozen catalogue and feature snapshot; the model can only propose an ID where the policy allows that. The effect broker separately checks operations later requested by the selected episode. Changing model identity never widens those grants. The evaluator receives all attempted routes, effective settings and independent outcome evidence.

Preserve proposed versus executed identity. A router may prefer route B but fail to reserve it, then use route A under a registered fallback. The result belongs to the complete policy and its actual path. Crediting the unexecuted B recommendation with A’s success or failure would corrupt future estimates. Record both recommendation and admission receipts.

The interface does not require a new routing service. A pure selector and a few host journal entries may suffice. A remote service adds availability, authentication and version-consistency questions; adopt it only when a concrete deployment requirement justifies them.

27.6 Worked example: cheap-first is not automatically cheap enough

All costs below are hypothetical units and the arithmetic is exact — it illustrates cost accounting, not a measured saving. Route A generation costs 1; route B generation costs 5. A candidate check costs 0.4 per generated candidate, the final independent validation costs 0.6 per task, and a dynamic routing decision costs 0.2. Suppose the frozen policy escalates 30% of tasks after running A. This escalation fraction is assumed for the arithmetic, not a measured detection rate or success probability.

Always-A costs 1 + 0.4 + 0.6 = 2 per attempted task. Always-B costs 5 + 0.4 + 0.6 = 6. Cheap-first routing costs 0.2 + 1 + 0.4 + 0.30 × (5 + 0.4) + 0.6 = 3.82. The second candidate check is charged on escalated tasks. Final validation at 0.6 is performed once on the selected final artifact only; intermediate candidates receive the separate 0.4 candidate check, not another final validation charge. Omitting the first failed candidate, its check or the routing call would make the policy look cheaper than it is.

Now compare a task-independent static mixture. Running B on 45.5% of tasks and A on 54.5% costs 0.455 × 6 + 0.545 × 2 = 3.82 on average under these assumed fixed costs. It has the same expected cost without paying to run A first on every B-bound task. This is not a recommended production randomization policy; it is a useful matched-cost control. A development-selected class-based static mapping may be stronger still.

Dynamic routing must demonstrate that its information directs expensive work to cases where it improves verified outcomes. Lower cost than always-B is insufficient. If the dynamic policy and static mixture have similar quality with adequate precision, the simpler policy may be preferable. If the detector misses difficult cases, the router can save money while silently reducing quality.

The example also reveals what cannot be inferred. Thirty percent escalation does not mean thirty percent initial failure, perfect failure detection or eventual success. The final evaluator must measure those outcomes independently. Correlated checks can make cheap-first appear confident while leaving precisely its undetected errors in the final artifact. Cost arithmetic cannot supply missing quality evidence.

Average cost is not the reservation for one task

The 3.82 value is a cohort expectation under the assumed escalation fraction, not a hard per-task ceiling. A task that actually escalates costs 0.2 + 1 + 0.4 + 5 + 0.4 + 0.6 = 7.6 in the example. A non-escalated task costs 2.2. Reserving only 3.82 for every task would prevent some of the very escalations the policy claims to support. Use a common per-task envelope that admits the registered path, or explicitly study the incomplete outcomes produced by a smaller envelope. Average-cost matching and individual resource admission are different constraints and must both be reported.

A hypothetical 200-task cohort makes the matching concrete. Sixty escalations give 200 × 2.2 + 60 × 5.4 = 764 units. A static mixture using B on 91 tasks and A on 109 gives 91 × 6 + 109 × 2 = 764. Those counts are constructed arithmetic inputs, not experimental results. They show how a finite cohort could match total generation/check costs without pretending every task consumed its cohort average.

Fairness also concerns who receives the stronger route. A task-independent mixture can be randomized before outcomes, while the dynamic policy uses its permitted features. A class-based static mapping is calibrated on development. The final comparison tests whether the dynamic information is worth its overhead and duplicated first attempt. It does not merely ask whether B is better than A on cases B was selected to handle.

Follow one escalation through the evidence boundary

Suppose A returns a patch with a citation to a real file but an unsupported line range. The candidate checker reports an evidence-refusal receipt under its pinned procedure. If the registered escalation trigger includes that code, the host first reconciles A’s actual usage, verifies remaining budget and current route eligibility, then admits B in a fresh episode. B receives the task, admitted source projection and the precise check failure, labelled as evidence about A’s candidate rather than as an authoritative diagnosis of the underlying bug.

B’s correct result does not erase A’s failure or expense. Both episodes and the route transition remain in the run’s evidence. If B returns the same unsupported citation, record the common miss; two identical answers do not override the checker. If a later independent evaluator finds the checker was wrong, preserve its original receipt and append the correction with scope and availability, rather than silently recoding the earlier escalation as unnecessary success.

Now change the schedule: A times out with unknown usage before the check can run. The permitted route is not simply try B. Under the root uncertainty rule, unresolved consumption can block another admission. The host records incomplete execution and reconciliation. This may reduce service availability, but the alternative would claim a bounded budget while making unobserved parallel expenditures. A different provider-side reservation mechanism would need its own qualified contract.

27.7 Benchmark protection includes route construction

Create the task/group split before route calibration. Development can choose prompts, routing features, thresholds, available model identities and fallback rules. Development-validation can qualify fixed components. Final confirmation assesses the complete frozen route policy without feeding outcomes back into it. The custodian exposes only the task data each admitted execution is permitted to see.

If model identity changes during the study, record the drift and apply the registered rule. A provider model label may not identify immutable weights. Interleave arms and record exposed fingerprints/settings where available, but do not claim that interleaving eliminates drift. A changed model or tariff can require a new study version rather than averaging incompatible conditions into one apparently precise estimate.

Repeated use of a public benchmark can guide human route design even without a machine-readable answer leak. Record prior exposure and use new sealed material for confirmation when the design has adapted to those results. Fresh private variants challenge specific memorization paths but do not establish absence of model pretraining exposure.

Avoid an oracle-best arm in the primary comparison. Choosing whichever route happened to succeed after seeing all final outcomes is an unattainable prospective policy unless that information is independently available before dispatch. It can be reported as a labelled exploratory upper-bound calculation, with the cost of all sampled routes, but never as the router’s achieved completion rate.

27.8 E27: test information value, not model reputation

The research question is whether a frozen dynamic policy improves verified outcomes at matched total cost over strong static alternatives. The primary hypothesis is a practical completion gain at a predeclared cost target. The plausible alternative is no gain because routing and duplicate work consume the apparent savings or its features fail to predict which route helps.

Arms are the strongest development-selected single route, the strongest registered class-based static mapping, a matched-cost task-independent mixture where meaningful, and dynamic admission/escalation routing. A shuffled-assignment control is a secondary ablation: permute route assignments only within predeclared matched eligibility strata, preserving route counts while breaking the intended task-feature association. If no valid permutation exists, mark the shuffled-assignment contrast NOT ESTIMABLE in that stratum, report coverage and retain the fixed primary dynamic-versus-static estimand. Do not replace it with an outcome-selected control or violate eligibility to manufacture a permutation. Oracle-informed routing belongs only to clearly labelled diagnostics, not achievable treatment arms.

Independent variables are routing policy and predeclared task strata. Primary dependent variable is task PASS with execution ACCEPTED at the common cost target. Secondary endpoints include actual spend, escalation rate, missed-error rate, route refusals, latency, review minutes and exposure-policy violations. Task fixtures and answer groups are versioned; no held-out labels enter feature construction or policy tuning.

Register provider account/cap/quota policy identities, scope, retention and exhaustion behavior alongside total monetary/call/token/time budgets, all routing and candidate verification costs, provider/model identities, context/tool compatibility, uncertainty handling, task/repository analysis units and paired clustered intervals. Freeze sample size, repetitions, practical margin, secondary multiplicity and stopping rules before confirmation. Any safety breach fails its separately qualified predicate; a quality gain does not waive it.

A dynamic gain requires the primary registered interval and cost criterion, not a favourable comparison picked from several targets. No gain with adequate precision supports the static default for this domain; broad uncertainty is inconclusive. Threats include model/judge correlation, unobserved provider changes, biased task classes and hidden benchmark exposure. EXPERIMENT PENDING.

27.9 Local, allowance-based and paid routes share an accounting problem

The escalation threshold is a tunable policy parameter. On development, compare thresholds using the complete route cost and independent final labels, then freeze one or a small registered sensitivity set. The threshold cannot be selected from whichever confirmation curve gives the largest apparent improvement. If the detector is recalibrated after model or prompt changes, it creates a new policy identity and qualification obligation.

Audit the feature path as carefully as the label path. An innocent-looking field such as expected repair depth may have been computed from a full solution trace. A cached task-family label may come from a prior failed benchmark run. Each feature therefore needs a producer, availability time, allowed transformation and source dependency closure. The router’s input digest establishes which features were used, while provenance establishes whether they were allowed.

For a negative control, supply a synthetic future-derived feature with a known prohibited source. Admission must reject it before routing; the model does not get a chance to promise to ignore the leak. A valid pre-decision feature should still pass, so refusal of every feature cannot qualify the pipeline. Such cases test information eligibility, not the eventual accuracy of the difficulty predictor.

A local route may avoid an external token invoice while consuming hardware time, electricity, setup and operator attention. An allowance-based hosted route may have a zero marginal charge until a quota or credit boundary is reached. A paid route may have predictable unit pricing but variable retries and context cost. These are accounting possibilities, not current product facts; use actual dated terms in a real study.

Report both the operator’s realized cash outlay and the registered resource/opportunity-cost account. Do not replace either with an invented universal price. A study using existing hardware can state that its purchase cost is sunk for that decision, while another deployment may need to buy capacity. The question determines the relevant cost boundary.

Routing can also change assurance cost. A cheaper generation model may need more verification or human review. A more capable one may reduce rework yet still fail required process checks. Compare complete routes through independent acceptance, not advertised model prices or unverified answer fluency. Chapter 28 develops that economic boundary in detail.

27.10 Implementation obligations and the next decision

Operational performance can depend on queues as well as model quality. A static route with slow average generation may have predictable capacity, while a dynamic policy concentrates demand on a scarce escalation route. Record queue wait separately from active model time and enforce admission backpressure. Do not let an external queue silently extend the declared run deadline or create unbounded pending reservations.

A separate load qualification can replay a frozen synthetic arrival schedule with scripted services. Measure admitted work, refusals, pending holds and settlement after cancellation. That deterministic infrastructure test answers whether the policy respects its queue/resource contract; it does not establish live model quality. A live comparison under changing load must balance or block arrival conditions across arms and report the remaining confound, rather than attribute all latency to model routing.

Keep the fallback policy explicit when a route is saturated. Waiting, using a qualified alternative or refusing may each be legitimate under different user constraints. Selecting among them is part of the frozen route policy, and its costs and failed deliveries belong in the primary intention-to-run account.

The implementation specification requires a versioned route catalogue, pre-decision feature capture, atomic resource admission, pinned episode creation, protected per-route observations and independent evaluation. D27-ROUTE-01 implements the catalogue, feature digests, admission with Rule P envelopes, pinned per-episode routes, and journaled observations (all deterministic properties); cross-model execution, SDK integration and live qualification remain future work. Reuse the existing host, Pi adapter, state and evidence contracts rather than implement another model execution loop. Verify actual public SDK interfaces before adding a cross-model or mid-session mechanism.

The scripted routing fixture below is executed for the admission layer — unavailable quotas and exhausted routes skipped, unknown usage blocking admission, forbidden data egress refused (unauthorized kinds never eligible), missing capability or compatibility evidence skipping the route, hard-budget refusal including unknown costs, retry bounds, ineligible escalation refused, and honest refusal with journaled recommendation/admission receipts when nothing fits — with independently specified expected refusals and positive controls. What remains pending is the live performance evaluation, not the admission qualification.

Routing is one lever within harness engineering, not its defining thesis. It is useful only insofar as it improves the task’s complete verified outcome under the user’s actual constraints. The next chapter asks what counts as cost, what counts as a reliable completion and how to report their relationship without hiding failed work.

Previous: Chapter 26: Predict, Test, Promote, or Revert.

Next: Chapter 28: The Economics of Reliability.