Skip to content

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

Closed

Description

@mstomar125

Summary

Core's side of ADR-084 §4.1 and §4.2 (proposed):

  1. A single-instance lock in the daemon library. Add nodespace_daemon::single_instance. It takes an exclusive advisory lock on the lock file beside the daemon's socket: the socket path with the extension lock. For the default sockets that gives ~/.nodespace/daemon.lock and daemon-dev.lock. Both daemons call this library function.
  2. nodespaced takes the lock before anything else. It does so before it loads the registry, opens a database, loads the model, or deletes and binds the socket. If another daemon holds the lock, it logs the holder's pid (if one was recorded), writes nothing, and exits 0.
  3. One exported launcher argument list. Add nodespace_proto::socket::LAUNCHER_ARGS, today ["--tray"], and re-export it as nodespace_daemon::LAUNCHER_ARGS.
    • The app's launchers pass exactly that list.
    • Today two literals are kept in step by hand: the daemon's TRAY_FLAG and the app's DAEMON_TRAY_FLAG. Both become the one shared constant.
    • A community-daemon test asserts that the daemon accepts every entry. The Pro daemon's tests parse the same list (ADR-084 §4.2 item 1).
  4. Uninstall cleans up locks. nodespace uninstall also removes stale lock files next to the sockets it removes.

Context

  • Nothing stops a second daemon on Unix today. Both serve_headless (1236) and serve_grpc (1315) delete an existing socket before binding. A second daemon therefore silently takes over the socket while the first keeps its databases open. Two ways this happens:
    • the nodespace-cli formula's brew services job, which uses keep_alive true (scripts/update-homebrew-formula.ts 330-340);
    • a daemon started by hand.
  • Windows gets no lock. Its named pipe already admits only one server, through first_pipe_instance(true).
  • Why the lock sits beside the socket, not at a fixed path. Isolated daemons that set their own NODESPACED_SOCKET then never contend with the user's daemon. That covers src-tauri/test-support, the e2e daemon-harness.ts, packages/daemon/tests/it and the two-window demo.
  • Exiting 0 is deliberate. A KeepAlive { SuccessfulExit = false } registration then leaves the daemon stopped. A Homebrew service restarts it on its throttle interval, and every restart exits the same way. ADR-084 §4.1 accepts that.
  • How to take the lock. The toolchain is 1.95, so use std::fs::File::try_lock (stable since 1.89).
    • On Unix it is flock, and it returns Err(TryLockError::WouldBlock) when the lock is held.
    • The OS releases the lock when the process exits, so a crash leaves no stale lock.
    • It is advisory only, not a security boundary (ADR-052).
  • When to take it. Take the lock before stdio_log_rotation::spawn() and before the runtime exists. A daemon that loses the lock must not touch the log file the two daemons share.
  • Contract test. It uses Remove the pro feature and --edition from nodespaced and reject unknown arguments #3348's first_unrecognized_arg.

Scope

packages/proto/src/socket.rs

  • Add pub const TRAY_FLAG: &str = "--tray"; and pub const LAUNCHER_ARGS: [&str; 1] = [TRAY_FLAG];.
  • Their docs say:
    • these are the arguments every launcher passes to the daemon it registers;
    • a daemon registered under core's service identity must accept each one;
    • adding an argument is an extension-API change (ADR-082 §6).
  • In the module doc, add the lock rule: <socket stem>.lock, beside the socket.

