Skip to content

Scope daemon compute per database (ADR-053): active-first embedding priority, close + idle eviction - #1603

Merged
mstomar125 merged 4 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-per-db-compute
Jul 10, 2026
Merged

mstomar125 merged 4 commits into
NodeSpaceAI:mainfrom
mstomar125:ns/adr053-per-db-compute

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Summary

ADR-053 §1/§4 compute follow-through: with N databases open in one daemon, the store-bound background machinery is now scoped per database while sharing the single loaded embedding model.

Most per-database scoping already landed with the ADR-053 daemon core — each open database already has 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 embedding model is process-global (published once over a watch channel, shared text-keyed LRU). This change adds the remaining lifecycle and priority behavior.

What's new

  • Active-first embedding priority — a process-global EmbeddingScheduler (in nodespace-core, keyed on the database ULID as a plain String so core stays free of any daemon type) that all per-database EmbeddingProcessors share. Each processor acquires a permit around every batch; while the active database has batches queued, non-active databases defer at batch granularity, so a background bulk import into B cannot starve foreground semantic-search freshness in A. The active-database signal is the live WatchNodes stream — the desktop already opens exactly one on the database it displays and re-subscribes on switch, so no protocol change is needed. A non-active database is never permanently starved: it resumes the moment the active database goes idle, and with no active database (None) every database runs immediately.
  • Per-database close + task cancellation — DatabaseManager::close(id) drops only that database's EmbeddingProcessor and cancels its agent event watcher (a new CancellationToken on LocalAgentServiceImpl). It never calls release_gpu_context()/shutdown() on the shared nlp-engine model — that is one-way and global, reserved for daemon shutdown.
  • Shutdown drains all open databases — previously only the boot database's processor was drained; shutdown now iterates every open database (shutdown_all), then releases the shared GPU context exactly once.
  • Idle eviction — a reaper closes non-default, non-active, idle (default 5 min, overridable via NODESPACE_DB_IDLE_SECS) local-only databases that have no pending embeddings, releasing their store connection; the next request reopens transparently via the existing lazy get_or_open.

Acceptance criteria

  • Embedding backlogs drain independently per database; the active database's queue takes priority — EmbeddingScheduler + a unit test that distinguishes active-first from a plain FIFO gate (a non-active batch queued before a later active batch is still granted second).
  • Agent events and chat sessions in database A never leak into database B — per-database event watcher + session handler; covered by per_db_compute test.
  • Idle local-only databases close and release their store connection; next request reopens transparently — reaper + close + get_or_open rebuild; covered by tests.
  • One embedding model instance serves all databases — the model stays process-global; no second load.
  • bun run test:all green; cargo fmt + cargo clippy --workspace -- -D warnings clean.

Non-goals (unchanged)

Per-database fairness beyond simple active-first; sync residency pinning (the sync issue pins the active synced database). Community single-database behavior is unchanged — one open database, always effectively active, never evicted.

Review

Independently reviewed (adversarial pass over the scheduler concurrency, GPU-teardown safety, eviction guards, and watcher cancellation) — no deadlock, no lost-wakeup, no permanent starvation, teardown once-only-on-shutdown. Follow-up fixes from that review: strengthened the active-first unit test to genuinely distinguish priority from FIFO, RAII-guarded the active-waiter count so a cancelled acquire can't leak it, and made the reaper treat a not-yet-recorded database as freshly used rather than idle.

Closes #1534.

Mayank Tomar and others added 4 commits July 10, 2026 08:49
Introduce a process-global EmbeddingScheduler that gates the single shared
embedding model and grants the active database's batches priority over other
open databases. It keys on the database id as a plain String so this core
type stays free of any daemon-side identifier.

The scheduler exposes set_active/active_id/is_active plus an async acquire
that returns a SchedulerPermit: the active database registers as a
high-priority waiter and contends for the gate directly, while a non-active
database defers on a notifier until no active batches remain, then contends.
The permit re-evaluates priority on drop, so non-active work is never
starved permanently.

EmbeddingProcessor::new now takes the scheduler and this database's id, and
process_until_empty acquires a permit around each batch, releasing it
between batches so a higher-priority database can interleave.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…DR-053)

Carry the shared EmbeddingScheduler in SharedContext and build one instance
in build_shared_services. Each database's embedding processor is wired with
the scheduler and its registry id; NodeServiceImpl holds the scheduler and
marks its database active on a live WatchNodes stream, so the foreground
database's embedding work takes priority with no protocol change.

Add per-database lifecycle to DatabaseManager:
- close(id): drop only that database's embedding processor and cancel its
  ai-chat event watcher, never releasing the process-global GPU context.
- shutdown_all(): drain every open database's compute on daemon shutdown.
- last_activity tracking touched on every routed request, plus an idle
  reaper (spawn_idle_reaper/evict_idle_databases) that evicts non-default,
  non-active, non-busy databases past the idle window; evicted databases
  reopen transparently on their next request. remove() now tears down
  compute as well as the registry entry.

LocalAgentServiceImpl gains a shutdown CancellationToken that stops its
event watcher promptly when the database is closed.

main.rs spawns the reaper at startup and, on shutdown, drains all databases
then releases the shared GPU context exactly once (replacing the per-default
drain_gpu). The idle window is overridable via NODESPACE_DB_IDLE_SECS.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Cover idle eviction of an idle non-default database and its transparent
reopen, the default and active databases never being evicted, shutdown_all
closing every open database, and per-database routing keeping ai-chat nodes
from leaking across databases. Active-first embedding priority is proven by
the EmbeddingScheduler unit test in nodespace-core, which needs no model.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The active-first unit test registered the active batch before the deferred
non-active one, so a plain FIFO gate would produce the same ordering — it did
not distinguish priority from FIFO. Rewrite it so a non-active batch queues
before a second active batch and assert the active batch is still granted first.

