Skip to content

Add daemon-ready tasks and channel-rebuilt hooks to AppExtensions - #3405

Merged
mstomar125 merged 2 commits into
mainfrom
issue-3307-daemon-ready-and-channel-rebuilt-hooks
Oct 1, 2026
Merged

mstomar125 merged 2 commits into
mainfrom
issue-3307-daemon-ready-and-channel-rebuilt-hooks

Conversation

@mstomar125

Copy link
Copy Markdown
Contributor

Closes #3307

Part of the Pro-boundary epic (#3298) and the Tauri extension points (#3322).

What this adds

Two daemon-side hooks on AppExtensions (ADR-082 sections 3.4 and 3.5). Later boundary issues use them to move the startup probe and the cloud client's rebind out of core.

  • AppExtensions::on_daemon_ready(task). Each task is spawned once per process with DaemonReady { app, grpc, shutdown }. Core's startup task spawns it after the daemon start attempt finishes and the watcher and token stream are wired, and never awaits it. grpc is a clone of the managed client. shutdown is the task's own child of core's shutdown token. A task that panics is logged, and the other tasks are unaffected.
  • AppExtensions::on_channel_rebuilt(hook). Awaited in probe_and_recover, after GrpcClient::reconnect() and before the re-probe. Hooks run in registration order. Each runs as its own spawned task under CHANNEL_REBUILT_HOOK_TIMEOUT (2 s). A hook that times out is aborted and logged, a hook that panics is logged, and recovery continues either way.
  • assemble always manages the hook state, empty for none(), so an app with no extension behaves as before. Channel and CancellationToken are re-exported from extensions.
  • probe_and_recover_channel's body moves into pub async fn probe_and_recover<R: Runtime>(app, client) -> bool, so a mock app can drive it. The command is now Ok(probe_and_recover(&app, client.inner()).await).
  • The docs for GrpcClient's channel field, channel() and reconnect() now describe extensions generically and name no product.
  • Test harness: TauriTestApp::connect_assembled(daemon, timeout, extensions).

This PR leaves the startup Pro probe and the ProClient rebind alone. Their own issue removes them.

Deviations from the issue text

  • BASELINES not lowered. Step 5 of the issue says to lower BASELINES to the printed counts. The standing instruction for this batch is the opposite, because parallel PRs collide on those lines and the closing issue tightens everything at once. This PR edits no baseline, and no count rises.

  • The daemon:data-plane-ready block from Add a neutral daemon:data-plane-ready event and stop reloading on pro:tier-detected #3318 has not landed. spawn_daemon_ready_tasks therefore sits directly after start_token_stream_subscription, as the issue specifies for that case. If Add a neutral daemon:data-plane-ready event and stop reloading on pro:tier-detected #3318 lands first, the call moves below its block.

  • The wedge seam test and the connect mutex. The issue says to hold the connect mutex for the whole test. TauriTestApp::connect_assembled, like connect, takes that mutex itself, so holding it across the call would deadlock. The test holds it in two sections instead:

    • one to build the wedged client under a socket override;
    • one, through hold_connect_mutex_and_socket_env, from after the app is built to the end, so the rebuild resolves the real daemon's socket.

    Each section's guard restores the environment variable when it drops.

  • tokio test-util is added to nodespace-app-lib's dev-dependencies for the start_paused timeout tests. No new crate enters the lockfile.

  • EXTENSION_API_VERSION stays (1, 0). It must equal the TypeScript constant. The sibling additions to the extension API (lifecycle hooks) also left both at 1.0, because the API is unreleased.

Ratchet

bun run scripts/check-pro-boundary.ts passes. Current counts move from proProtocol 95 to 93 and from proWording 274 to 272, and every other count is unchanged. Both drops come from the reworded GrpcClient docs. No count rises, BASELINES is not edited, and no added line carries a Pro marker.

Tests

Unit tests in extensions/fixture_tests.rs (mock runtime, a connect_lazy() client, no daemon):

  • daemon_ready_tasks_are_spawned_not_awaited
  • daemon_ready_task_gets_the_app_the_client_and_a_child_shutdown_token
  • daemon_ready_tasks_each_get_their_own_shutdown_token
  • a_panicking_daemon_ready_task_does_not_stop_the_others
  • daemon_ready_tasks_run_once
  • channel_rebuilt_hooks_run_in_registration_order
  • a_hanging_channel_rebuilt_hook_times_out_and_the_next_still_runs
  • a_panicking_channel_rebuilt_hook_does_not_stop_recovery
  • hooks_are_a_no_op_without_extension_state

Source-text tests:

  • In lib.rs, on run: the spawn comes after the token stream and before the reachability check, the call is not awaited, and the shutdown token is a child of core's.
  • In nodes.rs: the hooks run after reconnect() and before the final probe.

Seam tests in tests/it/extension_hooks_test.rs, against a real nodespaced:

  • A daemon-ready task's DatabaseService.List on ready.grpc.channel() succeeds.
  • A wedged channel makes probe_and_recover return true, with the hook's List on the rebuilt channel already completed. The wedge comes from a silent socket that accepts connections and never replies.

Mutation checks

Each new test was checked by breaking the code path it covers and confirming the test fails, then restoring the code.

All 22 mutations below were killed: each made its test fail.

# Mutation Test that fails
1 Run each daemon-ready task with block_on instead of spawning it daemon_ready_tasks_are_spawned_not_awaited
2 Give a task a fresh token instead of a child of core's daemon_ready_task_gets_the_app_the_client_and_a_child_shutdown_token
3 Give every task core's token itself (a clone) daemon_ready_tasks_each_get_their_own_shutdown_token
4 Give a task a fresh client instead of a clone of core's daemon_ready_task_gets_the_app_the_client_and_a_child_shutdown_token
5 Call the task outside the spawned future a_panicking_daemon_ready_task_does_not_stop_the_others
6 Treat a second spawn call as a bug and panic daemon_ready_tasks_run_once
7 Spawn every hook up front so they run side by side channel_rebuilt_hooks_run_in_registration_order
8 Make the hook timeout effectively unbounded a_hanging_channel_rebuilt_hook_times_out_and_the_next_still_runs
9 Don't abort a hook that timed out same
10 Stop the recovery at a hook that timed out same
11 Call the hook outside the spawned task a_panicking_channel_rebuilt_hook_does_not_stop_recovery
12 Stop the recovery at a panicking hook same
13 Make the hook runner require the hook state (state instead of try_state) hooks_are_a_no_op_without_extension_state
14 Make the task spawner require the hook state same
15 Spawn the tasks in run before the watcher and token stream run_spawns_daemon_ready_tasks_once_the_watcher_and_token_stream_are_wired
16 Await the spawn statement in run same
17 Make run's extension token a fresh token, not a child of the shutdown token run_derives_the_daemon_ready_shutdown_from_the_shutdown_token
18 Run the hooks after the re-probe probe_and_recover_runs_the_channel_rebuilt_hooks_between_the_rebuild_and_the_reprobe
19 Run the hooks before the rebuild same
20 Make GrpcClient::channel() return a channel that doesn't reach the daemon daemon_ready_task_reaches_the_daemon_on_the_shared_channel (seam)
21 Hand the hooks the old, wedged channel a_wedged_channel_rebuild_runs_the_hooks_before_recovery_returns (seam)
22 Don't run the hooks in probe_and_recover same (seam)

Each task runs at most once because the tasks are FnOnce and are taken out of the state, so the type system already rules out running a task twice. Mutation 6 covers the other way the run-once check can break: a second call that panics instead of doing nothing.

Commands run

cargo fmt -p nodespace-app-lib -p nodespace-app-test-support
cargo clippy -p nodespace-app-lib -p nodespace-app-test-support --all-targets -- -D warnings -D clippy::unused-async
cargo test --lib -p nodespace-app-lib
NODESPACED_TEST_BIN=$PWD/target/debug/nodespaced cargo test -p nodespace-app-lib --test it extension_hooks_test:: -- --test-threads=1
NODESPACE_PRO_SUPABASE_URL=https://example.invalid NODESPACE_PRO_ANON_KEY=dummy cargo check -p nodespace-app
bun run scripts/check-pro-boundary.ts
bun run test:changed

🤖 Generated with Claude Code

@mstomar125

Copy link
Copy Markdown
Contributor Author

Automated pragmatic-code-review (medium) — PR #3405 @ 6925893

Review Type: Initial Review

Requirements Check (issue #3307)

  • ✅ Daemon-ready tasks.
    • They run once: std::mem::take under the Mutex, and the guard is dropped at the end of the statement, not held across an await.
    • They are spawned on tauri::async_runtime and never awaited.
    • Each receives the app, a clone of the managed client and its own shutdown.child_token().
    • Panics are isolated. catch_unwind wraps the task(ready) call itself, so a panic before the task returns its future is caught too.
  • ✅ Channel-rebuilt hooks.
    • They run one after another in registration order, each in its own tokio::spawn.
    • timeout(.., &mut task) is valid because JoinHandle is Unpin.
    • On a timeout the task is aborted. The runner moves on whether or not the abort takes effect at once, because the hook lives in its own task.
    • A panic arrives as a JoinError, is logged, and recovery continues.
  • ✅ Wedge recovery against a real daemon. I rebuilt and ran extension_hooks_test:: at HEAD four times (once with --test-threads=1, three times with --test-threads=2). All passed, at about 5.3 s each.
    • 📝 The it-4c542e366354e0c2 binary left in target/ was built at 08:43:37. That is 5 s before nodes.rs was last written, so it is presumably the build from mutation 22.
    • It fails the wedge test with got None, which is what mutation 22 should do. So the mutation is really killed. That is not a defect at HEAD.
  • ✅ AppExtensions::none() behaves as before.
    • assemble manages an empty ExtensionHooks, so spawn_daemon_ready_tasks spawns nothing.
    • probe_and_recover only adds one RwLock read and an empty loop.
    • A plain mock_app(), as used by TauriTestApp::connect, has no hook state, so both runners return early. hooks_are_a_no_op_without_extension_state covers that.
    • I did not re-run the full existing seam suite. The PR reports test:changed.
  • ✅ GrpcClient docs. The docs for the channel field, channel() and reconnect() no longer name ProClient or the Pro tier.
  • ✅ check-pro-boundary.ts passes. I ran it, and no count is above its baseline.
    • 📝 BASELINES was deliberately not lowered. That is acceptable: parallel PRs collide on those lines, and the closing issue tightens them.
  • ✅ Pro-mode compile check. The PR reports it passing. I did not re-run it.
  • ✅ No product names or issue numbers. I scanned every added line for Pro, Supabase, tenant, nodespace-sync, cloud and #NNN, and found none.

Deviations, judged on their merits:

  • The two-section connect mutex in the wedge test is sound.
    • connect_lazy() resolves NODESPACED_SOCKET once, at construction. uds_channel_lazy captures that path in the connector.
    • reconnect() resolves it again at call time, and the test holds hold_connect_mutex_and_socket_env at that point.
    • connect_assembled locks internally.
    • So the environment variable is never read outside the mutex at a point that matters.
    • Guards drop in reverse order: in the block, and as tuple bindings.
  • tokio test-util as a dev-dependency matches what core, cli, agent and daemon already do. With resolver = "2", it does not reach the release build.

Other things I traced and found fine:

  • The release profile sets panic = "unwind", so the panic isolation holds in shipped builds.
  • run sets Tauri's async runtime to core's own multi-thread runtime. So tokio::spawn inside the probe_and_recover_channel command has a runtime context, and both hooks run on the same runtime.
  • extension_shutdown is a child of shutdown_token_for_setup, and graceful_shutdown cancels that token.
  • Tauri's Builder::manage asserts on a duplicate type. The "call assemble once per builder" doc covers that.
  • I ran the nine new unit tests and the three source-text tests from the current lib test binary. They passed three times in a row. The paused-clock reasoning holds: a lazy channel arms no timers, so auto-advance lands exactly on the 2 s timeout.

Code Review Findings

🔴 Critical: none.

🟡 Important: none.

🟢 Suggestion — document the gap between reading the channel and caching a client built on it.
📁 packages/desktop-app/app-lib/src/extensions/mod.rs:181-184

The scenario:

  1. A daemon-ready task does let ch = ready.grpc.channel().await;.
  2. It then builds a client and stores it.
  3. If a rebuild and its hooks run between steps 1 and 2, the hook installs a client on the new channel.
  4. The task then overwrites it with a client on the dead channel.
  5. Core's own channel is healthy from then on, so no later probe triggers another rebuild. The extension stays wedged until restart.

The window is narrow: a wedge during startup, while the frontend's steady-state poll is probing. It is also the same shape as core's existing probe-then-manage(pro) sequence.

But this bullet is the extension contract, and the issues that move the cloud client onto this seam will inherit it. Add one sentence: a task should read grpc.channel() and store its client under the same lock its on_channel_rebuilt hook uses to replace it. Swapping the channel finishes before any hook runs, so that ordering is enough.

Principle: an API contract should state the concurrency obligations it places on callers.

Nit: mod.rs:167 says "Tasks start in the order they were added". On core's multi-thread runtime, only the spawn order is fixed. Suggested wording: "are spawned in the order they were added". Otherwise an extension author may assume task A has started before task B.

Nit: mod.rs:355-356 drops the panic payload: tracing::error!("a daemon-ready task panicked"). The hook path logs the JoinError, which carries the message. For the same diagnostic value, downcast the Box<dyn Any> to &str or String and include it.

Nit: tests/it/extension_hooks_test.rs:9 imports use std::sync::{Arc, Mutex}; at file level, but only the #[cfg(unix)] wedge test uses it. On Windows that is an unused_imports warning, so clippy --all-targets -D warnings would fail there. Move it into that test function next to its other use lines.

Recommendation: APPROVE

The change is tight and correct, and it matches the issue's design. Concurrency and lifecycle hold up against tokio and Tauri semantics. The tests prove what they claim; I confirmed by running them, including the real-daemon wedge test. The Suggestion is a one-line doc addition, and the Nits are optional polish. None of them blocks merging.

@mstomar125 mstomar125 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Automated pragmatic-code-review (medium): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above: no Critical or Important findings, one Suggestion and three Nits.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review: PR #3405, review of 6925893

Addressed in 94c7bdb. Every finding was checked against the code before it was acted on.

Addressed (4 of 4)

  • ✅ 🟢 Suggestion: the cache-under-lock rule (extensions/mod.rs, the "Channels get rebuilt" bullet of on_daemon_ready).
    • The contract now says that a task that caches a client reads the channel and stores the client while holding the same lock its on_channel_rebuilt hook takes to replace it.
    • That is enough because reconnect() swaps the channel before run_channel_rebuilt_hooks runs any hook. A task holding the lock therefore either reads the new channel, or stores its client before the hook replaces it.
    • I traced the race the reviewer describes: an old channel read before the swap, then stored after the hook ran. It is real for an extension that doesn't take the lock, and core can't close it from its side, so it belongs in the contract.
  • ✅ Nit: spawn order is not start order. "Tasks start in the order they were added" is now "Tasks are spawned in the order they were added, each as its own task, but nothing orders when they start running".
  • ✅ Nit: panic payload. app-lib installs no panic hook, so the payload otherwise reaches only stderr. The catch_unwind arm now downcasts it to &str or String and logs it as panic = …, the way the channel-rebuilt path already does through its JoinError.
  • ✅ Nit: an unused import on Windows. use std::sync::{Arc, Mutex}; moves from file level into the #[cfg(unix)] wedge test, the only user. On Windows the file-level import would be unused and fail clippy --all-targets -D warnings.

Skipped

None.

Checks after the fixes

No test was added, so no mutation check is new. The 22 mutation results in the PR body still hold, because these edits change only docs, a log line and an import.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The review was APPROVE with no Critical or Important findings. The fixes are:

  • two rustdoc wording changes;
  • a log line that now carries the panic payload, with no control-flow change;
  • an import moved into the only function that uses it.

None of them changes behaviour that a test or a reviewer has already judged.

🤖 Generated with Claude Code

mstomar125 and others added 2 commits October 1, 2026 09:11
AppExtensions gains on_daemon_ready and on_channel_rebuilt. assemble
manages their state as ExtensionHooks, empty for AppExtensions::none().

- spawn_daemon_ready_tasks takes the tasks once and spawns each with a
  DaemonReady { app, grpc, shutdown }, where shutdown is the task's own
  child token. run's startup task calls it after the watcher and token
  stream are wired and does not await it.
- run_channel_rebuilt_hooks runs the hooks in order, each as a spawned
  task under CHANNEL_REBUILT_HOOK_TIMEOUT. A timeout aborts the task and
  a panic is logged; the next hook runs either way.
- probe_and_recover_channel's body moves to probe_and_recover, generic
  over the runtime, which runs the hooks after reconnect() and before
  the re-probe.
- The GrpcClient channel docs describe extensions instead of a product.
- TauriTestApp::connect_assembled builds a mock app through assemble.
- Unit tests on a mock runtime, source-order tests for run and
  probe_and_recover, and seam tests against a real nodespaced for the
  shared channel and a wedged-channel rebuild.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- on_daemon_ready's contract says a task that caches a client reads the
  channel and stores the client under the lock its channel-rebuilt hook
  uses, and that tasks are spawned, not started, in order.
- A panicking daemon-ready task's log line carries the panic message.
- The wedge seam test imports Arc and Mutex itself, so the file has no
  import that is unused on Windows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mstomar125
mstomar125 force-pushed the issue-3307-daemon-ready-and-channel-rebuilt-hooks branch from 94c7bdb to 92fa402 Compare October 1, 2026 07:11
@mstomar125
mstomar125 merged commit 066fac4 into main Oct 1, 2026
@mstomar125
mstomar125 deleted the issue-3307-daemon-ready-and-channel-rebuilt-hooks branch October 1, 2026 07:11
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.

Add daemon-ready tasks and a channel-rebuilt hook to AppExtensions

1 participant