inky-engine 0.2.2

A hand-fused Metal inference engine for Thinking Machines' Inkling 2 Mini, for Apple Silicon M5 Macs (Metal 4)
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
//! Layer 3 prefix matching: a request is a token list, matched against a
//! tree of sealed 64-position blocks; it starts at the deepest start point
//! the tree holds for its tokens (docs/DESIGN.md, Blocks; docs/SHARED-PREFIX.md,
//! "Find and retain a block").
//!
//! A block enters the tree only sealed and complete (64 positions), as a
//! child of the block before it, and is never changed afterwards. Matching
//! validates every token of every block it walks: a digest narrows the
//! sibling search, the exact comparison decides, so a digest collision
//! takes the miss path and can never return a block from another history.
//! Equal local tokens under different parents are different blocks.
//!
//! A start point is a tree position kept by the caller (a prompt end, every
//! 16th block boundary a prefill crosses, a lane head): the tree counts how
//! many holders keep each one, and a match returns the deepest start point
//! with a holder on the matched path, with the block handles from the root
//! to it. Position 0 is always a start point and needs nothing.
//!
//! A `BlockEntry` names a pool slot at a generation, and a slot is reused:
//! the entry alone goes stale. `LiveTree` is the matcher over Johnny's
//! slot records — cached blocks sit at zero pool refs until a lane
//! pins them, it refuses an entry whose generation its slot has moved
//! past, evicts every stale block on a seek before matching, and drops
//! pinned refs generation-checked so a reused slot's new owner is
//! never corrupted. The plain `PrefixTree` below it knows nothing of pools.
//!
//! Modelled by `specs/PrefixTree.tla`; this code is bound to that model
//! by the trace check in `specs/run_tlc.zsh` (`PrefixTreeTrace`): a
//! seeded walk over `LiveTree` emits its states, and TLC checks each
//! emitted state is a behaviour of the spec.
//!
//! The convolution state and the window blocks behind the handles are the
//! pool's business, not this file's: the matcher is behind the
//! `PrefixMatch` trait so the scheduler never names the concrete tree.
//! Nothing here hashes for the pool; it only matches tokens the caller
//! supplies. The sealed flag on a pool's `SlotRecord` and the sealed flag
//! on a tree block are the same fact seen from two sides; the caller
//! seals in both places, this file cannot seal for the pool.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::blocks::{BlockEntry, BlockError, BlockKind, Slot};

/// Positions in one sealed block: Johnny's constant, re-exported so this
/// file and `crate::blocks` can never disagree about a block's size.
pub use crate::blocks::BLOCK;

/// One sealed block in one tree. The id carries its tree's identity: an
/// id from another tree names nothing here, however its index looks.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct SealedId {
    tree: u64,
    index: u32,
}

impl SealedId {
    /// This block's index inside its own tree (diagnostics, tests).
    pub fn index(&self) -> u32 { self.index }
}

/// Why a block was not added. Nothing is added on any of these.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum InsertError {
    /// A sealed block is exactly `BLOCK` positions, never a partial tail.
    NotFullBlock(usize),
    /// `pos` must be the end of the parent chain (0 for a root block).
    WrongPosition { expected: usize, got: usize },
    /// The parent id names no block in this tree.
    UnknownParent,
    /// The parent id belongs to a different tree.
    ForeignId,
}

/// The deepest start point a request matches.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct StartMatch<B> {
    /// Positions the start point covers: a multiple of `BLOCK`, or 0.
    pub at: usize,
    /// The tree block that ends at `at`; `None` only for position 0.
    pub start: Option<SealedId>,
    /// The tree blocks from the root to `at`, in order.
    pub ids: Vec<SealedId>,
    /// The caller's handles for those blocks, in the same order.
    pub blocks: Vec<B>,
}

/// The tree whose handles are Johnny's table entries: what a caller gets
/// back from a match and installs, kind by kind. The matcher never
/// constructs an entry; it carries the caller's.
/// The two pool entries one sealed block carries at a start point:
/// its `Full` entry and, where the block has one, its `Window` entry
/// (BlockLayout.tla's two kinds for one block). The tree matches on
/// tokens; both entries ride on the node so a start point can be
/// installed without a second lookup.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct BlockHandles {
    full: BlockEntry,
    window: Option<BlockEntry>,
}

impl BlockHandles {
    pub fn new(full: BlockEntry, window: Option<BlockEntry>) -> BlockHandles { BlockHandles { full, window } }
    pub fn full(self) -> BlockEntry { self.full }
    pub fn window(self) -> Option<BlockEntry> { self.window }
    fn entries(self) -> impl Iterator<Item = BlockEntry> {
        std::iter::once(self.full).chain(self.window)
    }
}

pub type EntryTree = PrefixTree<BlockHandles>;

/// What the scheduler asks of a prefix matcher. The concrete tree in this
/// file is one implementation; the trait is the seam Rowan asked for while
/// the block interface (PR 49) was revised.
pub trait PrefixMatch<B> {
    /// The deepest retained start point whose blocks are an exact prefix
    /// of `tokens`. Never past the last completely matched block, and
    /// never a position that is not a retained start point.
    fn deepest_start(&self, tokens: &[u32]) -> StartMatch<B>;
}

struct Node<B> {
    parent: Option<SealedId>,
    pos: usize,
    digest: u64,
    tokens: Box<[u32]>,
    handle: B,
    starts: u32,
    pins: u32,
    children: Vec<SealedId>,
}

/// FNV-1a over the parent, the position and the ordered token ids. A
/// lookup aid only: the exact token comparison always decides the match.
fn digest(parent: Option<SealedId>, pos: usize, tokens: &[u32]) -> u64 {
    let mut h = 0xcbf29ce484222325u64;
    let mut mix = |x: u64| h = (h ^ x).wrapping_mul(0x100000001b3);
    mix(parent.map(|p| p.index as u64 + 1).unwrap_or(0));
    mix(pos as u64);
    for &t in tokens { mix(t as u64); }
    h
}

static NEXT_TREE: AtomicU64 = AtomicU64::new(1);

/// The prefix tree of sealed blocks.
pub struct PrefixTree<B> {
    tree: u64,
    nodes: Vec<Option<Node<B>>>,
    roots: Vec<SealedId>,
    by_digest: HashMap<u64, Vec<SealedId>>,
}

impl<B: Copy> PrefixTree<B> {
    pub fn new() -> PrefixTree<B> {
        PrefixTree { tree: NEXT_TREE.fetch_add(1, Ordering::Relaxed), nodes: Vec::new(), roots: Vec::new(), by_digest: HashMap::new() }
    }

    fn node(&self, id: SealedId) -> Option<&Node<B>> {
        if id.tree != self.tree { return None; }
        self.nodes.get(id.index as usize).and_then(|n| n.as_ref())
    }

    fn node_mut(&mut self, id: SealedId) -> Option<&mut Node<B>> {
        if id.tree != self.tree { return None; }
        self.nodes.get_mut(id.index as usize).and_then(|n| n.as_mut())
    }

