Skip to content

Daemon should bind gRPC socket before embedding model loads - #1292

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1287-daemon-early-socket-bind
Jun 2, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1287-daemon-early-socket-bind

Conversation

@malibio

@malibio malibio commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator

Closes #1287

Split daemon startup into two phases:
- Phase 1 (~100ms): init NodeService, seed schemas, build all gRPC
  handlers, bind socket — clients can connect immediately
- Phase 2 (background tokio::spawn): load NLP model; once ready,
  populate Arc<RwLock<Option<EmbeddingReady>>> shared by
  EmbeddingsServiceImpl and NodeServiceImpl

While the model loads, EmbeddingsService RPCs return UNAVAILABLE with
"embedding model loading, please retry". Once loaded, they work
normally — no client reconnect needed.

Key changes:
- build_services() returns (ServiceBundle, Option<JoinHandle>) and no
  longer blocks on nlp.initialize()
- EmbeddingReady struct holds (NodeEmbeddingService, EmbeddingProcessor)
  behind Arc<RwLock<Option<_>>> shared by both service impls
- NodeService.embedding_waker changed from Option<EmbeddingWaker> to
  Arc<OnceLock<EmbeddingWaker>> so the waker can be set from the bg task
  after NodeService is Arc-wrapped
- Tauri daemon startup timeout reduced from 30s to 2s

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jun 1, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1292: Daemon should bind gRPC socket before embedding model loads

Summary

This is a well-executed, targeted refactor. The two-phase startup split is the right architectural approach: Phase 1 establishes the socket and all non-NLP services in ~100ms, while Phase 2 loads the heavy NLP model in a background task. The Arc<RwLock<Option<EmbeddingReady>>> shared-state pattern is idiomatic and correct for this use case. The Arc<OnceLock<EmbeddingWaker>> change is an elegant solution to the problem of populating the waker after NodeService is already behind an Arc.

All acceptance criteria from issue #1287 are met. This is a net positive change and is safe to merge with the one improvement noted below addressed.


Findings

[Improvement] nlp.initialize() is a synchronous blocking call inside tokio::spawn

File: packages/daemon/src/main.rs, load_embedding_model_bg (line ~380)

EmbeddingService::initialize() is a &mut self synchronous function that blocks for 6–8 seconds doing CPU-bound llama.cpp model loading (Metal kernel compilation, file I/O). Running it directly inside tokio::spawn occupies a tokio worker thread for the full load window, which starves the async executor during startup — exactly when the gRPC server is handling its first connections.

The fix is to wrap the blocking call in tokio::task::spawn_blocking:

let nlp = tokio::task::spawn_blocking(move || {
    let mut nlp = EmbeddingService::new(config).map_err(|e| { ... })?;
    nlp.initialize().map_err(|e| { ... })?;
    Ok::<_, String>(nlp)
}).await;

This is particularly important because the Tauri socket-health check fires within 2 seconds of daemon start and the gRPC server will be handling early RPCs during the exact window the model is loading.


[Improvement] GraphContextAssembler is permanently stuck with None embedding service

File: packages/daemon/src/main.rs, line ~269–271

let assembler = Arc::new(GraphContextAssembler::new(
    node_service.clone(),
    None, // embedding not yet loaded; context assembly falls back to keyword search
));

The comment says "falls back to keyword search" — but this None is never updated after the background task completes. The AgentSessionHandler holds Arc<GraphContextAssembler> and that assembler is permanently without semantic context enrichment for the lifetime of the daemon process.

This is a functional regression for agent sessions: they will never use semantic neighbors for context assembly even after the model loads. Before this PR, when the model loaded (synchronously), the assembler received the live embedding_service. Now it never does.

This can be fixed by giving GraphContextAssembler its own Arc<RwLock<Option<EmbeddingReady>>> reference (same pattern used by the service impls), or by adding a setter that the background task calls after loading. The current approach silently degrades agent context quality with no log warning.


[Improvement] 2s Tauri timeout is tight for slow machines / cold-start edge cases

File: packages/desktop-app/src-tauri/src/daemon_setup.rs, line 84

The 2-second timeout is reasonable for the happy path — but Phase 1 startup includes SqliteStore::new(), schema seeding, and seed_agent_nodes(), which involves file I/O and DB queries. On a machine with a slow spinning disk, NFS home directory, or high load at launch time, these could exceed 2 seconds before the socket binds.

The acceptance criterion says "within 500ms" but the actual time budget needs margin. Consider 5s — it's still a 6x improvement over the previous 30s, correctly reflects that the socket should appear in well under a second, but provides a meaningful safety margin. Alternatively, make the timeout configurable via env var so it's tunable without a binary change.


