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
//! The declaration-scheduled preparation machine (S272): candidate
//! pinning, covered-entry classification, finish validation, and the
//! typed misses whose cure is the full rebuild.

extern crate alloc;

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

use crate::kairos::Kairos;
use crate::metis::dot::RawDot;
use crate::metis::{
    Adopted, Anchor, Cut, Declaration, Dot, DotSet, Dotted, EpochPreparation, EpochPreparationFold,
    EpochPreparationMiss, EpochStratum, EpochStratumError, Epochs, Locus, Metatheses, Metathesis,
    Rhapsody, Stability, Vouched,
};

/// 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")
}

type Text = Dotted<Rhapsody>;
type Moves = Dotted<Metatheses>;

fn rank(physical_ns: u64) -> Kairos {
    Kairos::new(physical_ns, 0, 1, 0u16)
}

fn locus(anchor: Anchor, rank: Kairos) -> Locus {
    Locus { anchor, rank }
}

fn text_delta(dot: Dot, locus: Locus) -> Text {
    let mut text = Rhapsody::new();
    assert!(text.weave(dot, locus));
    Dotted::from_store(text)
}

fn move_delta(testimony: Dot, target: (u32, u64), anchor: Anchor, rank: Kairos) -> Moves {
    Dotted::from_store(Metatheses::singleton(
        testimony,
        Metathesis {
            target: target.into(),
            to: locus(anchor, rank),
        },
    ))
}

/// The shared document: three text births and one movement testimony,
/// as log entries (each annotated with its own event dot, the log
/// discipline the classifier rides) beside the converged pairs the
/// rebuild folds, both spelling the same state.
type LogEntries<S> = Vec<((u32, u64), S)>;

fn generation_log() -> (LogEntries<Text>, LogEntries<Moves>, Text, Moves) {
    let text_entries = vec![
        ((1, 1), text_delta(d(1, 1), locus(Anchor::Origin, rank(3)))),
        (
            (1, 2),
            text_delta(
                d(1, 2),
                locus(
                    Anchor::After(RawDot {
                        station: 1,
                        counter: 1,
                    }),
                    rank(5),
                ),
            ),
        ),
        (
            (2, 1),
            text_delta(
                d(2, 1),
                locus(
                    Anchor::After(RawDot {
                        station: 1,
                        counter: 1,
                    }),
                    rank(4),
                ),
            ),
        ),
    ];
    let move_entries = vec![((2, 2), move_delta(d(2, 2), (1, 2), Anchor::Origin, rank(9)))];
    let mut text = Text::new();
    for (_, delta) in &text_entries {
        text.merge_from(delta);
    }
    let mut moves = Moves::new();
    for (_, delta) in &move_entries {
        moves.merge_from(delta);
    }
    (text_entries, move_entries, text, moves)
}

/// Declares over the pairs' own floor and drives the two-member machine
/// to adoption, returning the declaration and the witness.
fn declared_and_adopted(text: &Text, moves: &Moves) -> (Declaration, Adopted) {
    let coverage = text.context().merge(moves.context());
    let boundary = Cut::floor_of(&coverage);
    let dot = d(1, boundary.as_vector().get(1) + 1);
    let mut stability = Stability::new([1, 2]);
    stability.report_cut(1, &boundary).unwrap();
    stability.report_cut(2, &boundary).unwrap();
    let mut epochs = Epochs::new([1, 2], NonZeroUsize::new(1).unwrap());
    let declaration = epochs
        .declare(dot, rank(dot.counter()), &stability, &Cut::bottom())
        .unwrap();
    let mut delivered = boundary.as_vector().clone();
    delivered.observe(dot.station(), dot.counter());
    let delivered = Cut::from_witnessed(delivered);
    stability.report_cut(1, &delivered).unwrap();
    stability.report_cut(2, &delivered).unwrap();
    epochs
        .confirm(declaration.address(), &Vouched::trust(1, delivered.clone()))
        .unwrap();
    epochs
        .confirm(declaration.address(), &Vouched::trust(2, delivered.clone()))
        .unwrap();
    let adopted = epochs
        .adopt(1, delivered.as_vector().get(1), &stability)
        .unwrap();
    (declaration, adopted)
}

