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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! The recension: the movement replay read (PRD 0022, stage C's reorder
//! half).
//!
//! A [`Recension`] is the document order that results from resolving every
//! *placement testimony*, the births the skeleton records and the moves a
//! [`Metatheses`] record carries, in one fixed public order. The name is
//! the philologists' own: a recension is the critical text an editor
//! derives from the transmitted witnesses, never itself a witness. The
//! type enforces exactly that: it is a *decision-layer read*, derived from
//! the two records, exposing the sequence reads and nothing that could
//! re-enter a merge, so the chosen reading can never masquerade as the
//! record (the production-recording-decision rule, applied by
//! construction).
//!
//! # The replay rule, whole
//!
//! Every testimony has the same shape, `(target, Locus)`: a birth places a
//! fresh identity, a metathesis re-places an existing one.
//!
//! Births apply first, unconditionally. The weave accepts dangling anchors
//! and may contain an unplaced birth-anchor cycle, because birth placement is
//! record state and is never adjudicated as a movement refusal.
//!
//! Moves then apply in one total order. The locus rank orders first, and the
//! metathesis dot breaks ties. *Applying*
//! means overwriting the target's effective locus. A move is *refused*,
//! readably and deterministically, iff applying it would place its own target
//! inside its anchor cycle: the walk from the new anchor through the current
//! effective skeleton reaches the target. Later moves for the same target
//! simply win, so an element's effective locus is its highest-rank surviving
//! non-refused placement, and a refusal rejects only the candidate edge
//! without rewriting birth state.
//!
//! This is the replicated tree-move design read through the crate's own
//! separation. The *record* is monotone state under the survivor law, so
//! undoing a move is an observed-remove of its testimony and convergence is
//! state convergence rather than log-replay agreement; the *decision* is this
//! read; and the winner rule is the same public order the delivery buffer
//! uses. The machine still never chooses: refusal and rank are fixed public
//! rules, and every refusal is surfaced.
//!
//! # What it cures
//!
//! Move-as-delete-plus-reinsert forks identity: a concurrent edit anchors
//! to the deleted copy and converges stranded at the old slot (alma
//! COLLAB-8, the field twin of PRD 0019 stage A's exhibit). Here the
//! moved element keeps its dot, so a concurrent edit anchored to it
//! follows it: its own birth locus still names the same identity, and the
//! recension walk renders it beside the element's *new* place. Subtrees
//! follow for free, because followers anchor through the moved identity.

extern crate alloc;

use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;

use crate::kairos::Kairos;

use super::super::DotSet;
use super::super::metathesis::{Metatheses, Metathesis};
use super::ancestry::{
    AncestryQueryError, AncestryRelation, Coordinate, CoordinateError, QueryError,
};
use super::identity::IdentityPlane;
use super::placement::Dot;
use super::possession::OccupancyPlane;
use super::{Anchor, Extent, Locus, OrderWalk, PlacementEffect, Rhapsody, Verge};

mod batch;
mod collation;
mod cycle;
#[cfg(feature = "timing")]
mod profile;

use crate::metis::dot::RawDot;
pub use batch::{MovementBatch, MovementBatchError};
use cycle::{WalkBudget, move_forms_cycle};
#[cfg(feature = "timing")]
pub use profile::{
    MovementBatchMoveProfile, MovementCycleValidationProfile, MovementCycleValidationWork,
    MovementTopologyPhases, MovementTopologyProfile, MovementTopologyWork, ProfiledMovement,
};

/// The replay's total order key for one move: the locus rank, then the
/// metathesis dot as the tie-breaker (the fixed public rule). The witness
/// is a testimony identity, so it is a [`Dot`]; the target it names is a
/// payload coordinate and stays raw.
type PlayKey = (Kairos, Dot);

/// A movement target, read back as the identity the replay proved it names.
///
/// A target is a payload coordinate (zero-capable, possibly naming nothing),
/// so every replay path first gates it on skeleton membership; the non-dot
/// counter is never woven, so a gated target is always a dot (ruling R-91).
fn woven_target(target: RawDot) -> Dot {
    Dot::try_from(target).expect("a participating target is woven, so its counter is nonzero")
}

/// A payload coordinate read against identity-keyed state: the non-dot
/// counter names no woven element, so the read is total and answers
/// "absent" exactly as it did before the type carried the law (R-91).
fn as_identity(raw: RawDot) -> Option<Dot> {
    Dot::try_from(raw).ok()
}

/// One move's replay verdict, retained so a later collation can unwind
/// exactly to a changed position and replay the suffix (the undo-redo
/// suffix mechanics of the tree-move literature, the shape PRD 0022 R7
/// named for this seam).
#[derive(Clone, Copy, Debug)]
enum Verdict {
    /// The move applied, overwriting the target's effective locus;
    /// `displaced` is what it overwrote (the birth locus or the previous
    /// winning move), the value an unwind restores.
    Applied { displaced: Locus },
    /// The move was refused as a cycle-former: no state moved, so an
    /// unwind past it restores nothing.
    Refused,
}

/// One participating move (target born here), lifted for the replay's
/// total order and retained with its verdict.
#[derive(Clone, Debug)]
struct Play {
    /// `(rank, witness)`: the replay's ordering key.
    key: PlayKey,
    target: RawDot,
    locus: Locus,
    verdict: Verdict,
}

/// The resolved document: an effective sequence derived from the birth
/// skeleton and a movement record, plus the replay's surfaced verdicts.
///
/// Deliberately a sealed view: it exposes the sequence *reads* (the walk,
/// the extent projection, placement and visibility queries) by delegation,
/// and no path back to a mergeable store, so the derived reading cannot be
/// folded, shipped, or witnessed as if it were record state. In
/// particular it deliberately does NOT expose a recording-possession
/// witness: an anti-entropy witness must come from the canonical store,
/// never from a derived view.
///
/// Since S203 the view is also *maintainable*: [`collate`](Self::collate)
/// brings it to the pair's current state at the cost of the changed
/// regions' replay work plus per-call possession scans (since S205 one
/// `O(pages)` word-comparison walk over the visible occupancy planes
/// plus extraction of the flipped dots, the visible scan's cost
/// independent of its have-set fragmentation, beside the woven
/// have-set diff and a walk over the surviving testimonies; the method
/// doc carries the bound in full), with the
/// eager [`Rhapsody::recension`] the contract form the collation must
/// agree with exactly. The retained collation state (the
/// play log, the walk guard, the folded record, and the possession marks)
/// is maintenance machinery, excluded from equality: two recensions are
/// equal exactly when their performed sequence and surfaced verdicts are.
#[derive(Clone, Debug)]
pub struct Recension {
    /// The effective sequence: the canonical store's visible plane over
    /// the replayed skeleton.
    performed: Rhapsody,
    /// Exact side-free ancestry over `performed`, or the structural reason the
    /// derived coordinate cannot currently be served.
    ancestry: Result<Coordinate, CoordinateError>,
    /// The refused moves (cycle-formers), in replay order, by metathesis
    /// dot. Only moves are refutable: births are canonical and never
    /// refused, so a refusal never detaches content.
    refused: Vec<Dot>,
    /// Movement testimonies whose target has no birth here yet (the move
    /// delta outran the weave), by testimony dot, ascending: they take no
    /// part in this replay and resolve in a later one.
    pending: Vec<Dot>,
    /// The participating moves in replay order, each with its verdict and
    /// (when applied) the locus it displaced: the unwind log.
    plays: Vec<Play>,
    /// The walk guard: every dot some present locus has ever anchored to,
    /// monotone and never pruned (a stale entry costs a needless walk,
    /// never a wrong verdict).
    anchored: BTreeSet<RawDot>,
    /// Unborn dots some folded locus anchors to, each with the earliest
    /// play key whose verdict could depend on that birth (`None`: the
    /// whole log, for a birth-locus reference, which precedes every
    /// play). A chain can only ever grow at an unborn terminus, and every
    /// such terminus is anchored by some folded locus, so recording the
    /// reference at fold time is complete where recording it at walk time
    /// is not: the near-linearity guard SKIPS walks whose verdicts a
    /// later birth can still flip (the anchor itself unborn, or a chain
    /// ending unborn behind a childless target). When the birth arrives,
    /// the verdicts from the recorded key on are re-earned. Entries are
    /// over-approximate after unwinds (sound: an extra replay, never a
    /// missed one).
    dangling: BTreeMap<RawDot, Option<PlayKey>>,
    /// The movement record as last collated (witness dot to testimony):
    /// the diff base for the record's presence changes, sufficient
    /// because a testimony is immutable under its dot (axis law 3).
    folded: BTreeMap<Dot, Metathesis>,
    /// The text skeleton's key set as last collated: the diff base for
    /// births (and, shrinking, for the condense fallback).
    woven_mark: DotSet,
    /// The text's visible plane as last collated, in paged occupancy
    /// form (S205): the diff base for visibility flips, walked against
    /// the pair's own occupancy shell in `O(pages)` word compares
    /// instead of a membership probe per retained have-set exception
    /// (the churned-document term alma COLLAB-9 priced at ~135 us per
    /// keystroke). Content-exact for any pair: masks are compared, so
    /// this narrows no contract.
    visible_mark: OccupancyPlane,
    /// Suffix replays run by collations (accounting for the tests).
    #[cfg(test)]
    replays: usize,
    /// Whole-replay fallbacks run by collations (accounting for the
    /// tests).
    #[cfg(test)]
    rebuilds: usize,
    /// Pending-vector slots touched by collations compacting parked
    /// departures out (accounting for the tests): the observable that
    /// makes the departure path's cost claim falsifiable, since a
    /// per-witness splice and a single compaction agree on every value
    /// the view surfaces.
    #[cfg(test)]
    compacted: usize,
}

// The retained collation state is maintenance machinery, a pure function
// of the two records collated so far; the value is the performed sequence
// and the surfaced verdicts (the shell discipline's rule, applied to the
// decision layer).
impl PartialEq for Recension {
    fn eq(&self, other: &Self) -> bool {
        self.performed == other.performed
            && self.refused == other.refused
            && self.pending == other.pending
    }
}
impl Eq for Recension {}

/// Failure to borrow exact ancestry from a recension.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum AncestryAdmissionError {
    /// The effective reading contains at least one unplaced identity.
    #[error("exact ancestry requires a fully placed effective reading")]
    UnplacedReading,
    /// The derived coordinate could not cover or validate the effective plane.
    #[error("the exact ancestry coordinate is unavailable")]
    Coordinate(#[source] CoordinateError),
}

/// A borrow-scoped exact ancestry capability over one effective reading.
pub struct ExactAncestry<'a> {
    coordinate: &'a mut Coordinate,
}