Nitpicks

  • Nit: packages/daemon/src/services/embeddings_service.rs, line 198 — get_stale_count does not gate on state.read().await.is_some() while every other write-path RPC does. This is intentional (the stale count is DB-only, no model needed) and correct, but a brief comment noting "no model required — queries DB directly" would prevent future reviewers from adding a spurious state check.

  • Nit: packages/daemon/src/main.rs, build_services() line ~264–266 — EmbeddingsServiceImpl is only registered when a model file exists at startup. If the model file appears after daemon start (e.g. user downloads it), the EmbeddingsService gRPC endpoint will not exist in the server. This is identical behavior to before this PR, so not a regression — but worth a // NOTE: comment that the endpoint is absent until daemon restart when no model is present at startup.

  • Nit: packages/daemon/src/main.rs line ~115, ~167 — _bg_task is intentionally discarded via the underscore prefix. A one-line comment (// Task runs to completion independently; dropping the handle does not cancel it) would make the intentional drop explicit for future readers unfamiliar with tokio's detach-on-drop semantics.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review verdict: REQUEST CHANGES. Two improvements should be addressed before merge - see the detailed review comment above.

malibio and others added 2 commits June 1, 2026 12:17
…bedding

- Use tokio::task::spawn_blocking for EmbeddingService::new + initialize
  (~6-8s sync CPU/IO) so the tokio worker pool isn't blocked during the
  window when the gRPC server is accepting its first connections

- GraphContextAssembler now holds Arc<RwLock<Option<Arc<NodeEmbeddingService>>>>
  instead of Option<Arc<NodeEmbeddingService>>. The background load task
  populates it (via embedding_svc_state) once the model is ready, so
  agent sessions that start after model load get semantic context enrichment

Co-Authored-By: Claude <[email protected]>
- Add comment on get_stale_count clarifying it queries DB directly (no
  model required) to prevent future reviewers adding a spurious state check
- Add comments on _bg_task drops explaining tokio's detach-on-drop semantics
- Add comment on EmbeddingsService registration noting it's absent until
  daemon restart when no model file is present at startup
- Increase Tauri socket-wait timeout 2s → 5s for slow-disk margin;
  still 6x better than the previous 30s that blocked on model load

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator Author

Review Response

All findings addressed:

✅ Addressed (from prior commit eb57cd4):

  • spawn_blocking for EmbeddingService::new + initialize — sync CPU/IO ops no longer park a tokio worker thread
  • GraphContextAssembler now receives Arc<RwLock<Option<Arc<NodeEmbeddingService>>>> and is populated by the background task once the model loads — semantic context enrichment works for all agent sessions

✅ Addressed (this commit 953cc96):

  • Tauri timeout raised 2s → 5s for slow-disk margin (still 6x better than the previous 30s)
  • Added // No model required comment on get_stale_count
  • Added // _bg_task: dropping a JoinHandle does not cancel the task in tokio — it detaches comments on both _bg_task bindings
  • Added comment on EmbeddingsService registration noting model-file-at-startup requirement

Skipped: None — all recommendations were addressed.

@malibio
malibio merged commit 32e944a into main Jun 2, 2026
@malibio
malibio deleted the worktree-issue-1287-daemon-early-socket-bind branch June 2, 2026 06:38
malibio added a commit that referenced this pull request Jun 22, 2026
* Bind gRPC socket before embedding model loads (closes #1287)

Split daemon startup into two phases:
- Phase 1 (~100ms): init NodeService, seed schemas, build all gRPC
  handlers, bind socket — clients can connect immediately
- Phase 2 (background tokio::spawn): load NLP model; once ready,
  populate Arc<RwLock<Option<EmbeddingReady>>> shared by
  EmbeddingsServiceImpl and NodeServiceImpl

While the model loads, EmbeddingsService RPCs return UNAVAILABLE with
"embedding model loading, please retry". Once loaded, they work
normally — no client reconnect needed.

Key changes:
- build_services() returns (ServiceBundle, Option<JoinHandle>) and no
  longer blocks on nlp.initialize()
- EmbeddingReady struct holds (NodeEmbeddingService, EmbeddingProcessor)
  behind Arc<RwLock<Option<_>>> shared by both service impls
- NodeService.embedding_waker changed from Option<EmbeddingWaker> to
  Arc<OnceLock<EmbeddingWaker>> so the waker can be set from the bg task
  after NodeService is Arc-wrapped
- Tauri daemon startup timeout reduced from 30s to 2s

Co-Authored-By: Claude <[email protected]>

* Address review: spawn_blocking for model load; assembler gets live embedding

- Use tokio::task::spawn_blocking for EmbeddingService::new + initialize
  (~6-8s sync CPU/IO) so the tokio worker pool isn't blocked during the
  window when the gRPC server is accepting its first connections

- GraphContextAssembler now holds Arc<RwLock<Option<Arc<NodeEmbeddingService>>>>
  instead of Option<Arc<NodeEmbeddingService>>. The background load task
  populates it (via embedding_svc_state) once the model is ready, so
  agent sessions that start after model load get semantic context enrichment

Co-Authored-By: Claude <[email protected]>

* Address review nits: comments, timeout margin

- Add comment on get_stale_count clarifying it queries DB directly (no
  model required) to prevent future reviewers adding a spurious state check
- Add comments on _bg_task drops explaining tokio's detach-on-drop semantics
- Add comment on EmbeddingsService registration noting it's absent until
  daemon restart when no model file is present at startup
- Increase Tauri socket-wait timeout 2s → 5s for slow-disk margin;
  still 6x better than the previous 30s that blocked on model load

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
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.

Daemon should bind gRPC socket before embedding model loads

1 participant