    /// Add one sealed block. `parent` is the block before it (`None` for
    /// the first block of a prefix) and `pos` its absolute start position.
    /// Adding the same block again (a racing publisher) returns the
    /// canonical block already in the tree, with its original handle:
    /// deduplication happens only after the exact token comparison.
    pub fn insert(&mut self, parent: Option<SealedId>, pos: usize, tokens: &[u32], handle: B) -> Result<SealedId, InsertError> {
        if tokens.len() != BLOCK { return Err(InsertError::NotFullBlock(tokens.len())); }
        let expected = match parent {
            None => 0,
            Some(p) => {
                if p.tree != self.tree { return Err(InsertError::ForeignId); }
                self.node(p).ok_or(InsertError::UnknownParent)?.pos + BLOCK
            }
        };
        if pos != expected { return Err(InsertError::WrongPosition { expected, got: pos }); }
        let d = digest(parent, pos, tokens);
        if let Some(bucket) = self.by_digest.get(&d) {
            for &id in bucket {
                let n = self.node(id).expect("digest buckets hold live blocks");
                if n.parent == parent && n.pos == pos && n.tokens.as_ref() == tokens { return Ok(id); }
            }
        }
        let id = SealedId { tree: self.tree, index: self.nodes.len() as u32 };
        self.nodes.push(Some(Node { parent, pos, digest: d, tokens: tokens.into(), handle, starts: 0, pins: 0, children: Vec::new() }));
        match parent {
            None => self.roots.push(id),
            Some(p) => self.node_mut(p).expect("the parent was just checked").children.push(id),
        }
        self.by_digest.entry(d).or_default().push(id);
        Ok(id)
    }

    /// The block already in the tree for exactly this parent, position
    /// and tokens, if there is one.
    fn find(&self, parent: Option<SealedId>, pos: usize, tokens: &[u32]) -> Option<SealedId> {
        self.child(parent, pos, tokens)
    }

    /// Every live block with its handle, root-first in insertion order
    /// (a parent always precedes its children).
    pub fn entries(&self) -> Vec<(SealedId, B)> {
        self.nodes.iter().enumerate()
            .filter_map(|(i, n)| n.as_ref().map(|n| (SealedId { tree: self.tree, index: i as u32 }, n.handle)))
            .collect()
    }

    /// Keep the end of this block as a start point for one more holder.
    /// Start points are counted: two holders are normal (a lane head and
    /// a prompt end), and the point survives until the last release.
    /// `Ok(false)` when the id names no block in this tree; the count is
    /// checked, like Johnny's slot-record mutators, never saturated.
    pub fn retain_start(&mut self, id: SealedId) -> Result<bool, BlockError> {
        match self.node_mut(id) {
            Some(n) => {
                n.starts = n.starts.checked_add(1).ok_or(BlockError::Overflow)?;
                Ok(true)
            }
            None => Ok(false),
        }
    }

    /// The caller's handle on a block in this tree, if it is here.
    pub fn handle(&self, id: SealedId) -> Option<B> {
        self.node(id).map(|n| n.handle)
    }

    /// Replace a live block's stored handle in place (e.g. refreshing a stale window entry
    /// without removing descendants or breaking active start points).
    pub fn set_handle(&mut self, id: SealedId, handle: B) -> bool {
        match self.node_mut(id) {
            Some(n) => { n.handle = handle; true }
            None => false,
        }
    }

    /// Remove `id` and any ancestors that have no children, no start holders, and no active pins.
    pub fn prune_unreferenced(&mut self, mut id: SealedId) -> usize {
        let mut removed = 0usize;
        while let Some(n) = self.node(id) {
            if !n.children.is_empty() || n.starts > 0 || n.pins > 0 {
                break;
            }
            let parent = n.parent;
            self.remove(id);
            removed += 1;
            match parent {
                Some(p) => id = p,
                None => break,
            }
        }
        removed
    }

    /// Drop one holder of a start point. Returns false when the id names
    /// no block here or the point had no holder left; an evicted block
    /// and a drained point are the same `false`, so a caller that must
    /// tell them apart checks `handle` or `start_holders` first.
    pub fn release_start(&mut self, id: SealedId) -> bool {
        match self.node_mut(id) {
            Some(n) if n.starts > 0 => { n.starts -= 1; true }
            _ => false,
        }
    }

    /// How many holders keep this block's end as a start point.
    pub fn start_holders(&self, id: SealedId) -> u32 {
        self.node(id).map(|n| n.starts).unwrap_or(0)
    }

    /// How many pins hold this block. Pins are counted here; the pool
    /// ref behind them is the live tree's business (one ref per block,
    /// taken at the first pin).
    pub fn pin_count(&self, id: SealedId) -> u32 {
        self.node(id).map(|n| n.pins).unwrap_or(0)
    }

    /// Add one pin. `Ok(false)` when the id names no block here.
    pub fn pin(&mut self, id: SealedId) -> Result<bool, BlockError> {
        match self.node_mut(id) {
            Some(n) => { n.pins = n.pins.checked_add(1).ok_or(BlockError::Overflow)?; Ok(true) }
            None => Ok(false),
        }
    }

    /// Drop one pin. Returns false when the id names no block here or
    /// the block had no pin left.
    pub fn unpin(&mut self, id: SealedId) -> bool {
        match self.node_mut(id) {
            Some(n) if n.pins > 0 => { n.pins -= 1; true }
            _ => false,
        }
    }

    /// Remove this block and everything below it; the tree shrinks, and
    /// the removed handles come back root-first so the caller can drop
    /// whatever the blocks held. Ids are never reused. Returns an empty
    /// vec when the id names no block in this tree.
    pub fn remove(&mut self, id: SealedId) -> Vec<B> {
        self.remove_with_pins(id).into_iter().map(|(h, _)| h).collect()
    }

    /// `remove`, with each removed block's pin count beside its handle,
    /// root-first: the caller drops one pool ref per pinned block.
    pub fn remove_with_pins(&mut self, id: SealedId) -> Vec<(B, u32)> {
        let Some(node) = self.node(id) else { return Vec::new() };
        let parent = node.parent;
        // collect the subtree before touching anything
        let mut gone = vec![id];
        let mut i = 0;
        while i < gone.len() {
            let kids = self.node(gone[i]).map(|n| n.children.clone()).unwrap_or_default();
            gone.extend(kids);
            i += 1;
        }
        match parent {
            None => self.roots.retain(|&r| r != id),
            Some(p) => if let Some(n) = self.node_mut(p) { n.children.retain(|&c| c != id); },
        }
        let mut handles = Vec::new();
        for g in gone {
            let n = self.nodes[g.index as usize].take().expect("collected blocks are live");
            if let Some(bucket) = self.by_digest.get_mut(&n.digest) {
                bucket.retain(|&b| b != g);
                if bucket.is_empty() { self.by_digest.remove(&n.digest); }
            }
            handles.push((n.handle, n.pins));
        }
        handles
    }

    /// The child of `parent` (or a root) whose tokens are exactly this
    /// block. The digest bucket narrows the search; tokens decide.
    fn child(&self, parent: Option<SealedId>, pos: usize, tokens: &[u32]) -> Option<SealedId> {
        let bucket = self.by_digest.get(&digest(parent, pos, tokens))?;
        for &id in bucket {
            let n = self.node(id)?;
            if n.parent == parent && n.pos == pos && n.tokens.as_ref() == tokens { return Some(id); }
        }
        None
    }
}

impl<B: Copy> Default for PrefixTree<B> {
    fn default() -> Self { Self::new() }
}

impl<B: Copy> PrefixMatch<B> for PrefixTree<B> {
    fn deepest_start(&self, tokens: &[u32]) -> StartMatch<B> {
        let mut best = StartMatch { at: 0, start: None, ids: Vec::new(), blocks: Vec::new() };
        let mut parent = None;
        let mut ids: Vec<SealedId> = Vec::new();
        let mut chain: Vec<B> = Vec::new();
        let mut at = 0usize;
        while tokens.len() - at >= BLOCK {
            let Some(id) = self.child(parent, at, &tokens[at..at + BLOCK]) else { break };
            let n = self.node(id).expect("a child id names a live block");
            ids.push(id);
            chain.push(n.handle);
            at += BLOCK;
            parent = Some(id);
            if n.starts > 0 {
                best = StartMatch { at, start: Some(id), ids: ids.clone(), blocks: chain.clone() };
            }
        }
        best
    }
}

