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
//! [`BStackBTreeSet<K>`]: an owned ordered set of `Pod + Ord` keys, backed by a
//! copy-on-write B-tree, with an embedded counting Bloom filter front.
//!
//! The set analogue of [`crate::BStackBTreeMap`] — the same wide contiguous
//! nodes and path-copying insert, but each node stores only keys (no value
//! column). It gives sorted iteration and, like the map, is **single-writer /
//! multi-reader** (an insert path-copies the root-to-leaf path and commits the
//! new nodes plus the root swap as one atomic [`bstack::BStack::set_batched`]).
//!
//! # Bloom filter in front
//!
//! Like [`crate::BStackHashSet`], every set embeds a
//! [`crate::BStackCountingBloomFilter`] maintained as an over-approximation of
//! the tree, so [`contains`](BStackBTreeSet::contains) fast-rejects definitely-
//! absent keys without a tree descent. A key is added to the filter only when it
//! is genuinely new (an exact-membership check precedes the insert), so the
//! filter never over-counts and there are never false negatives. `remove` deletes
//! from the tree (rebalancing on the way down) and then decrements the filter,
//! the same ordering [`crate::BStackHashSet`] uses.

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::bloom::{BStackCountingBloomFilter, BloomOnDisk};
use super::util::{Scratch, alloc_image, read_fields, w8};
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 [`BStackBTreeSet`]: header, root node pointer (`0` =
/// empty), key count, and the embedded Bloom filter's handle offset.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub struct TreeSetOnDisk {
    /// The 16-byte block header (size + type tag).
    pub header: BlockHeader,
    /// Offset of the root node, or `0` when the set is empty.
    pub root: u64,
    /// Number of keys.
    pub len: u64,
    /// Offset of the embedded counting Bloom filter's handle block.
    pub bloom: u64,
}

const ROOT_OFF: u64 = HEADER_SIZE; // 16
const LEN_OFF: u64 = HEADER_SIZE + 8; // 24
const BLOOM_OFF: u64 = HEADER_SIZE + 16; // 32
const TREESET_SIZE: u64 = size_of::<TreeSetOnDisk>() as u64;
const BLOOM_SIZE: u64 = size_of::<BloomOnDisk>() as u64;

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

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

const DEFAULT_ITEMS: u64 = 1024;
const DEFAULT_FP: f64 = 0.01;

/// A node decoded for building: keys as raw bytes and (internal) child offsets.
struct BNode {
    leaf: bool,
    keys: Vec<Vec<u8>>,
    children: Vec<u64>,
}

/// A median key lifted from a split, plus the new right node.
struct Split {
    key: Vec<u8>,
    right: u64,
}

/// Accumulates a path-copy insert's new nodes and the old path nodes to free.
struct Build<'a, A: BStackRaiiAllocator> {
    allocator: &'a A,
    node_size: u64,
    ksize: usize,
    children_off: usize,
    writes: Vec<(u64, SmallBuf)>,
    freed: Vec<u64>,
}

impl<'a, A: BStackRaiiAllocator> Build<'a, A> {
    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, 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 set of `Pod + Ord` keys with an embedded Bloom filter.
pub struct BStackBTreeSet<K: Pod + Ord> {
    range: BStackRange,
    _marker: PhantomData<fn() -> K>,
}

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

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

    fn bloom(&self, stack: &BStack) -> io::Result<BStackCountingBloomFilter<K>> {
        let off = read_u64(stack, self.range.start() + BLOOM_OFF)?;
        Ok(unsafe {
            <BStackCountingBloomFilter<K> as BStackBlock>::from_range(BStackRange::new(
                off, BLOOM_SIZE,
            ))
        })
    }

    /// Allocate an empty set with a default-sized Bloom filter.
    pub fn new<A: BStackRaiiAllocator>(allocator: &A) -> io::Result<BStackOwned<Self>> {
        Self::with_capacity(allocator, DEFAULT_ITEMS, DEFAULT_FP)
    }

