Skip to content

fix(runtime): preserve local socket ownership - #9846

Merged
Audacity88 merged 5 commits into
zeroclaw-labs:masterfrom
JasonColapietro:fix/daemon-socket-ownership
Aug 13, 2026
Merged

Audacity88 merged 5 commits into
zeroclaw-labs:masterfrom
JasonColapietro:fix/daemon-socket-ownership

Conversation

@JasonColapietro

@JasonColapietro JasonColapietro commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Base branch: master
  • What changed and why:
    • Serialize the complete Unix local IPC endpoint lifecycle with a persistent sibling .lock file, acquired before stale inspection/probing/removal and held through EndpointGuard shutdown cleanup.
    • Validate the lock directory and opened lock inode before trusting the persistent lock, including ownership, sticky-directory, file-type, permissions, link-count, and post-lock identity checks.
    • Preserve the existing device/inode guard so shutdown removes only the socket path still owned by that listener, not a replacement endpoint.
    • Surface an initial socket AddrInUse as daemon startup failure so a second same-config daemon exits nonzero instead of being retried forever by the component supervisor.
    • Keep post-readiness socket failures under normal supervision, so runtime resilience behavior is unchanged after the daemon has successfully started.
  • Scope boundary: This does not change Windows named-pipe ownership behavior, desktop daemon discovery, config schema, gateway API shape, or RPC protocol behavior.
  • Blast radius: Unix local RPC listener startup/shutdown and daemon startup gating for the local socket component.
  • Linked issue(s): Fixes [Bug]: daemon steals daemon.sock on start and unlinks it on exit, stranding a live daemon #9840
  • Labels: bug, daemon, runtime, priority:p1, risk:high, size:L

Testing (required)

How you can test (when useful)

  • Reviewer testing requested? Yes
  • Interface(s) exercised: cli, local daemon transport
  • Setup / preconditions: Unix host with an isolated config directory and ZEROCLAW_SOCKET pointing at a temporary Unix socket path.
  • Steps to run: Start zeroclaw daemon --config-dir <tmp> --host 127.0.0.1 --port 0, start a second daemon with the same config/socket, confirm the second exits nonzero, then connect a client to the first daemon socket and call initialize then status.
  • Expected on this branch (after): The second daemon fails with endpoint ownership/address-in-use, while the first daemon remains reachable. A stale socket from a killed daemon is recovered on the next start, and graceful shutdown preserves a newer replacement socket.
  • Prior behavior on master (before): The second daemon could unlink/replace the first daemon's socket, and socket bind failures inside the socket component supervisor were logged and retried rather than failing initial daemon startup.

How I tested

  • CI checks relied on and why they cover this change: Required Quality Gate, Semgrep, and title checks passed on current head 6722a8f849.
  • Known CI coverage gap, if any: The real-process smoke covered macOS Unix sockets at 67914b2ca. The later lint-only change and fail-closed lock trust validation do not change the successful private-directory lifecycle it exercised; current-head focused tests cover the added private and sticky shared directory validation paths. Windows named pipes are intentionally unchanged and remain compile-covered by CI.
  • Commands run and tail output:
git diff --check
# clean

env RUSTC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustc" \
  RUSTDOC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustdoc" \
  "$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/cargo" fmt --all -- --check
# clean

env RUSTC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustc" \
  RUSTDOC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustdoc" \
  CARGO_BUILD_JOBS=2 \
  "$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/cargo" test -p zeroclaw-runtime --lib concurrent_stale_start_is_serialized_before_cleanup
# 1 passed; 0 failed

env RUSTC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustc" \
  RUSTDOC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustdoc" \
  CARGO_BUILD_JOBS=2 \
  "$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/cargo" test -p zeroclaw-runtime --lib endpoint_lock_is_held_through_guard_cleanup
# 1 passed; 0 failed

env CARGO_INCREMENTAL=0 \
  RUSTC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustc" \
  RUSTDOC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustdoc" \
  CARGO_BUILD_JOBS=2 \
  "$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/cargo" test -p zeroclaw-runtime --lib addr_in_use
# 3 passed; 0 failed

env CARGO_INCREMENTAL=0 \
  RUSTC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustc" \
  RUSTDOC="$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/rustdoc" \
  CARGO_BUILD_JOBS=2 \
  "$HOME/.rustup/toolchains/1.97.1-x86_64-apple-darwin/bin/cargo" build --bin zeroclaw --no-default-features --features agent-runtime,gateway
