Skip to content

Decide the runtime response to routing-suppressed OpenAI-compat models (matrix now exists) - #1842

Merged
malibio merged 2 commits into
mainfrom
issue-1830-routing-mitigation
Jul 31, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-1830-routing-mitigation

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Closes #1830

…e Stage-2 injection (closes #1830)

Widened the OpenAI-compat routing matrix from one served model to
three (llama3.1:8b, mistral:7b, gemma4:e4b), settling the prerequisite
ADR-056 left open: 2 of 3 measured served models route cleanly, so the
mistral:7b failure is a per-model property rather than a
native-vs-served split.

Implements Option C from the decision: a one-time routing-reliability
probe (nodespace_agent::local_agent::routing_probe) runs at OpenAI-compat
model load, caches a routing_ok verdict on OpenAiCompatConfig in
daemon.toml, and disables Stage-2 candidate-block injection
(session.routing_disabled) for a model that fails it while leaving
tool-surface scoping untouched — the matrix implicates the injected
block, not the scoped tool list. A disabled turn logs a visible warning
and a stage2_routing_disabled field on the turn's structured log rather
than degrading silently.

The probe cache is keyed on the (base_url, model) pair actually
measured, not on the opaque model_id used for engine-swap dedup — a
single-model server config with no /models discovery resolves every
load to the same model_id regardless of the config's model field, so
an in-place model edit needed its own invalidation path.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1842 (closes #1830)

Review Type: Initial Review
Scope: f548ad3 — 8 files, +1008/−7

Summary

This is a well-argued implementation of Option C, and the reasoning quality is unusually high — the comments consistently explain why a mechanism is shaped the way it is, and the (base_url, model) keying fix shows the author found and closed a real bug rather than shipping the obvious-but-wrong swapped-keyed version. The decision to gate only prompt injection and leave routing::stage2_tools scoping intact is correct and correctly justified: the matrix measured the injected block, and disabling the trust boundary (ADR-038) would have been an unmeasured, security-relevant side effect.

One blocking correctness gap: the on-disk verdict cache is keyed per config, but the probe is per model, and a single config exposes many discovered models. Details below.


Requirements Check (issue #1830)

  • ✅ Matrix covers enough served models to support a generalization — widened to 3 (llama3.1:8b, mistral:7b, gemma4:e4b); 2 clean / 1 failing settles the fork.
  • ✅ Decide between A/B/C, recorded as an ADR update — Option C; nodespace-docs@3007dbb "Record the widened routing matrix and the Option C mitigation" confirmed present.
  • ✅ Mechanism keys on what the matrix supports, not an assumed native-vs-served split — keyed on a per-model probe verdict. Skipping the probe on the native path is justified by ADR-056 rather than by assuming the split.
  • ✅ A suppressed turn produces a visible signal — tracing::warn! at both probe time and turn time, plus the stage2_routing_disabled structured-log field distinguishing "withheld" from "nothing matched".
  • ⚠️ The routing matrix test is extended to cover the mechanism — partially. the_probes_block_matches_the_routed_names_arm is a genuine guard, but see 🟡 Desktop shell with resizable panels #3 on what it does not catch.
  • ➖ If A: close with rationale — N/A.

Findings

🔴 Critical: The on-disk routing_ok cache collides across models served by one config

📁 packages/daemon/src/services/settings_service.rs:50-60 · packages/daemon/src/services/local_agent_service.rs:1219-1220, 1236-1243

parse_openai_compat_id (openai_compat_inference.rs:50) explicitly supports openai-compat:<uuid>:<model> — "which is how one config exposes the several models a server serves." So for an Ollama endpoint, one config id legitimately backs llama3.1:8b, mistral:7b, gemma4:e4b, … But routing_ok is a single Option<bool> on OpenAiCompatConfig, keyed only by config id.

The in-memory key (base_url, model) is correct. The disk cache is not, and disk wins on a fresh load:

  1. Load openai-compat:abc:mistral:7b → probes false → record_routing_probe_verdict(config_id="abc", …, model="mistral:7b") writes routing_ok = Some(false) on config abc.
  2. Load openai-compat:abc:llama3.1:8b → swapped == true, so the in-memory branch is skipped → falls to else if let Some(cached) = config.routing_ok → reads Some(false).
  3. llama3.1:8b — measured clean in the widened matrix — has Stage-2 injection permanently disabled, and never re-probes.

The entry.base_url != base_url || entry.model != model guard in record_routing_probe_verdict (settings_service.rs:347) does not save this. It only compares against the config's pinned model field, which for a discovery-driven load is unrelated to the model actually probed — so for a config whose pinned model is mistral:7b, the guard passes for mistral:7b and silently no-ops for every discovered model, meaning a clean discovered model can never write its own Some(true) to overwrite the poisoned entry either. The failure is sticky and silent, and it degrades exactly the models the matrix proved are fine.

The verdict.map(|_| this_key) in-memory bookkeeping is otherwise correct; this is purely the persistence layer's key being coarser than the value it stores.

Recommendation: make the persisted cache carry the model it was measured against. Minimal shape, no migration needed given greenfield:

/// Cached probe verdicts keyed by the served model they were measured
/// against — one config can serve many discovered models.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub routing_ok: BTreeMap<String, bool>,

…with the read becoming config.routing_ok.get(&model).copied(), the write inserting under model, and the carry-forward in set_open_ai_compat_configs retaining entries when base_url is unchanged (dropping all of them when base_url changes, plus dropping the pinned-model entry when that field changes).

Engineering principle: a cache key must be at least as specific as the value it caches. Here the value varies per model but the key does not.


🟡 Important: else if let Some(cached) bypasses the freshness check the in-memory path performs

📁 packages/daemon/src/services/local_agent_service.rs:1219-1220

Even after the above is fixed, note the asymmetry: the in-memory branch requires !swapped && cached_key_matches, but the disk branch trusts config.routing_ok with no corresponding validation at the point of read — it relies entirely on write-time and set_open_ai_compat_configs-time invalidation being exhaustive. That's a fragile invariant to hold across three separate call sites. Validating at read time (config.routing_ok.get(&model) under the fix above) makes the freshness property local and self-evident rather than distributed.


🟡 Important: the matrix module docs still state the pre-widening finding

📁 packages/agent/tests/live_openai_compat_routing.rs:44-66

The prerequisite for this whole issue was widening the matrix, and the code did that — but the module doc comment still carries the two-row table and the now-false conclusion:

//! model        baseline  stage1_only  routed_full  routed_names
//! gemma4:e4b   fires     fires        fires        fires
//! mistral:7b   fires     fires        SUPPRESSED   SUPPRESSED
//! What it does **not** establish is how far the failure generalises. One
//! served model exhibits it and none is yet confirmed clean, so neither "all
//! served models are at risk" nor "this is specific to `mistral:7b`" follows.
//! Settling that needs a broader matrix

That paragraph now contradicts the PR's central claim and the ADR. Since routing_probe.rs's module docs cite this matrix as the evidentiary basis for the probe's design, a future reader who follows the pointer lands on text saying the question is still open. Update the table to the three measured models and replace the closing paragraph with what the widened run established.

Engineering principle: CLAUDE.md's "do not infer architecture from existing code comments — they may be stale" is a rule about reading; the corresponding obligation when writing is to not leave a comment stale in the same commit that invalidates it.


🟡 Important: the probe adds an unbounded serial generation to the model-load path

📁 packages/daemon/src/services/local_agent_service.rs:1222-1223

probe_routing_ok runs two sequential generations (Stage 1 + the probe turn) inline in load_model_and_collect_events, before the ready event is pushed. max_tokens: None on the probe request (routing_probe.rs:414) means a chatty model that answers in prose instead of tool-calling can generate until the engine's own request timeout — and OpenAiCompatInferenceEngine's request timeout is deliberately long ("a generation legitimately runs for minutes on a slow local model").

The issue explicitly flagged "adds startup latency" as Option C's known cost, so this is accepted in principle, but the unbounded tail is avoidable: the verdict only depends on whether a ToolCallStart chunk arrives, so a modest max_tokens cap (the matrix's arms are the natural reference) bounds the worst case without changing what is measured. Worth confirming the ready event genuinely must wait on this, versus the probe running detached with the session picking up the verdict on the next turn.


🟢 Suggestion: let _ = engine.generate(stage1, …) discards the Stage-1 result silently

📁 packages/agent/src/local_agent/routing_probe.rs:401

The doc comment justifies not aborting on a Stage-1 failure ("the shipped loop warns and continues unrouted on a failed Stage 1, so the probe mirrors that") — good reasoning, and the behavior is right. But the shipped loop warns; the probe silently swallows. If Stage 1 is failing consistently (auth, endpoint shape), the probe's verdict is being formed on a materially different request sequence than intended, and nothing says so. A tracing::debug!/warn! in the error arm would cost nothing and make a misleading verdict diagnosable.


🟢 Suggestion: record_routing_probe_verdict's read-modify-write is genuinely lock-free against the RPC path

📁 packages/daemon/src/services/settings_service.rs:329-363

Answering the question raised in the PR description directly: the current risk is acceptable, but not for the reason the doc comment gives. The comment says "a lost write under a rare concurrent Settings save is not worth a cross-service lock" — true. What it doesn't say is that the failure mode isn't only a lost write: set_open_ai_compat_configs holds write_lock and does its own read-modify-write of the same file, so an interleaving can also drop a concurrent Settings edit (the probe's write serializes a DaemonConfig it read before the Settings save landed, then overwrites the file wholesale). That's a lost user edit, not a lost cache entry.

The window is small (both are sub-millisecond file ops, and a model load concurrent with a Settings save is rare), and nothing here is data the user can't re-enter, so I'd not block on it. But the doc comment should describe the actual worst case rather than the benign one, so whoever revisits this knows what they're weighing. Passing the existing write_lock in would be a small change if you'd rather just close it.

Engineering principle: a comment documenting an accepted risk should state the worst outcome, not the most likely one — that's the information the next reader needs.


🟢 Nit: probe fixtures are duplicated across three files

📁 packages/agent/src/local_agent/routing_probe.rs:354-364 · packages/agent/tests/live_openai_compat_routing.rs:34-43

the_probes_block_matches_the_routed_names_arm deliberately reconstructs the candidate rather than importing it, and the comment explaining why ("a public accessor would let this test trivially pass by construction") is a defensible call — comparing rendered output does test the real property. Noting it only because the same struct literal now exists in three places; if it grows a field, two of them will silently diverge in a way the assert_eq! will catch, so the guard holds. No action needed.


Test Quality

Meaningfully above coverage-padding, with one caveat:

  • routing_disabled_skips_injection_but_keeps_tool_scoping is the important one — it asserts both halves of the design decision (no block header, and search_nodes still scoped), so it would fail if someone "simplified" the gate to also disable scoping.
  • an_engine_error_is_not_a_suppression_verdict guards the exact false-caching hazard the design turns on.
  • editing_model_on_an_undiscovered_config_forces_a_reprobe — the author verified this catches the regression by reverting the fix, and the test's own doc comment is admirably honest that it asserts None == None and only proves re-evaluation happened. That honesty also marks its weakness: it cannot distinguish "re-probed and errored" from "never consulted the cache." A stronger version would point the second load at a base_url that does respond, but given no server in unit tests, the current form is a reasonable ceiling.
  • Gap: no test covers the multi-model-per-config disk-cache path (🔴 above), which is precisely why the collision went unnoticed. A test loading openai-compat:abc:model-a then openai-compat:abc:model-b and asserting the second does not inherit the first's persisted verdict would have caught it and should land with the fix.

Standards Compliance

No lint suppressions, no #[allow(dead_code)], no #[deprecated], no backward-compat scaffolding. routing_ok's #[serde(default)] is schema-evolution tolerance for an on-disk file rather than a compat shim, which is appropriate. Correctly kept out of the gRPC proto. tracing used throughout, no stray println! in production paths. ADR updates landed in nodespace-docs, not in this repo — matches the documentation standard.


Recommendation: REQUEST CHANGES

The architecture is sound and the change is a clear net improvement — I'd merge this happily once the cache key is fixed. Blocking on one item only:

  1. 🔴 Per-config routing_ok collides across models served by one config, silently disabling routing on models the matrix proved clean (+ a regression test).

Strongly recommended alongside it, both cheap:

  1. 🟡 Update the stale matrix module docs — they currently contradict the PR's own finding.
  2. 🟡 Cap the probe's max_tokens to bound model-load latency.

The remaining 🟢 items are optional polish and can be taken or left.

…one config

Critical fix from review: OpenAiCompatConfig.routing_ok was a single
scalar, but one config can discover several served models via /models
(openai-compat:<uuid>:<model>). A scalar let one model's probe verdict
overwrite another's — e.g. mistral:7b measuring suppressed would
silently disable injection for llama3.1:8b, discovered through the
same config and never itself probed as failing. Switched to
BTreeMap<String, bool> keyed by served model; updated the read/write
paths and carry-forward logic in set_open_ai_compat_configs
accordingly (carries forward on unchanged base_url, drops entirely on
a base_url change). Added a regression test reproducing the collision.

Also: bounded the probe's wall-clock time with a 60s timeout wrapper
(not a token cap, which would diverge from the real uncapped
production request), logged Stage-1 probe failures instead of
swallowing them silently, corrected a doc comment describing the
probe-write/Settings-save race's actual worst case, and updated the
routing matrix's module docs to the widened three-model result.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed all findings from the review (commit 12288a0):

🔴 Critical — fixed. OpenAiCompatConfig.routing_ok was a single Option<bool>, but one config can discover multiple served models via /models (openai-compat:<uuid>:<model>), so a scalar let one model's verdict leak onto another's — e.g. mistral:7b measuring suppressed would have silently disabled injection for llama3.1:8b discovered through the same config. Switched to BTreeMap<String, bool> keyed by served model. Read path (local_agent_service.rs) now does config.routing_ok.get(&model); write path (record_routing_probe_verdict) inserts under the probed model's key, matched on base_url only (not the config's pinned model field, which is irrelevant for a discovered model); set_open_ai_compat_configs's carry-forward now carries the whole map when base_url is unchanged and drops it entirely when base_url changes. Added verdicts_for_different_models_on_the_same_config_do_not_collide reproducing the exact scenario from the review.

🟡 Stale matrix docs — fixed. Module doc comment in live_openai_compat_routing.rs now shows the 3-model widened matrix and the "per-model, not native-vs-served" conclusion, replacing the pre-widening two-row table and its now-false "neither generalization is supported" paragraph.

🟡 Unbounded probe latency — fixed, but not via a token cap. Capping max_tokens on the probe request would have made it diverge from the real Stage-2 tool-calling request, which is deliberately uncapped in production (agent_loop.rs: "No cap on tool-calling iterations — truncated args produce invalid JSON"). Instead added ROUTING_PROBE_TIMEOUT (60s) as a tokio::time::timeout wrapper around the whole probe call — bounds wall-clock without changing what's measured; a timeout is treated as an engine error (unmeasured, not a verdict), consistent with the existing error-handling design.

🟢 Stage-1 silent failure — fixed. Now logs at debug level instead of silently discarding.

🟢 Write-lock race doc comment — fixed. Corrected to describe the actual worst case (a lost concurrent Settings-GUI edit, not just a lost cache entry) rather than the benign framing.

All new and existing tests pass (test:all, rust:test, plus the two new regression tests), quality:fix clean, and the full pre-push gate (including the 300s native-model e2e test) passed on repush.

@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1842 (Re-review)

Review Type: Re-review
Scope: f548ad3e..12288a03 — 4 files, +203/−68
Previous verdict: REQUEST CHANGES (1 🔴, 3 🟡, 3 🟢)

Summary

All five items are genuinely addressed, not papered over. The 🔴 fix is the right shape and — importantly — the author found and closed a second, subtler half of the bug that the original review only half-identified: the read-side guard in record_routing_probe_verdict was comparing against the config's pinned model field, which meant a clean discovered model could never write its own Some(true) to displace a poisoned entry. Matching on base_url alone and keying the map by the probed model closes both directions.

The 🟡 latency item was addressed by rejecting the review's suggested remedy in favor of a better one, with the reasoning stated. That's the correct response to a review suggestion that turns out to be wrong, and the justification holds up (see verification below).


Verification of each finding

🔴 Critical — routing_ok cache collision · Fixed, fully

Traced all four sites that touch the field:

  • Type (settings_service.rs:69): Option<bool> → BTreeMap<String, bool>, skip_serializing_if = "BTreeMap::is_empty". BTreeMap over HashMap is the right pick for a TOML-serialized field — deterministic key order means the file doesn't churn on rewrite.
  • Read (local_agent_service.rs:1233): config.routing_ok.get(&model).copied(). model here is the resolved served model (discovery wins over the pinned field, resolved at :1187-1193), which is exactly the key the write side uses. Correct.
  • Write (settings_service.rs:238-250): guard narrowed to entry.base_url != base_url, insert under model. This is the part the original review under-specified and the author got right: keeping entry.model != model in the guard would have left the fix half-broken, since a discovered model never equals the pinned field.
  • Carry-forward (settings_service.rs:412-415): prev.base_url == c.base_url → clone the whole map. The dropped prev.model == c.model condition is now correct rather than merely simplified — each entry self-describes the model it was measured against, so a pinned-model edit invalidates nothing that was measured for other models. The pinned model's own entry also stays valid, since it was measured against that model name and remains keyed by it; a new pinned model is simply a map miss that re-probes.

I checked for missed call sites — grep routing_ok across packages/ returns only the four above plus tests. Nothing in the proto, frontend, or CLI touches it.

Residual invariant (worth noting, not blocking): the disk map now legitimately grows one entry per served model ever probed behind a config, and entries are only ever dropped wholesale on a base_url change. For an Ollama endpoint with a large /models list, this accumulates. It's bounded by the number of models the user actually loads, each entry is a short string plus a bool, and stale entries are harmless (a model no longer served is never looked up), so this is fine as-is — flagging only so nobody is surprised later by a config file with 30 entries.

This also resolves the 🟡 "else if let Some(cached) bypasses the freshness check" finding as a side effect: the read is now get(&model), so freshness is a local property of the lookup rather than an invariant distributed across three call sites. That was the exact remedy suggested, arrived at for free.

🔴 Regression test — Meaningful; would have failed before

verdicts_for_different_models_on_the_same_config_do_not_collide (settings_service.rs:669-716) records mistral:7b → false then llama3.1:8b → true against a config whose pinned model is mistral:7b, and asserts both keys hold their own verdict.

Confirmed against git show f548ad3e:...: the old guard was if entry.base_url != base_url || entry.model != model { return Ok(()) }. The second call (model = "llama3.1:8b" vs pinned "mistral:7b") would have hit that early return and no-opped, leaving routing_ok == Some(false) — mistral's verdict — as the only stored value. The test asserts get("llama3.1:8b") == Some(&true), which the old code cannot produce under any reading. It fails before, passes after. Not a tautology.

The two repurposed tests are also net improvements: record_routing_probe_verdict_noops_when_base_url_changed now isolates the base_url guard specifically (the old combined test conflated two conditions, one of which was the bug), and set_open_ai_compat_configs_carries_forward_verdicts_when_base_url_unchanged gained a second model to assert the map carries as a whole rather than a single entry.

🟡 Stale matrix docs — Fixed

live_openai_compat_routing.rs:43-79 now carries the 3-row table and a new point 3 stating the per-model conclusion explicitly. The old closing paragraph ("neither generalization follows") is replaced with a correctly narrower open question — whether a fourth model shares mistral's failure — which is genuinely still open and is the right residual claim. The parenthetical distinguishing served gemma4:e4b from the locked native model is a good catch; without it the table's third row reads as if it were point 1's data.

No remaining contradiction with routing_probe.rs's module docs, which cite this matrix — I re-read both and they now agree.

🟡 Probe latency — Fixed, and the review's suggestion was correctly rejected

The author declined the max_tokens cap and used a 60s tokio::time::timeout instead. I think this is the better call and the stated reason is sound: capping the probe's max_tokens would make it structurally diverge from the production Stage-2 request it exists to imitate, and the probe's whole design principle (module docs, routing_probe.rs:18-25) is to measure the real request shape conservatively. A cap would introduce a variable the matrix never measured.

On the specific question of whether the wrapper distinguishes "timed out" from "measured suppression" — yes, correctly. local_agent_service.rs:1240-1250:

Err(_) => Err(nodespace_agent::agent_types::InferenceError::Engine(
    format!("routing probe exceeded {ROUTING_PROBE_TIMEOUT:?}"),
)),

The timeout is mapped to Err, and the surrounding match probe_result sends every Err down the arm that yields verdict = None, warns, and — critically — does not call record_routing_probe_verdict. Then routing_disabled = !verdict.unwrap_or(true) → false (routing stays enabled), and active_model_routing_key = verdict.map(|_| ...) → None, so the next load re-probes rather than treating this model as measured. A timeout is therefore unmeasured in all three places it could have leaked (disk, in-memory key, and the disable flag). This preserves exactly the ArmResult::Errored distinction the design turns on.

One asymmetry worth naming, not blocking: a timeout leaves the probe's in-flight HTTP request to be dropped rather than cancelled at the server, so a pathological model keeps generating on the server side until it finishes. That costs the server tokens, not NodeSpace's load path, and the load path is what the finding was about. Acceptable.

60s is a defensible choice — well above the "fires within the first handful of tokens" normal case, well below the engine's deliberately-long request timeout. The constant's doc comment explains both the bound and why the request stays uncapped, which is the information a future reader needs.

🟢 Stage-1 silent failure — Fixed

routing_probe.rs:113-119. debug rather than warn is the right level: a Stage-1 failure is expected-and-tolerated in production too, so warn would train the reader to ignore it. The comment explains why it's logged rather than aborted on.

🟢 Write-lock race doc comment — Fixed

settings_service.rs:206-222 now states the lost-user-edit worst case explicitly, notes the two writers are uncoordinated, and states why the risk is accepted anyway. This is what the finding asked for — the next reader now knows what they're weighing rather than an under-stated version of it.


New issues introduced by these fixes

None blocking. I looked specifically for:

  • Serde round-trip: BTreeMap<String, bool> serializes to a TOML sub-table. #[serde(default)] means an existing on-disk config with no routing_ok key (or the old scalar form) — greenfield, so no migration concern either way — loads as an empty map rather than failing. Correct.
  • Model names as TOML keys: keys like mistral:7b and llama3.1:8b contain : and .. toml::to_string_pretty quotes keys that need it, and the round-trip is exercised by every one of the four tests that writes then reads back through find_openai_compat_config — llama3.1:8b in particular would break on a naive dotted-key serializer, and the test asserting get("llama3.1:8b") == Some(&true) after a real file round-trip proves it doesn't. Good that this is covered incidentally.
  • Clone cost in the carry-forward: prev.routing_ok.clone() per config per Settings save. Trivially small, runs on an RPC that already does file I/O.
  • format! in the timeout error: {ROUTING_PROBE_TIMEOUT:?} renders as 60s. Fine for a log message.

Standards Compliance

Unchanged from the initial review and still clean: no lint suppressions, no #[allow(dead_code)], no #[deprecated], no compat shims. #[serde(default)] remains schema-evolution tolerance for an on-disk file, not a backward-compat scaffold. tracing throughout. Comments explain why rather than what, and the two comments the initial review flagged as under-stating reality were corrected rather than deleted.


Recommendation: APPROVE

The blocking finding is fully closed — including the second half of it the original review only partially identified — with a regression test I verified fails against the pre-fix code. Both 🟡 items and both 🟢 items are addressed. The one place the author disagreed with the review (max_tokens cap vs. timeout wrapper) is a case where the author is right and said why.

No re-review needed. Merge is the author's call.

@malibio
malibio merged commit 011752f into main Jul 31, 2026
2 checks passed
@malibio
malibio deleted the issue-1830-routing-mitigation branch July 31, 2026 05:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Decide the runtime response to routing-suppressed OpenAI-compat models (matrix now exists)

1 participant