Guard the high_waiters increment with an RAII reservation so an acquire future
cancelled while awaiting the gate releases the count instead of leaking it (a
leak would defer every non-active database forever).

Treat a database with no recorded activity as freshly used, not idle, so the
idle reaper cannot evict one in the sub-window between opening it and recording
its first activity.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE

Reviewed independently (my own read plus an adversarial pass focused on the new concurrency primitive) with special scrutiny on the four highest-risk areas:

  • EmbeddingScheduler concurrency — traced line by line: no deadlock (the 1-permit gate is held only for one batch; the active mutex is never held across an await), no lost-wakeup (non-active waiters use the Notified::enable() register-before-check ordering), and no permanent starvation (an active batch drops its permit and yield_nows each batch, opening a real high_waiters == 0 window for deferred non-active waiters). Critically, the sole/community database never defers forever — with no active database high_waiters stays 0, so a lone database's non-active path breaks out on the first check.
  • GPU teardown safety — release_gpu_context() has exactly one call site (daemon shutdown, once, after shutdown_all); per-database close/remove/evict/shutdown_all only drop that database's processor and cancel its watcher, never touching the shared model.
  • Idle eviction guards — the reaper skips the default, the scheduler-active, and any pending-embedding database, and collects candidates before releasing locks (never holds open across an await); evicted databases reopen transparently via get_or_open.
  • Watcher cancellation — close() calls shutdown(), whose CancellationToken breaks the watcher's select! loop; the task's captured Arc is released on exit so it can't outlive the database.

Follow-up fixes applied from the review (commit 14a3ab01): (1) the active-first unit test previously registered the active batch before the deferred one, so a plain FIFO gate would produce the same ordering — rewrote it so a non-active batch queues before a second active batch and asserted the active one is still granted first (genuinely distinguishes priority from FIFO); (2) RAII-guarded the high_waiters increment so an acquire future cancelled while awaiting the gate releases the count instead of leaking it; (3) the reaper now treats a not-yet-recorded database as freshly used, not idle.

Validated green locally before pushing: full test:all + test:e2e + cargo test -p nodespace-app via the pre-push gate; cargo test -p nodespace-core (1259) and -p nodespace-daemon (87, incl. the 5 per_db_compute acceptance tests); cargo fmt + cargo clippy --workspace -- -D warnings clean.

@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE — I independently ground-verified the two hardest parts (scheduler concurrency + eviction guards); both are correct and defensively coded. This closes #1534 cleanly.

EmbeddingScheduler — lost-wakeup-safe, leak-free, no permanent starvation

The non-active defer loop is the textbook tokio pattern and it's exactly right:

loop {
    let notified = self.notify.notified();
    tokio::pin!(notified);
    notified.as_mut().enable();                       // register BEFORE the check
    if self.high_waiters.load(SeqCst) == 0 { break; }
    notified.await;
}

enable() registers the waiter before reading high_waiters, so a notify_waiters() firing between the check and the await (which stores no permit) cannot be lost. Verified the surrounding invariants too:

  • HighPriorityReservation is genuine RAII — Drop does high_waiters.fetch_sub(1) then notify.notify_waiters() (correct order: woken waiters observe the decremented count), and it's held across the active path's gate.acquire().await, so a cancelled active acquire releases the count instead of leaking it (the exact bug the adversarial pass fixed).
  • No permanent starvation — when the active DB goes idle its last reservation drops → high_waiters → 0 → notify → deferred DBs proceed. set_active(None)/switch routes the former-active DB through the non-active path, so high_waiters naturally drains; with active = None nobody takes the active path so every DB proceeds immediately. Active-first at batch granularity (permit dropped between batches) is the intended priority, and "fairness beyond active-first" is an explicit non-goal.

Idle reaper — every dangerous eviction is guarded

evict_idle_databases excludes, in order: the default (default_id != id), the active (scheduler.active_id() != id), anything not idle beyond the window, a just-opened DB with no recorded activity (treated as freshly-used, so it can't be reaped between its open and first request — the other adversarial-pass fix), and any DB with pending embeddings (has_pending_embeddings → continue, so a mid-drain processor is never torn down). It collects candidates under the read lock and calls close after releasing it, so open/registry locks aren't held across the per-DB write awaits. And the open-request-races-eviction case is safe by construction: close drops only the map's Arc, so any in-flight caller holding an Arc to the services completes normally, and the next request lazily reopens via get_or_open. close() additionally refuses the default/active itself (defense-in-depth) and never calls the one-way release_gpu_context() on the shared model.

Model/lifecycle scoping is correct

One process-global embedding model (published over watch, shared LRU) — no second load; shutdown_all now drains every open DB's processor (not just the boot DB) and then releases the GPU context exactly once; per-DB agent watcher cancellation via a fresh CancellationToken. Session/event isolation (A's chat events never reach B) is covered by per_db_compute.

Community-unaffected

Single database is always effectively active and never evicted (default + active guards both apply to it) — behavior unchanged. ✅

Merge gate

test:e2e COMPLETED/SUCCESS; test:all IN_PROGRESS at 14a3ab01 — let it finish green (the new #1602 OpenSSL pin should keep it deterministic). Nice touch that the adversarial pass strengthened the active-first unit test to actually distinguish priority from a plain FIFO gate. Approve.

@mstomar125
mstomar125 merged commit 92bf512 into NodeSpaceAI:main Jul 10, 2026
3 of 4 checks passed
@mstomar125
mstomar125 deleted the ns/adr053-per-db-compute branch July 10, 2026 07:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant