bstack_raii 0.1.0

Typed, RAII-style ownership and lifetime layer over the bstack allocation primitives
Documentation
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
//! [`BStackBTreeMap<K, V>`]: an owned, ordered map backed by a copy-on-write
//! B-tree.
//!
//! # Why a B-tree, not a binary tree
//!
//! On disk, pointer chasing is the enemy: every edge you follow is a seek to a
//! physically unrelated block. A red-black or AVL tree stores **one** key per
//! node, so a lookup in a million-entry tree chases ~20 pointers. A B-tree packs
//! many keys into each wide, **contiguous** node, so the same lookup reads only a
//! handful of nodes (with minimum degree `T = 8`, up to 15 keys per node, height
//! ~5 at a million entries). Same `O(log n)`, far fewer seeks — the on-disk
//! ordered-map you actually want, giving sorted iteration and range scans that a
//! [`crate::BStackHashMap`] cannot.
//!
//! Keys are **`Pod + Ord`** (`K`): stored inline in the node and compared by
//! value; values are blocks (`V: BStackBlock`) the tree owns via a `u64` ref.
//!
//! # Copy-on-write, single-writer
//!
//! Mutation is **path-copying** (the LMDB model): an insert rewrites only the
//! root-to-leaf path into freshly allocated nodes (splitting as needed), leaving
//! every untouched subtree shared, then commits all the new nodes **and** the new
//! root pointer as one atomic [`bstack::BStack::set_batched`] batch. The commit
//! point is the root swap: before it the tree is entirely the old version, after
//! it entirely the new one — so it is crash-atomic, and any number of readers
//! traversing the old root are unaffected.
//!
//! Unlike the lock-free [`crate::BStackDeque`] / [`crate::BStackHashMap`]
//! mutators, a B-tree write reads a whole path to build the new one, so
//! **concurrent writers need external synchronization** (one writer at a time);
//! concurrent *readers* are always fine. This is the same trade LMDB makes, and
//! it keeps each write atomic and crash-safe. (A path is short — a handful of
//! nodes — so the copy cost is small.)
//!
//! `remove` uses the same path-copying commit, rebalancing on the way down
//! (borrow from a sibling, or merge) to keep every node at `≥ T-1` keys, and
//! collapses the root when it empties.

use core::cmp::Ordering;
use core::marker::PhantomData;
use core::mem::size_of;
use std::io;

use crate::BStackRaiiAllocator;
use bstack::{BStack, BStackRange};
use bytemuck::{Pod, Zeroable};

use super::util::{Scratch, alloc_image, read_fields, w8};
use crate::handback::ReplaceError;
use crate::io_core::{ClonePlan, TryCloneIn, dealloc_range};
use crate::primitives::EightCC;
use crate::types::compiled::{BStackOwned, BlockHeader, HEADER_SIZE};
use crate::types::traits::{BStackBlock, BStackCast, BStackDrop};
use crate::util::{SmallBuf, get_u64, io_error, io_errorfn, read_u64};

/// The on-disk image of a [`BStackBTreeMap`]: header, root node pointer (`0` =
/// empty), and entry count. Non-generic.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct TreeOnDisk {
    /// The 16-byte block header (size + type tag).
    pub header: BlockHeader,
    /// Offset of the root node, or `0` when the tree is empty.
    pub root: u64,
    /// Number of entries.
    pub len: u64,
}

const ROOT_OFF: u64 = HEADER_SIZE; // 16
const LEN_OFF: u64 = HEADER_SIZE + 8; // 24
const TREE_SIZE: u64 = size_of::<TreeOnDisk>() as u64;

/// Minimum degree: a node holds `T-1..=2T-1` keys (the root may hold fewer).
const T: usize = 8;
const MAXKEYS: usize = 2 * T - 1; // 15

/// Structural depth bound for every descent. A `T = 8` B-tree cannot exceed
/// ~22 levels even at `u64::MAX` entries, so a deeper chain of child pointers
/// is corruption (or a cycle) and must fail as `InvalidData` — not spin, grow
/// a frame stack without bound, or overflow the native stack in the recursive
/// walks.
const MAX_TREE_DEPTH: u32 = 64;

io_errorfn!(
    depth_exceeded,
    InvalidData,
    "B-tree deeper than the structural bound (corrupt child pointer or a cycle?)"
);
const MAXCHILDREN: usize = 2 * T; // 16

// Node field offsets (keys/vals/children arrays follow, sized by `K`).
const NKEYS_OFF: usize = HEADER_SIZE as usize; // 16
const LEAF_OFF: usize = HEADER_SIZE as usize + 8; // 24
const KEYS_OFF: usize = HEADER_SIZE as usize + 16; // 32

/// A node decoded for building/mutation: keys as raw `K` bytes, value refs, and
/// (for an internal node) child node offsets (`keys.len() + 1` of them).
struct BNode {
    leaf: bool,
    keys: Vec<Vec<u8>>,
    vals: Vec<u64>,
    children: Vec<u64>,
}

/// A median lifted out of a split child: its key/value plus the new right node.
struct Split {
    key: Vec<u8>,
    val: u64,
    right: u64,
}

/// Accumulates a path-copy insert's new-node writes and the old path nodes to
/// free, so the whole insert commits as one [`BStack::set_batched`] batch.
struct Build<'a, A: BStackRaiiAllocator> {
    allocator: &'a A,
    node_size: u64,
    ksize: usize,
    vals_off: usize,
    children_off: usize,
    /// New node images `(offset, bytes)`, committed together.
    writes: Vec<(u64, SmallBuf)>,
    /// Old path nodes, freed after the commit succeeds.
    freed: Vec<u64>,
}

impl<'a, A: BStackRaiiAllocator> Build<'a, A> {
    /// Serialize `nb` and allocate a fresh block for it (an orphan until the
    /// commit links it), returning its offset.
    fn emit(&mut self, nb: &BNode) -> io::Result<u64> {
        let mut b = vec![0u8; self.node_size as usize];
        b[NKEYS_OFF..NKEYS_OFF + 8].copy_from_slice(&(nb.keys.len() as u64).to_le_bytes());
        b[LEAF_OFF..LEAF_OFF + 8].copy_from_slice(&(nb.leaf as u64).to_le_bytes());
        for (i, k) in nb.keys.iter().enumerate() {
            let ko = KEYS_OFF + i * self.ksize;
            b[ko..ko + self.ksize].copy_from_slice(k);
        }
        for (i, v) in nb.vals.iter().enumerate() {
            let vo = self.vals_off + i * 8;
            b[vo..vo + 8].copy_from_slice(&v.to_le_bytes());
        }
        for (i, c) in nb.children.iter().enumerate() {
            let co = self.children_off + i * 8;
            b[co..co + 8].copy_from_slice(&c.to_le_bytes());
        }
        let off = self.allocator.alloc(self.node_size)?.as_range().start();
        self.writes
            .push((off, SmallBuf::Heap(b.into_boxed_slice())));
        Ok(off)
    }
}

/// An owned, ordered map backed by a copy-on-write B-tree.
///
/// A typed handle (a newtype over a [`BStackRange`]); [`new`](Self::new) returns a
/// bare [`BStackOwned<BStackBTreeMap<K, V>>`] that frees nothing on scope exit —
/// free it with [`bstack_drop`](BStackDrop::bstack_drop) or wrap it
/// (`AutoDrop` / [`crate::BStackCow`]).
pub struct BStackBTreeMap<K: Pod + Ord, V: BStackBlock> {
    range: BStackRange,
    _marker: PhantomData<fn() -> (K, V)>,
}

impl<K: Pod + Ord, V: BStackBlock> BStackBTreeMap<K, V> {
    const fn ksize() -> usize {
        size_of::<K>()
    }
    const fn vals_off() -> usize {
        KEYS_OFF + MAXKEYS * Self::ksize()
    }
    const fn children_off() -> usize {
        Self::vals_off() + MAXKEYS * 8
    }
    const fn node_size() -> u64 {
        (Self::children_off() + MAXCHILDREN * 8) as u64
    }

    fn value_size() -> u64 {
        size_of::<<V as BStackBlock>::OnDisk>() as u64
    }
    fn value_at(off: u64) -> V {
        unsafe { <V as BStackBlock>::from_range(BStackRange::new(off, Self::value_size())) }
    }

    fn read_key(bytes: &[u8]) -> K {
        bytemuck::pod_read_unaligned::<K>(&bytes[..Self::ksize()])
    }

    /// Allocate an empty tree.
    pub fn new<A: BStackRaiiAllocator>(allocator: &A) -> io::Result<BStackOwned<Self>> {
        let od = TreeOnDisk {
            header: BlockHeader {
                size: TREE_SIZE,
                tag: Self::eightcc(),
            },
            root: 0,
            len: 0,
        };
        let range = alloc_image(allocator, bytemuck::bytes_of(&od))?;
        // SAFETY: a freshly allocated block owned by no other handle.
        Ok(unsafe { BStackOwned::from_raw(Self::from_range(range)) })
    }

    /// Number of entries.
    pub fn len(&self, stack: &BStack) -> io::Result<u64> {
        read_u64(stack, self.range.start() + LEN_OFF)
    }

    /// Whether the tree has no entries.
    pub fn is_empty(&self, stack: &BStack) -> io::Result<bool> {
        Ok(self.len(stack)? == 0)
    }

    /// Decode the node at `off`.
    fn read_node(stack: &BStack, off: u64) -> io::Result<BNode> {
        let mut b = vec![0u8; Self::node_size() as usize];
        stack.get_into(off, &mut b)?;
        let nkeys = get_u64(&b[NKEYS_OFF..]) as usize;
        // `nkeys` is an on-disk field read straight from the node image; a
        // corrupted value indexes `b` (a fixed `node_size()`-byte buffer) past
        // its end, panicking on a plain `get`/`contains` read. No real node
        // (built by this crate) ever exceeds `MAXKEYS`.
        if nkeys > MAXKEYS {
            return Err(io_error!("corrupt B-tree node: key count exceeds capacity"));
        }
        let leaf = get_u64(&b[LEAF_OFF..]) != 0;
        let ksize = Self::ksize();
        let vals_off = Self::vals_off();
        let children_off = Self::children_off();
        let mut keys = Vec::with_capacity(nkeys);
        let mut vals = Vec::with_capacity(nkeys);
        for i in 0..nkeys {
            let ko = KEYS_OFF + i * ksize;
            keys.push(b[ko..ko + ksize].to_vec());
            vals.push(get_u64(&b[vals_off + i * 8..]));
        }
        let mut children = Vec::new();
        if !leaf {
            for i in 0..=nkeys {
                children.push(get_u64(&b[children_off + i * 8..]));
            }
        }
        Ok(BNode {
            leaf,
            keys,
            vals,
            children,
        })
    }

    /// Locate `target` among a node's keys: the first index `i` with
    /// `target <= keys[i]`, and whether it is an exact match.
    fn search(nb: &BNode, target: &K) -> (usize, bool) {
        for (j, kb) in nb.keys.iter().enumerate() {
            match target.cmp(&Self::read_key(kb)) {
                Ordering::Less => return (j, false),
                Ordering::Equal => return (j, true),
                Ordering::Greater => {}
            }
        }
        (nb.keys.len(), false)
    }

    /// Split an over-full node (`keys.len() == 2T`) around its median: returns the
    /// left node and the lifted median; the caller emits the right node.
    fn split(mut nb: BNode) -> (BNode, Split, BNode) {
        let m = nb.keys.len() / 2;
        let right_children = if nb.leaf {
            Vec::new()
        } else {
            nb.children.split_off(m + 1)
        };
        let right_keys = nb.keys.split_off(m + 1);
        let right_vals = nb.vals.split_off(m + 1);
        let med_key = nb.keys.pop().unwrap();
        let med_val = nb.vals.pop().unwrap();
        let right = BNode {
            leaf: nb.leaf,
            keys: right_keys,
            vals: right_vals,
            children: right_children,
        };
        let split = Split {
            key: med_key,
            val: med_val,
            right: 0, // filled in by the caller after emitting `right`
        };
        (nb, split, right)
    }

