⚑ 1. The Operational Problem: The "Routing Tax" in Multi-Turn Agent Loops

In autonomous agent workflowsβ€”such as coding harnesses, data engineering pipelines, and customer support fleetsβ€”an agent task is rarely a single prompt. It is a multi-step loop executing 20 to 50 intermediate turns: inspecting directory trees, running linters, generating diffs, linting SQL queries, and translating syntax errors.

Monolithically dispatching every turn to frontier reasoning models ($15.00 to $60.00 per million output tokens) is financially unsustainable. However, naive solutions introduce a cure that is often worse than the disease: The Routing Tax.

The "Routing Tax" Defined: When an architecture uses an auxiliary LLM (e.g., Orca, RouteLLM's LLM-judge, or LangChain ModelSelector) to classify prompt intent before picking a model, it adds 300ms to 1,200ms of Time-To-First-Token (TTFT) to every turn and bills auxiliary input/output tokens. In a 30-turn agent session, auxiliary routing adds 15 to 30 seconds of pure latency and consumes hundreds of thousands of overhead tokens.

In CPU microarchitecture, processors do not issue main memory (DRAM) read cycles for every instruction; they inspect an ultra-low-latency L1 cache in 1 clock cycle. If an L1 cache hit occurs, execution proceeds with zero memory-bus overhead. Cascade routing for agent fleets requires the exact same structural hierarchy: never spend a 500ms network round-trip or token budget just to decide where to send an unambiguous query.

Prior Art & Systems Engineering Synthesis

The academic foundations of model routing and cascading are well-established:

The contribution of this work is not a new mathematical theory of routing optimality, but rather an uncompromising systems-engineering synthesis for production agent runtimes. Most published routers exist as heavy Python services introducing tens to hundreds of milliseconds of overhead, or require training MLPs whose weights rapidly rot as provider model APIs evolve. The Krusch Cascade Router packages these concepts into a production-grade, zero-dependency TypeScript implementation: providing an ultra-low-latency deterministic CPU L1 gate (<15Β΅s), zero-retraining database centroids, speculative parallel hedging, and real-time stream degeneration guards.

πŸ›οΈ 2. The Multi-Tier Cascade Hierarchy

The Krusch Cascade Architecture structures model dispatch into an explicit, multi-tier execution funnel:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ INCOMING PROMPT / AGENT TURN β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ STAGE-0: SYNTACTIC CPU GATE (krusch-pre-router) < 15 Β΅s β”‚ β”‚ β”œβ”€ Rank 0: Coarse Prompt Manipulation Filter (Basic Injection Keyword Heuristic) β”‚ β”‚ β”œβ”€ Text Compaction & Normalization (pruneText: zero-regex-backtrack) [$0.00] β”‚ β”‚ β”œβ”€ Knowledge Boundary Detector (Closed-World vs Open-World Reasoning) β”‚ β”‚ β”œβ”€ Dual-Anchor Scan Window (Head 4k + Tail 4k chars: O(1) memory & CPU bounds) β”‚ β”‚ └─ Deterministic Precedence Matcher (Structure > Lexical > Key Anchor > Domain) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ [Clear Syntactic Match] [Ambiguous / Open Chat] β”‚ β”‚ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ FAST-PATH SPECIALIST DISPATCH β”‚ β”‚ STAGE-1: NEURAL CENTROID ESCALATION β”‚ β”‚ (Code, SQL, Math, Closed-World) β”‚ β”‚ (krusch-context-mcp) < 50 ms β”‚ β”‚ β€’ Edge Specialist Pool (e.g. Qwen, β”‚ β”‚ β€’ Local cosine distance against β”‚ β”‚ Gemini Flash, DeepSeek Flash) β”‚ β”‚ 768d/1536d cluster centroids β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ [Specialist Match] [High Complexity] β”‚ β”‚ β”‚ β–Ό β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ SPECULATIVE PARALLEL HEDGING & DYNAMIC EXECUTION ENGINE β”‚ β”‚ β”œβ”€ Borderline Complexity (Score ∈ [0.25, 0.70]): Optional hedged pre-warm of Heavy β”‚ β”‚ β”œβ”€ Fast Model Stream: Buffer first N tokens (N = 5) β”‚ β”‚ β”œβ”€ Early Confidence Gate: Calculate linear P = exp(logprob); abort if P < Ο„ (0.85) β”‚ β”‚ β”œβ”€ Mid-Stream Degenerate Loop Guard: Repetitive N-grams & entropy collapse abort β”‚ β”‚ └─ Self-Healing JSON Cascade: Instant fallback on malformed structural payloads β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ SUCCESS: COMMIT TURN & USAGE β”‚ β”‚ HEAVY / FRONTIER ESCALATION β”‚ β”‚ β€’ Cleanly abort hedged branch β”‚ β”‚ β€’ Await already-warm heavy stream β”‚ β”‚ β€’ Record latency & token telemetry β”‚ β”‚ β€’ Frontier Reasoning Tier (o1/Claude)β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚑ 3. Stage-0: Deterministic Syntactic CPU Gate (<15¡s, $0.00 Tax)

The foundation of the cascade is the Stage-0 Syntactic Gate, open-sourced in krusch-pre-router. Written in pure TypeScript with zero runtime dependencies and zero network calls, it runs on CPU in under 15 microseconds, achieving over 66,000 QPS per core.

A. Precedence Hierarchy & The "Honest Miss"

The critical design rule of Stage-0 is the Honest Miss: dispatch to fast-path only when syntactic or structural anchors are unambiguous; otherwise, pass cleanly to Stage-1. Over-confident heuristic classifiers that misroute ambiguous queries are disastrous; Stage-0 prevents this via strict rank ordering:

Precedence Rank Rule Class Inspection Logic & Signatures Routing Action
Rank 0 Prompt Manipulation Filter Coarse keyword signatures (DAN, basic template overrides, ignore previous instructions). Hard Abort / Frontier Safety Isolation
Rank 10 Custom Specialist Overrides Tenant-specific regex rules, custom keywords, or explicit developer routing overrides. Configured Custom Specialist
Rank 20–24 Structural Rules Triple-backtick fences (```ts, ```python, ```sql), JSON/XML schema blocks, Myers unified diff headers (@@ -1,4 +1,4 @@), stack traces. code specialist pool
Rank 30–34 Lexical Anchors SQL DDL/DML keywords (SELECT ... JOIN, CREATE TABLE), LaTeX mathematical equations, POSIX shell syntax. code or factual_stem specialist
Rank 40–50 Domain Keywords Biomedical, legal citations, financial ledgers, spatial reasoning terminology. Domain Specialist Pool
Rank 99 Syntactic Miss Conversational ambiguity, philosophical dialogue, multi-hop reasoning, open-ended prose. Escalate to Stage-1 Neural Centroid
Important Caveat on Rank 0 Safety Gating: Rank 0 is a fast, defensive syntactic filter designed to catch naive template overrides and known injection strings on CPU for $0.00 before wasting tokens. It is not an adaptive, bulletproof prompt injection defense. Sophisticated adversarial attacks require model-level alignment, system prompt hardening, and output sandboxing.

B. Knowledge Boundary Detection: Closed-World vs. Open-World

The Knowledge Boundary Router (detectKnowledgeBoundary) is a practical operational heuristic, not a philosophical theory of epistemology. It identifies tasks that are mathematically or syntactically self-contained:

C. Dual-Anchor Scan Windows: Bounded O(1) Overhead

In agent workflows, prompts frequently contain 200KB log dumps or multi-thousand-line source checkout files. Running unbounded regex across 500,000 characters causes catastrophic CPU regex backtracking (ReDoS) and memory spikes.

Stage-0 enforces a Dual-Anchor Scan Window (capped at MAX_PRE_ROUTE_SCAN_CHARS = 8000). If a prompt exceeds 8,000 characters, the classifier inspects strictly:

This guarantees strict $O(1)$ memory consumption and deterministically bounds CPU latency to <15Β΅s regardless of input payload size.

D. Known Failure Modes & Boundary Traps of Shallow Heuristics

Dual-anchor 8,000-character scan windows and keyword rankings are extraordinarily fast because they are shallow. In production systems, engineering teams must anticipate the specific failure modes where deterministic heuristics break down:

  1. Code & SQL Buried in Architectural Planning: Consider a 30-paragraph system design proposal that includes a brief 4-line SQL schema snippet or shell command in the middle. If a shallow classifier prematurely triggers on triple-backtick fences or DDL keywords, it risks routing an abstract, high-cognition architectural task to a small code specialist model. Stage-0 mitigates this by anchoring scans to prompt headers and footers and calculating code-to-prose density ratios, but buried syntax remains an inherent risk in monolithic prompts.
  2. Security-Sensitive Context Traps: A request such as "Write a regular expression to validate user JWT session tokens and sanitize authorization headers" syntactically matches closed-world regex keywords. However, this is an exploitable security surface requiring threat modeling, ReDoS vulnerability analysis, and auth invariant validation. Treating it as a routine syntax generation task on a lightweight edge model is dangerous.
  3. Domain Jargon vs. Open-World Reasoning: Clinical, legal, and financial queries often contain dense domain markers (e.g., ICD-10 diagnostic codes, statutory citations, or GAAP journal terminology). A shallow keyword match classifies them into domain buckets, but the query itself may demand complex statutory ambiguity resolution or multi-symptom differential diagnosis that exceeds a domain specialist's reasoning depth.
  4. Adversarial Injections & Semantic Jailbreaks: Rank 0 keyword filtering catches only naive, off-the-shelf jailbreak strings (e.g., ignore previous instructions, DAN mode). Sophisticated adversarial prompt injectionsβ€”employing semantic framing, roleplaying scenarios, or encoding transformationsβ€”trivially bypass shallow substring filters and require model-level safety alignment.
  5. Multilingual & Multimodal Payloads: Regex anchors and keyword lists are overwhelmingly English- and ASCII-biased. Prompts featuring non-English instructions with embedded code, polyglot developer comments, or multimodal media attachments must register an immediate "Honest Miss" and escalate to neural tiers.

🧠 4. Stage-1: Neural Centroid Escalation (<50ms)

When an incoming prompt is conversational or lacks explicit syntactic anchors (Rank 99 Miss), the system avoids blind defaulting to frontier models. Instead, it escalates to Stage-1 Neural Centroid Matching (implemented via krusch-context-mcp).

Centroid Cosine Matching vs. Trained MLP Routers: Rather than training an opaque multilayer perceptron (MLP) router that requires re-training whenever models or datasets shift, Stage-1 computes the unit-normalized mean vector $\vec{\mu}_k$ of representative embeddings for each domain $k$: $$\vec{\mu}_k = \frac{\sum_{i=1}^{N_k} \vec{v}_i}{\left\| \sum_{i=1}^{N_k} \vec{v}_i \right\|}$$ Incoming query embeddings $\vec{q}$ are matched via vector dot product: $\text{Sim}(\vec{q}, \vec{\mu}_k) = \vec{q} \cdot \vec{\mu}_k$.

The Architectural Trade-Off: Prototype Classification vs. Learned Preference Routers: In machine learning taxonomy, a domain centroid is a 1990s Rocchio-style nearest-prototype classifier. Understanding its operational strengths and theoretical ceilings is critical:

The Latency Reality of the Embedding Hop: The claimed <50ms Stage-1 latency is achievable only when embedding generation occurs locally (e.g., via an in-process ONNX model, local Ollama running a compact embedding model like bge-small-en-v1.5, or local PostgreSQL pgvector HNSW lookup). If an application calls a remote public cloud embedding API (e.g., OpenAI text-embedding-3-small), external TLS handshakes and WAN latency add 60ms to 150ms, re-introducing auxiliary routing latency. Stage-1 embeddings must run close to the gateway.

⚑ 5. Speculative Parallel Hedging & Mid-Stream Guardrails

The fatal flaw of classic sequential cascade routers (trying a cheap model, waiting for failure, then retrying with an expensive model) is the Cascade Latency Penalty: failures double TTFT and user wait times.

The Krusch Cascade Router addresses this with Speculative Parallel Hedging and Token Stream Guards.

A. Borderline Complexity Hedging

For queries falling in the borderline confidence interval (complexity score $S \in [0.25, 0.70]$), the router initiates dual-branch execution:

If the fast model succeeds, the speculative hedge is immediately aborted via controller.abort(). If the fast model fails, the system seamlessly awaits the already-in-flight heavy streamβ€”masking sequential fallback delay.

Cost Economics & Provider API Limitations of Hedging:
Speculative parallel hedging is an intentional latency-versus-cost trade-off. It is not free:
  • Billing on Cancelled Streams: Cloud providers (e.g., OpenAI, AWS Bedrock) bill for prompt tokens regardless of when a streaming response is aborted. If a provider charges for the full input prompt on aborted calls, parallel hedging increases dollar spend on the borderline band in exchange for masking latency. Hedging should therefore be enabled on interactive human turns, and disabled on background batch jobs.
  • Logprob Availability Constraints: Early confidence gating ($P = e^{\text{logprob}} \ge 0.85$) relies on provider-exposed logprobs. While OpenAI, vLLM, DeepSeek, and Groq expose logprobs natively, some providers (notably Anthropic Claude on certain AWS Bedrock endpoints) do not expose raw token logprobs. In environments where logprobs are unavailable, the router falls back to structural validation, fast HTTP error detection, and sliding-window repetition guards.

B. Mid-Stream Repetition & Entropy Collapse Guard

Small or quantized models deployed on edge hardware occasionally suffer from sudden degeneration loopsβ€”repeating tokens indefinitely. The router's stream evaluator incorporates real-time sliding-window entropy analysis:

// krusch-cascade-router: Mid-stream loop & entropy collapse detection
private detectRepetitiveLoop(tokens: string[]): boolean {
  const maxRep = this.config.maxRepetitiveTokens || 4;
  if (tokens.length < maxRep) return false;

  // 1. Single-token repetition (e.g. "import import import import")
  const lastToken = tokens[tokens.length - 1].trim();
  if (lastToken) {
    let identicalCount = 0;
    for (let i = tokens.length - 1; i >= 0; i--) {
      if (tokens[i].trim() === lastToken) identicalCount++;
      else break;
    }
    if (identicalCount >= maxRep) return true;
  }

  // 2. 2-gram cyclic repetition (e.g. A, B, A, B, A, B)
  if (tokens.length >= 6) {
    const t1 = tokens[tokens.length - 2].trim();
    const t2 = tokens[tokens.length - 1].trim();
    if (t1 && t2 && t1 !== t2) {
      if (tokens[tokens.length - 4].trim() === t1 &&
          tokens[tokens.length - 3].trim() === t2 &&
          tokens[tokens.length - 6].trim() === t1 &&
          tokens[tokens.length - 5].trim() === t2) {
        return true;
      }
    }
  }

  // 3. Sliding-window unique token entropy collapse (last 10 tokens)
  if (tokens.length >= 10) {
    const windowTokens = tokens.slice(-10).map(t => t.trim().toLowerCase()).filter(Boolean);
    const unique = new Set(windowTokens);
    if (windowTokens.length >= 8 && unique.size <= 2) {
      return true; // Entropy collapsed: abort stream
    }
  }

  return false;
}

C. The Speculative Hedging Cost Equation & Break-Even Dynamics

The core promise of speculative hedging is zero perceptible fallback delay: if the fast specialist falters or suffers entropy collapse, the user does not wait for a full second request cycle. However, systems engineers must understand the underlying economic ledger: speculative hedging has an unpriced prompt token bill.

Because major frontier model providers (OpenAI, Anthropic, Bedrock) bill for 100% of input prompt tokens the instant an API call is initiated, aborting a hedged stream after 5 tokens saves completion tokens but still invoices the full prompt tokens on the expensive tier. The true cost of a routed query under hedging is formalized as:

$$\text{Cost}_{\text{query}} = \text{Cost}(\text{Fast}) + \mathbf{1}_{S \in [0.25, 0.70]} \cdot \text{Cost}_{\text{prompt}}(\text{Heavy}) + \mathbf{1}_{\text{abort\_fast}} \cdot \text{Cost}_{\text{completion}}(\text{Heavy})$$

Where $\mathbf{1}_{S \in [0.25, 0.70]}$ is the indicator function for the borderline confidence band. The financial risk is immediate:

Operational Architecture Rule for Speculative Hedging:
Speculative parallel hedging is a P95 latency optimization policy, not a budget reducer.
  • Interactive Human Turns (IDE / Chat): Enable hedging (speculativeBranching: true). A human developer waiting for code generation values sub-second TTFT over a fractional cent of prompt token overhead.
  • Autonomous Agent Loops & Batch Swarms: Disable hedging (speculativeBranching: false). In autonomous test-runners, data migration pipelines, and CI linters, latency is amortized. Running pure sequential cascade or hard-gating to Stage-1 prevents unnecessary parallel prompt token expenditure.

☁️ 6. Multi-Cloud Agnostic Dispatching & Adapter Packaging

The router decouples intent classification from physical providers, dispatching seamlessly across AWS Bedrock, Azure OpenAI, GCP Vertex AI, and self-hosted vLLM clusters. Every turn logs structured telemetry (latency, prompt/completion tokens, model attribution, and estimated cost delta) into PostgreSQL for auditability.

Implementation Packaging Reality: In the public open-source package (krusch-cascade-router), the native, out-of-the-box streaming driver is configured around an OpenRouter client integration. This provides immediate, zero-config access to dozens of underlying models (Qwen, DeepSeek, Claude, Gemini) without requiring developers to bundle 300MB of disparate cloud SDKs. Direct native integrations for AWS Bedrock, GCP Vertex AI, Azure OpenAI, and local vLLM are implemented via pluggable ProviderAdapter interfaces, ensuring the core cascade routing logic remains lightweight and vendor-independent.

πŸ“Š 7. Empirical Benchmark Evaluation & Cost Modeling Realities

To evaluate the router's routing efficiency, experiments were conducted across public benchmark datasets and holdout suites:

Benchmark Suite Evaluation Scope Baseline Oracle Krusch Cascade Performance Cost Metric Dispatch Overhead
1. RouteWorks RouterArena 8,400 Benchmark Queries (+3,236 Optimality) Multi-Model Frontier Pool Workflow Score: 77.93
Accuracy: 81.53% (Candidate PR #169 CI)
$0.61 / 1K queries
(vs $0.27 Paix2 live #1, $4.10 NotDiamond)
< 0.15 ms
(6,600+ QPS)
2. Developer Integration Suite 100 Prompts (6 Domains) Target Rule Oracle Classification Precision: 100.0%
Noise Invariance: 100.0%
Deterministic Rules
(Self-authored test suite)
0.02 ms
(50,000+ QPS)
3. WithMartian RouterBench 36,497 Inference Outcomes (11 LLMs) GPT-4 Oracle ($94.39 baseline) AIQ Score: 0.7200
(Offline Reconstructed Simulation)
93.2% (Frugal)
56.3% (Balanced)
0.11 ms
(9,066 QPS)
4. Google AutoMix 14,571 QA / Reading Comp Queries LLaMA-13B $\rightarrow$ LLaMA-70B Cascade CoQA Lift: +55.17%
NarrativeQA Lift: +17.45%
82.4% on CoQA
68.4% on NarrativeQA
0.007 ms
(137,000+ QPS)
5. LMSYS RouteLLM 10,000+ Head-to-Head Arena Battles GPT-4 vs Mixtral / LLaMA-3 MT-Bench: 0.6027 APGR
GSM8K: 0.5602 APGR
50%–75% Savings
at 95% quality retention
< 0.05 ms
(20,000+ QPS)

Methodology Disclosures & Reproducibility Context

Important Benchmark & Leaderboard Disclosures:
  1. RouterArena Leaderboard Status (Candidate vs. Ratified): On the official live RouteWorks/RouterArena leaderboard, Paix2 is the official published #1 at 77.63 ($0.27/1K). The Krusch candidate submission achieved 77.93 in official GitHub Actions CI evaluation under PR #169 (81.53% accuracy, $0.61/1K cost). Split-level variations occur across full evaluations (~0.74 score / 76% accuracy / $0.37 per 1K on full splits). Until PR #169 is formally merged by upstream maintainers, this should be evaluated strictly as an unmerged candidate CI submission. Furthermore, notice the cost trade-off: Krusch's candidate evaluation trades off a higher blended query cost ($0.61 vs $0.27) for its higher accuracy bracket (81.53%).
  2. Developer Integration Suite (Suite 2): The 100% precision figure is derived from an internal 100-prompt unit/integration test suite designed to verify Stage-0 regex rules and precedence ranking across 6 structured domains. It confirms deterministic rule execution, not generalizable natural-language reasoning or independent third-party benchmark performance.
  3. Offline Reconstructed Simulations (Suites 3–5): The figures for RouterBench, AutoMix, and RouteLLM reflect reconstructed offline simulations evaluating our specialist models against public benchmark datasets and historical academic baselines (e.g., 2023/2024 GPT-4 vs LLaMA-13B literature). They are local simulations, not official live platform submissions.
  4. Catalog Volatility: The models listed (e.g., Qwen3-Coder-Next, DeepSeek-V4, Gemini 3.1 Flash) represent an illustrative 2026 reference stack. Because model names and pricing shift rapidly, the system architecture explicitly decouples routing logic from model IDs via PostgreSQL catalog pointers.

The Token Pareto Skew & Analytical Workload Projections

A common fallacy in AI routing economics is assuming that routing 70% of requests to cheap models automatically cuts 70% of the token bill. In real-world coding agents, token consumption follows a heavy Pareto distribution:

If unmanaged, 80% of total token volume remains concentrated in the 30% of hard turns. To realize genuine 60–80% cost reductions in practice, two complementary mechanisms are required:

  1. Stage-0 Text Compaction (pruneText): Stripping conversational filler and bounding scan windows to compact context before tokenization.
  2. High-Context Edge Specialists: Utilizing cheap high-context models (e.g. modern Flash/Lite variants at $0.15/M tokens) to handle large context dumps that require retrieval or formatting rather than frontier multi-hop reasoning.
Analytical Projections vs. Measured Case Studies: Enterprise budget models (such as projecting a drop from $324,000/month to $78,000/month across a 200-developer team) represent analytical workload models under high syntactic skew (assuming 70% of prompts are deterministic developer tasks: code fences, SQL migrations, unit tests, diffs). They are not empirical customer case studies. In organizations where traffic is heavily conversational, ambiguous, or knowledge-work heavy, the proportion of queries intercepted by Stage-0 will naturally be lower, and the realized cost savings will scale down proportionally. The architecture provides the routing levers; your production traffic distribution determines the invoice.

βš–οΈ 8. Architectural Trade-Off Analysis

The choice between heuristic gating, learned embedding routers, and LLM supervisors involves well-defined engineering trade-offs:

Dimension Krusch Cascade Router (Stage-0 + Stage-1) Learned Neural Routers (e.g. RouteLLM, NotDiamond) LLM Supervisor (e.g. Orca, LangChain Selector)
Routing Latency < 15 Β΅s (Stage-0) / ~20ms (Stage-1 local) 15 ms – 50 ms (Vectorization + MLP) 400 ms – 1,200 ms (LLM pre-flight round-trip)
Routing Cost Tax $0.00 (Stage-0) / $0.00 local (Stage-1) ~$0.0001 (Embedding API call) ~$0.002 to $0.01 (Prompt token charge)
Structured Code & SQL Precision Deterministic (Exact string, AST fence, & keyword anchors) Probabilistic / Statistical (Embedding vector space) High (Semantic comprehension, but nondeterministic)
Ambiguous Natural Language Coarse Nearest-Prototype (Centroids vulnerable to multi-intent overlap) Robust (Trained MLP captures non-linear preference boundaries) Highest (Full contextual world-model reasoning)
Fallback Latency Penalty 0 ms (When hedging enabled; trade-off is prompt token billing) Sequential fallback (2x latency penalty) Sequential fallback (2x latency penalty)
Mid-Stream Anomaly Abort Yes (repetition loops & logprob gating) No (routing decision only) No (routing decision only)
Catalog Maintenance Zero retraining (DB config pointer update) Requires re-training classifier matrix Requires prompt updates

πŸ’» 9. Implementation & Integration Guide

A. Using the Zero-Dependency Stage-0 Pre-Router

If you already operate an agent framework (LangChain, Claude Code, Vercel AI SDK, or custom) and simply need a sub-15Β΅s front door to intercept code and SQL before invoking expensive endpoints:

# Install zero-dependency L1 pre-router (<10KB gzipped)
npm install krusch-pre-router
import { classifyPreRoute } from 'krusch-pre-router';

// Fast CPU gate: runs in microseconds
const result = classifyPreRoute(userPrompt, {
  preset: 'structure',
  prunePreRouting: true
});

if (result.isFastPath) {
  // Dispatches instantly to domain specialist ($0.00 routing tax)
  console.log(`Syntactic hit: Role=${result.role}, Reason=${result.reason}`);
  await dispatchSpecialist(result.role, userPrompt);
} else {
  // Honest miss: pass to existing neural router or frontier model
  console.log(`Syntactic miss (Complexity=${result.complexityScore}). Escalate.`);
  await dispatchExistingPipeline(userPrompt);
}

B. Full Cascade Router with Speculative Hedging

# Install full cascade router
npm install krusch-cascade-router
import { createMultiSpecialistRouter } from 'krusch-cascade-router';

const router = createMultiSpecialistRouter({
  openrouterApiKey: process.env.OPENROUTER_API_KEY,
  speculativeBranching: true, // Enables parallel hedging on borderline queries
  cascadeThreshold: 0.85,     // Linear confidence cutoff for fast model
  maxRepetitiveTokens: 4,     // Abort degenerate repetition loops early
  customModels: {
    code: 'qwen/qwen3-coder-next',
    factual_stem: 'google/gemini-3.1-flash-lite',
    reasoning_fast: 'deepseek/deepseek-v4-flash',
    reasoning_deep: 'deepseek/deepseek-v4-pro',
    comprehension_rc: 'qwen/qwen3-235b-a22b-2507'
  },
  onEvent: (event, meta) => {
    console.log(`[Telemetry: ${event}]`, meta);
  }
});

for await (const chunk of router.stream("Explain PostgreSQL 2PC commit mechanics")) {
  process.stdout.write(chunk);
}