Skip to content

Per-database compute scoping: embedding queues, agent watchers, and idle eviction #1534

Closed

Description

@malibio

Overview

ADR-053 §1/§4 compute follow-through (../nodespace-docs/decisions/053-one-daemon-multiple-databases.md): with N databases open in one daemon (#1532), the store-bound background machinery — embedding processing, agent event watching, context assembly, sessions — must be scoped per database while sharing the single loaded model set.

Problem Statement

Today one EmbeddingProcessor, one local-agent event watcher, one GraphContextAssembler, and one agent-session state map exist per process, all bound to the single store. Opened as-is per database, they would contend without priority; left global, they would process the wrong database.

Proposed Solution

One instance of each store-bound worker per open database; all embedding processors share the one Arc<EmbeddingService> with active-database priority; local-only databases idle-close.

Implementation Approach

  • Embedding: one EmbeddingProcessor + waker per open database, each draining its own database's stale-flag queue (embedding table stale column). All share the process-global Arc<EmbeddingService>; scheduling prefers the active database so a background import cannot starve foreground semantic-search freshness. The text-keyed LRU cache on EmbeddingService stays shared (same text → same vector; benign across databases).
  • Agent: per-database local-agent event watcher and GraphContextAssembler; agent session state (AgentSessionHandler maps, session dirs) keyed by database id. PtySessionManager OS plumbing stays global. Chat model stays global with its single inference lock — turns from different databases queue (accepted in ADR-053).
  • Import: ImportServiceImpl bound per database via the routing extension.
  • Idle eviction: close a local-only database's service set after a configurable idle window (no client requests, no pending embeddings). The active database and any database mid-drain never evict. drain_gpu continues to run once at daemon shutdown after all databases close.

Acceptance Criteria

  • Embedding backlogs drain independently per database; active database's queue takes priority (test: bulk import into database B while database A is active; A's new-node embeddings complete first)
  • Agent events and chat sessions in database A never leak into database B (test with concurrent sessions)
  • Idle local-only databases close and release their store connection; next request reopens transparently
  • One embedding model instance serves all databases (assert no second model load)
  • Tests pass (bun run test:all)
  • Code passes bun run quality:fix

Technical Specifications

Reference Files

  • Processor: packages/core/src/services/embedding_processor.rs
  • Embedding service binding: packages/core/src/services/embedding_service.rs — NodeEmbeddingService::new(model, store, …)
  • Model internals: packages/nlp-engine/src/embedding.rs — stateless-per-call encode, shared LRU cache
  • Agent service: packages/daemon/src/services/local_agent_service.rs — event watcher, model managers
  • Session handling: packages/daemon/src/services/agent_session_service.rs

Implementation Details

  • Embedding inference is stateless per call (KV cache cleared each encode) — safe to interleave databases; serialization happens on the existing internal mutex.
  • EmbeddingService::shutdown()/release_gpu_context() are one-way and tear down for all sharers — only the daemon shutdown path may call them, never database close.

Dependencies

Non-Goals

Per-database fairness scheduling beyond simple active-first priority; sync-related residency rules (sync issue pins the active synced database).

Activity

  1. self-assigned this
    on Jul 7, 2026
  2. mstomar125 commented on Jul 7, 2026

    @mstomar125
    Contributor

    Not picked up today — hard-blocked by #1532.

    Every artifact this ticket scopes (DatabaseManager, Arc<DatabaseServices>, the build_shared_services/build_database_services split, the routing interceptor, the "active database" concept) is introduced by #1532, which is still open. Even after #1532 merges, this is a fiddly ~1–2 day Rust concurrency change (cross-database active-first scheduling, idle-eviction with never-evict-active/mid-drain guards, session keying, four multi-database integration tests). Ordered after #1532.

  3. mstomar125 commented on Jul 10, 2026

    @mstomar125
    Contributor

    Approach / design notes

    Mapped the current architecture: most of the per-database scoping already landed with the ADR-053 daemon core — each open database already gets its own EmbeddingProcessor (draining its own store's stale queue), its own LocalAgentServiceImpl event watcher (subscribed to that database's event bus, filtered to ai-chat), its own GraphContextAssembler, and its own AgentSessionHandler over the shared PtySessionManager. The single embedding model is already process-global (published once over a watch channel, shared text-keyed LRU). So "no A→B leak" and "one model instance" are already structurally true and mainly need tests.

    The remaining work this issue delivers:

    1. Per-database close + task cancellation — a DatabaseManager::close(id) that cancels the database's agent event watcher (new CancellationToken on LocalAgentServiceImpl) and drops its EmbeddingProcessor, without releasing the shared model's GPU context (that stays a daemon-shutdown-only, all-sharers teardown).
    2. Shutdown drains all open databases — today only the boot database's processor is drained; shutdown now iterates every open database, then releases the shared GPU context once.
    3. Active-first embedding priority — a process-global EmbeddingScheduler shared by all per-database processors. While the active database has pending embedding work, non-active databases defer at batch granularity (a background bulk import into B can't starve foreground semantic-search freshness in A). The active-database signal is the live WatchNodes stream — the desktop already opens exactly one on the active database and re-subscribes on switch, so no protocol change is needed.
    4. Idle eviction — a reaper closes non-default, non-active, idle (default 5 min) local-only databases with no pending embeddings and releases their store connection; the next request reopens transparently via the existing lazy get_or_open.
    5. Acceptance tests for per-database drain + active priority, no cross-database leak, idle close/reopen, and single-model assertion.

    Non-goals unchanged (no fairness beyond active-first; sync residency pinning is the sync issue's concern). Community single-database behavior is unchanged (one open database, always active, never evicted).

  4. mstomar125 commented on Jul 10, 2026

    @mstomar125
    Contributor

    Resolved in #1603 (merged).

    Delivered the ADR-053 §1/§4 compute follow-through. Most per-database scoping already existed from the ADR-053 daemon core (each open database already has its own embedding processor, agent event watcher on its own event bus, context assembler, and session handler; the embedding model is a single process-global instance). This change added:

    • Active-first embedding priority — a process-global EmbeddingScheduler shared by all per-database processors; non-active databases defer at batch granularity while the active database has queued work (a background bulk import can't starve foreground semantic-search freshness). The active-database signal is the live WatchNodes stream — no protocol change. A sole/community database is never deferred (no active ⇒ nothing defers), and no database is permanently starved.
    • Per-database close + watcher cancellation (DatabaseManager::close) that drops only that database's embedding processor and cancels its agent watcher — never releasing the shared model's GPU context (that stays a daemon-shutdown-only, all-sharers teardown).
    • Shutdown drains all open databases then releases the shared GPU context exactly once (previously only the boot database was drained).
    • Idle eviction of non-default, non-active, idle (default 5 min) local-only databases with no pending embeddings; the next request reopens transparently.

    All acceptance criteria met. Validated green locally before the PR (full test:all + test:e2e + cargo test -p nodespace-app via the pre-push gate; cargo test -p nodespace-core/-p nodespace-daemon including the 5 per_db_compute acceptance tests; fmt + clippy clean). Independently reviewed for concurrency/teardown/eviction safety (no deadlock, no starvation, teardown once-only). Community single-database behavior is unchanged.

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions