anomstream-core 2026.4.1

Core streaming anomaly detectors + companion primitives (Random Cut Forest, per-feature EWMA / CUSUM, drift detectors, streaming stats) — part of the anomstream toolkit
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
//! Flat-array node storage with `O(1)` allocation and deallocation.
//!
//! Internal nodes live in `internals[0..capacity)`, leaves live in
//! `leaves[0..capacity)`. Each arena owns its own free list (LIFO
//! stack of freed slot indices) so allocations reuse the most-recently
//! freed slot first — which keeps the live working set compact and
//! cache-friendly.
//!
//! Bounding-box semantics: only internal nodes carry a cached
//! bounding box. Leaves know their point only through `point_idx`
//! into the [`crate::forest::PointStore`]; when a caller needs a
//! leaf bounding box it builds a degenerate one from the point
//! itself. This keeps leaf storage at 24 bytes (idx + parent +
//! mass) instead of duplicating per-leaf coordinate data, saving
//! ~6 MB at default configuration.

use alloc::format;
use alloc::vec::Vec;

use crate::domain::{BoundingBox, Cut};
use crate::error::{RcfError, RcfResult};
use crate::tree::node::{InternalData, LeafData, NodeRef, NodeView, NodeViewMut};

/// Flat-array storage for [`NodeRef`]-addressed nodes with `O(1)` allocation and
/// deallocation via per-arena free lists.
///
/// # Examples
///
/// ```
/// use anomstream_core::NodeStore;
///
/// let mut store = NodeStore::<2>::new(4).unwrap();
/// let leaf = store.add_leaf(0, None, 1).unwrap();
/// assert!(leaf.is_leaf());
/// assert_eq!(store.live_count(), 1);
/// ```
#[derive(Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NodeStore<const D: usize> {
    /// Internal-node arena. `None` slots are free. Split from the
    /// leaves so each slot is exactly the size of one
    /// [`InternalData<D>`] record instead of paying the full
    /// `Node<D>`-enum worst-case.
    internals: Vec<Option<InternalData<D>>>,
    /// Leaf arena. `None` slots are free. Each slot holds a
    /// small [`LeafData`] record (24 bytes + `Option` overhead)
    /// instead of the old enum-sized ~320 bytes at `D = 16`.
    leaves: Vec<Option<LeafData>>,
    /// LIFO stack of free internal slot indices.
    internal_free: Vec<u32>,
    /// LIFO stack of free leaf slot indices.
    leaf_free: Vec<u32>,
    /// Per-arena capacity (each arena holds at most this many slots).
    capacity: u32,
}

impl<const D: usize> NodeStore<D> {
    /// Build a store with `capacity` internal slots and `capacity`
    /// leaf slots, all initially free.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::InvalidConfig`] when `capacity == 0` or
    /// `capacity > NodeRef::MAX_INDEX + 1`.
    pub fn new(capacity: u32) -> RcfResult<Self> {
        if capacity == 0 {
            return Err(RcfError::InvalidConfig(
                "NodeStore capacity must be > 0".into(),
            ));
        }
        if capacity > NodeRef::MAX_INDEX {
            return Err(RcfError::InvalidConfig(
                format!(
                    "NodeStore capacity {capacity} exceeds NodeRef::MAX_INDEX {}",
                    NodeRef::MAX_INDEX
                )
                .into(),
            ));
        }
        let cap = capacity as usize;
        let internals = (0..cap).map(|_| None).collect();
        let leaves = (0..cap).map(|_| None).collect();
        // Free list pre-populated in descending order so `pop()` hands
        // out index 0 first — keeps the live set front-loaded.
        let internal_free = (0..capacity).rev().collect();
        let leaf_free = (0..capacity).rev().collect();
        Ok(Self {
            internals,
            leaves,
            internal_free,
            leaf_free,
            capacity,
        })
    }

    /// Per-arena slot capacity.
    #[must_use]
    pub fn capacity(&self) -> u32 {
        self.capacity
    }

    /// Number of live nodes (internals + leaves).
    #[must_use]
    pub fn live_count(&self) -> usize {
        self.live_internal_count() + self.live_leaf_count()
    }

    /// Number of live internal nodes.
    #[must_use]
    pub fn live_internal_count(&self) -> usize {
        self.capacity as usize - self.internal_free.len()
    }

    /// Number of live leaf nodes.
    #[must_use]
    pub fn live_leaf_count(&self) -> usize {
        self.capacity as usize - self.leaf_free.len()
    }

    /// Allocate an internal node.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::InvalidConfig`] when the internal arena is
    /// exhausted (every slot is live).
    pub fn add_internal(
        &mut self,
        cut: Cut,
        bbox: BoundingBox<D>,
        left: NodeRef,
        right: NodeRef,
        parent: Option<NodeRef>,
        mass: u64,
    ) -> RcfResult<NodeRef> {
        let idx = self
            .internal_free
            .pop()
            .ok_or_else(|| RcfError::InvalidConfig("NodeStore internal arena exhausted".into()))?;
        self.internals[idx as usize] = Some(InternalData {
            cut,
            bbox,
            left,
            right,
            parent,
            mass,
        });
        Ok(NodeRef::internal(idx))
    }

    /// Allocate a leaf node.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::InvalidConfig`] when the leaf arena is
    /// exhausted (every slot is live).
    pub fn add_leaf(
        &mut self,
        point_idx: usize,
        parent: Option<NodeRef>,
        mass: u64,
    ) -> RcfResult<NodeRef> {
        let idx = self
            .leaf_free
            .pop()
            .ok_or_else(|| RcfError::InvalidConfig("NodeStore leaf arena exhausted".into()))?;
        self.leaves[idx as usize] = Some(LeafData {
            point_idx,
            parent,
            mass,
        });
        Ok(NodeRef::leaf(idx))
    }

    /// Free a node back to its arena. The slot becomes available for
    /// the next allocation.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::OutOfBounds`] when the slot is empty
    /// (double-free) or `n.index() >= capacity()`.
    pub fn delete(&mut self, n: NodeRef) -> RcfResult<()> {
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        let was_live = if n.is_leaf() {
            self.leaves[idx].take().is_some()
        } else {
            self.internals[idx].take().is_some()
        };
        if !was_live {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        if n.is_leaf() {
            #[allow(clippy::cast_possible_truncation)]
            self.leaf_free.push(idx as u32);
        } else {
            #[allow(clippy::cast_possible_truncation)]
            self.internal_free.push(idx as u32);
        }
        Ok(())
    }

    /// Zero-copy immutable view of a node. Pattern-match on the
    /// returned [`NodeView`] to branch on internal-vs-leaf without
    /// cloning the underlying record.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::OutOfBounds`] when the slot is empty or
    /// `n.index() >= capacity()`.
    pub fn view(&self, n: NodeRef) -> RcfResult<NodeView<'_, D>> {
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        if n.is_leaf() {
            self.leaves[idx]
                .as_ref()
                .map(NodeView::Leaf)
                .ok_or(RcfError::OutOfBounds {
                    index: idx,
                    len: self.capacity as usize,
                })
        } else {
            self.internals[idx]
                .as_ref()
                .map(NodeView::Internal)
                .ok_or(RcfError::OutOfBounds {
                    index: idx,
                    len: self.capacity as usize,
                })
        }
    }

    /// Zero-copy mutable view of a node — see [`Self::view`].
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::OutOfBounds`] when the slot is empty or
    /// `n.index() >= capacity()`.
    pub fn view_mut(&mut self, n: NodeRef) -> RcfResult<NodeViewMut<'_, D>> {
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        if n.is_leaf() {
            self.leaves[idx]
                .as_mut()
                .map(NodeViewMut::Leaf)
                .ok_or(RcfError::OutOfBounds {
                    index: idx,
                    len: self.capacity as usize,
                })
        } else {
            self.internals[idx]
                .as_mut()
                .map(NodeViewMut::Internal)
                .ok_or(RcfError::OutOfBounds {
                    index: idx,
                    len: self.capacity as usize,
                })
        }
    }

    /// Typed immutable accessor for an internal node. Prefer this
    /// when the caller already knows the node is internal —
    /// one-level shallower than going through [`Self::view`] + match.
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when the slot is empty or OOB.
    /// - [`RcfError::InvalidConfig`] when called on a leaf reference.
    pub fn internal(&self, n: NodeRef) -> RcfResult<&InternalData<D>> {
        if n.is_leaf() {
            return Err(RcfError::InvalidConfig(
                "NodeStore::internal: called on a leaf reference".into(),
            ));
        }
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        self.internals[idx].as_ref().ok_or(RcfError::OutOfBounds {
            index: idx,
            len: self.capacity as usize,
        })
    }

    /// Typed mutable accessor for an internal node — see
    /// [`Self::internal`].
    ///
    /// # Errors
    ///
    /// Same as [`Self::internal`].
    pub fn internal_mut(&mut self, n: NodeRef) -> RcfResult<&mut InternalData<D>> {
        if n.is_leaf() {
            return Err(RcfError::InvalidConfig(
                "NodeStore::internal_mut: called on a leaf reference".into(),
            ));
        }
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        self.internals[idx].as_mut().ok_or(RcfError::OutOfBounds {
            index: idx,
            len: self.capacity as usize,
        })
    }

    /// Typed immutable accessor for a leaf node.
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when the slot is empty or OOB.
    /// - [`RcfError::InvalidConfig`] when called on an internal reference.
    pub fn leaf(&self, n: NodeRef) -> RcfResult<&LeafData> {
        if !n.is_leaf() {
            return Err(RcfError::InvalidConfig(
                "NodeStore::leaf: called on an internal reference".into(),
            ));
        }
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        self.leaves[idx].as_ref().ok_or(RcfError::OutOfBounds {
            index: idx,
            len: self.capacity as usize,
        })
    }

    /// Typed mutable accessor for a leaf node — see [`Self::leaf`].
    ///
    /// # Errors
    ///
    /// Same as [`Self::leaf`].
    pub fn leaf_mut(&mut self, n: NodeRef) -> RcfResult<&mut LeafData> {
        if !n.is_leaf() {
            return Err(RcfError::InvalidConfig(
                "NodeStore::leaf_mut: called on an internal reference".into(),
            ));
        }
        let idx = n.index();
        if idx >= self.capacity as usize {
            return Err(RcfError::OutOfBounds {
                index: idx,
                len: self.capacity as usize,
            });
        }
        self.leaves[idx].as_mut().ok_or(RcfError::OutOfBounds {
            index: idx,
            len: self.capacity as usize,
        })
    }

    /// Parent reference of a node (`None` for the root).
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::OutOfBounds`] when the node does not exist.
    pub fn parent(&self, n: NodeRef) -> RcfResult<Option<NodeRef>> {
        Ok(self.view(n)?.parent())
    }

    /// Sibling of a node.
    ///
    /// Returns `None` when `n` is the root (no parent → no sibling).
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when `n` does not exist.
    /// - [`RcfError::InvalidConfig`] when the parent is a leaf
    ///   (impossible state — internal data structure invariant violated)
    ///   or when `n` is not registered as a child of its parent
    ///   (orphan).
    pub fn sibling(&self, n: NodeRef) -> RcfResult<Option<NodeRef>> {
        let Some(parent_ref) = self.parent(n)? else {
            return Ok(None);
        };
        if parent_ref.is_leaf() {
            return Err(RcfError::InvalidConfig(
                "NodeStore::sibling: parent is a leaf — invariant violated".into(),
            ));
        }
        let parent = self.internal(parent_ref)?;
        let n_raw = n.raw();
        if parent.left.raw() == n_raw {
            Ok(Some(parent.right))
        } else if parent.right.raw() == n_raw {
            Ok(Some(parent.left))
        } else {
            Err(RcfError::InvalidConfig(
                "NodeStore::sibling: child not registered with parent".into(),
            ))
        }
    }

    /// Cached bounding box of an *internal* node.
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when the node does not exist.
    /// - [`RcfError::InvalidConfig`] when called on a leaf — leaf
    ///   bounding boxes are degenerate single-point boxes; build them
    ///   from the underlying point store entry on the consumer side.
    pub fn internal_bbox(&self, n: NodeRef) -> RcfResult<&BoundingBox<D>> {
        Ok(&self.internal(n)?.bbox)
    }

    /// Set the parent of a node.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::OutOfBounds`] when the node does not exist.
    pub fn set_parent(&mut self, n: NodeRef, parent: Option<NodeRef>) -> RcfResult<()> {
        match self.view_mut(n)? {
            NodeViewMut::Internal(i) => {
                i.parent = parent;
            }
            NodeViewMut::Leaf(l) => {
                l.parent = parent;
            }
        }
        Ok(())
    }

    /// Replace the mass of a node.
    ///
    /// # Errors
    ///
    /// Returns [`RcfError::OutOfBounds`] when the node does not exist.
    pub fn set_mass(&mut self, n: NodeRef, mass: u64) -> RcfResult<()> {
        match self.view_mut(n)? {
            NodeViewMut::Internal(i) => {
                i.mass = mass;
            }
            NodeViewMut::Leaf(l) => {
                l.mass = mass;
            }
        }
        Ok(())
    }

    /// Replace the cached bounding box of an internal node.
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when the node does not exist.
    /// - [`RcfError::InvalidConfig`] when called on a leaf.
    pub fn set_internal_bbox(&mut self, n: NodeRef, bbox: BoundingBox<D>) -> RcfResult<()> {
        self.internal_mut(n)?.bbox = bbox;
        Ok(())
    }

    /// Replace the children of an internal node. Used by
    /// [`crate::RandomCutTree`] `delete` when merging a sibling
    /// into its grandparent's slot.
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when the node does not exist.
    /// - [`RcfError::InvalidConfig`] when called on a leaf.
    pub fn set_internal_children(
        &mut self,
        n: NodeRef,
        new_left: NodeRef,
        new_right: NodeRef,
    ) -> RcfResult<()> {
        let i = self.internal_mut(n)?;
        i.left = new_left;
        i.right = new_right;
        Ok(())
    }

    /// Replace the cut of an internal node. Used when a tree
    /// rearrangement preserves the slot but swaps in a new cut.
    ///
    /// # Errors
    ///
    /// - [`RcfError::OutOfBounds`] when the node does not exist.
    /// - [`RcfError::InvalidConfig`] when called on a leaf.
    pub fn set_internal_cut(&mut self, n: NodeRef, new_cut: Cut) -> RcfResult<()> {
        self.internal_mut(n)?.cut = new_cut;
        Ok(())
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)] // Tests assert exact equality on integer-valued masses.
mod tests {
    use super::*;
    use proptest::prelude::*;

