Skip to content

fix(daemon): shut sessions down through live streams and drop the deprecated split halves - #354

Merged
sunerpy merged 4 commits into
mainfrom
fix/daemon-interprocess-shutdown
Nov 27, 2026
Merged

sunerpy merged 4 commits into
mainfrom
fix/daemon-interprocess-shutdown

Conversation

@sunerpy

@sunerpy sunerpy commented Nov 27, 2026

Copy link
Copy Markdown
Owner

Summary

  • Fix the control_shutdown flake: send the control frame: Os { code: 32, kind: BrokenPipe } at tests/control_shutdown.rs:117, or EOF while parsing a value on the reply. The session registry recorded each session's raw socket fd. The drain (close_all_sessions) and the dead-client sweep (shutdown_session) then called shutdown(SHUT_RDWR) on that number, sometimes after it already named another connection's socket. The registry now keeps a Weak handle to the session's stream and shuts the socket down through the upgraded, live handle.
  • Replace interprocess's Stream::split, RecvHalf and SendHalf, deprecated since 2.4.7, with one Arc-shared stream per connection, and bump the locked interprocess from 2.4.6 to 2.4.10. Both unsafe { BorrowedFd::borrow_raw(..) } calls in the daemon are gone.

This PR does not change the public API, the wire protocol, the graph, the goldens or the extraction version. Cargo.toml still requires interprocess = "2.4".

Why

A recorded fd number can outlive its socket in three windows:

  1. shutdown_session reads the number under the registry lock and calls shutdown after releasing it.
  2. A session's socket closes before its SessionGuard removes the entry. select! drops the branch futures before the function's locals, and an rmcp session's transport lives in a spawned task.
  3. close_all_sessions wakes every session and then immediately shuts the same sessions down, so the drain always races the sessions it just woke.

The control_shutdown tests run in parallel in one process and share one fd table. One test's drain can therefore shut down another test's fresh control connection right after that connection reads the daemon hello. In a real daemon the same race lets a sweep or a drain cut off an unrelated client. With the fix, the upgraded Arc is held across the syscall, so the socket cannot close and its number cannot be reused. A session that already dropped its stream no longer upgrades, and nothing is touched.

Changes

  • transport.rs: Shared<T>(Arc<T>) forwards Read/Write and AsyncRead/AsyncWrite to &T, the replacement interprocess documents for split. It also adds the unix helpers shutdown_write(&Stream) and shutdown_both(&AsyncStream), and drops the re-exports of the deprecated halves.
  • session.rs: the reader and the writer are two Shared clones. The registry entry stores a Weak<AsyncStream> (record_socket replaces set_recv_fd), and shutdown_session upgrades it after releasing the lock. shutdown_session is still a no-op on Windows.
  • proxy.rs: run_proxy keeps its own clone and half-closes the write direction through it, so WriteFd, write_raw_fd and their borrow_raw are deleted. This also removes a latent copy of the bug. If the daemon-to-host pump ended first, the old code half-closed a number that dropping the send half had already closed.
  • One behavior moves. tokio's write half sent SHUT_WR when it was dropped, and a dropped clone does not. Every session path that drops the writer returns without another await, so the socket still closes at the same point. The new test a_control_connection_reaches_eof_after_its_reply pins this.

Verification

All runs use tokio 1.53.3, the locked version. The stress harness pins the test binary and 8 busy loops (timeout --foreground 900 sh -c 'while :; do :; done') to 4 CPUs. No busy loop was left over after any run.

Red evidence

Deterministic regression tests, commit fa6fae5, whose library code is identical to 8166929. dup2 points the recorded number at another socket, the state a retired session leaves behind. cargo test -p codegraph-daemon --lib --locked -- reused_a_retired_sessions_fd:

running 2 tests
test session::tests::close_all_sessions_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd ... FAILED
test session::tests::shutdown_session_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd ... FAILED

failures:

---- session::tests::close_all_sessions_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd stdout ----

thread 'session::tests::close_all_sessions_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd' (3177527) panicked at crates/codegraph-daemon/src/session.rs:911:18:
a socket that reused a retired session's fd number must stay open: Os { code: 32, kind: BrokenPipe, message: "Broken pipe" }

---- session::tests::shutdown_session_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd stdout ----

