minerva 0.2.0

Causal ordering for distributed systems
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//! The epoch schedule tape (S289): the fleet driven by a byte tape.
//!
//! The generated properties in `properties.rs` drive the lifecycle through
//! *scaffolded* shapes: every declaration lands on a drained fleet
//! (`cross_boundary` settles before declaring), severance brackets a whole
//! window, and crashes land at generated indices inside a fixed
//! settle-declare-window-drain skeleton. This module removes the scaffold:
//! bytes are interpreted as ops (edits, declarations, delivery steps,
//! severances, heals, crash-restarts) with *no implicit settling and no
//! implicit delivery*, so declarations race live traffic, windows open on
//! unsettled fleets, members crash mid-round, and delivery is withheld for
//! as long as the tape likes. The laws stay the charter's fleet-wide ones,
//! asserted after the final heal and drain: one generation, one lineage,
//! one seal record, one pair state, byte-identical frames (all via
//! [`assert_converged`]), plus *quiescence* (no open window, no parked
//! notes: convergence alone cannot see a symmetric wedge, every replica
//! identically stuck mid-round), with every per-seal law riding the
//! replica's own internal asserts.
//!
//! # The two delivery arms, and the libFuzzer leg (S331)
//!
//! S289 left the tape half-addressed: bytes chose *when* a delivery
//! happened, while the fabric's seed chose *which* envelope moved, so
//! transport order was sampled rather than driven (ruling R-71's
//! counterweight). [`Delivery::Addressed`] closes that gap by reading the
//! tape from both ends: ops from the front, one delivery address per
//! `Step` from the back, the two cursors meeting in the middle. The pinned
//! seeded tapes keep their exact schedules ([`Delivery::Seeded`] draws as
//! before), so nothing this module already caught is disturbed.
//!
//! The addressed arm is what the coverage-guided leg drives.
//! [`run_addressed_tape`] is the whole exposure: under `--cfg fuzzing`
//! (never a feature, never the public surface) `metis::fuzz_harness`
//! re-exports it and the `epoch_schedule_tape` fuzz target calls it, so
//! libFuzzer runs *this* fleet recipe rather than a copy. R-71 named the
//! copy the wrong shape at this scale: the replica recipe alone runs
//! past two thousand lines, and a fork drifts from the tree it defends.
//! The proptest arm above stays the always-on gate for both doors.
//!
//! # The displaced-window instrument (the S288-session stray, closed here)
//!
//! The seal retains two distinct sets, the candidate addresses and the
//! protocol declaration-dot ledger, and their difference (a delivered
//! declaration displaced by its own causal predecessor, its dot surviving
//! only in the ledger) is load-bearing for the consignment's coverage
//! check. The stray asked whether any *generated* suite reaches
//! displaced-then-sealed windows or whether that corner lives only in
//! directed machine-level pins. The answer this module records: under the
//! fleet's honest replica recipe the corner is *unreachable by
//! construction*, not merely unsampled. A declaration's cut can cover a
//! peer declaration's dot only by delivering that declaration's note (the
//! note is the dot's only delivery vehicle, and the fleet's have-sets
//! count event dots, never context spillover); a same-generation delivery
//! that records the dot also opens the local window, and an open window
//! refuses the local mint (`WindowOpen`), so no honest replica can ever
//! mint the covering declaration displacement requires. Cross-generation
//! arrivals refuse as `BeyondHorizon` or an address miss instead of
//! displacing. The evidence stays evidence-grade, not a theorem: the
//! [`displaced_dots`] detector is pinned against the machine-driven
//! fixture (`wire::lifecycle::displaced_window`, the S284 R4 window), the
//! generated sweep counts zero across its whole corpus, and the sweep is
//! a *loud tripwire*: if a future recipe change opens an honest path to
//! the corner, `the_honest_recipe_never_displaces_a_declaration` fails
//! and the record above must be rewritten, coverage celebrated rather
//! than restored.