/// Structural accounting for every variable-size component of a maintained
/// effective reading.
#[cfg(feature = "instrumentation")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct RecensionProfile {
    /// The materialized sequence coordinates.
    pub sequence: super::RhapsodyProfile,
    /// The exact ancestry coordinate, or its structural unavailability.
    pub ancestry: Result<super::ancestry::AncestryProfile, CoordinateError>,
    /// Refused move verdicts retained in replay order.
    pub refused: usize,
    /// Allocated refused-verdict slots.
    pub refused_capacity: usize,
    /// Pending testimony dots awaiting their targets.
    pub pending: usize,
    /// Allocated pending-testimony slots.
    pub pending_capacity: usize,
    /// Participating move plays in the unwind log.
    pub plays: usize,
    /// Allocated unwind-log slots.
    pub play_capacity: usize,
    /// Monotone anchored-dot guard entries.
    pub anchored: usize,
    /// Unborn termini tracked for replay.
    pub dangling: usize,
    /// Testimonies in the last-collated record.
    pub folded: usize,
    /// Station rows in the last-collated woven mark.
    pub woven_mark_stations: usize,
    /// Sparse entries in the last-collated woven mark.
    pub woven_mark_exceptions: usize,
    /// Station fibers in the last-collated visible mark.
    pub visible_mark_stations: usize,
    /// Nonzero pages in the last-collated visible mark.
    pub visible_mark_pages: usize,
}