    /// Recursively path-copy the subtree at `off`, inserting `key -> val`.
    /// Returns the new subtree offset, an optional lifted split, whether a new
    /// entry was added, and any replaced value.
    fn insert_rec(
        build: &mut Build<'_, impl BStackRaiiAllocator>,
        stack: &BStack,
        off: u64,
        key: &K,
        key_bytes: &[u8],
        val: u64,
    ) -> io::Result<(u64, Option<Split>, bool, Option<u64>)> {
        let mut nb = Self::read_node(stack, off)?;
        build.freed.push(off);
        let (i, exact) = Self::search(&nb, key);

        if exact {
            let old = nb.vals[i];
            nb.vals[i] = val;
            let new_off = build.emit(&nb)?;
            return Ok((new_off, None, false, Some(old)));
        }

        let (added, old) = if nb.leaf {
            nb.keys.insert(i, key_bytes.to_vec());
            nb.vals.insert(i, val);
            (true, None)
        } else {
            let child = nb.children[i];
            let (new_child, child_split, added, old) =
                Self::insert_rec(build, stack, child, key, key_bytes, val)?;
            nb.children[i] = new_child;
            if let Some(s) = child_split {
                // The child split and already emitted its right node into `s.right`.
                nb.keys.insert(i, s.key);
                nb.vals.insert(i, s.val);
                nb.children.insert(i + 1, s.right);
            }
            (added, old)
        };

        if nb.keys.len() <= MAXKEYS {
            let new_off = build.emit(&nb)?;
            Ok((new_off, None, added, old))
        } else {
            let (left, mut split, right) = Self::split(nb);
            split.right = build.emit(&right)?;
            let left_off = build.emit(&left)?;
            Ok((left_off, Some(split), added, old))
        }
    }