extern crate alloc;

use alloc::collections::BTreeMap;
#[cfg(test)]
use alloc::vec::Vec;
use core::num::NonZeroUsize;

// The pins and the property arm are the `cargo test` gate; the fuzz build
// compiles the interpreter alone, so it resolves no dev-dependency.
#[cfg(test)]
use proptest::prelude::*;

use crate::metis::{EpochAddress, Epochs, SealedEpoch};

use super::fabric::Fabric;
#[cfg(test)]
use super::fabric::Schedule;
use super::replica::Replica;
use super::{act, assert_converged, crash, fleet_of, resync};

const ROSTER: [u32; 3] = [1, 2, 3];

/// The per-run op cap: tapes stay fast even when every op is a crash.
const MAX_OPS: usize = 48;

/// What a tape run left behind, for directed pins and the instrument.
struct TapeOutcome {
    /// Sealed epochs per replica at the end (converged, so one number).
    seals: usize,
    /// Displaced declaration dots accumulated per sealed generation *as
    /// each seal appears*, before the retention horizon can evict it (a
    /// retained-lineage read alone would let an old displaced window
    /// vanish after two later seals and the tripwire's zero lie).
    displaced: usize,
    /// An order-sensitive digest of the run's *shape*: after every op the
    /// fleet's per-replica generation, open-candidate count, and parked
    /// count fold into a rolling hash. Final states converge by law, so
    /// two runs differing only in delivery order agree on everything a
    /// closing assert can see; the trace is where the difference lives,
    /// and it is what makes the addressing door falsifiable.
    trace: u64,
}

/// The trace's mixing step (the splitmix finalizer, as in [`Schedule`]):
/// order-sensitive, cheap, and deterministic forever.
const fn mix(state: u64) -> u64 {
    let mut z = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// Folds one observation of the whole fleet into the run trace.
fn observe_shape(fleet: &BTreeMap<u32, Replica>, trace: u64) -> u64 {
    let mut trace = trace;
    for (&id, replica) in fleet {
        trace = mix(trace ^ u64::from(id));
        trace = mix(trace ^ replica.generation());
        trace = mix(trace ^ u64::try_from(replica.epochs().candidates().count()).expect("bounded"));
        trace = mix(trace ^ u64::try_from(replica.parked_len()).expect("bounded"));
    }
    trace
}

/// Counts `sealed`'s displaced declaration dots: the ledger entries whose
/// address is neither the winning declaration nor a retired candidate,
/// exactly the accepted-but-non-candidate records the S284 R4 fixture
/// pins into golden bytes.
fn displaced_dots(sealed: &SealedEpoch) -> usize {
    let generation = sealed.declaration().generation();
    sealed
        .declaration_dots()
        .filter(|&dot| {
            EpochAddress::try_from_parts(generation, dot.into())
                .is_ok_and(|address| address != sealed.declaration() && !sealed.contains(address))
        })
        .count()
}

/// Folds every currently retained seal into the per-generation
/// displacement ledger, first sighting wins (the fold is idempotent, so
/// harvesting after every op accumulates each generation exactly once,
/// before the horizon can evict it).
fn harvest_displacement(epochs: &Epochs, ledger: &mut BTreeMap<u64, usize>) {
    for sealed in epochs.sealed() {
        let _ = ledger
            .entry(sealed.declaration().generation())
            .or_insert_with(|| displaced_dots(sealed));
    }
}

/// Post-drain quiescence: a healed, drained fleet must hold no open
/// epoch window and no parked notes. Convergence alone cannot see a
/// *symmetric* wedge (every replica identically stuck mid-round), so the
/// tape demands quiescence beside it.
pub(super) fn assert_quiescent(fleet: &BTreeMap<u32, Replica>) {
    for (&id, replica) in fleet {
        assert_eq!(
            replica.epochs().candidates().count(),
            0,
            "replica {id}: an epoch window is still open after the closing drain",
        );
        assert_eq!(
            replica.parked_len(),
            0,
            "replica {id}: parked notes survived the closing drain",
        );
    }
}

/// How a tape's deliveries choose their envelope.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Delivery {
    /// The S289 arm: bytes choose *when* a delivery happens, the seed
    /// chooses *which* envelope moves. Every pinned tape reads this way,
    /// and its schedules are byte-identical to the pre-S331 interpreter.
    Seeded,
    /// The S331 arm: the tape's second end chooses the envelope too, so
    /// transport order is addressed rather than sampled (ruling R-71's
    /// counterweight named this as the prerequisite for reaching a wedge
    /// class that needs envelope-level addressing, and the libFuzzer leg
    /// is the caller that wanted the depth).
    Addressed,
}