    fn unit_bbox<const D: usize>() -> BoundingBox<D> {
        let mut b = BoundingBox::<D>::from_point(&vec![0.0; D]).unwrap();
        b.extend(&vec![1.0; D]).unwrap();
        b
    }

    #[test]
    fn new_rejects_zero_capacity() {
        assert!(matches!(
            NodeStore::<2>::new(0).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
    }

    #[test]
    fn new_rejects_capacity_above_max() {
        // u32::MAX is > MAX_INDEX (1 << 31).
        assert!(matches!(
            NodeStore::<2>::new(u32::MAX).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
    }

    #[test]
    fn new_starts_empty() {
        let s = NodeStore::<2>::new(8).unwrap();
        assert_eq!(s.capacity(), 8);
        assert_eq!(s.live_count(), 0);
        assert_eq!(s.live_internal_count(), 0);
        assert_eq!(s.live_leaf_count(), 0);
    }

    #[test]
    fn add_leaf_increments_live() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let l = s.add_leaf(7, None, 1).unwrap();
        assert!(l.is_leaf());
        assert_eq!(s.live_leaf_count(), 1);
        assert_eq!(s.live_internal_count(), 0);
    }

    #[test]
    fn add_internal_increments_live() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1).unwrap();
        let cut = Cut::new(0, 0.5);
        let i = s
            .add_internal(cut, unit_bbox::<2>(), l1, l2, None, 2)
            .unwrap();
        assert!(i.is_internal());
        assert_eq!(s.live_internal_count(), 1);
        assert_eq!(s.live_leaf_count(), 2);
        assert_eq!(s.live_count(), 3);
    }

    #[test]
    fn add_leaf_capacity_exhausted() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        s.add_leaf(0, None, 1).unwrap();
        s.add_leaf(1, None, 1).unwrap();
        assert!(matches!(
            s.add_leaf(2, None, 1).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
    }

    #[test]
    fn add_internal_capacity_exhausted() {
        let mut s = NodeStore::<2>::new(1).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1);
        // capacity=1: only one leaf slot.
        assert!(matches!(l2.unwrap_err(), RcfError::InvalidConfig(_)));
        let i = s
            .add_internal(Cut::new(0, 0.0), unit_bbox::<2>(), l1, l1, None, 1)
            .unwrap();
        assert!(
            s.add_internal(Cut::new(0, 0.0), unit_bbox::<2>(), i, i, None, 1)
                .is_err()
        );
    }

    #[test]
    fn delete_frees_slot_for_reuse() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(7, None, 1).unwrap();
        let l_idx = l.index();
        s.delete(l).unwrap();
        assert_eq!(s.live_leaf_count(), 0);
        // Same slot reused on next allocation (LIFO).
        let l2 = s.add_leaf(99, None, 1).unwrap();
        assert_eq!(l2.index(), l_idx);
    }

