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
//! The bootstrap admission door (S292): a verified lineage proof becomes
//! a joiner's recognizer horizon.
//!
//! The one law is agreement: a machine bootstrapped from a proof exported
//! by a sealed machine *equals* that machine, so every recognizer verdict,
//! duplicate absorption, and future lifecycle round is inherited rather
//! than re-pinned. Beside it, the refusal suite drives each typed
//! [`EpochBootstrapError`] through hand-built seal frames: every refusal
//! is a state no honest export can carry, constructible only by a hostile
//! or corrupted frame, and each is pinned with its evidence.

extern crate alloc;

use alloc::vec;
use alloc::vec::Vec;
use core::num::NonZeroUsize;

use crate::kairos::Kairos;
use crate::metis::{
    Cut, Dot, DotSet, EpochAddress, EpochBootstrapError, EpochRefusal, Epochs, LineageProofEntry,
    LineageProofRecord, SealRecord, SealedEpoch, Stability, VersionVector, Vouched,
};

use super::wire::lifecycle::displaced_window;
use crate::metis::dot::RawDot;

/// Builds an identity literal. Panics on the non-dot counter zero (R-91).
#[track_caller]
fn d(station: u32, counter: u64) -> Dot {
    Dot::from_parts(station, counter).expect("test literal names the non-dot counter zero")
}

/// One epoch address from raw parts, unwrapped: the fixture spelling.
fn address(generation: u64, dot: (u32, u64)) -> EpochAddress {
    EpochAddress::try_from_parts(generation, dot).unwrap()
}

/// A witnessed cut over `entries`.
fn cut(entries: &[(u32, u64)]) -> Cut {
    let mut vector = VersionVector::new();
    for &(station, counter) in entries {
        vector.observe(station, counter);
    }
    Cut::from_witnessed(vector)
}

/// A proof over `seals` with opaque boundary-node values.
fn proof(seals: Vec<SealRecord>) -> LineageProofRecord {
    LineageProofRecord::try_new(
        seals
            .into_iter()
            .map(|seal| LineageProofEntry::new(seal, [0u8; 32]))
            .collect(),
    )
    .unwrap()
}

/// Hand-builds one canonical `SEAL_WIRE_V1` frame and decodes it: the
/// only door to a [`SealRecord`] whose retained sets the machine would
/// never produce, which is exactly what the bootstrap refusal suite
/// needs (the decode layer is structural by design; the door owns the
/// semantics).
fn seal_record(
    winner: (u64, (u32, u64)),
    candidates: &[(u64, (u32, u64))],
    ledger: &[(u32, u64)],
    join: &[(u32, u64)],
) -> SealRecord {
    let mut frame = vec![0x01];
    frame.extend_from_slice(&winner.0.to_be_bytes());
    frame.extend_from_slice(&winner.1.0.to_be_bytes());
    frame.extend_from_slice(&winner.1.1.to_be_bytes());
    frame.extend_from_slice(&u32::try_from(candidates.len()).unwrap().to_be_bytes());
    for &(generation, dot) in candidates {
        frame.extend_from_slice(&generation.to_be_bytes());
        frame.extend_from_slice(&dot.0.to_be_bytes());
        frame.extend_from_slice(&dot.1.to_be_bytes());
    }
    frame.extend_from_slice(&u32::try_from(ledger.len()).unwrap().to_be_bytes());
    for &(station, counter) in ledger {
        frame.extend_from_slice(&station.to_be_bytes());
        frame.extend_from_slice(&counter.to_be_bytes());
    }
    frame.extend_from_slice(&DotSet::from_witnessed(&cut(join)).to_bytes());
    SealRecord::from_bytes(&frame).expect("the fixture frame is structurally canonical")
}

/// Re-mints a declaration through the licensed door: a tracker whose
/// watermark is exactly `at`, a fresh dot above it (the lifecycle wire
/// suite's twin helper).
fn declaration(
    roster: &[u32],
    dot: Dot,
    tick: u64,
    at: &[(u32, u64)],
) -> crate::metis::Declaration {
    let witnessed = cut(at);
    let mut stability = Stability::new(roster.iter().copied());
    for &station in roster {
        stability.report_cut(station, &witnessed).unwrap();
    }
    let mut epochs = Epochs::new(roster.iter().copied(), NonZeroUsize::new(1).unwrap());
    epochs
        .declare(
            dot,
            Kairos::new(tick, 0u16, 1, 0u16),
            &stability,
            &Cut::bottom(),
        )
        .expect("the fixture dot is fresh above the fixture cut")
}