    /// Allocate an empty set whose Bloom filter is sized for `expected_items` at
    /// false-positive rate `fp_rate`.
    pub fn with_capacity<A: BStackRaiiAllocator>(
        allocator: &A,
        expected_items: u64,
        fp_rate: f64,
    ) -> io::Result<BStackOwned<Self>> {
        let bloom =
            BStackCountingBloomFilter::<K>::with_capacity(allocator, expected_items, fp_rate)?;
        let bloom_off = bloom.into_inner().range().start();
        let od = TreeSetOnDisk {
            header: BlockHeader {
                size: TREESET_SIZE,
                tag: Self::eightcc(),
            },
            root: 0,
            len: 0,
            bloom: bloom_off,
        };
        match alloc_image(allocator, bytemuck::bytes_of(&od)) {
            // SAFETY: a freshly allocated block owned by no other handle.
            Ok(range) => Ok(unsafe { BStackOwned::from_raw(Self::from_range(range)) }),
            Err(e) => {
                let bloom = unsafe {
                    <BStackCountingBloomFilter<K> as BStackBlock>::from_range(BStackRange::new(
                        bloom_off, BLOOM_SIZE,
                    ))
                };
                let _ = unsafe { BStackOwned::from_raw(bloom) }.bstack_drop(allocator);
                Err(e)
            }
        }
    }

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

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

    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; a corrupted value indexes `b` (a fixed
        // `node_size()`-byte buffer) past its end, panicking on a plain
        // `contains` read. No real node 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 children_off = Self::children_off();
        let mut keys = Vec::with_capacity(nkeys);
        for i in 0..nkeys {
            let ko = KEYS_OFF + i * ksize;
            keys.push(b[ko..ko + ksize].to_vec());
        }
        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,
            children,
        })
    }

    /// First index `i` with `target <= keys[i]`, and whether it is exact.
    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 around its median.
    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 med_key = nb.keys.pop().unwrap();
        let right = BNode {
            leaf: nb.leaf,
            keys: right_keys,
            children: right_children,
        };
        (
            nb,
            Split {
                key: med_key,
                right: 0,
            },
            right,
        )
    }

    /// Path-copy the subtree at `off`, inserting a **new** `key` (assumed absent).
    fn insert_rec(
        build: &mut Build<'_, impl BStackRaiiAllocator>,
        stack: &BStack,
        off: u64,
        key: &K,
        key_bytes: &[u8],
    ) -> io::Result<(u64, Option<Split>)> {
        let mut nb = Self::read_node(stack, off)?;
        build.freed.push(off);
        let (i, _exact) = Self::search(&nb, key);

        if nb.leaf {
            nb.keys.insert(i, key_bytes.to_vec());
        } else {
            let child = nb.children[i];
            let (new_child, child_split) = Self::insert_rec(build, stack, child, key, key_bytes)?;
            nb.children[i] = new_child;
            if let Some(s) = child_split {
                nb.keys.insert(i, s.key);
                nb.children.insert(i + 1, s.right);
            }
        }

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

    /// Insert `key`; returns `true` if newly added, `false` if already present.
    pub fn insert<A: BStackRaiiAllocator>(&self, allocator: &A, key: K) -> io::Result<bool> {
        // Exact check first, so the filter is only touched for genuinely new keys.
        if self.tree_contains(allocator.stack(), &key)? {
            return Ok(false);
        }
        let key_bytes = bytemuck::bytes_of(&key).to_vec();
        self.bloom(allocator.stack())?.insert(allocator, &key)?;

        let handle = self.range.start();
        let stack = allocator.stack();
        let [root, len] = read_fields::<2>(stack, handle + ROOT_OFF)?;

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

        let built: io::Result<u64> = (|| {
            if root == 0 {
                let leaf = BNode {
                    leaf: true,
                    keys: vec![key_bytes.clone()],
                    children: Vec::new(),
                };
                return build.emit(&leaf);
            }
            let (new_root0, split) = Self::insert_rec(&mut build, stack, root, &key, &key_bytes)?;
            if let Some(s) = split {
                let root_node = BNode {
                    leaf: false,
                    keys: vec![s.key],
                    children: vec![new_root0, s.right],
                };
                build.emit(&root_node)
            } else {
                Ok(new_root0)
            }
        })();

        match built {
            Ok(new_root) => {
                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 by the copy just committed (single-writer).
                            let _ = unsafe {
                                dealloc_range(allocator, BStackRange::new(*off, build.node_size))
                            };
                        }
                        Ok(true)
                    }
                    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)
            }
        }
    }

    /// Whether `key` is present. Fast-rejects via the Bloom filter first.
    pub fn contains(&self, stack: &BStack, key: &K) -> io::Result<bool> {
        if !self.bloom(stack)?.contains(stack, key)? {
            return Ok(false);
        }
        self.tree_contains(stack, key)
    }

    /// Exact membership descent (no Bloom fast-reject).
    fn tree_contains(&self, stack: &BStack, key: &K) -> io::Result<bool> {
        let mut off = read_u64(stack, self.range.start() + ROOT_OFF)?;
        let ksize = Self::ksize();
        let children_off = Self::children_off();
        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;
            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 => return Ok(true),
                    Ordering::Greater => {}
                }
            }
            if leaf {
                return Ok(false);
            }
            off = get_u64(&buf[children_off + i * 8..]);
        }
        Ok(false)
    }

    /// The number of keys in the node at `off`. `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 mut b = [0u8; 8];
        stack.get_into(pos, &mut b)?;
        let nkeys = get_u64(&b) as usize;
        if nkeys > MAXKEYS {
            return Err(io_error!("corrupt B-tree node: key count exceeds capacity"));
        }
        Ok(nkeys)
    }

    /// The rightmost / leftmost key bytes in the subtree at `off`.
    fn edge_key(stack: &BStack, off: u64, rightmost: bool) -> io::Result<Vec<u8>> {
        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 c = if rightmost {
                nb.children.last()
            } else {
                nb.children.first()
            }
            .copied()
            .ok_or_else(|| io_error!("corrupt B-tree: internal node has no children"))?;
            nb = Self::read_node(stack, c)?;
        }
        if nb.keys.is_empty() {
            return Err(io_error!("corrupt B-tree: empty leaf node"));
        }
        let i = if rightmost { nb.keys.len() - 1 } else { 0 };
        Ok(nb.keys[i].clone())
    }

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

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

        if found {
            if nb.leaf {
                nb.keys.remove(i);
                return Ok((nb, true));
            }
            let yc = Self::child_nkeys(stack, nb.children[i])?;
            let zc = Self::child_nkeys(stack, nb.children[i + 1])?;
            if yc >= T {
                let pk = Self::edge_key(stack, nb.children[i], true)?;
                nb.keys[i] = pk.clone();
                let (new_y, _) =
                    Self::delete_off(build, stack, nb.children[i], &Self::read_key(&pk))?;
                nb.children[i] = new_y;
            } else if zc >= T {
                let sk = Self::edge_key(stack, nb.children[i + 1], false)?;
                nb.keys[i] = sk.clone();
                let (new_z, _) =
                    Self::delete_off(build, stack, nb.children[i + 1], &Self::read_key(&sk))?;
                nb.children[i + 1] = new_z;
            } else {
                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);
                nb.children.remove(i + 1);
                y.keys.push(sk);
                y.keys.append(&mut z.keys);
                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, true));
        }

        if nb.leaf {
            return Ok((nb, false));
        }

        if Self::child_nkeys(stack, nb.children[i])? >= T {
            let (new_c, found) = Self::delete_off(build, stack, nb.children[i], key)?;
            nb.children[i] = new_c;
            return Ok((nb, found));
        }

        let n = nb.keys.len();
        if i > 0 && Self::child_nkeys(stack, nb.children[i - 1])? >= T {
            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());
            if !ci.leaf {
                ci.children.insert(0, ls.children.pop().unwrap());
            }
            nb.keys[i - 1] = ls.keys.pop().unwrap();
            nb.children[i - 1] = build.emit(&ls)?;
            let (ci2, found) = Self::delete_bnode(build, stack, ci, key)?;
            nb.children[i] = build.emit(&ci2)?;
            return Ok((nb, found));
        }
        if i < n && Self::child_nkeys(stack, nb.children[i + 1])? >= T {
            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());
            if !ci.leaf {
                ci.children.push(rs.children.remove(0));
            }
            nb.keys[i] = rs.keys.remove(0);
            nb.children[i + 1] = build.emit(&rs)?;
            let (ci2, found) = Self::delete_bnode(build, stack, ci, key)?;
            nb.children[i] = build.emit(&ci2)?;
            return Ok((nb, found));
        }

        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);
            nb.children.remove(i + 1);
            ci.keys.push(sk);
            ci.keys.append(&mut rs.keys);
            if !ci.leaf {
                ci.children.append(&mut rs.children);
            }
            let (ci2, found) = Self::delete_bnode(build, stack, ci, key)?;
            nb.children[i] = build.emit(&ci2)?;
            Ok((nb, found))
        } 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);
            nb.children.remove(i);
            ls.keys.push(sk);
            ls.keys.append(&mut ci.keys);
            if !ls.leaf {
                ls.children.append(&mut ci.children);
            }
            let (ls2, found) = Self::delete_bnode(build, stack, ls, key)?;
            nb.children[i - 1] = build.emit(&ls2)?;
            Ok((nb, found))
        }
    }

    /// Remove `key`; returns `true` if it was present. Deletes from the tree
    /// first, then decrements the Bloom filter (see the module docs).
    pub fn remove<A: BStackRaiiAllocator>(&self, allocator: &A, key: &K) -> io::Result<bool> {
        let handle = self.range.start();
        let stack = allocator.stack();
        if !self.tree_contains(stack, key)? {
            return Ok(false);
        }
        let [root, len] = read_fields::<2>(stack, handle + ROOT_OFF)?;

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

        let built: io::Result<u64> = (|| {
            let nb = Self::read_node(stack, root)?;
            build.freed.push(root);
            let (root_nb, _) = Self::delete_bnode(&mut build, stack, nb, key)?;
            let new_root = if root_nb.keys.is_empty() {
                if root_nb.leaf {
                    0
                } else {
                    // Corrupt data errors (reclaimed by the `Err` arm) rather than
                    // panicking past it and leaking the path-copied nodes.
                    *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)
        })();

        match built {
            Ok(new_root) => {
                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 {
                            let _ = unsafe {
                                dealloc_range(allocator, BStackRange::new(*off, build.node_size))
                            };
                        }
                        // Tree updated (the durable commit above); decrement the filter
                        // best-effort. A failure (or a failure to read the filter)
                        // leaves the counter over-high — extra false positives only, a
                        // later `contains` still probes the tree, never a false negative
                        // — so it must not turn this completed removal into an `Err`.
                        let _ = self.bloom(stack).and_then(|b| b.remove(allocator, key));
                        Ok(true)
                    }
                    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 key, or `None` if empty.
    pub fn first(&self, stack: &BStack) -> io::Result<Option<K>> {
        self.extreme(stack, true)
    }

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

    fn extreme(&self, stack: &BStack, leftmost: bool) -> io::Result<Option<K>> {
        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])));
            }
            off = if leftmost {
                nb.children[0]
            } else {
                nb.children[nb.keys.len()]
            };
        }
    }

    /// Collect every key in ascending order.
    pub fn to_vec(&self, stack: &BStack) -> io::Result<Vec<K>> {
        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>) -> 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]));
        }
        if !nb.leaf {
            Self::collect(stack, nb.children[nb.keys.len()], depth + 1, out)?;
        }
        Ok(())
    }

    /// A lazy in-order iterator over all keys, ascending. Reads nodes on demand;
    /// yields `io::Result`. Do not mutate the set's structure while iterating.
    pub fn iter<'a>(&self, stack: &'a BStack) -> io::Result<BTreeSetIter<'a, K>> {
        let [root, len] = read_fields::<2>(stack, self.range.start() + ROOT_OFF)?;
        let frames = Self::descend_left(stack, root)?;
        Ok(BTreeSetIter {
            stack,
            block_off: self.range.start(),
            root0: root,
            len0: len,
            frames,
            hi: None,
            _marker: PhantomData,
        })
    }

    /// A lazy in-order iterator over the keys with `lo <= key <= hi`, ascending.
    pub fn range<'a>(&self, stack: &'a BStack, lo: K, hi: K) -> io::Result<BTreeSetIter<'a, K>> {
        let [root, len] = read_fields::<2>(stack, self.range.start() + ROOT_OFF)?;
        let frames = Self::seek(stack, root, &lo)?;
        Ok(BTreeSetIter {
            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`.
    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);
            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)
    }

    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)?;
            }
        }
        // SAFETY: the set solely owns each node block.
        unsafe { dealloc_range(allocator, BStackRange::new(off, Self::node_size()))? };
        Ok(())
    }

    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 children_off = Self::children_off();
        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> BStackCast for BStackBTreeSet<K> {
    /// A `"TSt"` prefix perturbed by the key size.
    fn eightcc() -> EightCC {
        const BASE: EightCC = EightCC::new([b'T', b'S', b't', 0x80, 0x81, 0x82, 0x83, 0x84]);
        BASE.mix(EightCC::new((size_of::<K>() as u64).to_le_bytes()))
    }
}

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

impl<K: Pod + Ord> BStackBlock for BStackBTreeSet<K> {
    type OnDisk = TreeSetOnDisk;

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

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

    /// Recursively free every node and the embedded Bloom filter, **without**
    /// freeing the handle block itself.
    fn __bstack_drop_children<A: BStackRaiiAllocator>(
        allocator: &A,
        range: BStackRange,
    ) -> io::Result<()> {
        let handle = range.start();
        let [root, _len, bloom_off] = read_fields::<3>(allocator.stack(), handle + ROOT_OFF)?;
        Self::drop_subtree(allocator.stack(), root, allocator, 0)?;
        if bloom_off != 0 {
            // SAFETY: the set solely owns its embedded Bloom filter.
            let bloom = unsafe {
                <BStackCountingBloomFilter<K> as BStackBlock>::from_range(BStackRange::new(
                    bloom_off, BLOOM_SIZE,
                ))
            };
            unsafe { BStackOwned::from_raw(bloom) }.bstack_drop(allocator)?;
        }
        Ok(())
    }

    /// Deep-clone every node and the Bloom filter into `plan`, then stage the
    /// handle.
    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, bloom_off] = read_fields::<3>(allocator.stack(), handle + ROOT_OFF)?;

        let new_root = Self::clone_subtree(allocator.stack(), root, allocator, plan, 0)?;
        let bloom = unsafe {
            <BStackCountingBloomFilter<K> as BStackBlock>::from_range(BStackRange::new(
                bloom_off, BLOOM_SIZE,
            ))
        };
        let new_bloom = bloom.__bstack_clone_into(allocator, plan)?.start();

        let od = TreeSetOnDisk {
            header: BlockHeader {
                size: TREESET_SIZE,
                tag: Self::eightcc(),
            },
            root: new_root,
            len,
            bloom: new_bloom,
        };
        Ok(od)
    }
}

impl<K: Pod + Ord> TryCloneIn for BStackBTreeSet<K> {}

/// A lazy in-order iterator over a [`BStackBTreeSet`], yielding `io::Result<K>`
/// in ascending order. Created by [`BStackBTreeSet::iter`] /
/// [`BStackBTreeSet::range`].
pub struct BTreeSetIter<'a, K: Pod + Ord> {
    stack: &'a BStack,
    /// The set 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>,
}

impl<'a, K: Pod + Ord> Iterator for BTreeSetIter<'a, K> {
    type Item = io::Result<K>;

    fn next(&mut self) -> Option<Self::Item> {
        // Fail fast if the set was mutated during iteration: a path-copying
        // insert / 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.
        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!(
                        "BStackBTreeSet 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 = BStackBTreeSet::<K>::read_key(&node.keys[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;
            }
            self.frames.last_mut().unwrap().1 = i + 1;
            if !leaf {
                match BStackBTreeSet::<K>::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));
        }
    }
}