thread 'session::tests::shutdown_session_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd' (3177528) panicked at crates/codegraph-daemon/src/session.rs:911:18:
a socket that reused a retired session's fd number must stay open: Os { code: 32, kind: BrokenPipe, message: "Broken pipe" }

test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 148 filtered out; finished in 0.00s

The fix commit rewrites both tests to the new API, because the old form records a raw fd through set_recv_fd, which no longer exists. The scenario and the assertions stay the same: a recorded stream is dropped, and another socket takes its number through fcntl_dupfd_cloexec. If the new code is changed back to "shut the recorded number down when the handle no longer upgrades", both tests fail with the same BrokenPipe.

The mechanism was traced with an uncommitted diagnostic patch on 8166929. The patch records /proc/self/fd/N at registration, compares it right before the syscall, and can pause to widen a window.

control_shutdown run Failing runs Diagnostic lines
20 ms pause before the check; churn test (refused frames in a loop while 20 drains run) 20/20 133 failed exchanges; 172 shutdowns on a number that named another socket, 208 on a closed number
20 ms pause before the check; the 4 existing tests 40/200 every failing run has a shutdown on a reused socket number
20 ms pause after the check; the 4 existing tests 70/200 1 stale line in total; in 66 of the 70 failing runs, the number named another socket right after the syscall
no pause, 28 min 4/25,838 (p_pre ≈ 1.5e-4) 2 of 4 come right after a shutdown on a reused number; the other 2 match the after-check row

All 4 natural failures carry the flake's signature, BrokenPipe at :117; three of them are in an_unauthorized_frame_is_refused_without_shutting_the_daemon_down.

Deprecation: with the 2.4.10 lockfile, main's sources fail cargo clippy -p codegraph-daemon --all-targets --locked -- -D warnings with 14 deprecated errors. The x86_64-pc-windows-msvc clippy run (cargo-xwin) fails with 9. These are the sites CI reported on #345.

Green

  • Same harness after the fix, with the diagnostic patch ported so the pause sits between upgrade() and the syscall. For each pause position, 0/20 churn runs and 0/200 suite runs failed. Natural runs: 0/19,379 (N = 3/p_pre, 23 min), with no stale or raced line.
  • cargo test -p codegraph-daemon --locked: green, including control_shutdown, rmcp_reap, async_model, the rewritten tests and two positive controls. The controls check that a live session's peer still reads EOF after the sweep and after the drain; disabling the shutdown makes them fail.
  • cargo test -p codegraph-rs --locked --test proxy_e2e --test daemon_sweep --test daemon_idle --test daemon_handover: green.
  • a_control_connection_reaches_eof_after_its_reply: 21/21 before the migration and 21/21 after. It fails when a stream clone is leaked on purpose.
  • cargo clippy -p codegraph-daemon -p codegraph-rs --all-targets --locked -- -D warnings is clean on 2.4.6 and on 2.4.10 (0 deprecated). cargo xwin clippy --target x86_64-pc-windows-msvc -p codegraph-daemon --all-targets --locked -- -D warnings is clean on both, and so is cargo fmt --all --check.
  • The pre-push make pre-ci passed on d82e297.
  • Still to do before merge: CI Success on the exact head, and the macOS run (a throwaway workflow on branch perf/a2-macos-1, commit 73b99b1 = this head plus that workflow file; the result is posted as a comment and the branch is deleted afterwards).

Notes

  • Commits: test(daemon) is red on purpose, and refactor(daemon) leaves those two tests red; fix(daemon) turns them green. A squash merge leaves one commit on main.
  • Lockfile: cargo update -p interprocess --precise 2.4.10 also rewrote 12 windows-sys dependency edges of unrelated packages. A no-op cargo update -p interprocess --precise 2.4.6 rewrites the same 12, so they come from cargo 1.98 re-resolving the lockfile, not from the bump. Only the interprocess entry (version and checksum) is kept, and cargo metadata --locked accepts it.
  • Windows: named pipes have no half-close, so shutdown_session stays a no-op there. The shared stream closes the way the old split did, because both halves already shared one RawPipeStream.
  • tokio 1.54.1, which changes UnixStream::shutdown, is not part of this PR. Rerun the harness when it lands.

…umber