/// The agreement law: bootstrapping from a sealed machine's exported
/// proof reconstructs that machine exactly, displaced-ledger distinction
/// included, so recognizer behavior is inherited wholesale.
#[test]
fn test_bootstrap_equals_the_exporting_machine() {
    let (exporter, sealed) = displaced_window();
    let lineage = proof(vec![SealRecord::from_sealed(&sealed)]);
    let joiner = Epochs::bootstrap([1, 2], NonZeroUsize::new(2).unwrap(), &lineage).unwrap();
    assert_eq!(joiner, exporter);
}

/// The duplicate contract answers identically on the joiner: covered
/// old-addressed dots absorb, uncovered ones refuse with evidence,
/// off-lineage addresses refuse as beyond the horizon, and post-seal
/// replays of the round's own records absorb as no-ops.
#[test]
fn test_bootstrap_recognizer_holds_the_duplicate_contract() {
    let (_, sealed) = displaced_window();
    let epoch = sealed.declaration();
    let lineage = proof(vec![SealRecord::from_sealed(&sealed)]);
    let mut joiner = Epochs::bootstrap([1, 2], NonZeroUsize::new(2).unwrap(), &lineage).unwrap();

    // Covered by the sealed join {1: 3, 2: 3}: the duplicate verdict.
    assert_eq!(joiner.recognize(epoch, d(1, 3)), Ok(()));
    // Above it: the typed violation.
    assert_eq!(
        joiner.recognize(epoch, d(2, 4)),
        Err(EpochRefusal::AddressMiss {
            epoch,
            dot: RawDot::new(2, 4)
        })
    );
    // An address never sealed: the machine refuses to guess.
    let foreign = address(1, (1, 3));
    assert_eq!(
        joiner.recognize(foreign, d(1, 1)),
        Err(EpochRefusal::BeyondHorizon { epoch: foreign })
    );

    // Replays of the sealed round's own records absorb as no-ops: the
    // winning declaration re-minted verbatim, then both report kinds.
    let replay = declaration(&[1, 2], d(2, 3), 7, &[(1, 2), (2, 2)]);
    let stability = Stability::new([1, 2]);
    assert_eq!(joiner.deliver(replay, &stability, &Cut::bottom()), Ok(()));
    assert_eq!(
        joiner.confirm(epoch, &Vouched::trust(1, cut(&[(1, 3), (2, 3)]))),
        Ok(())
    );
    assert_eq!(joiner.adopt_report(epoch, &Vouched::trust(2, 3)), Ok(()));
}

/// A joiner is a full lifecycle participant: it declares, confirms,
/// adopts, and seals the next generation, and a second bootstrap from
/// the grown proof equals the grown machine (the agreement law composes
/// across generations).
#[test]
fn test_bootstrap_continues_the_lifecycle() {
    let (_, sealed) = displaced_window();
    let lineage = proof(vec![SealRecord::from_sealed(&sealed)]);
    let mut joiner = Epochs::bootstrap([1, 2], NonZeroUsize::new(2).unwrap(), &lineage).unwrap();

    // Drive generation 2 to its seal through the ordinary rounds.
    let mut stability = Stability::new([1, 2]);
    let at = cut(&[(1, 3), (2, 3)]);
    for station in [1, 2] {
        stability.report_cut(station, &at).unwrap();
    }
    let next = joiner
        .declare(
            d(1, 9),
            Kairos::new(11, 0u16, 1, 0u16),
            &stability,
            &Cut::bottom(),
        )
        .expect("the joiner's watermark licenses the next declaration");
    assert_eq!(next.address().generation(), 2);
    let delivered = cut(&[(1, 9), (2, 3)]);
    let mut progressed = Stability::new([1, 2]);
    for station in [1, 2] {
        progressed.report_cut(station, &delivered).unwrap();
        joiner
            .confirm(next.address(), &Vouched::trust(station, delivered.clone()))
            .unwrap();
    }
    let _ = joiner.adopt(1, 9, &progressed).expect("confirmed");
    joiner
        .adopt_report(next.address(), &Vouched::trust(2, 3))
        .unwrap();
    let second = joiner.try_seal(&progressed).expect("seals").clone();
    assert_eq!(second.declaration().generation(), 2);

    // Export both generations; the fresh joiner equals the grown one.
    let grown = proof(vec![
        SealRecord::from_sealed(&sealed),
        SealRecord::from_sealed(&second),
    ]);
    let second_joiner = Epochs::bootstrap([1, 2], NonZeroUsize::new(2).unwrap(), &grown).unwrap();
    assert_eq!(second_joiner, joiner);
}

/// The two restore doors compose: a bootstrapped machine's own local
/// checkpoint rehydrates to the same machine.
#[test]
fn test_bootstrap_then_snapshot_round_trips() {
    let (_, sealed) = displaced_window();
    let lineage = proof(vec![SealRecord::from_sealed(&sealed)]);
    let joiner = Epochs::bootstrap([1, 2], NonZeroUsize::new(2).unwrap(), &lineage).unwrap();
    let restored =
        Epochs::rehydrate(&joiner.snapshot(), [1, 2], NonZeroUsize::new(2).unwrap()).unwrap();
    assert_eq!(restored, joiner);
}

