Skip to content

Route LocalAgentService per database over one daemon-global engine, and make DatabaseServices teardown a single complete operation - #2267

Merged
mstomar125 merged 1 commit into
mainfrom
issue-2187-2191-2193-database-services-lifecycle
Aug 24, 2026
Merged

mstomar125 merged 1 commit into
mainfrom
issue-2187-2191-2193-database-services-lifecycle

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Closes #2187, Closes #2191, Closes #2193

One root cause, three symptoms

All three issues are the same gap: nothing owns "which DatabaseServices instance is authoritative for this database right now." build_database_services starts background work (ai-chat event watcher, embedding wiring) before it returns, but teardown was ad-hoc — implemented once, inline, in close_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:

manifestation
#2187 The router never resolves the authoritative instance for LocalAgentService at all — it registers the boot-time default database's.
#2191 An instance that stops being authoritative (a lost open race) is dropped without teardown, so it keeps running forever.
#2193 An instance is torn down while still authoritative (mid-turn eviction), and the teardown was incomplete anyway — it never stopped the turn.

So this is fixed once, not patched three times:

  1. Teardown is a single operation. 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.
  2. Teardown is complete. It cancels in-flight turns as well as stopping the watcher and dropping the embedding processor.
  3. Eviction respects in-flight work. The idle reaper skips a database with a turn running, alongside the existing pending-embeddings check.
  4. The router resolves the authoritative instance for local-agent turn state, exactly the way every other per-database service already does.

#2187 — LocalAgentService routing, over a daemon-global engine

The 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:

  • The loaded chat model is a machine resource — gigabytes of weights on one accelerator, chosen from the app's single model selector. Routing EnsureModelReady per database would load N copies of the same GGUF and re-pay a multi-minute load on every database switch (the desktop app calls ensureModelReady before every send).
  • A turn is per-database — its cancellation token, its live token stream, its busy/idle status, and its tool executor all belong to the graph being written into. The event watcher must be per-database: it subscribes to that database's NodeService event bus.

So the split is now explicit:

  • New SharedLocalAgent (process-global, on SharedContext next to the embedding model): the engine, GgufModelManager, active-model id, loaded-model geometry, routing-probe verdicts, OpenAI-compat discovery cache, daemon.toml path.
  • LocalAgentServiceImpl (per database): tool executor + prompt assembler, turn_tokens, token_tx, event watcher, shutdown token.
  • route() adapter matching NodeServiceImpl/ImportServiceImpl/AgentSessionHandler. SubscribeTokenStream, CancelTurn and GetStatus route; model management does not, because it acts on shared state and reaches the same engine from any database (same reasoning as AgentSessionHandler, where only launch_session routes and the shared PTY ops don't).
  • The per-database agent service is built per turn rather than cached — construction is a few Arc moves 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.
  • Desktop client: local_agent moves from the "unrouted, daemon-global" group to the routed group, so it carries x-ns-database-id and is rebuilt on both set_active_database and 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 into cache_or_discard, which calls shutdown() on the discarded set before returning the winner. Dropping the Arc never worked and never could: the watcher task holds a clone of the very NodeService that owns the sender it is receiving from, so rx.recv() can never return Closed and only shutdown_token can end the loop.

#2193 — mid-turn eviction

evict_idle_databases now skips a database whose local_agent.has_active_turns(). Two mechanisms make this hold rather than merely usually hold:

  • The check itself covers the ordinary case (long turn on a backgrounded database).
  • Because teardown now cancels turns, the residual race (a turn starting between the check and the close) degenerates safely: the turn is cancelled, its cancel path settles the node back to idle, and the next open's recover_stuck_turns finds nothing to re-run. Previously the turn kept generating against detached handles and the node stayed processing, which is exactly what produced the duplicate assistant message and duplicate write-tool side effects.

begin_turn also 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):

Test Covers
database_manager::a_lost_open_race_shuts_the_discarded_service_set_down #2191 — discarded set's in-flight turn is cancelled and it refuses further turns
database_manager::an_in_flight_turn_defers_idle_eviction #2193 — reaper skips a mid-turn database, evicts it once the turn settles
local_agent_service::turn_state_rpcs_route_to_the_targeted_database #2187 — GetStatus/CancelTurn act on the named database, not the boot default
local_agent_service::token_stream_subscribes_to_the_targeted_database #2187 — live tokens follow the named database
local_agent_service::a_model_loaded_once_serves_every_database #2187 — a turn on a second database runs against the daemon's loaded engine instead of failing NoModelLoaded

They 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_node and recover_stuck_turns is now one begin_turn, and the four turn_tokens.remove(...) sites are one end_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 builds BaseServices from build_database_services' bundle, whose shape is unchanged, and it already installs DbManagerLayer, so it picks up the new routing for free. Verified against nodespace-sync/nodespaced-pro/src/main.rs rather than assumed.

🤖 Generated with Claude Code

…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]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

Self-review

Adversarial 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 hardest

The substantive judgement in this PR is what belongs on SharedLocalAgent versus what stays per-database, and an author's own model of that is exactly what needs an outside check. My rule was: anything that reads or writes one graph stays per-database; anything that describes the one loaded model is shared.

  • Per-database: tool executor, prompt assembler, turn_tokens, token_tx, event watcher, shutdown token.
  • Shared: engine, GgufModelManager, active_model_id, loaded_model_spec, active_model_routing_disabled / active_model_routing_key, OpenAI-compat discovery cache, daemon_config_path.

The two I'd argue about if I were reviewing: the routing-probe verdict and the discovery cache. Both are properties of a (base_url, served_model) pair and of daemon.toml, neither of which is per-database — and the discovery cache's existing doc comment explicitly called out "potentially many instances under ADR-053" as the reason it had no cross-instance invalidation, which this change removes. I think shared is right; it is a defensible call rather than an obvious one.