    /// Insert `key -> value`, taking ownership of the value block. Returns the
    /// previously-mapped value (owned) if `key` was already present, else `None`.
    ///
    /// Path-copies the affected path and commits every new node plus the root
    /// swap as one crash-atomic batch. **Single-writer** (see the module docs).
    pub fn insert<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        key: K,
        value: BStackOwned<V>,
    ) -> Result<Option<BStackOwned<V>>, ReplaceError<BStackOwned<V>>> {
        let handle = self.range.start();
        let stack = allocator.stack();
        let key_bytes = bytemuck::bytes_of(&key).to_vec();
        // Guard the value block: on failure [`finish_handback`] returns it to the
        // caller rather than freeing it, defused once the tree
        // commit succeeds.
        let value = value.auto(allocator);
        let val_ref = value.range().start();

        let outcome: io::Result<Option<BStackOwned<V>>> = (|| {
            let [root, len] = read_fields::<2>(stack, handle + ROOT_OFF)?;

            let mut build = Build {
                allocator,
                node_size: Self::node_size(),
                ksize: Self::ksize(),
                vals_off: Self::vals_off(),
                children_off: Self::children_off(),
                writes: Vec::new(),
                freed: Vec::new(),
            };

            let built: io::Result<(u64, bool, Option<u64>)> = (|| {
                if root == 0 {
                    // Empty tree: a single-entry leaf becomes the root.
                    let leaf = BNode {
                        leaf: true,
                        keys: vec![key_bytes.clone()],
                        vals: vec![val_ref],
                        children: Vec::new(),
                    };
                    let new_root = build.emit(&leaf)?;
                    return Ok((new_root, true, None));
                }
                let (new_root0, split, added, old) =
                    Self::insert_rec(&mut build, stack, root, &key, &key_bytes, val_ref)?;
                let new_root = if let Some(s) = split {
                    // Root split: a fresh root holds the median over the two halves.
                    let root_node = BNode {
                        leaf: false,
                        keys: vec![s.key],
                        vals: vec![s.val],
                        children: vec![new_root0, s.right],
                    };
                    build.emit(&root_node)?
                } else {
                    new_root0
                };
                Ok((new_root, added, old))
            })();

            match built {
                Ok((new_root, added, old)) => {
                    let new_node_offs: Vec<u64> = build.writes.iter().map(|(o, _)| *o).collect();
                    let mut writes = core::mem::take(&mut build.writes);
                    writes.push(w8(handle + ROOT_OFF, new_root));
                    if added {
                        writes.push(w8(handle + LEN_OFF, len + 1));
                    }
                    match stack.set_batched(writes) {
                        Ok(()) => {
                            // Committed: the value is linked into the tree.
                            // Free the old path nodes (leak-only on crash).
                            for off in &build.freed {
                                // SAFETY: replaced by the copy just committed; nothing
                                // else references it (single-writer).
                                let _ = unsafe {
                                    dealloc_range(
                                        allocator,
                                        BStackRange::new(*off, build.node_size),
                                    )
                                };
                            }
                            Ok(old.map(|o| unsafe { BStackOwned::from_raw(Self::value_at(o)) }))
                        }
                        Err(e) => {
                            // Nothing committed: reclaim the new nodes we allocated.
                            for off in new_node_offs {
                                let _ = unsafe {
                                    dealloc_range(allocator, BStackRange::new(off, build.node_size))
                                };
                            }
                            Err(e)
                        }
                    }
                }
                Err(e) => {
                    for (off, _) in &build.writes {
                        let _ = unsafe {
                            dealloc_range(allocator, BStackRange::new(*off, build.node_size))
                        };
                    }
                    Err(e)
                }
            }
        })();
        value.finish_handback(outcome)
    }

    /// A **borrowed** handle to the value mapped by `key` (no ownership), or
    /// `None` if absent.
    pub fn get(&self, stack: &BStack, key: &K) -> io::Result<Option<V>> {
        let mut off = read_u64(stack, self.range.start() + ROOT_OFF)?;
        let ksize = Self::ksize();
        let vals_off = Self::vals_off();
        let children_off = Self::children_off();
        // Stack buffer for the node (reused down the descent; no heap alloc for
        // typical key sizes — see `Scratch`).
        let mut scratch = Scratch::new();
        let node_size = Self::node_size() as usize;
        let mut depth = 0u32;
        while off != 0 {
            depth += 1;
            if depth > MAX_TREE_DEPTH {
                return Err(depth_exceeded());
            }
            let buf = scratch.buf(node_size);
            stack.get_into(off, buf)?;
            let nkeys = get_u64(&buf[NKEYS_OFF..]) as usize;
            if nkeys > MAXKEYS {
                return Err(io_error!("corrupt B-tree node: key count exceeds capacity"));
            }
            let leaf = get_u64(&buf[LEAF_OFF..]) != 0;
            let mut i = nkeys;
            let mut exact = false;
            for j in 0..nkeys {
                let ko = KEYS_OFF + j * ksize;
                match key.cmp(&Self::read_key(&buf[ko..ko + ksize])) {
                    Ordering::Less => {
                        i = j;
                        break;
                    }
                    Ordering::Equal => {
                        i = j;
                        exact = true;
                        break;
                    }
                    Ordering::Greater => {}
                }
            }
            if exact {
                return Ok(Some(Self::value_at(get_u64(&buf[vals_off + i * 8..]))));
            }
            if leaf {
                return Ok(None);
            }
            off = get_u64(&buf[children_off + i * 8..]);
        }
        Ok(None)
    }

    /// Whether `key` is present.
    pub fn contains_key(&self, stack: &BStack, key: &K) -> io::Result<bool> {
        Ok(self.get(stack, key)?.is_some())
    }

    /// Get the value for `key`, inserting one produced by `f` if absent — the
    /// fused entry operation. Returns `(value handle, was_newly_inserted)`.
    ///
    /// If `key` is present this is a single descent: `f` is **not** called and
    /// nothing is allocated. Existing values are never replaced (use
    /// [`insert`](Self::insert)). The returned handle is mutable in place, and the
    /// `bool` distinguishes a fresh insert from a hit. **Single-writer.**
    pub fn get_or_insert_with<A, F>(&self, allocator: &A, key: K, f: F) -> io::Result<(V, bool)>
    where
        A: BStackRaiiAllocator,
        F: FnOnce() -> io::Result<BStackOwned<V>>,
    {
        if let Some(v) = self.get(allocator.stack(), &key)? {
            return Ok((v, false));
        }
        let value = f()?;
        let vref = value.handle().range().start();
        if let Some(old) = self
            .insert(allocator, key, value)
            .map_err(|e| e.discard_freeing(allocator))?
        {
            old.bstack_drop(allocator)?;
        }
        Ok((Self::value_at(vref), true))
    }

    /// Like [`get_or_insert_with`](Self::get_or_insert_with) but with an eager
    /// `default`, which is **freed** if `key` is already present.
    pub fn get_or_insert<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        key: K,
        default: BStackOwned<V>,
    ) -> io::Result<(V, bool)> {
        if let Some(v) = self.get(allocator.stack(), &key)? {
            default.bstack_drop(allocator)?;
            return Ok((v, false));
        }
        let vref = default.handle().range().start();
        if let Some(old) = self
            .insert(allocator, key, default)
            .map_err(|e| e.discard_freeing(allocator))?
        {
            old.bstack_drop(allocator)?;
        }
        Ok((Self::value_at(vref), true))
    }

    /// The number of keys in the node at `off` (reads just the count field).
    /// `off` comes from a parent node's on-disk `children` array — untrusted.
    fn child_nkeys(stack: &BStack, off: u64) -> io::Result<usize> {
        let pos = off
            .checked_add(NKEYS_OFF as u64)
            .ok_or_else(|| io_error!("corrupt B-tree child offset"))?;
        let nkeys = get_u64(&{
            let mut b = [0u8; 8];
            stack.get_into(pos, &mut b)?;
            b
        }) as usize;
        if nkeys > MAXKEYS {
            return Err(io_error!("corrupt B-tree node: key count exceeds capacity"));
        }
        Ok(nkeys)
    }

    /// The rightmost (largest) `(key_bytes, value)` in the subtree at `off`.
    fn max_entry(stack: &BStack, off: u64) -> io::Result<(Vec<u8>, u64)> {
        let mut nb = Self::read_node(stack, off)?;
        while !nb.leaf {
            // Corrupt data (an internal node with no children) errors here rather than
            // panicking past the caller's node-reclaim path.
            let child = *nb
                .children
                .last()
                .ok_or_else(|| io_error!("corrupt B-tree: internal node has no children"))?;
            nb = Self::read_node(stack, child)?;
        }
        let i = nb
            .keys
            .len()
            .checked_sub(1)
            .ok_or_else(|| io_error!("corrupt B-tree: empty leaf node"))?;
        Ok((nb.keys[i].clone(), nb.vals[i]))
    }

    /// The leftmost (smallest) `(key_bytes, value)` in the subtree at `off`.
    fn min_entry(stack: &BStack, off: u64) -> io::Result<(Vec<u8>, u64)> {
        let mut nb = Self::read_node(stack, off)?;
        while !nb.leaf {
            let child = *nb
                .children
                .first()
                .ok_or_else(|| io_error!("corrupt B-tree: internal node has no children"))?;
            nb = Self::read_node(stack, child)?;
        }
        if nb.keys.is_empty() {
            return Err(io_error!("corrupt B-tree: empty leaf node"));
        }
        Ok((nb.keys[0].clone(), nb.vals[0]))
    }

    /// Path-copy delete of `key` from the subtree at `off`; returns the new
    /// subtree offset and the removed value (if the key was found).
    fn delete_off(
        build: &mut Build<'_, impl BStackRaiiAllocator>,
        stack: &BStack,
        off: u64,
        key: &K,
    ) -> io::Result<(u64, Option<u64>)> {
        let nb = Self::read_node(stack, off)?;
        build.freed.push(off);
        let (nb2, val) = Self::delete_bnode(build, stack, nb, key)?;
        Ok((build.emit(&nb2)?, val))
    }

    /// Delete `key` from the in-memory node `nb` (its old block already recorded
    /// for freeing), rebalancing children to keep the B-tree invariant. Returns
    /// the modified node (not yet emitted) and the removed value.
    fn delete_bnode(
        build: &mut Build<'_, impl BStackRaiiAllocator>,
        stack: &BStack,
        mut nb: BNode,
        key: &K,
    ) -> io::Result<(BNode, Option<u64>)> {
        let (i, found) = Self::search(&nb, key);

        if found {
            if nb.leaf {
                let v = nb.vals.remove(i);
                nb.keys.remove(i);
                return Ok((nb, Some(v)));
            }
            // Internal: the value at `i` is what we return.
            let removed = nb.vals[i];
            let yc = Self::child_nkeys(stack, nb.children[i])?;
            let zc = Self::child_nkeys(stack, nb.children[i + 1])?;
            if yc >= T {
                // Replace with predecessor, then delete it from the left child.
                let (pk, pv) = Self::max_entry(stack, nb.children[i])?;
                nb.keys[i] = pk.clone();
                nb.vals[i] = pv;
                let (new_y, _) =
                    Self::delete_off(build, stack, nb.children[i], &Self::read_key(&pk))?;
                nb.children[i] = new_y;
            } else if zc >= T {
                // Replace with successor, then delete it from the right child.
                let (sk, sv) = Self::min_entry(stack, nb.children[i + 1])?;
                nb.keys[i] = sk.clone();
                nb.vals[i] = sv;
                let (new_z, _) =
                    Self::delete_off(build, stack, nb.children[i + 1], &Self::read_key(&sk))?;
                nb.children[i + 1] = new_z;
            } else {
                // Merge children[i] + separator + children[i+1], then delete from it.
                let y_off = nb.children[i];
                let z_off = nb.children[i + 1];
                let mut y = Self::read_node(stack, y_off)?;
                build.freed.push(y_off);
                let mut z = Self::read_node(stack, z_off)?;
                build.freed.push(z_off);
                let sk = nb.keys.remove(i);
                let sv = nb.vals.remove(i);
                nb.children.remove(i + 1);
                y.keys.push(sk);
                y.vals.push(sv);
                y.keys.append(&mut z.keys);
                y.vals.append(&mut z.vals);
                if !y.leaf {
                    y.children.append(&mut z.children);
                }
                let (y2, _) = Self::delete_bnode(build, stack, y, key)?;
                nb.children[i] = build.emit(&y2)?;
            }
            return Ok((nb, Some(removed)));
        }

        if nb.leaf {
            return Ok((nb, None)); // key absent
        }

        // Key is in children[i]; ensure it has at least `T` keys before descending.
        if Self::child_nkeys(stack, nb.children[i])? >= T {
            let (new_c, val) = Self::delete_off(build, stack, nb.children[i], key)?;
            nb.children[i] = new_c;
            return Ok((nb, val));
        }

        let n = nb.keys.len();
        if i > 0 && Self::child_nkeys(stack, nb.children[i - 1])? >= T {
            // Borrow from the left sibling (rotate right through the parent).
            let ci_off = nb.children[i];
            let ls_off = nb.children[i - 1];
            let mut ci = Self::read_node(stack, ci_off)?;
            build.freed.push(ci_off);
            let mut ls = Self::read_node(stack, ls_off)?;
            build.freed.push(ls_off);
            ci.keys.insert(0, nb.keys[i - 1].clone());
            ci.vals.insert(0, nb.vals[i - 1]);
            if !ci.leaf {
                ci.children.insert(0, ls.children.pop().unwrap());
            }
            nb.keys[i - 1] = ls.keys.pop().unwrap();
            nb.vals[i - 1] = ls.vals.pop().unwrap();
            nb.children[i - 1] = build.emit(&ls)?;
            let (ci2, val) = Self::delete_bnode(build, stack, ci, key)?;
            nb.children[i] = build.emit(&ci2)?;
            return Ok((nb, val));
        }
        if i < n && Self::child_nkeys(stack, nb.children[i + 1])? >= T {
            // Borrow from the right sibling (rotate left through the parent).
            let ci_off = nb.children[i];
            let rs_off = nb.children[i + 1];
            let mut ci = Self::read_node(stack, ci_off)?;
            build.freed.push(ci_off);
            let mut rs = Self::read_node(stack, rs_off)?;
            build.freed.push(rs_off);
            ci.keys.push(nb.keys[i].clone());
            ci.vals.push(nb.vals[i]);
            if !ci.leaf {
                ci.children.push(rs.children.remove(0));
            }
            nb.keys[i] = rs.keys.remove(0);
            nb.vals[i] = rs.vals.remove(0);
            nb.children[i + 1] = build.emit(&rs)?;
            let (ci2, val) = Self::delete_bnode(build, stack, ci, key)?;
            nb.children[i] = build.emit(&ci2)?;
            return Ok((nb, val));
        }

        // No lending sibling: merge with one (pulling a separator down).
        if i < n {
            let ci_off = nb.children[i];
            let rs_off = nb.children[i + 1];
            let mut ci = Self::read_node(stack, ci_off)?;
            build.freed.push(ci_off);
            let mut rs = Self::read_node(stack, rs_off)?;
            build.freed.push(rs_off);
            let sk = nb.keys.remove(i);
            let sv = nb.vals.remove(i);
            nb.children.remove(i + 1);
            ci.keys.push(sk);
            ci.vals.push(sv);
            ci.keys.append(&mut rs.keys);
            ci.vals.append(&mut rs.vals);
            if !ci.leaf {
                ci.children.append(&mut rs.children);
            }
            let (ci2, val) = Self::delete_bnode(build, stack, ci, key)?;
            nb.children[i] = build.emit(&ci2)?;
            Ok((nb, val))
        } else {
            let ls_off = nb.children[i - 1];
            let ci_off = nb.children[i];
            let mut ls = Self::read_node(stack, ls_off)?;
            build.freed.push(ls_off);
            let mut ci = Self::read_node(stack, ci_off)?;
            build.freed.push(ci_off);
            let sk = nb.keys.remove(i - 1);
            let sv = nb.vals.remove(i - 1);
            nb.children.remove(i);
            ls.keys.push(sk);
            ls.vals.push(sv);
            ls.keys.append(&mut ci.keys);
            ls.vals.append(&mut ci.vals);
            if !ls.leaf {
                ls.children.append(&mut ci.children);
            }
            let (ls2, val) = Self::delete_bnode(build, stack, ls, key)?;
            nb.children[i - 1] = build.emit(&ls2)?;
            Ok((nb, val))
        }
    }

    /// Remove `key`, returning its value (owned) if present, else `None`.
    /// Path-copies the affected path (rebalancing as needed) and commits the new
    /// nodes plus the root update as one crash-atomic batch. **Single-writer.**
    pub fn remove<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        key: &K,
    ) -> io::Result<Option<BStackOwned<V>>> {
        let handle = self.range.start();
        let stack = allocator.stack();
        let [root, len] = read_fields::<2>(stack, handle + ROOT_OFF)?;
        // Absent-key fast path avoids a wasted path copy.
        if root == 0 || self.get(stack, key)?.is_none() {
            return Ok(None);
        }

        let mut build = Build {
            allocator,
            node_size: Self::node_size(),
            ksize: Self::ksize(),
            vals_off: Self::vals_off(),
            children_off: Self::children_off(),
            writes: Vec::new(),
            freed: Vec::new(),
        };

        let built: io::Result<(u64, u64)> = (|| {
            let nb = Self::read_node(stack, root)?;
            build.freed.push(root);
            let (root_nb, val) = Self::delete_bnode(&mut build, stack, nb, key)?;
            // `get` above confirmed the key is present, so `None` here means the on-disk
            // structure is corrupt/inconsistent — return an error (which the `Err` arm
            // below reclaims `build.writes` through) rather than panicking past the
            // reclaim and leaking the path-copied nodes.
            let val = val.ok_or_else(|| io_error!("corrupt B-tree: key vanished mid-delete"))?;
            // Collapse an empty root: a leaf → empty tree; an internal → its child.
            let new_root = if root_nb.keys.is_empty() {
                if root_nb.leaf {
                    0
                } else {
                    *root_nb
                        .children
                        .first()
                        .ok_or_else(|| io_error!("corrupt B-tree: internal node has no children"))?
                }
            } else {
                build.emit(&root_nb)?
            };
            Ok((new_root, val))
        })();

        match built {
            Ok((new_root, val)) => {
                let new_node_offs: Vec<u64> = build.writes.iter().map(|(o, _)| *o).collect();
                let mut writes = core::mem::take(&mut build.writes);
                writes.push(w8(handle + ROOT_OFF, new_root));
                writes.push(w8(handle + LEN_OFF, len - 1));
                match stack.set_batched(writes) {
                    Ok(()) => {
                        for off in &build.freed {
                            // SAFETY: replaced/merged away by the commit (single-writer).
                            let _ = unsafe {
                                dealloc_range(allocator, BStackRange::new(*off, build.node_size))
                            };
                        }
                        Ok(Some(unsafe { BStackOwned::from_raw(Self::value_at(val)) }))
                    }
                    Err(e) => {
                        for off in new_node_offs {
                            let _ = unsafe {
                                dealloc_range(allocator, BStackRange::new(off, build.node_size))
                            };
                        }
                        Err(e)
                    }
                }
            }
            Err(e) => {
                for (off, _) in &build.writes {
                    let _ = unsafe {
                        dealloc_range(allocator, BStackRange::new(*off, build.node_size))
                    };
                }
                Err(e)
            }
        }
    }

    /// The smallest entry, or `None` if empty. Descends the leftmost path.
    pub fn first(&self, stack: &BStack) -> io::Result<Option<(K, V)>> {
        self.extreme(stack, true)
    }

    /// The largest entry, or `None` if empty. Descends the rightmost path.
    pub fn last(&self, stack: &BStack) -> io::Result<Option<(K, V)>> {
        self.extreme(stack, false)
    }

    fn extreme(&self, stack: &BStack, leftmost: bool) -> io::Result<Option<(K, V)>> {
        let mut off = read_u64(stack, self.range.start() + ROOT_OFF)?;
        if off == 0 {
            return Ok(None);
        }
        // A forged cyclic leftmost/rightmost chain never reaches a leaf; bound the
        // descent like `get` so it errors instead of looping forever.
        let mut depth = 0u32;
        loop {
            depth += 1;
            if depth > MAX_TREE_DEPTH {
                return Err(depth_exceeded());
            }
            let nb = Self::read_node(stack, off)?;
            if nb.leaf {
                let i = if leftmost { 0 } else { nb.keys.len() - 1 };
                return Ok(Some((
                    Self::read_key(&nb.keys[i]),
                    Self::value_at(nb.vals[i]),
                )));
            }
            off = if leftmost {
                nb.children[0]
            } else {
                nb.children[nb.keys.len()]
            };
        }
    }

    /// Collect every entry in ascending key order. The value handles are borrowed
    /// (do not free them; valid only while the tree does).
    pub fn to_vec(&self, stack: &BStack) -> io::Result<Vec<(K, V)>> {
        let mut out = Vec::new();
        let root = read_u64(stack, self.range.start() + ROOT_OFF)?;
        Self::collect(stack, root, 0, &mut out)?;
        Ok(out)
    }

    fn collect(stack: &BStack, off: u64, depth: u32, out: &mut Vec<(K, V)>) -> io::Result<()> {
        if off == 0 {
            return Ok(());
        }
        // A forged cyclic child pointer would otherwise recurse until the native
        // stack overflows; bound the descent like every sibling walk.
        if depth >= MAX_TREE_DEPTH {
            return Err(depth_exceeded());
        }
        let nb = Self::read_node(stack, off)?;
        for i in 0..nb.keys.len() {
            if !nb.leaf {
                Self::collect(stack, nb.children[i], depth + 1, out)?;
            }
            out.push((Self::read_key(&nb.keys[i]), Self::value_at(nb.vals[i])));
        }
        if !nb.leaf {
            Self::collect(stack, nb.children[nb.keys.len()], depth + 1, out)?;
        }
        Ok(())
    }

    /// A lazy in-order iterator over all `(key, value)` entries, ascending. Reads
    /// nodes on demand (no full materialization); yields `io::Result` so a read
    /// error surfaces per step. Do not mutate the tree's *structure* while
    /// iterating (mutating a yielded value block is fine).
    pub fn iter<'a>(&self, stack: &'a BStack) -> io::Result<BTreeMapIter<'a, K, V>> {
        let [root, len] = read_fields::<2>(stack, self.range.start() + ROOT_OFF)?;
        let frames = Self::descend_left(stack, root)?;
        Ok(BTreeMapIter {
            stack,
            block_off: self.range.start(),
            root0: root,
            len0: len,
            frames,
            hi: None,
            _marker: PhantomData,
        })
    }

    /// A lazy in-order iterator over the entries with `lo <= key <= hi`, ascending.
    pub fn range<'a>(&self, stack: &'a BStack, lo: K, hi: K) -> io::Result<BTreeMapIter<'a, K, V>> {
        let [root, len] = read_fields::<2>(stack, self.range.start() + ROOT_OFF)?;
        let frames = Self::seek(stack, root, &lo)?;
        Ok(BTreeMapIter {
            stack,
            block_off: self.range.start(),
            root0: root,
            len0: len,
            frames,
            hi: Some(hi),
            _marker: PhantomData,
        })
    }

    /// Build the frame stack for the leftmost path from `root` (positions an
    /// in-order iterator at the smallest key).
    fn descend_left(stack: &BStack, mut cur: u64) -> io::Result<Vec<(BNode, usize)>> {
        let mut frames = Vec::new();
        while cur != 0 {
            if frames.len() as u32 >= MAX_TREE_DEPTH {
                return Err(depth_exceeded());
            }
            let n = Self::read_node(stack, cur)?;
            let next = if n.leaf { 0 } else { n.children[0] };
            let leaf = n.leaf;
            frames.push((n, 0));
            if leaf {
                break;
            }
            cur = next;
        }
        Ok(frames)
    }

    /// Build the frame stack positioned at the first key `>= lo`.
    fn seek(stack: &BStack, mut cur: u64, lo: &K) -> io::Result<Vec<(BNode, usize)>> {
        let mut frames = Vec::new();
        while cur != 0 {
            if frames.len() as u32 >= MAX_TREE_DEPTH {
                return Err(depth_exceeded());
            }
            let n = Self::read_node(stack, cur)?;
            let (i, exact) = Self::search(&n, lo);
            // Descend into child[i] only when it may hold keys `>= lo` — i.e. an
            // internal node with no exact hit here (an exact hit means child[i] is
            // entirely `< lo` and is skipped).
            let descend = if n.leaf || exact {
                None
            } else {
                Some(n.children[i])
            };
            frames.push((n, i));
            match descend {
                Some(c) => cur = c,
                None => break,
            }
        }
        Ok(frames)
    }

    /// Recursively free the subtree at `off` (values then nodes).
    fn drop_subtree<A: BStackRaiiAllocator>(
        stack: &BStack,
        off: u64,
        allocator: &A,
        depth: u32,
    ) -> io::Result<()> {
        if off == 0 {
            return Ok(());
        }
        if depth >= MAX_TREE_DEPTH {
            return Err(depth_exceeded());
        }
        let nb = Self::read_node(stack, off)?;
        if !nb.leaf {
            for &c in &nb.children {
                Self::drop_subtree(stack, c, allocator, depth + 1)?;
            }
        }
        for &v in &nb.vals {
            if v != 0 {
                // SAFETY: the tree solely owns each value block.
                let owned = unsafe { BStackOwned::from_raw(Self::value_at(v)) };
                owned.bstack_drop(allocator)?;
            }
        }
        // SAFETY: the tree solely owns each node block.
        unsafe { dealloc_range(allocator, BStackRange::new(off, Self::node_size()))? };
        Ok(())
    }

    /// Recursively deep-clone the subtree at `off` into `plan`, returning the new
    /// subtree offset.
    fn clone_subtree<A: BStackRaiiAllocator>(
        stack: &BStack,
        off: u64,
        allocator: &A,
        plan: &mut ClonePlan,
        depth: u32,
    ) -> io::Result<u64> {
        if off == 0 {
            return Ok(0);
        }
        if depth >= MAX_TREE_DEPTH {
            return Err(depth_exceeded());
        }
        let mut buf = vec![0u8; Self::node_size() as usize];
        stack.get_into(off, &mut buf)?;
        let nkeys = get_u64(&buf[NKEYS_OFF..]) as usize;
        if nkeys > MAXKEYS {
            return Err(io_error!("corrupt B-tree node: key count exceeds capacity"));
        }
        let leaf = get_u64(&buf[LEAF_OFF..]) != 0;
        let vals_off = Self::vals_off();
        let children_off = Self::children_off();

        // Deep-clone each value and repoint it in the copy.
        for i in 0..nkeys {
            let vo = vals_off + i * 8;
            let vref = get_u64(&buf[vo..]);
            let cloned = Self::value_at(vref)
                .__bstack_clone_into(allocator, plan)?
                .start();
            buf[vo..vo + 8].copy_from_slice(&cloned.to_le_bytes());
        }
        // Recurse into children and repoint them.
        if !leaf {
            for i in 0..=nkeys {
                let co = children_off + i * 8;
                let child = get_u64(&buf[co..]);
                let new_child = Self::clone_subtree(stack, child, allocator, plan, depth + 1)?;
                buf[co..co + 8].copy_from_slice(&new_child.to_le_bytes());
            }
        }
        let dst = plan.alloc_raw(allocator, Self::node_size())?;
        plan.write(dst.start(), buf);
        Ok(dst.start())
    }
}