/// The tape read from both ends: ops from the front, delivery addresses
/// from the back, the two cursors meeting in the middle. The split is
/// decided by consumption rather than by a length header, so a
/// coverage-guided mutator never has to keep a header consistent with the
/// body: appending bytes lengthens the address supply, and prepending
/// bytes lengthens the op program.
pub(super) struct Cursor<'a> {
    bytes: &'a [u8],
    front: usize,
    back: usize,
}

impl<'a> Cursor<'a> {
    /// The op region starts after the fabric seed.
    pub(super) fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            front: bytes.len().min(8),
            back: bytes.len(),
        }
    }

    /// The next `(opcode, argument)` pair, or `None` once the cursors meet.
    pub(super) fn op(&mut self) -> Option<(u8, u8)> {
        if self.front + 2 > self.back {
            return None;
        }
        let pair = (self.bytes[self.front], self.bytes[self.front + 1]);
        self.front += 2;
        Some(pair)
    }

    /// The next delivery address, or `None` once the cursors meet (a short
    /// tape simply falls back to the seeded draw, so it still drains).
    pub(super) fn address(&mut self) -> Option<u8> {
        if self.back <= self.front {
            return None;
        }
        self.back -= 1;
        self.bytes.get(self.back).copied()
    }
}

/// Interprets a byte tape over a fresh three-replica fleet.
///
/// The first eight bytes seed the fabric's delivery schedule (which note
/// moves when a step runs under [`Delivery::Seeded`], and which deliveries
/// duplicate under both arms); the rest are consumed two at a time as
/// `(opcode, argument)`, capped at [`MAX_OPS`]. `opcode % 8` selects the
/// op; the argument selects operands (`station = argument % 3`, positions
/// from the remaining bits). No op settles the fleet and none delivers
/// implicitly:
///
/// * `0` Insert: the station weaves at a visible position.
/// * `1` Delete: the station observed-removes a visible element.
/// * `2` Move: the station mints a movement testimony.
/// * `3` Declare: the station tries to declare an epoch *now*, however
///   unsettled the fleet is; a `Decline` is a lawful outcome and absorbed.
/// * `4` Step: deliver `argument % 32 + 1` notes. Under
///   [`Delivery::Seeded`] the fabric's seed picks each envelope; under
///   [`Delivery::Addressed`] each delivery consumes one byte from the
///   tape's second end and that byte indexes the deliverable set, so the
///   driver addresses transport order directly (and falls back to the
///   seeded draw once the two cursors meet).
/// * `5` Sever: cut the station off (accumulating; traffic waits).
/// * `6` Heal: restore full connectivity.
/// * `7` Crash: rebuild the station from its journal and run the repair
///   lane; repair notes enter the scheduled pool like any other traffic.
///
/// After the tape: heal, drain, and assert the fleet-wide convergence
/// laws. Any window still open when the tape ends completes during the
/// drain (every round note is in the pool or regenerated by handlers), so
/// the laws are asserted against a quiet fleet. The closing drain is
/// seeded under both arms: it is the settling step whose job is to reach
/// quiescence, not an adversary, and addressing it would only change
/// which order the same residue lands in.
fn interpret(tape: &[u8]) -> TapeOutcome {
    interpret_with(tape, Delivery::Seeded)
}

