From d25463ad0ead296ed8c2a311c82ad86cc03bfc57 Mon Sep 17 00:00:00 2001 From: wan9chi Date: Mon, 30 Nov 2026 17:25:14 +0800 Subject: [PATCH] feat(fspy_shared): carry opaque abort payload in shm_io Extend shm_io with an atomic abort_slot descriptor, AbortSlotState (supporting 0-byte payloads without reserving payload space), wait-free ShmWriter::claim_abort / AbortFrameMut::finish with Release/Acquire synchronization (rule 4), and zero-copy AbortFrame returned on SealError::Aborted. Update shm_io's README (including the abort-path soundness argument) and add Miri-verified concurrent abort and abort/seal race tests that read the payload bytes before joining writer threads. Co-authored-by: Gemini 4 Neon --- crates/fspy_shared/src/ipc/channel/mod.rs | 12 +- .../src/ipc/channel/shm_io/README.md | 16 +- .../src/ipc/channel/shm_io/layout.rs | 119 +++++++++- .../fspy_shared/src/ipc/channel/shm_io/mod.rs | 205 +++++++++++++++++- .../src/ipc/channel/shm_io/reader.rs | 106 ++++++++- .../src/ipc/channel/shm_io/writer.rs | 130 ++++++++++- 6 files changed, 545 insertions(+), 43 deletions(-) diff --git a/crates/fspy_shared/src/ipc/channel/mod.rs b/crates/fspy_shared/src/ipc/channel/mod.rs index 362b357c8..d9f8bc289 100644 --- a/crates/fspy_shared/src/ipc/channel/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/mod.rs @@ -301,7 +301,9 @@ impl Sender

