Repository navigation
Route LocalAgentService per database over one daemon-global engine, and make DatabaseServices teardown a single complete operation - #2267
Conversation
…nd make DatabaseServices teardown a single complete operation Three DatabaseServices lifecycle bugs shared one gap: nothing owned which instance is authoritative for a database at a given moment. Teardown becomes one operation, `DatabaseServices::shutdown`, called on every path that retires a service set — deliberate close, idle eviction, `shutdown_all`, and a set discarded for losing an open race in `get_or_open` (extracted as `cache_or_discard`). A discarded set was previously just dropped, which stops nothing: its event watcher holds a clone of the very NodeService that owns the sender it waits on, so the channel can never close and the watcher pins its own store for the life of the process. Teardown also now cancels in-flight turns, not just the event watcher, and `evict_idle_databases` skips a database with a turn running. A turn records no activity while it runs and loses the active-database protection as soon as the app's foreground stream moves, so on the activity clock alone a long turn looked exactly like an abandoned database; closing under it left the turn writing to a database the manager had forgotten and the chat node in `processing` for the next open's recovery scan to run a second time. Split LocalAgentServiceImpl into a process-global `SharedLocalAgent` (the chat engine, GGUF model manager, active-model bookkeeping, routing-probe verdicts, OpenAI-compat discovery cache) and the per-database half (tool executor, prompt assembler, turn tokens, token broadcast, event watcher). The loaded model is a machine resource chosen from one model selector, so building an engine per database loaded N copies of the same GGUF and reached only the boot-time default database. Turn state is per-database, so `SubscribeTokenStream`, `CancelTurn` and `GetStatus` now take the same `route()` adapter every other per-database service has, and the desktop client stamps the routing header on local-agent calls. The per-database agent service is built per turn rather than cached, so a swap cannot leave the previous model's weights pinned by a database nobody has chatted with. Deduplicates the atomic turn claim into `begin_turn`/`end_turn`, shared by the event watcher and the recovery scan; `begin_turn` also refuses to start once the database has been shut down. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Self-reviewAdversarial pass over my own diff, calling out where I think a reviewer should push hardest. Not merging on this — core policy needs an independent re-review. 1. The shared/per-database split is the thing to check hardestThe substantive judgement in this PR is what belongs on
The two I'd argue about if I were reviewing: the routing-probe verdict and the discovery cache. Both are properties of a 2. Teardown paths — please re-derive rather than take my wordGrepped and confirmed on the final tree: Ordering inside 3. Residual race I am accepting rather than papering overA turn can still start in the window between the reaper's It is safe by construction instead: teardown cancels the turn, the cancel path settles the node to The narrower thing that does remain possible: the cancelled turn's terminal 4. A wedged turn now pins its database open indefinitely
5. Behaviour changes a reviewer might not expect from the issue text
6. Lock discipline
7. Where I was wrong the first timeMy first implementation cached the per-database 8. Test rigourEach of the five regression tests was verified to fail without its fix and pass with it, by reverting each fix in turn and re-running (race-loser teardown, the eviction guard, the three VerdictAPPROVE with the residual risks in §3 and §4 stated rather than hidden — but requesting an independent re-review before merge, per core policy and because §1 is a judgement call. Note on process: |
Final review (mstomar125)Read the diff directly across the three pieces that matter most: `cache_or_discard` (database_manager.rs): correctly closes #2191 — `evict_idle_databases`'s new `has_active_turns()` check: correctly `SharedLocalAgent` split: the right call, and better than either Good judgment finding and fixing the ONE shared root cause (no owner for APPROVE. Merging — this closes out today's priority-15 batch. |
Closes #2187, Closes #2191, Closes #2193
One root cause, three symptoms
All three issues are the same gap: nothing owns "which
DatabaseServicesinstance is authoritative for this database right now."build_database_servicesstarts background work (ai-chat event watcher, embedding wiring) before it returns, but teardown was ad-hoc — implemented once, inline, inclose_without_notify— and the router bound one per-database service to a boot-time snapshot instead of resolving the authoritative instance per request. That produces three distinct failures:LocalAgentServiceat all — it registers the boot-time default database's.So this is fixed once, not patched three times:
DatabaseServices::shutdown()is now the only way a service set is retired, and every path that retires one calls it — deliberate close, idle eviction,shutdown_all, and a set discarded for losing an open race.#2187 —
LocalAgentServicerouting, over a daemon-global engineThe issue offered two options: route the per-database instances, or collapse to one daemon-global instance. Neither alone is right, because the service is genuinely two halves:
EnsureModelReadyper database would load N copies of the same GGUF and re-pay a multi-minute load on every database switch (the desktop app callsensureModelReadybefore every send).NodeServiceevent bus.So the split is now explicit:
SharedLocalAgent(process-global, onSharedContextnext to the embedding model): the engine,GgufModelManager, active-model id, loaded-model geometry, routing-probe verdicts, OpenAI-compat discovery cache,daemon.tomlpath.LocalAgentServiceImpl(per database): tool executor + prompt assembler,turn_tokens,token_tx, event watcher, shutdown token.route()adapter matchingNodeServiceImpl/ImportServiceImpl/AgentSessionHandler.SubscribeTokenStream,CancelTurnandGetStatusroute; model management does not, because it acts on shared state and reaches the same engine from any database (same reasoning asAgentSessionHandler, where onlylaunch_sessionroutes and the shared PTY ops don't).Arcmoves and two empty maps, and a cached one would pin the previous model's weights in any database that hasn't been chatted with since a swap.local_agentmoves from the "unrouted, daemon-global" group to the routed group, so it carriesx-ns-database-idand is rebuilt on bothset_active_databaseand reconnect. The token-stream subscriber already re-subscribes on a database switch, so it now follows the active database. This is the client-side contract ADR-053 specifies.Net effect: a model loaded once serves every database, and turn state is answered by the database that owns it.
#2191 — race-loser teardown
get_or_open's inline re-check is extracted intocache_or_discard, which callsshutdown()on the discarded set before returning the winner. Dropping theArcnever worked and never could: the watcher task holds a clone of the veryNodeServicethat owns the sender it is receiving from, sorx.recv()can never returnClosedand onlyshutdown_tokencan end the loop.#2193 — mid-turn eviction
evict_idle_databasesnow skips a database whoselocal_agent.has_active_turns(). Two mechanisms make this hold rather than merely usually hold:idle, and the next open'srecover_stuck_turnsfinds nothing to re-run. Previously the turn kept generating against detached handles and the node stayedprocessing, which is exactly what produced the duplicate assistant message and duplicate write-tool side effects.begin_turnalso refuses to start once the shutdown token is cancelled, so a shut-down set cannot pick up new work.Tests
Five regression tests, each verified to fail without its fix and pass with it (checked by temporarily reverting each fix in turn and re-running):
database_manager::a_lost_open_race_shuts_the_discarded_service_set_downdatabase_manager::an_in_flight_turn_defers_idle_evictionlocal_agent_service::turn_state_rpcs_route_to_the_targeted_databaseGetStatus/CancelTurnact on the named database, not the boot defaultlocal_agent_service::token_stream_subscribes_to_the_targeted_databaselocal_agent_service::a_model_loaded_once_serves_every_databaseNoModelLoadedThey assert on behaviour — a cancellation token actually firing, a turn actually being refused, a reply actually coming back from the loaded stub engine — not on a flag recording that a function was called.
Also refactored (production dedup, not test-only): the duplicated atomic "check-and-insert a turn token" in
maybe_handle_ai_chat_nodeandrecover_stuck_turnsis now onebegin_turn, and the fourturn_tokens.remove(...)sites are oneend_turn.Results
bun run test:all— no new failures vs. baseline (frontend 227 files / 4794 tests, unchanged; skill 24; full Rust workspace, 0 failures)bun run quality:fix— clean (eslint, svelte-check, tsc, cargo fmt, clippy-D warnings -D clippy::unused-async)Pro daemon (
nodespaced-pro) is unaffected at the source level: it buildsBaseServicesfrombuild_database_services' bundle, whose shape is unchanged, and it already installsDbManagerLayer, so it picks up the new routing for free. Verified againstnodespace-sync/nodespaced-pro/src/main.rsrather than assumed.🤖 Generated with Claude Code