/// [`interpret`] under an explicit delivery arm. The op alphabet, the
/// closing heal-and-drain, and every asserted law are identical; only the
/// chooser behind a `Step` differs.
fn interpret_with(tape: &[u8], delivery: Delivery) -> TapeOutcome {
    let mut seed = [0u8; 8];
    for (slot, byte) in seed.iter_mut().zip(tape.iter()) {
        *slot = *byte;
    }
    let mut cursor = Cursor::new(tape);

    let mut fleet = fleet_of(&ROSTER, NonZeroUsize::new(2).expect("positive"));
    let mut fabric = Fabric::new(u64::from_le_bytes(seed), &ROSTER, 7);
    let mut displacement: BTreeMap<u64, usize> = BTreeMap::new();
    let mut trace = 0u64;

    for _ in 0..MAX_OPS {
        let Some((opcode, argument)) = cursor.op() else {
            break;
        };
        let station = ROSTER[usize::from(argument) % ROSTER.len()];
        let at = (usize::from(argument) / 3) % 8;
        let to = (usize::from(argument) / 24) % 8;
        match opcode % 8 {
            0 => {
                let _ = act(&mut fabric, &mut fleet, station, |replica, out| {
                    replica.insert_visible(at, out)
                });
            }
            1 => {
                let _ = act(&mut fabric, &mut fleet, station, |replica, out| {
                    replica.delete_visible(at, out)
                });
            }
            2 => {
                // The deferral duty is the consumer's (an adopted replica
                // mints no movement testimonies while its window is open,
                // the recipe's duty list), so the tape honors it the way
                // `play_window` does: adopted replicas edit natively.
                if fleet[&station].adopted() {
                    let _ = act(&mut fabric, &mut fleet, station, |replica, out| {
                        replica.delete_visible(at, out)
                    });
                } else {
                    let _ = act(&mut fabric, &mut fleet, station, |replica, out| {
                        replica.move_visible(at, Some(to), out)
                    });
                }
            }
            3 => {
                // Mid-traffic declaration: acceptance and decline are both
                // lawful; the machine's refusal vocabulary is the shield.
                let _ = act(&mut fabric, &mut fleet, station, |replica, out| {
                    replica.try_declare(out)
                });
            }
            4 => {
                let steps = usize::from(argument) % 32 + 1;
                for _ in 0..steps {
                    let address = match delivery {
                        Delivery::Seeded => None,
                        Delivery::Addressed => cursor.address(),
                    };
                    let _ = fabric.step_addressed(&mut fleet, address);
                }
            }
            5 => fabric.sever(&[station]),
            6 => fabric.heal(),
            _ => {
                crash(
                    &mut fleet,
                    &ROSTER,
                    NonZeroUsize::new(2).expect("positive"),
                    station,
                );
                resync(&mut fabric, &fleet, station);
            }
        }
        // Harvest every replica's retained seals each op, so a displaced
        // generation is counted before the horizon can evict it.
        for replica in fleet.values() {
            harvest_displacement(replica.epochs(), &mut displacement);
        }
        trace = observe_shape(&fleet, trace);
    }

    fabric.heal();
    fabric.drain(&mut fleet);
    // Deliberately no ambient repair here: the resync lane runs only
    // where the recipe runs it (at restarts), so repair-lane holes stay
    // visible instead of being papered over by a closing anti-entropy
    // round. The first such hole this choice caught is the restate
    // floor-standing fix (the sealed join re-stated as every member's
    // proven under-claim); a future wedge surfacing here is a finding,
    // not a flake.
    assert_converged(&fleet);
    assert_quiescent(&fleet);

    for replica in fleet.values() {
        harvest_displacement(replica.epochs(), &mut displacement);
    }
    let witness = fleet.get(&ROSTER[0]).expect("roster member");
    TapeOutcome {
        seals: witness.seals.len(),
        displaced: displacement.values().sum(),
        trace,
    }
}