2. Teardown paths — please re-derive rather than take my word

Grepped and confirmed on the final tree: local_agent.shutdown() has exactly one caller (DatabaseServices::shutdown), and DatabaseServices::shutdown has exactly four (cache_or_discard's loser branch, close_without_notify, shutdown_all, and the reaper via close). The claim "no path retires a service set without tearing it down" rests entirely on that being exhaustive, so it is worth re-deriving independently.

Ordering inside shutdown() is deliberate: shutdown_token.cancel() runs before walking turn_tokens, so a turn starting between the two cannot exist — begin_turn checks the token first and refuses. The walk does not clear the map; each turn removes its own entry via end_turn as it settles, which is also what keeps has_active_turns true (and eviction still deferred) while cancelled turns wind down.

3. Residual race I am accepting rather than papering over

A turn can still start in the window between the reaper's has_active_turns check and the close. I did not close it with a lock, because that would mean holding the open map across an await on per-database state.

It is safe by construction instead: teardown cancels the turn, the cancel path settles the node to idle, and the next open's recover_stuck_turns therefore finds nothing to re-run. The pre-change failure mode — a detached turn generating to completion, node left in processing for recovery to duplicate — is not reachable through this window.

The narrower thing that does remain possible: the cancelled turn's terminal idle write and a reopened instance's recovery scan can interleave, so a recovery turn could start while the old one is winding down. That is not duplicate execution (a cancelled turn makes no further inference or tool calls — it only writes its status), so the visible outcome is one assistant message, not two. Stating this rather than claiming the race is gone.

4. A wedged turn now pins its database open indefinitely

has_active_turns defers eviction with no timeout, exactly as has_pending_embeddings already does. Preferring a retained handle over duplicate turn execution is the deliberate trade; a turn that never completes is a separate bug from this one. If a reviewer wants a ceiling on that, it should be its own issue rather than smuggled in here.

5. Behaviour changes a reviewer might not expect from the issue text

  • SubscribeTokenStream now opens the target database. Routing runs get_or_open, so subscribing with a header lazily opens (and touches) that database. Consistent with every other routed RPC, and desirable — you are subscribing to it — but it is new behaviour for that endpoint.
  • GetStatus's model_id / granted_n_ctx are now identical across databases. That is the point (one engine), but it means the field no longer distinguishes databases.
  • MODEL_MANAGER_UNAVAILABLE wording changed from "for this database" to daemon-wide, because that is now true. No test asserts on the string.
  • shutdown_all cancels turns on daemon shutdown. Best-effort — the process exits shortly after, so a terminal idle write may not land. Strictly better than the previous behaviour (killed mid-flight with the node left processing), not a regression.
  • remove() on a mid-turn database now cancels the turn. remove() unregisters but does not delete files, so the terminal write lands on a file that still exists.

6. Lock discipline

SharedLocalAgent holds engine and loaded_model_spec and never both at once — set_engine drops the engine write guard before taking loaded_model_spec, preserving the acyclic ordering the original code documented. No site takes a per-database turn_tokens and a SharedLocalAgent lock in both orders; get_status is now explicitly scoped so it does not hold the turn map across the shared reads at all (it previously did).

7. Where I was wrong the first time

My first implementation cached the per-database AgentService, keyed by an engine generation counter bumped on each swap. It worked and all tests passed. I removed it: construction is a handful of Arc moves plus two empty maps, it happens once per turn, and a cache would keep the previous model's weights alive in any database not chatted with since a swap — real memory for no measurable gain. If the per-turn rebuild looks naive, that is why it is deliberate.

8. Test rigour

Each 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 route() call sites, and the shared engine). I would rather a reviewer spot-check one of those than trust this summary.

Verdict

APPROVE 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: bun run gh:status could not set the board status — scripts/github-client.ts targets projectV2(number: 5), which does not resolve. Pre-existing tooling bug, unrelated to this change; I set the status directly via GraphQL against org project #2 instead and left the script alone.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Final review (mstomar125)

Read the diff directly across the three pieces that matter most:

`cache_or_discard` (database_manager.rs): correctly closes #2191 —
the race loser now goes through the same `DatabaseServices::shutdown()`
the deliberate-close path uses, instead of just falling out of scope. The
doc comment correctly identifies why a dropped `Arc` alone doesn't stop
the leak (the event watcher holds a clone of the very `NodeService` whose
sender it's waiting on, so the channel never closes on its own).

`evict_idle_databases`'s new `has_active_turns()` check: correctly
closes #2193, and the reasoning for why activity-clock-alone and active-
database-alone both fail to protect an in-flight turn is sound and
verified by `an_in_flight_turn_defers_idle_eviction` — genuinely tests
the eviction-then-recovery-double-run failure mode, not just a flag.

`SharedLocalAgent` split: the right call, and better than either
option the issue offered. Global engine/model-catalog (correctly avoids
loading N copies of the same GGUF weights), per-database turn state/event
watcher (correctly graph-bound). The desktop `grpc_client.rs` change
moving `local_agent` into the routed-client group matches this exactly —
turn cancellation/token-stream/status are per-database even though the
model itself is daemon-global, and the doc comment explains precisely why
that split is necessary, not just asserted.

Good judgment finding and fixing the ONE shared root cause (no owner for
"which DatabaseServices instance is authoritative right now") instead of
three point-patches, and good judgment removing your own first-cut
per-database service cache after recognizing it would pin stale model
weights for no gain.

APPROVE. Merging — this closes out today's priority-15 batch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment