Skip to content

Idle reaper can evict a database with an agent turn in flight, causing duplicate turn execution on reopen #2193

Closed

Description

@mstomar125

Problem

The idle reaper's eviction check (evict_idle_databases, packages/daemon/src/services/database_manager.rs:958) only holds off closing a database for two reasons: it's the default/active database, or it has queued embedding work (has_pending_embeddings). It never checks whether the database has an ai-chat turn in flight:

// packages/daemon/src/services/database_manager.rs:958-998
pub async fn evict_idle_databases(&self, window: Duration) {
    let default_id = self.registry.read().await.default_database.clone();
    let active_id = self.context.scheduler.active_id();
    let now = Instant::now();

    let candidates: Vec<(DatabaseId, Arc<DatabaseServices>)> = {
        let open = self.open.read().await;
        let activity = self.last_activity.read().await;
        open.iter()
            .filter(|(id, _)| default_id.as_ref() != Some(*id))
            .filter(|(id, _)| active_id.as_deref() != Some(id.as_str()))
            .filter(|(id, _)| {
                activity
                    .get(*id)
                    .map(|seen| now.duration_since(*seen) > window)
                    .unwrap_or(false)
            })
            .map(|(id, services)| (id.clone(), services.clone()))
            .collect()
    };

    for (id, services) in candidates {
        if has_pending_embeddings(&services).await {
            continue;
        }
        if self.close(&id).await {
            ...
        }
    }
}

The idle test is entirely activity-based (self.last_activity), and last_activity is only ever touched from DatabaseManager itself — the only call sites of touch() are all in database_manager.rs (open/get_or_open paths):

packages/daemon/src/services/database_manager.rs:462:  self.touch(&id).await;
packages/daemon/src/services/database_manager.rs:838:  self.touch(id).await;
packages/daemon/src/services/database_manager.rs:861:  self.touch(id).await;
packages/daemon/src/services/database_manager.rs:866:  self.touch(id).await;

local_agent_service.rs — the module that runs an ai-chat turn end-to-end (the ai-chat event watcher, tool execution, append_assistant_message) — has zero references to DatabaseManager or touch(). It already holds its own Arc<NodeService>/Arc<DatabaseServices> handles from when the database was opened, so a turn never needs to route back through get_or_open, and therefore never records activity while it runs. A database can sit in status: 'processing' for the entire duration of a slow local-inference turn (plus however many tool calls it makes) while last_activity stays frozen at whenever the last RPC landed.

Compounding this, WatchNodes is what marks a database "active" (packages/daemon/src/services/node_service.rs:1601, this.scheduler.set_active(Some(this.database_id.clone()))), and the desktop app opens exactly one such stream, on whichever database is in the foreground. So switching the app to a different database immediately un-marks the database a turn is still running on — it loses both of the reaper's two protections (not-idle and active) at once, while has_pending_embeddings protects only queued embedding work, not an in-flight LLM turn or its tool calls.

Once evict_idle_databases selects the database, close_without_notify (database_manager.rs:902-916) calls services.local_agent.shutdown(), which only cancels shutdown_token — checked exclusively inside the event watcher's select! loop (local_agent_service.rs:457). The in-flight turn is a separately spawned task (tokio::spawn(... this.run_ai_chat_turn(node_id, cancel) ...)) that never checks shutdown_token, only its own per-turn CancellationToken from turn_tokens — which shutdown() does not touch. So closing the database stops the watcher and drops the embedding processor, but the turn keeps running underneath, writing through its own already-cloned Arcs to a database the manager no longer considers open.

Failure scenario

  1. User sends an ai-chat message on non-default database X. A turn starts: run_ai_chat_turn is spawned, doing local inference plus tool calls — easily minutes for a non-trivial request.
  2. Before the turn finishes, the user switches the desktop app to database Y (opening a new WatchNodes stream, which flips scheduler.active_id() to Y) or quits/backgrounds the app entirely. Either way, no more RPCs land on X, so last_activity[X] stops advancing — and X is no longer the active database either.
  3. X's turn keeps running (inference + tool calls), touching only local_agent_service's own handles, so last_activity[X] never updates during this whole window.
  4. After the idle window (5 minutes) elapses, the reaper's next tick finds X idle, not default, not active, with no pending embeddings, and closes it — despite the turn still being in progress. close_without_notify shuts down X's watcher and drops its embedding processor; the spawned turn task is untouched and keeps running against its captured Arcs.
  5. Any subsequent request to X calls get_or_open, which reopens X fresh and calls start_event_watcher() → recover_stuck_turns(). That scan finds the ai-chat node still at status: 'processing' with a trailing user message (the original turn hasn't finished/wasn't cancelled) and spawns a second run_ai_chat_turn for the same node, racing the still-running original.
  6. Both turns finish independently: each appends its own assistant message (two visible replies for one user turn), and each executes its own copy of any write tools (create_node, update_node, ...) — the cross-turn duplicate-write guard is seeded from the same pre-turn message history on both sides, so neither instance's guard sees the other's writes and both apply.

File/line

packages/daemon/src/services/database_manager.rs:958 (evict_idle_databases)

Severity

Important. Not a crash, but a data-integrity issue reachable through ordinary use (switching the active database, or quitting the app, while a turn is still running) — duplicate assistant messages and duplicate write-tool side effects on the database that got evicted mid-turn. Related to but distinct from #2191 (which covers a concurrent-open race at get_or_open time); this is a time-based eviction path with a different root cause — the idle check has no concept of "turn in flight" at all.

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