Route CortexDB memory model requests through Surplus Intelligence, falling back to OpenRouter
Description
Route CortexDB's memory-related model requests through Surplus Intelligence first, falling back to OpenRouter when Surplus has no eligible seller.
This scoping is well chosen. Memory model work — enrichment, belief and fact derivation, entity extraction, verification, image extraction — is background, latency-tolerant, high-volume, and carries no shared KV-cache prefix between calls. It is exactly the workload a discount marketplace suits, and it avoids the cache-affinity problem that makes price-routing a bad idea for interactive agent traffic (see #6999, #7000).
The spend is also real: CORTEX_ENTITY_GRAPH=1 is on in production, which cortexdb-saas documents as ~3× write and ~4× recall model cost. A discount applies to an already-multiplied bill.
The good news: these are all config, not code
Every model route in the CortexDB engine is an OpenAI-compatible URL + model + key, and all of them currently point at OpenRouter. From deploy/cortexdb.env.example:
| Role | URL | Model | Key |
|---|---|---|---|
| Chat, all roles + entity extraction | CORTEX_LLM_URL |
CORTEX_LLM_MODEL |
LLM_API_KEY / CORTEX_ENTITY_API_KEY |
| Enrichment | CORTEX_ENRICHMENT_URL |
CORTEX_ENRICHMENT_MODEL |
CORTEX_ENRICHMENT_API_KEY |
| Answer | CORTEX_ANSWER_URL |
CORTEX_ANSWER_MODEL |
CORTEX_ANSWER_API_KEY |
| Verifier | CORTEX_VERIFIER_URL |
CORTEX_VERIFIER_MODEL |
CORTEX_VERIFIER_API_KEY |
| Image extraction | CORTEX_IMAGE_API_URL |
CORTEX_IMAGE_MODEL |
CORTEX_IMAGE_API_KEY |
| Embeddings | CORTEX_EMBEDDING_URL |
CORTEX_EMBEDDING_MODEL |
LLM_API_KEY only |
All are https://openrouter.ai/api/v1, and CORTEX_ANSWER_PROVIDER / CORTEX_IMAGE_PROVIDER are openai — meaning the OpenAI dialect. Surplus is OpenAI-compatible (its own SDK provider is a thin wrapper over createOpenAICompatible), so pointing a role at it is a URL and key change.
The catch: "fall back to OpenRouter" cannot be configuration
The engine takes exactly one URL per role. There is no fallback list, and CortexDB is a closed third-party binary (cortexdb/cortexdb, pinned by digest) — we cannot teach it to fail over.
Worse, Surplus will not cover for us. Its own documentation is explicit:
"Catalog discovery is not an authentication test or a guarantee that sellers are currently available." "[It] does not widen the route or retry with weaker restrictions when sellers are unavailable."
So the requested behaviour needs a small OpenAI-compatible shim that we own, sitting between the engine and the two upstreams:
cortexdb ──CORTEX_*_URL──▶ memory-llm-router ──1st──▶ api.surplusintelligence.ai
└──2nd──▶ openrouter.ai (on no-seller / error / timeout)
That shim is the actual deliverable. cortexdb-saas is the natural home — it already owns the engine's configuration and already proxies on the data path. Keep it narrow: pass the request through unchanged, add Surplus routing headers, fall back on failure, and record which upstream served each call.
Routing controls worth setting on the Surplus leg: si_route.objective (price is appropriate here, unlike agent traffic), X-Min-Discount, and providers_blocked. Note price_tolerance_pct is a ranking band, not a cost cap, and max_latency_ms filters on observed p50 and is not a request deadline — so the shim needs its own timeout.
The landmine: embeddings
Do not move embeddings in the first pass. Two independent reasons, both from the engine's own documentation:
1. A key mistake silently poisons every user's data. cortexdb.env.example warns:
"With none of these set the engine does NOT refuse: it falls back to mock embeddings, pins the data directory to
mock::1536, and still reports healthy. On a shared instance that one mistake poisons every company."
And v0.9.9 has no separate embedding key — it reads LLM_API_KEY (or OPENAI_API_KEY). Since LLM_API_KEY is shared with the chat route, changing the chat key can silently change embedding behaviour. Any change to these variables must be followed by checking embedding_provider in /v1/admin/ready.
2. A marketplace may not return byte-identical vectors. Embeddings write into a shared vector index pinned at 1536 dims, and CORTEX_VECTOR_TENANT_SHARDS "latches on disk at pool creation." Surplus routes a request to whichever seller wins — and sellers running nominally the same model can differ in version or quantisation. Mixed-provenance vectors in one index degrade recall silently, with no error and no obvious symptom. That has to be measured before it is risked, not assumed safe.
So: chat roles first, embeddings only after vector equivalence is demonstrated — or never, which is a perfectly acceptable outcome.
Suggested sequence
- Build the shim with Surplus disabled — pure passthrough to OpenRouter. Proves the hop costs nothing.
- Enable Surplus for enrichment only. It is background, already delayed 30 s (
CORTEX_ENRICHMENT_DELAY_SECONDS=30), and a failure degrades gracefully: enrichment off means "no facts, beliefs or concepts — recall on raw events only", not broken recall. - Extend to verifier, entity and image extraction.
answerlast — it is the only one of these on a user's critical path, since recall synthesis is user-visible.- Embeddings only behind a measured equivalence check, or not at all.
Also worth deciding
TinyMemory has its own summariser path, separate from the engine's. This session's logs show it failing through OpenRouter:
[archivist] summarize_entries: LLM recap failed (non-fatal) … provider=inference:openrouter/deepseek/deepseek-v4-flash
… no summarization provider — enable local AI, or opt in …
That is memory-related model work too, but it does not go through CORTEX_*. Say whether it is in scope — the shim could serve it as well, since it is the same shape of request.
Related
- #6999 / #7000 — why this is the right traffic to price-route and agent traffic is not
- #7002 — CortexDB per-user scoping. The shim sits inside the trust boundary, so it must not log request bodies: memory content is user data, and
cortexdb-saasnotes "image extraction sends uploaded images to the same OpenRouter account that already receives every memory's text." Adding an upstream adds a party that sees that content. - #6718 — hosted CortexDB validation and the tinycortex retirement
- #6717 — usage and balance reporting; a second upstream makes per-call cost attribution harder, and that ledger already disagrees across surfaces
- Memory-migration credits, previously the second half of this issue, is now tracked separately so each has a clean definition of done.
Acceptance Criteria
- [ ] An OpenAI-compatible shim exists that the engine can be pointed at, serving the roles in scope unchanged
- [ ] Surplus is attempted first and OpenRouter is used on no-eligible-seller, error, or timeout — with the shim's own timeout, not
max_latency_ms - [ ] Fallback is verified by fault injection: a bad Surplus key, a no-seller response, and a hung connection each fall through to OpenRouter with no engine-visible error
- [ ] Every call records which upstream served it, and the Surplus/OpenRouter split is reportable per role
- [ ] Enrichment runs on Surplus in production for a full week with facts, beliefs and concepts still deriving — verified via
/v1/derivation/status, not inferred - [ ] Realized savings are measured against invoices, not estimated from
X-Min-Discount - [ ]
embedding_providerin/v1/admin/readyis asserted after every config change, with a check that fails loudly if it ever readsmock - [ ] A regression guard exists so no deployment can start with mock embeddings while reporting healthy
- [ ] Embeddings stay on OpenRouter unless vector equivalence across Surplus sellers is demonstrated and recorded here
- [ ] The shim does not log or persist request or response bodies; this is reviewed as part of #7002's boundary
- [ ] A documented rollback: one config change per role returns it to OpenRouter, tested
- [ ] A decision is recorded on whether TinyMemory's archivist summariser is in scope
A two-part enhancement request: integrate Surplus Intelligence as a discounted OpenAI-compatible inference route with explicit cache-affinity-preserving routing defaults and measured go/no-go evaluation, plus a credits-funded memory-migration offer gated on fixing known bulk-ingest timeouts and trusted balance reporting. New functionality with design questions, not a defect.
This reads like self-promotion: it matched a new API credential setting; a new outbound service endpoint. That is a set of textual signals rather than a verdict, and nothing was closed on account of it. If the signals are wrong, say so and clear the label.
Labelled priority: p3 flag: promotional.
Request to route CortexDB memory-model traffic through Surplus Intelligence with OpenRouter fallback via an owned shim; new functionality with design questions, not a defect. No matching prior art in candidates.
Labelled priority: p3.
Scope narrowed to CortexDB model-request routing. The memory-migration credits half of this issue moved to #7003 so each has its own definition of done — #7001 should land first, since the credit cost depends on the measured rates here.
Status: the shim exists and has been serving production since 2026-10-05
Noting this because the issue currently reads as though nothing has been built. The deliverable asked for here — "a small OpenAI-compatible shim that we own" — is deployed and routing live memory traffic.
It is senamakel/llm-ladder-router, configured with an ordered ladder per model role: cheap marketplace rungs first, an OpenRouter rung last as the outage fallback. Two of the engine's roles point at it today — enrichment and entity extraction / query planning — on Flash-class models. Deployment and configuration live in the infrastructure repo (private): PRs 100, 102, 103, 108, 109, 110.
Met
- [x] An OpenAI-compatible shim the engine can be pointed at, serving its roles unchanged.
- [x] Marketplace first, OpenRouter on no-seller / error / timeout, with the shim's own per-attempt timeout. The sizing rule that matters: rungs × per-attempt timeout must stay below the engine's own HTTP timeout, or the engine gives up before the ladder has finished falling back. We got this wrong once and corrected it.
- [x] Embeddings stay on OpenRouter. They traverse the shim, but that ladder has exactly one rung by design, and must keep exactly one: a cheaper second rung would mix vectors of different dimensionality and meaning into a single index and degrade recall silently for every tenant.
- [x] A regression guard against mock embeddings — the engine now refuses to start in a configuration that would silently fall back to them while still reporting healthy.
- [x] No request or response bodies are logged or persisted. The one feature that inspects a body emits a count only.
- [x] A documented rollback, one role at a time, back to OpenRouter directly.
Still open
- [ ] A full week of enrichment on the marketplace with derivation still working. Live since 2026-10-05, so the week completes 2026-10-12. The verification half is outstanding: this wants the derivation status endpoint read and recorded, not inferred from nobody complaining.
- [ ] Realized savings measured against an invoice. Needs a billing period — and see the reliability note below, which is why the headline discount is not the number to quote.
- [ ] A per-role marketplace/OpenRouter split. Not satisfiable as configured. Enrichment and entity extraction name the same ladder, so the shim's logs distinguish upstreams but not roles. Either give them two ladder names with identical rungs — cheap, and it makes the two largest write-side costs separable — or narrow this criterion to a per-ladder split. Worth deciding rather than leaving ambiguous.
- [ ] Deliberate fault injection. Two of the three cases have been occurring in production unprompted and are handled correctly, which is reassuring but is not a test. The bad-key case is untested.
- [ ] Which roles are in scope.
answer,verifierand image extraction still go to OpenRouter directly. That follows the sequence in the description —answerlast, as the only one on a user's critical path — but closing this issue should state whether those three are in or out.
Decision: the TinyMemory archivist summariser is out of scope — it no longer exists
The description asks for a decision either way. It is out of scope, and not as a judgement call: the entire archivist module was deleted by #6949 (memory v2, 2026-10-02), replaced by the experience-capture path. There is no summarize_entries left to route.
The recap failure quoted in the description came from a build predating that deletion — v0.64.10, the newest release, still contains the archivist, which is what anyone on a released build is running. The release branch no longer does. So no issue is being filed for it: publishing the pending release resolves it by removing the code.
For the record, the provider-pin theory for that failure was also wrong — the provider.order + allow_fallbacks: false shape was removed from both the app and the backend on 2026-09-22, two weeks before the sighting.
Worth acting on now: the cheapest rung is unreliable
Independent of the above. Sampled over roughly a minute of production traffic this morning, the cheapest marketplace rung failed about half the time with a no-healthy-sellers response, each time advancing correctly to the next rung and being served.
The ladder is working as designed, but two things follow. The best discount applies to only about half the calls, so realized savings cannot be read off the quoted discount and must come from the invoice. And each failure spends a round trip before advancing, which eats the multi-rung timeout budget on a slow day.
The cause is on the marketplace side: the rejections name a seller's upstream credential, not ours — our key authenticates, which is why we see a no-seller response rather than an auth failure. Worth raising with them, with timestamps.
Three corrections to the status above.
Query planning is not routed through the shim — it is disabled. tinyhumansai/k8s#105 (2026-10-06) set the HyDE passage count to zero, disabled HyDE for every question type and disabled the multihop planner outright, keeping the model off the read path entirely. Only enrichment and entity extraction reach the shim.
The unreliable cheapest rung is already tracked, and it has already caused a user-facing regression — tinyhumansai/cortexdb-saas#14, "Hosted memory is 13–20× slower than local: pre_turn p95 26.5 s, write-to-visible 95 s on production". Measured 2026-10-06: hosted recall p50 2.5 s / p95 26.5 s / max 33.5 s against the backend's 30 s cut-off, versus 1.1 s / 1.5 s for the same engine on a healthy model, specifically while the ladder was failing rungs. That is what prompted the read-path change above. So this is not just a cost-accuracy footnote: it is the reason a user-facing mitigation was needed, and it strengthens the case for a per-ladder reliability signal rather than inferring health from spend.
#6949 landed on main on 2026-10-04, not 2026-10-02 — that is the commit's authorship date. The conclusion is unchanged, since the newest release is v0.64.10 from 2026-09-30, but the margin against the 2026-10-05 sighting is one day.