/// A proof may start mid-history (the exporter's horizon already evicted
/// older generations): the joiner opens at the newest seal's successor
/// and refuses evicted generations as beyond the horizon.
#[test]
fn test_bootstrap_admits_a_truncated_suffix() {
    let five = seal_record((5, (1, 4)), &[(5, (1, 4))], &[(1, 4)], &[(1, 4), (2, 2)]);
    let six = seal_record((6, (2, 5)), &[(6, (2, 5))], &[(2, 5)], &[(1, 4), (2, 5)]);
    let lineage = proof(vec![five, six]);
    let joiner = Epochs::bootstrap([1, 2], NonZeroUsize::new(3).unwrap(), &lineage).unwrap();
    assert_eq!(joiner.sealed().count(), 2);
    assert_eq!(joiner.recognize(address(6, (2, 5)), d(1, 4)), Ok(()));
    let evicted = address(4, (1, 1));
    assert_eq!(
        joiner.recognize(evicted, d(1, 1)),
        Err(EpochRefusal::BeyondHorizon { epoch: evicted })
    );
}

/// The empty proof refuses: fresh join already has its door, and a
/// second, weaker spelling of the same claim is exactly what the kind-9
/// boundary refuses on the other side of the seam.
#[test]
fn test_bootstrap_refuses_the_empty_proof() {
    let empty = LineageProofRecord::try_new(Vec::new()).unwrap();
    assert_eq!(
        Epochs::bootstrap([1, 2], NonZeroUsize::new(2).unwrap(), &empty),
        Err(EpochBootstrapError::EmptyProof)
    );
}

/// A proof past the declared horizon refuses loudly; trimming to the
/// newest suffix is the caller's visible act.
#[test]
fn test_bootstrap_refuses_past_the_horizon() {
    let one = seal_record((1, (1, 1)), &[(1, (1, 1))], &[(1, 1)], &[(1, 1)]);
    let two = seal_record((2, (1, 2)), &[(2, (1, 2))], &[(1, 2)], &[(1, 2)]);
    let lineage = proof(vec![one, two]);
    assert_eq!(
        Epochs::bootstrap([1], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::HorizonExceeded {
            generations: 2,
            horizon: 1
        })
    );
}

/// A proof at or directly below the generation ceiling refuses: at
/// `u64::MAX` no successor exists, and at `u64::MAX - 1` the next
/// window would open at the ceiling itself, which `try_seal` refuses
/// terminally, so admitting the proof would hand the joiner a wedge
/// (the review-round finding).
#[test]
fn test_bootstrap_refuses_the_generation_ceiling() {
    for newest in [u64::MAX, u64::MAX - 1] {
        let ceiling = seal_record((newest, (1, 1)), &[(newest, (1, 1))], &[(1, 1)], &[(1, 1)]);
        let lineage = proof(vec![ceiling]);
        assert_eq!(
            Epochs::bootstrap([1], NonZeroUsize::new(1).unwrap(), &lineage),
            Err(EpochBootstrapError::CeilingGeneration),
            "newest generation {newest} must refuse"
        );
    }
}

/// The lifecycle near the ceiling: a proof ending at `u64::MAX - 2`
/// admits, its next window (at `u64::MAX - 1`) seals normally, and the
/// window after that (at the ceiling itself) completes every round yet
/// never seals: `try_seal`'s terminal refusal fires before any
/// mutation, so lineage and the open window are untouched rather than
/// aliased (the review-round finding's continuation half).
#[test]
fn test_the_ceiling_window_never_seals() {
    let near = seal_record(
        (u64::MAX - 2, (1, 1)),
        &[(u64::MAX - 2, (1, 1))],
        &[(1, 1)],
        &[(1, 1)],
    );
    let lineage = proof(vec![near]);
    let mut joiner = Epochs::bootstrap([1], NonZeroUsize::new(3).unwrap(), &lineage).unwrap();

    // One full round at u64::MAX - 1: seals normally.
    let drive = |epochs: &mut Epochs, dot: Dot, tick: u64| {
        let mut stability = Stability::new([1]);
        stability
            .report_cut(1, &cut(&[(1, dot.counter() - 1)]))
            .unwrap();
        let declaration = epochs
            .declare(
                dot,
                Kairos::new(tick, 0u16, 1, 0u16),
                &stability,
                &Cut::bottom(),
            )
            .expect("licensed");
        let delivered = cut(&[(1, dot.counter())]);
        let mut progressed = Stability::new([1]);
        progressed.report_cut(1, &delivered).unwrap();
        epochs
            .confirm(declaration.address(), &Vouched::trust(1, delivered.clone()))
            .unwrap();
        let _ = epochs
            .adopt(1, dot.counter(), &progressed)
            .expect("confirmed");
        epochs.try_seal(&progressed).map(SealedEpoch::declaration)
    };
    let sealed = drive(&mut joiner, d(1, 2), 5);
    assert_eq!(sealed.map(EpochAddress::generation), Some(u64::MAX - 1));

    // The ceiling window completes its rounds and refuses to seal.
    assert_eq!(drive(&mut joiner, d(1, 3), 7), None);
    assert!(joiner.adopted(), "the round itself completed");
    assert_eq!(
        joiner
            .sealed()
            .last()
            .map(|sealed| sealed.declaration().generation()),
        Some(u64::MAX - 1),
        "lineage is untouched by the refused ceiling seal"
    );
}