impl ExactAncestry<'_> {
    /// Returns the inclusive relation from `descendant` to `ancestor`.
    ///
    /// # Errors
    ///
    /// Returns a typed error for unknown operands or bounded structural
    /// exhaustion. Admission guarantees a fully placed reading.
    pub fn relation(
        &mut self,
        descendant: Dot,
        ancestor: Dot,
    ) -> Result<AncestryRelation, AncestryQueryError> {
        self.coordinate
            .relation(descendant, ancestor)
            .map_err(QueryError::into_public)
    }
}

fn synchronize_coordinate(
    coordinate: &mut Coordinate,
    skeleton: &IdentityPlane,
    first_unplaced: Option<Dot>,
    effect: PlacementEffect,
) -> Result<(), CoordinateError> {
    match effect {
        PlacementEffect::Unchanged => {}
        PlacementEffect::Reparented { dot, parent } => {
            coordinate.replace_parent(dot, parent)?;
        }
        PlacementEffect::Parked(region) => {
            for dot in region {
                coordinate.park(dot)?;
            }
        }
        PlacementEffect::Repaired(region) => {
            for dot in region {
                let parent = skeleton
                    .get(&dot)
                    .ok_or(CoordinateError::InvariantViolation)?
                    .anchor
                    .dot();
                coordinate.repair(dot, parent)?;
            }
        }
    }
    coordinate.publish_state(first_unplaced);
    Ok(())
}

