Repository navigation
Add a single-instance daemon lock and export the launcher's argument list - #3388
Conversation
Pragmatic code review (initial)Review Type: Initial Review
Requirements Check
Author's stated deviations, verified:
Findings[Improvement] The lock can be held by a daemon that no longer serves, and then every successor exits 0 and nothing restarts itFiles: 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.
Suggested fixes. Either fits in this PR or in a tracked follow-up that lands before the next release:
[Nit] Move
|
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.
02d3821 to
68011ce
Compare
Address review (round 1)Commit Addressed
Skipped, with reasons
Tests (each mutation-checked, all restored afterwards)
Not covered by a test: the Re-Review DecisionDecision: 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 (re-review)Review Type: Re-review of commit Previous Review Summary
Findings[Critical] The new test can send SIGTERM to the developer's real, running NodeSpace daemonWhere: 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 What lsof actually does. The helper runs What happens under
Who is affected. Any developer who runs the app-lib tests (
The file already guards against exactly this: Fix (small):
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
|
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review): REQUEST CHANGES (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.
68011ce to
ef2c5a2
Compare
Address review (round 2)Commit Addressed
Skipped, with reason
Tests: 23 targeted app-lib tests pass, clippy ( Re-Review DecisionDecision: RE-REVIEW NEEDED (brief) Rationale: the fix touches the safety of a test that can signal processes. Review only |
Pragmatic code review (re-review 2)Review Type: Re-review of commit Previous Review Summary
Checks1.
So The legitimate case still holds:
If the two strings ever did differ, the result fails safe:
That is far better than the OR behaviour, where every process running the installed binary got signalled whichever socket it held. 2.
3. The
4.
5. The skipped Nit (keep unlinking when the function signalled its own daemon). Accepted.
Findings[Nit] Say in the doc that the match is by path stringWhere: 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." RecommendationAPPROVE. The Critical is fixed in depth:
The |
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review 2): APPROVE (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.
Address review (round 3)Commit Addressed
Skipped: none. Re-Review DecisionDecision: NO RE-REVIEW NEEDED Rationale: the change is a doc comment only. Clippy ( The PR is ready for the merge gate. I have not merged it. |
e6435e8 to
e568b20
Compare
Bounded wait for the lock (commit
|
Pragmatic code review (re-review 3)Review Type: Re-review of commit Previous Review Summary
Findings[Critical, one-line fix] After a wait,
|
| 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 aKeepAlive { 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). RaisingDEFAULT_LOCK_WAITtowards 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:
bootoutandsystemctl stopunload the job, so there is no restart.- The app's
signal_daemon_to_stoptargets 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
acquire_waitingloop:- The first attempt is immediate.
Duration::ZEROmakes exactly one attempt.max_wait - waitedruns only afterwaited >= max_waithas returned, sowaited < max_waitstrictly 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_lockretries 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.
- 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_daemonwaits 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.
- The env seam: see the Nit. It is acceptable as is.
- 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 withO_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 forconnect. - 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.
- The timing assertions are lower bounds only (
- Merge resolution: correct.
- Upstream's
service_envblock sits besidelauncher_args. - The template has
{launcher_args}after{bin}andservice_env = service_envin the named arguments. - No
pro_envorDAEMON_TRAY_FLAGremains. macos_plist_keepalive_testsimportsuse super::{write_plist, DaemonProfile}; use nodespace_proto::socket::LAUNCHER_ARGS;.- The systemd and Windows substitutions are intact.
- Upstream's
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_pidread, 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
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review 3): REQUEST CHANGES (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.
e568b20 to
87fdc2a
Compare
Address review: bounded wait (commit
|
Pragmatic code review (re-review 4)Review Type: Re-review of commit Ran (all isolated; no live daemon or
Previous Review Summary
Answers to the requester's questions
Findings[Improvement, not blocking] The exit-0-or-error policy lives in core's binary, not in the shared libraryWhere: The concern. ADR-084 says every daemon on core's crates calls Suggestion. Put the decision where every daemon gets it. Either:
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
|
mstomar125
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review (re-review 4): APPROVE (posted as a comment; GitHub blocks self-approval). Full findings in the review comment above.
87fdc2a to
c80c581
Compare
Address review: re-review 4 (commit
|
…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]>
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]>
… float noise Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
c80c581 to
19fc9cd
Compare
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
nodespace_daemon::single_instance, Unix only).acquire(socket)takes an exclusiveflockon<socket stem>.lock, beside the socket, and records the holder's pid.main()takes it right after argument handling and tracing init, beforestdio_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 aKeepAlive { 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.nodespace_proto::socket::{TRAY_FLAG, LAUNCHER_ARGS}, re-exported asnodespace_daemon::LAUNCHER_ARGS. The daemon'sTRAY_FLAGand the app'sDAEMON_TRAY_FLAG(two literals kept in step by hand) are gone. The launchd plist writes one<string>per entry, the systemdExecStartand 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"].remove_sockalso removes each socket's lock file (Unix).kill_running_daemonandkill_stale_daemon_syncnow delete the socket only once nothing accepts connections on it. Also:scripts/uninstall.shremoves the lock file, theLAUNCHER_ARGSdoc 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
packages/desktop-app/app-lib/src/daemon_setup.rs, notsrc-tauri/src. The acceptance grep therefore runs overpackages/desktop-app/app-lib/srctoo; it finds no"--tray"literal inpackages/daemon/srcor anypackages/desktop-appRust source.create_dir_owner_only. The issue asks for a sync helper that both callers use.create_dir_owner_only_blockingis that helper (same steps, same errors, same doc contract) and the async function now delegates to it throughspawn_blocking.acquire(socket)waits up toDEFAULT_LOCK_WAIT(20 s);acquire_waiting(socket, max_wait)takes the wait as a parameter (Duration::ZEROis 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 variableNODESPACED_LOCK_WAIT_MSshortens 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).acquirereturns an error when the socket path already ends in.lock, becausewith_extension("lock")would make the socket its own lock file.None; lock file mode;remove_sock.connect, not by the socket file existing, because a SIGKILLed daemon leaves a stale socket file behind.Ratchet
bun run scripts/check-pro-boundary.tspasses. My branch andorigin/mainprint identical counts for every marker, so the delta is 0 andBASELINESis unchanged. (cloudSyncHooksis 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-asyncis 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):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_lockalways reports contentiontry_lockalways succeedsa_second_acquire_...names_the_holder,an_unreadable_recorded_pid_is_reported_as_none, the second-daemon integration testsockets_in_one_directory_do_not_contend,daemons_on_different_sockets_do_not_block_each_other(+ path test)a_crashed_daemon_leaves_no_lock_behind,dropping_the_lock_frees_it,a_stale_pid_...set_len(0)a_stale_pid_from_a_dead_holder_is_replaced_not_appended_toDropdropping_the_lock_frees_itcreate_dir_allinstead of the owner-only helperthe_parent_directory_is_created_owner_only0o666the_lock_file_is_owner_only.lock-extension guarda_socket_path_that_is_its_own_lock_file_is_refusedSome(0)an_unreadable_recorded_pid_is_reported_as_nonelcklock_path_sits_beside_the_socket_with_the_lock_extensiona_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_waita_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_alonethe_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 holdera_second_daemon_on_a_served_socket_exits_zero_and_leaves_the_socket_alonea_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_defaultLAUNCHER_ARGS = []the_launcher_arguments_put_the_daemon_in_tray_mode,pkg_plist_opts_the_daemon_into_tray_modeLAUNCHER_ARGSgains an entry the daemon rejectsevery_launcher_argument_is_recognized,pkg_plist_opts_the_daemon_into_tray_mode(the static.pkgplist drifts)write_plistwrites only the first entryplist_opts_the_daemon_into_tray_mode,pkg_plist_opts_the_daemon_into_tray_moderemove_sockleaves lock filesremove_sock_removes_every_variants_socket_and_lock_file_onlya_socket_something_answers_on_is_left_alone,kill_running_daemon_leaves_the_socket_of_a_daemon_it_cannot_stopa_socket_nothing_answers_on_is_removed,a_socket_that_stops_answering_within_the_grace_is_removedlauncher_args_survive_an_unquoted_command_lineThe integration tests start real
nodespacedprocesses 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
brew servicesdaemon 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.flockover a network home directory is best effort.kill_stale_daemon_synccall 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.🤖 Generated with Claude Code