impl<K: Pod + Ord, V: BStackBlock> BStackCast for BStackBTreeMap<K, V> {
    /// A `"Tree"` prefix perturbed by the key size and the value type's tag.
    fn eightcc() -> EightCC {
        const BASE: EightCC = EightCC::new([b'T', b'r', b'e', b'e', 0x80, 0x81, 0x82, 0x83]);
        BASE.mix(EightCC::new((size_of::<K>() as u64).to_le_bytes()))
            .mix(<V as BStackCast>::eightcc())
    }
}

// Self-contained (no separate control block): may be `#[embed]`ded.
impl<K: Pod + Ord, V: BStackBlock> crate::types::traits::BStackEmbeddable for BStackBTreeMap<K, V> {}

impl<K: Pod + Ord, V: BStackBlock> BStackBlock for BStackBTreeMap<K, V> {
    type OnDisk = TreeOnDisk;

    unsafe fn from_range(range: BStackRange) -> Self {
        BStackBTreeMap {
            range,
            _marker: PhantomData,
        }
    }

    fn range(&self) -> BStackRange {
        self.range
    }

    /// Recursively free every value block and node, **without** freeing the
    /// handle block itself.
    fn __bstack_drop_children<A: BStackRaiiAllocator>(
        allocator: &A,
        range: BStackRange,
    ) -> io::Result<()> {
        let root = read_u64(allocator.stack(), range.start() + ROOT_OFF)?;
        Self::drop_subtree(allocator.stack(), root, allocator, 0)
    }