/// The libFuzzer leg's whole entry point (R-71's named path, S331): one
/// byte slice, one fleet, the charter's laws, no return value a fuzz
/// target could be tempted to interpret. It runs the *addressed* arm
/// because the coverage-guided mutator's edge over the in-tree proptest
/// driver is exactly the ability to steer transport order, which the
/// seeded arm hides behind a hash of the first eight bytes.
///
/// This is the reason the harness is exposed rather than copied: at the
/// fleet's scale a fuzz-crate copy of the replica recipe would be a fork
/// that drifts from the tree it is supposed to defend.
pub(in crate::metis) fn run_addressed_tape(tape: &[u8]) {
    let _ = interpret_with(tape, Delivery::Addressed);
}

#[cfg(test)]
#[test]
fn a_causally_covered_weave_still_crosses_the_boundary() {
    // Station 2 sees station 3's delete before its weave. Causal coverage
    // must not masquerade as possession of the weave's ordering locus when
    // adoption rebuilds the open window from its log.
    let tape = [
        69, 55, 93, 189, 113, 147, 226, 26, 99, 45, 28, 220, 157, 10, 195, 4, 204, 50, 21, 213, 13,
        222, 227, 181, 6, 194, 199, 216, 149, 176, 247, 213, 20, 98, 17, 155, 143, 97, 213, 13,
        136, 248, 255, 139, 116, 225, 11, 200, 41, 212, 207, 208, 212, 150, 102, 243, 251, 198, 85,
        250, 84, 14, 38, 34, 150, 177, 27, 203, 27, 141, 212, 58, 123, 232, 48, 2,
    ];
    let _ = interpret(&tape);
}

#[cfg(test)]
proptest! {
    #![proptest_config(ProptestConfig::with_cases(64))]

    /// The scaffold-free law: any byte tape (racing declarations, withheld
    /// delivery, accumulated severance, mid-round crashes) heals, drains,
    /// and converges to one record.
    #[test]
    fn any_byte_tape_heals_drains_and_converges(
        tape in prop::collection::vec(any::<u8>(), 0..104),
    ) {
        let _ = interpret(&tape);
    }

    /// The same law under the addressed arm: with the tape choosing which
    /// envelope moves as well as when, the fleet still heals, drains, and
    /// converges. This is the in-tree gate for the door the libFuzzer leg
    /// drives, so the fuzz target can never be the only thing exercising
    /// it (the ladder's rungs are complements, never upgrades).
    #[test]
    fn any_addressed_tape_heals_drains_and_converges(
        tape in prop::collection::vec(any::<u8>(), 0..104),
    ) {
        run_addressed_tape(&tape);
    }
}

#[cfg(test)]
#[test]
fn test_an_address_picks_the_envelope_the_seed_would_not() {
    // The addressing door is not decoration: two addresses over the same
    // pool deliver to two different stations. Station 1 weaves once, so
    // the pool holds exactly the broadcast pair (to 2 and to 3); address
    // 0 and address 1 index that pair directly, and the fleet reads back
    // which one moved. Without this pin the addressed arm could silently
    // degrade to the seeded draw and every law would still pass.
    let mut delivered = Vec::new();
    for address in [0u8, 1u8] {
        let mut fleet = fleet_of(&ROSTER, NonZeroUsize::new(2).expect("positive"));
        let mut fabric = Fabric::new(0x5f33_1000, &ROSTER, 0);
        let _ = act(&mut fabric, &mut fleet, ROSTER[0], |replica, out| {
            replica.insert_visible(0, out)
        });
        assert!(fabric.step_addressed(&mut fleet, Some(address)));
        let heard: Vec<u32> = fleet
            .iter()
            .filter(|(_, replica)| !replica.effective_order().is_empty())
            .map(|(&id, _)| id)
            .collect();
        assert_eq!(heard.len(), 2, "the weaver plus exactly one receiver");
        delivered.push(heard);
    }
    assert_ne!(
        delivered[0], delivered[1],
        "two addresses must select two different envelopes",
    );
}

