Skip to content

get_or_open race loser drops DatabaseServices without shutdown — permanent watcher/store leak plus duplicate stuck-turn recovery #2191

Closed

Description

@mstomar125

Problem

DatabaseManager::get_or_open builds a full DatabaseServices set outside the open lock so opens of distinct databases don't serialize, then re-checks under the write lock to converge concurrent first-opens of the same database on one cached handle:

// packages/daemon/src/services/database_manager.rs:851-863
let (services, _embed_task) = build_database_services(&path, &self.context, id.as_str())
    .await
    .with_context(|| format!("opening database {id}"))?;
let services = Arc::new(services);

// Cache under the write lock; if a concurrent caller opened it first,
// drop ours and reuse theirs so every request shares one open handle.
let mut open = self.open.write().await;
if let Some(existing) = open.get(id).cloned() {
    drop(open);
    self.touch(id).await;
    return Ok(existing);
}

When the race loses, services — the local Arc<DatabaseServices> — just falls out of scope. build_database_services (packages/daemon/src/services/assembly.rs:223-228) already started that instance's background work before returning it: local_agent.start_event_watcher() (an ai-chat event-watcher task) and a detached embedding-wiring task. Dropping the Arc does not stop either of them, and nothing here calls local_agent.shutdown() on the loser.

Compare this to the deliberate close path, which does it correctly:

// packages/daemon/src/services/database_manager.rs:902-915
async fn close_without_notify(&self, id: &DatabaseId) -> bool {
    let services = self.open.write().await.remove(id);
    ...
    // Stop the per-database ai-chat event watcher.
    services.local_agent.shutdown();
    if let Some(ready) = services.embedding_state.write().await.take() {
        drop(ready.processor);
    }
    true
}

get_or_open's race-loser branch has no equivalent — the watcher that build_database_services just started is simply abandoned running.

Why the leaked watcher can never exit on its own

start_event_watcher spawns a task that clones self (an Arc<LocalAgentServiceInner> under the hood) into the task, then awaits the node-service event bus with a select! against shutdown_token:

// packages/daemon/src/services/local_agent_service.rs:446-464
pub fn start_event_watcher(&self) {
    let this = self.clone();
    tokio::spawn(async move {
        this.recover_stuck_turns().await;
        let mut rx = this.inner.node_service.subscribe_to_events();
        loop {
            let event = tokio::select! {
                _ = this.inner.shutdown_token.cancelled() => { break; }
                event = rx.recv() => event,
            };
            ...
            Err(broadcast::error::RecvError::Closed) => { break; }
        }
    });
}

this.inner.node_service is the same Arc<NodeService> that owns the broadcast sender the watcher is receiving from (event_tx: broadcast::Sender<...> is a field of NodeService itself — packages/core/src/services/node_service/mod.rs:811, subscribed via subscribe_to_events at line 1820). Because the watcher task holds that Arc<NodeService> alive for as long as it runs, the sender it depends on can never drop — so rx.recv() can never return RecvError::Closed. The only way out of the loop is shutdown_token.cancelled(), which only LocalAgentServiceImpl::shutdown() triggers. A leaked race-loser instance's shutdown() is never called, so its watcher runs for the rest of the daemon's life, permanently pinning that instance's own SqliteStore/NodeService/embedding processor along with it.

Failure scenario

  1. The daemon restarts (or ADR-053 idle-eviction closes a database) while an ai-chat node on some non-default database sits at status: 'processing' with a trailing user message — a normal in-flight turn interrupted mid-generation.
  2. The frontend reconnects and, as usual, fires a burst of parallel RPCs at that database (e.g. list nodes + subscribe + get status, all carrying x-ns-database-id). Two of them land in get_or_open before either has cached its result, so both run build_database_services and both call start_event_watcher().
  3. The loser's Arc<DatabaseServices> is dropped without shutdown(). Its watcher task keeps running forever per the mechanism above — a second SqliteStore connection, NodeService, and background watcher leaked for the remaining lifetime of the daemon process, invisible to close()/close_all() since the registry no longer references it.
  4. Both instances' watchers independently ran recover_stuck_turns() at startup (local_agent_service.rs:450) against the same on-disk database file, and each instance's turn_tokens cancellation map (local_agent_service.rs:189) is per-instance state — the in-map dedup check at recover_stuck_turns (local_agent_service.rs:826) only prevents a second recovery within the same instance, not across the two racing instances. Both spawn run_ai_chat_turn for the same stuck node concurrently.
  5. Result: the same stuck turn executes twice. Each side's optimistic-concurrency retry re-applies its own message append, so the ai-chat node ends up with a duplicated assistant response, and any write-tool calls the turn makes (task creation, node edits, etc.) run twice.

Why it matters

This is exactly the case the get_or_open doc comment says is handled ("concurrent first-opens of the same id converge on a single cached handle") — but only the caching converges; the losing side's side effects (spawned tasks, open DB handle) do not get torn down. Every open-race loss leaks a watcher task plus a database connection for the rest of the process lifetime, and — specifically when it races during startup/idle-reopen recovery — produces duplicate visible output (duplicate assistant messages, duplicate tool effects) on top of the leak.

Suggested fix

In the race-loser branch of get_or_open, call services.local_agent.shutdown() (and anything else close_without_notify tears down, e.g. taking embedding_state) on the discarded Arc<DatabaseServices> before returning existing — mirroring what close_without_notify already does for the deliberate-close path. Longer term, recover_stuck_turns's dedup could also be made robust to concurrent instances (e.g. an actual DB-level claim on the stuck node) rather than relying on each instance's in-memory turn_tokens map, but fixing the leak itself removes the window that makes the duplicate-recovery race reachable in the first place.

Severity

Important. Not a crash, but a real resource leak (unbounded over a long-running daemon's lifetime across repeated races) plus a data-integrity issue (duplicate assistant messages and duplicate write-tool side effects) reachable through an ordinary frontend reconnect burst against a non-default database.

Activity

  1. added
    bug
    on Aug 21, 2026
  2. self-assigned this
    on Aug 21, 2026
  3. mstomar125 commented on Aug 24, 2026

    @mstomar125
    ContributorAuthor

    Baseline (worktree issue-2187-2191-2193-database-services-lifecycle, branched from origin/main @ d393ad1): frontend 227 test files / 4794 tests passed. Fixing #2187, #2191 and #2193 together in one PR — they are three manifestations of the same DatabaseServices lifecycle gap and two of them touch the same lines.

  4. mstomar125 commented on Aug 24, 2026

    @mstomar125
    ContributorAuthor

    Resolved in PR #2267 (#2267).

    All three issues were fixed together: they are three manifestations of one root cause — nothing owned which DatabaseServices instance is authoritative for a database at a given moment. DatabaseServices::shutdown() is now the single, complete teardown (it also cancels in-flight turns) called on every path that retires a service set; evict_idle_databases skips a database with a turn running; and LocalAgentServiceImpl is split into a process-global SharedLocalAgent (engine + model catalog) and a per-database half whose turn-state RPCs route by x-ns-database-id like every other per-database service.

    Five regression tests, each verified to fail without its fix. Awaiting review — not self-merged.

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

Metadata

Metadata

Labels

backendbug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions