Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions crates/fspy_shared/src/ipc/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,9 @@ impl<P: ChannelProtocol> Sender<P> {
/// 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();
}
Comment thread
wan9chi marked this conversation as resolved.
Resolved
}

/// Serializes one record into a committed frame.
Expand Down Expand Up @@ -506,7 +508,7 @@ impl<P: ChannelProtocol, A: Allocator> Receiver<P, A> {
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")
}
Expand Down Expand Up @@ -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::<U16Protocol, _>(8, Global) else {
panic!("a region too small for the protocol made a channel");
Expand Down Expand Up @@ -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::<U16Protocol, _>(SLOTS * 8 + 20, Global).unwrap();
let receiver = channel::<U16Protocol, _>(SLOTS * 8 + 28, Global).unwrap();
let sender = receiver.conf().sender(Global).unwrap();
sender.send(&1);
sender.send(&2);
Expand Down
16 changes: 12 additions & 4 deletions crates/fspy_shared/src/ipc/channel/shm_io/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand Down
119 changes: 113 additions & 6 deletions crates/fspy_shared/src/ipc/channel/shm_io/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand All @@ -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
Expand All @@ -58,7 +62,7 @@ const _: () = assert!(size_of::<Counters>().is_multiple_of(align_of::<AtomicU64>
// 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::<Counters>() == 2 * size_of::<AtomicU64>());
const _: () = assert!(size_of::<Counters>() == 3 * size_of::<AtomicU64>());

// --- The descriptor slot codec ---------------------------------------------
//
Expand Down Expand Up @@ -111,6 +115,19 @@ const _: () = assert!(size_of::<Counters>() == 2 * size_of::<AtomicU64>());
// 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`.
///
Expand Down Expand Up @@ -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::<u64, [u32; 2]>(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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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::<u8>(), 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::<u8>(), 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());
Expand Down
Loading
Loading