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
9 changes: 5 additions & 4 deletions crates/fspy_shared/src/ipc/channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ impl Sender {
/// [`RecordsLost`], so the run is treated as untracked rather than
/// cached from a partial trace.
pub fn report_loss(&self) {
self.writer.report_loss();
self.writer.abort();
}

/// Serializes one record into a committed frame.
Expand Down Expand Up @@ -377,9 +377,10 @@ impl<A: Allocator> Receiver<A> {
drop(keeper);
match sealed {
Ok(reader) => Ok(reader),
// This receiver is the only one that could have sealed, and it
// is gone by now, so the gate can only be a sender's report.
Err(SealError::Closed) => Err(RecordsLost),
Err(SealError::Capacity | SealError::Aborted) => Err(RecordsLost),
Err(SealError::AlreadySealed) => {
panic!("the unique receiver cannot have already sealed the channel")
}
Err(SealError::UnsupportedRegion) => {
panic!("the shared-memory region cannot hold the channel")
}
Expand Down
13 changes: 7 additions & 6 deletions crates/fspy_shared/src/ipc/channel/shm_io/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Any zero-initialized shared memory works. In practice it is a sparse file mapped

Two `AtomicU64` counters sit at the front, followed by one 8-byte descriptor slot per frame.

- The **claim counter** counts frames ever claimed. Bit 63 is the CLOSED gate: the receiver sets it when it seals, and so does any writer whose claim failed or that went on to do something it could not record, which is how the receiver hears about a lost record.
- 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 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 All @@ -27,7 +27,7 @@ Where the table ends and payloads begin never moves. Claiming needs no retry loo

## Writing a frame

1. **Claim.** Two `fetch_add`s reserve payload bytes and a slot. No retry loop, no lock. A claim that does not fit fails after the fact, and sets the CLOSED gate before the writer moves on.
1. **Claim.** Check that no close gate is set, then two `fetch_add`s reserve payload bytes and a slot. No retry loop, no lock. A claim that does not fit fails after the fact, and sets `GATE_OVERFLOW` before the writer moves on.
2. **Fill.** The writer serializes into its payload span, which nobody else knows exists.
3. **Commit.** One store puts the payload's offset and length into the slot. Only the writer that claimed a slot ever writes it, so it needs no compare-and-swap. The receiver cannot see the frame before that store, and nobody touches the payload after it.

Expand All @@ -42,17 +42,17 @@ So the channel asks one thing of its users: **publish a record before performing

A 4 GiB region holds tens of millions of records, but not endless ones. When a claim asks for more room than the payload area or the table has left, it fails. The writer skips that record and carries on, because recording must never stop the program doing the work.

The loss is not silent. The failed claim sets the CLOSED gate before it returns, and a receiver that finds that bit already set fails its seal and hands back nothing.
The loss is not silent. The failed claim sets `GATE_OVERFLOW` with `fetch_or` before it returns, and a receiver that finds that bit already set fails its seal with `SealError::Capacity` and hands back nothing.

Setting the bit first matters for the same reason publishing before acting does. If the receiver's read misses the bit, the writer set it after the seal, so the skipped record describes an action performed after the channel closed. And a writer that died before setting it never performed its action.

Because the bit is also the gate, the first lost record closes the channel and every later claim is refused. Those records would only pile up in a result nobody can use.
Because every gate bit closes the channel, the first lost record or writer abort refuses every later claim. Those records would only pile up in a result nobody can use.

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.

## Sealing and reading

Sealing swaps the CLOSED gate into the claim counter and reads the old value. That one operation draws the boundary and shuts the gate: claims at or before it are in, every later one fails. If the bit was already set, a record was lost or someone sealed earlier, and sealing fails here.
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.

No slot is touched, so sealing a channel holding ten million frames costs what sealing an empty one costs.

Expand All @@ -63,7 +63,8 @@ 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.
- No counter has to be exact. Both 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.
- 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.

## Deployment note
Expand Down
52 changes: 31 additions & 21 deletions crates/fspy_shared/src/ipc/channel/shm_io/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,34 @@

use core::{num::NonZeroU32, ptr::NonNull, sync::atomic::AtomicU64};

/// The CLOSED gate bit of the claim counter. The receiver sets it when it
/// seals, and so does a claim the region had no room for, which is how it
/// reports the loss (rule 1). Nothing else sets it: what a writer cannot
/// record for its own reasons is not this protocol's to report.
/// Bit 63 of the claim counter: the receiver has sealed the channel.
///
/// A bit rather than a value to compare against, so it survives the
/// increment of a writer that arrives late. Counting cannot reach it: that
/// takes 2^63 claims, and a channel lives for one command. A gate that
/// somehow read as set would fail the seal, which is the cautious
/// answer.
pub const CLOSED: u64 = 1 << 63;
/// Bits 61..=63 form the three independent close gates: setting any one stops
/// further claims, and `fetch_or` preserves every gate that was already set so
/// [`ShmReader::seal`](super::ShmReader::seal) can tell a second seal, a
/// capacity overflow, and a writer-initiated abort apart. Counting cannot reach
/// bit 61: that takes 2^61 claims, and a channel lives for one command.
pub const GATE_SEALED: u64 = 1 << 63;

/// Bit 62 of the claim counter: a claim exceeded the region's slot table,
/// payload space, or 32-bit descriptor length limit.
pub const GATE_OVERFLOW: u64 = 1 << 62;

/// Bit 61 of the claim counter: a writer explicitly aborted the channel.
pub const GATE_ABORTED: u64 = 1 << 61;

/// Mask of every close gate bit in the claim counter. Any bit set rejects new
/// 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
/// that starts zeroed. The descriptor table follows them, and payloads
/// take the rest of the mapping.
#[repr(C)]
pub struct Counters {
/// Bit 63 is the CLOSED gate. The low bits count claims that got as
/// far as reserving payload space, which is where a slot is taken.
/// Bits 61..=63 are the close gates ([`GATE_ABORTED`], [`GATE_OVERFLOW`],
/// [`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.
pub payload_reserved: AtomicU64,
Expand Down Expand Up @@ -82,19 +91,20 @@ const _: () = assert!(size_of::<Counters>() == 2 * size_of::<AtomicU64>());
// Neither counter guards its add against wrapping, because neither wrap is
// reachable. The payload counter passes the region only after a claim has
// failed, and every claim after that is refused before it builds a span.
// The claim count needs 2^63 increments to reach the gate bit.
// The claim count needs 2^61 increments to reach the lowest gate bit.
//
// # Memory-ordering contract
//
// 1. **Claim versus seal.** The seal swaps the gate into the claim counter
// and reads the old value in one step, so the boundary and the gate are
// one point in that counter's modification order: claims at or before
// it are in, every later one fails on the gate. Claims publish no
// 1. **Claim versus seal.** The seal `fetch_or`s `GATE_SEALED` into the claim
// counter and reads the old value in one step, so the boundary and the gate
// are one point in that counter's modification order: claims at or before
// it are in, every later one fails on `ANY_CLOSED`. Claims publish no
// payload data, so `Relaxed` suffices. Completeness rides the same
// order: a failed claim sets the gate before performing the operation
// whose record it lost, so either the seal sees the bit or the loss
// happened past the boundary. A writer that died before setting it
// never performed its operation.
// order: a failed claim (`GATE_OVERFLOW`) or writer abort (`GATE_ABORTED`)
// sets its gate bit before performing the unrecorded operation, so either
// the seal sees the bit or the unrecorded operation happened past the
// boundary. A writer that died before setting it never performed its
// operation.
// 2. **Writer commit.** `FrameMut::finish` stores the descriptor with
// `Release`, so every payload write lands first. The writer that
// claimed the slot is the only one that writes it, so a store is
Expand Down
42 changes: 29 additions & 13 deletions crates/fspy_shared/src/ipc/channel/shm_io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,19 +196,19 @@ mod tests {
assert!(writer.try_write_frame(b"test"));

// Larger than the payload region: the claim fails and sets the
// gate, which is what tells the receiver a record was lost.
// overflow gate, which is what tells the receiver a record was lost.
assert!(!writer.try_write_frame(&vec![0u8; 2048]));
// The refused reservation stays counted: four bytes of "test"
// plus the 2048 that did not fit.
assert!(shm.peek_u64(8) == 4 + 2048);
// The loss report replaces the count with the gate.
assert!(shm.peek_u64(0) == 1 << 63);
// The overflow gate is OR'd in, preserving the claim count.
assert!(shm.peek_u64(0) == (layout::GATE_OVERFLOW | 1));

// "test" did land, but a lost record means the frames are not all
// 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::Closed);
assert!(sealed.unwrap_err() == SealError::Capacity);
}

#[test]
Expand All @@ -219,8 +219,8 @@ mod tests {
assert!(writer.try_write_frame(b"kept"));

// No descriptor can describe a frame this long: the claim is
// refused and sets the gate, which shuts out later claims: their
// records would ride on a result the receiver must already
// refused and sets the overflow gate, which shuts out later claims:
// their records would ride on a result the receiver must already
// reject.
let oversized = (layout::to_usize(u32::MAX) + 1).try_into().unwrap();
assert!(matches!(writer.claim_frame(oversized), Err(ClaimError::Capacity)));
Expand All @@ -229,7 +229,23 @@ mod tests {

// SAFETY: see `collect_frames`.
let sealed = unsafe { ShmReader::seal(shm, S) };
assert!(sealed.unwrap_err() == SealError::Closed);
assert!(sealed.unwrap_err() == SealError::Capacity);
}

#[test]
fn abort_fails_seal_with_aborted_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.is_closed());
assert!(writer.claim_frame(5.try_into().unwrap()).unwrap_err() == ClaimError::Closed);

// SAFETY: see `collect_frames`.
let sealed = unsafe { ShmReader::seal(shm, S) };
assert!(sealed.unwrap_err() == SealError::Aborted);
}

#[test]
Expand Down Expand Up @@ -332,13 +348,13 @@ mod tests {
assert!(writer.try_write_frame(b"x"));
}
assert!(writer.claim_frame(1.try_into().unwrap()).unwrap_err() == ClaimError::Capacity);
// The loss report replaces the count with the gate.
assert!(shm.peek_u64(0) == 1 << 63);
// The overflow gate is OR'd in, preserving the claim count (15 + 1 refused).
assert!(shm.peek_u64(0) == (layout::GATE_OVERFLOW | 16));

// Fifteen frames landed, but the sixteenth was lost.
// SAFETY: see `collect_frames`.
let sealed = unsafe { ShmReader::seal(shm, S) };
assert!(sealed.unwrap_err() == SealError::Closed);
assert!(sealed.unwrap_err() == SealError::Capacity);
}

#[test]
Expand Down Expand Up @@ -391,11 +407,11 @@ mod tests {
frame.finish();
assert!(frames.iter().count() == 1);

// A second seal fails: the first one set the gate, and a re-seal
// A second seal fails: the first one set the seal gate, and a re-seal
// cannot say what was refused since then.
// SAFETY: see `collect_frames`.
let sealed = unsafe { ShmReader::seal(shm, S) };
assert!(sealed.unwrap_err() == SealError::Closed);
assert!(sealed.unwrap_err() == SealError::AlreadySealed);
}

#[test]
Expand Down Expand Up @@ -455,7 +471,7 @@ mod tests {
assert!(writer.is_closed());
// SAFETY: see `collect_frames`.
let sealed = unsafe { ShmReader::seal(shm, S) };
assert!(sealed.unwrap_err() == SealError::Closed);
assert!(sealed.unwrap_err() == SealError::Capacity);
}

#[test]
Expand Down
Loading
Loading