impl Recension {
    /// Borrows the exact ancestry coordinate for this effective reading.
    ///
    /// # Errors
    ///
    /// Refuses before invoking `use_ancestry` when any effective identity is
    /// unplaced or the derived coordinate is structurally unavailable.
    pub fn with_exact_ancestry<R>(
        &mut self,
        use_ancestry: impl FnOnce(&mut ExactAncestry<'_>) -> R,
    ) -> Result<R, AncestryAdmissionError> {
        if !self.performed.unplaced.is_empty() {
            return Err(AncestryAdmissionError::UnplacedReading);
        }
        let coordinate = self
            .ancestry
            .as_mut()
            .map_err(|error| AncestryAdmissionError::Coordinate(*error))?;
        Ok(use_ancestry(&mut ExactAncestry { coordinate }))
    }

    /// Captures the effective sequence's structural measurement profile.
    #[cfg(feature = "instrumentation")]
    #[must_use]
    pub fn profile(&self) -> RecensionProfile {
        RecensionProfile {
            sequence: self.performed.profile(),
            ancestry: self
                .ancestry
                .as_ref()
                .map(Coordinate::profile)
                .map_err(|error| *error),
            refused: self.refused.len(),
            refused_capacity: self.refused.capacity(),
            pending: self.pending.len(),
            pending_capacity: self.pending.capacity(),
            plays: self.plays.len(),
            play_capacity: self.plays.capacity(),
            anchored: self.anchored.len(),
            dangling: self.dangling.len(),
            folded: self.folded.len(),
            woven_mark_stations: self.woven_mark.station_count(),
            woven_mark_exceptions: self.woven_mark.exceptions_len(),
            visible_mark_stations: self.visible_mark.station_count(),
            visible_mark_pages: self.visible_mark.page_count(),
        }
    }

    /// Document order under the movement record: the visible dots of the
    /// effective sequence, front to back.
    #[must_use]
    pub fn order(&self) -> Vec<Dot> {
        self.performed.order()
    }

    /// The performed sequence itself, for the one in-crate reader that
    /// needs its tombstone-inclusive coordinates: the seal consignment's
    /// re-spelling walk (PRD 0024 stage four). Deliberately not public:
    /// the recension stays a sealed view, and the reading crosses back
    /// into record state only through the epoch seal's witnessed door.
    pub(in crate::metis::rhapsody) const fn performed(&self) -> &Rhapsody {
        &self.performed
    }

    /// The lazy in-order walk over the effective sequence.
    #[must_use]
    pub fn order_walk(&self) -> OrderWalk<'_> {
        self.performed.order_walk()
    }

    /// The walk resumed after a placed element of the effective sequence
    /// (`None` for a dot with no place in it).
    #[must_use]
    pub fn order_walk_after(&self, dot: Dot) -> Option<OrderWalk<'_>> {
        self.performed.order_walk_after(dot)
    }

    /// The effective order's length without materializing it (the
    /// positional reads delegate like the walks: the recension's thread is
    /// the effective sequence's own, arc 11 phase three).
    #[must_use]
    pub fn order_len(&self) -> usize {
        self.performed.order_len()
    }

    /// The element at visible offset `offset` of the effective order.
    #[must_use]
    pub fn order_at(&self, offset: usize) -> Option<Dot> {
        self.performed.order_at(offset)
    }

    /// The visible offset of an element's slot in the effective order.
    #[must_use]
    pub fn offset_of(&self, dot: Dot) -> Option<usize> {
        self.performed.offset_of(dot)
    }

    /// The reverse walk over the effective order, from its end.
    #[must_use]
    pub fn order_walk_rev(&self) -> super::OrderWalkRev<'_> {
        self.performed.order_walk_rev()
    }

    /// The reverse walk resumed immediately before a placed element of the
    /// effective order.
    #[must_use]
    pub fn order_walk_rev_before(&self, dot: Dot) -> Option<super::OrderWalkRev<'_>> {
        self.performed.order_walk_rev_before(dot)
    }

    /// The span projection against the effective sequence: a mark's
    /// verges resolve at the moved places, which is how marks and moves
    /// compose (PRD 0021 meets PRD 0022).
    #[must_use]
    pub fn extent(&self, start: Verge, end: Verge) -> Extent {
        self.performed.extent(start, end)
    }

    /// The effective locus of `(station, dot)`: its highest-rank
    /// surviving, non-refused placement. By value, as
    /// [`Rhapsody::locus`](super::Rhapsody::locus) is (S199).
    #[must_use]
    pub fn locus(&self, dot: Dot) -> Option<Locus> {
        self.performed.locus(dot)
    }

    /// Whether the element is visible (visibility is the canonical
    /// store's, untouched by movement).
    #[must_use]
    pub fn is_visible(&self, dot: Dot) -> bool {
        self.performed.is_visible(dot)
    }

    /// Whether the element has a place in the effective order.
    #[must_use]
    pub fn is_reachable(&self, dot: Dot) -> bool {
        self.performed.is_reachable(dot)
    }

    /// The effective skeleton children of `anchor`, in stored sibling
    /// order (the rank to beat when minting above the bucket).
    pub fn children_of(&self, anchor: Anchor) -> impl Iterator<Item = Dot> + '_ {
        self.performed.children_of(anchor)
    }

    /// The anchor that places a fresh top-rank element immediately after
    /// the visible element the caret sits on, computed against the
    /// EFFECTIVE sequence: an editor displaying a recension inserts
    /// against the order its user sees.
    #[must_use]
    pub fn anchor_for_visual_insert(&self, after: Option<RawDot>) -> Anchor {
        self.performed.anchor_for_visual_insert(after)
    }

    /// Visible elements in the effective sequence.
    #[must_use]
    pub fn visible_len(&self) -> usize {
        self.performed.visible_len()
    }

    /// Moves the replay refused as cycle-formers, in replay order, by
    /// metathesis dot: surfaced, deterministic at every converged replica,
    /// and empty for every history without concurrent conflicting moves.
    /// Births are never refused, so refusal never detaches content.
    #[must_use]
    pub fn refused(&self) -> &[Dot] {
        &self.refused
    }

    /// Movement testimonies whose target has no birth here yet, by
    /// testimony dot: the out-of-order-delivery surface, resolved by the
    /// weave's arrival, never fabricated into a placement.
    #[must_use]
    pub fn pending(&self) -> &[Dot] {
        &self.pending
    }
}