# Finished `dev` profile [unoptimized + debuginfo]
  • Beyond CI, what did you manually verify? At 67914b2ca, a real-process smoke against target/debug/zeroclaw used a temporary config directory and ZEROCLAW_SOCKET: the first daemon completed initialize and status; a duplicate daemon exited nonzero with endpoint ownership/address-in-use while the incumbent remained reachable; a killed incumbent left a stale socket that the successor recovered; graceful shutdown did not remove a newer replacement socket. This evidence is carried forward to the current head for the reasons above.
  • Additional current-head coverage: Focused tests reject permissive, FIFO, and symlink lock entries; reject a swappable non-sticky directory; and accept a sticky shared directory while preserving endpoint service.
  • If any command was intentionally skipped, why: Full workspace tests and Clippy are left to hosted CI. Local focused tests and the real-process smoke target the reviewed race, lock trust boundary, and daemon-startup behavior directly.

Security & Privacy Impact (required)

  • New permissions, capabilities, or file system access scope? Yes
  • New external network calls? No
  • Secrets / tokens / credentials handling changed? No
  • PII, real identities, or personal data in diff, tests, fixtures, or docs? No
  • Prompt injection or untrusted model-visible text introduced/changed? No
  • If any Yes, describe the risk and mitigation: Unix local IPC startup creates and retains a persistent sibling <socket>.lock file. The immediate parent must be owned by the daemon user or root; group/other-writable parents require the sticky bit. The opened lock must be a regular owner-only file owned by the daemon user, remain linked, and still match the locked device/inode after the directory-entry recheck. The file is intentionally not unlinked so all daemon processes contend on the same lock inode; the kernel releases the advisory lock when the owner process exits or drops the guard. Sticky shared directories preserve integrity but cannot guarantee availability when another local user pre-creates the socket or lock name, so an owner-private socket directory is recommended for reliable startup.

Compatibility (required)

  • Backward compatible? Yes
  • Config / env / CLI surface changed? No
  • Rust/MSRV/toolchain floor changed? No
  • If backward compatibility is No or either surface/floor question is Yes: N/A

Rollback (required for medium/high-risk PRs)

  • Fast rollback command/path: Revert the eventual squash commit. No migration or persisted-state conversion is involved.
  • Feature flags or config toggles: None.
  • Observable failure symptoms: A second daemon starts successfully against a live socket, startup cannot recover a genuinely stale socket, daemon startup hangs/retries forever on initial socket ownership conflict, an unsafe lock location is accepted, or shutdown removes a socket whose device/inode differs from the listener's captured identity.