Add two unix unit tests to the session registry for the control_shutdown
BrokenPipe flake. Each registers a session socket, then uses dup2 to close
that socket and hand its descriptor number to another connection in one
atomic step, which is the state a session is in after its socket closed
and before its guard removed the registry entry. The drain
(close_all_sessions) and the dead-client sweep (shutdown_session) must
leave the other connection open: it must still write, and its peer must
read the byte.

Both tests fail on the current registry, which records a raw fd and
shuts that number down: the other connection's write returns
Os { code: 32, kind: BrokenPipe }, the error the flaky control test
reported. This commit is red on purpose; the fix follows in this branch.

Verified with env -u RUSTUP_TOOLCHAIN cargo test -p codegraph-daemon
--lib --locked -- reused_a_retired_sessions_fd (2 failed, both
BrokenPipe), and clippy -D warnings plus cargo fmt --check are clean.
interprocess 2.4.7 deprecated Stream::split and the RecvHalf/SendHalf
types in favour of sharing one stream: &Stream implements Read/Write
(AsyncRead/AsyncWrite for the tokio stream), so clones of one Arc can
read and write at once. The locked version is still 2.4.6; this change
removes every use of the deprecated API so the bump compiles warning-free.

- transport: add Shared<T>, an Arc newtype that forwards Read/Write and
  AsyncRead/AsyncWrite to &T, and a unix shutdown_write helper; drop the
  SendHalf and async RecvHalf/SendHalf re-exports.
- session: the session's reader and writer are two Shared clones. The
  registry still records the socket's raw fd, read from the shared
  stream, so the sweep and drain behave exactly as before; their fix
  follows separately.
- proxy: run_proxy keeps its own clone and half-closes the write
  direction through it, so WriteFd, write_raw_fd and their unsafe
  borrow_raw are gone. Holding the clone keeps the socket open until the
  half-close; the old code could reach a closed or reused number if the
  daemon-to-host pump ended first.

One behaviour moves: tokio's write half sent SHUT_WR when it dropped,
and a dropped clone does not. Every session path that drops the writer
returns without awaiting again, so the socket still closes at the same
point. The new test a_control_connection_reaches_eof_after_its_reply
pins that: a client reads EOF after the daemon answers its control
frame. It passed 21/21 before this change and 21/21 after, and it fails
(WouldBlock after the 10 s read timeout) when a clone is leaked on
purpose.

Verified on interprocess 2.4.6: cargo clippy -p codegraph-daemon -p
codegraph-rs --all-targets --locked -- -D warnings; cargo xwin clippy
--target x86_64-pc-windows-msvc -p codegraph-daemon --all-targets;
cargo test -p codegraph-daemon (all green except the two reused-fd
tests from the previous commit, still red by design); codegraph-rs
proxy_e2e, daemon_sweep, daemon_idle and daemon_handover.
The session registry recorded each session's raw socket fd, and the drain
(close_all_sessions) and the dead-client sweep (shutdown_session) called
shutdown(SHUT_RDWR) on that number. The number can outlive the socket:
the session's stream closes before its guard removes the entry, and
shutdown_session reads the number under the lock but calls shutdown
outside it. In either window another connection can take the number, and
the shutdown then lands on that connection. That is the control_shutdown
flake: a drain in one test closes the next test's fresh control
connection, which reports BrokenPipe on its write or EOF on its reply. In
production the same race can cut off another client's session.

The registry now stores a Weak handle to the session's Shared stream.
shutdown_session upgrades it outside the lock and shuts the socket down
through the live handle. A session that already dropped its stream no
longer upgrades, so nothing is touched; while the upgraded handle is
held the socket cannot close, so its number cannot be reused. The Weak
never keeps a socket open. The last unsafe borrow_raw in the daemon goes
with the raw fd, and Windows keeps its no-op shutdown_session.

Tests: the two reused-fd tests from the previous commit now build the
state on the new API (a real Shared stream is recorded and dropped, and
another socket takes its number through fcntl_dupfd_cloexec, retried up
to 20 times if another thread takes the number first) and pass. Two new
positive controls check that shutting a live session down still makes
its peer read EOF, through the sweep and through the drain. Mutation
checks: restoring "shut the recorded number down" makes the reused-fd
tests fail with BrokenPipe, and disabling the shutdown makes the EOF
controls fail. The full lib suite passed 30 of 30 repeats.

Verified on interprocess 2.4.6 and tokio 1.53.3: cargo test -p
codegraph-daemon --locked (all green), codegraph-rs proxy_e2e,
daemon_sweep, daemon_idle and daemon_handover, cargo clippy -p
codegraph-daemon -p codegraph-rs --all-targets -D warnings, and cargo
xwin clippy for x86_64-pc-windows-msvc.
Move the locked interprocess from 2.4.6 to 2.4.10; the Cargo.toml
requirement stays "2.4". The lockfile change is the version and the
checksum, and the dependency list is unchanged. 2.4.7 deprecated the
split halves, which the previous commits stopped using; on the sources
of 8166929 this lockfile fails clippy -D warnings with 14 deprecated
errors on Linux and 9 on x86_64-pc-windows-msvc, the same sites CI
reported on #345.

cargo update -p interprocess --precise 2.4.10 also rewrote 12
windows-sys dependency edges of unrelated packages. A no-op
cargo update -p interprocess --precise 2.4.6 rewrites the same edges, so
they come from cargo 1.98 re-resolving this lockfile rather than from
the bump; only the interprocess entry is kept. cargo metadata --locked
accepts the result, and cargo tree --locked -i interprocess shows 2.4.10.

Verified: cargo clippy -p codegraph-daemon -p codegraph-rs --all-targets
--locked -- -D warnings and cargo xwin clippy --target
x86_64-pc-windows-msvc -p codegraph-daemon --all-targets report no
warnings (0 deprecated); cargo test -p codegraph-daemon --locked and
codegraph-rs proxy_e2e, daemon_sweep, daemon_idle and daemon_handover
pass.
@codecov

codecov Bot commented Nov 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.38554% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/codegraph-daemon/src/transport.rs 92.45% 4 Missing ⚠️
crates/codegraph-daemon/src/session.rs 98.13% 2 Missing ⚠️

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #354      +/-   ##
==========================================
- Coverage   96.40%   96.40%   -0.01%     
==========================================
  Files         368      368              
  Lines      254382   254517     +135     
==========================================
+ Hits       245229   245357     +128     
- Misses       9153     9160       +7     
Files with missing lines Coverage Δ
crates/codegraph-daemon/src/proxy.rs 96.82% <100.00%> (-0.05%) ⬇️
crates/codegraph-daemon/src/session.rs 97.46% <98.13%> (+0.06%) ⬆️
crates/codegraph-daemon/src/transport.rs 94.93% <92.45%> (-5.07%) ⬇️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sunerpy

sunerpy commented Nov 27, 2026

Copy link
Copy Markdown
Owner Author

macOS verification (owner decision OD-C7), on GitHub macos-15 runners through throwaway branches that are now deleted:

  • Red reproduced on macOS (run 45970123543, job 140408231891): at fa6fae5 both session::tests::*_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd fail with Os { code: 32, kind: BrokenPipe, message: "Broken pipe" }, the same as on Linux.
  • No new macOS failure (run 45972600093, job 140416417528): cargo test -p codegraph-daemon --locked --no-fail-fast was run at the base 8166929 and at this head d82e297 on the same runner, and the two failing sets are identical (7 tests). At this head the two reused-fd tests and a_control_connection_reaches_eof_after_its_reply pass.
  • The 7 failures exist before this PR and are environmental. These daemon tests had never run on macOS in CI:
    • paths::tests ×2: the in-root socket path under /var/folders/… is too long, and /var is /private/var;
    • spawn::tests ×4: they require /bin/true, which macOS lacks (it has /usr/bin/true);
    • control_shutdown::an_incomplete_drain_reply_is_unresponsive_and_never_signals_the_owner: its stub socket path exceeds sun_path.
  • The CLI daemon, proxy and handover tests (codegraph-rs --test proxy_e2e/daemon_sweep/daemon_idle/daemon_handover) cannot build on macOS at all. codegraph-bench calls libc::posix_fadvise, which macOS does not have. This also predates this PR. On Windows those tests ran in this PR's CI (Windows Tests, run 45966230039).

The macOS test portability issues are recorded for a separate change; they are not part of this patch.

@sunerpy
sunerpy merged commit 9ff6295 into main Nov 27, 2026
11 checks passed
@sunerpy
sunerpy deleted the fix/daemon-interprocess-shutdown branch November 27, 2026 09:32
@github-actions github-actions Bot mentioned this pull request Nov 27, 2026
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.

1 participant