/// The pool's slot records, as the live matcher needs them. Johnny's pool
/// worker owns the records; this seam is only the three operations the
/// tree performs on them, so the tree never names the pool type.
pub trait SlotRecords {
    /// Take one more ref on a slot, for an entry at `generation`. The
    /// record must refuse when it is no longer at that generation:
    /// a generation-blind ref would pin (or, on drop, corrupt) the
    /// slot's new owner after a reuse.
    fn add_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError>;
    /// Drop one ref, under the same generation check as `add_ref`.
    fn drop_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError>;
    /// The generation the slot is at now, or `None` when it is not live.
    fn generation(&self, slot: Slot, kind: BlockKind) -> Option<u32>;
}

/// Why a live insert or removal failed.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum LiveError {
    /// The tree refused the block; the pool was left as it was.
    Insert(InsertError),
    /// A slot record refused (overflow, a drop at zero, out of range).
    Pool(BlockError),
    /// The entry names a generation its slot is no longer at (or a slot
    /// that is not live): the entry is stale on arrival, so nothing was
    /// inserted and no ref was taken.
    StaleEntry { slot: Slot, claimed: u32, current: Option<u32> },
    /// A handles pair whose entries are not one `Full` and at most one
    /// `Window` entry.
    WrongKind { expected: BlockKind, got: BlockKind },
}

impl From<InsertError> for LiveError {
    fn from(e: InsertError) -> LiveError { LiveError::Insert(e) }
}

impl From<BlockError> for LiveError {
    fn from(e: BlockError) -> LiveError { LiveError::Pool(e) }
}

/// The prefix matcher over live pool slots. A cached block sits at
/// zero pool refs: it is evictable, and lookup validates it by
/// generation instead of by holding it. A lane pins a block it is
/// actively stepping from; the first pin takes one generation-checked
/// ref on each of the block's entries, and the last unpin drops them
/// the same checked way, so a slot reused in between never has its
/// new owner's refcount corrupted. A seek evicts every stale block
/// (each with everything below it) before matching, as the model's
/// `Seek` does, and never returns the whole prompt: the final token
/// must remain for prefill, so an exact full match steps back one
/// block.
pub struct LiveTree<R> {
    tree: EntryTree,
    records: R,
}

impl<R: SlotRecords> LiveTree<R> {
    pub fn new(records: R) -> LiveTree<R> {
        LiveTree { tree: PrefixTree::new(), records }
    }

    fn check_current(&self, e: BlockEntry) -> Result<(), LiveError> {
        match self.records.generation(e.slot(), e.kind()) {
            Some(g) if g == e.generation() => Ok(()),
            current => Err(LiveError::StaleEntry { slot: e.slot(), claimed: e.generation(), current }),
        }
    }

    fn handles_current(&self, h: BlockHandles) -> Result<(), LiveError> {
        for e in h.entries() { self.check_current(e)?; }
        Ok(())
    }

    /// Drop the ref behind one entry, only while the record is still
    /// at the entry's generation. A slot reused since the entry was
    /// sealed has a new owner (and, on Emma's poolgate, its refcount
    /// was reset at the reuse): dropping then would corrupt it, so a
    /// generation mismatch skips the drop, never forces it.
    fn drop_ref_if_current(&mut self, e: BlockEntry) -> Result<(), LiveError> {
        if self.records.generation(e.slot(), e.kind()) == Some(e.generation()) {
            self.records.drop_ref(e.slot(), e.kind(), e.generation())?;
        }
        Ok(())
    }

    fn drop_pinned(&mut self, h: BlockHandles) -> Result<(), LiveError> {
        for e in h.entries() { self.drop_ref_if_current(e)?; }
        Ok(())
    }

    /// Add one sealed block. The block is cached at zero pool refs:
    /// no ref is taken here. Both entries must name their slots'
    /// current generations (a stale entry, or one naming a slot that
    /// is not live, is refused before anything is inserted, even when
    /// its tokens are already in the tree), and the pair must be one
    /// `Full` entry plus at most one `Window` entry. A block already
    /// in the tree (a racing publisher) returns the canonical block —
    /// unless the twin in the tree is stale: its slot has moved on, so
    /// the twin is evicted (its pinned refs dropped, checked) and the
    /// fresh block takes its place, also unpinned. The returned id's
    /// handles may be another publisher's entries; `handle` shows the
    /// pair the tree actually holds.
    pub fn insert(&mut self, parent: Option<SealedId>, pos: usize, tokens: &[u32], handles: BlockHandles) -> Result<SealedId, LiveError> {
        if handles.full.kind() != BlockKind::Full {
            return Err(LiveError::WrongKind { expected: BlockKind::Full, got: handles.full.kind() });
        }
        if let Some(w) = handles.window {
            if w.kind() != BlockKind::Window {
                return Err(LiveError::WrongKind { expected: BlockKind::Window, got: w.kind() });
            }
        }
        self.handles_current(handles)?;
        if tokens.len() == BLOCK {
            if let Some(id) = self.tree.find(parent, pos, tokens) {
                let twin = self.tree.handle(id).expect("a found block has handles");
                if self.handles_current(twin).is_ok() { return Ok(id); }
                self.remove(id)?; // the stale twin: evict it, then insert fresh below
            }
        }
        Ok(self.tree.insert(parent, pos, tokens, handles)?)
    }

    /// Pin a block for an active lane or step. The first pin takes one
    /// generation-checked ref on each of the block's entries; further
    /// pins only count. A stale block cannot be pinned. `Ok(false)`
    /// when the id names no block here.
    pub fn pin(&mut self, id: SealedId) -> Result<bool, LiveError> {
        let Some(handles) = self.tree.handle(id) else { return Ok(false) };
        self.handles_current(handles)?;
        if self.tree.pin_count(id) == 0 {
            let mut taken: Vec<BlockEntry> = Vec::new();
            for e in handles.entries() {
                match self.records.add_ref(e.slot(), e.kind(), e.generation()) {
                    Ok(()) => taken.push(e),
                    Err(err) => {
                        for t in taken { let _ = self.drop_ref_if_current(t); }
                        return Err(err.into());
                    }
                }
            }
        }
        self.tree.pin(id)?;
        Ok(true)
    }

    /// Drop one pin. At the last pin the entries' refs are dropped,
    /// generation-checked: a slot reused while pinned keeps its new
    /// owner's refcount untouched. `Ok(false)` when the id names no
    /// block here or the block had no pin left.
    pub fn unpin(&mut self, id: SealedId) -> Result<bool, LiveError> {
        let Some(handles) = self.tree.handle(id) else { return Ok(false) };
        if self.tree.pin_count(id) == 0 { return Ok(false); }
        if self.tree.pin_count(id) == 1 { self.drop_pinned(handles)?; }
        Ok(self.tree.unpin(id))
    }

    /// How many pins hold this block.
    pub fn pin_count(&self, id: SealedId) -> u32 { self.tree.pin_count(id) }

    /// Keep or drop one holder of a start point (see `PrefixTree`).
    pub fn retain_start(&mut self, id: SealedId) -> Result<bool, BlockError> { self.tree.retain_start(id) }
    pub fn release_start(&mut self, id: SealedId) -> bool { self.tree.release_start(id) }

    /// The handles the tree holds on a block, if it is here. After a
    /// racing publisher's `Ok(id)`, this is how the caller tells whose
    /// entries the tree kept.
    pub fn handle(&self, id: SealedId) -> Option<BlockHandles> { self.tree.handle(id) }