packages/daemon

  • New src/single_instance.rs (#[cfg(unix)]). Register it with pub mod single_instance; in src/lib.rs, and add pub use nodespace_proto::socket::LAUNCHER_ARGS; there too.
    • pub fn lock_path_for(socket: &Path) -> PathBuf, which returns socket.with_extension("lock").
    • pub enum Acquire { Held(InstanceLock), HeldByAnother { holder_pid: Option<u32> } }.
    • pub struct InstanceLock, which holds the open File. Dropping it releases the lock.
    • pub fn acquire(socket: &Path) -> Result<Acquire>, which is synchronous. In order, it:
      1. creates the parent directory with the same owner-only rule as create_dir_owner_only (src/lib.rs 104-138), factored into a sync helper that both use;
      2. opens or creates the lock file with mode 0o600, without truncating it;
      3. calls try_lock();
      4. on success, truncates the file and writes this process's pid;
      5. on WouldBlock, reads the pid (best effort) and returns HeldByAnother;
      6. returns any other error.
  • src/main.rs main(). After argument handling and tracing init, and before stdio_log_rotation::spawn() and the runtime, add a #[cfg(unix)] block that takes the lock:
    • On Held(l), keep l as _instance_lock for the rest of main.
    • On HeldByAnother { holder_pid }, log at info! that another daemon already serves this socket, and return Ok(()), which exits 0.
    • Replace const TRAY_FLAG (1130-1134) with the proto constant. ACCEPTED_ARGS keeps listing what the daemon handles.
    • Add the contract test: first_unrecognized_arg returns None for an argv built from LAUNCHER_ARGS. sync mirrors this test.

packages/desktop-app/src-tauri/src/daemon_setup.rs

  • Delete DAEMON_TRAY_FLAG (107-115). Each launcher passes every entry of LAUNCHER_ARGS:

    • write_plist: one <string> per entry.
    • write_systemd_service: ExecStart joins the entries with spaces.
    • spawn_daemon_windows: .args(LAUNCHER_ARGS).
    • register_autorun_windows: the entries, joined, after the quoted binary.

    The output stays byte-identical while the list is ["--tray"].

  • plist_opts_the_daemon_into_tray_mode and pkg_plist_opts_the_daemon_into_tray_mode assert each entry of LAUNCHER_ARGS. The second test then also guards scripts/pkg-resources/app.nodespace.daemon.plist against drift.

packages/cli/src/commands/uninstall.rs

  • In remove_sock, also remove lock_path_for(dir.join(name)) for each socket name. The CLI already depends on nodespace-daemon.

Out of scope

Steps

  1. Run the startup sequence, and assign the issue at pickup.
  2. Add the proto constants, then single_instance and its unit tests.
  3. Wire the lock into main(), replace the tray constant, and add the contract test.
  4. Switch the app's launchers to LAUNCHER_ARGS.
  5. Update remove_sock.
  6. Add the integration test.
  7. Run bun run scripts/check-pro-boundary.ts and paste BASELINES.
  8. Run bun run test:changed and bun run quality:fix, push, and open the PR. Code comments must not cite GitHub issue numbers.

Acceptance criteria

  • When a second nodespaced starts on the socket a running one serves, it exits 0 within 10 s and never deletes or binds the socket. The first keeps serving.
  • Daemons on different sockets never block each other.
  • LAUNCHER_ARGS is exported from both nodespace_proto::socket and nodespace_daemon.
  • No other --tray literal remains in packages/daemon/src or packages/desktop-app/src-tauri/src: git grep -n -F -e '"--tray"' -- packages/daemon/src packages/desktop-app/src-tauri/src shows only the proto definition's re-use sites.
  • The community plist, systemd unit and Windows command lines are byte-identical to before.
  • bun run scripts/check-pro-boundary.ts passes, with BASELINES pasted. No change is expected.

Tests and verification

  • Unit tests for single_instance:
    • acquiring A gives Held;
    • acquiring B on the same path gives HeldByAnother, with holder_pid equal to this process's pid (flock locks belong to the open file description, so two opens in one process conflict);
    • after dropping A, acquiring C gives Held;
    • lock_path_for maps daemon.sock to daemon.lock, and daemon-dev.sock to daemon-dev.lock;
    • the parent directory is created with mode 0o700.
  • Integration test: add tests/it/single_instance.rs and register it in tests/it/main.rs.
    1. Spawn daemon A with a FIFO model path and a tempdir socket, following sigterm_during_model_load.rs, and wait for the socket.
    2. Spawn B with the same environment. Assert that B exits 0 within 10 s, A is still alive, and the socket still accepts a connection.
    3. Send SIGTERM to A.
  • Mutation check: remove the lock step, and the integration test must fail.
  • Commands:
    • bun run test:changed
    • cargo clippy -p nodespace-proto -p nodespace-daemon -p nodespace-cli -p nodespace-app --all-targets -- -D warnings -D clippy::unused-async
    • .tools/bin/cargo-nextest nextest run -p nodespace-daemon --test it single_instance::

Dependencies

Risks and rollback

  • Two dev daemons on one socket. A developer running dev daemons from two worktrees on the default dev socket now sees the second exit 0. Until now, the two fought over the socket.
  • Log noise from Homebrew. A brew services daemon that loses the lock is restarted on every throttle interval.
  • Network home directories. flock over NFS is best effort.
  • Rollback: revert the PR.

Plan key: C8.9 (pro-boundary DAG).

🤖 Generated with Claude Code

Activity

  1. self-assigned this
    on Sep 30, 2026
  2. added
    pro-boundary
    on Sep 30, 2026
  3. mstomar125 commented on Sep 30, 2026

    @mstomar125
    ContributorAuthor

    Completed in #3375 (merged). Auto-close did not fire; closing manually.

  4. mstomar125 commented on Sep 30, 2026

    @mstomar125
    ContributorAuthor

    Correction to the closing comment above: this issue was completed in #3388 (merged), not the PR named there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

pro-boundary

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions