From fa6fae5978c87f7b7b2b9db1e902990042c3268c Mon Sep 17 00:00:00 2001 From: sunerpy Date: Fri, 27 Nov 2026 15:10:59 +0800 Subject: [PATCH 1/4] test(daemon): pin that a session shutdown never reaches a reused fd number 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. --- crates/codegraph-daemon/src/session.rs | 79 ++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/crates/codegraph-daemon/src/session.rs b/crates/codegraph-daemon/src/session.rs index 1f0867b5..f1fa67f3 100644 --- a/crates/codegraph-daemon/src/session.rs +++ b/crates/codegraph-daemon/src/session.rs @@ -861,6 +861,85 @@ mod tests { let mut empty = BufReader::new(std::io::Cursor::new(Vec::::new())); assert!(read_first_line_bounded(&mut empty, 64).is_empty()); } + + /// The state behind the `control_shutdown` BrokenPipe flake: a registered + /// session whose socket closed before its guard dropped, and another + /// connection that took the descriptor number the registry recorded. + #[cfg(unix)] + struct ReusedSessionFd { + registry: SessionRegistry, + guard: SessionGuard, + /// The recorded number, which now names `other`'s socket. + _number: std::os::fd::OwnedFd, + other: std::os::unix::net::UnixStream, + other_peer: std::os::unix::net::UnixStream, + } + + #[cfg(unix)] + impl ReusedSessionFd { + fn new() -> Self { + use std::os::fd::{AsRawFd, OwnedFd}; + use std::os::unix::net::UnixStream; + + let registry = SessionRegistry::default(); + let guard = registry.start_session(); + let (session_socket, _session_peer) = UnixStream::pair().expect("session socket pair"); + registry.set_recv_fd(guard.session_id(), session_socket.as_raw_fd()); + // Close the session's socket and hand its number to another connection + // in one step: `dup2` replaces the file the number names atomically, so + // no other test thread can take the number in between. + let (other, other_peer) = UnixStream::pair().expect("other socket pair"); + let mut number: OwnedFd = session_socket.into(); + rustix::io::dup2(&other, &mut number) + .expect("point the recorded number at the other socket"); + Self { + registry, + guard, + _number: number, + other, + other_peer, + } + } + + /// The other connection is still open: it can write, and its peer reads + /// the byte it wrote. + fn assert_other_connection_still_open(&self) { + use std::io::{Read, Write}; + + (&self.other) + .write_all(b"x") + .expect("a socket that reused a retired session's fd number must stay open"); + self.other_peer + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound the peer read"); + let mut byte = [0u8; 1]; + (&self.other_peer) + .read_exact(&mut byte) + .expect("the byte written on the other connection arrives"); + assert_eq!(&byte, b"x"); + } + } + + /// The drain (`close_all_sessions`) must never shut down a socket that took a + /// retired session's fd number. On failure the other connection's write fails + /// with `BrokenPipe`, the error the flaky control test reported. + #[cfg(unix)] + #[test] + fn close_all_sessions_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd() { + let state = ReusedSessionFd::new(); + state.registry.close_all_sessions(); + state.assert_other_connection_still_open(); + } + + /// The dead-client sweep (`shutdown_session`) must never shut down a socket + /// that took a retired session's fd number either. + #[cfg(unix)] + #[test] + fn shutdown_session_never_shuts_down_a_socket_that_reused_a_retired_sessions_fd() { + let state = ReusedSessionFd::new(); + state.registry.shutdown_session(state.guard.session_id()); + state.assert_other_connection_still_open(); + } } #[cfg(all(test, unix))] From 3b87bb479e9730face1d7119ce5c854c9624da4f Mon Sep 17 00:00:00 2001 From: sunerpy Date: Fri, 27 Nov 2026 15:19:59 +0800 Subject: [PATCH 2/4] refactor(daemon): share local-socket streams instead of splitting them 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, 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. --- crates/codegraph-daemon/src/proxy.rs | 83 ++++--------- crates/codegraph-daemon/src/session.rs | 38 +++--- crates/codegraph-daemon/src/transport.rs | 116 ++++++++++++++++-- .../tests/control_shutdown.rs | 48 ++++++++ 4 files changed, 199 insertions(+), 86 deletions(-) diff --git a/crates/codegraph-daemon/src/proxy.rs b/crates/codegraph-daemon/src/proxy.rs index 328c516a..69243122 100644 --- a/crates/codegraph-daemon/src/proxy.rs +++ b/crates/codegraph-daemon/src/proxy.rs @@ -37,12 +37,11 @@ use std::thread; use std::time::Duration; use anyhow::{Context, Result}; -use interprocess::local_socket::traits::Stream as _; use serde_json::{Value, json}; use crate::process::{SupervisionState, current_ppid, is_process_alive, supervision_lost_reason}; use crate::session::read_daemon_hello; -use crate::transport::{Rendezvous, connect}; +use crate::transport::{Rendezvous, Shared, Stream, connect}; /// The wire protocol version the daemon advertises in its hello /// (`session.rs` `DaemonHello.protocol`). Proxy and daemon must agree. @@ -172,18 +171,19 @@ pub fn run_proxy( return Ok(mismatch); } - // Split into independent recv/send halves. interprocess's split hands BOTH - // halves a refcount over the SAME kernel object (an `Arc` on - // windows, an `Arc` over one fd on unix), so merely DROPPING the send half - // does not signal EOF to the daemon — the object stays open via the recv - // half. On unix we therefore capture the WRITE-side fd before moving `send` - // into the up pump and, once the host side is done, explicitly half-close it - // (shutdown(SHUT_WR)), which makes the daemon's session reader hit EOF, - // flush its last reply, and close. Windows named pipes have NO half-close, - // so teardown there cannot depend on the daemon closing first; the reply + // Share the stream between the two pumps (the replacement for + // interprocess's deprecated split): every clone refers to the SAME kernel + // object, so merely DROPPING the writer's clone does not signal EOF to the + // daemon — the object stays open while any clone lives. This function keeps + // its own clone and, once the host side is done, explicitly half-closes the + // write direction through it (shutdown(SHUT_WR) on unix), which makes the + // daemon's session reader hit EOF, flush its last reply, and close. Holding + // that clone also keeps the socket open until the half-close, so it always + // reaches this connection. Windows named pipes have NO half-close, so + // teardown there cannot depend on the daemon closing first; the reply // ledger below is what bounds it on every platform. - let (recv, mut send) = stream.split(); - let write_fd = write_raw_fd(&send); + let stream = Shared::new(stream); + let mut send = stream.clone(); // Send the OPTIONAL client-hello FIRST (T9), before any JSON-RPC: it // announces the host pid this proxy serves so the daemon can reap our @@ -218,7 +218,7 @@ pub fn run_proxy( // daemon -> host pump (own thread): forward every daemon line to the host, // except the suppressed-initialize reply. - let socket_reader = BufReader::new(recv); + let socket_reader = BufReader::new(stream.clone()); let down_suppressed = Arc::clone(&suppressed_id); let down_out = Arc::clone(&host_out); let down_ledger = Arc::clone(&ledger); @@ -244,11 +244,11 @@ pub fn run_proxy( // flushes its final reply, and closes, so the down pump reaches EOF on its // own and `down.join()` returns. Windows named pipes have NO half-close // (`half_close_write` is a documented no-op there), so the daemon's session - // reader NEVER EOFs while our recv half keeps the pipe open — its rmcp serve + // reader NEVER EOFs while our reader's clone keeps the pipe open — its rmcp serve // loop parks on the next frame, the pipe is never closed, and the down pump // therefore never returns. Joining it unconditionally is an UNBOUNDED wait on // windows; it is what made this function never return there. - half_close_write(write_fd); + half_close_write(&stream); let settled = ledger.wait_until_settled(REPLY_DRAIN_BUDGET); shutdown.store(true, Ordering::SeqCst); // Wake the watchdog at once so its join (in drop) returns promptly instead @@ -359,56 +359,21 @@ impl ReplyLedger { } } -/// The write-side fd handle carried between `write_raw_fd` and -/// `half_close_write`. On unix it is the real socket `RawFd`; on non-unix there -/// is no half-close and the value is always `None`, so a unit placeholder keeps -/// both cfg variants' signatures structurally identical for the cfg-agnostic -/// caller. NEVER name `std::os::fd::*` outside the `#[cfg(unix)]` path — that -/// module does not exist on Windows. -#[cfg(unix)] -type WriteFd = std::os::fd::RawFd; -#[cfg(not(unix))] -type WriteFd = (); - -/// Capture the write-side raw fd from the send half before it is moved into the -/// up pump. `None` on non-unix (no half-close there). -#[cfg(unix)] -fn write_raw_fd(send: &crate::transport::SendHalf) -> Option { - use std::os::fd::{AsFd, AsRawFd}; - // The enum `SendHalf` does not surface `AsFd`/`AsRawFd`; the concrete - // `UdSocket` variant does. Match it to read the raw fd. - match send { - interprocess::local_socket::SendHalf::UdSocket(uds) => Some(uds.as_fd().as_raw_fd()), - #[allow(unreachable_patterns)] - _ => None, - } -} - -#[cfg(not(unix))] -fn write_raw_fd(_send: &crate::transport::SendHalf) -> Option { - None -} - /// Half-close the WRITE direction of the daemon socket (`shutdown(SHUT_WR)`), /// leaving the read direction open to drain the daemon's final reply. This is -/// the EOF signal the daemon's blocking line-reader needs; a plain drop of the -/// send half is insufficient because interprocess shares one fd across halves. +/// the EOF signal the daemon's blocking line-reader needs; dropping the writer's +/// clone is insufficient because the socket stays open while any clone lives. +/// `stream` is a live clone, so the shutdown cannot reach a closed or reused +/// descriptor. #[cfg(unix)] -fn half_close_write(write_fd: Option) { - use std::os::fd::BorrowedFd; - if let Some(fd) = write_fd { - // SAFETY: `fd` is the live socket fd captured at split time; the recv - // half still owns the socket, so the fd is valid for this borrow. We - // only issue shutdown(SHUT_WR) on it — no ownership is taken. - let borrowed = unsafe { BorrowedFd::borrow_raw(fd) }; - let _ = rustix::net::shutdown(borrowed, rustix::net::Shutdown::Write); - } +fn half_close_write(stream: &Shared) { + let _ = crate::transport::shutdown_write(stream); } /// Windows named pipes have no half-close; the proxy relies on the full-stream /// drop + the daemon's own idle/sweep lifecycle instead. #[cfg(not(unix))] -fn half_close_write(_write_fd: Option) {} +fn half_close_write(_stream: &Shared) {} /// host -> daemon: read host_in line-by-line; answer `initialize`, and an /// `initialize`-lifecycle `tools/list`, locally, and forward everything else. @@ -1143,7 +1108,7 @@ mod tests { /// The teardown wait must be released by the LEDGER, not by the daemon /// closing its end: a windows named pipe has no half-close, so the daemon - /// never EOFs while the proxy's recv half holds the pipe open. Waiting on the + /// never EOFs while the proxy's reader holds the pipe open. Waiting on the /// ledger settles on the last reply DELIVERED, which happens on every /// platform. #[test] diff --git a/crates/codegraph-daemon/src/session.rs b/crates/codegraph-daemon/src/session.rs index f1fa67f3..e5eb4b6a 100644 --- a/crates/codegraph-daemon/src/session.rs +++ b/crates/codegraph-daemon/src/session.rs @@ -8,13 +8,12 @@ use std::time::Instant; use anyhow::Result; #[cfg(unix)] use interprocess::local_socket::traits::Stream as _; -use interprocess::local_socket::traits::tokio::Stream as _; use serde::{Deserialize, Serialize}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tracing::debug; use crate::control::{ControlAck, ControlFrame, encode_control_line, parse_control_frame}; -use crate::transport::{AsyncStream, Stream}; +use crate::transport::{AsyncStream, Shared, Stream}; /// Max milliseconds the PROXY waits for the daemon's one-line versioned hello /// after connecting, before giving up so the caller falls back to direct @@ -368,13 +367,13 @@ pub struct DaemonHello<'a> { /// parse recorded BEFORE serving, force-close reap via the recorded recv fd /// (unix), and no lost/duplicated bytes at the hello seam. /// -/// The recv half is split with interprocess's OWN async split (not -/// `tokio::io::split`) so its unix `AsFd` raw fd can be recorded for the -/// pid-sweep force-close; the (hello-consumed) recv remainder is re-chained via -/// [`tokio::io::AsyncReadExt::chain`] and joined with the send half into one -/// async transport handed to the standard rmcp serve. On non-unix the recv fd is -/// not recorded (no `SHUT_RDWR`), so the half-dead-peer force-close reap is -/// unix-only; ordinary disconnects still reap via async EOF everywhere. +/// The reader and the writer are two clones of one [`Shared`] stream (the +/// replacement for interprocess's deprecated split). On unix the socket's raw +/// fd is recorded for the pid-sweep force-close; the (hello-consumed) reader is +/// re-chained via [`tokio::io::AsyncReadExt::chain`] and joined with the writer +/// into one async transport handed to the standard rmcp serve. On non-unix the +/// fd is not recorded (no `SHUT_RDWR`), so the half-dead-peer force-close reap +/// is unix-only; ordinary disconnects still reap via async EOF everywhere. pub(crate) async fn serve_session_async( stream: AsyncStream, project_root: PathBuf, @@ -387,17 +386,16 @@ pub(crate) async fn serve_session_async( let guard = registry.start_session(); let session_id = guard.session_id(); - let (recv, mut send) = stream.split(); - + let stream = Shared::new(stream); #[cfg(unix)] { - use interprocess::local_socket::tokio::RecvHalf; use std::os::fd::{AsFd, AsRawFd}; - #[allow(irrefutable_let_patterns)] - if let RecvHalf::UdSocket(uds) = &recv { - registry.set_recv_fd(session_id, uds.as_fd().as_raw_fd()); - } + // `UdSocket` is the only variant on unix. + let AsyncStream::UdSocket(uds) = &*stream; + registry.set_recv_fd(session_id, uds.as_fd().as_raw_fd()); } + let mut send = stream.clone(); + let recv = stream; let version = hello_version(); let hello = DaemonHello { @@ -483,7 +481,7 @@ pub(crate) async fn serve_session_async( /// authorized frame hands the request to the accept loop, waits for the loop's /// post-drain signal, writes the ACK, and reports completion. async fn serve_control_frame( - mut send: crate::transport::AsyncSendHalf, + mut send: Shared, frame: &ControlFrame, control: Option<&ControlHandle>, ) -> Result<()> { @@ -536,12 +534,12 @@ fn refusal_line(frame: &ControlFrame) -> String { /// Async analog of [`read_first_line_bounded`]: read from `recv` up to and /// including the first `\n`, or `max` bytes, whichever comes first. Returns the -/// raw bytes read plus the (unconsumed) recv half so the caller can chain the +/// raw bytes read plus the (unconsumed) reader so the caller can chain the /// put-back bytes in front of it. One-byte reads consume EXACTLY the first line. async fn read_first_line_bounded_async( - mut recv: crate::transport::AsyncRecvHalf, + mut recv: Shared, max: usize, -) -> (Vec, crate::transport::AsyncRecvHalf) { +) -> (Vec, Shared) { let mut buf = Vec::with_capacity(64); let mut byte = [0u8; 1]; while buf.len() < max { diff --git a/crates/codegraph-daemon/src/transport.rs b/crates/codegraph-daemon/src/transport.rs index e46dd2d1..efb3e55d 100644 --- a/crates/codegraph-daemon/src/transport.rs +++ b/crates/codegraph-daemon/src/transport.rs @@ -9,6 +9,9 @@ use std::io; #[cfg(unix)] use std::path::Path; use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context, Poll}; #[cfg(all(test, unix))] use interprocess::local_socket::ListenerNonblockingMode; @@ -20,18 +23,117 @@ use interprocess::local_socket::traits::Stream as _; use interprocess::local_socket::{GenericFilePath, ToFsName}; #[cfg(windows)] use interprocess::local_socket::{GenericNamespaced, ToNsName}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; #[cfg(all(test, unix))] pub use interprocess::local_socket::Listener; -pub use interprocess::local_socket::{SendHalf, Stream}; +pub use interprocess::local_socket::Stream; /// Async (tokio) local-socket types for the daemon accept loop. `AsyncListener` -/// yields `AsyncStream`s whose split halves are `AsyncRead`/`AsyncWrite`, and on -/// unix expose `AsFd` for the force-close reap handle. -pub use interprocess::local_socket::tokio::{ - Listener as AsyncListener, RecvHalf as AsyncRecvHalf, SendHalf as AsyncSendHalf, - Stream as AsyncStream, -}; +/// yields `AsyncStream`s, which a session reads and writes through [`Shared`]. +pub use interprocess::local_socket::tokio::{Listener as AsyncListener, Stream as AsyncStream}; + +/// One local-socket stream shared by its reader and its writer. +/// +/// interprocess 2.4.7 deprecated `split` in favour of this shape: `&Stream` +/// implements the I/O traits in both directions (`Read`/`Write` for the sync +/// stream, `AsyncRead`/`AsyncWrite` for the tokio one), so clones of one `Arc` +/// can read and write at the same time. The socket closes when the last clone +/// drops, and dropping one clone never half-closes it; a caller that needs a +/// half-close issues it explicitly through a live clone. +#[derive(Debug)] +pub(crate) struct Shared(Arc); + +impl Shared { + pub(crate) fn new(inner: T) -> Self { + Self(Arc::new(inner)) + } +} + +impl Clone for Shared { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl std::ops::Deref for Shared { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl io::Read for Shared +where + for<'a> &'a T: io::Read, +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result { + (&*self.0).read(buf) + } +} + +impl io::Write for Shared +where + for<'a> &'a T: io::Write, +{ + fn write(&mut self, buf: &[u8]) -> io::Result { + (&*self.0).write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + (&*self.0).flush() + } +} + +impl AsyncRead for Shared +where + for<'a> &'a T: AsyncRead, +{ + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let mut inner: &T = &self.get_mut().0; + Pin::new(&mut inner).poll_read(cx, buf) + } +} + +impl AsyncWrite for Shared +where + for<'a> &'a T: AsyncWrite, +{ + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let mut inner: &T = &self.get_mut().0; + Pin::new(&mut inner).poll_write(cx, buf) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut inner: &T = &self.get_mut().0; + Pin::new(&mut inner).poll_flush(cx) + } + + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut inner: &T = &self.get_mut().0; + Pin::new(&mut inner).poll_shutdown(cx) + } +} + +/// Half-close the write direction of a sync local-socket stream: the peer's +/// reader sees EOF while this side can still read. Unix only; named pipes have +/// no half-close. +#[cfg(unix)] +pub(crate) fn shutdown_write(stream: &Stream) -> io::Result<()> { + // `UdSocket` is the only variant on unix, so this binding is irrefutable; a + // new variant fails to compile here instead of silently skipping the shutdown. + let Stream::UdSocket(uds) = stream; + rustix::net::shutdown(uds, rustix::net::Shutdown::Write).map_err(io::Error::from) +} /// Resolved rendezvous address for a project daemon. On unix `socket_path` is /// the `.sock` filesystem path; on windows it holds the BARE namespaced name diff --git a/crates/codegraph-daemon/tests/control_shutdown.rs b/crates/codegraph-daemon/tests/control_shutdown.rs index fcda4c57..035b40f5 100644 --- a/crates/codegraph-daemon/tests/control_shutdown.rs +++ b/crates/codegraph-daemon/tests/control_shutdown.rs @@ -205,6 +205,54 @@ fn an_unauthorized_frame_is_refused_without_shutting_the_daemon_down() { let _ = std::fs::remove_dir_all(&project); } +/// The daemon closes a control connection once it has replied: the client's +/// next read returns EOF (zero bytes) instead of timing out. This pins the close +/// after a refused frame, so a dropped writer that no longer half-closes the +/// socket, or a stray reference that keeps it open, fails here instead of +/// leaving clients waiting. +#[test] +fn a_control_connection_reaches_eof_after_its_reply() { + let project = temp_project("eof-after-reply"); + let paths = paths_of(&project); + let handle = start(&project, Duration::from_secs(10)); + let socket = handle.socket_path().to_path_buf(); + + let stream = connect(&socket); + stream + .set_recv_timeout(Some(WAIT)) + .expect("bound the control read"); + stream + .set_send_timeout(Some(WAIT)) + .expect("bound the control write"); + let mut reader = BufReader::new(&stream); + let mut hello = String::new(); + reader.read_line(&mut hello).expect("read the daemon hello"); + let refused = + ControlFrame::shutdown("0000000000000000000000000000000000000000000000000000000000000000"); + (&stream) + .write_all(format!("{}\n", serde_json::to_string(&refused).expect("frame json")).as_bytes()) + .expect("send the control frame"); + let mut ack = String::new(); + reader.read_line(&mut ack).expect("read the control reply"); + let ack: ControlAck = serde_json::from_str(ack.trim()).expect("decode the control reply"); + assert!(!ack.accepted(), "a foreign identity is refused: {ack:?}"); + + // A read that times out returns an error here, so this only passes on EOF. + let mut rest = Vec::new(); + reader + .read_to_end(&mut rest) + .expect("the answered control connection must reach EOF, not time out"); + assert!(rest.is_empty(), "nothing follows the reply: {rest:?}"); + drop(reader); + drop(stream); + + let ack = send_control_frame(&socket, &ControlFrame::shutdown(paths.project_identity())); + assert!(ack.accepted()); + wait_finished(&handle, "the drained daemon"); + handle.wait().expect("the accept loop joins cleanly"); + let _ = std::fs::remove_dir_all(&project); +} + #[test] fn an_exhausted_drain_budget_replies_incomplete_instead_of_success() { let project = temp_project("budget-exhausted"); From 4484ea8afed500aa32a06746246bef6908f6d333 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Fri, 27 Nov 2026 15:28:20 +0800 Subject: [PATCH 3/4] fix(daemon): shut sessions down through a live handle, not a stale fd 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. --- crates/codegraph-daemon/src/session.rs | 203 ++++++++++++++++------- crates/codegraph-daemon/src/transport.rs | 17 ++ 2 files changed, 159 insertions(+), 61 deletions(-) diff --git a/crates/codegraph-daemon/src/session.rs b/crates/codegraph-daemon/src/session.rs index e5eb4b6a..9592bdda 100644 --- a/crates/codegraph-daemon/src/session.rs +++ b/crates/codegraph-daemon/src/session.rs @@ -56,14 +56,18 @@ pub fn parse_client_hello_line(line: &str) -> Option { } /// A session's force-close handle. Dropping the [`SessionGuard`] removes the -/// session from the registry; the sweep additionally calls -/// [`SessionRegistry::shutdown_session`] to force the session thread (blocked in -/// the rmcp session serve loop) to EOF by half/full-closing its socket. +/// session from the registry; the sweep and the drain additionally call +/// [`SessionRegistry::shutdown_session`] to force the session task (blocked in +/// the rmcp session serve loop) to EOF by shutting its socket down. #[derive(Clone)] struct SessionEntry { pid: Option, + /// A weak handle to the session's socket, so the entry never keeps it open. + /// Once the session drops its stream the handle no longer upgrades, and a + /// later shutdown touches nothing, whichever connection now holds the + /// socket's old descriptor number. #[cfg(unix)] - recv_fd: Option, + socket: Option>, } /// Tracks live client sessions (each with an OPTIONAL host pid + a shutdown @@ -124,7 +128,7 @@ impl SessionRegistry { SessionEntry { pid: None, #[cfg(unix)] - recv_fd: None, + socket: None, }, ); bump_or_read(&self.last_active, true); @@ -147,17 +151,17 @@ impl SessionRegistry { } } - /// Record a session's recv-side socket fd so the sweep can force EOF by - /// shutting it down (unix only). + /// Record a weak handle to a session's socket so the sweep and the drain can + /// force EOF by shutting it down (unix only). #[cfg(unix)] - pub(crate) fn set_recv_fd(&self, session_id: u64, fd: std::os::fd::RawFd) { + pub(crate) fn record_socket(&self, session_id: u64, socket: &Shared) { if let Some(entry) = self .sessions .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .get_mut(&session_id) { - entry.recv_fd = Some(fd); + entry.socket = Some(socket.downgrade()); } } @@ -200,9 +204,9 @@ impl SessionRegistry { self.closing.send_replace(true); #[cfg(unix)] { - // Additionally force EOF on the recorded recv fds: a session blocked in - // a read that has not yet reached an await point observes the close - // immediately rather than at its next poll. + // Additionally shut down every recorded socket that is still open: a + // session blocked in a read that has not yet reached an await point + // observes the close immediately rather than at its next poll. let ids = self .sessions .lock() @@ -225,28 +229,26 @@ impl SessionRegistry { self.closing.subscribe() } - /// Force a dead session's reader to EOF by half-closing the read direction - /// of its socket. The session thread, blocked in the rmcp serve loop, then sees - /// EOF, returns, and drops its [`SessionGuard`] (which removes the entry + - /// bumps last-active). No-op when the fd is unknown or on non-unix. + /// Force a session's reader to EOF by shutting down both directions of its + /// socket. The session task, blocked in the rmcp serve loop, then sees EOF, + /// returns, and drops its [`SessionGuard`] (which removes the entry + bumps + /// last-active). No-op when no socket was recorded, when the session has + /// already dropped its stream, or on non-unix. pub(crate) fn shutdown_session(&self, session_id: u64) { #[cfg(unix)] { - let fd = self + let socket = self .sessions .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) .get(&session_id) - .and_then(|entry| entry.recv_fd); - if let Some(fd) = fd { - use std::os::fd::BorrowedFd; - // SAFETY: `fd` is the live recv socket fd recorded by the session - // thread, which owns the socket and outlives the sweep call (the - // session only drops AFTER its reader EOFs, which this shutdown - // triggers). We only issue shutdown(SHUT_RDWR); no ownership is - // taken and the fd is not closed here. - let borrowed = unsafe { BorrowedFd::borrow_raw(fd) }; - let _ = rustix::net::shutdown(borrowed, rustix::net::Shutdown::Both); + .and_then(|entry| entry.socket.clone()); + // A session that dropped its stream no longer upgrades, so nothing is + // touched even if its old descriptor number now names another + // connection. While `stream` is held the socket cannot close, so the + // shutdown reaches only this session's socket. + if let Some(stream) = socket.and_then(|weak| weak.upgrade()) { + let _ = crate::transport::shutdown_both(&stream); } } #[cfg(not(unix))] @@ -364,16 +366,17 @@ pub struct DaemonHello<'a> { /// Serve one async session over the daemon's tokio local-socket `stream` /// through the rmcp handler: daemon hello on accept, optional client-hello pid -/// parse recorded BEFORE serving, force-close reap via the recorded recv fd -/// (unix), and no lost/duplicated bytes at the hello seam. +/// parse recorded BEFORE serving, force-close reap via a recorded weak handle to +/// the socket (unix), and no lost/duplicated bytes at the hello seam. /// /// The reader and the writer are two clones of one [`Shared`] stream (the -/// replacement for interprocess's deprecated split). On unix the socket's raw -/// fd is recorded for the pid-sweep force-close; the (hello-consumed) reader is -/// re-chained via [`tokio::io::AsyncReadExt::chain`] and joined with the writer -/// into one async transport handed to the standard rmcp serve. On non-unix the -/// fd is not recorded (no `SHUT_RDWR`), so the half-dead-peer force-close reap -/// is unix-only; ordinary disconnects still reap via async EOF everywhere. +/// replacement for interprocess's deprecated split). On unix the registry keeps +/// a weak handle to it for the pid-sweep and drain force-close; the +/// (hello-consumed) reader is re-chained via [`tokio::io::AsyncReadExt::chain`] +/// and joined with the writer into one async transport handed to the standard +/// rmcp serve. On non-unix no handle is recorded (no `SHUT_RDWR`), so the +/// half-dead-peer force-close reap is unix-only; ordinary disconnects still reap +/// via async EOF everywhere. pub(crate) async fn serve_session_async( stream: AsyncStream, project_root: PathBuf, @@ -388,12 +391,7 @@ pub(crate) async fn serve_session_async( let stream = Shared::new(stream); #[cfg(unix)] - { - use std::os::fd::{AsFd, AsRawFd}; - // `UdSocket` is the only variant on unix. - let AsyncStream::UdSocket(uds) = &*stream; - registry.set_recv_fd(session_id, uds.as_fd().as_raw_fd()); - } + registry.record_socket(session_id, &stream); let mut send = stream.clone(); let recv = stream; @@ -860,14 +858,40 @@ mod tests { assert!(read_first_line_bounded(&mut empty, 64).is_empty()); } + /// A tokio local-socket stream over one end of a fresh socket pair, and the + /// pair's other end. Must run inside a tokio runtime. + #[cfg(unix)] + fn async_stream_pair() -> (Shared, std::os::unix::net::UnixStream) { + use std::os::fd::OwnedFd; + use std::os::unix::net::UnixStream; + + let (session_end, peer) = UnixStream::pair().expect("session socket pair"); + session_end + .set_nonblocking(true) + .expect("tokio needs a nonblocking socket"); + let stream = interprocess::os::unix::uds_local_socket::tokio::Stream::try_from( + OwnedFd::from(session_end), + ) + .expect("register the session socket with tokio"); + (Shared::new(AsyncStream::from(stream)), peer) + } + + #[cfg(unix)] + fn test_runtime() -> tokio::runtime::Runtime { + tokio::runtime::Builder::new_current_thread() + .enable_io() + .build() + .expect("test runtime") + } + /// The state behind the `control_shutdown` BrokenPipe flake: a registered /// session whose socket closed before its guard dropped, and another - /// connection that took the descriptor number the registry recorded. + /// connection that took the descriptor number the session's socket had. #[cfg(unix)] struct ReusedSessionFd { registry: SessionRegistry, guard: SessionGuard, - /// The recorded number, which now names `other`'s socket. + /// The session socket's old number, which now names `other`'s socket. _number: std::os::fd::OwnedFd, other: std::os::unix::net::UnixStream, other_peer: std::os::unix::net::UnixStream, @@ -876,27 +900,43 @@ mod tests { #[cfg(unix)] impl ReusedSessionFd { fn new() -> Self { - use std::os::fd::{AsRawFd, OwnedFd}; + use std::os::fd::{AsFd, AsRawFd}; use std::os::unix::net::UnixStream; - let registry = SessionRegistry::default(); - let guard = registry.start_session(); - let (session_socket, _session_peer) = UnixStream::pair().expect("session socket pair"); - registry.set_recv_fd(guard.session_id(), session_socket.as_raw_fd()); - // Close the session's socket and hand its number to another connection - // in one step: `dup2` replaces the file the number names atomically, so - // no other test thread can take the number in between. - let (other, other_peer) = UnixStream::pair().expect("other socket pair"); - let mut number: OwnedFd = session_socket.into(); - rustix::io::dup2(&other, &mut number) - .expect("point the recorded number at the other socket"); - Self { - registry, - guard, - _number: number, - other, - other_peer, + let runtime = test_runtime(); + // Dropping the session's stream frees its number, and the next + // descriptor any thread opens takes it. The other connection exists + // before that, so its own sockets cannot take the number; when another + // test thread wins it, the scenario is rebuilt, a bounded number of + // times. + for _ in 0..20 { + let registry = SessionRegistry::default(); + let guard = registry.start_session(); + let (other, other_peer) = UnixStream::pair().expect("other socket pair"); + let number = { + let _runtime = runtime.enter(); + let (stream, _peer) = async_stream_pair(); + registry.record_socket(guard.session_id(), &stream); + let AsyncStream::UdSocket(uds) = &*stream; + uds.as_fd().as_raw_fd() + // `stream` is the session's last clone: it drops here and + // closes the socket while `guard` keeps the registry entry. + }; + // The lowest free number at or above `number`: `number` itself + // unless another thread took it in between. + let reused = rustix::io::fcntl_dupfd_cloexec(&other, number) + .expect("duplicate the other socket"); + if reused.as_raw_fd() == number { + return Self { + registry, + guard, + _number: reused, + other, + other_peer, + }; + } } + panic!("in 20 attempts the retired session's fd number never went to the other socket"); } /// The other connection is still open: it can write, and its peer reads @@ -938,6 +978,47 @@ mod tests { state.registry.shutdown_session(state.guard.session_id()); state.assert_other_connection_still_open(); } + + /// The force-close still works: shutting down a session whose stream is + /// alive makes its peer read EOF. + #[cfg(unix)] + fn assert_a_live_session_shutdown_reaches_its_peer( + shut_down: impl FnOnce(&SessionRegistry, u64), + ) { + use std::io::Read; + + let runtime = test_runtime(); + let _runtime = runtime.enter(); + let registry = SessionRegistry::default(); + let guard = registry.start_session(); + let (stream, peer) = async_stream_pair(); + registry.record_socket(guard.session_id(), &stream); + shut_down(®istry, guard.session_id()); + peer.set_read_timeout(Some(std::time::Duration::from_secs(5))) + .expect("bound the peer read"); + let mut byte = [0u8; 1]; + let read = (&peer) + .read(&mut byte) + .expect("the peer of a shut-down session reads EOF, not a timeout"); + assert_eq!(read, 0, "the peer of a shut-down session reads EOF"); + drop((stream, guard)); + } + + #[cfg(unix)] + #[test] + fn shutdown_session_makes_a_live_sessions_peer_read_eof() { + assert_a_live_session_shutdown_reaches_its_peer(|registry, id| { + registry.shutdown_session(id); + }); + } + + #[cfg(unix)] + #[test] + fn close_all_sessions_makes_a_live_sessions_peer_read_eof() { + assert_a_live_session_shutdown_reaches_its_peer(|registry, _| { + registry.close_all_sessions(); + }); + } } #[cfg(all(test, unix))] diff --git a/crates/codegraph-daemon/src/transport.rs b/crates/codegraph-daemon/src/transport.rs index efb3e55d..6e15783b 100644 --- a/crates/codegraph-daemon/src/transport.rs +++ b/crates/codegraph-daemon/src/transport.rs @@ -48,6 +48,13 @@ impl Shared { pub(crate) fn new(inner: T) -> Self { Self(Arc::new(inner)) } + + /// A handle that does not keep the stream open: it upgrades only while + /// some clone still holds the stream. + #[cfg(unix)] + pub(crate) fn downgrade(&self) -> std::sync::Weak { + Arc::downgrade(&self.0) + } } impl Clone for Shared { @@ -135,6 +142,16 @@ pub(crate) fn shutdown_write(stream: &Stream) -> io::Result<()> { rustix::net::shutdown(uds, rustix::net::Shutdown::Write).map_err(io::Error::from) } +/// Shut down both directions of an async local-socket stream, so whoever reads +/// it, and its peer, see EOF. Unix only. The caller passes a live stream, so the +/// shutdown reaches that socket and no other. +#[cfg(unix)] +pub(crate) fn shutdown_both(stream: &AsyncStream) -> io::Result<()> { + // The only variant on unix; see `shutdown_write`. + let AsyncStream::UdSocket(uds) = stream; + rustix::net::shutdown(uds, rustix::net::Shutdown::Both).map_err(io::Error::from) +} + /// Resolved rendezvous address for a project daemon. On unix `socket_path` is /// the `.sock` filesystem path; on windows it holds the BARE namespaced name /// `codegraph-` (no `\\.\pipe\` prefix — `GenericNamespaced` adds it). From d82e2970f575e206f01eb2db97625062beb455a6 Mon Sep 17 00:00:00 2001 From: sunerpy Date: Fri, 27 Nov 2026 15:36:50 +0800 Subject: [PATCH 4/4] build(deps): bump interprocess to 2.4.10 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. --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 75ddfdb4..2c88f088 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1806,9 +1806,9 @@ dependencies = [ [[package]] name = "interprocess" -version = "2.4.6" +version = "2.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7529951166d4dd4d2a6b9f0bb97919b810623f75eeb76e81ee9e6644886cae37" +checksum = "a50ad48c57a73eb3e157c55c3bf6a35cbc9c57b4ebc177d24a92b02de884388d" dependencies = [ "doctest-file", "futures-core",