How 30-Second Counterfactual Log Replay Works: Semantic Caching & Tiered Model Routing Explained
Inside the deterministic browser-local math behind CostLean's 0-byte-upload AI Spend Scanner, plus how RouteLLM complexity routing and entity-guarded semantic caching slash live API bills by 30%–68%.
- Why Legacy Spend Trackers Fail Developer Trust: Tools that demand Plaid bank OAuth, production API admin keys, or ironic $9.99/week subscription traps alienate security-conscious engineering teams.
- Zero-Upload Counterfactual Log Replay: By running deterministic token-table math inside the user's browser on historical CSV/JSONL exports, teams see exact recoverable dollars in < 2 seconds with 0 bytes transmitted over the network.
- Entity-Guarded Contrastive Semantic Caching: Augmenting GPTCache-style dense embeddings with deterministic date, SKU, currency, and negation fingerprints eliminates false-positive cache collisions while cutting 18%–39% of calls.
- Per-Step Calibrated Model Routing: Extending RouteLLM preference calibration from whole chats to individual agent sub-steps cuts blended token bills by 38%–45% at <= 50ms p95 gateway overhead and <= 2.0% quality variance.
📑 Table of Contents (7 sections)
- 1. Why Developers Reject Bank-Linking FinOps Tools and Opaque Proxies
- 2. Stage 1: Deterministic Counterfactual Log Replay in < 2 Seconds
- The Weighted AI & Cloud Cost Health Score (0–100) Formula
- 3. Stage 2: How Live Semantic Caching & Tiered Routing Protect Quality
- Mechanism A: Entity-Guarded Contrastive Semantic Caching
- Mechanism B: Sub-Step Complexity Routing + Confidence Escalation
- 4. From Audit to Production in One base_url Change
1. Why Developers Reject Bank-Linking FinOps Tools and Opaque Proxies
Ask an indie founder, staff engineer, or enterprise CISO why they have not audited their AI and SaaS spend yet, and you will rarely hear “we don’t care about money.” Instead, you hear a well-earned distrust of traditional spend-management apps:
- Invasive Credential Demands: Consumer subscription trackers force Plaid bank logins (which break outside US/EU institutions) or demand read-write OAuth access to corporate mailboxes.
- Paywall-Before-Proof Dark Patterns: Several viral subscription apps charge ironic
$9.99/weekrecurring fees before revealing whether they detected a single actionable leak. - Fear of Routing Quality Collapse: Engineering leads worry that putting an uncalibrated “cheap model router” in front of production agents will silently degrade JSON schema compliance or legal reasoning accuracy.
To solve both the privacy barrier and the quality-assurance barrier, we split CostLean’s optimization engine into two mathematically linked stages: Stage 1 — Zero-Upload Browser Counterfactual Replay (/scanner/), and Stage 2 — Live 4-Engine Calibrated Gateway (LeanRouter).
2. Stage 1: Deterministic Counterfactual Log Replay in < 2 Seconds
Instead of asking you to guess what a smart gateway might save next month, Counterfactual Log Replay answers an exact historical question: “If your past 30 days of real OpenAI, Anthropic, OpenRouter, Cursor/OpenCode, and AWS requests had passed through calibrated caching, routing, and cloud guardrails, what would your invoice have been down to the cent?”
Because usage exports (usage.csv, activity.csv, multi-bot .jsonl traces, and AWS Cost Explorer CSVs) already contain timestamps, model identifiers, input_tokens, cached_tokens, output_tokens, and billed amounts, zero server-side LLM inference is needed to audit them. Everything executes locally in browser memory (0 Bytes Uploaded—verifiable in your DevTools Network tab).
The Weighted AI & Cloud Cost Health Score (0–100) Formula
Every replayed log file produces a deterministic score from 0 (Critical Burn) to 100 (Lean & Surgical) across three transparent sub-scores:
// Deterministic Counterfactual Scoring & Savings Replay (Simplified Core)
export interface ReplaySummary {
healthScore: number; // 0..100 composite score
modelFitScore: number; // 40% weight: flagship overkill detection
cacheLoopScore: number; // 35% weight: uncached prefixes & retry storms
cloudSaasScore: number; // 25% weight: AWS NAT bleed & duplicate SaaS seats
monthlyRecoverableUsd: number;
}
export function computeCompositeHealth(
sModel: number,
sCache: number,
sCloudSaas: number,
hasCloudOrSaasRows: boolean
): number {
if (!hasCloudOrSaasRows) {
// API-Only Mode auto-normalizes weights to 55% Model Fit + 45% Cache/Loop Hygiene
return Math.round(0.55 * sModel + 0.45 * sCache);
}
return Math.round(0.40 * sModel + 0.35 * sCache + 0.25 * sCloudSaas);
}
Here is how each counterfactual detector isolates recoverable dollars without hand-waving:
- Flagship Overkill Detector (
40%weight): Flags rows invoking frontier models (claude-opus,claude-sonnet,gpt-4o,o1/o3) whereinput_tokens < 800andoutput_tokens < 400—typical signatures of commit-message generation, intent classification, boilerplate translation, or JSON reformatting. Recoverable savings apply a conservative65%price-spread capture against high-efficiency tiers (deepseek-v3-lean/gpt-4o-mini/gemini-flash). - Uncached Prefix & Retry-Storm Detector (
35%weight):- Measures
cached_tokens / total_input_tokens. When repeated system prompts or 20k-token RAG contexts exhibit< 25%cache hit ratios, counterfactual prefix/semantic caching models a conservative50%discount on eligible repeated input blocks. - Scans sliding 60-second windows for
>= 4consecutive calls to the same model with monotonically growing input tokens—the unmistakable fingerprint of an autonomous tool-error retry storm (70%recoverable via loop circuit-breakers).
- Measures
- Cloud Network & Duplicate SaaS Seat Detector (
25%weight): Flags AWSNatGateway-Bytes(85%recoverable via S3 Gateway Endpoints +fck-nat), idleElasticIPhours, and overlapping individual AI subscriptions (ChatGPT Plus+Claude Pro+Cursor+Windsurfbilled concurrently on the same card).
3. Stage 2: How Live Semantic Caching & Tiered Routing Protect Quality
Once /scanner/ proves that your workload leaks $420/month or $14,000/month, how do you capture those savings in live production without breaking agent reliability? Simply swapping every API call to the cheapest open-weight model fails whenever edge-case legal, financial, or architectural prompts arrive.
CostLean’s production gateway (https://api.costlean.com/v1) builds on academic breakthroughs including RouteLLM (Ong et al., preference-calibrated routing), GPTCache (semantic embedding lookup), and LLMLingua (context token pruning), hardened with two enterprise safety mechanisms:
Mechanism A: Entity-Guarded Contrastive Semantic Caching
Off-the-shelf vector caches like basic GPTCache configurations embed a user prompt into dense vector space and return a cached answer whenever cosine similarity exceeds 0.90. In enterprise production, naive cosine similarity causes dangerous false-positive collisions:
- “What is the SLA penalty under Vendor Contract
#2024-09?” vs. “What is the SLA penalty under Vendor Contract#2025-09?” share0.985cosine similarity on generic embeddings—yet returning last year’s answer is catastrophic! - “Approve refund requests under
$500” vs. “Approve refund requests not under$500” also collide in naive vector space.
Dr. Ye’s routing engine resolves this by combining hard-negative contrastive embeddings with a sub-millisecond Deterministic Entity & Negation Guard:
| Cache Evaluation Check | Naive Vector Cache (cosine >= 0.90) | CostLean Entity-Guarded Contrastive Cache |
|---|---|---|
| Semantic Paraphrase (“Tokyo Q3 per-diem cap?” vs. “Max daily meal/hotel limit in Tokyo for Q3?”) | Hit (0.95) | Verified Hit (tau >= 0.94 + matching Tokyo, Q3) |
ID / Fiscal Date Shift (“Invoice #8841” vs. “Invoice #8842”) | False-Positive Bug! (0.99 similarity) | Safe Miss (Hard token fingerprint mismatch 8841 != 8842) |
| Negation Flip (“Include VAT” vs. “Exclude VAT”) | False-Positive Bug! (0.96 similarity) | Safe Miss (Polarity token guard blocks cache shortcut) |
| Gateway Latency & Token Cost on Hit | ~15ms / $0.00 | 6ms–11ms / $0.00 (18%–39% call elimination) |
Mechanism B: Sub-Step Complexity Routing + Confidence Escalation
Inspired by RouteLLM, our router scores structural complexity per individual agent sub-step rather than locking an entire conversation to one model:
- Tier 1 (
deepseek-v3-lean/ fast value tier): Handles65%–75%of agent sub-steps—HTML/JSON extraction, log summarization, boilerplate drafting, and SQL parameter formatting at1/8thto1/12thfrontier cost. - Tier 2 (Bilingual domain mid-tier): Handles cross-border regulatory mapping and high-volume categorization.
- Tier 3 (
claude-sonnet-lean/ frontier reasoning tier): Reserved for initial multi-agent task decomposition, ambiguous multi-party contract indemnities, and automatic escalation whenever a Tier 1 response triggers a schema validation warning.
Across the 3,000+ test cases in CostLean-Bench, combining Entity-Guarded Semantic Caching, Context Compression, Sub-Step Routing, and Loop Circuit-Breakers delivers 38%–68% net API cost reduction inside <= 50ms p95 gateway latency, while holding benchmark accuracy within <= 2.0% of a 100%-flagship baseline.
4. From Audit to Production in One base_url Change
You never have to guess or take vendor benchmarks on faith. First, run your historical logs through /scanner/ to verify your counterfactual floor with zero data upload. Second, point your OpenAI SDK, Cursor, or ./opencode.json baseURL to https://api.costlean.com/v1 with a free sk-lean-* key—and watch every response return live costlean_meta proof of exact credits saved.