synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-wire / tests / g3_ring.rs
| 1 | //! G3 acceptance (ADR 0003 section 9 row 26): a hostile writer (bad lengths, index wrap, |
| 2 | //! torn frames) cannot make the reader panic, read outside the ring, or accept a frame |
| 3 | //! twice; no frame is lost or duplicated in a model test. Supporting: the sealed shared |
| 4 | //! region, two processes, a hostile reader, and the G1 session carried over the ring. |
| 5 | //! |
| 6 | //! "Read outside the ring": every ring access is a bounds-checked slice index of the |
| 7 | //! region's words, so an out-of-ring position would panic instead of reading. The tests |
| 8 | //! below therefore check "no panic" under `catch_unwind` for every hostile input, and the |
| 9 | //! negative control shows that a reader without the masking and checks does panic (that |
| 10 | //! is, would read outside the ring if it were written with raw pointers) on the same inputs. |
| 11 | |
| 12 | use std::collections::VecDeque; |
| 13 | use std::panic::{catch_unwind, AssertUnwindSafe}; |
| 14 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 15 | use std::sync::Arc; |
| 16 | use std::time::Duration; |
| 17 | use synapse_core::RefusalCode; |
| 18 | use synapse_wire::frame::{decode_frame, encode_frame, WireLimits}; |
| 19 | use synapse_wire::ring::{layout, record_span, RecvStatus, CONTROL_WORDS, RECORD_HEADER_LEN}; |
| 20 | use synapse_wire::session::submit_request; |
| 21 | use synapse_wire::testkit::{envelope, open_store, sample_frames, server, temp_dir, ChainFixture}; |
| 22 | use synapse_wire::{ |
| 23 | FrameConn, RingConfig, RingReceiver, RingRefusal, RingRegion, RingSender, Side, WireClient, |
| 24 | }; |
| 25 | |
| 26 | // --------------------------------------------------------------------------------------- |
| 27 | // Helpers |
| 28 | // --------------------------------------------------------------------------------------- |
| 29 | |
| 30 | struct SplitMix(u64); |
| 31 | |
| 32 | impl SplitMix { |
| 33 | fn next(&mut self) -> u64 { |
| 34 | self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 35 | let mut z = self.0; |
| 36 | z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 37 | z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 38 | z ^ (z >> 31) |
| 39 | } |
| 40 | fn below(&mut self, n: u64) -> u64 { |
| 41 | self.next() % n |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | fn cfg(capacity: usize, max_record: usize, start: u64) -> RingConfig { |
| 46 | RingConfig { |
| 47 | capacity, |
| 48 | max_record, |
| 49 | start, |
| 50 | spin: Duration::from_micros(20), |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Starts that cross the 2^64 index wrap, the data-area wrap, and the plain case. |
| 55 | const STARTS: [u64; 4] = [0, u64::MAX - 7, u64::MAX - 7 - 128, 1 << 63]; |
| 56 | |
| 57 | /// Ring 0 is written by the creator and read by the attacher: the tests play a hostile |
| 58 | /// creator by writing ring 0's words directly, and read with the attacher's receiver. |
| 59 | fn hostile_ring(c: RingConfig) -> (Arc<RingRegion>, RingSender, RingReceiver) { |
| 60 | let region = RingRegion::in_process(c).unwrap(); |
| 61 | let (tx, _) = region.endpoints(Side::Creator); |
| 62 | let (_, rx) = region.endpoints(Side::Attacher); |
| 63 | (region, tx, rx) |
| 64 | } |
| 65 | |
| 66 | fn ctl(region: &RingRegion, off: usize) -> &AtomicU64 { |
| 67 | ®ion.words()[region.config().ring_base(0) + off] |
| 68 | } |
| 69 | |
| 70 | fn data(region: &RingRegion, index: u64) -> &AtomicU64 { |
| 71 | let c = region.config(); |
| 72 | let pos = ((index / 8) as usize) & (c.capacity / 8 - 1); |
| 73 | ®ion.words()[c.ring_base(0) + CONTROL_WORDS + pos] |
| 74 | } |
| 75 | |
| 76 | /// Payload `i` of `len` bytes: the record number in the first bytes, then a pattern. |
| 77 | fn payload(i: u64, len: usize) -> Vec<u8> { |
| 78 | let mut v: Vec<u8> = (0..len) |
| 79 | .map(|j| (i as u8).wrapping_mul(31).wrapping_add(j as u8)) |
| 80 | .collect(); |
| 81 | let n = len.min(8); |
| 82 | v[..n].copy_from_slice(&i.to_le_bytes()[..n]); |
| 83 | v |
| 84 | } |
| 85 | |
| 86 | /// Run `f` and require that it does not panic. |
| 87 | fn no_panic<T>(what: &str, f: impl FnOnce() -> T) -> T { |
| 88 | match catch_unwind(AssertUnwindSafe(f)) { |
| 89 | Ok(v) => v, |
| 90 | Err(_) => panic!("reader panicked on hostile input: {what}"), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// After a refusal the receiver stays refused with the same refusal. |
| 95 | fn assert_poisoned(rx: &mut RingReceiver, first: &RingRefusal) { |
| 96 | let mut out = Vec::new(); |
| 97 | for _ in 0..3 { |
| 98 | assert_eq!(rx.try_recv(&mut out).as_ref(), Err(first)); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // --------------------------------------------------------------------------------------- |
| 103 | // Hostile writer: bad lengths |
| 104 | // --------------------------------------------------------------------------------------- |
| 105 | |
| 106 | #[test] |
| 107 | fn hostile_writer_bad_lengths_cannot_make_the_reader_panic_or_read_outside_the_ring() { |
| 108 | let (capacity, max_record) = (256usize, 120usize); |
| 109 | // (declared len, bytes published, expected refusal kind) |
| 110 | let cases: [(u64, u64, &str); 9] = [ |
| 111 | (max_record as u64 + 1, 256, "LengthOverCap"), |
| 112 | (u64::MAX, 64, "LengthOverCap"), |
| 113 | (u64::MAX - 7, 64, "LengthOverCap"), |
| 114 | (1 << 63, 64, "LengthOverCap"), |
| 115 | (capacity as u64, 256, "LengthOverCap"), |
| 116 | (usize::MAX as u64 - 15, 256, "LengthOverCap"), |
| 117 | // A legal length whose payload was not all published. |
| 118 | (100, 64, "TornRecord"), |
| 119 | (max_record as u64, 128, "TornRecord"), |
| 120 | (9, 24, "TornRecord"), |
| 121 | ]; |
| 122 | for start in STARTS { |
| 123 | for (len, published, kind) in cases { |
| 124 | let (region, _tx, mut rx) = hostile_ring(cfg(capacity, max_record, start)); |
| 125 | data(®ion, start).store(len, Ordering::Relaxed); |
| 126 | data(®ion, start.wrapping_add(8)).store(0, Ordering::Relaxed); |
| 127 | ctl(®ion, layout::HEAD).store(start.wrapping_add(published), Ordering::Release); |
| 128 | let mut out = Vec::new(); |
| 129 | let got = no_panic(&format!("len {len} published {published}"), || { |
| 130 | rx.try_recv(&mut out) |
| 131 | }); |
| 132 | let err = got.expect_err("hostile length accepted"); |
| 133 | assert_eq!(err.kind(), kind, "len {len} published {published}: {err:?}"); |
| 134 | assert!(out.is_empty(), "bytes delivered for a refused record"); |
| 135 | assert_eq!(rx.records_received(), 0); |
| 136 | assert_poisoned(&mut rx, &err); |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | // --------------------------------------------------------------------------------------- |
| 142 | // Hostile writer: index wrap |
| 143 | // --------------------------------------------------------------------------------------- |
| 144 | |
| 145 | #[test] |
| 146 | fn hostile_writer_index_wrap_cannot_make_the_reader_panic_or_read_outside_the_ring() { |
| 147 | let capacity = 256u64; |
| 148 | for start in STARTS { |
| 149 | // (published head, expected refusal kind) |
| 150 | let cases: [(u64, &str); 8] = [ |
| 151 | (start.wrapping_add(capacity + 8), "IndexOutOfRange"), |
| 152 | (start.wrapping_add(u64::MAX - 7), "IndexOutOfRange"), |
| 153 | (start.wrapping_sub(8), "IndexOutOfRange"), |
| 154 | (start.wrapping_add(1 << 63), "IndexOutOfRange"), |
| 155 | (start ^ (1 << 62), "IndexOutOfRange"), |
| 156 | (start.wrapping_add(4), "IndexMisaligned"), |
| 157 | (start.wrapping_add(capacity + 1), "IndexMisaligned"), |
| 158 | (u64::MAX, "IndexMisaligned"), |
| 159 | ]; |
| 160 | for (head, kind) in cases { |
| 161 | let (region, _tx, mut rx) = hostile_ring(cfg(capacity as usize, 64, start)); |
| 162 | ctl(®ion, layout::HEAD).store(head, Ordering::Release); |
| 163 | let mut out = Vec::new(); |
| 164 | let err = no_panic(&format!("start {start} head {head}"), || { |
| 165 | rx.try_recv(&mut out) |
| 166 | }) |
| 167 | .expect_err("hostile head accepted"); |
| 168 | assert_eq!(err.kind(), kind, "start {start} head {head}: {err:?}"); |
| 169 | assert_poisoned(&mut rx, &err); |
| 170 | } |
| 171 | |
| 172 | // Head moved back behind a value the reader already saw (but not behind its tail). |
| 173 | let (region, mut tx, mut rx) = hostile_ring(cfg(capacity as usize, 64, start)); |
| 174 | let mut out = Vec::new(); |
| 175 | tx.try_send(&payload(0, 10)).unwrap(); |
| 176 | let after_one = ctl(®ion, layout::HEAD).load(Ordering::Acquire); |
| 177 | tx.try_send(&payload(1, 10)).unwrap(); |
| 178 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 179 | ctl(®ion, layout::HEAD).store(after_one, Ordering::Release); |
| 180 | let err = no_panic("head regressed", || rx.try_recv(&mut out)).unwrap_err(); |
| 181 | assert_eq!(err.kind(), "IndexRegressed", "{err:?}"); |
| 182 | assert_eq!(rx.records_received(), 1); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn honest_indices_wrap_past_u64_max_and_the_ring_end_without_loss() { |
| 188 | for start in STARTS { |
| 189 | let (_region, mut tx, mut rx) = hostile_ring(cfg(128, 100, start)); |
| 190 | let mut out = Vec::new(); |
| 191 | for i in 0..2_000u64 { |
| 192 | let p = payload(i, (i % 101) as usize); |
| 193 | assert!( |
| 194 | tx.try_send(&p).unwrap(), |
| 195 | "record {i} did not fit an empty ring" |
| 196 | ); |
| 197 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 198 | assert_eq!(out, p, "record {i} start {start}"); |
| 199 | } |
| 200 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Empty)); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // --------------------------------------------------------------------------------------- |
| 205 | // Hostile writer: torn frames |
| 206 | // --------------------------------------------------------------------------------------- |
| 207 | |
| 208 | #[test] |
| 209 | fn hostile_writer_torn_frames_are_refused_and_payloads_are_copied_out_before_validation() { |
| 210 | // 1. A record published before its payload was written: head ends inside it. |
| 211 | for start in STARTS { |
| 212 | for published in [8u64, 16, 24, 40] { |
| 213 | let (region, _tx, mut rx) = hostile_ring(cfg(256, 200, start)); |
| 214 | data(®ion, start).store(64, Ordering::Relaxed); |
| 215 | ctl(®ion, layout::HEAD).store(start.wrapping_add(published), Ordering::Release); |
| 216 | let mut out = Vec::new(); |
| 217 | let err = no_panic("torn record", || rx.try_recv(&mut out)).unwrap_err(); |
| 218 | assert_eq!(err.kind(), "TornRecord", "{err:?}"); |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | // 2. A frame cut across a record that is then closed: the G1 stream reader refuses it |
| 223 | // with a typed refusal, never a panic or a partial frame. |
| 224 | let frame = sample_frames() |
| 225 | .iter() |
| 226 | .map(|f| encode_frame(f).unwrap()) |
| 227 | .max_by_key(Vec::len) |
| 228 | .unwrap(); |
| 229 | for cut in [1usize, 8, 15, 16, 17, frame.len() / 2, frame.len() - 1] { |
| 230 | let region = RingRegion::in_process(cfg(1 << 16, 1 << 14, 0)).unwrap(); |
| 231 | let (mut tx, _) = region.endpoints(Side::Creator); |
| 232 | tx.send(&frame[..cut]).unwrap(); |
| 233 | tx.close(); |
| 234 | let mut conn = FrameConn::new(region.stream(Side::Attacher), WireLimits::default()); |
| 235 | let err = no_panic("torn frame", || conn.recv()).unwrap_err(); |
| 236 | assert_eq!( |
| 237 | err.code, |
| 238 | RefusalCode::WireFrameMalformed, |
| 239 | "cut {cut}: {err:?}" |
| 240 | ); |
| 241 | } |
| 242 | |
| 243 | // 3. Garbage where a frame should be: typed refusal from the frame decoder. |
| 244 | let region = RingRegion::in_process(cfg(1 << 16, 1 << 14, 0)).unwrap(); |
| 245 | let (mut tx, _) = region.endpoints(Side::Creator); |
| 246 | let mut bad = frame.clone(); |
| 247 | bad[0] ^= 0xFF; |
| 248 | tx.send(&bad).unwrap(); |
| 249 | let mut conn = FrameConn::new(region.stream(Side::Attacher), WireLimits::default()); |
| 250 | assert_eq!( |
| 251 | conn.recv().unwrap_err().code, |
| 252 | RefusalCode::WireFrameMalformed |
| 253 | ); |
| 254 | |
| 255 | // 4. The writer keeps rewriting the record's bytes while the reader copies it out. The |
| 256 | // reader validates its own copy, so deciding twice on that copy gives the same |
| 257 | // answer whatever the writer does meanwhile. |
| 258 | let frames: Vec<Vec<u8>> = sample_frames() |
| 259 | .iter() |
| 260 | .map(|f| encode_frame(f).unwrap()) |
| 261 | .collect(); |
| 262 | // A mutator that races the sender can also land on a header word; the reader then |
| 263 | // refuses (and is poisoned), and the next round starts on a fresh region. |
| 264 | let (mut decoded, mut refused, mut ring_refused) = (0u32, 0u32, 0u32); |
| 265 | for round in 0..200u64 { |
| 266 | if decoded + refused >= 5_000 { |
| 267 | break; |
| 268 | } |
| 269 | let region = RingRegion::in_process(cfg(1 << 12, 1 << 11, u64::MAX - 7)).unwrap(); |
| 270 | let stop = Arc::new(AtomicBool::new(false)); |
| 271 | let mutator = { |
| 272 | let (region, stop) = (region.clone(), stop.clone()); |
| 273 | std::thread::spawn(move || { |
| 274 | let mut r = SplitMix(round); |
| 275 | let c = *region.config(); |
| 276 | let base = c.ring_base(0) + CONTROL_WORDS; |
| 277 | while !stop.load(Ordering::Relaxed) { |
| 278 | // Only words above 2^20: payload words, not a record header (len at |
| 279 | // most max_record, seq below 2,000) unless the race described above. |
| 280 | let w = ®ion.words()[base + r.below((c.capacity / 8) as u64) as usize]; |
| 281 | let v = w.load(Ordering::Relaxed); |
| 282 | if v > 1 << 20 { |
| 283 | w.store(v ^ (1 << r.below(64)), Ordering::Relaxed); |
| 284 | } |
| 285 | } |
| 286 | }) |
| 287 | }; |
| 288 | let (mut tx, _) = region.endpoints(Side::Creator); |
| 289 | let (_, mut rx) = region.endpoints(Side::Attacher); |
| 290 | let mut out = Vec::new(); |
| 291 | for i in 0..2_000usize { |
| 292 | if tx.try_send(&frames[i % frames.len()]).is_err() { |
| 293 | break; |
| 294 | } |
| 295 | match no_panic("record rewritten during copy", || rx.try_recv(&mut out)) { |
| 296 | Ok(RecvStatus::Record) => { |
| 297 | let a = decode_frame(&out, &WireLimits::default()); |
| 298 | let b = decode_frame(&out, &WireLimits::default()); |
| 299 | assert_eq!(a, b, "decision changed on the private copy"); |
| 300 | if a.is_ok() { |
| 301 | decoded += 1 |
| 302 | } else { |
| 303 | refused += 1 |
| 304 | } |
| 305 | } |
| 306 | Ok(other) => panic!("published record not read: {other:?}"), |
| 307 | Err(_) => { |
| 308 | ring_refused += 1; |
| 309 | break; |
| 310 | } |
| 311 | } |
| 312 | } |
| 313 | stop.store(true, Ordering::Relaxed); |
| 314 | mutator.join().unwrap(); |
| 315 | } |
| 316 | // Both outcomes of validating a rewritten copy were reached. |
| 317 | assert!( |
| 318 | decoded > 0 && refused > 0, |
| 319 | "decoded {decoded} refused {refused} ring refusals {ring_refused}" |
| 320 | ); |
| 321 | } |
| 322 | |
| 323 | // --------------------------------------------------------------------------------------- |
| 324 | // Hostile writer: no record accepted twice |
| 325 | // --------------------------------------------------------------------------------------- |
| 326 | |
| 327 | #[test] |
| 328 | fn hostile_writer_cannot_make_the_reader_accept_a_record_twice() { |
| 329 | for start in STARTS { |
| 330 | let c = cfg(256, 64, start); |
| 331 | let mut out = Vec::new(); |
| 332 | |
| 333 | // Replay: the writer copies record 0 (sequence 0) to the next position. |
| 334 | let (region, mut tx, mut rx) = hostile_ring(c); |
| 335 | let p0 = payload(0, 20); |
| 336 | tx.try_send(&p0).unwrap(); |
| 337 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 338 | let span = record_span(p0.len()) as u64; |
| 339 | for k in 0..span / 8 { |
| 340 | let v = data(®ion, start.wrapping_add(8 * k)).load(Ordering::Relaxed); |
| 341 | data(®ion, start.wrapping_add(span + 8 * k)).store(v, Ordering::Relaxed); |
| 342 | } |
| 343 | ctl(®ion, layout::HEAD).store(start.wrapping_add(2 * span), Ordering::Release); |
| 344 | let err = no_panic("replayed record", || rx.try_recv(&mut out)).unwrap_err(); |
| 345 | assert_eq!( |
| 346 | err, |
| 347 | RingRefusal::SequenceMismatch { |
| 348 | expected: 1, |
| 349 | found: 0 |
| 350 | } |
| 351 | ); |
| 352 | assert_eq!(rx.records_received(), 1); |
| 353 | |
| 354 | // Rewind: the writer moves head back behind a record already read, to republish it. |
| 355 | let (region, mut tx, mut rx) = hostile_ring(c); |
| 356 | tx.try_send(&payload(0, 20)).unwrap(); |
| 357 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 358 | ctl(®ion, layout::HEAD).store(start, Ordering::Release); |
| 359 | let err = no_panic("rewound head", || rx.try_recv(&mut out)).unwrap_err(); |
| 360 | assert_eq!(err.kind(), "IndexOutOfRange", "{err:?}"); |
| 361 | ctl(®ion, layout::HEAD).store(start.wrapping_add(span), Ordering::Release); |
| 362 | assert_eq!(rx.try_recv(&mut out), Err(err)); |
| 363 | assert_eq!(rx.records_received(), 1); |
| 364 | |
| 365 | // The writer resets the shared tail word (the reader's published position): the |
| 366 | // reader keeps its own tail, so the record is not read again. |
| 367 | let (region, mut tx, mut rx) = hostile_ring(c); |
| 368 | tx.try_send(&payload(0, 20)).unwrap(); |
| 369 | tx.try_send(&payload(1, 20)).unwrap(); |
| 370 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 371 | assert_eq!(out, payload(0, 20)); |
| 372 | ctl(®ion, layout::TAIL).store(start, Ordering::Release); |
| 373 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 374 | assert_eq!(out, payload(1, 20)); |
| 375 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Empty)); |
| 376 | assert_eq!(rx.records_received(), 2); |
| 377 | |
| 378 | // Skip: a record whose sequence number jumps ahead is refused (nothing skipped). |
| 379 | let (region, _tx, mut rx) = hostile_ring(c); |
| 380 | data(®ion, start).store(4, Ordering::Relaxed); |
| 381 | data(®ion, start.wrapping_add(8)).store(5, Ordering::Relaxed); |
| 382 | ctl(®ion, layout::HEAD).store(start.wrapping_add(24), Ordering::Release); |
| 383 | let err = rx.try_recv(&mut out).unwrap_err(); |
| 384 | assert_eq!(err.kind(), "SequenceMismatch"); |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | /// Random hostile pokes of control and data words, interleaved with honest sends. Checks, |
| 389 | /// per step: no panic; a delivered record is no longer than `max_record`; the receiver's |
| 390 | /// accepted count rises by exactly one per delivered record and never otherwise; once |
| 391 | /// refused it stays refused. Records delivered before the first poke equal what was sent. |
| 392 | #[test] |
| 393 | fn hostile_writer_random_pokes_never_panic_and_never_deliver_a_record_twice() { |
| 394 | let mut kinds = std::collections::BTreeMap::<&'static str, u32>::new(); |
| 395 | let boundary = |r: &mut SplitMix, start: u64, cap: u64| -> u64 { |
| 396 | let v = [ |
| 397 | 0, |
| 398 | 1, |
| 399 | 7, |
| 400 | 8, |
| 401 | 16, |
| 402 | cap - 8, |
| 403 | cap, |
| 404 | cap + 8, |
| 405 | u64::MAX, |
| 406 | u64::MAX - 7, |
| 407 | 1 << 63, |
| 408 | r.next(), |
| 409 | ]; |
| 410 | let base = if r.below(2) == 0 { start } else { 0 }; |
| 411 | base.wrapping_add(v[r.below(v.len() as u64) as usize]) |
| 412 | }; |
| 413 | for seed in 0..3_000u64 { |
| 414 | let mut r = SplitMix(seed); |
| 415 | let start = STARTS[(seed % 4) as usize]; |
| 416 | let c = cfg(256, 96, start); |
| 417 | let (region, mut tx, mut rx) = hostile_ring(c); |
| 418 | let mut out = Vec::new(); |
| 419 | let mut sent = VecDeque::new(); |
| 420 | let mut poked = false; |
| 421 | let mut refused: Option<RingRefusal> = None; |
| 422 | for step in 0..200u32 { |
| 423 | match r.below(8) { |
| 424 | 0..=2 => { |
| 425 | let i = u64::from(step); |
| 426 | let p = payload(i, r.below(97) as usize); |
| 427 | if let Ok(true) = tx.try_send(&p) { |
| 428 | sent.push_back(p); |
| 429 | } |
| 430 | } |
| 431 | 3 => { |
| 432 | poked = true; |
| 433 | let off = [ |
| 434 | layout::HEAD, |
| 435 | layout::TAIL, |
| 436 | layout::CLOSED, |
| 437 | layout::DOORBELL, |
| 438 | layout::RX_SLEEPING, |
| 439 | ][r.below(5) as usize]; |
| 440 | ctl(®ion, off).store(boundary(&mut r, start, 256), Ordering::Release); |
| 441 | } |
| 442 | 4 => { |
| 443 | poked = true; |
| 444 | let at = start.wrapping_add(8 * r.below(32)); |
| 445 | data(®ion, at).store(boundary(&mut r, 0, 96), Ordering::Relaxed); |
| 446 | } |
| 447 | _ => { |
| 448 | let before = rx.records_received(); |
| 449 | let got = no_panic(&format!("seed {seed} step {step}"), || { |
| 450 | rx.try_recv(&mut out) |
| 451 | }); |
| 452 | match got { |
| 453 | Ok(RecvStatus::Record) => { |
| 454 | assert!(refused.is_none(), "delivered after a refusal"); |
| 455 | assert_eq!(rx.records_received(), before + 1); |
| 456 | assert!(out.len() <= c.max_record); |
| 457 | let want = sent.pop_front(); |
| 458 | if !poked { |
| 459 | assert_eq!(Some(&out), want.as_ref(), "seed {seed}"); |
| 460 | } |
| 461 | } |
| 462 | Ok(_) => assert_eq!(rx.records_received(), before), |
| 463 | Err(e) => { |
| 464 | assert_eq!(rx.records_received(), before); |
| 465 | if let Some(first) = &refused { |
| 466 | assert_eq!(&e, first, "refusal changed"); |
| 467 | } else { |
| 468 | *kinds.entry(e.kind()).or_default() += 1; |
| 469 | refused = Some(e); |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 | // The pokes reach every peer-fault check (the detectors are live). |
| 478 | for k in [ |
| 479 | "IndexOutOfRange", |
| 480 | "IndexMisaligned", |
| 481 | "IndexRegressed", |
| 482 | "TornRecord", |
| 483 | "LengthOverCap", |
| 484 | "SequenceMismatch", |
| 485 | ] { |
| 486 | assert!(kinds.contains_key(k), "{k} never hit: {kinds:?}"); |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | /// Negative control: a reader that trusts the writer (no masking, no length, index or |
| 491 | /// sequence check) fails on the same hostile inputs, so the tests above can fail. |
| 492 | #[test] |
| 493 | fn negative_control_trusting_reader_panics_or_accepts_twice_on_the_same_inputs() { |
| 494 | /// Reads like `try_recv` but trusts every word it loads. |
| 495 | fn trusting_recv(region: &RingRegion, tail: &mut u64, out: &mut Vec<u8>) -> bool { |
| 496 | let c = region.config(); |
| 497 | let base = c.ring_base(0); |
| 498 | let w = region.words(); |
| 499 | let head = w[base + layout::HEAD].load(Ordering::Acquire); |
| 500 | if head == *tail { |
| 501 | return false; |
| 502 | } |
| 503 | // No mask: the position is used as given. |
| 504 | let at = |i: u64| base + CONTROL_WORDS + (i / 8) as usize % (1 << 40); |
| 505 | let len = w[at(*tail)].load(Ordering::Relaxed) as usize; |
| 506 | out.clear(); |
| 507 | for k in 0..len.div_ceil(8) { |
| 508 | let word = w[at(tail.wrapping_add(16 + 8 * k as u64))].load(Ordering::Relaxed); |
| 509 | out.extend_from_slice(&word.to_le_bytes()); |
| 510 | } |
| 511 | out.truncate(len); |
| 512 | *tail = tail.wrapping_add(record_span(len) as u64); |
| 513 | true |
| 514 | } |
| 515 | |
| 516 | // Bad length: reads past the ring, which in safe Rust is a panic. |
| 517 | let (region, _tx, _rx) = hostile_ring(cfg(256, 120, 0)); |
| 518 | data(®ion, 0).store(4096, Ordering::Relaxed); |
| 519 | ctl(®ion, layout::HEAD).store(64, Ordering::Release); |
| 520 | let mut out = Vec::new(); |
| 521 | let mut tail = 0u64; |
| 522 | assert!( |
| 523 | catch_unwind(AssertUnwindSafe(|| trusting_recv( |
| 524 | ®ion, &mut tail, &mut out |
| 525 | ))) |
| 526 | .is_err(), |
| 527 | "trusting reader survived a bad length" |
| 528 | ); |
| 529 | |
| 530 | // Index wrap: an honest record near the end of the index space, read without the mask. |
| 531 | let (region, mut tx, _rx) = hostile_ring(cfg(256, 120, u64::MAX - 7)); |
| 532 | tx.try_send(&payload(0, 40)).unwrap(); |
| 533 | let mut tail = u64::MAX - 7; |
| 534 | assert!( |
| 535 | catch_unwind(AssertUnwindSafe(|| trusting_recv( |
| 536 | ®ion, &mut tail, &mut out |
| 537 | ))) |
| 538 | .is_err(), |
| 539 | "trusting reader survived the index wrap" |
| 540 | ); |
| 541 | |
| 542 | // Replay: the trusting reader accepts record 0 twice. |
| 543 | let (region, mut tx, _rx) = hostile_ring(cfg(256, 64, 0)); |
| 544 | let p0 = payload(0, 20); |
| 545 | tx.try_send(&p0).unwrap(); |
| 546 | let mut tail = 0u64; |
| 547 | assert!(trusting_recv(®ion, &mut tail, &mut out)); |
| 548 | let span = record_span(p0.len()) as u64; |
| 549 | for k in 0..span / 8 { |
| 550 | let v = data(®ion, 8 * k).load(Ordering::Relaxed); |
| 551 | data(®ion, span + 8 * k).store(v, Ordering::Relaxed); |
| 552 | } |
| 553 | ctl(®ion, layout::HEAD).store(2 * span, Ordering::Release); |
| 554 | assert!(trusting_recv(®ion, &mut tail, &mut out)); |
| 555 | assert_eq!(out, p0, "the trusting reader accepted record 0 twice"); |
| 556 | } |
| 557 | |
| 558 | // --------------------------------------------------------------------------------------- |
| 559 | // Model test: nothing lost, nothing duplicated |
| 560 | // --------------------------------------------------------------------------------------- |
| 561 | |
| 562 | /// A random schedule of sends and receives against a queue model, over small rings that |
| 563 | /// wrap thousands of times, with starts on both sides of the 2^64 index wrap. Every record |
| 564 | /// received equals the model's next record; a full ring is full by the model's own count; |
| 565 | /// after close, the ring drains exactly the model and then reports the end. |
| 566 | #[test] |
| 567 | fn model_test_no_frame_is_lost_or_duplicated() { |
| 568 | let mut total = 0u64; |
| 569 | for seed in 0..400u64 { |
| 570 | let mut r = SplitMix(seed ^ 0xD1CE); |
| 571 | let capacity = [64usize, 128, 256, 1024][(seed % 4) as usize]; |
| 572 | let max_record = |
| 573 | [1usize, 8, capacity / 2, capacity - RECORD_HEADER_LEN][(seed / 4 % 4) as usize]; |
| 574 | let start = STARTS[(seed / 16 % 4) as usize]; |
| 575 | let (_region, mut tx, mut rx) = hostile_ring(cfg(capacity, max_record, start)); |
| 576 | let mut model: VecDeque<Vec<u8>> = VecDeque::new(); |
| 577 | let mut in_ring = 0usize; |
| 578 | let mut out = Vec::new(); |
| 579 | let mut next = 0u64; |
| 580 | for _ in 0..3_000 { |
| 581 | if r.below(2) == 0 { |
| 582 | let len = if r.below(4) == 0 { |
| 583 | max_record |
| 584 | } else { |
| 585 | r.below(max_record as u64 + 1) as usize |
| 586 | }; |
| 587 | let p = payload(next, len); |
| 588 | let fits = in_ring + record_span(len) <= capacity; |
| 589 | assert_eq!( |
| 590 | tx.try_send(&p), |
| 591 | Ok(fits), |
| 592 | "seed {seed}: full by model {fits}" |
| 593 | ); |
| 594 | if fits { |
| 595 | in_ring += record_span(len); |
| 596 | model.push_back(p); |
| 597 | next += 1; |
| 598 | } |
| 599 | } else { |
| 600 | match rx.try_recv(&mut out).unwrap() { |
| 601 | RecvStatus::Record => { |
| 602 | let want = model.pop_front().expect("record the model never sent"); |
| 603 | assert_eq!(out, want, "seed {seed}"); |
| 604 | in_ring -= record_span(want.len()); |
| 605 | total += 1; |
| 606 | } |
| 607 | RecvStatus::Empty => assert!(model.is_empty(), "seed {seed}: lost record"), |
| 608 | RecvStatus::Closed => panic!("closed before close"), |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | tx.close(); |
| 613 | while let Some(want) = model.pop_front() { |
| 614 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Record)); |
| 615 | assert_eq!(out, want); |
| 616 | total += 1; |
| 617 | } |
| 618 | assert_eq!(rx.try_recv(&mut out), Ok(RecvStatus::Closed)); |
| 619 | assert_eq!(rx.records_received(), tx.records_sent()); |
| 620 | } |
| 621 | assert!(total > 100_000, "model exercised only {total} records"); |
| 622 | } |
| 623 | |
| 624 | /// Two threads over a sealed shared mapping, the receiver on a second mapping of the same |
| 625 | /// memory: every record arrives once, in order, intact. |
| 626 | #[cfg(target_os = "linux")] |
| 627 | #[test] |
| 628 | fn model_test_two_threads_two_mappings_no_record_lost_or_duplicated() { |
| 629 | let c = cfg(1 << 12, 1 << 10, u64::MAX - 1023); |
| 630 | let region = RingRegion::create_shared(c).unwrap(); |
| 631 | let other = RingRegion::attach_shared(®ion.attach_path().unwrap(), c).unwrap(); |
| 632 | let n = 200_000u64; |
| 633 | let writer = { |
| 634 | let region = region.clone(); |
| 635 | std::thread::spawn(move || { |
| 636 | let (mut tx, _) = region.endpoints(Side::Creator); |
| 637 | for i in 0..n { |
| 638 | tx.send(&payload(i, (i % 1025) as usize)).unwrap(); |
| 639 | } |
| 640 | }) |
| 641 | }; |
| 642 | let (_, mut rx) = other.endpoints(Side::Attacher); |
| 643 | let mut out = Vec::new(); |
| 644 | let mut i = 0u64; |
| 645 | while rx.recv(&mut out).unwrap() { |
| 646 | assert_eq!(out, payload(i, (i % 1025) as usize), "record {i}"); |
| 647 | i += 1; |
| 648 | } |
| 649 | writer.join().unwrap(); |
| 650 | assert_eq!(i, n); |
| 651 | } |
| 652 | |
| 653 | // --------------------------------------------------------------------------------------- |
| 654 | // Shared region, processes, hostile reader, session |
| 655 | // --------------------------------------------------------------------------------------- |
| 656 | |
| 657 | #[cfg(target_os = "linux")] |
| 658 | #[test] |
| 659 | fn attached_peer_cannot_shrink_or_grow_the_sealed_region() { |
| 660 | let c = cfg(1 << 12, 1 << 10, 0); |
| 661 | let region = RingRegion::create_shared(c).unwrap(); |
| 662 | let f = std::fs::OpenOptions::new() |
| 663 | .read(true) |
| 664 | .write(true) |
| 665 | .open(region.attach_path().unwrap()) |
| 666 | .unwrap(); |
| 667 | assert!(f.set_len(64).is_err(), "peer shrank the region"); |
| 668 | assert!(f.set_len(1 << 24).is_err(), "peer grew the region"); |
| 669 | assert_eq!(f.metadata().unwrap().len(), c.region_bytes() as u64); |
| 670 | } |
| 671 | |
| 672 | #[cfg(target_os = "linux")] |
| 673 | #[test] |
| 674 | fn attach_refuses_an_unsealed_wrong_size_or_mismatched_region() { |
| 675 | let c = cfg(1 << 12, 1 << 10, 0); |
| 676 | // An ordinary file of the right size: no seals, so the peer could shrink it. |
| 677 | let dir = temp_dir("g3-unsealed"); |
| 678 | let path = dir.join("ring"); |
| 679 | std::fs::write(&path, vec![0u8; c.region_bytes()]).unwrap(); |
| 680 | let err = RingRegion::attach_shared(&path, c).err().unwrap(); |
| 681 | assert_eq!(err.code, RefusalCode::WireRingViolation, "{err:?}"); |
| 682 | assert!(err.message.contains("RegionNotSealed"), "{}", err.message); |
| 683 | |
| 684 | let region = RingRegion::create_shared(c).unwrap(); |
| 685 | let path = region.attach_path().unwrap(); |
| 686 | let bigger = RingConfig { |
| 687 | capacity: 1 << 13, |
| 688 | ..c |
| 689 | }; |
| 690 | let err = RingRegion::attach_shared(&path, bigger).err().unwrap(); |
| 691 | assert!(err.message.contains("RegionSize"), "{}", err.message); |
| 692 | let moved = RingConfig { start: 64, ..c }; |
| 693 | let err = RingRegion::attach_shared(&path, moved).err().unwrap(); |
| 694 | assert!(err.message.contains("HeaderMismatch"), "{}", err.message); |
| 695 | } |
| 696 | |
| 697 | #[cfg(target_os = "linux")] |
| 698 | #[test] |
| 699 | fn cross_process_ring_delivers_every_record_once_in_order() { |
| 700 | const ENV: &str = "SYNAPSE_G3_CHILD_RING"; |
| 701 | const N: u64 = 50_000; |
| 702 | let c = cfg(1 << 14, 1 << 12, u64::MAX - 4095); |
| 703 | if let Ok(path) = std::env::var(ENV) { |
| 704 | // Child: attach and send on ring 1. |
| 705 | let region = RingRegion::attach_shared(std::path::Path::new(&path), c).unwrap(); |
| 706 | let (mut tx, _) = region.endpoints(Side::Attacher); |
| 707 | for i in 0..N { |
| 708 | tx.send(&payload(i, (i % 4097) as usize)).unwrap(); |
| 709 | } |
| 710 | return; |
| 711 | } |
| 712 | let region = RingRegion::create_shared(c).unwrap(); |
| 713 | let mut child = std::process::Command::new(std::env::current_exe().unwrap()) |
| 714 | .args([ |
| 715 | "--exact", |
| 716 | "cross_process_ring_delivers_every_record_once_in_order", |
| 717 | "--test-threads=1", |
| 718 | "--quiet", |
| 719 | ]) |
| 720 | .env(ENV, region.attach_path().unwrap()) |
| 721 | .stdout(std::process::Stdio::null()) |
| 722 | .spawn() |
| 723 | .unwrap(); |
| 724 | let (_, mut rx) = region.endpoints(Side::Creator); |
| 725 | let mut out = Vec::new(); |
| 726 | let mut i = 0u64; |
| 727 | while rx.recv(&mut out).unwrap() { |
| 728 | assert_eq!(out, payload(i, (i % 4097) as usize), "record {i}"); |
| 729 | i += 1; |
| 730 | } |
| 731 | assert!(child.wait().unwrap().success()); |
| 732 | assert_eq!(i, N); |
| 733 | } |
| 734 | |
| 735 | #[test] |
| 736 | fn hostile_reader_tail_is_refused_by_the_sender() { |
| 737 | for start in STARTS { |
| 738 | for (tail, kind) in [ |
| 739 | (start.wrapping_add(64), "IndexOutOfRange"), |
| 740 | (start.wrapping_sub(8), "IndexOutOfRange"), |
| 741 | (start.wrapping_add(1 << 63), "IndexOutOfRange"), |
| 742 | (start.wrapping_add(3), "IndexMisaligned"), |
| 743 | ] { |
| 744 | let (region, mut tx, _rx) = hostile_ring(cfg(256, 64, start)); |
| 745 | tx.try_send(&payload(0, 8)).unwrap(); |
| 746 | ctl(®ion, layout::TAIL).store(tail, Ordering::Release); |
| 747 | let err = no_panic("hostile tail", || tx.try_send(&payload(1, 8))).unwrap_err(); |
| 748 | assert_eq!(err.kind(), kind, "start {start} tail {tail}: {err:?}"); |
| 749 | } |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn ring_refusal_reaches_the_frame_transport_as_wire_ring_violation() { |
| 755 | let (region, _tx, _rx) = hostile_ring(cfg(1 << 12, 1 << 10, 0)); |
| 756 | ctl(®ion, layout::HEAD).store(1 << 20, Ordering::Release); |
| 757 | let mut conn = FrameConn::new(region.stream(Side::Attacher), WireLimits::default()); |
| 758 | let err = conn.recv().unwrap_err(); |
| 759 | assert_eq!(err.code, RefusalCode::WireRingViolation, "{err:?}"); |
| 760 | } |
| 761 | |
| 762 | #[cfg(target_os = "linux")] |
| 763 | #[test] |
| 764 | fn ring_stream_carries_the_g1_session_and_acknowledges_durable_changes() { |
| 765 | let dir = temp_dir("g3-session"); |
| 766 | let fx = ChainFixture::new(2, None); |
| 767 | let mut last = None; |
| 768 | { |
| 769 | let region = RingRegion::create_shared(RingConfig::default()).unwrap(); |
| 770 | let store = open_store(&dir); |
| 771 | let srv = server(&fx, store.clone()); |
| 772 | let path = region.attach_path().unwrap(); |
| 773 | let attached = RingRegion::attach_shared(&path, RingConfig::default()).unwrap(); |
| 774 | let s = srv.clone(); |
| 775 | let t = std::thread::spawn(move || s.serve(attached.stream(Side::Attacher))); |
| 776 | let mut client = |
| 777 | WireClient::connect(region.stream(Side::Creator), WireLimits::default()).unwrap(); |
| 778 | let shared: Vec<u8> = (0..3000).map(|i| (i * 7) as u8).collect(); |
| 779 | for i in 0..20u64 { |
| 780 | let new: Vec<u8> = (0..3967).map(|j| (i as usize * 13 + j) as u8).collect(); |
| 781 | let (p_new, p_shared) = (format!("ring/c{i}.rs"), format!("ring/s{i}.rs")); |
| 782 | let (env, blobs) = envelope( |
| 783 | &fx.agent, |
| 784 | &format!("ring-{i}"), |
| 785 | &[(p_new.as_str(), new), (p_shared.as_str(), shared.clone())], |
| 786 | &[], |
| 787 | 100 + i, |
| 788 | ); |
| 789 | let mut nonce = [0u8; 32]; |
| 790 | nonce[..8].copy_from_slice(&i.to_le_bytes()); |
| 791 | let req = submit_request(&fx.agent, fx.chain.clone(), &env, nonce, 100 + i).unwrap(); |
| 792 | let rep = client.submit(&req, &blobs).unwrap(); |
| 793 | assert!(!rep.accepted.duplicate); |
| 794 | assert_eq!(rep.wanted, if i == 0 { 2 } else { 1 }, "change {i}"); |
| 795 | last = Some(rep.accepted.wal_seq); |
| 796 | } |
| 797 | assert_eq!(store.read().committed_seq(), last.unwrap()); |
| 798 | drop(client); |
| 799 | let stats = t.join().unwrap().unwrap(); |
| 800 | assert!(stats.frames_received >= 60); |
| 801 | } |
| 802 | // Durable: a fresh open of the directory sees every acknowledged change. |
| 803 | let reopened = open_store(&dir); |
| 804 | assert_eq!(reopened.read().committed_seq(), last.unwrap()); |
| 805 | } |