#[cfg(test)]
#[test]
fn test_the_addressed_arm_schedules_what_the_seed_would_not() {
    // The arm must not quietly degrade into the seeded one. The fabric
    // pin above proves the *door* reads its address; this proves the
    // address reaches the *protocol*, and it isolates the variable the
    // way comparing the two arms cannot: consuming an address moves the
    // back cursor, so the arms run different op programs and would
    // "diverge" even under a chooser that discarded every address. Here
    // the op program is held fixed and only the address region varies,
    // so a divergence can only have come through the chooser.
    // The op region is the eight seed bytes plus two bytes per op, so a
    // head of exactly `8 + 2 * MAX_OPS` bytes is a full op program and
    // the front cursor can never reach the tail. The tail is longer than
    // the largest possible delivery count (`MAX_OPS` bursts of 32), so
    // the back cursor can never reach the head either: the two regions
    // are disjoint by construction, which is what makes the comparison
    // below a controlled one.
    let mut bytes = Schedule::new(0x5f33_1a00);
    let mut divergences = 0usize;
    for _ in 0..32 {
        let head: Vec<u8> = (0..8 + 2 * MAX_OPS)
            .map(|_| u8::try_from(bytes.below(256)).expect("bounded"))
            .collect();
        let mut left = head.clone();
        let mut right = head;
        for _ in 0..(MAX_OPS * 32 + 64) {
            left.push(u8::try_from(bytes.below(256)).expect("bounded"));
            right.push(u8::try_from(bytes.below(256)).expect("bounded"));
        }
        if interpret_with(&left, Delivery::Addressed).trace
            != interpret_with(&right, Delivery::Addressed).trace
        {
            divergences += 1;
        }
    }
    assert!(
        divergences > 0,
        "thirty-two op programs read the same lifecycle under two address \
         regions each; the address is not reaching the fabric",
    );
}

#[cfg(test)]
#[test]
fn test_the_detector_reads_the_machine_driven_displaced_window() {
    // The detector's own pin: the S284 R4 fixture (a two-station window
    // whose later declaration is displaced by its arriving predecessor)
    // reads exactly one displaced dot, and an ordinary sealed window
    // reads zero (checked below over the directed tape's seal). The
    // harvest fold is pinned beside it: repeated harvesting accumulates
    // the generation exactly once (the idempotence the per-op harvest
    // relies on to count a seal before the horizon evicts it).
    let (epochs, sealed) = super::super::wire::lifecycle::displaced_window();
    assert_eq!(displaced_dots(&sealed), 1);

    let mut ledger = BTreeMap::new();
    harvest_displacement(&epochs, &mut ledger);
    harvest_displacement(&epochs, &mut ledger);
    assert_eq!(ledger.len(), 1);
    assert_eq!(ledger.values().sum::<usize>(), 1);
}

