Skip to content

Add a single-instance daemon lock and export the launcher's argument list - #3388

Merged
mstomar125 merged 7 commits into
mainfrom
issue-3352-single-instance-lock
Sep 30, 2026
Merged

mstomar125 merged 7 commits into
mainfrom
issue-3352-single-instance-lock

Conversation

@mstomar125

@mstomar125 mstomar125 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Closes #3352

Core's side of ADR-084 sections 4.1 and 4.2 (proposed). Part of the Pro/core boundary epic (#3298).

What changes

  • Single-instance lock (nodespace_daemon::single_instance, Unix only). acquire(socket) takes an exclusive flock on <socket stem>.lock, beside the socket, and records the holder's pid. main() takes it right after argument handling and tracing init, before stdio_log_rotation::spawn() and before the runtime exists, so a daemon that loses the lock never loads the registry, opens a database, loads the model, rotates the shared log, or deletes and binds the socket. It then waits for the lock (retrying every 250 ms, up to 20 s) before it logs the holder's pid and exits 0, so a KeepAlive { SuccessfulExit = false } registration leaves a running daemon alone. The wait matters because launchd never restarts a daemon that exits 0: a restart starts the new daemon while the old one may still be draining (up to the 15 s shutdown watchdog), and losing the lock at once would leave no daemon at all. A free lock is taken on the first attempt. When the wait ends with the lock still held, the daemon binary looks at the socket: if it answers, a peer really serves and the daemon exits 0; if nothing answers, the holder is still starting or stuck in a drain that outlasts the wait (the two 15 s shutdown watchdogs run one after the other, so a stalled daemon can hold the lock for about 30 s), and the daemon exits with an error so the service manager tries again after its throttle. The OS releases the lock when the process exits, so a crash leaves nothing stale. Windows needs no lock; its named pipe already admits one server.
  • One launcher argument list. nodespace_proto::socket::{TRAY_FLAG, LAUNCHER_ARGS}, re-exported as nodespace_daemon::LAUNCHER_ARGS. The daemon's TRAY_FLAG and the app's DAEMON_TRAY_FLAG (two literals kept in step by hand) are gone. The launchd plist writes one <string> per entry, the systemd ExecStart and the Windows autorun entry join the entries with spaces, and the Windows spawn passes .args(LAUNCHER_ARGS). Output is byte-identical while the list is ["--tray"].
  • Uninstall. remove_sock also removes each socket's lock file (Unix).
  • Restart path (added after review). The app deleted the daemon socket unconditionally when it restarted the daemon. With the lock, a daemon the app did not start (a Homebrew service, one started by hand) would lose its socket file while keeping the lock, and the app's replacement would exit without serving. kill_running_daemon and kill_stale_daemon_sync now delete the socket only once nothing accepts connections on it. Also: scripts/uninstall.sh removes the lock file, the LAUNCHER_ARGS doc is scoped to the desktop app's launchers, and a proto test keeps the entries free of whitespace and quotes.