{ /// Must be called before performing the unrecorded operation. The receiver's /// close then fails with [`CloseError::Reported`]. pub fn report_loss(&self) { - self.writer.abort(); + if let Ok(frame) = self.writer.claim_abort(0) { + frame.finish(); + } } /// Serializes one record into a committed frame. @@ -506,7 +508,7 @@ impl Receiver { match sealed { Ok(inner) => Ok(RecordReader { inner, _protocol: PhantomData }), Err(SealError::Capacity) => Err(CloseError::Capacity), - Err(SealError::Aborted) => Err(CloseError::Reported), + Err(SealError::Aborted(_)) => Err(CloseError::Reported), Err(SealError::AlreadySealed) => { panic!("the unique receiver cannot have already sealed the channel") } @@ -560,7 +562,7 @@ mod tests { /// `Receiver::close`. #[test] fn a_capacity_too_small_for_the_table_fails_the_channel() { - // The counters alone need sixteen bytes, and the table needs eight + // The counters alone need twenty-four bytes, and the table needs eight // per slot on top. let Err(error) = channel::(8, Global) else { panic!("a region too small for the protocol made a channel"); @@ -639,9 +641,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn capacity_exhaustion_returns_capacity_close_error() { - // Descriptor table (512 MiB) + 16-byte counters + 4 bytes of payload + // Descriptor table (512 MiB) + 24-byte counters + 4 bytes of payload // room: fits two u16 records (4 bytes) and overflows on the third. - let receiver = channel::(SLOTS * 8 + 20, Global).unwrap(); + let receiver = channel::(SLOTS * 8 + 28, Global).unwrap(); let sender = receiver.conf().sender(Global).unwrap(); sender.send(&1); sender.send(&2); diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/README.md b/crates/fspy_shared/src/ipc/channel/shm_io/README.md index de6624e92..e134a7da4 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/README.md +++ b/crates/fspy_shared/src/ipc/channel/shm_io/README.md @@ -16,10 +16,11 @@ Any zero-initialized shared memory works. In practice it is a sparse file mapped | counters | descriptor table (one slot per frame) | payloads (the rest, grow up) | ``` -Two `AtomicU64` counters sit at the front, followed by one 8-byte descriptor slot per frame. +Three `AtomicU64` words sit at the front, followed by one 8-byte descriptor slot per frame. -- The **claim counter** counts frames ever claimed in bits 0..=60. Bits 61..=63 are three independent close gates: the receiver sets bit 63 (`GATE_SEALED`) when it seals, a claim that overflows capacity sets bit 62 (`GATE_OVERFLOW`), and a writer that explicitly aborts sets bit 61 (`GATE_ABORTED`). Setting any gate stops further claims and lets sealing distinguish a second seal, a capacity overflow, and a writer abort. -- The **payload counter** counts payload bytes ever reserved. +- The **claim counter** counts frames ever claimed in bits 0..=60. Bits 61..=63 are three independent close gates: the receiver sets bit 63 (`GATE_SEALED`) when it seals, a claim that overflows capacity sets bit 62 (`GATE_OVERFLOW`), and a writer that commits an abort payload sets bit 61 (`GATE_ABORTED`). Setting any gate stops further claims and lets sealing distinguish a second seal, a capacity overflow, and a writer abort. +- The **payload counter** counts payload bytes ever reserved (for both normal frames and abort payloads). +- The **abort slot** stores the descriptor of the first committed abort payload (or a dedicated sentinel for a 0-byte abort). A writer claims an abort payload with `claim_abort`, writes its opaque bytes, publishes the descriptor via CAS, and sets `GATE_ABORTED` with `Release`; `seal` reads `GATE_ABORTED` with `Acquire` and returns the committed bytes in `O(1)` time without scanning the descriptor table. The mapping's size and the number of slots are the whole geometry, and every process attaching to a region passes the slot count it was created with. Payloads take what the table leaves. Attaching checks one bound: the counters and the table fit, and what remains is small enough for the descriptors' 32-bit offsets. Splitting 4 GiB at one slot per 64 bytes, say, gives ~67 million slots and ~3.5 GiB of payload room, which is tens of millions of records of a few hundred bytes; payload space runs out first. @@ -50,9 +51,15 @@ Because every gate bit closes the channel, the first lost record or writer abort A single frame holds at most `u32::MAX` bytes, since a descriptor cannot describe more. Such a claim is refused and reported the same way. +## Aborting with a payload + +A writer that is about to perform an operation it cannot record calls `claim_abort(len)` to reserve an opaque payload span from the same payload bump allocator (zero-length aborts need no payload bytes and use a dedicated sentinel). Filling the span is exclusively owned; dropping `AbortFrameMut` before `finish()` leaves the channel open and complete, matching the publish-before-act rule. + +`AbortFrameMut::finish` commits the descriptor into `abort_slot` with `compare_exchange(0, desc, Release, Acquire)` so the first writer wins, and then sets `GATE_ABORTED` with `fetch_or(..., Release)` (even on CAS failure, so a concurrent loser cannot return before `GATE_ABORTED` is visible). If a writer dies between winning `abort_slot` and setting `GATE_ABORTED`, sealing still succeeds unless another writer later aborts, in which case sealing reports `SealError::Aborted` with the first writer's committed payload. If the region cannot fit the abort payload, `claim_abort` sets `GATE_OVERFLOW` instead so the loss is never silent. + ## Sealing and reading -Sealing ORs `GATE_SEALED` into the claim counter (`fetch_or`) and reads the old value. That one operation draws the boundary and shuts the gate without clobbering any other gate bit: claims at or before it are in, every later one fails. If any gate bit was already set, sealing fails with the matching `SealError`, checked in order when multiple gates are set: `AlreadySealed` if `GATE_SEALED` was set, `Aborted` if `GATE_ABORTED` was set, or `Capacity` if `GATE_OVERFLOW` was set. +Sealing ORs `GATE_SEALED` into the claim counter (`fetch_or(..., Acquire)`) and reads the old value. That one operation draws the boundary and shuts the gate without clobbering any other gate bit: claims at or before it are in, every later one fails. If any gate bit was already set, sealing fails with the matching `SealError`, checked in order when multiple gates are set: `AlreadySealed` if `GATE_SEALED` was set, `Aborted(AbortFrame)` if `GATE_ABORTED` was set (borrowing the committed abort payload straight from the mapping in `O(1)` time), or `Capacity` if `GATE_OVERFLOW` was set. No slot is touched, so sealing a channel holding ten million frames costs what sealing an empty one costs. @@ -63,6 +70,7 @@ No slot is touched, so sealing a channel holding ten million frames costs what s - Finding frames never reads payload bytes, and every slot sits at a fixed place, so a half-written payload cannot be mistaken for metadata. - The receiver reaches a payload only through its committed descriptor. The writer commits with `Release` and the receiver loads with `Acquire`, so a descriptor the receiver sees brings its payload bytes along. - One writer owns each slot and writes it once. A slot goes from zero to committed and stops. +- Abort payloads follow the same single-assignment invariant (rule 4 in `layout.rs`): every aborting writer reserves a disjoint payload span, the first writer publishes `abort_slot` with `Release` and sets `GATE_ABORTED` with `Release`, and any concurrent loser synchronizes with the winner via the CAS failure `Acquire` before setting `GATE_ABORTED` with `Release`. `ShmReader::seal` loads the prior gate bits with `Acquire`, so whenever it sees `GATE_ABORTED`, `abort_slot` is guaranteed committed and the winning writer's payload bytes are visible and immutable. - Close gates are set monotonically with `fetch_or`, so setting one gate never erases another or drops the claim count. - No counter has to be exact. Both counters only climb, refused claims leave their increments behind, and the receiver clamps its snapshot to the table length, so a scribbled counter costs it a walk over empty slots. - The receiver builds its borrows from a committed descriptor without re-checking it. That trusts the other processes to follow the protocol; one that scribbles random memory is outside the model. It is also why the receiver reads frames straight out of shared memory, with no copies and no checksums. diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs b/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs index 84d279b20..c9bddee5b 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/layout.rs @@ -29,7 +29,7 @@ pub const GATE_ABORTED: u64 = 1 << 61; /// claims. pub const ANY_CLOSED: u64 = GATE_SEALED | GATE_OVERFLOW | GATE_ABORTED; -/// The two counters at the start of the region, as one `repr(C)` struct +/// The header counters at the start of the region, as one `repr(C)` struct /// that starts zeroed. The descriptor table follows them, and payloads /// take the rest of the mapping. #[repr(C)] @@ -38,8 +38,12 @@ pub struct Counters { /// [`GATE_SEALED`]). The low bits count claims that got as far as reserving /// payload space, which is where a slot is taken. pub claims: AtomicU64, - /// Payload bytes ever reserved, failed claims included. + /// Payload bytes ever reserved, failed claims and abort payloads included. pub payload_reserved: AtomicU64, + /// Descriptor of the first committed abort payload (see [`AbortSlotState`]). + /// Starts zeroed (`AbortSlotState::Empty`) and transitions at most once to + /// a committed state before `GATE_ABORTED` is set. + pub abort_slot: AtomicU64, } // The mapping starts at a `u64`-aligned address and is cast to @@ -58,7 +62,7 @@ const _: () = assert!(size_of::().is_multiple_of(align_of:: // because every byte they point at sits inside an atomic. This catches a // field being added or padding appearing; it cannot catch a field changing // type, so keep that in mind when editing the struct. -const _: () = assert!(size_of::() == 2 * size_of::()); +const _: () = assert!(size_of::() == 3 * size_of::()); // --- The descriptor slot codec --------------------------------------------- // @@ -111,6 +115,19 @@ const _: () = assert!(size_of::() == 2 * size_of::()); // enough. // 3. **Receiver read.** `Iter` loads each descriptor with `Acquire`, so a // descriptor it sees brings the payload bytes along. +// 4. **Writer abort and reader seal.** `AbortFrameMut::finish` publishes its +// descriptor into `abort_slot` with `compare_exchange(0, desc, Release, +// Acquire)` and then sets `GATE_ABORTED` in `claims` with `Release`. +// - The winning writer's `Release` store orders its payload writes before +// `abort_slot` and before `GATE_ABORTED`. +// - Any concurrent aborting writer that loses the CAS synchronizes-with +// the winning writer via the CAS failure `Acquire` load, so the winner's +// payload writes happen-before the loser's `fetch_or(GATE_ABORTED, +// Release)`. +// - `ShmReader::seal` runs `claims.fetch_or(GATE_SEALED, Acquire)`. If it +// observes `GATE_ABORTED`, that `Acquire` synchronizes-with whichever +// writer set `GATE_ABORTED`, so `abort_slot` is guaranteed non-zero and +// the winning writer's payload bytes are visible. /// Converts an integer into a `usize`. /// @@ -205,6 +222,72 @@ impl SlotState { } } +/// Sentinel stored in [`Counters::abort_slot`] for a committed 0-byte abort +/// payload. +/// +/// Distinct from `0` (`Empty`) and impossible for any non-empty payload (whose +/// length field is nonzero). +const EMPTY_ABORT_SLOT: u64 = bytemuck::must_cast::<[u32; 2], u64>([u32::MAX, 0]); + +/// Decoded state of [`Counters::abort_slot`]. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum AbortSlotState { + /// No abort payload has been committed yet. + #[cfg_attr( + target_os = "none", + expect( + dead_code, + reason = "target-none builds only the writer; the hosted reader uses it" + ) + )] + Empty, + /// A 0-byte abort payload has been committed. + CommittedEmpty, + /// A non-empty abort payload has been committed inside the payload area. + Committed { + /// Byte offset of the abort payload from the start of the payload area. + offset: u32, + /// Byte length of the abort payload. + len: NonZeroU32, + }, +} + +impl AbortSlotState { + /// Decodes a raw `abort_slot` value into its state. + #[cfg_attr( + target_os = "none", + expect( + dead_code, + reason = "target-none builds only the writer; the hosted reader uses it" + ) + )] + pub const fn decode(slot_value: u64) -> Self { + if slot_value == 0 { + return Self::Empty; + } + if slot_value == EMPTY_ABORT_SLOT { + return Self::CommittedEmpty; + } + let [offset, len] = bytemuck::must_cast::(slot_value); + // The protocol never writes a nonzero word with `len == 0` other than + // `EMPTY_ABORT_SLOT`; under the protocol trust model, treat any other + // zero-length word as empty (matching `SlotState::decode`). + let Some(len) = NonZeroU32::new(len) else { + return Self::Empty; + }; + Self::Committed { offset, len } + } + + /// Encodes this state as a raw `abort_slot` value; the inverse of [`Self::decode`]. + pub const fn encode(self) -> u64 { + match self { + Self::Empty => 0, + Self::CommittedEmpty => EMPTY_ABORT_SLOT, + Self::Committed { offset, len } => bytemuck::must_cast([offset, len.get()]), + } + } +} + impl MappedLayout { /// Locates the parts of a shared mapping whose table holds `slots` /// descriptors, or returns `None` when the mapping cannot hold the @@ -270,6 +353,11 @@ impl MappedLayout { &self.counters().payload_reserved } + /// The abort-payload descriptor slot. + pub const fn abort_slot(&self) -> &AtomicU64 { + &self.counters().abort_slot + } + /// The descriptor table. pub const fn table(&self) -> &[AtomicU64] { // SAFETY: see `counters`; the table is a run of atomics inside the @@ -317,11 +405,30 @@ mod tests { } } + #[test] + fn abort_slot_codec_roundtrips() { + assert!(AbortSlotState::decode(0) == AbortSlotState::Empty); + assert!(AbortSlotState::Empty.encode() == 0); + + let empty_encoded = AbortSlotState::CommittedEmpty.encode(); + assert!(empty_encoded != 0); + assert!(AbortSlotState::decode(empty_encoded) == AbortSlotState::CommittedEmpty); + + for (offset, len) in [(0, 1), (3, 5), (u32::MAX - 1, 1), (0, u32::MAX)] { + let len = NonZeroU32::new(len).unwrap(); + let state = AbortSlotState::Committed { offset, len }; + let encoded = state.encode(); + assert!(encoded != 0 && encoded != empty_encoded); + assert!(AbortSlotState::decode(encoded) == state); + } + } + #[test] fn a_region_too_small_for_the_table_is_rejected() { - let mut mem = [0u64; 4]; - let raw = std::ptr::slice_from_raw_parts_mut(mem.as_mut_ptr().cast::(), 32); - // Two counters and two slots exactly fill it; a third slot does not. + let mut mem = [0u64; 5]; + let raw = std::ptr::slice_from_raw_parts_mut(mem.as_mut_ptr().cast::(), 40); + // Three counters (24 bytes) and two slots (16 bytes) exactly fill it; + // a third slot does not. // SAFETY: the array is live, aligned and zeroed, and nothing else // touches it. assert!(unsafe { MappedLayout::new(raw, 2) }.is_some()); diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs index bd701d130..e367e6a1a 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/mod.rs @@ -208,7 +208,7 @@ mod tests { // of them, so the seal hands back none of them. // SAFETY: see `collect_frames`. let sealed = unsafe { ShmReader::seal(shm, S) }; - assert!(sealed.unwrap_err() == SealError::Capacity); + assert!(matches!(sealed, Err(SealError::Capacity))); } #[test] @@ -229,23 +229,212 @@ mod tests { // SAFETY: see `collect_frames`. let sealed = unsafe { ShmReader::seal(shm, S) }; - assert!(sealed.unwrap_err() == SealError::Capacity); + assert!(matches!(sealed, Err(SealError::Capacity))); } #[test] - fn abort_fails_seal_with_aborted_and_gates_claims() { + fn abort_with_payload_roundtrips_and_gates_claims() { let shm = MockedShm::alloc(1024); // SAFETY: see `single_thread_basic`. let writer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); assert!(writer.try_write_frame(b"kept")); - writer.abort(); + assert!(writer.try_abort(b"seccomp denied")); assert!(writer.is_closed()); assert!(writer.claim_frame(5.try_into().unwrap()).unwrap_err() == ClaimError::Closed); + assert!(!writer.try_abort(b"second abort ignored")); + + // SAFETY: see `collect_frames`. + let Err(SealError::Aborted(frame)) = (unsafe { ShmReader::seal(shm, S) }) else { + panic!("expected SealError::Aborted"); + }; + assert!(frame.as_bytes() == b"seccomp denied"); + } + + #[test] + fn abort_with_empty_payload_roundtrips() { + let shm = MockedShm::alloc(1024); + // SAFETY: see `single_thread_basic`. + let writer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); + assert!(writer.try_abort(b"")); + assert!(writer.is_closed()); + assert!(shm.peek_u64(8) == 0); + + // SAFETY: see `collect_frames`. + let Err(SealError::Aborted(frame)) = (unsafe { ShmReader::seal(shm, S) }) else { + panic!("expected SealError::Aborted"); + }; + assert!(frame.as_bytes().is_empty()); + } + + #[test] + fn abandoned_abort_frame_leaves_channel_complete() { + let shm = MockedShm::alloc(1024); + // SAFETY: see `single_thread_basic`. + let writer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); + assert!(writer.try_write_frame(b"foo")); + + // Dropping an unfinished abort frame simulates a crash before the + // writer performed its unrecorded operation: the channel stays open + // and complete. + { + let mut abort = writer.claim_abort(8).unwrap(); + abort[..4].copy_from_slice(b"half"); + } + assert!(!writer.is_closed()); + assert!(writer.try_write_frame(b"bar")); + + let frames = collect_frames(&shm); + assert!(frames.iter().collect::>() == [b"foo".as_slice(), b"bar".as_slice()]); + } + + #[test] + fn abort_when_region_full_reports_capacity() { + let shm = MockedShm::alloc(1024); + // SAFETY: see `single_thread_basic`. + let writer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); + assert!(writer.claim_abort(2048).unwrap_err() == ClaimError::Capacity); + assert!(writer.is_closed()); // SAFETY: see `collect_frames`. let sealed = unsafe { ShmReader::seal(shm, S) }; - assert!(sealed.unwrap_err() == SealError::Aborted); + assert!(matches!(sealed, Err(SealError::Capacity))); + } + + #[test] + fn abort_after_seal_does_not_corrupt_reader() { + let shm = MockedShm::alloc(1024); + // SAFETY: see `single_thread_basic`. + let writer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); + assert!(writer.try_write_frame(b"before")); + + // Claim an abort before sealing, then seal before it finishes. + let mut abort = writer.claim_abort(5).unwrap(); + abort.copy_from_slice(b"later"); + + let frames = collect_frames(&shm); + abort.finish(); + + assert!(frames.iter().collect::>() == [b"before".as_slice()]); + // A second seal still reports AlreadySealed. + // SAFETY: see `collect_frames`. + let second = unsafe { ShmReader::seal(shm, S) }; + assert!(matches!(second, Err(SealError::AlreadySealed))); + } + + #[test] + fn concurrent_aborts_first_wins_without_data_race() { + let shm = MockedShm::alloc(4096); + let barrier = Barrier::new(5); + // SAFETY: see `concurrent`. + let observer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); + thread::scope(|s| { + let writers: Vec<_> = (0u8..4) + .map(|id| { + let shm = shm.clone(); + let barrier = &barrier; + s.spawn(move || { + // SAFETY: see `concurrent`. + let writer = unsafe { ShmWriter::new(shm, S) }.unwrap(); + let payload = [id + 1; 32]; + barrier.wait(); + let _ = writer.try_abort(&payload); + }) + }) + .collect(); + + barrier.wait(); + // Spin on the Relaxed `is_closed()` check (which establishes no + // happens-before on its own), then seal and read the payload bytes + // BEFORE joining the writer threads so Miri verifies rule 4's + // Release/Acquire ordering on the payload itself. + while !observer.is_closed() { + thread::yield_now(); + } + // SAFETY: see `collect_frames`. + let Err(SealError::Aborted(frame)) = (unsafe { ShmReader::seal(shm.clone(), S) }) + else { + panic!("expected SealError::Aborted"); + }; + let bytes = frame.as_bytes(); + assert!(bytes.len() == 32); + let winner = bytes[0]; + assert!((1..=4).contains(&winner)); + assert!(bytes.iter().all(|&b| b == winner)); + drop(frame); + + for w in writers { + w.join().unwrap(); + } + }); + } + + #[test] + fn abort_racing_with_seal_is_sound() { + let shm = MockedShm::alloc(4096); + let barrier = Barrier::new(3); + thread::scope(|s| { + let writers = [1u8, 2u8].map(|id| { + let shm = shm.clone(); + let barrier = &barrier; + s.spawn(move || { + // SAFETY: see `concurrent`. + let writer = unsafe { ShmWriter::new(shm, S) }.unwrap(); + let payload = [id; 24]; + barrier.wait(); + let _ = writer.try_abort(&payload); + }) + }); + barrier.wait(); + // SAFETY: see `collect_frames`. + let sealed = unsafe { ShmReader::seal(shm.clone(), S) }; + // Inspect the sealed result and payload bytes BEFORE joining the + // writer threads so Miri verifies rule 4's Release/Acquire ordering + // without relying on thread-join happens-before. + match sealed { + Ok(reader) => assert!(reader.iter().next().is_none()), + Err(SealError::Aborted(frame)) => { + let bytes = frame.as_bytes(); + assert!(bytes.len() == 24); + let winner = bytes[0]; + assert!(winner == 1 || winner == 2); + assert!(bytes.iter().all(|&b| b == winner)); + } + Err(other) => panic!("unexpected seal error: {other:?}"), + } + for w in writers { + w.join().unwrap(); + } + }); + } + + #[test] + fn seal_error_precedence_is_already_sealed_then_aborted_then_capacity() { + let shm = MockedShm::alloc(1024); + // SAFETY: see `single_thread_basic`. + let writer = unsafe { ShmWriter::new(shm.clone(), S) }.unwrap(); + + let mut abort = writer.claim_abort(4).unwrap(); + abort.copy_from_slice(b"loss"); + // Set `GATE_OVERFLOW` before `abort.finish()` sets `GATE_ABORTED`. + assert!(writer.claim_frame(2048.try_into().unwrap()).unwrap_err() == ClaimError::Capacity); + abort.finish(); + assert!(shm.peek_u64(0) & layout::GATE_OVERFLOW != 0); + assert!(shm.peek_u64(0) & layout::GATE_ABORTED != 0); + + // When both `GATE_ABORTED` and `GATE_OVERFLOW` are set, `Aborted` wins + // and carries the committed payload. + // SAFETY: see `collect_frames`. + let Err(SealError::Aborted(frame)) = (unsafe { ShmReader::seal(shm.clone(), S) }) else { + panic!("expected SealError::Aborted"); + }; + assert!(frame.as_bytes() == b"loss"); + drop(frame); + + // Once `GATE_SEALED` is also set, `AlreadySealed` takes precedence over + // both `Aborted` and `Capacity`. + // SAFETY: see `collect_frames`. + assert!(matches!(unsafe { ShmReader::seal(shm, S) }, Err(SealError::AlreadySealed))); } #[test] @@ -354,7 +543,7 @@ mod tests { // Fifteen frames landed, but the sixteenth was lost. // SAFETY: see `collect_frames`. let sealed = unsafe { ShmReader::seal(shm, S) }; - assert!(sealed.unwrap_err() == SealError::Capacity); + assert!(matches!(sealed, Err(SealError::Capacity))); } #[test] @@ -411,7 +600,7 @@ mod tests { // cannot say what was refused since then. // SAFETY: see `collect_frames`. let sealed = unsafe { ShmReader::seal(shm, S) }; - assert!(sealed.unwrap_err() == SealError::AlreadySealed); + assert!(matches!(sealed, Err(SealError::AlreadySealed))); } #[test] @@ -471,7 +660,7 @@ mod tests { assert!(writer.is_closed()); // SAFETY: see `collect_frames`. let sealed = unsafe { ShmReader::seal(shm, S) }; - assert!(sealed.unwrap_err() == SealError::Capacity); + assert!(matches!(sealed, Err(SealError::Capacity))); } #[test] diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/reader.rs b/crates/fspy_shared/src/ipc/channel/shm_io/reader.rs index 4ef48f083..f1c42e035 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/reader.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/reader.rs @@ -15,6 +15,7 @@ use std::{ fmt, iter::FusedIterator, + ops::Deref, ptr::NonNull, slice, sync::atomic::{AtomicU64, Ordering}, @@ -22,12 +23,63 @@ use std::{ use super::{ AsRawSlice, - layout::{GATE_ABORTED, GATE_OVERFLOW, GATE_SEALED, MappedLayout, SlotState, to_usize}, + layout::{ + AbortSlotState, GATE_ABORTED, GATE_OVERFLOW, GATE_SEALED, MappedLayout, SlotState, to_usize, + }, }; +/// Opaque abort payload committed by the first writer that aborted the channel. +/// +/// Owns the mapping `M` so the committed bytes can be read in place without +/// copying; dropping it releases the mapping. +pub struct AbortFrame { + ptr: NonNull, + len: usize, + /// Owns the region `ptr` points into. Declared last so fields drop in order. + _mem: M, +} + +// SAFETY: `ptr` points into the independently owned mapping `_mem` at an +// immutable committed abort span (or is dangling with `len == 0`), so moving +// or sharing `AbortFrame` across threads is sound whenever `M` is. +unsafe impl Send for AbortFrame {} +// SAFETY: see the `Send` impl. +unsafe impl Sync for AbortFrame {} + +impl AbortFrame { + /// Returns the committed abort payload bytes. + #[must_use] + pub const fn as_bytes(&self) -> &[u8] { + // SAFETY: either `len == 0` with a dangling aligned `NonNull`, or + // `(ptr, len)` is the immutable committed span inside `_mem`, which + // stays alive for `&self`. + unsafe { slice::from_raw_parts(self.ptr.as_ptr().cast_const(), self.len) } + } +} + +impl Deref for AbortFrame { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.as_bytes() + } +} + +impl AsRef<[u8]> for AbortFrame { + fn as_ref(&self) -> &[u8] { + self.as_bytes() + } +} + +impl fmt::Debug for AbortFrame { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("AbortFrame").field("len", &self.len).finish_non_exhaustive() + } +} + /// Why a channel could not be sealed. -#[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] -pub enum SealError { +#[derive(thiserror::Error)] +pub enum SealError { /// The mapping cannot hold the protocol at all (see /// [`MappedLayout::new`]). #[error("the shared-memory region cannot host the channel")] @@ -40,9 +92,22 @@ pub enum SealError { /// 32-bit descriptor length limit. #[error("the shared-memory channel ran out of capacity")] Capacity, - /// A writer explicitly aborted the channel via [`ShmWriter::abort`](super::ShmWriter::abort). + /// A writer explicitly aborted the channel via + /// [`AbortFrameMut::finish`](super::writer::AbortFrameMut::finish), + /// carrying the committed opaque payload bytes. #[error("a writer aborted the shared-memory channel")] - Aborted, + Aborted(AbortFrame), +} + +impl fmt::Debug for SealError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnsupportedRegion => f.write_str("UnsupportedRegion"), + Self::AlreadySealed => f.write_str("AlreadySealed"), + Self::Capacity => f.write_str("Capacity"), + Self::Aborted(frame) => f.debug_tuple("Aborted").field(frame).finish(), + } + } } /// A reader over the committed frames of a sealed channel, serving them @@ -96,7 +161,7 @@ impl ShmReader { /// was already closed before this call. When multiple close gates are set, /// they are reported in precedence order: [`SealError::AlreadySealed`], /// then [`SealError::Aborted`], then [`SealError::Capacity`]. - pub unsafe fn seal(mem: M, slots: usize) -> Result { + pub unsafe fn seal(mem: M, slots: usize) -> Result> { // SAFETY: forwarded from this function's contract, which keeps the // region valid for as long as the reader lives, and so for every // use of the pointers, which are stored in the reader and dropped @@ -105,16 +170,33 @@ impl ShmReader { return Err(SealError::UnsupportedRegion); }; - // Draw the boundary and shut the seal gate in one step (rule 1): this - // returns the prior gate bits and claim count at the instant no later - // claim can succeed. Using `fetch_or` preserves any gate bits already - // set by earlier seals, aborts, or capacity overflows. - let prev = mapped.claims().fetch_or(GATE_SEALED, Ordering::Relaxed); + // Draw the boundary and shut the seal gate in one step (rules 1 & 4): + // `Acquire` synchronizes-with `AbortFrameMut::finish`'s `Release` so + // seeing `GATE_ABORTED` guarantees `abort_slot` and its payload bytes + // are visible. + let prev = mapped.claims().fetch_or(GATE_SEALED, Ordering::Acquire); if prev & GATE_SEALED != 0 { return Err(SealError::AlreadySealed); } if prev & GATE_ABORTED != 0 { - return Err(SealError::Aborted); + let slot_value = mapped.abort_slot().load(Ordering::Acquire); + let frame = match AbortSlotState::decode(slot_value) { + AbortSlotState::CommittedEmpty => { + AbortFrame { ptr: NonNull::dangling(), len: 0, _mem: mem } + } + AbortSlotState::Committed { offset, len } => AbortFrame { + // SAFETY: the committed abort descriptor names the span + // its writer reserved inside the payload area, and nothing + // mutates a committed abort span again. + ptr: unsafe { mapped.payload_start.add(to_usize(offset)) }, + len: to_usize(len.get()), + _mem: mem, + }, + AbortSlotState::Empty => { + unreachable!("GATE_ABORTED is only set after abort_slot is committed") + } + }; + return Err(SealError::Aborted(frame)); } if prev & GATE_OVERFLOW != 0 { return Err(SealError::Capacity); diff --git a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs index 2f4abb11d..79a3003ea 100644 --- a/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs +++ b/crates/fspy_shared/src/ipc/channel/shm_io/writer.rs @@ -9,7 +9,9 @@ use core::{ use super::{ AsRawSlice, - layout::{ANY_CLOSED, GATE_ABORTED, GATE_OVERFLOW, MappedLayout, SlotState, to_usize}, + layout::{ + ANY_CLOSED, AbortSlotState, GATE_ABORTED, GATE_OVERFLOW, MappedLayout, SlotState, to_usize, + }, }; /// A shared-memory frame writer, usable from many threads and processes at @@ -36,7 +38,7 @@ unsafe impl Sync for ShmWriter {} #[derive(thiserror::Error, Clone, Copy, PartialEq, Eq, Debug)] pub enum ClaimError { /// A close gate is set, by a seal, by an earlier failed claim, or by - /// [`ShmWriter::abort`]. Dropping the record is right in every + /// [`AbortFrameMut::finish`]. Dropping the record is right in every /// case: the receiver had stopped collecting, or that same gate already /// fails its seal. #[error("the channel has been closed")] @@ -71,17 +73,80 @@ impl ShmWriter { } /// Whether any close gate is set, by a seal, by a failed claim, or by - /// [`ShmWriter::abort`]. + /// [`AbortFrameMut::finish`]. pub fn is_closed(&self) -> bool { self.mapped.claims().load(Ordering::Relaxed) & ANY_CLOSED != 0 } - /// Marks the channel aborted, shutting it against further claims. + /// Claims an opaque abort payload of `payload_size` bytes to abort the + /// channel (rule 4). /// - /// A subsequent seal fails with [`SealError::Aborted`](super::SealError::Aborted) - /// (unless the receiver already sealed before this call took effect). - pub fn abort(&self) { - self.mapped.claims().fetch_or(GATE_ABORTED, Ordering::Relaxed); + /// Unlike [`Self::claim_frame`], `payload_size` may be zero (which needs no + /// payload bytes and cannot fail on capacity). The channel stays open until + /// [`AbortFrameMut::finish`] runs; dropping the returned handle abandons + /// the abort cleanly, as if the writer died before performing the + /// unrecorded action. + /// + /// If the payload area has no room for `payload_size` bytes (or it exceeds + /// `u32::MAX`), this sets `GATE_OVERFLOW` and returns + /// [`ClaimError::Capacity`] so the receiver still knows records were lost. + pub fn claim_abort(&self, payload_size: usize) -> Result, ClaimError> { + let mapped = self.mapped; + if self.is_closed() { + return Err(ClaimError::Closed); + } + + let Some(payload_size) = NonZeroUsize::new(payload_size) else { + return Ok(AbortFrameMut { + claims: self.mapped.claims(), + abort_slot: self.mapped.abort_slot(), + slot_to_commit: AbortSlotState::CommittedEmpty.encode(), + content: &mut [], + }); + }; + + let mark_overflow = || { + self.mark_overflow(); + ClaimError::Capacity + }; + + let Ok(payload_size) = NonZeroU32::try_from(payload_size) else { + return Err(mark_overflow()); + }; + let reservation = u64::from(payload_size.get()); + let payload_start = mapped.payload_reserved().fetch_add(reservation, Ordering::Relaxed); + let Some(payload_offset) = + fitted_offset(payload_start, payload_size.get(), mapped.payload_len) + else { + return Err(mark_overflow()); + }; + + // SAFETY: the reservation owns this span exclusively inside the payload + // area; nothing reads it until `AbortFrameMut::finish` publishes its + // descriptor into `abort_slot` and sets `GATE_ABORTED`. + let content = unsafe { + slice::from_raw_parts_mut( + mapped.payload_start.add(to_usize(payload_offset)).as_ptr(), + to_usize(payload_size.get()), + ) + }; + Ok(AbortFrameMut { + claims: self.mapped.claims(), + abort_slot: self.mapped.abort_slot(), + slot_to_commit: AbortSlotState::Committed { offset: payload_offset, len: payload_size } + .encode(), + content, + }) + } + + #[cfg(test)] + pub fn try_abort(&self, payload: &[u8]) -> bool { + let Ok(mut frame) = self.claim_abort(payload.len()) else { + return false; + }; + frame.copy_from_slice(payload); + frame.finish(); + true } /// Marks the channel overflowed, shutting it against further claims. @@ -226,3 +291,52 @@ impl FrameMut<'_> { self.slot.store(self.slot_to_commit, Ordering::Release); } } + +/// An exclusively owned abort payload, claimed but not yet published. +/// +/// [`AbortFrameMut::finish`] publishes the payload into the channel's abort +/// slot (first writer wins) and sets `GATE_ABORTED`. Dropping without calling +/// `finish` abandons the abort cleanly, leaving the channel open. +#[derive(Debug)] +pub struct AbortFrameMut<'a> { + claims: &'a AtomicU64, + abort_slot: &'a AtomicU64, + slot_to_commit: u64, + content: &'a mut [u8], +} + +impl Deref for AbortFrameMut<'_> { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + self.content + } +} + +impl DerefMut for AbortFrameMut<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.content + } +} + +impl AbortFrameMut<'_> { + /// Commits the abort payload and shuts the channel against further claims. + /// + /// First writer wins `abort_slot`; concurrent losers still synchronize with + /// the winner and ensure `GATE_ABORTED` is visible before returning + /// (rule 4). + /// + /// If a writer dies in the single-instruction window between winning + /// `abort_slot` and setting `GATE_ABORTED`, `seal` succeeds unless another + /// writer later aborts, in which case `seal` observes `GATE_ABORTED` with + /// the first writer's already-committed payload. + pub fn finish(self) { + let _ = self.abort_slot.compare_exchange( + 0, + self.slot_to_commit, + Ordering::Release, + Ordering::Acquire, + ); + self.claims.fetch_or(GATE_ABORTED, Ordering::Release); + } +}