    #[test]
    fn delete_oob_index_rejected() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let bogus = NodeRef::leaf(99);
        assert!(matches!(
            s.delete(bogus).unwrap_err(),
            RcfError::OutOfBounds { .. }
        ));
    }

    #[test]
    fn delete_double_free_rejected() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(0, None, 1).unwrap();
        s.delete(l).unwrap();
        assert!(matches!(
            s.delete(l).unwrap_err(),
            RcfError::OutOfBounds { .. }
        ));
    }

    #[test]
    fn leaf_returns_inserted_value() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(42, None, 1).unwrap();
        let data = s.leaf(l).unwrap();
        assert_eq!(data.point_idx, 42);
        assert_eq!(data.mass, 1);
    }

    #[test]
    fn leaf_mut_allows_inplace_update() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(1, None, 1).unwrap();
        s.leaf_mut(l).unwrap().mass = 5;
        assert_eq!(s.view(l).unwrap().mass(), 5);
    }

    #[test]
    fn view_oob_returns_err() {
        let s = NodeStore::<2>::new(2).unwrap();
        assert!(matches!(
            s.view(NodeRef::leaf(7)).unwrap_err(),
            RcfError::OutOfBounds { .. }
        ));
    }

    #[test]
    fn parent_and_sibling_lookup() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1).unwrap();
        let i = s
            .add_internal(Cut::new(0, 0.5), unit_bbox::<2>(), l1, l2, None, 2)
            .unwrap();
        s.set_parent(l1, Some(i)).unwrap();
        s.set_parent(l2, Some(i)).unwrap();

        assert_eq!(s.parent(l1).unwrap(), Some(i));
        assert_eq!(s.parent(i).unwrap(), None);
        assert_eq!(s.sibling(l1).unwrap(), Some(l2));
        assert_eq!(s.sibling(l2).unwrap(), Some(l1));
        // Root has no sibling.
        assert_eq!(s.sibling(i).unwrap(), None);
    }

    #[test]
    fn sibling_orphan_detected() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let real_l = s.add_leaf(0, None, 1).unwrap();
        let fake_l = s.add_leaf(1, None, 1).unwrap();
        let other = s.add_leaf(2, None, 1).unwrap();
        let i = s
            .add_internal(Cut::new(0, 0.5), unit_bbox::<2>(), real_l, other, None, 2)
            .unwrap();
        // fake_l claims `i` as its parent without being one of its children.
        s.set_parent(fake_l, Some(i)).unwrap();
        assert!(matches!(
            s.sibling(fake_l).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
    }

    #[test]
    fn sibling_parent_is_leaf_rejected() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let leaf_parent = s.add_leaf(0, None, 1).unwrap();
        let child = s.add_leaf(1, None, 1).unwrap();
        // Manually break the invariant: child claims a leaf as its parent.
        s.set_parent(child, Some(leaf_parent)).unwrap();
        assert!(matches!(
            s.sibling(child).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
    }

    #[test]
    fn internal_bbox_returns_cached_box() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1).unwrap();
        let bbox = unit_bbox::<2>();
        let i = s
            .add_internal(Cut::new(0, 0.5), bbox.clone(), l1, l2, None, 2)
            .unwrap();
        assert_eq!(s.internal_bbox(i).unwrap(), &bbox);
    }

    #[test]
    fn internal_bbox_on_leaf_rejected() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(0, None, 1).unwrap();
        assert!(matches!(
            s.internal_bbox(l).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
    }

    #[test]
    fn set_mass_updates_leaf_and_internal() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(0, None, 1).unwrap();
        s.set_mass(l, 9).unwrap();
        assert_eq!(s.view(l).unwrap().mass(), 9);
    }

    #[test]
    fn set_internal_bbox_replaces_cached() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1).unwrap();
        let i = s
            .add_internal(Cut::new(0, 0.5), unit_bbox::<2>(), l1, l2, None, 2)
            .unwrap();
        let mut new_bbox = BoundingBox::<2>::from_point(&[0.0, 0.0]).unwrap();
        new_bbox.extend(&[10.0, 10.0]).unwrap();
        s.set_internal_bbox(i, new_bbox.clone()).unwrap();
        assert_eq!(s.internal_bbox(i).unwrap(), &new_bbox);
    }

    #[test]
    fn set_internal_children_swaps_refs() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1).unwrap();
        let l3 = s.add_leaf(2, None, 1).unwrap();
        let i = s
            .add_internal(Cut::new(0, 0.5), unit_bbox::<2>(), l1, l2, None, 2)
            .unwrap();
        s.set_internal_children(i, l1, l3).unwrap();
        let data = s.internal(i).unwrap();
        assert_eq!(data.left, l1);
        assert_eq!(data.right, l3);
    }

    #[test]
    fn set_internal_cut_replaces_cut() {
        let mut s = NodeStore::<2>::new(4).unwrap();
        let l1 = s.add_leaf(0, None, 1).unwrap();
        let l2 = s.add_leaf(1, None, 1).unwrap();
        let i = s
            .add_internal(Cut::new(0, 0.5), unit_bbox::<2>(), l1, l2, None, 2)
            .unwrap();
        s.set_internal_cut(i, Cut::new(1, 9.0)).unwrap();
        let data = s.internal(i).unwrap();
        assert_eq!(data.cut.dim(), 1);
        assert_eq!(data.cut.value(), 9.0);
    }

    #[test]
    fn setters_reject_oob_or_wrong_kind() {
        let mut s = NodeStore::<2>::new(2).unwrap();
        let l = s.add_leaf(0, None, 1).unwrap();
        assert!(matches!(
            s.set_internal_bbox(l, unit_bbox::<2>()).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
        assert!(matches!(
            s.set_internal_children(l, l, l).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
        assert!(matches!(
            s.set_internal_cut(l, Cut::new(0, 0.0)).unwrap_err(),
            RcfError::InvalidConfig(_)
        ));
        assert!(matches!(
            s.set_parent(NodeRef::leaf(99), None).unwrap_err(),
            RcfError::OutOfBounds { .. }
        ));
        assert!(matches!(
            s.set_mass(NodeRef::leaf(99), 1).unwrap_err(),
            RcfError::OutOfBounds { .. }
        ));
    }

    // Property test: random sequences of add/delete keep the
    // invariant `live_count = capacity − free_list.len()` and never
    // produce duplicate live indices.
    proptest! {
        #![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
        #[test]
        fn invariants_under_random_ops(ops in proptest::collection::vec(0u32..20, 0..200)) {
            const CAP: u32 = 16;
            let mut s = NodeStore::<2>::new(CAP).unwrap();
            let mut live_leaves: Vec<NodeRef> = Vec::new();
            let mut live_internals: Vec<NodeRef> = Vec::new();

            for op in ops {
                match op % 4 {
                    0 => {
                        if let Ok(r) = s.add_leaf(0, None, 1) {
                            // No duplicate live ref for the same slot.
                            prop_assert!(!live_leaves.iter().any(|x| x.raw() == r.raw()));
                            live_leaves.push(r);
                        }
                    }
                    1 => {
                        if live_leaves.len() >= 2 {
                            let l1 = live_leaves[live_leaves.len() - 1];
                            let l2 = live_leaves[live_leaves.len() - 2];
                            if let Ok(r) = s.add_internal(
                                Cut::new(0, 0.0), unit_bbox::<2>(), l1, l2, None, 2,
                            ) {
                                prop_assert!(!live_internals.iter().any(|x| x.raw() == r.raw()));
                                live_internals.push(r);
                            }
                        }
                    }
                    2 => {
                        if let Some(l) = live_leaves.pop() {
                            s.delete(l).unwrap();
                        }
                    }
                    _ => {
                        if let Some(i) = live_internals.pop() {
                            s.delete(i).unwrap();
                        }
                    }
                }
                prop_assert_eq!(s.live_leaf_count(), live_leaves.len());
                prop_assert_eq!(s.live_internal_count(), live_internals.len());
                prop_assert_eq!(s.live_count(), live_leaves.len() + live_internals.len());
            }
        }
    }
}