Deviations from the issue, and why

  • Paths. The crate split has landed, so the app-side edits are in packages/desktop-app/app-lib/src/daemon_setup.rs, not src-tauri/src. The acceptance grep therefore runs over packages/desktop-app/app-lib/src too; it finds no "--tray" literal in packages/daemon/src or any packages/desktop-app Rust source.
  • create_dir_owner_only. The issue asks for a sync helper that both callers use. create_dir_owner_only_blocking is that helper (same steps, same errors, same doc contract) and the async function now delegates to it through spawn_blocking.
  • Bounded wait (added at the coordinator's request; the issue said to exit 0 at once). acquire(socket) waits up to DEFAULT_LOCK_WAIT (20 s); acquire_waiting(socket, max_wait) takes the wait as a parameter (Duration::ZERO is one attempt). The first acceptance criterion therefore reads "exits 0 after the bounded wait, when a peer is serving" rather than "within 10 s". The environment variable NODESPACED_LOCK_WAIT_MS shortens the wait for tests that start a real second daemon; it is not a supported setting and not an argument (the daemon exits 2 on unknown arguments).
  • Extra guard. acquire returns an error when the socket path already ends in .lock, because with_extension("lock") would make the socket its own lock file.
  • Extra tests beyond the issue's list: the launcher arguments put the daemon in tray mode; a crashed daemon leaves no lock; a lock file that outlives its holder is overwritten, not appended to; an unreadable pid gives None; lock file mode; remove_sock.
  • The integration test decides "serving" by a successful connect, not by the socket file existing, because a SIGKILLed daemon leaves a stale socket file behind.

Ratchet

bun run scripts/check-pro-boundary.ts passes. My branch and origin/main print identical counts for every marker, so the delta is 0 and BASELINES is unchanged. (cloudSyncHooks is already 0 against a baseline of 4 on main; that tightening belongs to the change that removed those hooks.) The new comments avoid Pro/sync wording per the placement rule.

Tests and mutation checks

bun run test:changed (scripts + the full Rust workspace, run on the final code commit) passes; crate-scoped clippy with -D warnings -D clippy::unused-async is clean for proto, daemon, cli and app-lib. Each new test was checked by applying a mutation and confirming it fails (and that only the expected tests fail):

Mutation Tests that failed
main() takes no lock (the issue's mutation check) it single_instance::a_second_daemon_on_a_served_socket_exits_zero_and_leaves_the_socket_alone (second daemon never exits)
try_lock always reports contention every test that needs the lock (7 unit tests, all 3 integration tests)
try_lock always succeeds a_second_acquire_...names_the_holder, an_unreadable_recorded_pid_is_reported_as_none, the second-daemon integration test
lock path is one global file sockets_in_one_directory_do_not_contend, daemons_on_different_sockets_do_not_block_each_other (+ path test)
pid-file semantics (non-empty file means held) a_crashed_daemon_leaves_no_lock_behind, dropping_the_lock_frees_it, a_stale_pid_...
no set_len(0) a_stale_pid_from_a_dead_holder_is_replaced_not_appended_to
fd leaked past Drop dropping_the_lock_frees_it
create_dir_all instead of the owner-only helper the_parent_directory_is_created_owner_only
lock file mode 0o666 the_lock_file_is_owner_only
no .lock-extension guard a_socket_path_that_is_its_own_lock_file_is_refused
pid parse falls back to Some(0) an_unreadable_recorded_pid_is_reported_as_none
extension lck lock_path_sits_beside_the_socket_with_the_lock_extension
no retry (give up on first contention) a_daemon_started_while_the_lock_is_held_waits_for_it_and_then_serves, a_second_daemon_on_a_served_socket_exits_zero_and_leaves_the_socket_alone (it must live at least its wait), a_lock_released_during_the_wait_is_taken, a_lock_that_stays_held_is_reported_only_after_the_wait
the give-up always exits 0 / never exits 0 a_daemon_that_finds_the_lock_held_but_nothing_serving_exits_with_an_error / a_second_daemon_on_a_served_socket_exits_zero_and_leaves_the_socket_alone
the holder pid read moves the file offset (the original wait implementation) the_holder_pid_can_be_read_more_than_once_from_one_open_file, a_lock_that_stays_held_is_reported_only_after_the_wait, and the second-daemon test, which checks the exit line names the holder
retry never gives up a_second_daemon_on_a_served_socket_exits_zero_and_leaves_the_socket_alone
the wait override ignored / read as seconds a_second_daemon_on_a_served_socket_exits_zero_and_leaves_the_socket_alone / the_wait_override_is_read_in_milliseconds_and_falls_back_to_the_default
LAUNCHER_ARGS = [] the_launcher_arguments_put_the_daemon_in_tray_mode, pkg_plist_opts_the_daemon_into_tray_mode
LAUNCHER_ARGS gains an entry the daemon rejects every_launcher_argument_is_recognized, pkg_plist_opts_the_daemon_into_tray_mode (the static .pkg plist drifts)
write_plist writes only the first entry plist_opts_the_daemon_into_tray_mode, pkg_plist_opts_the_daemon_into_tray_mode
remove_sock leaves lock files remove_sock_removes_every_variants_socket_and_lock_file_only
the app's socket cleanup deletes unconditionally a_socket_something_answers_on_is_left_alone, kill_running_daemon_leaves_the_socket_of_a_daemon_it_cannot_stop
the app's socket cleanup never deletes / ignores its grace a_socket_nothing_answers_on_is_removed, a_socket_that_stops_answering_within_the_grace_is_removed
a launcher argument containing a space launcher_args_survive_an_unquoted_command_line

The integration tests start real nodespaced processes against tempdir homes and sockets, and never touch ~/.nodespace. The systemd and Windows launcher edits are one-line substitutions that this macOS machine cannot compile; they were checked by inspection only.

Risks

  • A developer running dev daemons from two worktrees on the default dev socket now sees the second exit 0.
  • A brew services daemon that loses the lock waits up to 20 s, exits 0, and is restarted on every throttle interval, so it waits again (a sleeping process and some log noise, no load). The app's daemon that loses to a foreign daemon also exits only after the wait; the app is unaffected because the foreign daemon answers on the socket.
  • During a slow drain the new daemon's socket is up later: at most the 15 s drain plus the model load (about 9 s), inside the app's 30 s startup wait.
  • flock over a network home directory is best effort.
  • The kill_stale_daemon_sync call site of the new socket cleanup has no test of its own (it needs a resolved bundled sidecar); it shares the helper that the other call site's tests cover.
  • Rollback: revert the PR.

🤖 Generated with Claude Code

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (initial)

Review Type: Initial Review
Scope: commit 02d3821d (8 files, +625/-38). I read the whole diff and the code around it: main() ordering, both Unix serve loops, the app's kill_running_daemon and kill_stale_daemon_sync, ensure_daemon_running, and the existing daemon_custom_socket_test.
Independently verified:

  • I ran the branch's prebuilt test binaries. single_instance unit tests: 10/10 pass. it single_instance:: integration tests: 3/3 pass in 1.9 s, and no daemon processes were left behind.
  • I re-ran bun run scripts/check-pro-boundary.ts and it passes. No added or removed line in the diff contains a Pro, sync, tenant or cloud marker, so the claimed delta of 0 holds.
  • The added lines cite no #NNNN issue numbers.

Requirements Check

Acceptance criterion Status Note
A second nodespaced on a served socket exits 0 within 10 s, never deletes or binds the socket, and the first keeps serving Met The integration test checks exit code 0, that the socket inode is unchanged, that connect still succeeds, and that the holder's pid is in the log. The lock is taken at main.rs:466, after argv and tracing and before stdio_log_rotation::spawn() (486), the runtime, the registry, the DB, the model and the socket.
Daemons on different sockets never block each other Met Covered for the same directory by the unit test sockets_in_one_directory_do_not_contend, and for different homes by the integration test.
LAUNCHER_ARGS is exported from nodespace_proto::socket and nodespace_daemon Met proto/src/socket.rs:110 and the lib.rs re-export.
No other "--tray" literal in the daemon or app sources Met Checked over the correct path (app-lib/src, since the crate split landed). The only hit is proto/src/socket.rs:102. The static .pkg plist keeps its literal, and pkg_plist_opts_the_daemon_into_tray_mode now guards it.
Plist, systemd unit and Windows command lines are byte-identical Met (by reading) Plist: {launcher_args} expands to " <string>--tray</string>\n", which reproduces the old two lines exactly, and xml_escape("--tray") is a no-op. systemd: ExecStart={bin} --tray is unchanged. Windows spawn: .args([&str;1]) is equivalent to .arg. Autorun: "\"{bin}\" --tray" is unchanged. Named format arguments and types check out; this could not be compiled here for Linux or Windows.
check-pro-boundary.ts passes with BASELINES pasted Met (minor gap) It passes (re-run). The PR states the counts are identical rather than pasting the block verbatim.
Uninstall removes lock files (Scope item 4) Met remove_sock has a cfg(unix) lock removal and a test that checks all four variants plus a file that must be left alone.
Contract test uses first_unrecognized_arg Met every_launcher_argument_is_recognized.

Author's stated deviations, verified:

  • create_dir_owner_only refactor. Behaviour and error messages are identical for all seven callers (main.rs ×2, assembly.rs, database_manager.rs, settings_service.rs ×3). The only new error is the spawn_blocking JoinError context, which fires only on a panic.
  • daemon_custom_socket_test's /tmp case. It now fails earlier, inside acquire. The anyhow chain that main prints to stderr still contains both "cannot narrow it to owner-only" and "this process is uid", and the test support captures stderr.
  • Windows compile. single_instance and its caller are cfg(unix). TRAY_FLAG is used on every platform, so there is no unused-import warning. The new main.rs tests use the LAUNCHER_ARGS re-export, which is not cfg-gated. tests/it/single_instance.rs is #![cfg(unix)].

Findings

[Improvement] The lock can be held by a daemon that no longer serves, and then every successor exits 0 and nothing restarts it

Files: packages/desktop-app/app-lib/src/daemon_setup.rs:626-658 (kill_running_daemon, unconditional unlink at 657) and :153-197 (kill_stale_daemon_sync, unlink at 197); packages/daemon/src/main.rs:1377-1379 and 1458-1460, where the socket is removed before drain_and_release_gpu.

Principle: a lock guarantees what you want only if the thing it guards stays tied to it. This PR makes "holds the lock" mean "owns the socket path". Two existing behaviours break that link, and the lock turns what used to be self-healing into a stuck state.

  1. The app unlinks a socket whose owner may still be alive. In kill_running_daemon, a daemon whose argv0 is not ~/.nodespace/bin/nodespaced is never signalled. Examples are a brew services daemon or a hand-started one. The function still deletes the socket file after 5 s.

    Walk through an app update (binary_updated is true) while a Homebrew daemon serves daemon.sock:

    • the app unlinks the Homebrew daemon's socket;
    • it bootstraps its own daemon, which loses the lock and exits 0;
    • SuccessfulExit=false leaves that daemon stopped;
    • the app times out after 30 s;
    • the Homebrew daemon is alive and holds the lock but cannot be reached.

    The outage lasts until the Homebrew service restarts, which in practice means the next login. Before this PR the app's daemon would have taken the socket over. That was the unsafe dual-writer case, but the app worked. Check the running daemon's executable against the app's DaemonProfile at startup #3353's plan also depends on this not happening: its body says "the app keeps using the Homebrew daemon", yet its own Mismatch path "then remove[s] a stale socket file" the same way.

  2. The drain window. A daemon removes its socket, then runs drain_and_release_gpu, which can take up to the shutdown watchdog of about 15 s. It releases the lock only when it exits. A starter from a different mechanism in that window loses the lock and exits 0; launchd and systemd serialise restarts of the same job, so this only affects a different launcher. The PR's Risks section already names this window.

Suggested fixes. Either fits in this PR or in a tracked follow-up that lands before the next release:

  • Unlink only a stale socket. The lock is now an exact staleness test: a socket is stale if and only if its lock is free. In both kill_* helpers, remove the socket only when a non-blocking try_lock on <stem>.lock succeeds, or drop the unlink entirely, since the daemon removes and rebinds its own socket after taking the lock.
  • Give the loser a bounded wait. When acquire returns HeldByAnother and the socket refuses connect, retry the lock for a bounded time longer than SHUTDOWN_WATCHDOG_TIMEOUT before exiting 0. On a served socket the loser still exits at once, so the 10 s criterion holds.
  • Log the stuck state. In either case, log at warn! when the holder is not answering on the socket, so the stuck state can be diagnosed from the log.

[Nit] Move lock_path_for into nodespace_proto::socket

Files: packages/daemon/src/single_instance.rs:43 and packages/proto/src/socket.rs.

It is a pure naming rule, and the proto module doc already states it. The other socket naming rules live in proto. app-lib depends only on nodespace-proto, so moving it lets the app apply the staleness test above without a new dependency on the daemon crate. acquire stays in the daemon.

[Nit] remove_sock unlinks a lock file that a running daemon may still hold

File: packages/cli/src/commands/uninstall.rs:134-142.

stop_daemon boots out only the app's launchd/systemd job. A Homebrew or hand-started daemon survives the uninstall and keeps its lock on an inode that is now unlinked. The next daemon creates a fresh inode and also "holds" the lock.

This is not a regression: the flow gives two daemons with or without this PR. But it is the one path where the new lock is bypassed. A fix is cheap: remove the file only if a non-blocking lock on it succeeds.

[Nit] Scope the LAUNCHER_ARGS doc to the launchers that pass it

File: packages/proto/src/socket.rs:104-110.

"The arguments every launcher passes" is broader than the truth. The Homebrew formula's service do block (scripts/update-homebrew-formula.ts:331) is a launcher that deliberately passes none, because it runs headless. Say "the desktop app's launchers and the .pkg plist", so nobody later "fixes" the formula to pass --tray.

[Nit] Enforce that entries contain no whitespace or quotes

File: packages/desktop-app/app-lib/src/daemon_setup.rs:1491 and :1974-1978.

The systemd ExecStart and the Windows Run value join the entries unquoted. A one-line test asserting that no LAUNCHER_ARGS entry contains whitespace or " would enforce the constraint that byte-identical output depends on, before a future entry breaks it on the two platforms CI here cannot compile.

[Nit] scripts/uninstall.sh still removes only daemon.sock

File: scripts/uninstall.sh:62-66.

It now leaves daemon.lock behind, unlike nodespace uninstall. This is trivial to mirror if the script is kept in step with the CLI.

What's good

  • Correct flock use.
    • Locks belong to the open file description, so two opens in one process conflict, and the unit test relies on that.
    • Rust opens files with O_CLOEXEC, so spawned agent and PTY children never inherit the lock.
    • It is released on drop and on exit.
    • Only WouldBlock maps to HeldByAnother; every other error propagates, which fails closed.
    • The set_len(0) then pwrite sequence and the "pid is a hint" doc handle the small read window honestly.
  • Lifetime of _instance_lock. It is declared before runtime, so it outlives it. Every exit path (return, process::exit in the watchdog, _exit in exit_if_model_load_in_flight) releases the lock through drop or through the OS.
  • The owner-only directory rule runs before the lock file is opened. A socket pointed into a shared directory like /tmp is refused before anything is created there, so no new symlink or permission exposure.
  • Integration tests are well built.
    • They decide readiness by connect, not by the file existing.
    • They use a tempdir home and socket, and Drop kills the children.
    • They assert the socket inode is unchanged, which is the right way to test "never rebinds".
    • The mutation table is thorough, and each test's name matches what it asserts.

Recommendation

APPROVE. It is a clear net improvement, every acceptance criterion is met, and the code is correct and well tested. Before this reaches a release, deal with the Improvement: make the app's socket unlinks check the lock, either here or in a tracked follow-up (it fits naturally into #3353, which touches the same ensure_daemon_running flow and currently plans another unconditional unlink). The Nits are optional.

@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: APPROVE (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125
mstomar125 force-pushed the issue-3352-single-instance-lock branch from 02d3821 to 68011ce Compare September 30, 2026 11:38
@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review (round 1)

Commit 68011ce8 on top of the rebased branch (rebased onto d0345f3d after a fresh fetch; ratchet delta is still 0 on every marker).

Addressed

  • [Improvement] The app deleted a live foreign daemon's socket. Fixed. kill_running_daemon and kill_stale_daemon_sync now go through remove_socket_if_stale, which deletes the socket file only once nothing accepts connections on it (a bounded grace for a just-SIGKILLed daemon, none after the SIGTERM wait). A Homebrew or hand-started daemon that survives keeps its socket, so the app's replacement daemon exits on the lock and the app keeps using the daemon that is serving. I decided staleness by connecting, as check_daemon_socket does, rather than by probing the lock: a lock probe would make a daemon starting at that instant see the lock held and exit 0 permanently, which is the failure this fix exists to avoid. kill_running_daemon takes its 5 s exit grace as a parameter internally so the test does not sit out the wait.
  • [Nit] LAUNCHER_ARGS doc scope. Now says the desktop app's launchers, notes the .pkg plist repeats them by hand and that a headless registration such as the Homebrew formula's service passes none (verified against scripts/update-homebrew-formula.ts).
  • [Nit] Whitespace/quote guard. Added launcher_args_survive_an_unquoted_command_line in proto.
  • [Nit] scripts/uninstall.sh. Removes daemon.lock beside daemon.sock.

Skipped, with reasons

  • Move lock_path_for into proto. The reviewer's motivation was letting the app probe the lock. With connect-based staleness the app needs no lock path, so there is no consumer outside the daemon and the CLI, which already depends on the daemon crate. Revisit if the app ever needs the path (for example the ADR-084 notice work).
  • remove_sock removes a lock file a still-running daemon might hold. It mirrors the unconditional socket removal in the same function and runs after the app's own daemon has been stopped; a foreign daemon survives an uninstall with or without this PR. Adding a lock probe there has the same startup race described above. Revisit if uninstall learns to stop non-app daemons.
  • Bounded wait for the loser / warn! when the holder does not answer. Not needed once the app stops deleting a live socket, and a losing daemon waiting would delay the exit-0 contract the ADR specifies. The drain-window case (a starter from a different mechanism than launchd/systemd while the old daemon drains) remains as described in the PR's Risks.

Tests (each mutation-checked, all restored afterwards)

Mutation Tests that failed
helper always deletes a_socket_something_answers_on_is_left_alone, kill_running_daemon_leaves_the_socket_of_a_daemon_it_cannot_stop
helper never deletes a_socket_nothing_answers_on_is_removed, a_socket_that_stops_answering_within_the_grace_is_removed
grace ignored a_socket_that_stops_answering_within_the_grace_is_removed
kill_running_daemon deletes unconditionally again kill_running_daemon_leaves_the_socket_of_a_daemon_it_cannot_stop
a launcher argument containing a space launcher_args_survive_an_unquoted_command_line

Not covered by a test: the kill_stale_daemon_sync call site (it needs a resolved bundled sidecar and a size mismatch); it shares the helper with the covered call site. bun run test:changed passed on the previous commit (nextest 4117 plus the app-lib cargo tests including the four new ones); after the rebase I re-ran clippy (-D warnings -D clippy::unused-async, four crates), the ratchet, and 44 targeted tests, all green.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: the fix changes behavior in the app's daemon-restart path, which the first review did not cover as new code. Run /pragmatic-code-review again; it should review only 68011ce8.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (re-review)

Review Type: Re-review of commit 68011ce8 only. The rebased first commit c8a54d1d was not re-reviewed.
Read: the full commit diff, the author's round-1 response, and the unchanged helpers the new code and tests call: check_daemon_socket, pids_holding_unix_socket, process_argv0_matches, home_dir, and the kill_stale_daemon_sync call site in lib.rs:461.

Previous Review Summary

  • Recommendations in round 1: 6 (1 Improvement, 5 Nits).
  • Addressed: 4.
    • The Improvement: the app no longer deletes a live daemon's socket.
    • The LAUNCHER_ARGS doc scope.
    • The whitespace and quote guard test.
    • scripts/uninstall.sh.
  • Not addressed, and I accept the reasons: 2.
    • lock_path_for stays in the daemon crate: with connect-based staleness the app needs no lock path.
    • remove_sock still unlinks lock files: not a regression, and a rare flow.
    • The optional sub-suggestions (a bounded wait for the losing daemon, warn! when the holder does not answer) were declined with a sound argument. Once the app stops unlinking live sockets, the only case left is the drain window from a different launcher, which the PR's Risks section documents.
    • I also agree with deciding staleness by connect rather than by probing the lock. A probe that briefly holds the lock can make a daemon starting at that instant exit 0 for good, which is worse than the problem the probe would solve.
  • New issues: 1 Critical and 2 Nits.

Findings

[Critical] The new test can send SIGTERM to the developer's real, running NodeSpace daemon

Where: packages/desktop-app/app-lib/src/daemon_setup.rs, the test kill_running_daemon_leaves_the_socket_of_a_daemon_it_cannot_stop (in stale_socket_removal_tests). The root cause is the existing pids_holding_unix_socket, lines 243-251.

What the test assumes. It relies on this: "This test process holds the socket, and its argv[0] is not the installed daemon's, so kill_running_daemon signals nobody." That is only true if pids_holding_unix_socket(path) returns just the processes holding path. It does not.

What lsof actually does. The helper runs lsof -F pn -U <path>. lsof ORs its selection options unless -a is given, so this lists every process with any Unix-domain socket open, plus the holders of <path>. I checked this on this machine with a throwaway socket:

lsof -F pn -U     /private/tmp/claude-502/nslsof.sock  -> 38 pids
lsof -F pn -a -U  /private/tmp/claude-502/nslsof.sock  ->  1 pid (the holder)

What happens under cargo test:

  1. check_daemon_socket sees Healthy, because the test's own listener answers.
  2. installed resolves through the real dirs::home_dir() to ~/.nodespace/bin/nodespaced.
  3. Every process with any Unix socket is checked with process_argv0_matches. The developer's live daemon runs from exactly that path and always holds its own listener socket.
  4. The live daemon receives a real libc::kill(pid, SIGTERM).
  5. It exits 0, so launchd's SuccessfulExit=false leaves it stopped. The test still passes.

Who is affected. Any developer who runs the app-lib tests (bun run test:changed does) while their installed NodeSpace app's daemon is running.

  • The author's runs were harmless only because this account has no installed daemon.
  • On this shared Mac the live daemon belongs to another account, and a cross-user kill fails with EPERM.
  • That account's own test runs would stop it.

The file already guards against exactly this: signal_daemon_to_stop compiles its kill out under cfg(test), because it is "a real, irreversible action against whatever process is actually holding the daemon socket on the machine cargo test runs on." kill_running_daemon had no test before this commit, so the unguarded kill was never reached in tests.

Fix (small):

  1. Add -a to the lsof arguments: ["-a", "-F", "pn", "-U", sock]. This also corrects the production helper, which today over-matches in kill_stale_daemon_sync, kill_running_daemon and signal_daemon_to_stop. The argv0 filter hides that only by luck.
  2. Add a regression test that fails under OR semantics. For example, bind socket A in the test process, leave a stale socket file at B, and assert pids_holding_unix_socket(B) is empty. Today it would contain the test's own pid. The existing ..._is_empty_for_an_unbound_path test uses a path that does not exist, so lsof errors out and returns nothing, which is why it never caught this.
  3. For defence in depth, either compile the kill in kill_running_daemon_within out under cfg(test) as signal_daemon_to_stop does, or pass the pid list in so the test cannot reach a real process at all. This test only needs the "leave a live socket alone" branch, not real signalling.

Principle: a test must never have side effects on real user processes or state. Its safety has to be structural, not dependent on what happens to be running on the machine.

[Nit] A draining daemon still accepts connect, so the post-bootstrap wait can briefly report Healthy on the dying daemon

Where: daemon_setup.rs, the end of kill_running_daemon_within.

Why. Tonic keeps the listener open through its graceful drain: the incoming stream lives until serve_with_incoming_shutdown returns. The kernel therefore keeps completing connections into the backlog. If the app's own daemon is still draining RPCs when the 5 s grace ends, the file is now kept. The earlier code unlinked it. As a result, wait_for_daemon_or_refusal after bootstrap can see that daemon as Healthy until it exits, at most about the 15 s drain watchdog, and the client then reconnects.

This is transient and needs slow drains, so it is fine to leave. If you want it gone: kill_running_daemon_within knows whether it signalled any pid. When it signalled its own daemon, the old unconditional unlink is correct, because that socket is ours and dying. Only a socket it did not signal needs the staleness test.

[Nit] Blocking std::os::unix::net::UnixStream::connect inside an async fn

Where: remove_socket_if_stale, called from kill_running_daemon_within.

With Duration::ZERO this is one syscall, and a Unix-domain connect normally completes or fails at once, so it is acceptable. Two edge cases:

  • On Linux a blocking connect to a listener with a full backlog waits until there is room, which could stall the runtime worker.
  • On macOS a full backlog returns ECONNREFUSED, which this code reads as stale.

In the async path, check_daemon_socket(..).await == DaemonStatus::NotRunning would reuse the existing non-blocking probe, with its 500 ms timeout treated as live. The sync kill_stale_daemon_sync path is fine as written.

Answers to the specific questions

  1. Is staleness-by-connect sound? Yes. It is the right oracle, and the lock makes it safer than before: a replacement daemon removes and rebinds the file only after it holds the lock, so a stale file left behind cannot block anything.
    • The only socket-existence shortcut is check_daemon_socket:759. It maps "file present, connect refused" to NotRunning, so a stale file left by the 500 ms path behaves the same as a deleted one.
    • I found no other code that relies on the file being absent.
    • The race between "refused" and remove_file is microseconds long, and it is narrower than the old unconditional unlink.
    • The 500 ms grace at startup is reasonable. It runs only when the bundled and installed sizes differ, which is once per update. It exits as soon as connect fails, typically within about 10 ms, and it only waits the full 500 ms when a daemon the app did not signal is serving.
  2. Tests.
    • The three remove_socket_if_stale tests are deterministic, their names match their assertions, and the grace test has 50× headroom: 100 ms against 5 s.
    • The kill_running_daemon_within test can signal a real process. See the Critical above: the premise that the test process can never match is true, but lsof returns far more than the test process.
  3. Proto doc, the unquoted command-line test, and uninstall.sh.
    • The proto doc is now accurate.
    • launcher_args_survive_an_unquoted_command_line checks non-empty, whitespace and both quote characters, which is correct.
    • The uninstall.sh edit is correct POSIX sh ([ -e ], rm -f, printf, safe under set -e).
  4. Skipped items. I accept all three reasons (see the summary above).

Recommendation

REQUEST CHANGES. The production change is sound and closes the round-1 Improvement. The blocker is the new test's ability to SIGTERM a developer's live daemon, which then stays stopped. It comes from a pre-existing lsof selection bug that this commit makes reachable under cargo test. Adding -a, a regression test for it, and ideally a cfg(test) guard on the kill is a small change. After that this is an APPROVE from me.

@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 (re-review): REQUEST CHANGES (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125
mstomar125 force-pushed the issue-3352-single-instance-lock branch from 68011ce to ef2c5a2 Compare September 30, 2026 11:47
@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review (round 2)

Commit ef2c5a28 (branch rebased onto 1a0f437a; ratchet still passes with delta 0).

Addressed

  • [Critical] The new test could SIGTERM a developer's live daemon. Confirmed the root cause on this machine before changing anything: lsof -F p -U <path> lists 43 processes, lsof -a -F p -U <path> lists 1 (lsof ORs its selectors without -a). Fixed in three layers:
    1. pids_holding_unix_socket now runs lsof -a -F pn -U <path>. This also corrects the production callers, which relied on the argv[0] check alone.
    2. New regression test pids_holding_unix_socket_ignores_processes_holding_other_sockets (this process holds an unrelated socket, and the queried path is a stale file with no holder). Mutation check: dropping -a fails exactly that test.
    3. The libc::kill in kill_running_daemon_within is compiled out under cfg(test), mirroring signal_daemon_to_stop. This one is structural, so it has no mutation test.
      For the record, none of my earlier runs could have hit a real daemon: this account has no ~/.nodespace/bin/nodespaced, and the installed daemon on this Mac belongs to another user.
  • [Nit] Blocking connect in an async fn. The connect that decides staleness now runs through spawn_blocking.

Skipped, with reason

  • [Nit] Keep unlinking the socket when the function signalled its own daemon. The lock, not the file, decides whether a replacement daemon can start: a draining daemon holds the lock until it exits either way. Deleting its socket file would only make it unreachable sooner, and the app would then start a replacement that exits on the lock. Under launchd, bootout serialises that restart. Revisit if a real restart shows the post-bootstrap wait reporting the dying daemon as healthy for long.

Tests: 23 targeted app-lib tests pass, clippy (-D warnings -D clippy::unused-async) is clean, and the full bun run test:changed is re-running on this commit.

Re-Review Decision

Decision: RE-REVIEW NEEDED (brief)

Rationale: the fix touches the safety of a test that can signal processes. Review only ef2c5a28.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (re-review 2)

Review Type: Re-review of commit ef2c5a28 only. The rebased 0514286b and 2bb67c7a were reviewed earlier and not re-reviewed.
Read: the commit diff and the author's "Address review (round 2)" response, plus everything kill_running_daemon_within reaches: check_daemon_socket, pids_holding_unix_socket, process_argv0_matches, remove_socket_if_stale. I also read the daemon's bind_uds_owner_only and every caller of the daemon kill paths in app-lib/src, app-lib/tests, test-support and src-tauri.

Previous Review Summary

  • Previous findings: 1 Critical and 2 Nits.
  • Addressed: 2.
    • The Critical: -a on lsof, a regression test, and a cfg(test) guard on the kill.
    • The blocking-connect Nit: now run through spawn_blocking.
  • Not addressed, reason accepted: 1, the premature-Healthy Nit.
  • New issues: none that block. One informational note is below.

Checks

1. -a on lsof, and whether it breaks a legitimate match. Correct, and the doc text is accurate. I checked the behaviour on this Mac with throwaway sockets:

bound at queried as pids with -a
/private/tmp/…/x.sock the same string 1 (the holder, including its accepted connection)
/tmp/…/x.sock /private/tmp/…/x.sock 0
/private/tmp/…/x.sock /tmp/…/x.sock 0

So -a finds the listener of a live daemon. But lsof matches the path string the socket was bound with, not the inode, so a symlinked or otherwise differently spelled path no longer matches.

The legitimate case still holds:

  • bind_uds_owner_only binds directly at the final path; there is no temp-name-and-rename step.
  • The launchd plist's NODESPACED_SOCKET is format!("{}/{}", home_str, rel), built from the same dirs::home_dir() the app queries with.
  • The fallback for a Homebrew or hand-started daemon builds the path from the same $HOME.

If the two strings ever did differ, the result fails safe:

  • The old daemon is not signalled.
  • Its socket is left alone because it still answers.
  • A launchd-managed daemon is still replaced by bootstrap_launchd_agent's bootout.

That is far better than the OR behaviour, where every process running the installed binary got signalled whichever socket it held.

2. pids_holding_unix_socket_ignores_processes_holding_other_sockets.

  • Right regression. This process holds an unrelated socket, and the queried path is a stale socket file that exists but has no holder. That is exactly the gap the older unbound-path test missed, because lsof errors out on a missing path.
  • Correct failure mode. Under OR semantics the result contains this process, so the test fails. The mutation result in the author's table matches this.
  • Not flaky. No other process can hold a socket at that tempdir path.
  • Caveat. Like the existing lsof tests, it would pass without checking anything on a runner with no lsof, because the helper returns empty on a spawn error. That caveat predates this commit.

3. The #[cfg(not(test))] guard, and whether anything reachable from tests can still signal a real process.

  • The guard: it mirrors signal_daemon_to_stop. Under cfg(test), nothing in kill_running_daemon_within or its callees sends a signal. The callees only run connect, lsof, ps and remove_file on the socket path passed in, which is a tempdir in the test.
  • The file's other kill paths:
    • kill_running_daemon is private, and only ensure_daemon_running calls it. That needs a Tauri AppHandle, and no test calls it.
    • kill_stale_daemon_sync (still an unguarded SIGKILL) is called only from the app's Tauri setup in lib.rs:461. No unit test, integration test, test-support or src-tauri test calls it.
  • Integration tests: cfg(test) is not set when app-lib/tests/it links the library. I grepped, and none of those tests reach these functions either.

4. spawn_blocking. Correct.

  • ensure_daemon_running already runs in a Tokio context: it uses tokio::time and tokio::fs in the same function.
  • The #[tokio::test] current-thread runtime also has a blocking pool.
  • Ignoring the JoinError is fine, because remove_socket_if_stale cannot panic.
  • Shadowing socket_path with an owned copy is clean.

5. The skipped Nit (keep unlinking when the function signalled its own daemon). Accepted.

  • It is true that deleting the file does not let a replacement start any sooner: the draining daemon holds the lock until it exits.
  • Under launchd, the bootout inside bootstrap_launchd_agent serialises the restart, so by the time the post-bootstrap wait runs, the old job is normally gone.
  • What is left is a short window of reporting the dying daemon as healthy, and only on a slow drain. Revisiting it only if it is ever observed is proportionate.

Findings

[Nit] Say in the doc that the match is by path string

Where: daemon_setup.rs, the pids_holding_unix_socket doc comment.

One more clause would stop a future caller passing a canonicalised or symlinked spelling and silently finding no one. For example: "lsof matches the path string the socket was bound with, so pass exactly the path the daemon was told to bind."

Recommendation

APPROVE. The Critical is fixed in depth:

  • -a corrects the helper for tests and production alike.
  • The regression test fails under the old OR semantics.
  • The cfg(test) guard makes it structurally impossible for this function's tests to signal a real process.

The spawn_blocking change is correct, and the reasoning for the skipped Nit is sound. The one Nit above is optional.

@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 (re-review 2): APPROVE (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review (round 3)

Commit e6435e87. Re-review 2 was APPROVE with one optional Nit; addressed it.

Addressed

  • [Nit] Say in the pids_holding_unix_socket doc that lsof matches the bound path string. Added, with the /tmp against /private/tmp example.

Skipped: none.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: the change is a doc comment only. Clippy (-D warnings -D clippy::unused-async) is clean and bun run test:changed had already passed on the parent commit ef2c5a28 (scripts tier plus the full Rust workspace). origin/main had not moved since. The push check, including the boundary ratchet, passed.

The PR is ready for the merge gate. I have not merged it.

@mstomar125
mstomar125 force-pushed the issue-3352-single-instance-lock branch from e6435e8 to e568b20 Compare September 30, 2026 12:09
@mstomar125

Copy link
Copy Markdown
Contributor Author

Bounded wait for the lock (commit e568b209)

KeepAlive { SuccessfulExit = false } means launchd never restarts a daemon that exits 0. A restart (app kickstart, log-rotation restart, update, service-manager restart) starts the new daemon while the old one may still be draining for up to 15 s, so a daemon that lost the lock at once would leave the user with no daemon. It now waits instead.

  • acquire(socket) retries the lock every 250 ms for up to 20 s (DEFAULT_LOCK_WAIT, above the 15 s drain watchdog). A free lock is taken on the first attempt, with no delay. It logs once when it starts waiting.
  • A daemon that still finds the lock held after the wait is a genuine second daemon: it logs the holder's pid and exits 0, as before.
  • acquire_waiting(socket, max_wait) takes the wait as a parameter; Duration::ZERO is a single attempt, which the who-holds-the-lock unit tests use.
  • Test seam: the environment variable NODESPACED_LOCK_WAIT_MS shortens the wait for tests that start a real second daemon. It is not a command-line argument (unknown arguments exit 2), and not a supported setting.
  • Acceptance criterion 1 now reads "exits 0 after the bounded wait" instead of "within 10 s".

New tests: a_daemon_started_while_the_lock_is_held_waits_for_it_and_then_serves (the test process holds the lock, a real nodespaced logs that it is waiting, the lock is released, and the daemon then serves), a_lock_released_during_the_wait_is_taken, a_lock_that_stays_held_is_reported_only_after_the_wait, the_wait_override_is_read_in_milliseconds_and_falls_back_to_the_default; the existing second-daemon test now asserts the daemon lived at least its wait.

Mutation checks: no retry fails four tests (the waiting-daemon integration test, the second-daemon test, and both unit wait tests); a retry that never gives up fails the second-daemon test; ignoring the override fails the second-daemon test; reading it as seconds fails the override test.

Also: rebased onto 698246cb (the DaemonProfile change); the only conflict was in daemon_setup.rs (kept its service_env block next to my launcher_args block). Clippy (-D warnings -D clippy::unused-async, four crates) and the ratchet (delta 0 against the new main) are clean, and bun run test:changed passed on this tree (4136 nextest tests plus 261 app-lib cargo tests).

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (re-review 3)

Review Type: Re-review of commit e568b209 ("Wait a bounded time for the single-instance lock before giving up") and the rebase conflict resolution in daemon_setup.rs. The earlier commits were not re-reviewed.
Read: git show e568b209 and the author's "Bounded wait for the lock" comment. For timing, I read the daemon's shutdown path: watch_for_shutdown_signal, force_exit_on_serve_drain_timeout, drain_and_release_gpu, and main's arm_shutdown_watchdog. For the conflict, I compared against the merge base 698246cb.
Ran (safe, isolated): the branch's prebuilt target/debug/nodespaced, built 14:08 and containing the new code. It ran against a scratch tempdir, with HOME, NODESPACE_HOME and NODESPACED_SOCKET all pointed inside it, and with the lock held by a throwaway Python process. The daemon exited 0 after the wait, touched nothing outside the tempdir, and the tempdir was removed.

Previous Review Summary

  • Previous round (re-review 2): APPROVE, with 1 Nit (document that lsof matches the bound path string). The author addressed it in 9d999ac5.
  • This round: new design work, not a response to findings.
  • New issues:
    • 1 Critical: a small correctness regression, confirmed in the real binary.
    • 1 Improvement.
    • 3 Nits, one of which is a silently reverted earlier fix.

Findings

[Critical, one-line fix] After a wait, HeldByAnother.holder_pid is always None in production, and the new unit test passes only because logging is off in unit tests

Where: packages/daemon/src/single_instance.rs. The problem is in acquire_waiting and read_holder_pid.

How it happens:

  • read_holder_pid reads through Read for &File, which advances the file offset on the shared open file description.
  • The loop calls it twice on the same file: first inside the tracing::info! "waiting for the single-instance lock" announcement, then again when it gives up.
  • The first read leaves the offset at end-of-file, so the second read gets an empty string and returns None.

Why the tests pass. tracing evaluates field expressions only when the callsite is enabled. Unit tests install no subscriber, so the announcement never reads and a_lock_that_stays_held_is_reported_only_after_the_wait sees Some(pid). The real daemon logs at info, so it always gets None.

Reproduced against the built binary (lock held by pid 90549, NODESPACED_LOCK_WAIT_MS=1000):

INFO nodespace_daemon::single_instance: waiting for the single-instance lock: another nodespaced holds it holder_pid=Some(90549) max_wait_secs=1.0
INFO nodespaced: another nodespaced still holds the lock for this socket after waiting; exiting sock=… holder_pid=None

Impact:

  • The line that explains why the daemon exited now always says holder_pid=None. That regresses round-1 behaviour and contradicts the HeldByAnother doc.
  • The value of a public return field now depends on log configuration.
  • The second-daemon integration test still passes, because the pid appears in the earlier "waiting" line.

Fix. Make the read position-independent, for example FileExt::read_at(&mut buf, 0) into a 32-byte buffer, and keep side-effecting calls out of log macro arguments. Read the pid into a local before tracing::info! if you want it logged. Add a test that calls read_holder_pid twice on one File and gets Some both times; the current tests cannot catch this.

Principle: a test that passes for the wrong reason is worse than no test. Also, log macros must never carry side effects, because whether they run depends on configuration.

[Improvement] 20 s is not "comfortably above" how long an old daemon can take to exit

Where: the DEFAULT_LOCK_WAIT doc, "the daemon's shutdown watchdog is 15 s".

The watchdogs run one after another, not as one bound:

Phase Watchdog Armed Socket state
gRPC serve drain force_exit_on_serve_drain_timeout, 15 s when the signal arrives listener still open
DB and GPU drain drain_and_release_gpu, 15 s when that drain starts socket file already removed

In tray mode, main's arm_shutdown_watchdog adds a further bound after tray::run returns. So a draining daemon can hold the lock for about 30 s or more when both drains stall. The code documents both stalls as observed in practice: a stalled WatchNodes stream, and the teardown stall. A successor that gives up at 20 s still leaves no daemon in that case.

Options, not blocking:

  • Correct the doc to state the real bound and that 20 s covers the common case.
  • More robust: exit non-zero when nobody is serving. At give-up, if the socket refuses connect, the holder is not serving: it is draining, stuck, or has had its socket removed. Exit non-zero in that case, so a KeepAlive { SuccessfulExit = false } registration retries after its throttle. Exit 0 only when the socket answers, because only then does a genuine peer serve. This removes the need to guess an upper bound.
    • The one caveat: during phase 1 the old listener still accepts connections. But after a 20 s wait, any daemon that was in phase 1 at the start has moved on, so the check is reliable at give-up time.
    • It keeps ADR-084's "exit 0 when another daemon serves" intact.
  • Mind the app's 30 s startup wait (wait_for_daemon_or_refusal). Raising DEFAULT_LOCK_WAIT towards 30 s or more would make the app report a failure while the daemon is still legitimately waiting, so the non-zero-exit route fits better than a longer wait.

[Nit] This commit silently reverts the round-3 doc fix

Where: the doc for pids_holding_unix_socket in packages/desktop-app/app-lib/src/daemon_setup.rs.

9d999ac5 added "lsof matches the path string the socket was bound with … (/tmp against /private/tmp) finds nobody". This commit's diff removes it again: git show e568b209 -- …/daemon_setup.rs shows only that hunk. It is most likely a rebase artifact. Please restore it.

[Nit] A SIGTERM during the wait now looks like a crash to KeepAlive

No signal handler exists before the lock is taken, so a SIGTERM during the up-to-20 s wait kills the process with a signal status. KeepAlive { SuccessfulExit = false } counts that as unsuccessful and restarts it.

The usual stop paths are fine:

  • bootout and systemctl stop unload the job, so there is no restart.
  • The app's signal_daemon_to_stop targets only socket holders, and a waiting daemon holds no socket.

Only a bare launchctl kill TERM would respawn it. Before this commit the window was microseconds; now it is up to 20 s. If "stop" should mean stop, check a signal flag between polls and return exit 0; signal-hook or a sigwait with a timeout are simple ways. Otherwise, say in a comment that this is accepted.

[Nit] The library reads a process environment variable

Where: acquire calls lock_wait(), which reads NODESPACED_LOCK_WAIT_MS.

That gives every daemon built on the crate a hidden input. acquire_waiting is already public. Reading the variable in main.rs and passing it in would keep the library free of environment reads, and a caller that wants the seam can do the same.

It cannot become a user-facing flag: it is not an argument, and it is documented as unsupported. Values are safe too: Duration::from_millis(u64) and the arithmetic cannot overflow, and garbage input falls back to the default.

Checks the requester asked for

  1. acquire_waiting loop:
    • The first attempt is immediate.
    • Duration::ZERO makes exactly one attempt.
    • max_wait - waited runs only after waited >= max_wait has returned, so waited < max_wait strictly and it cannot underflow.
    • One try happens after the last sleep, at or after max_wait, before it gives up.
    • Reusing one open file across try_lock retries is valid for flock.
    • Error paths (TryLockError::Error, the pid-record failure) are unchanged.
    • The pid is read at the announcement and at give-up, which is what causes the Critical above.
  2. Timing, and places that assume a losing daemon exits quickly:
    • 20 s is coherent with each 15 s watchdog alone, but not with their sum (see the Improvement).
    • The app's 30 s startup wait still covers a 20 s lock wait plus bind, because model load is backgrounded and bind follows the DB open.
    • kill_running_daemon waits 5 s and then re-registers, and a successor now waits for the old daemon instead of exiting. That is an improvement.
    • I found no test or code path that needs a losing daemon to exit quickly. The second-daemon test uses the override (1.5 s) with a 10 s exit timeout.
    • SIGTERM during the wait: see the Nit.
  3. The env seam: see the Nit. It is acceptable as is.
  4. Tests:
    • The timing assertions are lower bounds only (>= 300 ms, >= wait, lived >= lock_wait). All are deterministic.
    • The integration test holds the lock through acquire_waiting(ZERO). std opens with O_CLOEXEC, so the spawned daemon cannot inherit the lock's file description. It waits for the "waiting for the single-instance lock" line, asserts the daemon is alive, releases the lock, and then waits for connect.
    • The successor has its full 20 s between logging and the release, so it is not flaky.
    • Each test uses its own tempdir home, so they are isolated.
    • The one weakness is the unit test that masks the pid bug.
  5. Merge resolution: correct.
    • Upstream's service_env block sits beside launcher_args.
    • The template has {launcher_args} after {bin} and service_env = service_env in the named arguments.
    • No pro_env or DAEMON_TRAY_FLAG remains.
    • macos_plist_keepalive_tests imports use super::{write_plist, DaemonProfile}; use nodespace_proto::socket::LAUNCHER_ARGS;.
    • The systemd and Windows substitutions are intact.

Recommendation

REQUEST CHANGES. The bounded wait is the right design and a clear net improvement. Before merge, two small, confirmed regressions need fixing:

  • the holder_pid read, with a test that can actually catch it;
  • the dropped lsof doc sentence.

Please also either correct the DEFAULT_LOCK_WAIT justification or adopt the "exit non-zero when nobody is serving" give-up. Both changes are a few lines. With the pid fix and the doc restored, this is an APPROVE from me.

@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 (re-review 3): REQUEST CHANGES (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125
mstomar125 force-pushed the issue-3352-single-instance-lock branch from e568b20 to 87fdc2a Compare September 30, 2026 12:29
@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review: bounded wait (commit 87fdc2a7)

Re-review 3 (of the bounded wait) was REQUEST CHANGES. Addressed:

  • [Critical] The holder pid was None after a wait. Confirmed: read_holder_pid moved the lock file's shared read position, the wait's log line read it first, and the give-up read then hit end of file. The unit tests passed only because they install no log subscriber. Now the pid is read at a fixed offset (read_at), outside the log macro, with the_holder_pid_can_be_read_more_than_once_from_one_open_file and a process-level check that the second daemon's exit line names the holder. Mutation (the original read): fails those two and a_lock_that_stays_held_is_reported_only_after_the_wait.
  • [Improvement] 20 s does not always outlast a draining daemon. Confirmed: the two 15 s shutdown watchdogs run in sequence, so a stalled old daemon can hold the lock for about 30 s. I took the reviewer's second option. When the wait ends with the lock still held, the daemon exits 0 only if the socket answers (a peer really serves); if nothing answers it exits with an error, so KeepAlive { SuccessfulExit = false } retries after its throttle instead of leaving no daemon. The DEFAULT_LOCK_WAIT doc now states the real bound. This is a small addition to the requested behavior (the genuine-second-daemon case still exits 0 after the wait); it is confined to the HeldByAnother arm in main.rs, so it is easy to drop if you would rather keep exit 0 there. New test: a_daemon_that_finds_the_lock_held_but_nothing_serving_exits_with_an_error; mutations "always exit 0" and "never exit 0" each fail one of the two give-up tests.
  • [Nit] The lsof doc sentence was dropped by the previous commit. My mistake, not a rebase artifact: my mutation-check script restored a stale backup of that file. Restored; I now diff the whole tree before and after mutation runs.
  • [Nit] A stop signal during the wait ends the process by signal. Accepted and documented in main.rs (only a bare launchctl kill would respawn it; bootout and systemctl stop unload the job).

Skipped: moving the NODESPACED_LOCK_WAIT_MS read out of the library into main.rs. It keeps every daemon built on the crate able to shorten the wait in its own tests, it is documented as unsupported, and it cannot become a command-line argument. Revisit if a second consumer objects to a library environment read.

Verified on the rebased tree (onto d767ef36): clippy (-D warnings -D clippy::unused-async, four crates) clean, ratchet delta 0 against main, bun run test:changed passed.

@mstomar125

Copy link
Copy Markdown
Contributor Author

Pragmatic code review (re-review 4)

Review Type: Re-review of commit 87fdc2a7 ("keep the holder pid across the wait, and exit with an error when nothing serves"), plus a check that the final tree is clean. The earlier commits (rebased onto d767ef36) were not re-reviewed.

Ran (all isolated; no live daemon or ~/.nodespace touched, no processes left behind):

  • Prebuilt tests (binaries built 14:27, after the commit): the single_instance unit tests pass (14/14, including the new twice-read test). The integration tests pass (it single_instance::, 5/5 in 3.2 s, serial).
  • The real target/debug/nodespaced, in a scratch tempdir with HOME, NODESPACE_HOME and the socket inside it, the lock held by a throwaway Python process, and NODESPACED_LOCK_WAIT_MS=600:
lock held, nothing serving:  exit=1
  INFO … waiting for the single-instance lock … holder_pid=Some(11518) …
  Error: the single-instance lock for …/d.sock is still held (holder pid Some(11518)) after waiting, but nothing answers on the socket; exiting with an error so the service manager tries again
lock held, socket answering: exit=0
  INFO … waiting for the single-instance lock … holder_pid=Some(11518) …
  INFO nodespaced: another nodespaced still holds the lock for this socket after waiting; exiting … holder_pid=Some(11518)

Previous Review Summary

  • Previous findings (re-review 3): 5 — 1 Critical, 1 Improvement, 3 Nits.
  • Addressed: 4.
    • Critical: the holder pid survives the wait.
    • Improvement: a non-zero exit when nothing serves, and a corrected wait doc.
    • Nit: the dropped lsof doc sentence is restored.
    • Nit: SIGTERM during the wait is now documented as accepted.
  • Not addressed, accepted: 1. The environment variable is still read in the library. It is harmless.
  • New issues: 1 Improvement (not blocking) and 2 Nits.

Answers to the requester's questions

  1. The pid fix is correct.

    • read_at(&mut [0u8; 32], 0) is a positional pread, independent of the shared file offset.
    • For a file this small, a single call returns everything.
    • PID_READ_LIMIT: usize is right for a buffer length.
    • The pid is now read into a local before tracing::info!, so no side effect runs inside a log macro.
    • the_holder_pid_can_be_read_more_than_once_from_one_open_file fails under the old cursor-based read, so it guards the regression properly.
    • The process-level check asserts Some(<pid>) on the exit line, not on any earlier line, which is the right target. The field value stays contiguous even when tracing styles the field name with ANSI codes, so the match holds in colour and in NO_COLOR output.
  2. Exit non-zero when nothing answers: right for both registrations.

    • KeepAlive { SuccessfulExit = false }: exit 1 means launchd retries. The attempt lived about 20 s, which is more than the throttle interval, so it relaunches promptly.
    • Homebrew keep_alive true restarts on any exit, so nothing changes there.
    • systemd Restart=on-failure also retries, and each attempt lasts 20 s or more, so it stays clear of the default start-rate limit.

    Cases where it could be worse than exit 0:

    • A genuine peer still starting at give-up time (for example a slow database open or migration longer than 20 s before it binds). The loser exits 1, is restarted, finds the peer serving on the next attempt, and exits 0. The cost is one extra cycle and one Error: line. Exit 0 would have been correct here only by luck, and it strands the user in the stuck-holder case, so this is the better trade.
    • A holder stuck forever. This gives a 20 s retry loop with one error per cycle. That is visible and self-heals when the holder dies, which is better than silently having no daemon.
    • A holder in its first drain phase, when its listener is still open so connect succeeds. The loser would then exit 0 wrongly, but only if it started before the holder's stop signal. Restart flows signal first, and phase 1 is at most 15 s, which is less than 20 s, so the check is reliable at give-up time.
    • Error message: acceptable, and it names the socket, the pid and the reason. See the Nit on wording.
    • ADR-084: the behaviour now refines the proposed §4.1 "a held lock is a deliberate exit 0". It is exit 0 only when a peer answers. See the Improvement.
  3. a_daemon_that_finds_the_lock_held_but_nothing_serving_exits_with_an_error is deterministic: the socket never exists and the wait is 500 ms against a 10 s exit timeout. It is isolated in its own tempdir home. It asserts all of these:

    • a non-success exit;
    • the reason in the log (anyhow's Error: goes to stderr, which is the same file);
    • that no socket was created.
  4. Docs.

    • The DEFAULT_LOCK_WAIT doc now states the true bound: two sequential 15 s watchdogs, so about 30 s. It explains why 20 s covers a full stall of either phase and stays under the app's 30 s wait.
    • The SIGTERM-during-wait comment in main documents the accepted behaviour.
  5. The final tree is clean.

    • The lsof bound-path sentence appears exactly once.
    • -a is on the lsof call, and the cfg(not(test)) guard on the kill and the spawn_blocking probe are both in place.
    • There is no DAEMON_TRAY_FLAG anywhere.
    • There are no #NNNN references in the added lines.
    • The conflict resolution from the last round is unchanged.

Findings

[Improvement, not blocking] The exit-0-or-error policy lives in core's binary, not in the shared library

Where: packages/daemon/src/main.rs, the HeldByAnother arm.

The concern. ADR-084 says every daemon on core's crates calls single_instance::acquire. The new "exit 0 only if the socket answers, otherwise fail" rule sits in core's main. Another daemon built on these crates that follows the ADR's current text (a held lock means exit 0) would still strand the user in the stuck-holder case.

Suggestion. Put the decision where every daemon gets it. Either:

  • carry it in the outcome: Acquire::HeldByAnother { holder_pid, serving: bool }, or a separate variant for "held, but nothing serves"; or
  • add a pub fn holder_serves(socket: &Path) -> bool beside acquire.

Then amend ADR-084 §4.1, which is still proposed, to say a daemon exits 0 only when a peer answers and otherwise exits non-zero so the service manager retries. The fix belongs here as a follow-up, or in the ADR PR. It does not change core's behaviour, which is correct.

Principle: a contract that other binaries must honour belongs in the shared API and the ADR, not only in one caller.

[Nit] Blocking connect at give-up on Linux

A blocking Unix-domain connect to a listener whose backlog is full waits until there is room. So a loser facing a hung, backlogged holder would sit in connect until that holder dies, then exit 1. It still resolves on its own. An optional fix is a non-blocking connect with a short timeout. macOS returns ECONNREFUSED at once.

[Nit] Log and error formatting

  • The error reads holder pid Some(11518). Printing holder pid 11518, or unknown for None, would read better.
  • max_wait_secs = max_wait.as_secs_f32() prints 0.6000000238418579. ?max_wait (600ms) or max_wait.as_millis() avoids the float noise.

Recommendation

APPROVE. Every re-review 3 finding is resolved:

  • The pid regression is fixed with a test that actually catches it.
  • The give-up now distinguishes "a peer serves" (exit 0) from "nothing serves" (exit 1, retried). I verified both against the real binary.
  • The wait's justification is corrected, and the reverted doc is restored.

What remains is optional: moving the serve check into the library and amending ADR-084 §4.1 so the other daemon built on these crates gets the same rule, plus two formatting Nits.

@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 (re-review 4): APPROVE (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.

@mstomar125
mstomar125 force-pushed the issue-3352-single-instance-lock branch from 87fdc2a to c80c581 Compare September 30, 2026 12:42
@mstomar125

Copy link
Copy Markdown
Contributor Author

Address review: re-review 4 (commit c80c5815)

Re-review 4 was APPROVE. Addressed its two formatting nits: the exit error prints holder pid 11518 (or unknown), and the wait is logged as max_wait=600ms instead of a float.

Not addressed here, for the merger to decide:

  • [Improvement] The "exit 0 only if a peer answers, otherwise exit non-zero" rule lives in core's main.rs, not in the shared library. A daemon built elsewhere on these crates that follows ADR-084 section 4.1's current wording (a held lock means exit 0) would still strand the user when the holder is stuck. Moving the decision into single_instance (a serving field on HeldByAnother, or a holder_serves(socket) next to acquire) and amending section 4.1 would give every daemon the rule. It does not change core's behavior, so it can follow this PR.
  • [Nit] Blocking connect at give-up on Linux waits until a hung, backlogged holder dies; it still resolves on its own.

Final verification on the rebased tree (onto ea4bfd86): clippy (-D warnings -D clippy::unused-async, four crates) clean, boundary ratchet delta 0 against main, bun run test:changed passed. Main has since moved two more commits (978a3a52, 399a5d35); the branch merges with them cleanly (mergeStateStatus: CLEAN). Not merged.

mstomar125 and others added 7 commits September 30, 2026 14:54
…list

A daemon takes an exclusive advisory lock on <socket stem>.lock, beside its
socket, before it loads the registry, opens a database, loads the model or
touches the socket. A daemon that loses the lock logs the holder's pid and
exits 0, so a KeepAlive { SuccessfulExit = false } registration leaves the
running daemon alone. Both serve loops delete an existing socket before they
bind, so until now a second daemon silently took the socket over while the
first kept its databases open. Isolated daemons set their own
NODESPACED_SOCKET, so their locks never contend with the user's daemon.

nodespace_proto::socket now owns TRAY_FLAG and LAUNCHER_ARGS, re-exported as
nodespace_daemon::LAUNCHER_ARGS. The daemon's TRAY_FLAG and the app's
DAEMON_TRAY_FLAG, two literals kept in step by hand, become that one constant,
and each launcher (plist, systemd unit, Windows spawn and autorun entry)
passes every entry. A daemon test asserts the daemon accepts every entry.

create_dir_owner_only gains a blocking form so the lock can be taken before
the async runtime exists. nodespace uninstall removes each socket's lock file
with the socket.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…e daemon

kill_running_daemon and kill_stale_daemon_sync deleted the daemon socket
unconditionally. With the single-instance lock, a daemon the app did not start
(a Homebrew service, one started by hand) that is still serving the socket
would lose its socket file while keeping the lock, and the daemon the app then
starts would exit without serving, leaving nothing reachable. Both now go
through remove_socket_if_stale, which deletes the file only once nothing
accepts connections on it. Staleness is decided by connecting, as
check_daemon_socket does, not by probing the lock, because a probe would make a
daemon starting at that moment see the lock held and exit.

Also: scope the LAUNCHER_ARGS doc to the desktop app's launchers (the Homebrew
formula's headless service passes none), guard that entries stay one plain word
because two launchers join them unquoted, and have scripts/uninstall.sh remove
the lock file beside the socket.

Not changed: lock_path_for stays in the daemon crate, since the app no longer
needs it; nodespace uninstall's lock removal mirrors its unconditional socket
removal and runs after the app's own daemon has been stopped.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
lsof ORs its selectors unless given -a, so `lsof -F pn -U <path>` listed every
process on the machine with any Unix socket open, not the holders of <path>.
The argv[0] check before each signal kept that from killing the wrong process
in production, but the new kill_running_daemon test could reach a real
installed daemon: it now runs with -a, has a regression test that fails
without it, and compiles the kill out under cfg(test) as signal_daemon_to_stop
already does.

The blocking connect that decides whether a socket is stale now runs on the
blocking pool instead of an async worker.

Not changed: after the exit grace, a socket a draining daemon still answers on
is kept. The lock, not the file, decides whether a replacement can start, so
deleting a draining daemon's socket would only make it unreachable sooner.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
A daemon that exits with status 0 is a deliberate stop that a
KeepAlive { SuccessfulExit = false } registration never restarts. A restart
starts the new daemon while the old one may still be draining after its stop
signal, for up to the shutdown watchdog's 15 s, so a new daemon that lost the
lock at once left the user with no daemon at all. That covers an app-initiated
restart, the log-rotation restart, an update and a service-manager restart.

acquire now retries the lock every 250 ms for up to 20 s before it reports
another holder; a free lock is still taken on the first attempt.
acquire_waiting takes the wait as a parameter, and Duration::ZERO makes one
attempt. A daemon that still finds the lock held after the wait is a genuine
second daemon and exits 0 as before. NODESPACED_LOCK_WAIT_MS shortens the wait
for a test that starts a real second daemon; it is an environment variable, not
an argument, because the daemon exits with status 2 on arguments it does not
know.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
… error when nothing serves

The wait read the holder's pid once to log it and again when it gave up, but
the read moved the lock file's shared position, so the second read hit end of
file and the daemon's exit line always said holder_pid=None. The unit test
passed only because unit tests install no log subscriber. The pid is now read
at a fixed offset, outside the log macro, with a test that reads it twice from
one open file and a process-level check on the exit line.

A daemon whose wait ends with the lock still held now looks at the socket. If
it answers, a peer really serves and the daemon exits 0 as before. If nothing
answers, the holder is still starting or stuck in a drain that outlasts the
wait (the two 15 s shutdown watchdogs run one after the other, so a stalled
daemon can hold the lock for about 30 s), and exiting 0 would leave no daemon:
it exits with an error so the service manager tries again after its throttle.

Also restores the lsof doc sentence that the previous commit dropped by
mistake, and documents that a stop signal during the wait ends the process by
signal.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@mstomar125
mstomar125 force-pushed the issue-3352-single-instance-lock branch from c80c581 to 19fc9cd Compare September 30, 2026 12:54
@mstomar125
mstomar125 merged commit e2c499e into main Sep 30, 2026
@mstomar125
mstomar125 deleted the issue-3352-single-instance-lock branch September 30, 2026 12:54
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 a single-instance daemon lock and export the launcher's argument list

1 participant