impl Rhapsody {
    /// Resolves this sequence under a movement record: the replay read
    /// (PRD 0022), handing back the [`Recension`] whose order every
    /// display should use once moves exist.
    ///
    /// The replay applies the skeleton's births first, then the record's
    /// moves in ascending rank order (ties broken by the metathesis dot),
    /// overwriting the target's effective locus, and refuses exactly the
    /// moves whose application would place their target inside its own
    /// anchor chain. Births are canonical record state and are never refused;
    /// dangling anchors and unplaced birth-anchor cycles remain represented as
    /// woven state. Applying all births before any move ensures a movement
    /// refusal rejects only its candidate edge, even when a malformed record
    /// carries a move ranked below its anchor's birth. The winner among
    /// concurrent moves of one element is therefore the highest-rank surviving
    /// move, by the same fixed public `Kairos` rule the delivery buffer
    /// linearizes with; the machine chooses nothing, and every refusal is
    /// readable ([`Recension::refused`]).
    ///
    /// Identity is preserved by construction: a moved element keeps its
    /// dot, so concurrent edits anchored to it (and whole subtrees
    /// anchoring through it) follow it to its new place, which is the
    /// cure for the delete-plus-reinsert identity fork (PRD 0019 stage
    /// A's exhibit; alma COLLAB-8's stranded edit).
    ///
    /// A move whose target has no birth here yet takes no part and is
    /// surfaced ([`Recension::pending`]); a move whose *anchor* has not
    /// arrived applies and parks unplaced, exactly as a dangling weave
    /// does. Visibility is untouched: moving neither revives nor deletes.
    ///
    /// # Shape and cost
    ///
    /// One eager replay: births applied in a linear pass, `O(M log M)` to order
    /// the moves, and one `from_parts` rebuild of the positional coordinates.
    /// A fully placed reading maintains the exact ancestry coordinate through
    /// replay. Lawful unknown or unplaced anchors use the bounded parent walk;
    /// its finite-skeleton failsafe and monotone child guard retain the total
    /// replay semantics. Births perform no cycle query.
    #[must_use]
    pub fn recension(&self, moves: &Metatheses) -> Recension {
        Recension::replay_full(self, moves)
    }
}