#[cfg(test)]
#[test]
fn test_a_directed_tape_seals_mid_traffic_declarations() {
    // One deterministic pass through the whole op alphabet: edits on all
    // three stations, partial delivery, a severance bracketing a crash,
    // a declaration raced against undelivered traffic (declined or
    // accepted, the machine chooses lawfully), a heal, a settled
    // declaration, and the closing drain. The run must seal at least one
    // generation and, per the instrument's standing claim, displace
    // nothing.
    let mut tape: Vec<u8> = alloc::vec![7, 7, 7, 7, 7, 7, 7, 7];
    tape.extend([
        0, 0, // station 1 inserts
        0, 1, // station 2 inserts
        0, 2, // station 3 inserts
        4, 31, // deliver a burst
        1, 3, // station 1 deletes
        5, 1, // sever station 2
        0, 4, // station 2 edits while severed
        7, 1, // crash and repair station 2 behind the severance
        3, 0, // station 1 declares against withheld traffic
        4, 63, // deliver what can move
        6, 0, // heal
        4, 63, // deliver the released residue
        3, 2, // a second declaration attempt (its own verdict)
        2, 5, // a movement testimony
        5, 0, // sever station 1...
        0,
        0, // ...which then edits behind the severance, so the tape
           // ends with a blocked delta only the interpreter's closing
           // heal-and-drain can deliver
    ]);
    let outcome = interpret(&tape);
    assert!(
        outcome.seals >= 1,
        "the drained tape seals at least one generation",
    );
    assert_eq!(outcome.displaced, 0, "the honest recipe never displaces");
}

#[cfg(test)]
#[test]
fn the_honest_recipe_never_displaces_a_declaration() {
    // The instrument, and a loud tripwire. Sixty-four seeded tapes (a
    // fixed pseudo-random corpus, deterministic forever) drive the full
    // alphabet; the displaced count must read zero across every retained
    // lineage, because the honest recipe cannot mint the covering
    // declaration displacement requires (the module doc carries the
    // argument). If this ever fails, the fleet has grown an honest path
    // to the displaced corner: update the module doc and the S289 record,
    // convert this sweep into coverage, and celebrate rather than
    // restore.
    let mut bytes = Schedule::new(0x5f28_9d00);
    let mut total_seals = 0usize;
    let mut total_displaced = 0usize;
    for _ in 0..64 {
        let length = bytes.below(96);
        let tape: Vec<u8> = (0..length)
            .map(|_| u8::try_from(bytes.below(256)).expect("bounded"))
            .collect();
        // Both arms over the one corpus: the seeded schedules are the
        // S289 record, and the addressed ones are genuinely different
        // interleavings of the same op programs (S331), so the claim now
        // binds the door the fuzz leg drives as well as the pinned one.
        for outcome in [
            interpret_with(&tape, Delivery::Seeded),
            interpret_with(&tape, Delivery::Addressed),
        ] {
            total_seals += outcome.seals;
            total_displaced += outcome.displaced;
        }
    }
    assert_eq!(
        total_displaced, 0,
        "an honest schedule reached the displaced corner; see the module doc",
    );
    // The sweep is not vacuous: some tapes must actually seal.
    assert!(total_seals > 0, "the corpus exercises real lifecycles");
}
#[cfg(test)]
#[test]
fn test_a_sealed_windows_native_note_redelivers_after_the_next_adoption() {
    // The tape's second catch, pinned from the review gate's worktree run
    // (the proptest-shrunk bytes verbatim): a duplicated native note from
    // an already-sealed window redelivers after its receiver has adopted
    // the NEXT window's winner. The recipe's old assert ("honest native
    // traffic names the one fixed winner") declared that lawful
    // redelivery dishonest; the cure routes a non-matching native note
    // through the verdict lanes the handler already owns (the sealed
    // branch's duplicate fold, the pre-adoption gate), and this tape
    // replays the exact schedule that found it.
    let tape: alloc::vec::Vec<u8> = alloc::vec![
        127, 224, 47, 1, 31, 24, 196, 131, 4, 0, 1, 0, 33, 0, 83, 63, 43, 93, 45, 193, 14, 5, 68,
        150, 240, 246, 201, 66, 93, 214, 151, 159, 44, 12, 11, 237, 142, 247, 171, 132, 150, 221,
        128, 86, 105, 2, 212, 186, 146, 34, 142, 48, 137, 194, 253, 102, 159, 15, 154, 1, 115, 247,
        59, 192, 102,
    ];
    let _ = interpret(&tape);
}