@github-actions github-actions Bot added the runtime Auto scope: src/runtime/** changed. label Aug 8, 2026
@JasonColapietro
JasonColapietro marked this pull request as ready for review August 8, 2026 07:59
@JasonColapietro

Copy link
Copy Markdown
Contributor Author

Focused socket ownership tests pass and this is ready for review. 😎

@Audacity88 Audacity88 added bug Something isn't working risk:high Trust, credential, compatibility, governance, release-authority, or security boundary. size:S Auto size: 81-250 non-doc changed lines. labels Aug 9, 2026
@Audacity88 Audacity88 added this to the v0.8.5 milestone Aug 9, 2026

@Audacity88 Audacity88 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@JasonColapietro, thanks for taking on #9840. I reviewed the focused Unix socket-ownership fix at 8573a132.

The one-file scope is appropriate. Required CI is green, and I checked the diff, linked issue, focused tests, and process-boundary evidence.

The sequential case is improved, but a concurrent stale-start race can still reproduce the core failure, so this needs one more repair.

🟢 What looks good — Sequential ownership behavior is well covered

The live-incumbent probe fails closed instead of unlinking a serving endpoint, and unexpected probe errors propagate. The focused tests use real Unix sockets to cover sequential incumbent rejection, stale recovery, owned cleanup, and replacement preservation. Windows behavior remains unchanged and compile-covered.

🔴 Blocking — Make stale cleanup and rebinding race-safe

The liveness probe protects an already-serving socket, but remove_stale still separates its second inode check from remove_file(path).

Two same-user daemons starting concurrently over one stale socket can both observe and recheck the same stale inode. Daemon A can then unlink it and bind a live replacement before daemon B's already-authorized pathname removal runs. B can consequently unlink A's new endpoint and bind over it, leaving A alive but unreachable—the central failure this PR is intended to eliminate. Directory permissions do not serialize same-user daemons.

Please make cleanup authority race-safe through stale inspection, unlink, and bind. A lifecycle lock is one possible approach, but any equivalent design is fine.

Please also add a deterministic regression for the concurrent stale-start interleaving. EndpointGuard::drop has the same narrower check-then-unlink limitation when a replacement is installed between those operations, so the shutdown ownership guarantee should use the same race-safe model.

🟡 Warning — Provide real process-boundary evidence before approval

The current tests use real Unix sockets and provide good component coverage, but both listeners run inside one process and shutdown uses an internal cancellation token.

After the race is fixed, please report an isolated Unix smoke tied to the tested commit showing:

  • Two real zeroclaw daemon processes sharing one temporary config directory cause the second process to exit nonzero while the first still completes initialize and status.
  • A genuinely stale socket is recovered.
  • Normal process termination preserves a replacement endpoint.

The pending smoke is not why this review requests changes; the race above is.

@Audacity88 Audacity88 added the needs-author-action Author response needed before review or merge can continue; not a stale warning. label Aug 9, 2026
@JasonColapietro

Copy link
Copy Markdown
Contributor Author

Updated this PR to address the socket ownership review comments.

Changes since the prior head:

  • Added a persistent sibling <socket>.lock file on Unix and hold its advisory lock across stale cleanup, bind, and EndpointGuard shutdown cleanup.
  • Kept the existing device/inode guard so shutdown preserves a replacement socket.
  • Made initial socket AddrInUse fatal to daemon startup so a duplicate same-config daemon exits nonzero instead of retrying forever under supervision.
  • Kept post-readiness socket failures under normal supervision.

Fresh verification:

  • cargo fmt --all -- --check
  • git diff --check
  • cargo test -p zeroclaw-runtime --lib concurrent_stale_start_is_serialized_before_cleanup
  • cargo test -p zeroclaw-runtime --lib endpoint_lock_is_held_through_guard_cleanup
  • cargo test -p zeroclaw-runtime --lib addr_in_use
  • Real-process smoke against target/debug/zeroclaw: duplicate daemon exits nonzero, stale socket recovers after killed daemon, replacement socket survives graceful shutdown.

Two independent read-only QA passes found no blocking findings. Hosted CI is now running on head 67914b2ca.

@github-actions github-actions Bot added the daemon Auto scope: src/daemon/** changed. label Aug 10, 2026
@JasonColapietro

Copy link
Copy Markdown
Contributor Author

Pushed the hosted lint fix in b03d671bc: changed the daemon startup error health update from &format!(...) to format!(...) to satisfy Clippy needless_borrows_for_generic_args. Local verification passed: git diff --check, cargo fmt --all -- --check, and cargo clippy -p zeroclaw-runtime --lib -- -D warnings under Rust 1.97.1. Fresh CI is running on the new head.

@Audacity88 Audacity88 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@JasonColapietro, thank you for the substantial repair. The current head now serializes stale cleanup, bind, and shutdown cleanup, and it makes an initial ownership conflict fail daemon startup instead of disappearing into supervisor retries.

I rereviewed the complete diff at b03d671bc, my prior blocker, issue #9840, the local RPC transport contract, the new startup-state path, the focused tests, the reported process smoke, and current required CI.

The original race is resolved. One trust-boundary issue remains in the new persistent lock file, so I cannot approve this head yet.

✅ Resolved — The endpoint lifecycle is serialized

EndpointLock is acquired before stale inspection and retained inside EndpointGuard through identity-checked shutdown cleanup. That closes both parts of my prior blocker: concurrent stale startups cannot enter cleanup together, and a listener cannot drop the lock before deciding whether it still owns the socket path. The deterministic lock-lifetime tests cover those transitions.

🟢 What looks good — Startup failure and supervision are separated correctly

The socket startup tracker treats AddrInUse as fatal only while startup is pending. Once the listener reports ready, later failures remain under the existing supervisor retry behavior. The focused tests cover both states, and the real-process smoke reported on 67914b2ca remains applicable because the only later change was the lint-only borrow cleanup in b03d671bc.

🔴 Blocking — Make the persistent lock inode trustworthy

The documented ZEROCLAW_SOCKET=/tmp/... override means the sibling lock can live in a shared directory. prepare_parent ignores failure to make that directory owner-only, while EndpointLock::acquire accepts an existing entry without verifying its owner, file type, permissions, link state, or whether the directory entry can be replaced. O_NOFOLLOW protects only the final symlink lookup, and .mode(0o600) applies only when this call creates a new file.

This can defeat the lock's central guarantee. A foreign-owned writable lock entry can be opened and locked by the daemon, then unlinked and recreated by its owner while the daemon still holds the old inode. A second daemon can acquire the replacement inode and enter stale cleanup and bind concurrently, recreating the split-ownership race this PR is meant to close. A permissive pre-existing lock can also be held by another local user to block daemon startup.

Please make lock acquisition fail closed unless the opened inode and its containing directory provide stable, current-user ownership. The exact design is up to you: an owner-private lock location is the simplest model, while a sibling design needs equivalent owner, regular-file, permission, and replacement protections for existing entries. Please add focused coverage for a pre-existing unsafe lock entry and for the supported external socket-path case.

@Audacity88 Audacity88 added the priority:p1 High priority label Aug 11, 2026
The documented ZEROCLAW_SOCKET override can place the sibling lifecycle
lock in a shared directory, where a foreign or permissive entry defeats
the lock's guarantee: another local user could hold it to block startup,
or swap the entry so two daemons lock different inodes and re-enter the
split-ownership race.

Acquisition now fails closed unless the lock's directory entry and inode
provide stable, current-user ownership:

- The containing directory must be owned by the daemon user or root and
  must not be group/other-writable unless the sticky bit restricts entry
  replacement to owners, which keeps /tmp-style external socket paths
  supported.
- The opened inode must be a regular file owned by the current user with
  no group/other access and still linked, so pre-existing unsafe entries
  are rejected instead of silently locked.
- After the advisory lock is taken, the directory entry must still name
  the locked inode, closing the open-to-lock replacement window.

prepare_parent's owner-only chmod remains best-effort and is documented
as hardening only; the acquire-time checks are what decide whether the
directory is safe to hold the lock.
@JasonColapietro

Copy link
Copy Markdown
Contributor Author

Thanks for the precise threat model — agreed the sibling lock was trusting whatever inode sat at the path. 6722a8f84 makes acquisition fail closed along the lines you outlined, keeping the sibling design and the persistent-inode semantics:

Directory gate (require_trusted_lock_dir, checked before open): the containing directory must be owned by the daemon user or root, and must not be group/other-writable unless the sticky bit is set. Sticky is what makes the documented ZEROCLAW_SOCKET=/tmp/... case sound: in a sticky directory only the entry owner can unlink or rename the entry, so a foreign user can neither swap our lock inode nor pre-seat a replaceable one. A group/other-writable directory without sticky is rejected outright.

Inode gate (require_trusted_lock_file, fstat on the opened fd): regular file only (a FIFO or device no longer passes O_NOFOLLOW's narrow protection), owned by the current euid, no group/other permission bits, and still linked. This is the fail-closed answer to the pre-existing unsafe entry: a foreign-owned or permissive lock is an error with remediation in the message, never something we lock.

Swap gate: after try_lock succeeds, the directory entry is re-stat'ed and must still name the locked inode, closing the open→lock window. Together with the gates above this removes the unlink-and-recreate path: in a trusted directory only we can replace the entry, and we never unlink lock files.

prepare_parent's owner-only chmod stays best-effort but is now documented as hardening only — the acquire-time directory gate is what actually decides safety, so a failed chmod on /tmp no longer silently degrades anything.

New focused coverage (all passing alongside the existing lifecycle tests, 28/28 locally):

  • endpoint_lock_rejects_preexisting_permissive_entry — 0666 entry rejected; tightening it to 0600 restores acquisition without recreating the inode
  • endpoint_lock_rejects_non_regular_entry (FIFO) and endpoint_lock_rejects_symlinked_entry
  • endpoint_lock_rejects_swappable_directory — group-writable, non-sticky
  • endpoint_lock_supports_sticky_shared_directory — the /tmp shape (1777) binds and serves, covering the supported external socket-path case

@Audacity88 Audacity88 removed the needs-author-action Author response needed before review or merge can continue; not a stale warning. label Aug 13, 2026

@Audacity88 Audacity88 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@JasonColapietro, I re-reviewed the current head, including the lock trust checks added after the previous review.

I checked the complete diff, both prior findings, the linked issue, the focused current-head tests, the carried-forward process smoke, and current required CI.

The endpoint lifecycle and lock-integrity blockers are resolved. The shared-directory availability limitation below remains worth documenting, but it does not reopen the ownership race or block approval.

✅ Resolved — Serialize the complete endpoint lifecycle

The lifecycle lock is acquired before stale probing or removal and remains held through EndpointGuard cleanup. Concurrent stale starts therefore contend on one lock instead of independently authorizing pathname removal, while the socket device/inode check still prevents an old listener from deleting a replacement endpoint.

✅ Resolved — Make the persistent lock inode trustworthy

The current head validates the immediate parent, rejects writable non-sticky directories, opens the lock without following symlinks, requires a regular owner-only inode owned by the daemon user, and rechecks the directory entry's device/inode identity after locking. The added tests cover permissive entries, FIFOs, symlinks, swappable directories, and sticky shared directories.

🟢 What looks good — Separate startup failure from runtime supervision

An initial AddrInUse now fails daemon startup, so a duplicate daemon exits instead of retrying indefinitely. Failures after readiness remain under the existing supervisor behavior.

I did not run reviewer-local Cargo on this head. Required CI is green.

The real-process smoke from 67914b2ca carries forward because the next commit was lint-only and the current repair adds fail-closed lock validation without changing the successful private-directory lifecycle it exercised. Current-head tests separately exercise private and sticky shared directory startup paths. The smoke confirmed that the duplicate daemon exits nonzero, the incumbent remains reachable through initialize and status, stale sockets recover, and graceful shutdown preserves a replacement socket.

🟡 Warning — Shared sticky directories remain availability-sensitive

Fail-closed validation protects integrity, but a shared path such as /tmp cannot guarantee availability against another local user pre-creating the socket or sibling lock entry. Sticky-bit rules then prevent the daemon from removing that foreign-owned entry, so startup rejects the path. The socket pathname already had this availability limitation on master; the persistent sibling lock creates another name with the same limitation. Operators who need reliable local IPC startup should use an owner-private directory for ZEROCLAW_SOCKET.

Approved.

@Audacity88 Audacity88 added size:L Auto size: 501-1000 non-doc changed lines. and removed size:S Auto size: 81-250 non-doc changed lines. labels Aug 13, 2026
NiuBlibing added a commit to NiuBlibing/zeroclaw that referenced this pull request Aug 29, 2026
…signature

Master's tool-scoping change (zeroclaw-labs#9846 line of work) altered
`Agent::builder().tools()` from `Vec<Box<dyn Tool>>` to `ScopedToolRegistry`,
and `ResolvedIo::tools_registry` / `drive_step` correspondingly. The merge
resolved cleanly at the source level but left this branch's own regressions on
the old signature, so the lib built while the test target did not.

Migrated all nine call sites to `ScopedToolRegistry::from_raw_for_test(..)`,
matching how master converted its own tests. No assertion or behaviour changed
— this is a signature migration only.

Runtime suite 3,944 passed / 0 failed; fmt clean.
@JasonColapietro
JasonColapietro deleted the fix/daemon-socket-ownership branch September 28, 2026 03:10
belumume pushed a commit to belumume/zeroclaw that referenced this pull request Oct 9, 2026
- 8573a13 fix(runtime): preserve local socket ownership
- 67914b2 fix(runtime): serialize local socket ownership
- b03d671 fix(runtime): satisfy daemon error lint
- 6722a8f fix(runtime): fail closed on untrusted endpoint locks
- ae250ea Merge branch 'master' into fix/daemon-socket-ownership
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working daemon Auto scope: src/daemon/** changed. priority:p1 High priority risk:high Trust, credential, compatibility, governance, release-authority, or security boundary. runtime Auto scope: src/runtime/** changed. size:L Auto size: 501-1000 non-doc changed lines.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: daemon steals daemon.sock on start and unlinks it on exit, stranding a live daemon

2 participants