/// A sealed join whose support leaves the roster refuses: `recognize`
/// grants the duplicate verdict off the join alone, so an installed
/// foreign entry would absorb non-roster traffic the deliver door
/// refuses. The foreign station rides only the join (candidates and
/// ledger stay lawful), so this pin holds the join walk alone.
#[test]
fn test_bootstrap_refuses_a_foreign_join_station() {
    let crafted = seal_record((1, (1, 1)), &[(1, (1, 1))], &[(1, 1)], &[(1, 1), (9, 1)]);
    let lineage = proof(vec![crafted]);
    assert_eq!(
        Epochs::bootstrap([1, 2], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::ForeignStation {
            generation: 1,
            station: 9
        })
    );
}

/// A candidate claiming a foreign generation refuses: one window seals
/// one generation.
#[test]
fn test_bootstrap_refuses_a_candidate_outside_its_generation() {
    let crafted = seal_record((1, (1, 1)), &[(2, (1, 1))], &[(1, 1)], &[(1, 1)]);
    let lineage = proof(vec![crafted]);
    assert_eq!(
        Epochs::bootstrap([1], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::CandidateOutsideGeneration {
            generation: 1,
            found: 2
        })
    );
}

/// A candidate minted outside the caller's roster refuses: the deliver
/// door would have refused it before it could ever be retained. The
/// foreign station rides only the candidate set (the winner and ledger
/// stay lawful), so this pin holds the candidate walk alone and cannot
/// be masked by the ledger's twin check.
#[test]
fn test_bootstrap_refuses_a_foreign_candidate_station() {
    let crafted = seal_record(
        (1, (1, 1)),
        &[(1, (1, 1)), (1, (9, 1))],
        &[(1, 1)],
        &[(1, 1)],
    );
    let lineage = proof(vec![crafted]);
    assert_eq!(
        Epochs::bootstrap([1, 2], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::ForeignStation {
            generation: 1,
            station: 9
        })
    );
}

/// A ledger dot minted outside the roster refuses through the same
/// vocabulary. The join stays roster-clean, so this pin holds the
/// ledger walk alone: were its roster check dropped, the dot would
/// misclassify as uncovered rather than foreign.
#[test]
fn test_bootstrap_refuses_a_foreign_ledger_station() {
    let crafted = seal_record((1, (1, 1)), &[(1, (1, 1))], &[(1, 1), (9, 1)], &[(1, 1)]);
    let lineage = proof(vec![crafted]);
    assert_eq!(
        Epochs::bootstrap([1, 2], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::ForeignStation {
            generation: 1,
            station: 9
        })
    );
}

/// A seal whose winner is missing from its own candidate set refuses:
/// such a recognizer could not absorb the winning declaration's replay.
#[test]
fn test_bootstrap_refuses_a_winner_outside_its_candidates() {
    let crafted = seal_record((1, (1, 1)), &[], &[(1, 1)], &[(1, 1)]);
    let lineage = proof(vec![crafted]);
    assert_eq!(
        Epochs::bootstrap([1], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::WinnerNotCandidate {
            generation: 1,
            winner: d(1, 1)
        })
    );
}

/// A ledger dot above the sealed join refuses: the seal canonicalizes
/// its ledger against the join, so the claim is one no machine can seal.
#[test]
fn test_bootstrap_refuses_an_uncovered_ledger_dot() {
    let crafted = seal_record((1, (1, 1)), &[(1, (1, 1))], &[(1, 1), (1, 3)], &[(1, 1)]);
    let lineage = proof(vec![crafted]);
    assert_eq!(
        Epochs::bootstrap([1], NonZeroUsize::new(1).unwrap(), &lineage),
        Err(EpochBootstrapError::UncoveredLedgerDot {
            generation: 1,
            dot: d(1, 3)
        })
    );
}