    /// Remove a block and everything below it. Pinned blocks among
    /// them drop their refs generation-checked (see
    /// `drop_ref_if_current`); idle blocks held no ref to drop.
    pub fn remove(&mut self, id: SealedId) -> Result<Vec<BlockHandles>, LiveError> {
        let removed = self.tree.remove_with_pins(id);
        let mut first_err = None;
        for (h, pins) in &removed {
            if *pins > 0 {
                if let Err(e) = self.drop_pinned(*h) {
                    if first_err.is_none() { first_err = Some(e); }
                }
            }
        }
        let handles: Vec<BlockHandles> = removed.into_iter().map(|(h, _)| h).collect();
        match first_err {
            None => Ok(handles),
            Some(e) => Err(e),
        }
    }

    /// The deepest start point whose blocks are all still the slots
    /// and generations the tree sealed them at. A seek first evicts
    /// every stale block in the tree — not only those on the matched
    /// path, as the model's `Seek` does — so a later lookup never
    /// meets it; a pool error from an eviction is returned, not
    /// swallowed. The result never covers the whole prompt when the
    /// prompt is non-empty: an exact full match steps back one block,
    /// leaving at least the final token to prefill.
    pub fn deepest_start(&mut self, tokens: &[u32]) -> Result<StartMatch<BlockHandles>, LiveError> {
        let stale: Vec<SealedId> = self.tree.entries().into_iter()
            .filter(|(_, h)| h.entries().any(|e| self.records.generation(e.slot(), e.kind()) != Some(e.generation())))
            .map(|(id, _)| id)
            .collect();
        for id in stale {
            // an ancestor's eviction already took this block: removing
            // it again removes nothing and drops no second ref
            self.remove(id)?;
        }
        let m = self.tree.deepest_start(tokens);
        if !tokens.is_empty() && m.at == tokens.len() {
            // exact full-prompt match: step back one block so the
            // suffix to prefill is never empty
            return Ok(self.tree.deepest_start(&tokens[..tokens.len() - BLOCK]));
        }
        Ok(m)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::blocks::SlotRecord;

    fn block(seed: u32) -> Vec<u32> { (0..BLOCK as u32).map(|i| seed * 1000 + i).collect() }

    fn tree3() -> (PrefixTree<u64>, Vec<SealedId>) {
        let mut t = PrefixTree::new();
        let a = t.insert(None, 0, &block(1), 10).unwrap();
        let b = t.insert(Some(a), BLOCK, &block(2), 20).unwrap();
        let c = t.insert(Some(b), 2 * BLOCK, &block(3), 30).unwrap();
        (t, vec![a, b, c])
    }

    #[test]
    fn an_empty_tree_starts_at_zero() {
        let t: PrefixTree<u64> = PrefixTree::new();
        let m = t.deepest_start(&block(1));
        assert_eq!(m, StartMatch { at: 0, start: None, ids: vec![], blocks: vec![] });
    }

    #[test]
    fn the_deepest_retained_start_point_wins() {
        let (mut t, ids) = tree3();
        t.retain_start(ids[0]).unwrap();
        t.retain_start(ids[2]).unwrap();
        let toks = [block(1), block(2), block(3), block(9)].concat();
        let m = t.deepest_start(&toks);
        assert_eq!(m.at, 3 * BLOCK);
        assert_eq!(m.start, Some(ids[2]));
        assert_eq!(m.ids, ids);
        assert_eq!(m.blocks, vec![10, 20, 30], "handles from the root to the start point, in order");
    }

    #[test]
    fn start_points_are_counted_not_boolean() {
        // Rowan's failing case: a lane head and a prompt end both hold
        // the same point; one release must not unmatch it.
        let (mut t, ids) = tree3();
        t.retain_start(ids[2]).unwrap();
        t.retain_start(ids[2]).unwrap();
        assert_eq!(t.start_holders(ids[2]), 2);
        let toks = [block(1), block(2), block(3)].concat();
        assert!(t.release_start(ids[2]), "the lane head lets go");
        assert_eq!(t.deepest_start(&toks).at, 3 * BLOCK, "the prompt end still holds it");
        assert!(t.release_start(ids[2]));
        assert_eq!(t.deepest_start(&toks).at, 0, "the last release unmatches it");
        assert!(!t.release_start(ids[2]), "no holder left to release");
    }

    #[test]
    fn a_block_that_differs_anywhere_stops_the_match() {
        let (mut t, ids) = tree3();
        t.retain_start(ids[2]).unwrap();
        let mut second = block(2);
        second[63] ^= 1;
        let toks = [block(1), second, block(3)].concat();
        assert_eq!(t.deepest_start(&toks).at, 0, "the second block differs, so even the third block's start point is unreachable");
        let (mut t2, ids2) = tree3();
        t2.retain_start(ids2[1]).unwrap();
        assert_eq!(t2.deepest_start(&[block(1), block(7)].concat()).at, 0);
    }

    #[test]
    fn equal_local_tokens_under_different_parents_are_different_blocks() {
        let mut t: PrefixTree<u64> = PrefixTree::new();
        let a = t.insert(None, 0, &block(1), 10).unwrap();
        let x = t.insert(None, 0, &block(5), 50).unwrap();
        let a2 = t.insert(Some(a), BLOCK, &block(2), 20).unwrap();
        let x2 = t.insert(Some(x), BLOCK, &block(2), 60).unwrap();
        assert_ne!(a2, x2);
        t.retain_start(a2).unwrap();
        t.retain_start(x2).unwrap();
        assert_eq!(t.deepest_start(&[block(5), block(2)].concat()).blocks, vec![50, 60],
            "the match follows the parent chain, never the local tokens alone");
        assert_eq!(t.deepest_start(&[block(1), block(2)].concat()).blocks, vec![10, 20]);
    }

    #[test]
    fn racing_publishers_dedupe_only_on_exact_tokens() {
        let mut t: PrefixTree<u64> = PrefixTree::new();
        let a = t.insert(None, 0, &block(1), 10).unwrap();
        assert_eq!(t.insert(None, 0, &block(1), 99), Ok(a), "the same block again is the canonical one, with its first handle");
        assert_ne!(t.insert(None, 0, &block(2), 20).unwrap(), a, "different tokens are a different root");
    }

    #[test]
    fn unsealed_misplaced_and_foreign_blocks_never_enter() {
        let mut t: PrefixTree<u64> = PrefixTree::new();
        let mut other: PrefixTree<u64> = PrefixTree::new();
        let foreign = other.insert(None, 0, &block(1), 1).unwrap();
        assert_eq!(t.insert(None, 0, &block(1)[..63], 10), Err(InsertError::NotFullBlock(63)), "a partial tail is unsealed");
        assert_eq!(t.insert(None, BLOCK, &block(1), 10), Err(InsertError::WrongPosition { expected: 0, got: BLOCK }));
        assert_eq!(t.insert(Some(foreign), BLOCK, &block(1), 10), Err(InsertError::ForeignId),
            "an id from another tree names nothing here, even at an existing index");
        assert_eq!(t.retain_start(foreign), Ok(false), "a foreign id is no block here");
        assert!(t.remove(foreign).is_empty());
        let a = t.insert(None, 0, &block(1), 10).unwrap();
        assert_eq!(t.insert(Some(a), 0, &block(2), 20), Err(InsertError::WrongPosition { expected: BLOCK, got: 0 }));
        // a removed block is unknown to its own tree, not foreign
        t.remove(a);
        assert_eq!(t.insert(Some(a), BLOCK, &block(2), 20), Err(InsertError::UnknownParent));
    }

    #[test]
    fn remove_shrinks_the_tree_and_returns_handles() {
        let (mut t, ids) = tree3();
        t.retain_start(ids[2]).unwrap();
        let toks = [block(1), block(2), block(3)].concat();
        assert_eq!(t.remove(ids[1]), vec![20, 30], "the block and everything below it, root-first");
        assert_eq!(t.deepest_start(&toks).at, 0);
        assert!(t.remove(ids[1]).is_empty(), "already gone");
        // the same tokens publish again as new blocks; no stale digest entry answers
        let b = t.insert(Some(ids[0]), BLOCK, &block(2), 21).unwrap();
        assert_ne!(b, ids[1], "ids are never reused");
        t.retain_start(b).unwrap();
        assert_eq!(t.deepest_start(&toks).blocks, vec![10, 21]);
    }

    #[test]
    fn a_partial_final_block_and_sixteen_block_starts() {
        let mut t: PrefixTree<u64> = PrefixTree::new();
        let mut parent = None;
        let mut ids = Vec::new();
        for i in 0..17u32 {
            let id = t.insert(parent, i as usize * BLOCK, &block(i + 1), i as u64).unwrap();
            ids.push(id);
            parent = Some(id);
        }
        t.retain_start(ids[15]).unwrap(); // a 16th-block-boundary start point, position 1024
        let mut toks: Vec<u32> = (1..=17u32).flat_map(block).collect();
        assert_eq!(t.deepest_start(&toks).at, 16 * BLOCK);
        toks.truncate(16 * BLOCK + 63);
        let m = t.deepest_start(&toks);
        assert_eq!(m.at, 16 * BLOCK, "63 tokens into block 17 is not a block");
        assert_eq!(m.blocks.len(), 16);
    }

    /// Johnny's slot records behind the test's own map: the fake is only
    /// storage; every record in it is his `SlotRecord`.
    #[derive(Default)]
    struct FakeRecords { map: HashMap<(u32, bool), SlotRecord> }

    impl FakeRecords {
        fn key(slot: Slot, kind: BlockKind) -> (u32, bool) { (slot.get(), kind == BlockKind::Full) }
        fn record(&mut self, slot: Slot, kind: BlockKind) -> &mut SlotRecord {
            // a record starts at generation 1 when the slot is first
            // taken: generation 0 is "never taken" (blocks.rs)
            self.map.entry(Self::key(slot, kind)).or_insert_with(|| {
                let mut r = SlotRecord::fresh(kind);
                r.bump_generation().unwrap();
                r
            })
        }
        fn refs(&mut self, slot: Slot, kind: BlockKind) -> u32 { self.record(slot, kind).refs() }
        fn pool_refs(&self, slot: Slot, kind: BlockKind) -> u32 {
            self.map.get(&Self::key(slot, kind)).map(|r| r.refs()).unwrap_or(0)
        }
        fn reuse(&mut self, slot: Slot, kind: BlockKind) {
            let r = self.record(slot, kind);
            while r.refs() > 0 { r.drop_ref().unwrap(); }
            r.reissue().unwrap();
        }
    }

    impl SlotRecords for FakeRecords {
        fn add_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError> {
            if self.generation(slot, kind) != Some(generation) { return Err(BlockError::Generation); }
            self.record(slot, kind).add_ref()
        }
        fn drop_ref(&mut self, slot: Slot, kind: BlockKind, generation: u32) -> Result<(), BlockError> {
            if self.generation(slot, kind) != Some(generation) { return Err(BlockError::Generation); }
            self.record(slot, kind).drop_ref()
        }
        fn generation(&self, slot: Slot, kind: BlockKind) -> Option<u32> {
            // an untouched slot reads as generation 1, the generation
            // `record` takes it at (fresh 0 bumped once on first use)
            Some(self.map.get(&Self::key(slot, kind)).map(|r| r.generation()).unwrap_or(1))
        }
    }

    fn entry(slot: u32, generation: u32, kind: BlockKind) -> BlockEntry {
        BlockEntry::new(Slot::new(slot).unwrap(), generation, 4096, kind, 2)
    }

    fn handles(slot: u32, generation: u32) -> BlockHandles {
        BlockHandles::new(entry(slot, generation, BlockKind::Full), None)
    }

    fn handles_win(slot: u32, generation: u32, wslot: u32, wgen: u32) -> BlockHandles {
        BlockHandles::new(entry(slot, generation, BlockKind::Full), Some(entry(wslot, wgen, BlockKind::Window)))
    }

    #[test]
    fn a_reused_slots_stale_entry_is_a_miss_never_a_match() {
        // Rowan's failing case: insert A at (slot 3, gen 1); the pool
        // reuses slot 3 at gen 2 for other tokens; A's tokens must miss,
        // and pinned refs must settle, not leak.
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
        let b = live.insert(Some(a), BLOCK, &block(2), handles(4, 1)).unwrap();
        live.retain_start(b).unwrap();
        let toks = [block(1), block(2)].concat();
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "a cached block sits at zero refs");
        live.pin(a).unwrap();
        live.pin(b).unwrap();
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1, "the first pin took the ref");
        live.retain_start(a).unwrap();
        assert_eq!(live.deepest_start(&toks).unwrap().at, BLOCK, "exact full match steps back one block");
        live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); // slot 3 is generation 2 now
        let m = live.deepest_start(&toks).unwrap();
        assert_eq!(m.at, 0, "the gen-1 entry for a gen-2 slot is stale: a miss, not a match");
        assert_eq!(live.deepest_start(&toks).unwrap().at, 0, "and it was evicted, not rechecked forever");
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "no ref leaks on the reused slot");
        assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Full), 0, "the evicted child's pinned ref was dropped too");
        // a fresh block at the slot's new generation matches again
        let a2 = live.insert(None, 0, &block(1), handles(3, 2)).unwrap();
        live.retain_start(a2).unwrap();
        assert_eq!(live.deepest_start(&block(1)).unwrap().at, 0, "one block is the whole prompt: the suffix is never empty");
        assert_eq!(live.deepest_start(&[block(1), block(9)].concat()).unwrap().blocks, vec![handles(3, 2)]);
    }

    #[test]
    fn a_fresh_block_is_never_lost_to_its_stale_twin() {
        // the stale twin is still in the tree when the fresh block is
        // sealed at the slot's new generation: the dedupe must evict
        // the twin and keep the fresh block, unpinned like any cache entry
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
        live.pin(a).unwrap();
        live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); // gen 2; the gen-1 twin is stale
        let a2 = live.insert(None, 0, &block(1), handles(3, 2)).unwrap();
        assert_ne!(a2, a, "the fresh block is a new block, not the stale twin");
        assert_eq!(live.pin_count(a2), 0, "the fresh block starts unpinned");
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0,
            "the twin's pin died with its generation; no blind drop touched the new owner");
        live.pin(a2).unwrap();
        live.retain_start(a2).unwrap();
        assert_eq!(live.deepest_start(&[block(1), block(9)].concat()).unwrap().blocks, vec![handles(3, 2)],
            "and the fresh block survives the next seek");
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1);
    }

    #[test]
    fn a_stale_entry_is_refused_at_insert() {
        // the cold reader's probe: slot 3 is at generation 2, and a
        // generation-1 entry must not be accepted — for new tokens or
        // for tokens already in the tree — and must take no ref
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
        live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); // slot 3 is generation 2 now
        let stale = LiveError::StaleEntry { slot: Slot::new(3).unwrap(), claimed: 1, current: Some(2) };
        assert_eq!(live.insert(None, 0, &block(9), handles(3, 1)), Err(stale.clone()),
            "a gen-1 entry for a gen-2 slot is refused, not inserted");
        assert_eq!(live.insert(None, 0, &block(1), handles(3, 1)), Err(stale),
            "the same refusal when the tokens are already in the tree");
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "no ref was taken by either refusal");
        assert_eq!(live.handle(a), Some(handles(3, 1)), "the tree is unchanged");
        // a fresh entry at the current generation still lands
        assert!(live.insert(None, 0, &block(9), handles(3, 2)).is_ok());
    }

    #[test]
    fn a_seek_evicts_stale_blocks_off_the_matched_path() {
        // the model's Seek evicts every stale block; the code does the
        // same, so a stale block the request never touches is gone
        // after any seek, not only after a matching one
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
        let off = live.insert(None, 0, &block(7), handles(4, 1)).unwrap();
        live.retain_start(a).unwrap();
        live.pin(off).unwrap();
        live.records.reuse(Slot::new(4).unwrap(), BlockKind::Full); // slot 4 at gen 2: `off` is stale
        let m = live.deepest_start(&[block(1), block(9)].concat()).unwrap();
        assert_eq!(m.at, BLOCK, "the live path still matches");
        assert_eq!(live.handle(off), None, "the stale off-path block was evicted by the seek");
        assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Full), 0, "and no ref is left on the reused slot");
    }

    #[test]
    fn pins_take_and_drop_one_ref_per_block() {
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles_win(3, 1, 4, 1)).unwrap();
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "idle: no Full ref");
        assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Window), 0, "idle: no Window ref");
        live.pin(a).unwrap();
        live.pin(a).unwrap();
        assert_eq!(live.pin_count(a), 2);
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1, "two pins, one Full ref");
        assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Window), 1, "two pins, one Window ref");
        assert_eq!(live.handle(a).unwrap().window(), Some(entry(4, 1, BlockKind::Window)), "both entries ride on the node");
        live.unpin(a).unwrap();
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1, "a pin remains");
        live.unpin(a).unwrap();
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "the last unpin dropped the Full ref");
        assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Window), 0, "and the Window ref");
        assert_eq!(live.unpin(a), Ok(false), "no pin left to drop");
        // removing a pinned block drops its refs; removing an idle one drops none
        live.pin(a).unwrap();
        let gone = live.remove(a).unwrap();
        assert_eq!(gone, vec![handles_win(3, 1, 4, 1)]);
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0);
    }

    #[test]
    fn a_reused_slots_new_owner_keeps_its_refcount() {
        // the generation-checked drop: a block pinned at gen 1, its
        // slot reused to gen 2 and re-owned; evicting the stale block
        // must not drop the new owner's ref
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
        live.pin(a).unwrap();
        live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full); // gen 2; Emma's poolgate resets refs there
        live.records.add_ref(Slot::new(3).unwrap(), BlockKind::Full, 2).unwrap(); // the new owner's ref
        live.remove(a).unwrap();
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 1,
            "the stale block's eviction skipped the drop: the new owner's ref stands");
        // and a generation-blind checked drop at the old generation refuses outright
        assert_eq!(live.records.drop_ref(Slot::new(3).unwrap(), BlockKind::Full, 1), Err(BlockError::Generation));
    }

    #[test]
    fn live_inserts_and_removes_balance_their_refs() {
        let mut live = LiveTree::new(FakeRecords::default());
        let a = live.insert(None, 0, &block(1), handles(3, 1)).unwrap();
        assert_eq!(live.insert(None, 0, &block(1), handles(3, 1)), Ok(a), "a racing publisher dedupes");
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "and still takes no ref");
        // a refused insert takes no ref either
        assert!(live.insert(Some(a), 0, &block(2), handles(4, 1)).is_err());
        assert_eq!(live.records.refs(Slot::new(4).unwrap(), BlockKind::Full), 0);
        live.pin(a).unwrap();
        let gone = live.remove(a).unwrap();
        assert_eq!(gone, vec![handles(3, 1)]);
        assert_eq!(live.records.refs(Slot::new(3).unwrap(), BlockKind::Full), 0, "removal dropped the pinned ref");
    }

    /// One abstract block of the model (two tokens over {1, 2}) as a
    /// code block: the first token fills the first half, the second
    /// the second half, so abstractly distinct blocks stay distinct.
    fn enc(block: [u32; 2]) -> Vec<u32> {
        let mut v = vec![block[0]; BLOCK / 2];
        v.extend([block[1]; BLOCK / 2]);
        v
    }

    fn tla_seq(s: &[u32]) -> String {
        let inner: Vec<String> = s.iter().map(|t| t.to_string()).collect();
        format!("<<{}>>", inner.join(", "))
    }

    /// The model's block-boundary sequences over {1, 2}, shortest first.
    fn tla_universe() -> Vec<Vec<u32>> {
        let mut u = vec![Vec::new()];
        for a in 1..=2 { for b in 1..=2 { u.push(vec![a, b]); } }
        for a in 1..=2 { for b in 1..=2 { for c in 1..=2 { for d in 1..=2 { u.push(vec![a, b, c, d]); } } } }
        u
    }

    fn tla_fn(values: &HashMap<Vec<u32>, i64>) -> String {
        // a CASE function over the whole domain: explicit-point
        // function literals ([<<>> |-> 0, ...]) do not parse
        let cases: Vec<String> = tla_universe().iter()
            .filter(|s| values.get(*s).copied().unwrap_or(0) != 0)
            .map(|s| format!("s = {} -> {}", tla_seq(s), values[s]))
            .collect();
        if cases.is_empty() { return "[s \\in BlockSeqs |-> 0]".to_string(); }
        format!("[s \\in BlockSeqs |-> CASE {} [] OTHER -> 0]", cases.join(" [] "))
    }

    /// The trace dump behind the `PrefixTreeTrace` TLC check: a seeded
    /// walk over `LiveTree` (slots 1-3, abstract generations one below
    /// the records' so the model starts at 0), every operation's
    /// resulting state emitted as one row of `PrefixTreeTraceData.tla`.
    /// TLC then checks the emitted states are behaviours of
    /// `specs/PrefixTree.tla`. The walk opens with a steered pass over
    /// the model's request — held starts, pins, a stale root, a
    /// stale-twin reinsert — then wanders, seeks included, so a broken
    /// seek writes a row the model cannot step to. Ignored by default;
    /// `specs/run_tlc.zsh` runs it before the trace check.
    #[test]
    #[ignore = "trace dump; run by specs/run_tlc.zsh"]
    fn prefix_trace_dump() {
        let out = std::env::var("INKY_PREFIX_TRACE_OUT")
            .unwrap_or_else(|_| "specs/PrefixTreeTraceData.tla".to_string());
        let mut live = LiveTree::new(FakeRecords::default());
        let mut seq_of: HashMap<SealedId, Vec<u32>> = HashMap::new();
        let mut rows: Vec<String> = Vec::new();
        let mut random: u64 = 0x9e3779b97f4a7c15;
        let mut pick = move |n: usize| -> usize {
            random = random.wrapping_mul(6364136223846793005).wrapping_add(1);
            (random >> 32) as usize % n
        };

        let snapshot = |live: &LiveTree<FakeRecords>, seq_of: &HashMap<SealedId, Vec<u32>>,
                        op: &str, s: &[u32], slot: u32, wslot: u32, result: &[u32], sought: bool| -> String {
            let mut sealed: Vec<String> = vec![tla_seq(&[])];
            let (mut starts, mut slot_of_m, mut gen_of, mut win_slot, mut win_gen, mut refs) =
                (HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new(), HashMap::new());
            for (id, h) in live.tree.entries() {
                let seq = seq_of[&id].clone();
                sealed.push(tla_seq(&seq));
                starts.insert(seq.clone(), live.tree.start_holders(id) as i64);
                slot_of_m.insert(seq.clone(), h.full().slot().get() as i64);
                gen_of.insert(seq.clone(), h.full().generation() as i64 - 1);
                if let Some(w) = h.window() {
                    win_slot.insert(seq.clone(), w.slot().get() as i64);
                    win_gen.insert(seq.clone(), w.generation() as i64 - 1);
                }
                if live.pin_count(id) > 0 { refs.insert(seq, 1); }
            }
            // the pool's own counts, read from the records (both kinds
            // summed per slot): PoolBooks in PrefixTreeTrace binds them
            // to the pinned blocks and their entries
            let pr = |sl: u32| live.records.pool_refs(Slot::new(sl).unwrap(), BlockKind::Full)
                + live.records.pool_refs(Slot::new(sl).unwrap(), BlockKind::Window);
            let pool_refs = format!("[s \\in Slots |-> IF s = 1 THEN {} ELSE IF s = 2 THEN {} ELSE {}]", pr(1), pr(2), pr(3));
            let g = |sl: u32| live.records.generation(Slot::new(sl).unwrap(), BlockKind::Full).unwrap() - 1;
            let pool = format!("[s \\in Slots |-> IF s = 1 THEN {} ELSE IF s = 2 THEN {} ELSE {}]", g(1), g(2), g(3));
            format!(
                "[op |-> \"{op}\", s |-> {}, slot |-> {slot}, wslot |-> {wslot}, sealed |-> {{{}}}, starts |-> {}, \
                 slotOf |-> {}, genOf |-> {}, winSlotOf |-> {}, winGenOf |-> {}, poolGen |-> {}, refs |-> {}, poolRefs |-> {}, result |-> {}, sought |-> {}, bad |-> FALSE]",
                tla_seq(s), sealed.join(", "), tla_fn(&starts), tla_fn(&slot_of_m),
                tla_fn(&gen_of), tla_fn(&win_slot), tla_fn(&win_gen), pool, tla_fn(&refs), pool_refs, tla_seq(result),
                if sought { "TRUE" } else { "FALSE" })
        };
        let req_abstract: Vec<u32> = vec![1, 2, 1, 2];
        let req: Vec<u32> = [enc([1, 2]), enc([1, 2])].concat();
        // a handles pair on two distinct slots, at their current generations
        let pair = |live: &LiveTree<FakeRecords>, slot: u32, wslot: u32| -> BlockHandles {
            let fg = live.records.generation(Slot::new(slot).unwrap(), BlockKind::Full).unwrap();
            let wg = live.records.generation(Slot::new(wslot).unwrap(), BlockKind::Window).unwrap();
            handles_win(slot, fg, wslot, wg)
        };

        rows.push(snapshot(&live, &seq_of, "init", &[], 0, 0, &[], false));

        // --- the steered pass over the model's request ---
        let root = live.insert(None, 0, &enc([1, 2]), pair(&live, 1, 3)).unwrap();
        seq_of.insert(root, vec![1, 2]);
        rows.push(snapshot(&live, &seq_of, "seal", &[1, 2], 1, 3, &[], false));
        let child = live.insert(Some(root), BLOCK, &enc([1, 2]), pair(&live, 2, 1)).unwrap();
        seq_of.insert(child, req_abstract.clone());
        rows.push(snapshot(&live, &seq_of, "seal", &req_abstract, 2, 1, &[], false));
        live.retain_start(root).unwrap();
        rows.push(snapshot(&live, &seq_of, "retain", &[1, 2], 0, 0, &[], false));
        live.retain_start(child).unwrap();
        rows.push(snapshot(&live, &seq_of, "retain", &req_abstract, 0, 0, &[], false));
        live.pin(root).unwrap();
        rows.push(snapshot(&live, &seq_of, "pin", &[1, 2], 0, 0, &[], false));
        live.pin(child).unwrap();
        rows.push(snapshot(&live, &seq_of, "pin", &req_abstract, 0, 0, &[], false));
        let m = live.deepest_start(&req).unwrap();
        rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
        // only the child held now: the clamped result is position 0,
        // where a shallowest-start bug would still answer the child
        assert!(live.release_start(root));
        rows.push(snapshot(&live, &seq_of, "release", &[1, 2], 0, 0, &[], false));
        live.unpin(child).unwrap();
        rows.push(snapshot(&live, &seq_of, "unpin", &req_abstract, 0, 0, &[], false));
        let m = live.deepest_start(&req).unwrap();
        rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
        live.unpin(root).unwrap();
        rows.push(snapshot(&live, &seq_of, "unpin", &[1, 2], 0, 0, &[], false));
        // the root's slots move on: the root (and the child below it) is stale
        live.records.reuse(Slot::new(1).unwrap(), BlockKind::Full);
        live.records.reuse(Slot::new(1).unwrap(), BlockKind::Window);
        rows.push(snapshot(&live, &seq_of, "reuse", &[], 1, 0, &[], false));
        let m = live.deepest_start(&req).unwrap();
        rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
        // the stale twin, reinserted fresh on other slots
        let root2 = live.insert(None, 0, &enc([1, 2]), pair(&live, 3, 2)).unwrap();
        seq_of.insert(root2, vec![1, 2]);
        rows.push(snapshot(&live, &seq_of, "seal", &[1, 2], 3, 2, &[], false));
        live.retain_start(root2).unwrap();
        rows.push(snapshot(&live, &seq_of, "retain", &[1, 2], 0, 0, &[], false));
        live.records.reuse(Slot::new(3).unwrap(), BlockKind::Full);
        live.records.reuse(Slot::new(3).unwrap(), BlockKind::Window);
        rows.push(snapshot(&live, &seq_of, "reuse", &[], 3, 0, &[], false));
        let fresh = pair(&live, 2, 1);
        let root3 = live.insert(None, 0, &enc([1, 2]), fresh).unwrap();
        assert_ne!(root3, root2, "the fresh block replaces the stale twin");
        seq_of.retain(|id, _| *id != root2);
        seq_of.insert(root3, vec![1, 2]);
        rows.push(snapshot(&live, &seq_of, "seal-twin", &[1, 2], 2, 1, &[], false));
        live.retain_start(root3).unwrap();
        rows.push(snapshot(&live, &seq_of, "retain", &[1, 2], 0, 0, &[], false));
        live.pin(root3).unwrap();
        rows.push(snapshot(&live, &seq_of, "pin", &[1, 2], 0, 0, &[], false));
        let m = live.deepest_start(&req).unwrap();
        rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));

        // --- the wander: every operation, seeks included ---
        let mut mutating = 0;
        let mut attempts = 0;
        while mutating < 40 && attempts < 500 {
            attempts += 1;
            let live_ids: Vec<SealedId> = live.tree.entries().into_iter().map(|(id, _)| id).collect();
            seq_of.retain(|id, _| live_ids.contains(id));
            match pick(10) {
                0 => { // seal a fresh block under a live parent (or the root)
                    let parents: Vec<Option<SealedId>> = std::iter::once(None)
                        .chain(live_ids.iter().filter(|id| seq_of[id].len() == 2).map(|id| Some(*id)))
                        .collect();
                    let parent = parents[pick(parents.len())];
                    let base: Vec<u32> = parent.map(|p| seq_of[&p].clone()).unwrap_or_default();
                    let block = [1 + pick(2) as u32, 1 + pick(2) as u32];
                    let mut seq = base.clone();
                    seq.extend(block);
                    if seq_of.values().any(|s| *s == seq) { continue; }
                    let slot = 1 + pick(3) as u32;
                    let wslot = 1 + (slot + pick(2) as u32) % 3;
                    let id = live.insert(parent, base.len() / 2 * BLOCK, &enc(block),
                        pair(&live, slot, wslot)).expect("a fresh seal at the current generations");
                    seq_of.insert(id, seq.clone());
                    rows.push(snapshot(&live, &seq_of, "seal", &seq, slot, wslot, &[], false));
                }
                1 => { // a stale insert, refused: the state must not move
                    let slot = 1 + pick(3) as u32;
                    let gen = live.records.generation(Slot::new(slot).unwrap(), BlockKind::Full).unwrap();
                    if gen < 2 { continue; }
                    let block = [1 + pick(2) as u32, 1 + pick(2) as u32];
                    let got = live.insert(None, 0, &enc(block), handles(slot, gen - 1));
                    assert_eq!(got, Err(LiveError::StaleEntry {
                        slot: Slot::new(slot).unwrap(), claimed: gen - 1, current: Some(gen) }),
                        "the walk's stale insert is refused");
                    rows.push(snapshot(&live, &seq_of, "seal-stale", &block.to_vec(), slot, 0, &[], false));
                }
                2 => { // retain a start point (at most two holders each)
                    let held: Vec<SealedId> = live_ids.iter().copied()
                        .filter(|id| live.tree.start_holders(*id) < 2).collect();
                    if held.is_empty() { continue; }
                    let id = held[pick(held.len())];
                    live.retain_start(id).unwrap();
                    let seq = seq_of[&id].clone();
                    rows.push(snapshot(&live, &seq_of, "retain", &seq, 0, 0, &[], false));
                }
                3 => { // release a held start point
                    let held: Vec<SealedId> = live_ids.iter().copied()
                        .filter(|id| live.tree.start_holders(*id) > 0).collect();
                    if held.is_empty() { continue; }
                    let id = held[pick(held.len())];
                    assert!(live.release_start(id));
                    let seq = seq_of[&id].clone();
                    rows.push(snapshot(&live, &seq_of, "release", &seq, 0, 0, &[], false));
                }
                4 => { // reuse a slot, both kinds together (abstract generation at most 2);
                       // never a slot a pinned block names: the pool's Free rule
                    let slot = 1 + pick(3) as u32;
                    let gen = live.records.generation(Slot::new(slot).unwrap(), BlockKind::Full).unwrap();
                    if gen >= 3 { continue; }
                    let pinned_slots: Vec<u32> = live.tree.entries().into_iter()
                        .filter(|(id, _)| live.pin_count(*id) > 0)
                        .flat_map(|(_, h)| h.entries().map(|e| e.slot().get()).collect::<Vec<_>>())
                        .collect();
                    if pinned_slots.contains(&slot) { continue; }
                    live.records.reuse(Slot::new(slot).unwrap(), BlockKind::Full);
                    live.records.reuse(Slot::new(slot).unwrap(), BlockKind::Window);
                    rows.push(snapshot(&live, &seq_of, "reuse", &[], slot, 0, &[], false));
                }
                5 => { // insert a block that is already in the tree
                    if live_ids.is_empty() { continue; }
                    let id = live_ids[pick(live_ids.len())];
                    let seq = seq_of[&id].clone();
                    let twin = live.handle(id).unwrap();
                    let (parent, pos) = if seq.len() == 2 { (None, 0) } else {
                        let pid = *seq_of.iter().find(|(_, s)| **s == seq[..2]).unwrap().0;
                        (Some(pid), BLOCK)
                    };
                    let block = [seq[seq.len() - 2], seq[seq.len() - 1]];
                    let current = |e: BlockEntry| live.records.generation(e.slot(), e.kind()) == Some(e.generation());
                    if current(twin.full()) && twin.window().map(current).unwrap_or(true) {
                        // the twin is live: a dedup, the tree keeps its entries
                        let got = live.insert(parent, pos, &enc(block), twin).unwrap();
                        assert_eq!(got, id, "the dedup returns the block already in the tree");
                        rows.push(snapshot(&live, &seq_of, "seal-dup", &seq, twin.full().slot().get(), twin.window().map(|w| w.slot().get()).unwrap_or(0), &[], false));
                    } else {
                        // the twin is stale: evicted, the fresh entries sealed in its place
                        let slot = 1 + pick(3) as u32;
                        let wslot = 1 + (slot + pick(2) as u32) % 3;
                        let fresh = live.insert(parent, pos, &enc(block), pair(&live, slot, wslot)).unwrap();
                        assert_ne!(fresh, id, "the fresh block replaces the stale twin");
                        seq_of.retain(|k, _| *k != id);
                        seq_of.insert(fresh, seq.clone());
                        rows.push(snapshot(&live, &seq_of, "seal-twin", &seq, slot, wslot, &[], false));
                    }
                }
                6 => { // seek the model's request, wherever the walk is
                    let m = live.deepest_start(&req).unwrap();
                    rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));
                }
                7 => { // pin a live, unpinned block
                    let cand: Vec<SealedId> = live_ids.iter().copied()
                        .filter(|id| live.pin_count(*id) == 0).collect();
                    if cand.is_empty() { continue; }
                    let id = cand[pick(cand.len())];
                    if live.pin(id).is_err() { continue; } // stale: not pinnable, no row
                    let seq = seq_of[&id].clone();
                    rows.push(snapshot(&live, &seq_of, "pin", &seq, 0, 0, &[], false));
                }
                8 => { // unpin a pinned block
                    let cand: Vec<SealedId> = live_ids.iter().copied()
                        .filter(|id| live.pin_count(*id) > 0).collect();
                    if cand.is_empty() { continue; }
                    let id = cand[pick(cand.len())];
                    live.unpin(id).unwrap();
                    let seq = seq_of[&id].clone();
                    rows.push(snapshot(&live, &seq_of, "unpin", &seq, 0, 0, &[], false));
                }
                _ => { // remove a block and everything below it
                    if live_ids.is_empty() { continue; }
                    let id = live_ids[pick(live_ids.len())];
                    let seq = seq_of[&id].clone();
                    live.remove(id).unwrap();
                    rows.push(snapshot(&live, &seq_of, "remove", &seq, 0, 0, &[], false));
                }
            }
            mutating += 1;
        }
        assert_eq!(mutating, 40, "the walk took its wandering steps");
        let m = live.deepest_start(&req).unwrap();
        rows.push(snapshot(&live, &seq_of, "seek", &[], 0, 0, &req_abstract[..m.at / BLOCK * 2], true));

        let body = format!(
            "------------------------- MODULE PrefixTreeTraceData -------------------------\n\
             \\* Generated by prefix::tests::prefix_trace_dump (specs/run_tlc.zsh runs it).\n\
             \\* Do not edit; the generator is the code under test.\n\
             EXTENDS PrefixTree\n\nTrace == <<\n{}\n>>\n\n=============================================================================\n",
            rows.join(",\n"));
        std::fs::write(&out, body).unwrap();
    }


    #[test]
    fn entry_handles_come_back_as_johnnys_entries() {
        let full = BlockEntry::new(Slot::new(3).unwrap(), 1, 4096, BlockKind::Full, 2);
        let win = BlockEntry::new(Slot::new(5).unwrap(), 2, 8192, BlockKind::Window, 2);
        let full2 = BlockEntry::new(Slot::new(4).unwrap(), 1, 4096, BlockKind::Full, 2);
        let ha = BlockHandles::new(full, Some(win));
        let hb = BlockHandles::new(full2, None);
        let mut t: EntryTree = PrefixTree::new();
        let a = t.insert(None, 0, &block(1), ha).unwrap();
        let b = t.insert(Some(a), BLOCK, &block(2), hb).unwrap();
        t.retain_start(b).unwrap();
        let m = t.deepest_start(&[block(1), block(2), block(3)].concat());
        assert_eq!(m.at, 2 * BLOCK);
        assert_eq!(m.blocks, vec![ha, hb]);
        assert_eq!(m.blocks[0].full().kind(), BlockKind::Full);
        assert_eq!(m.blocks[0].full().offset(), 4096);
        assert_eq!(m.blocks[0].full().slot().get(), 3);
        assert_eq!(m.blocks[0].window(), Some(win), "the Window entry rides on the same node");
        assert_eq!(m.blocks[0].window().unwrap().generation(), 2);
        assert_eq!(m.blocks[1].window(), None);
    }
}