    /// Deep-clone the whole tree into `plan`: every node copied, every value
    /// deep-cloned via `V`'s clone hook, the handle staged — all in the parent
    /// plan's single atomic commit.
    fn __bstack_clone_children_inplace<A: BStackRaiiAllocator>(
        &self,
        allocator: &A,
        plan: &mut ClonePlan,
    ) -> io::Result<Self::OnDisk> {
        let handle = self.range.start();
        let [root, len] = read_fields::<2>(allocator.stack(), handle + ROOT_OFF)?;
        let new_root = Self::clone_subtree(allocator.stack(), root, allocator, plan, 0)?;

        let od = TreeOnDisk {
            header: BlockHeader {
                size: TREE_SIZE,
                tag: Self::eightcc(),
            },
            root: new_root,
            len,
        };
        Ok(od)
    }
}

impl<K: Pod + Ord, V: BStackBlock> TryCloneIn for BStackBTreeMap<K, V> {}

/// A lazy in-order iterator over a [`BStackBTreeMap`], yielding
/// `io::Result<(K, V)>` in ascending key order. Created by
/// [`BStackBTreeMap::iter`] / [`BStackBTreeMap::range`]; borrows the `BStack` for
/// its lifetime and reads nodes on demand.
///
/// Each frame `(node, i)` on the stack means "`key[i]` is next; the subtree of
/// `child[i]` has already been yielded" — the standard iterative in-order walk
/// generalized to a B-tree.
pub struct BTreeMapIter<'a, K: Pod + Ord, V: BStackBlock> {
    stack: &'a BStack,
    /// The tree handle block, re-read each step to detect mutation.
    block_off: u64,
    /// The `(root, len)` at construction — a change means it was mutated.
    root0: u64,
    len0: u64,
    frames: Vec<(BNode, usize)>,
    hi: Option<K>,
    _marker: PhantomData<fn() -> (K, V)>,
}