impl Recension {
    /// The whole replay: births first (canonical, never refused), then
    /// the participating moves in the fixed public order, each verdict
    /// and displacement retained so the result is collatable. The eager
    /// contract form [`Rhapsody::recension`] delegates here, and the
    /// collation's whole-replay fallback re-earns its state here.
    fn replay_full(text: &Rhapsody, moves: &Metatheses) -> Self {
        // Births are canonical record state and are never movement refusals;
        // dangling anchors and unplaced birth cycles remain represented.
        // Apply them all first, recording every anchor dot in the
        // `anchored` guard set (the dots that already have a child, so a
        // later move onto one of them must run the cycle walk).
        let mut effective: BTreeMap<Dot, Locus> = BTreeMap::new();
        let mut anchored: BTreeSet<RawDot> = BTreeSet::new();
        let mut dangling: BTreeMap<RawDot, Option<PlayKey>> = BTreeMap::new();
        for (dot, locus) in text.skeleton.iter() {
            if let Some(anchor_dot) = locus.anchor.dot() {
                let _ = anchored.insert(anchor_dot);
                // A birth anchored to an unborn dot: that birth, when it
                // arrives, can extend chains through this locus, so it
                // re-earns the whole log (births precede every play).
                if !as_identity(anchor_dot).is_some_and(|dot| text.skeleton.contains(dot)) {
                    let _ = dangling.insert(anchor_dot, None);
                }
            }
            let _ = effective.insert(dot, locus);
        }

        // Moves are the only refutable testimonies. Gather those whose
        // target is born here (a move that outran its weave takes no part
        // and is surfaced as pending, never fabricated into a placement),
        // order them by the fixed public rule (rank, then the metathesis
        // dot), and apply. Applying every birth first is what keeps
        // refusal from ever detaching content: a cycle is broken by
        // refusing the *move*, never a birth, even when a malformed record
        // carries a move ranked below its anchor's birth.
        let mut plays: Vec<Play> = Vec::with_capacity(moves.len());
        let mut pending: Vec<Dot> = Vec::new();
        let mut folded: BTreeMap<Dot, Metathesis> = BTreeMap::new();
        for (dot, metathesis) in moves {
            let _ = folded.insert(dot, *metathesis);
            if as_identity(metathesis.target).is_some_and(|target| text.skeleton.contains(target)) {
                plays.push(Play {
                    key: (metathesis.to.rank, dot),
                    target: metathesis.target,
                    locus: metathesis.to,
                    verdict: Verdict::Refused,
                });
            } else {
                pending.push(dot);
            }
        }
        plays.sort_unstable_by_key(|play| play.key);

        let mut ancestry = if text.unplaced.is_empty() {
            Coordinate::build(&text.skeleton, &text.unplaced).ok()
        } else {
            None
        };
        let mut refused: Vec<Dot> = Vec::new();
        for play in &mut plays {
            let cycles = move_forms_cycle(
                ancestry.as_mut(),
                play.target,
                play.locus.anchor,
                &anchored,
                WalkBudget::for_skeleton(effective.len()),
                |link| {
                    as_identity(link)
                        .and_then(|link| effective.get(&link))
                        .map(|locus| locus.anchor.dot())
                },
            )
            .must_refuse();
            if cycles {
                play.verdict = Verdict::Refused;
                refused.push(play.key.1);
            } else {
                let displaced = *effective
                    .get(&woven_target(play.target))
                    .expect("a participating target is born");
                play.verdict = Verdict::Applied { displaced };
                if let Some(anchor_dot) = play.locus.anchor.dot() {
                    let _ = anchored.insert(anchor_dot);
                    // An applied move anchored to an unborn dot: its
                    // arrival re-earns the verdicts from this play on.
                    if !as_identity(anchor_dot).is_some_and(|dot| text.skeleton.contains(dot)) {
                        let earliest = dangling.entry(anchor_dot).or_insert(Some(play.key));
                        *earliest = (*earliest).min(Some(play.key));
                    }
                }
                if let Some(coordinate) = &mut ancestry
                    && coordinate
                        .replace_parent(woven_target(play.target), play.locus.anchor.dot())
                        .is_err()
                {
                    ancestry = None;
                }
                let _ = effective.insert(woven_target(play.target), play.locus);
            }
        }

        // Births are never refused, so every visible dot is placed: the
        // visible plane is the store's own, untouched by movement.
        let performed = Rhapsody::from_parts(effective, text.visible.clone());
        let ancestry = ancestry.map_or_else(
            || Coordinate::build(&performed.skeleton, &performed.unplaced),
            Ok,
        );
        Self {
            performed,
            ancestry,
            refused,
            pending,
            plays,
            anchored,
            dangling,
            folded,
            woven_mark: text.woven.clone(),
            visible_mark: text.visible_pages.clone(),
            #[cfg(test)]
            replays: 0,
            #[cfg(test)]
            rebuilds: 0,
            #[cfg(test)]
            compacted: 0,
        }
    }
}