Repository navigation
GetStatus blocks a tokio worker for the length of a generation - #1791
Conversation
…#1779) `get_status` reported the loaded model's id and context window by calling `model_spec()` live. That reaches `LlamaChatEngine::model_info()`, which takes the same `std::sync::Mutex` that `generate_blocking` holds for the entire duration of inference — so a status RPC could block a tokio worker for 60-180s during a turn, while holding the `service` read lock. Harmless today only because the sole caller (`nodespace model status`) runs before generation. It is a trap for the next caller: a UI status poller would hang during streaming, several layers from the symptom. Snapshot the spec at engine-swap time instead. `replace_engine` is the single choke point where the geometry can change, and a swap happens between turns, so the mutex is uncontended there. `get_status` now reads a cached value and never touches the engine. `reset_to_noop_engine` bypasses `replace_engine`, so it clears the cache explicitly. Tests: geometry is reported from the swapped engine, cleared on reset, and — the actual regression — a status call returns while a generation holds the engine lock. That last test hangs outright against the pre-fix code, so it runs on a multi-thread runtime and bounds a spawned task's join rather than the call, turning the hang into a clean 5s failure. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr
Code Review: PR #1791 — Cache model geometry so GetStatus cannot block on a generationReview Type: Initial Review Requirements CheckIssue #1779 has no
I independently verified the defect premise rather than taking it on trust:
The blocking path is real, and the fix severs it at the correct point. Verification I PerformedMutation test 1 — does the regression test guard the defect? Reverted only the Fails cleanly in 5.08s, does not hang. The Mutation test 2 — does the reset test guard the cache clear? Deleted only the Both tests fail against their respective defects. This is a genuinely-guarding test suite, not coverage theater. Unmodified: Findings🔴 CriticalNone. 🟡 Important1. 📁 "rust:test": "cargo test --lib -p nodespace-core ... && cargo test --lib --bins -p nodespace-agent ..."
This is pre-existing and not caused by this PR — but this PR is the one that makes it costly, because it is the first change to ship a regression test whose entire purpose is to catch a silent reintroduction. A regression test outside the gate is a comment with a compiler. Principle: a test that isn't executed by the gate provides no regression protection — it documents an intention rather than enforcing it. Suggest a follow-up issue to append 2. 📁 let spec = new_service.model_spec().await.unwrap_or_else(|e| {
tracing::warn!(error = %e, "model_spec failed during engine swap; ...");
None
});Previously a transient I think this is acceptable and would not block on it, for a concrete reason rather than a general one: The 3. 📁 /// The regression this issue is about: `get_status` must not touch the
CLAUDE.md: "Do not embed GitHub issue numbers in documentation content or code comments — describe the behavior/constraint directly." No literal number here, so it's the soft edge of the rule, but "this issue" points at a ticketing artifact the reader of the file cannot see. The sentence is strictly better without it: /// `get_status` must not touch the engine mutex, which a generation holds
/// for its entire duration.
The rest of the comment (which explains why the multi-thread runtime and the bounded join are required) is exactly the kind of intent-not-mechanics commentary the standard asks for — keep all of it. 🟢 Suggestions4. 📁 I enumerated every acquisition of the four
No site holds two of these simultaneously, so the third lock cannot introduce a cycle — the invariant the issue called out is preserved. The Principle: invariants enforced by a single 5. 📁
Not worth doing in this PR — it touches the Principle: SRP applied to state — values that always change together should be guarded together. 6. Cache staleness — I checked for uncovered paths and found none Verified the claim of exactly three
7. Test-stub fidelity is good — one note on the 5s bound
The 5s timeout is only ever paid on failure — the passing path returns in ~0.1s (measured), so it adds no CI time when green. And it cannot flake into a false pass, because the assertion is one-directional: a cached read cannot become slow, only a live query can. If a loaded machine ever made 5s marginal, the failure would be a real signal about Standards Compliance
SummaryA well-executed, tightly-scoped fix that removes a real latent hang rather than papering over it. Three things I want to call out as above-average:
Net effect on code health is clearly positive. The findings are one real coverage gap (finding 1, pre-existing and deserving its own issue), one deliberate trade-off worth confirming (finding 2), one one-word comment fix (finding 3), and the rest are optional. Recommendation: APPROVE (with the comment fix in finding 3, and a follow-up issue for finding 1)Neither blocks merge. Finding 3 is a one-line edit. Finding 1 is the one I would genuinely not let slip — the value of this PR's regression test is contingent on something actually running it. |
malibio
left a comment
There was a problem hiding this comment.
Code Review: PR #1791 — Cache model geometry so GetStatus cannot block on a generation
Review Type: Initial Review
Scope: commit 1aa18482 only (42e395b8 is main's HEAD that landed mid-development, out of scope)
Files: 1 changed — packages/daemon/src/services/local_agent_service.rs
Requirements Check
Issue #1779 has no - [ ] checklist, so validated against the described defect and the suggested fix.
| Requirement | Status | Evidence |
|---|---|---|
get_status must not reach LlamaChatEngine::model_info() |
✅ | get_status now reads inner.loaded_model_spec only; no service.read() remains in the function |
Cache the spec at load time alongside active_model_id |
✅ | loaded_model_spec: Mutex<Option<ChatModelSpec>> added to LocalAgentServiceInner, mirroring active_model_id |
Update it at the replace_engine choke point |
✅ | replace_engine snapshots the spec before taking the service write lock |
get_status non-blocking |
✅ | Verified by mutation test below |
| Preserve reported values (catalog id, granted window) | ✅ | The active_model_id.unwrap_or(spec.model_id) precedence is unchanged; a test now pins it |
I independently verified the defect premise rather than taking it on trust:
packages/nlp-engine/src/chat/mod.rs:343—generate_blockingtakesstate.lock()and holds the guard through the entire decode loop.packages/nlp-engine/src/chat/mod.rs:1120—model_info()takes the sameself.statemutex.packages/agent/src/local_agent/agent_loop.rs:1341—model_spec()is a thin delegate toengine().model_info().
The blocking path is real, and the fix severs it at the correct point.
Verification I Performed
Mutation test 1 — does the regression test guard the defect? Reverted only the get_status line back to the live query:
test ...get_status_does_not_block_while_a_generation_holds_the_engine_lock ... FAILED
panicked at ...:1954:10:
get_status must return while a generation holds the engine lock: Elapsed(())
test result: FAILED. 2 passed; 1 failed; finished in 5.08s
Fails cleanly in 5.08s, does not hang. The multi_thread + bound-the-join construction does what the commit message claims.
Mutation test 2 — does the reset test guard the cache clear? Deleted only the loaded_model_spec clear from reset_to_noop_engine:
test ...get_status_reports_no_model_after_reset ... FAILED
left: "/models/resolved-path.gguf"
right: ""
Both tests fail against their respective defects. This is a genuinely-guarding test suite, not coverage theater.
Unmodified: cargo test --lib -p nodespace-daemon get_status → 3 passed. cargo clippy -p nodespace-daemon --all-targets → clean, no new warnings, no suppressions.
Findings
🔴 Critical
None.
🟡 Important
1. 📁 package.json:58 — the daemon crate is not in any test gate, so these tests never run automatically
"rust:test": "cargo test --lib -p nodespace-core ... && cargo test --lib --bins -p nodespace-agent ..."nodespace-daemon is absent. test:all → rust:test skips it, and scripts/test-gate.ts adds only cargo test -p nodespace-app on top. .github/workflows/ contains only audit.yml, nightly-webkit.yml, and release.yml — no test workflow at all. So the three tests added here, the 88 pre-existing daemon tests, and any future regression of this exact defect run only when someone types the command by hand.
This is pre-existing and not caused by this PR — but this PR is the one that makes it costly, because it is the first change to ship a regression test whose entire purpose is to catch a silent reintroduction. A regression test outside the gate is a comment with a compiler.
Principle: a test that isn't executed by the gate provides no regression protection — it documents an intention rather than enforcing it. Suggest a follow-up issue to append && cargo test --lib -p nodespace-daemon to rust:test. Worth confirming the daemon suite's runtime and hermeticity first (it builds real SqliteStore tempdirs, and the new blocking test costs a guaranteed ~0.1s and a worst-case 5s), so I would not fold that into this PR — but it should not be left implicit.
2. 📁 local_agent_service.rs:210-217 — a spec failure at swap time is now permanent for the life of the engine
let spec = new_service.model_spec().await.unwrap_or_else(|e| {
tracing::warn!(error = %e, "model_spec failed during engine swap; ...");
None
});Previously a transient model_info() error degraded that one status call to None and the next call could recover. Now a failure at swap time is latched: status reports "no model loaded" for the entire lifetime of a correctly-loaded engine, until the next swap.
I think this is acceptable and would not block on it, for a concrete reason rather than a general one: model_info() on the native engine is infallible in practice — it is self.state.lock().map(...), returning None when nothing is loaded rather than Err. Its lock is poison-tolerant (unwrap_or_else(|p| p.into_inner())). So the error arm is close to unreachable for the engine that motivated the change. The remote engines (Ollama, OpenAI-compat) are the ones that could realistically fail — worth a quick check that they don't make a network call in model_info(), because if they do, replace_engine now performs an awaited network round-trip on the model-load path that it previously did not.
The warn! leaves a trail, which is the right call. Flagging so the trade-off is deliberate rather than incidental.
3. 📁 local_agent_service.rs:1801 — code comment references the issue tracker
/// The regression this issue is about: `get_status` must not touch the
CLAUDE.md: "Do not embed GitHub issue numbers in documentation content or code comments — describe the behavior/constraint directly." No literal number here, so it's the soft edge of the rule, but "this issue" points at a ticketing artifact the reader of the file cannot see. The sentence is strictly better without it:
/// `get_status` must not touch the engine mutex, which a generation holds
/// for its entire duration.
The rest of the comment (which explains why the multi-thread runtime and the bounded join are required) is exactly the kind of intent-not-mechanics commentary the standard asks for — keep all of it.
🟢 Suggestions
4. 📁 local_agent_service.rs:218-221 — lock ordering is correct; consider pinning the invariant in a comment
I enumerated every acquisition of the four inner locks across all non-test code:
| Line | Lock | Nesting |
|---|---|---|
| 174 | service.read() |
statement temporary |
| 218 → 221 | service.write() → drop → loaded_model_spec |
sequential, explicit drop |
| 230 (scoped block), 236 | active_model_id |
scoped / temporary |
| 241 → 247, 248 | service.write() → drop → active_model_id, loaded_model_spec |
sequential |
| 755, 759 | loaded_model_spec, active_model_id |
two statement temporaries, each released at ; |
No site holds two of these simultaneously, so the third lock cannot introduce a cycle — the invariant the issue called out is preserved. The drop(guard) at :220 is what makes this true rather than accidental, and it is load-bearing but easy to delete during a later refactor. A one-line note (// Release the service lock before taking the cache lock: no site holds two of these at once.) would make the constraint survive its next reader.
Principle: invariants enforced by a single drop call want a comment, or the next refactor silently removes them.
5. 📁 local_agent_service.rs:755-759 — get_status takes two locks where one struct would do
loaded_model_spec and active_model_id are written together at every site and read together here. They are one logical value ("what is loaded") split across two mutexes. Merging them into a single Mutex<Option<LoadedModel>> would make the coupling structural instead of conventional, and remove the (currently benign) window where a concurrent swap could interleave between :755 and :759 and produce a mismatched id/geometry pair.
Not worth doing in this PR — it touches the unwrap_or precedence logic and would expand a tight one-file diff. Noting it as the natural next consolidation if a third correlated field ever appears.
Principle: SRP applied to state — values that always change together should be guarded together.
6. Cache staleness — I checked for uncovered paths and found none
Verified the claim of exactly three inner.service write sites (:135 construction, :218 replace_engine, :241 reset_to_noop_engine). Specifically checked the paths that could plausibly desync:
- All three engine-load paths (Ollama
:1069, OpenAI-compat:1137, GGUF:1283) route throughreplace_engine. The GGUF path calls it directly rather than viareplace_engine_if_changed— still covered, since the cache write lives insidereplace_engine. replace_engine_if_changedearly return (:230-233): returns only whenactive_model_idalready matches, i.e. the engine is unchanged, so the cache is already correct. Correct.- Load-failure paths: every failure arm
return eventsbeforereplace_engine, leaving both the engine and the cache untouched. Correct. unload_modelRPC (:942): this one is worth stating explicitly. It callsmodel_manager.unload(), which only flips bookkeeping (loaded_model_id/statuses) and never touchesinner.serviceoractive_model_id. So afterUnloadModel,get_statusstill reports the model as loaded. This is unchanged by the PR — the pre-fix live query would have reported the same thing, because the engine itself is still loaded andmodel_info()would still return its spec. Pre-existing inconsistency between the model manager's view and the engine's view, correctly out of scope here, but it is the kind of thing a future "why does status lie after unload?" bug will trace back to.- Post-load geometry drift:
context_windowis set fromChatConfig.n_ctxatLlamaChatInferenceEngine::loadand there is no path that resizes a live context. Caching cannot go stale on this axis.
7. Test-stub fidelity is good — one note on the 5s bound
MutexHeldDuringGenerationEngine faithfully models the real discipline: a std::sync::Mutex taken on a spawn_blocking thread and held across the whole generation, with model_info contending for the same lock. The comment explaining why the guard cannot be held across an await is accurate and useful.
The 5s timeout is only ever paid on failure — the passing path returns in ~0.1s (measured), so it adds no CI time when green. And it cannot flake into a false pass, because the assertion is one-directional: a cached read cannot become slow, only a live query can. If a loaded machine ever made 5s marginal, the failure would be a real signal about get_status doing unexpected work. No change needed; noting it because timeouts in tests usually deserve the scrutiny.
Standards Compliance
| Standard | Status |
|---|---|
| No backward-compat / migration / deprecation code | ✅ Old live-query path deleted outright, not flagged or dual-pathed |
No #[allow(dead_code)] / lint suppression |
✅ None added; cargo clippy --all-targets clean |
| No issue numbers in code comments | 🟡 One soft violation (finding 3) |
| Atomic, single-purpose change | ✅ One file, one concern, tests included |
| Comments explain why not what | ✅ Consistently — the struct-field doc, the swap-site rationale, and the test's runtime-flavor explanation are all genuine intent |
Summary
A well-executed, tightly-scoped fix that removes a real latent hang rather than papering over it. Three things I want to call out as above-average:
- The regression test actually fails against the defect — I mutated the code both ways and confirmed it. That is the failure mode most "regression tests" have, and this one avoids it.
- The stub models the real locking discipline rather than asserting on a mock's call count, so it will keep catching this defect even if the surrounding code is restructured.
- The hang-vs-fail distinction was handled deliberately. The naive version of this test hangs forever against pre-fix code, which is worse than no test — a hung CI job gets retried, a failed one gets read. The multi-thread-runtime + bound-the-join construction converts it into a clean 5s failure, and the comment records why.
Net effect on code health is clearly positive. The findings are one real coverage gap (finding 1, pre-existing and deserving its own issue), one deliberate trade-off worth confirming (finding 2), one one-word comment fix (finding 3), and the rest are optional.
Recommendation: APPROVE (with the comment fix in finding 3, and a follow-up issue for finding 1)
Neither blocks merge. Finding 3 is a one-line edit. Finding 1 is the one I would genuinely not let slip — the value of this PR's regression test is contingent on something actually running it.
…ock a model load Addresses review findings on #1791. The snapshot added in the previous commit is not always a local read. The Ollama engine answers `model_info` with an HTTP POST to /api/show on a `reqwest::Client` built with no default timeout, so an endpoint that accepts the connection and then stalls would hang `replace_engine` — and with it the EnsureModelReady RPC that awaits it. That is a regression the previous commit introduced: before it, nothing called `model_info` on the swap path. Bound the snapshot instead. Losing the geometry only degrades the status report to "no model loaded"; blocking the swap would cost the load itself. The bound is a field rather than a constant so the test can drive the timeout path in 50ms instead of paying the production 10s on every run. The new test bounds the swap on a spawned task rather than awaiting it directly: if the timeout regresses away, `replace_engine` never returns, and an unbounded await would hang the suite rather than fail it. Verified by removing the timeout — it fails cleanly in 5.12s. Also from review: reworded a test comment that pointed at the originating ticket rather than describing the behavior, and documented that the `drop(guard)` before taking `loaded_model_spec` is load-bearing — no site holds two of these locks at once, which is what keeps the ordering acyclic. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr
|
Filed the test-gate gap from review as #1792 rather than folding it into this PR, per the reviewer's recommendation. Confirmed the scope while writing it up: |
Re-Review: PR #1791 — Cache model geometry so GetStatus cannot block on a generationReview Type: Re-Review Previous Review Summary
4 recommendations + 1 deferral. 3 addressed, 1 deferred with justification, 1 optional left open. 2 new findings. Finding 2 was the important one, and the response was correctI re-verified the investigation independently rather than trusting the summary:
So the prior commit did introduce an awaited, unbounded network round-trip on the model-load path ( Worth noting the fix's blast radius is wider than the review that prompted it: Verification I PerformedMutation 1 — does the new test guard the defect? Replaced the Confirms the claim exactly: fails cleanly in 5.11s, does not hang. The spawn-and-bound-the-join construction does what the commit message says. This is the second test in this PR that I have mutated and confirmed genuinely guards its defect. Mutation 2 — assertion strength. I made the Fails in 0.11s. So the Unmodified: Follow-up issue: #1792 "Rust test gate covers 2 of 9 crates: nodespace-daemon's 92 tests never run automatically" exists and is open. Finding 1's deferral was honored, not dropped. Code Review Findings🔴 CriticalNone. 🟡 Important1. 📁 Both the commit message and the new code comment describe the degradation as losing geometry:
But let (model_id, granted_n_ctx) = match spec {
Some(spec) => (active_model_id.unwrap_or(spec.model_id), spec.context_window),
None => (String::new(), 0),
};
My mutation 2 demonstrates this concretely: with a spec present the test sees So the actual user-visible outcome of a 10s Ollama stall is not "correct model, unknown window" — it is "no model loaded", on a model that loaded fine and will generate fine. A status poller and any UI driven by it will show a disconnected/unloaded state for a working agent. The fix is small and local — report what is known: let (model_id, granted_n_ctx) = match spec {
Some(spec) => (active_model_id.unwrap_or(spec.model_id), spec.context_window),
None => (active_model_id.unwrap_or_default(), 0),
};Principle: degrade one axis, not all of them. Losing an optional enrichment (the context window) should not invalidate the authoritative fact next to it (which model is active). Note this also interacts with prior finding 5 — the two-mutex split is precisely what makes it easy to write a 2. 📁 Finding 2 from the prior review flagged latching; this commit bounds the duration but does not change the latching. Now there is a second, more reachable way to latch: a 10s-slow Concretely: user's Ollama is briefly slow during a model load (plausible — I do not think this blocks merge, for a concrete reason: with finding 1 applied, the latched state degrades to "right model, If you want to close it properly later, the cheap version is a repair-on-read: if 🟢 Suggestions3. 📁 Arc::get_mut(&mut svc.inner)
.expect("sole owner before any clone")
.model_spec_snapshot_timeout = short;I checked this specifically since it was called out. It is sound today: The brittleness is that the invariant lives in Cheapest hardening, no production change: take the timeout as a parameter of the test-only constructor path, or have 4. 📁 Judging this pragmatically as asked: it is a plain The alternative — pay 10s of wall-clock in the test — is strictly worse, and the third alternative ( Nit: the doc comment justifies the field purely in terms of tests ("A field rather than a constant so tests can drive the timeout path…"). It would read better if it also noted the production intent, so a future reader doesn't see a test-only smell and inline it back to the constant. 5. 📁 Checked the teardown concern. It is also a better model of the failure than a 6. Comment/standards fixes verified
Standards Compliance
On the 10s valueAsked to scrutinize this specifically. I think 10s is defensible but sits on the wrong side of the trade-off as currently written, and becomes clearly right with finding 1 applied.
That asymmetry argues for the longer bound — which is the choice made. But it only holds because the false-timeout cost is currently permanent. Fix finding 1 and the false-timeout cost drops to "context window shows 0", at which point 10s is comfortably right and could even come down. Either way I would not change the number in this PR. SummaryThe response to the prior review was better than "addressed the comments." Finding 2 was raised as "worth a quick check" — a soft flag on a path I thought was probably fine. The check found a real regression the previous commit had introduced, and the fix landed with a mutation-verified test that fails in 5s instead of hanging the suite. That is the outcome you want from a review comment, and it is the second defect in this PR whose guard I have independently mutated and confirmed. Two things I want to highlight as above-average:
New finding 1 is the one I would take before merge: it is a four-token change ( Recommendation: APPROVEFinding 1 is worth folding in now (one line, and it materially improves the failure mode). Finding 2 and the Ollama-client-timeout note from the finding-2 discussion belong in follow-up issues alongside #1792. Findings 3-6 are optional. |
malibio
left a comment
There was a problem hiding this comment.
Re-Review: PR #1791 — Cache model geometry so GetStatus cannot block on a generation
Review Type: Re-Review
Scope: commit 88b3364f only ("Bound the engine-swap geometry snapshot so a stalled remote cannot block a model load"). 1aa18482 was reviewed and approved previously.
Files: 1 changed — packages/daemon/src/services/local_agent_service.rs
Previous Review Summary
| # | Prior finding | Status | Notes |
|---|---|---|---|
| 1 | 🟡 Daemon crate in no test gate | ⏭️ Deferred — justified | Filed as #1792. Deferral was my own recommendation; correctly honored |
| 2 | 🟡 Spec failure at swap time is latched; confirm remote engines don't do network I/O in model_info() |
✅ Addressed — and it was a real regression | See below |
| 3 | 🟡 Comment referenced the issue tracker | ✅ Addressed | :2003 now reads "The core regression guard: …" |
| 4 | 🟢 drop(guard) load-bearing but undocumented |
✅ Addressed | :229-230 documents the acyclic-ordering invariant |
| 5 | 🟢 loaded_model_spec + active_model_id are one value across two mutexes |
⏭️ Not addressed | Explicitly optional; still true. See new finding 2 — this PR has now produced the first observable symptom of that split |
4 recommendations + 1 deferral. 3 addressed, 1 deferred with justification, 1 optional left open. 2 new findings.
Finding 2 was the important one, and the response was correct
I re-verified the investigation independently rather than trusting the summary:
packages/agent/src/local_agent/ollama_inference.rs:326—model_info()is an HTTP POST to/api/show. Confirmed.ollama_inference.rs:22,31— both constructors usereqwest::Client::new(). NoClientBuilder, no.timeout()anywhere in the file. Confirmed: no default timeout.ollama_inference.rs:401— the transport-error arm isErr(_) => Ok(None). A stalled-but-connected endpoint never reaches it; it just never returns.openai_compat_inference.rs:372— hardcoded spec, no network call. Confirmed.
So the prior commit did introduce an awaited, unbounded network round-trip on the model-load path (ensure_model_ready → load_model_and_collect_events → replace_engine_if_changed → replace_engine), where none existed before. That is a genuine regression, correctly diagnosed and correctly fixed. Bounding rather than removing the snapshot is the right call: the degradation cost is a wrong status field, the alternative cost is a dead model-load RPC.
Worth noting the fix's blast radius is wider than the review that prompted it: OllamaInferenceEngine::generate at :157 performs the same unbounded /api/show call via cached_context_window.get_or_init(…) whenever tools are present. That path is pre-existing, out of scope here, and belongs with #1792-style follow-up rather than this PR — but the underlying defect is the client, not the call site. Suggest a follow-up to give the Ollama reqwest::Client a default timeout at construction, which fixes both sites structurally instead of bounding each caller.
Verification I Performed
Mutation 1 — does the new test guard the defect? Replaced the tokio::time::timeout(…) wrapper with a bare new_service.model_spec().await:
test ...engine_swap_completes_when_model_info_hangs ... FAILED
panicked at ...:1985:10:
engine swap must not block on a stalled model_info: Elapsed(())
test result: FAILED. 0 passed; 1 failed; finished in 5.11s
Confirms the claim exactly: fails cleanly in 5.11s, does not hang. The spawn-and-bound-the-join construction does what the commit message says. This is the second test in this PR that I have mutated and confirmed genuinely guards its defect.
Mutation 2 — assertion strength. I made the Err(_) timeout arm return a Some(spec) instead of None:
assertion `left == right` failed
left: "hanging-model"
right: ""
Fails in 0.11s. So the assert_eq!(status.model_id, "") is load-bearing, not incidental — but it also exposed something about the production behavior (finding 2 below).
Unmodified: cargo test --lib -p nodespace-daemon → 92 passed, 0 failed, 0.85s. cargo clippy -p nodespace-daemon --all-targets → clean, no warnings, no suppressions. Both match the stated claims. Working tree verified clean after reverting both mutations.
Follow-up issue: #1792 "Rust test gate covers 2 of 9 crates: nodespace-daemon's 92 tests never run automatically" exists and is open. Finding 1's deferral was honored, not dropped.
Code Review Findings
🔴 Critical
None.
🟡 Important
1. 📁 packages/daemon/src/services/local_agent_service.rs:788-799 — on timeout, status loses the model id too, not just the geometry
Both the commit message and the new code comment describe the degradation as losing geometry:
"Losing the geometry only costs a degraded status report"
But get_status collapses on spec, not on the two fields independently:
let (model_id, granted_n_ctx) = match spec {
Some(spec) => (active_model_id.unwrap_or(spec.model_id), spec.context_window),
None => (String::new(), 0),
};active_model_id is set unconditionally by replace_engine_if_changed at :270, immediately after replace_engine returns — so at the moment of a timeout the daemon does know the model id. It discards it anyway, because the None arm never consults active_model_id.
My mutation 2 demonstrates this concretely: with a spec present the test sees model_id == "hanging-model"; with the real None it sees "". The id was available in both cases.
So the actual user-visible outcome of a 10s Ollama stall is not "correct model, unknown window" — it is "no model loaded", on a model that loaded fine and will generate fine. A status poller and any UI driven by it will show a disconnected/unloaded state for a working agent.
The fix is small and local — report what is known:
let (model_id, granted_n_ctx) = match spec {
Some(spec) => (active_model_id.unwrap_or(spec.model_id), spec.context_window),
None => (active_model_id.unwrap_or_default(), 0),
};Principle: degrade one axis, not all of them. Losing an optional enrichment (the context window) should not invalidate the authoritative fact next to it (which model is active).
Note this also interacts with prior finding 5 — the two-mutex split is precisely what makes it easy to write a match that forgets one of them. Not blocking, but it is the first time that split has produced a real symptom.
2. 📁 packages/daemon/src/services/local_agent_service.rs:187-247 — the timeout latches; nothing ever retries the snapshot
Finding 2 from the prior review flagged latching; this commit bounds the duration but does not change the latching. Now there is a second, more reachable way to latch: a 10s-slow /api/show on a loaded machine.
Concretely: user's Ollama is briefly slow during a model load (plausible — /api/show on a machine already thrashing on a large model pull). The swap completes, the model works, and status reports "no model loaded" for the entire lifetime of that engine — until the user loads a different model. There is no refresh path, and get_status is now a pure cache read by design, so it cannot self-heal.
I do not think this blocks merge, for a concrete reason: with finding 1 applied, the latched state degrades to "right model, granted_n_ctx == 0" rather than "nothing loaded", which is a far less alarming failure and is arguably tolerable indefinitely. Finding 1 substantially defuses finding 2, which is why I would take finding 1 and leave this.
If you want to close it properly later, the cheap version is a repair-on-read: if loaded_model_spec is None but active_model_id is Some, kick off a bounded background refresh (not an inline await — that would reintroduce the original hang). Worth a follow-up issue rather than this PR.
🟢 Suggestions
3. 📁 local_agent_service.rs:1971-1974 — Arc::get_mut in the test is sound, but its safety is non-local
Arc::get_mut(&mut svc.inner)
.expect("sole owner before any clone")
.model_spec_snapshot_timeout = short;I checked this specifically since it was called out. It is sound today: LocalAgentServiceImpl::new (:141-159) constructs Arc::new(inner) and returns it directly — it never clones the handle, stores it in the executor, or hands it to a spawned task. test_service() (:1638-1650) does nothing but call new. Refcount is 1 at the get_mut, and the .expect would catch it loudly rather than silently if that changed.
The brittleness is that the invariant lives in new(), two hundred lines away, and the expect message asserts it without pointing at it. If someone later has new register the handle somewhere (a watcher, a shutdown registry — plausible given shutdown_token already exists), this test starts panicking with a message that reads like a test bug rather than the design change it actually is.
Cheapest hardening, no production change: take the timeout as a parameter of the test-only constructor path, or have test_service() return the Arc<LocalAgentServiceInner> pre-configured. Optional — the current form fails loudly and correctly, which is the important property.
4. 📁 local_agent_service.rs:99-105 — the injectable timeout field is acceptable DI, not test-only production code
Judging this pragmatically as asked: it is a plain Duration field, initialized from the production constant at the single construction site, read on the production path, with no #[cfg(test)], no test-only constructor, no branch that behaves differently under test. Production behavior is identical to a const. The only cost is 16 bytes in a struct that is allocated once per daemon.
The alternative — pay 10s of wall-clock in the test — is strictly worse, and the third alternative (tokio::time::pause()) would not work here because the hang is a real pending future on a multi_thread runtime, not a timer. This is textbook dependency injection of a policy value. No objection.
Nit: the doc comment justifies the field purely in terms of tests ("A field rather than a constant so tests can drive the timeout path…"). It would read better if it also noted the production intent, so a future reader doesn't see a test-only smell and inline it back to the constant.
5. 📁 local_agent_service.rs:1953-1955 — std::future::pending() is the right stub and leaks nothing
Checked the teardown concern. tokio::time::timeout drops the inner future when the bound elapses, which drops the Pending — it holds no resources, spawns no task, and registers no waker that outlives it. The engine Arc is dropped with the service. #[tokio::test] tears the runtime down at the end regardless, and the 92-test suite completing in 0.85s confirms nothing is lingering.
It is also a better model of the failure than a sleep would be: a real stalled endpoint doesn't resolve after a known delay, and a sleep long enough to be safe would risk a flake on a loaded machine. Correct choice.
6. Comment/standards fixes verified
:2003— "The core regression guard:get_statusmust not touch the engine mutex" — the tracker reference is gone and the sentence describes the constraint directly. Resolves prior finding 3.:229-230— thedrop(guard)now carries "no site holds two of these locks at once, which is what keeps the ordering acyclic," which is the invariant rather than the mechanic. Resolves prior finding 4.- I re-scanned the new code for issue numbers,
#[allow(…)],#[deprecated], and backward-compat scaffolding: none. The old unbounded call was replaced outright, not dual-pathed.
Standards Compliance
| Standard | Status |
|---|---|
| No backward-compat / migration / deprecation code | ✅ unwrap_or_else path replaced outright |
No #[allow(dead_code)] / lint suppression |
✅ clippy --all-targets clean |
| No issue numbers in code comments | ✅ Prior soft violation fixed; nothing new |
| Atomic, single-purpose change | ✅ One file, one concern, test included |
| Comments explain why not what | ✅ The bound, the field, and the spawn-vs-await construction all record intent |
On the 10s value
Asked to scrutinize this specifically. I think 10s is defensible but sits on the wrong side of the trade-off as currently written, and becomes clearly right with finding 1 applied.
/api/show is a metadata read, not inference — sub-second on any healthy Ollama, and slow only when the machine is already saturated. 10s is generous enough that a false timeout requires genuine pathology. The cost of too long is a delayed model load (capped at 10s, visible, self-resolving); the cost of too short is a latched wrong status (invisible, permanent until the next swap).
That asymmetry argues for the longer bound — which is the choice made. But it only holds because the false-timeout cost is currently permanent. Fix finding 1 and the false-timeout cost drops to "context window shows 0", at which point 10s is comfortably right and could even come down. Either way I would not change the number in this PR.
Summary
The response to the prior review was better than "addressed the comments." Finding 2 was raised as "worth a quick check" — a soft flag on a path I thought was probably fine. The check found a real regression the previous commit had introduced, and the fix landed with a mutation-verified test that fails in 5s instead of hanging the suite. That is the outcome you want from a review comment, and it is the second defect in this PR whose guard I have independently mutated and confirmed.
Two things I want to highlight as above-average:
- The hang-vs-fail problem was recognized a second time. The commit message records that an earlier version of this test did hang the suite for 5 minutes before being restructured to bound a spawned join. Noting the failed approach in the message is what stops the next person from "simplifying" it back.
- The bound was chosen over removal. The easy response to "this can hang" is to delete the call and go back to a live query in
get_status— which would have reintroduced the original defect. Bounding preserves the fix and pays for it in the cheaper currency.
New finding 1 is the one I would take before merge: it is a four-token change (String::new() → active_model_id.unwrap_or_default()) that turns the degradation from "the daemon lies about having no model" into "the daemon reports the model with an unknown window," and in doing so largely defuses the latching concern in finding 2. It does not block — the PR is a clear net improvement over both main and its own previous commit either way.
Recommendation: APPROVE
Finding 1 is worth folding in now (one line, and it materially improves the failure mode). Finding 2 and the Ollama-client-timeout note from the finding-2 discussion belong in follow-up issues alongside #1792. Findings 3-6 are optional.
Addresses re-review finding on #1791. `get_status` matched on the cached spec as a whole, so the `None` arm returned an empty model id — discarding `active_model_id`, which the same engine swap had already set and which is still authoritative. The effect: a 10s Ollama stall during a swap made a working, loaded model report as "no model loaded" until the next swap, rather than reporting itself with an unknown context window. The id and the window degrade independently, so treat them that way. The `None` arm now falls back to `active_model_id`, yielding "right model, granted_n_ctx == 0". `reset_to_noop_engine` clears both, so a genuine "nothing loaded" still reports empty — covered by the existing reset test, which passes unchanged. This also defuses most of the latching concern raised in the same review: a latched failed snapshot now costs the window rather than the model's identity. Verified by mutation: restoring the empty-string arm fails `engine_swap_completes_when_model_info_hangs` and nothing else. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr
|
Both re-review findings addressed in Finding 1 — the degradation loses the model id. Confirmed and fixed. The
Mutation-verified: restoring the empty-string arm fails Finding 2 — latching with no retry. Largely defused by the above rather than fixed directly, which matches your read. A latched failed snapshot now costs the context window, not the model's identity. I left Root cause beyond scope — filed as #1793. You were right that the client is the real defect. I confirmed the second path: The call-site timeout here should stay regardless: the daemon shouldn't depend on an engine's internal timeout policy for its own liveness. Also filed #1792 for the test-gate gap.
|
Resolves an import-block conflict in local_agent_service.rs: main added ChatModelSpec (#1791) while this branch added PriorWrite and the agent_loop imports for the duplicate-write guard. Both are needed, so the resolution is the union of the two import lists. No logic conflict. The SelfLimitingWrite doc's claims about handle_update_schema were re-verified against the merged schema/mod.rs (#1788 touched that file): adds still error on an existing name, removes are still retain() calls that converge. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
Closes #1779