conformal gates
Suppose someone in a team channel writes: "Looks good to me, let's ship it tomorrow." Before an AI teammate ever writes a word back, it has to answer a chain of tiny, invisible questions. Should it speak, react, or stay silent? Did that message commit to a task, or was it casual chatter? Is the request easy, medium, or hard? If the agent replies "Want me to open the PR now?", should the interface attach quick Yes and No buttons?
In an active team workspace at Ando, those small routing checks add up to tens of thousands of hosted classifier calls every day. The same pattern shows up across almost every AI product: routing prompts between a fast and frontier model, triaging incoming support tickets, or pre-filtering prompt injection and abuse. Every network hop adds 250 to 1,000+ milliseconds of latency and timeout risk on the hot path, yet nobody wants to train, deploy, and maintain a bespoke PyTorch model for every yes/no gate.
We built conformal-gate (Rust compiled to a single zero-dependency WebAssembly binary, plus a pure-TypeScript zero-WASM serving runtime) so a tiny local model inside our backend or edge isolate can answer clear-cut, repetitive calls in microseconds while sending every uncertain call to the hosted model. The rule is strict: it only skips the network call when finite-sample math proves its error rate stays inside your budget. Once certified, the serving state strips down to a 6.3 KB gzipped snapshot that runs identically in browsers, V8 isolates, Electron, and Cloudflare Workers.
- warm tenant SC (shadow · 2% α)
- 62.7%
- 24h error on SC (target 2% α)
- 0.23%
- local p50 (Rust / V8 prod)
- 9 µs / 0.14 ms
- zero-WASM ServingSnapshot
- 6.3 KB
From chat models to dedicated decision engines
The way software teams run small AI decisions has gone through three stages.
First, chat models playing classifier (2023 to 2025). Teams asked small generative models like Haiku, Flash-Lite, or GPT-mini to print a JSON object, parsed the string, retried whenever a brace was missing, and paid for output tokens. Latency sat between 300 and 2,500 milliseconds, and each extra check added another network timeout to user-facing replies.
Second, dedicated single-pass decision engines (2026). Instead of writing text one token at a time, a dedicated decision engine reads the context once and scores a fixed set of choices in a single forward pass, returning calibrated probabilities directly. At Ando we run Typesafe's Jev across our agent routing checks. In November 2026, Google launched the Gemini Decisions API (gemini-decision-1) along the same lines: read a shared payload once (up to 262,144 tokens of text or media), score up to 1,000 independent yes/no (noul), multiple-choice (choice), or rubric (score) questions in one pass, bill zero output tokens, and respond in 150 to 250 milliseconds.
Third, a local certified fast path in front of the decision engine. Dedicated decision engines solved broken JSON and output-token billing, yet they still cannot beat the speed of light. Every check leaves your server, crosses the network to a GPU cluster, and returns 150 to 560 milliseconds later. Meanwhile, real products and workspaces repeat themselves constantly. Once Jev or Gemini has labeled a few hundred inputs for a tenant, the obvious cases do not need a datacenter anymore. conformal-gate sits directly in front of those hosted decision engines as Stage 0.
How the local fast path works
Every incoming event hits the local gate first, inside the same backend process or edge isolate. Clear-cut calls short-circuit in memory at zero network cost; uncertain calls escalate to the hosted teacher as usual; and 5% of traffic rides a blind spot-check rail to the teacher regardless of confidence so an e-CUSUM drift monitor can prove the local model has not gone stale.
Why standard conformal prediction broke
Before jumping into formulas, consider a simple example. Imagine a gate inspects 1,000 messages and promises your team: "At most 5% errors." Because the gate is cautious, it only handles 100 of those messages locally and passes the other 900 to the hosted model. On the 100 messages it answered locally, it gets 20 wrong.
If you divide 20 mistakes by all 1,000 messages, the overall error rate is 2%. On paper, 2% beats your 5% goal. Yet on the 100 messages the local gate actually decided, it was wrong 20% of the time, or one in five.
That exact failure happened to us in our first prototype. We built a standard Mondrian conformal predictor targeting 5% error and replayed it chronologically against 1,966 real agent-participation decisions from Ando. Across all 1,966 messages, overall error was just 1.9%. Because those messages were hard (simple rules for direct mentions and DMs had already filtered out easy cases), the gate only short-circuited 8.2% of them (161 messages), and 38 of those 161 disagreed with the teacher: a 23.6% error rate on the traffic we actually skipped. On our deterministic stress suites at 5% target, marginal Mondrian CP broke even harder: 10.9% conditional error on clean separable data, 49.9% on pure noise, and 82.9% on diurnal bursts.
How a tiny local model reads inputs in microseconds
A common instinct here is to train a small neural network in PyTorch and deploy it behind a GPU or CPU endpoint. The catch is operational weight: maintaining a separate training pipeline, model registry, serving cluster, and drift dashboard for every tiny yes/no gate costs more engineering time than the latency it saves.
Instead, conformal-gate is written in pure Rust and compiled to a single zero-dependency WebAssembly binary (~256 KB gzipped for the full crate — single-gate trainer, multi-predicate bundles, k-NN OOD guard, and ConformalSemanticCache). It loads directly inside an existing Node or edge backend, with no Python runtime and no external service to manage. How does a tiny binary classify text in 9 to 35 microseconds?
- Text fingerprints instead of a giant vocabulary. Rather than maintaining a dictionary of every word ever seen, the extractor chops text into individual words, two-word pairs (like
"want me"), short four-letter chunks (like^shipandping$so "shipped" and "shipping" share overlap), and simple structural clues like message length, punctuation, URLs, and code blocks. Each clue hashes via 64-bit FNV-1a into one of 8,192 fixed numeric buckets. Different input fields get different hash seeds, so the word "saved" in a user's question never collides with "saved" in an agent's reply. If the caller already has a dense embedding vector, the model accepts that too. - Learning from probabilities, not just yes or no. When a decision engine scores an input, it does not just say "skip." It returns calibrated soft probabilities like
0.94 skip, 0.06 speak. Those probabilities carry far more signal than a bare label. A fast online linear model (multinomial logistic regression) adjusts its weights to match them via KL divergence, keeping a bounded replay buffer so memory stays flat. - Zero-WASM V8 serving (
PureServingGate). Strict V8 isolates (serverless V8 runtimes, locked-down edge workers, and strict CSP environments) often disallow dynamic WebAssembly instantiation altogether. Because a certifiedServingSnapshotis just sparse non-zero weights plus per-class thresholds (~6.3 KB gzipped), ourconformal-gate/servingentry point reproduces the exact 64-bit FNV-1a feature hashing, sparse dot-product, softmax, and LTT checks in pure TypeScript with zero WASM and zeronode:*imports — serving live production traffic in 0.14 ms p50 with bit-for-bit identical probabilities.
How we prove the local model is safe to trust
Getting a fast local prediction is the easy half. The hard half is deciding when to trust it. Two quiet traps ruin naive accuracy checks in production:
First, you cannot grade a student while they are still editing the exam. If you measure accuracy on examples a model already trained on, or while its weights keep moving, its score looks better than reality. To prevent that leak, conformal-gate runs two models side by side. One model (serving_model) stays completely frozen while we grade it on brand-new teacher answers. Meanwhile, a second model (trainer_model) keeps learning in the background. When a fresh candidate freezes, it only replaces a healthy serving model via scale-invariant paired promotion: it has to beat the incumbent's empirical acceptance on the exact same pre-update out-of-sample rows, regardless of confidence-scale shifts.
Second, checking your score after every input breaks ordinary statistics. Imagine flipping a coin and checking after every single flip whether it looks biased, stopping the moment you hit a lucky streak. Textbook confidence intervals assume you chose your sample size in advance. When an online gate checks its accuracy on every request, continuous peeking lets unsafe thresholds slip through.
To make continuous peeking mathematically honest, conformal-gate uses a betting test (a one-sided mixture supermartingale governed by Ville's inequality). Picture starting with $1 and betting against the skeptic's claim: "this gate's true error rate is worse than my target α." Under a fair game, if the gate really is worse than α, no betting strategy can turn $1 into $40 more than 1 time in 40, no matter how often you check your balance.
We run that betting test at 32 descending geometric confidence levels from 0.999 down to 0.25 per predicted class (extending below 0.50 lets 50- to 150-class tasks certify confident predictions well above uniform 1/K without paying any multiple-testing penalty under fixed-sequence Learn-then-Test; Figure 5 zooms into the binary 0.995 → 0.50 band). Every newer model generation g gets a telescoping slice of a lifetime error budget (δ / (g * (g + 1)), which sums to at most δ even across infinite future generations). Cached per-class quantiles and thresholds keep hot-path predict() strictly O(1). If local features cannot separate the classes, no level crosses the line and the gate stays quietly at 0% short-circuit rather than guessing.
What actually broke in live production (and how 0% became 62.7%)
The math above looks clean on paper. The most useful part of building conformal-gate was everything that broke once we deployed it across isolated per-tenant gates in live serverless production — tens of thousands of daily evaluations with real traffic skew, container restarts, and multi-generation promotion races.
1. Output-space coarsening + the prior-inverting class-weight bug
Our highest-volume classifier at Ando categorizes what each incoming message did to the conversation across eight pragmatic intents (chatter, informs, asks, decides, commits, changes, blocks, resolves). On our first replay, trying to gate all eight classes directly with hashed n-grams produced 0.0% short-circuiting. That honest abstention saved us from corrupting live traffic, yet it looked like linear text features had hit a hard ceiling.
Then we stepped back and asked what the caller actually needed to skip a network hop. Most messages are either ignorable chatter (skip) or plain updates (informs); only the minority that mutate team state (action) need the fine six-way breakdown. Collapsing the Stage 0 gate to three coarse routing buckets — certifying skip and informs locally at α = 2% while always escalating action to the teacher — changed the learning problem from subtle pragmatics into a clean routing boundary.
Even after that coarsening, something strange happened in live production: across active tenant snapshots, zero gates certified. Tracing the live weights exposed a subtle calibration bug. Our online SGD trainer had been weighting updates by inverse class frequency — a textbook trick to boost macro-F1 on imbalanced benchmarks. In a real workspace where 75%+ of messages belong to one bucket, inverse weighting distorted predicted posteriors so badly that the model's highest-confidence predictions were no longer the cleanest ones, starving LTT of any certifiable threshold. Switching to unweighted cross-entropy with exact global L2 decay unblocked live certification immediately.
2. "Zombie candidates" and exact mathematical futility retirement
Once live certification started working, a second failure appeared in the tenant census: several of our highest-volume production gates were stuck at 0% short-circuiting despite thousands of teacher calls. Their background challengers had already frozen and entered the calibration slot — and then sat there indefinitely without promoting or retiring.
The cause was pure martingale arithmetic. At a strict α = 2% error budget, Ville's supermartingale punishes early errors hard. If a freshly frozen challenger suffers three or four unlucky misses in its first 100 calibration calls, its log-wealth plunges so far that even if every single remaining call in its budget agreed with the teacher, it could never cross the ln(1/δ) certification line. Because the gate only rotated candidates when the budget ran out (or never retired an uncertified candidate early), a mathematically dead challenger occupied the slot as a "zombie," blocking a much better background trainer from ever getting tested.
The fix requires zero heuristics and preserves exact statistical validity: after each calibration observation t with e misses and remaining budget B − t, evaluate the exact best-case future log-wealth ln M(e, B, α) assuming zero future errors. The instant ln M(e, B, α) < ln(1/δ), the challenger is mathematically incapable of certifying — retire it immediately and promote a fresh candidate from the background trainer.
3. Minority-class starvation and three drift bugs
Before shipping live, our deterministic replay and stress suites caught four more subtle statistical bugs:
- 20× minority-class calibration speedup. Once a majority class certified and entered active mode, we restricted all calibration updates to the 5% uniform audit slice to avoid selection bias. That quietly threw away 95% of teacher labels for uncertified minority classes that were still going 100% to the teacher. Updating an uncertified class's threshold grid directly from its teacher calls (while keeping global drift detection strictly on unbiased 5% audits) stays valid and jumped post-warmup short-circuiting by +18.6 to +22.7 percentage points at 0.00% error across our stress suites (
separable51.6% → 74.3%,diurnal_burst48.3% → 66.9%,rare_class_starvation47.0% → 67.9%). - Unscaled ACI collapse. Adaptive Conformal Inference (ACI) tightens the allowed ceiling when a 5% spot-check misses and relaxes it when spot-checks agree. With a raw step size (
aci_gamma = 0.05), a single expected error at a 5% target slammed the effective ceiling down 10× to its floor, throttling participation short-circuiting from 27.4% down to 2.9%. Scaling the step relative totarget_alpharecovered 9.4× coverage at 1.79% error. - A drift alarm that degraded too softly. Our first detector (Page-Hinkley, which merely halved
αon drift) was blind to the target budget and kept short-circuiting 85% of traffic even while drifted. Replacing it with an e-CUSUM likelihood detector tuned directly toαmakes the gate fail closed immediately (100% teacher) the moment spot-checks look worse than budget. - Post-drift weight inertia. Even after failing closed, the background trainer still held pre-drift weights and replay rows, fighting the new distribution. Calling
reset_for_drift()when e-CUSUM trips liftedconcept_shift(100% abrupt label inversion) short-circuiting by +32.9 percentage points (29.7% → 62.6%) and recovered with 0/510 post-recovery errors.
4. Live serverless production: persistence and split V8/Node invariants
On day one of live production, our containers ran cleanly with zero errors — yet 100% of calls stayed permanently in cold_start because ephemeral serverless workers recycled before any single process saw 60 consecutive calls for one tenant. Sharing snapshots across containers and splitting fast V8 serving from async Node training surfaced five real systems requirements:
- Stripped snapshots and bounded blob storage. Raw full snapshots (1.68 MB JSON) exceeded database document limits. Stripping frozen model replay buffers cut snapshot size ~10×, gzipping shrank trainer state to ~122 KB (zero raw text, only hashed weights and quantiles) in blob storage behind a tiny metadata row, and
exportServingSnapshot()stripped serving state down to 6.3 KB gzipped. - Fail-open hydration and async persistence. Cold hydration is strictly time-bounded and fails open to the teacher; snapshot uploads drain asynchronously after the response returns so persistence adds 0 ms to user-facing latency.
- Compare-and-swap eviction for corrupt blobs. Monotonic write guards (only higher
teacher_callsoverwrite lower ones) can trap a corrupt blob forever; a CAS eviction guard clears broken blobs without clobbering healthy in-memory gates. - Generation fencing on split-process escalations. When a lightweight V8 isolate evaluates a frozen
ServingSnapshotand forwards escalations to a separate Node trainer, every non-audit escalation must carry theservingGenerationthat evaluated it. If Node has already promoted to generationg+1, it must drop generationg's non-audit escalations — otherwise an incomplete sample filtered by an older model can bias calibration for the newer model. - Per-batch drift revocation. Long background sweeps cannot cache a serving snapshot for the entire job. Refreshing snapshot metadata per batch guarantees that an e-CUSUM drift trip halts short-circuiting immediately rather than waiting for the sweep to finish.
- Lineage fencing, OOD safety nets, and untrusted edge callbacks. Three practical guardrails came from studying peer systems and auditing the edge-to-server trust boundary:
teacher_versionfencing resets calibration fail-closed whenever a prompt or teacher model changes;confidence_floorrefuses to count low-confidence teacher guesses as ground truth; a training-only k-NN cosine OOD guard (EmbeddingOodGuard) catches off-manifold dense embeddings before linear softmax overconfidence can short-circuit; and the central trainer re-scores immutableserving_modelon current-generation escalations so an untrusted edge client can never forge calibration scores or sabotage e-CUSUM drift detection.
| Live production & trace summary | Scope | Short-circuit | Error on SC | Local p50 | Status |
|---|---|---|---|---|---|
| Message-act routing (3-bucket, warm tenant) | Prod shadow · α 2% | 62.7% | 0.23% | 0.14 ms | Certified |
| Message-act routing (fleet-wide incl. cold tenants) | Prod shadow · 24h | ~9% | 0.23% | 0.14 ms | 0 errors · 0 drift |
| Task complexity (easy / med / hard) | Prod shadow · α 2% | promoted | 0.00% | 0.34 ms | Certified |
| Agent participation (3-class replay, n=2,659) | Active replay · α 5% | 39.4% (967) | 2.69% (26/967) | 9.1 µs | Certified |
| 8-class pragmatic intent (uncoarsened, n=1,175) | Active replay · α 5% | 0.0% (0) | 0.00% (0/0) | 13.3 µs | Abstained |
Notice the split between a warm tenant and the full fleet: 62.7% short-circuiting on a warm workspace, versus roughly 9% across the full fleet including newly created or quiet workspaces that have not crossed warmup yet — measured in live shadow mode right before flipping active V8 serving on. Across tens of thousands of evaluations in that 24-hour window, the runtime recorded zero errors, zero drift trips, and 0.14–0.34 ms p50 local inference — roughly 1,800× faster than a 254 ms hosted decision call.
"Jev does not reason" and gating composed decision trees
In November 2026, Nathan Flurry at Rivet published a practical field note titled Jev Does Not Reason. When his team asked Jev to assign a ticket directly across a compound rubric like [SEV1, SEV2, SEV3, SEV4], accuracy was mediocre because a single-pass decision engine intentionally spends zero reasoning tokens. What worked was splitting every compound decision into 2 to 13 atomic yes/no Jev questions (security vulnerability? data loss? production down? blocked with no workaround? something broken?) and putting the priority logic into ordinary deterministic code.
That sounded like an obvious win for running five separate conformal gates, one per predicate. Instead of guessing, we built MultiPredicateGate (single-pass shared feature extraction plus correlated request-level auditing so forced audits stay at 5% instead of compounding to 1 - 0.95^m = 40%) and benchmarked it head-to-head against gating the composed final verdict on a 2,500-ticket Rivet-style Severity tree (α = 5%):
| Eval harness (2,500-ticket 5-predicate Severity tree) | Full-ticket SC | Predicates saved | Tree error | Local p50 / p95 |
|---|---|---|---|---|
| 1 gate on composed SEV1..SEV4 | 66.9% (1,673) | 66.9% | 0.00% | 1.8 / 2.2 µs |
5 separate gates (Bonferroni + 0.5% SEV1 no) |
35.9% (898) | 55.5% | 0.00% | 3.0 / 4.4 µs |
| 5 separate gates (top-to-bottom cascade) | 35.9% (898) | 55.5% | 0.00% | 3.1 / 4.2 µs |
The benchmark exposed two subtle mathematical truths that beat our first intuition:
- The Bonferroni sample-complexity tax. To guarantee 5% total error across
m = 5separate gates, each gate has to prove a 5× tighter ceiling (1% each). That multiplies the warmup data each head needs byO(m / α)(~450 to 900 samples per head versus ~90 for one composed gate), cutting full-ticket short-circuiting nearly in half (35.9% vs. 66.9%, even after early futile-gen-1 retirement lifted 5-gate SC from 30.5% to 35.9%). - The intersection trap. Bounding each check separately controls overall errors across all tickets, not the error rate restricted to tickets where all five checks short-circuit at once. Suppose Check 1 makes almost all of its mistakes on one rare kind of billing ticket (just 1% of all traffic), and Check 2 only accepts that exact kind of ticket: each check looks safe on its own, yet tickets where both checks short-circuit together can fail far more often than
α.
The winning hybrid architecture: use decomposed atomic yes/no questions plus deterministic TypeScript code as the teacher (for accuracy, inspectability, and Rivet-style backtesting), and wrap the composed final verdict with one ConformalGate (1.9× higher full-ticket skip rate, 1.7× faster with O(1) cached thresholds, and directly certified on the composed output). Reserve MultiPredicateGate for genuinely independent multi-label outputs (such as parallel routing flags or tool-group selections) where no single composed class exists.
One caveat from benchmarking atomic decomposition across both architectures: splitting a rubric into nine yes/no checks works because single-pass decision engines score parallel noul heads in one forward pass at zero output tokens (~254 ms). When we tried the same nine-boolean JSON rubric on a fast autoregressive chat model (with zero thinking budget), emitting 126 output tokens instead of 6 added +200 ms p50 (849 ms → 1,055 ms) and lowered accuracy (59/64 → 56/64). Atomic binary decomposition is specifically a parallel-probe decision-engine superpower, not an autoregressive JSON win.
Beyond chat: three patterns where conformal gates shine
Although we built conformal-gate for team chat agents at Ando, the pattern applies anywhere an AI system sits in front of repetitive, skewed traffic with asymmetric mistake costs:
- LLM model tiering (
fast_modelvs.frontier_model). Set a tight per-class bound onfast_model(α = 0.01) so complex prompts are never downgraded silently, while letting obvious lookups, format conversions, and short edits bypass the router LLM in microseconds. - Support ticket triage (
billing,bug,how_to,human_handoff). Combine free text (subject, body) with structured numeric signals (plan tier, message length, prior ticket count) and serve the certified 6 KB snapshot directly at the edge viaPureServingGate. - Prompt-injection and abuse pre-filtering (
allow,flag,block). Set a strict bound onallow(α = 0.005) so novel jailbreaks never slip through; when an attacker shifts phrasing, the 5% blind audit trips e-CUSUM and fails closed to the full moderation model automatically.
In practice, the split between an async trainer (or shadow rollout) and zero-WASM edge serving takes a few dozen lines of TypeScript:
import { createConformalGate } from "conformal-gate";
const routerGate = await createConformalGate({
name: "llm-tier-router",
classes: ["fast_model", "frontier_model"] as const,
mode: "active", // Start in "shadow", verify 24h disagreement, then flip
maxDisagreement: 0.05,
classAlphas: {
fast_model: 0.01, // Never silently downgrade a hard prompt
frontier_model: 0.05, // Extra headroom when escalating to frontier
},
auditRate: 0.05,
featurize: (req) => ({
fields: {
prompt: req.prompt.slice(0, 1_200),
tool_names: req.tools.join(" "),
},
numeric: {
prompt_chars: req.prompt.length,
has_code_fence: req.prompt.includes("```") ? 1 : 0,
turn_depth: req.historyLength,
tool_count: req.tools.length,
},
}),
teacher: async (req) => routeWithDecisionEngine(req),
});
import { PureServingGate } from "conformal-gate/serving";
// Runs in Workers, V8 isolates, and strict CSP with zero WASM.
const gate = PureServingGate.fromSnapshot(certifiedSnapshotJson);
const pred = gate.predict(featurize(req));
if (pred.should_short_circuit) {
return pred.predicted_label; // ~0.14 ms · 0 network hops
}
// Escalate uncertain inputs + 5% audits; fence by generation.
const teacherVerdict = await routeWithDecisionEngine(req);
ctx.waitUntil(reportObservation({
input: req,
teacherVerdict,
wasAudit: pred.is_audit,
servingGeneration: pred.model_generation,
}));
return teacherVerdict.label;
How we test it: eval harness and shadow verification
Inspired by Parallel's Search Eval Harness, we wrapped conformal-gate in a deterministic binary (conformal-gate-eval) with eight stress suites (separable, imbalanced_routing, pure_noise, concept_shift, diurnal_burst, rare_class_starvation, boundary_drift, and cascaded_binary_tree), head-to-head baselines against always_teacher, naive_softmax, and marginal_mondrian_cp, FNV-1a trace fingerprinting so config mismatches never sneak into diffs, and explicit drift-phase metrics. Every major improvement above — +32.9 pp drift recovery, +22.7 pp minority calibration, unweighted CE + global L2, futility retirement, 15× lower boundary-drift error under adaptive auditing, and the composed-vs-Bonferroni tradeoff — came from running the harness or auditing live shadow telemetry rather than theorizing in a design doc.
Formal verification: proving the gate fails closed
A bug inside a short-circuit gate does not throw an exception — it silently skips the teacher LLM and breaks the statistical bound you promised. Ordinary unit tests only check the inputs you remembered to write down, so we ran four formal and mechanized checks across the Rust core, unsafe WASM ABI, zero-WASM TypeScript runtime, and multi-container persistence protocol:
| Verification layer | Tool | What is proved |
|---|---|---|
| Rust math & invariants | Kani (CBMC) | 23 proofs across all 7 core Rust modules (ood.rs, conformal.rs, model.rs, gate.rs, features.rs, semantic_cache.rs, bundle.rs): fail-closed NaN/±Inf/f32::MAX handling, anytime-valid LTT risk bounds, softmax simplex normalization, adaptive-audit propensity conservation, Bonferroni budget division, and OOB panic freedom. |
| Unsafe WASM ABI & parser | Miri + recursive fuzzer | All 25 unsafe extern "C" entrypoints in wasm_abi.rs verified UB- and leak-free, plus structure-aware recursive JSON fuzzing across populated snapshots of all four persisted formats. |
| Rust ↔ TypeScript parity | Differential Vitest suite | 320+ randomized scenarios (including NaN, ±Inf, ±f32::MAX, overflow logits, OOD embeddings, and teacher-version fencing) proving exact agreement between Rust ServingGate and zero-WASM PureServingGate. |
| Distributed persistence | TLA+ / TLC | 19 checks (main + 9 negative mutations + 9 reachability witnesses; 25.1M states generated, 3.93M distinct) across two concurrent Node containers, a V8 serving reader, numeric warm-start priors, drift shutdown, stale-generation prior fencing, and CAS corrupt-blob eviction. |
This was not theater — the checkers caught 11 real bugs across Rust and TypeScript plus one cross-layer protocol trap:
- Fail-open
NaNon OOD embeddings (Rust & TS). InEmbeddingOodGuard::is_ood, IEEE-754 makesmax_sim < thresholdevaluate tofalsewheneverthresholdisNaN, silently accepting an out-of-distribution input instead of escalating. Fixed with!(max_sim >= threshold)and explicit finiteness checks (andquantile_sortedclamping). f32::MAXvector collapse (Rust & TS). Squaring a dense embedding withf32::MAXentries overflowedf32norm accumulation toInfand divided to[0, 0]instead of preserving unit direction. Fixed acrossood.rs,features.rs,semantic_cache.rs, andts/serving.tsviaf64max-abs rescaling.- TypeScript softmax overflow divergence. On extreme overflow logits, zero-WASM
PureServingGatereturned[NaN, ...]where Rust fell back to uniform[1/K, ...]. Randomized differential testing caught it immediately, along with explicitexpectedTeacherVersion: nullparity. - Out-of-bounds WASM panics &
Inf + (-Inf)auditNaN. Six class-index accessors inconformal.rscould panic on an out-of-range class index instead of failing closed, andadaptive_audit_schedulecould produceInf + (-Inf) = NaNon non-finite thresholds. - Cross-layer version-bump livelock found by TLA+.
set_teacher_version()resetsserving_generation = 0, which collides with monotonic(serving_generation, drift_active, teacher_calls)storage CAS if a multi-container persistence layer does not also track lineage epoch — caught before wiring teacher-version bumps into our production store.
Prior art, the 2026 landscape, and where this sits
None of the statistical primitives inside conformal-gate were invented in a vacuum. The library sits at the intersection of four active research threads that converged rapidly between 2021 and 2026:
- Selective risk control and anytime-valid e-processes. Geifman & El-Yaniv (2017) formalized selective classification with guaranteed conditional risk; Angelopoulos et al. (2021) turned non-monotone risk control into finite-sample multiple hypothesis testing in Learn then Test (the reason selective risk cannot use the tighter monotone Conformal Risk Control bound directly); and Gui, Jin, & Ren (2024) extended distribution-free selection to foundation models in Conformal Alignment. The closest statistical ancestors to our continuous-peeking loop are Xu, Karampatziakis, & Mineiro (NeurIPS 2024), who brought testing-by-betting e-processes to active risk-controlling sets, and Hultberg, Zachariah, & Ribeiro (2026) on anytime-valid conformal risk control over growing calibration streams.
- Online adaptation and nonparametric risk-drift detectors. Gibbs & Candès (2021, 2024) introduced Adaptive Conformal Inference (ACI and multi-rate DtACI), and Angelopoulos, Candès, & Tibshirani (2023) reframed online coverage tracking as Conformal PID Control. On drift monitoring, Podkopaev & Ramdas (ICLR 2022) drew the crucial distinction between benign covariate shift and harmful risk shift, and Shin, Ramdas, & Rinaldo (2024) formalized nonparametric e-detectors (e-CUSUM and e-SR) — the direct theoretical basis for our
α-aware fail-closed tripwire. - LLM routing and the 2026 wave of conformal cascades. Early routing frameworks like FrugalGPT (2023) and RouteLLM (2024) proved 40–85% API savings with preference-trained routers, while Narasimhan et al. (2024) merged cascades with speculative decoding for generative latency. Between late 2025 and mid-2026 (surveyed in Moslem & Kelleher 2026), several papers converged on formal guarantees for cascades: Huang et al. (2025) framed edge-cloud offloading as conformal alignment; Dou, Lian, & Li (2026) introduced multi-tier Conformal Cascade via set collapse (explicitly noting that tightening its
1 − Kαunion bound to1 − αrequires a selection-preservation condition beyond marginal coverage — the denominator trap in Figure 3); Guo, Wu, & Yiu (ACL 2026) built RouteNLP, pairing conformal cascading with targeted distillation on clustered escalation failures (reporting 58% cost reduction and >2× the gain of untargeted distillation); and two open-source peers — Rida's TRACER (2026) and Tomer Glick's Jevstiller — proved out practical trace-based local surrogates for LLM and Jev classification, directly inspiring our v0.1.0 embedding OOD guard,teacher_versionfencing,confidence_floor, and boundary diagnostics. - Non-uniform active auditing. Zrnic & Candès (ICML 2024) showed in Active Statistical Inference that uniform random auditing leaves statistical power on the table: propensity-weighted active sampling concentrates expensive teacher checks near uncertain boundaries while keeping finite-sample and asymptotic validity intact.
| System / paper | Guarantee | Online distillation | Drift revocation | Runtime & footprint |
|---|---|---|---|---|
| RouteLLM (2024) | Heuristic scalar threshold | Offline Arena preference | None | Python / PyTorch server |
| Edge-Cloud CAb (2025) | Cloud-aligned conditional MHT | Static student | None | Research PyTorch |
| Conformal Cascade (2026) | Multi-tier set collapse (1−Kα) |
None (black-box LLMs) | None | Multi-tier LLM API |
| RouteNLP (2026) | Conformal threshold init | Failure-clustered LoRA/distill | Periodic retrain | GPU cluster (~387 ms p99) |
| TRACER (2026) | Parity gate + k-NN OOD | Offline trace surrogates | Parity monitor | Python / scikit-learn |
| conformal-gate (v0.1.0) | Anytime-valid LTT e-process + futility + warm priors | Online soft-KL + paired swap + opt-in hard replay | α-aware global & boundary e-CUSUM + wipe |
1–9 µs Rust / 0.14 ms V8 · 6.3 KB + semantic cache |
Seeing the full map made our real niche — and the highest-leverage next upgrades — clear. Most conformal cascade papers assume a static pre-trained student with an offline calibration split; most closed-loop distillation routers assume Python and GPU serving stacks. conformal-gate packages anytime-valid LTT, e-CUSUM fail-closed drift recovery, and online distillation into a 6.3 KB zero-WASM edge artifact. Translating the 2024–2026 literature directly into v0.1.0, we implemented and measured four concrete extensions:
- Hierarchical warm-start priors (
createWithPrior/with_prior_model). Export a fleet model's weights viaexportPriorModel()— stripping sparse hashed n-gram weights (sparse_entries: []) when crossing tenant boundaries so zero workspace tokens ever leak — and initialize a new tenant with that numeric prior frozen as generation 1 behind a brand-new empty per-tenant calibrator (zero prior thresholds, zero leakage). Aligned tenants skip cold-start warmup and certify >40 calls earlier at0%error; 100%-inverted misaligned tenants never certify gen 1, retire it early via futility checks, adapt togen >= 2, and hold0bad short-circuits. - Propensity-weighted two-stratum active auditing (
adaptiveAudit: true). Inspired by Zrnic & Candès (2024) and Xu et al. (2024), opt-in adaptive auditing samples near-threshold accepted predictions (p < τ + 0.25(1 − τ)) at2.0× audit_rateinto an unthinned boundary-stratum e-CUSUM, while core/deferred traffic audits at0.75× audit_rateand boundary audits are server-side Bernoulli-thinned back to0.75× audit_ratebefore updating global LTT/Mondrian calibration (exact Ville's inequality). On ourboundary_driftsuite (75% stationary core, 25% boundary flips at row 700), conditional disagreement dropped 15× — from3.59%(45/1,254) to0.26%(3/1,163) — andimbalanced_routingshort-circuiting jumped from61.3%to69.5%(at1.37%error). We keep it opt-in (default: false) because quiet-then-noisy diurnal bursts trade ~1 extra daytime audit (0.00%→3.71%error, still inside the 5% bound). - Feature-only hard-boundary replay (
hardReplayCapacity). Inspired by RouteNLP (2026), an opt-in bounded hard-replay buffer retains mispredicted or low-margin examples (p_true < 0.70) and runs feature-only margin passes with class intercepts anchored to uniform FIFO replay — avoiding the prior-inversion bug we hit with inverse class weights. Measured honestly: zero regression on skewed 93/5.5/1.5% workloads, and kept opt-in because short synthetic streams already fit inside the 512-row uniform FIFO. - Anytime-valid semantic caching (
ConformalSemanticCache). Standard LLM semantic caches pick an arbitrary cosine-similarity cutoff like0.92. Reusing our bounded embedding engine,ConformalSemanticCachecertifies similarity across a 24-point descending grid (0.998 → 0.65) using pre-insert filtration-safe evaluation + Ville's mixture martingale, and trips e-CUSUM to purge stale entries and bump generation automatically on staleness or poisoning drift.
Two genuinely open directions remain for future versions: swapping single-rate ACI for multi-rate DtACI or Conformal PID control under smooth continuous drift, and offline neural distillation for shared semantic tasks where hashed lexical n-grams hit their representational ceiling.
What this changes, and where it stops
Real multi-tenant production traffic makes both the upside and the boundaries of conformal gating clear:
- Sub-millisecond certified routing works in production without a bespoke ML stack. On our highest-volume classifier, coarsening the output space and fixing class-weight calibration lifted a live tenant from 0.0% to 62.7% short-circuiting at 0.23% disagreement in 0.14 ms p50 inside V8 isolates — zero runtime errors and zero drift trips across tens of thousands of daily evaluations.
- Per-tenant cold start is real — and now has a safe bridge. In multi-tenant production, a heavy-tailed share of new or quiet
(tenant, gate)pairs take a long time to cross 300+ calls on their own, sitting honestly at 0% short-circuiting. Warm-starting new tenants from a shared fleet prior viacreateWithPriorcuts certification time on aligned workspaces while preserving per-tenant anytime-valid safety on divergent ones. - Lexical features still have a ceiling. Nuanced semantic checks, subtle emoji interpretation, and multi-step reasoning over long threads still require dense embeddings (via
input.embedding,EmbeddingOodGuard, orConformalSemanticCache) or the hosted teacher. When local features cannot separate the classes, the gate refuses to certify and abstains at 0%. - Be honest about the immediate ROI. When your teacher is already an inexpensive single-pass decision engine, the first payoff is tail latency (0.14 ms vs. 250–850 ms) and deterministic fail-closed safety; raw dollar savings compound mostly at high volume or when gating slower autoregressive LLMs.