#[test]
fn the_declarer_dry_run_seeds_and_finishes_the_exact_stratum() {
    let (_, _, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    let control = EpochStratum::new(&adopted, text.clone(), moves.clone()).unwrap();
    let preparation = EpochPreparation::begin(&declaration, text, moves)
        .expect("the dry-run pairs sit below their own declaration cut");
    assert_eq!(preparation.address(), declaration.address());
    assert_eq!(preparation.cut(), declaration.cut());
    let staged = preparation
        .finish(&adopted)
        .expect("the staged winner is the adopted winner");
    assert_eq!(staged.pristine(), control.pristine());
    assert_eq!(
        staged.into_transition().shadow.projection(),
        control.into_transition().shadow.projection(),
    );
}

#[test]
fn a_peer_stages_from_the_base_and_agrees_with_the_rebuild() {
    let (text_entries, move_entries, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    let mut preparation = EpochPreparation::begin(&declaration, Text::new(), Moves::new())
        .expect("the empty base sits below every cut");
    for (dot, delta) in &text_entries {
        assert_eq!(
            preparation.absorb_text(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    for (dot, delta) in &move_entries {
        assert_eq!(
            preparation.absorb_moves(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    let staged = preparation
        .finish(&adopted)
        .expect("the covered log is exactly the fold input");
    let control = EpochStratum::new(&adopted, text, moves).unwrap();
    assert_eq!(staged.pristine(), control.pristine());
}

#[test]
fn a_window_delta_is_classified_and_left_unfolded() {
    let (text_entries, move_entries, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    let mut preparation = EpochPreparation::begin(&declaration, Text::new(), Moves::new()).unwrap();
    for (dot, delta) in &text_entries {
        assert_eq!(
            preparation.absorb_text(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    for (dot, delta) in &move_entries {
        assert_eq!(
            preparation.absorb_moves(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    // Window traffic: minted above the pinned cut, on both planes.
    assert_eq!(
        preparation.absorb_text(
            &[RawDot::new(2, 9)],
            &text_delta(d(2, 9), locus(Anchor::Origin, rank(11)))
        ),
        EpochPreparationFold::Window {
            dot: RawDot::new(2, 9)
        }
    );
    assert_eq!(
        preparation.absorb_moves(
            &[RawDot::new(2, 9)],
            &move_delta(d(2, 9), (1, 1), Anchor::Origin, rank(12))
        ),
        EpochPreparationFold::Window {
            dot: RawDot::new(2, 9)
        }
    );
    // Nothing was folded: the staging still finishes as the exact
    // covered stratum.
    let staged = preparation.finish(&adopted).unwrap();
    let control = EpochStratum::new(&adopted, text, moves).unwrap();
    assert_eq!(staged.pristine(), control.pristine());
}

#[test]
fn a_recording_only_fragment_is_classified_by_its_skeleton() {
    let (text_entries, move_entries, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    let mut preparation = EpochPreparation::begin(&declaration, Text::new(), Moves::new()).unwrap();
    for (dot, delta) in &text_entries {
        assert_eq!(
            preparation.absorb_text(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    for (dot, delta) in &move_entries {
        assert_eq!(
            preparation.absorb_moves(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }

    // A fragment whose only above-cut content is *invisible skeleton*: a
    // locus born above the cut and already deleted, so the visible
    // support is empty and the empty context lawfully covers it (the
    // skeleton ships whole, the S190 `novel_to` law). The entry arrives
    // *mislabeled* with a covered event dot; the declared events pass,
    // and the footprint defense scan must still refuse it.
    let mut pair = Text::new();
    pair.merge_from(&text_delta(d(2, 9), locus(Anchor::Origin, rank(11))));
    let mut removal = DotSet::new();
    assert!(removal.insert(d(2, 9)));
    pair.merge_from(&Dotted::from_context(removal));
    let fragment = Dotted::try_new(pair.store().clone(), DotSet::new())
        .expect("an invisible skeleton needs no context coverage");
    assert_eq!(
        preparation.absorb_text(&[RawDot::new(1, 1)], &fragment),
        EpochPreparationFold::Window {
            dot: RawDot::new(2, 9)
        }
    );
    // Nothing was folded: the staging still finishes as the exact
    // covered stratum.
    let staged = preparation.finish(&adopted).unwrap();
    let control = EpochStratum::new(&adopted, text, moves).unwrap();
    assert_eq!(staged.pristine(), control.pristine());

    // The same fragment poisons a base at the seam.
    assert_eq!(
        EpochPreparation::begin(&declaration, fragment, Moves::new()).unwrap_err(),
        EpochPreparationMiss::UnpinnedBase {
            dot: RawDot::new(2, 9)
        }
    );
}

#[test]
fn a_post_cut_deletion_of_a_pre_cut_identity_is_window_traffic() {
    let (text_entries, move_entries, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    let mut preparation = EpochPreparation::begin(&declaration, Text::new(), Moves::new()).unwrap();
    for (dot, delta) in &text_entries {
        assert_eq!(
            preparation.absorb_text(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    for (dot, delta) in &move_entries {
        assert_eq!(
            preparation.absorb_moves(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }

    // A dotted deletion minted above the cut retracting the pre-cut
    // identity (1, 1): its delta is a bare context carrying the marker
    // dot and the retracted dot, so the footprint alone reads mixed;
    // the declared event dot is what classifies it. The at-cut stratum
    // must retain (1, 1) and leave the deletion to the shadow.
    let mut deletion = DotSet::new();
    assert!(deletion.insert(d(2, 9)));
    assert!(deletion.insert(d(1, 1)));
    assert_eq!(
        preparation.absorb_text(
            &[RawDot::new(2, 9)],
            &Dotted::from_context(deletion.clone())
        ),
        EpochPreparationFold::Window {
            dot: RawDot::new(2, 9)
        }
    );
    // The movement twin: a post-cut retraction of the pre-cut testimony.
    let mut move_retract = DotSet::new();
    assert!(move_retract.insert(d(2, 10)));
    assert!(move_retract.insert(d(2, 2)));
    assert_eq!(
        preparation.absorb_moves(&[RawDot::new(2, 10)], &Dotted::from_context(move_retract)),
        EpochPreparationFold::Window {
            dot: RawDot::new(2, 10)
        }
    );

    let staged = preparation.finish(&adopted).unwrap();
    let control = EpochStratum::new(&adopted, text, moves).unwrap();
    assert_eq!(staged.pristine(), control.pristine());
    assert!(
        staged.pristine().woven().dots().next().is_some(),
        "the retained at-cut content survives the misdirected deletion"
    );
}

#[test]
fn an_undotted_retraction_is_unclassifiable_and_stays_window_side() {
    let (text_entries, move_entries, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    let mut preparation = EpochPreparation::begin(&declaration, Text::new(), Moves::new()).unwrap();
    for (dot, delta) in &text_entries {
        assert_eq!(
            preparation.absorb_text(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }
    for (dot, delta) in &move_entries {
        assert_eq!(
            preparation.absorb_moves(&[(*dot).into()], delta),
            EpochPreparationFold::Staged
        );
    }

    // A raw `Composer::retract` shape: a bare context delta naming only
    // the retracted (pre-cut) dot, with no reserved marker dot to
    // declare. No cut can witness which side of the boundary it fell
    // on, so the door refuses to guess: the entry stays window-side and
    // the non-dot is its evidence (the dotted-deletes half of the
    // one-event-space duty, R-53).
    let mut retract = DotSet::new();
    assert!(retract.insert(d(1, 1)));
    let retraction = Dotted::from_context(retract);
    assert_eq!(
        preparation.absorb_text(&[], &retraction),
        EpochPreparationFold::Window {
            dot: RawDot::new(0, 0)
        }
    );
    // Naming the non-dot is declaring no event: a zero-index label
    // cannot smuggle the retraction past the cut either.
    assert_eq!(
        preparation.absorb_text(&[RawDot::new(2, 0)], &retraction),
        EpochPreparationFold::Window {
            dot: RawDot::new(2, 0)
        }
    );

    // End to end: the window-side entry replays lawfully through the
    // shadow after adoption, where the removal is judged in the old
    // world (a covered retraction absorbs under the survivor law and
    // the projection drops the swept identity), so nothing is lost by
    // the conservative classification.
    let staged = preparation.finish(&adopted).unwrap();
    let mut shadow = staged.into_transition().shadow;
    let before = shadow.projection().order().len();
    shadow
        .deliver_text(&retraction)
        .expect("a window retraction replays through the shadow");
    let after = shadow.projection().order().len();
    assert_eq!(
        before - after,
        1,
        "the retracted identity leaves the judgment"
    );
}

#[test]
fn an_unpinned_base_refuses_at_the_seam() {
    let (_, _, text, moves) = generation_log();
    let (declaration, _) = declared_and_adopted(&text, &moves);

    let mut poisoned = text;
    poisoned.merge_from(&text_delta(d(2, 9), locus(Anchor::Origin, rank(11))));
    assert_eq!(
        EpochPreparation::begin(&declaration, poisoned, moves).unwrap_err(),
        EpochPreparationMiss::UnpinnedBase {
            dot: RawDot::new(2, 9)
        }
    );
}

#[test]
fn a_losing_candidate_misses_with_both_addresses_named() {
    let (_, _, text, moves) = generation_log();
    let coverage = text.context().merge(moves.context());
    let boundary = Cut::floor_of(&coverage);
    let mut stability = Stability::new([1, 2]);
    stability.report_cut(1, &boundary).unwrap();
    stability.report_cut(2, &boundary).unwrap();

    // Two concurrent candidates at one cut; the fixed public rule (rank,
    // then dot) picks station 2's higher rank.
    let dot_one = d(1, boundary.as_vector().get(1) + 1);
    let dot_two = d(2, boundary.as_vector().get(2) + 1);
    let mut epochs = Epochs::new([1, 2], NonZeroUsize::new(1).unwrap());
    let losing = epochs
        .declare(dot_one, rank(1), &stability, &Cut::bottom())
        .unwrap();
    let mut rival = Epochs::new([1, 2], NonZeroUsize::new(1).unwrap());
    let winning = rival
        .declare(dot_two, rank(9), &stability, &Cut::bottom())
        .unwrap();
    epochs.deliver(winning, &stability, &Cut::bottom()).unwrap();

    let mut delivered = boundary.as_vector().clone();
    delivered.observe(dot_one.station(), dot_one.counter());
    delivered.observe(dot_two.station(), dot_two.counter());
    let delivered = Cut::from_witnessed(delivered);
    stability.report_cut(1, &delivered).unwrap();
    stability.report_cut(2, &delivered).unwrap();
    epochs
        .confirm(losing.address(), &Vouched::trust(1, delivered.clone()))
        .unwrap();
    epochs
        .confirm(losing.address(), &Vouched::trust(2, delivered.clone()))
        .unwrap();
    let adopted = epochs
        .adopt(1, delivered.as_vector().get(1), &stability)
        .unwrap();
    assert_ne!(adopted.address(), losing.address());

    let preparation = EpochPreparation::begin(&losing, text, moves).unwrap();
    assert_eq!(
        preparation.finish(&adopted).unwrap_err(),
        EpochPreparationMiss::DifferentWinner {
            staged: losing.address(),
            adopted: adopted.address(),
        }
    );
}

#[test]
fn a_drifted_cut_names_the_first_disagreeing_station() {
    let (_, _, text, moves) = generation_log();
    let (_, adopted) = declared_and_adopted(&text, &moves);

    // A same-address declaration from another document: same dot, a
    // shorter witnessed cut.
    let mut short = DotSet::new();
    assert!(short.insert(d(1, 1)));
    let short_boundary = Cut::floor_of(&short);
    let mut stability = Stability::new([1, 2]);
    stability.report_cut(1, &short_boundary).unwrap();
    stability.report_cut(2, &short_boundary).unwrap();
    let mut foreign = Epochs::new([1, 2], NonZeroUsize::new(1).unwrap());
    let alien = foreign
        .declare(adopted.dot(), adopted.rank(), &stability, &Cut::bottom())
        .unwrap();
    assert_eq!(alien.address(), adopted.address());
    assert_ne!(alien.cut(), adopted.cut());

    let preparation = EpochPreparation::begin(&alien, Text::new(), Moves::new()).unwrap();
    let miss = preparation.finish(&adopted).unwrap_err();
    assert!(matches!(
        miss,
        EpochPreparationMiss::DriftedCut { station: 1, .. }
    ));
}

#[test]
fn a_context_complete_but_content_empty_base_is_the_callers_log_obligation() {
    let (_, _, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    // Coverage is a receipt property: a base whose context covers the
    // cut while its store carries none of the covered content passes
    // every structural law (coverage, bounds, foldability) and
    // re-founds empty. The door proves candidate identity and
    // structure, never log honesty; that obligation is the caller's
    // under staging and full rebuild alike (the documented boundary
    // this test pins).
    let hollow = Dotted::from_context(declaration.cut().to_have_set());
    let preparation = EpochPreparation::begin(&declaration, hollow, Moves::new()).unwrap();
    let staged = preparation
        .finish(&adopted)
        .expect("a context-complete base passes the structural proof");
    let control = EpochStratum::new(&adopted, text, moves).unwrap();
    assert!(staged.pristine().woven().dots().next().is_none());
    assert_ne!(staged.pristine(), control.pristine());
}

#[test]
fn an_unfed_staging_surfaces_the_stratum_refusal() {
    let (_, _, text, moves) = generation_log();
    let (declaration, adopted) = declared_and_adopted(&text, &moves);

    // The base was seeded but the covered log was never fed: the finish
    // proof refuses exactly as the stratum door would.
    let preparation = EpochPreparation::begin(&declaration, Text::new(), Moves::new()).unwrap();
    assert!(matches!(
        preparation.finish(&adopted).unwrap_err(),
        EpochPreparationMiss::Stratum(EpochStratumError::Incomplete { .. })
    ));
}