impl<'a, K: Pod + Ord, V: BStackBlock> Iterator for BTreeMapIter<'a, K, V> {
    type Item = io::Result<(K, V)>;

    fn next(&mut self) -> Option<Self::Item> {
        // Fail fast if the tree was mutated during iteration: a path-copying
        // insert (or a remove) frees the old path and swaps the root, so the cached
        // `frames` name freed nodes. A changed `(root, len)` means the snapshot is
        // stale — a clean error instead of decoding freed storage.
        if !self.frames.is_empty() {
            match read_fields::<2>(self.stack, self.block_off + ROOT_OFF) {
                Ok([root, len]) if root == self.root0 && len == self.len0 => {}
                Ok(_) => {
                    self.frames.clear();
                    return Some(Err(io_error!(
                        "BStackBTreeMap was mutated during iteration (its root changed); \
                         the iterator is invalidated"
                    )));
                }
                Err(e) => {
                    self.frames.clear();
                    return Some(Err(e));
                }
            }
        }
        loop {
            let (node, i) = self.frames.last()?;
            let i = *i;
            if i >= node.keys.len() {
                self.frames.pop();
                continue;
            }
            let key = BStackBTreeMap::<K, V>::read_key(&node.keys[i]);
            let vref = node.vals[i];
            let leaf = node.leaf;
            let child = if leaf { 0 } else { node.children[i + 1] };

            if let Some(ref hi) = self.hi
                && key > *hi
            {
                self.frames.clear();
                return None;
            }
            // Advance this frame past `key[i]`, then (if internal) descend the
            // leftmost path of `child[i+1]` so `key[i+1]` comes after its subtree.
            self.frames.last_mut().unwrap().1 = i + 1;
            if !leaf {
                match BStackBTreeMap::<K, V>::descend_left(self.stack, child) {
                    Ok(mut f) => self.frames.append(&mut f),
                    Err(e) => {
                        self.frames.clear();
                        return Some(Err(e));
                    }
                }
            }
            return Some(Ok((key, BStackBTreeMap::<K, V>::value_at(vref))));
        }
    }
}