holt 0.3.2

An adaptive-radix-tree metadata storage engine for path-shaped keys, with per-blob concurrency and crash-safe persistence.
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
//! Spillover infra — pick a subtree to migrate when a blob fills,
//! stage it as a fresh dirty child blob, free the source's slots,
//! and install a `BlobNode` placeholder.
//!
//! Also hosts:
//! - `free_subtree` (recursive slot reclaim after migration)
//! - `fresh_blob_guid` (cheap process-local GUIDs)
//! - `compact_blob` (in-place repack, re-exported from
//!   [`super::migrate`])

use crate::api::errors::{Error, Result};
use crate::layout::{
    leaf_extent_size, size_of_node, BlobGuid, BlobNode, Node16, Node256, Node4, Node48, NodeType,
    Prefix, DATA_AREA_START, PAGE_SIZE,
};
use crate::store::{BlobFrame, BufferManager};

use super::cast;
use super::migrate::make_blob_from_node_in;
use super::readers::{
    ntype_of, read_leaf_key_ref, read_node16, read_node256, read_node4, read_node48, read_prefix,
};
use super::types::{Victim, VictimEdgeKind};
use super::writers::{inner_update_child, set_prefix_child, write_struct_to_slot};

// Re-export `compact_blob` so `insert_multi` can reach it via
// `super::spillover::compact_blob`.
pub(super) use super::migrate::compact_blob;

const SPILLOVER_TARGET_CHILD_FILL_PCT: u32 = 70;
const SPILLOVER_MIN_CHILD_FILL_PCT: u32 = 35;

#[derive(Debug, Clone, Copy)]
struct SubtreeFootprint {
    nodes: u32,
    bytes: u32,
}

#[derive(Debug, Clone, Copy)]
struct VictimCandidate {
    victim: Victim,
    footprint: SubtreeFootprint,
    boundary: BoundaryQuality,
    boundary_depth: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BoundaryQuality {
    Arbitrary,
    PathComponent,
}

fn spillover_data_capacity() -> u32 {
    PAGE_SIZE - DATA_AREA_START
}

fn spillover_target_child_bytes() -> u32 {
    spillover_data_capacity() * SPILLOVER_TARGET_CHILD_FILL_PCT / 100
}

fn spillover_min_child_bytes() -> u32 {
    spillover_data_capacity() * SPILLOVER_MIN_CHILD_FILL_PCT / 100
}

/// Trigger spillover on `frame`: migrate a subtree out to a fresh
/// child blob (via [`make_blob_from_node`]), free the migrated
/// slots, and install a [`BlobNode`] placeholder at the migrated
/// location.
///
/// Heuristic: pick an occupancy-aware non-Blob subtree at the
/// root's first branching node (i.e. skip BlobNode children —
/// those are already migrated). The target is a child blob around
/// 70% full, with node count used only as a tie-breaker. This keeps
/// blob hops and follow-up split pressure stable at multi-million
/// key scale instead of repeatedly peeling off the largest branch
/// into near-full child blobs.
///
/// Returns the BlobNode slot installed in `frame` so callers /
/// tests can verify. The new blob lives in the BM cache + dirty
/// map; its store write happens during the next checkpoint round
/// (after the WAL record for the spillover-triggering op is
/// durable — invariant W2D).
///
/// `seq` is the WAL seq the caller pre-allocated for the op that
/// triggered spillover (insert / rename / batched put). The new
/// child blob is tagged `mark_dirty(new_guid, seq)` so the
/// checkpoint round's truncate gate can't drop the WAL record
/// before the blob's bytes are durable.
pub(super) fn spillover_blob(
    bm: &BufferManager,
    frame: &mut BlobFrame<'_>,
    seq: u64,
) -> Result<u16> {
    let root_slot = frame.header().root_slot;
    let victim = pick_victim_subtree(frame, root_slot)?;

    let new_guid = fresh_blob_guid();
    let outcome = make_blob_from_node_in(bm, frame, victim.victim_slot, new_guid)?;

    // Stage the new blob via the unified `mark_dirty → checkpoint
    // round` protocol — the bytes stay in cache until the round
    // flushes WAL **first** and then writes them through. An
    // inline `bm.write_blob(new_guid, ...) + bm.flush()` here
    // would violate invariant W2D: a crash between the inline
    // write and the user's WAL flush would leave an orphan in
    // store AND the parent's BlobNode staged only in cache —
    // and a racing checkpointer could flush the parent's
    // BlobNode before the user's WAL record was durable,
    // leaving the on-disk parent pointing at the pre-spillover
    // orphan position.
    bm.install_new_blob(new_guid, outcome.buf, seq);

    // Free the migrated subtree's slots in the source blob.
    free_subtree(frame, victim.victim_slot)?;

    // Allocate a BlobNode pointing at the child blob. The child
    // blob's own header.root_slot is the only entry slot.
    let bn_alloc = frame.alloc_node(NodeType::Blob)?;
    let bn = BlobNode::new(&[], new_guid);
    write_struct_to_slot(frame, bn_alloc.slot, &bn)?;

    // Wire the parent of the migrated subtree to point at the new
    // BlobNode instead of the now-freed victim slot.
    if victim.parent_slot == root_slot && victim.via_header_root {
        frame.header_mut().root_slot = bn_alloc.slot;
    } else {
        match victim.kind {
            VictimEdgeKind::Prefix => {
                set_prefix_child(frame, victim.parent_slot, u32::from(bn_alloc.slot))?;
            }
            VictimEdgeKind::Inner(parent_ntype) => {
                inner_update_child(
                    frame,
                    victim.parent_slot,
                    parent_ntype,
                    victim.byte,
                    u32::from(bn_alloc.slot),
                )?;
            }
        }
    }

    #[cfg(feature = "tracing")]
    tracing::debug!(
        target: "holt::engine::spillover",
        new_child_guid = ?&new_guid[..4],
        victim_slot = victim.victim_slot,
        bn_slot = bn_alloc.slot,
        "spillover: migrated subtree to fresh child blob",
    );

    Ok(bn_alloc.slot)
}

fn subtree_footprint(frame: &BlobFrame<'_>, root: u16) -> Result<SubtreeFootprint> {
    let ntype = ntype_of(frame.as_ref(), root)?;
    if ntype == NodeType::Invalid {
        return Err(Error::node_corrupt("subtree_footprint: Invalid"));
    }
    let body = frame.body_of_slot(root).ok_or(Error::node_corrupt(
        "subtree_footprint: body resolution failed",
    ))?;
    let mut out = SubtreeFootprint {
        nodes: 1,
        bytes: size_of_node(ntype),
    };
    match ntype {
        NodeType::Invalid => unreachable!("handled before size_of_node"),
        NodeType::Leaf => {
            let (key, leaf) = read_leaf_key_ref(frame.as_ref(), root)?;
            out.bytes = out.bytes.saturating_add(leaf_extent_size(
                key.len() as u32,
                u32::from(leaf.value_size),
            ));
        }
        NodeType::EmptyRoot | NodeType::Blob => {}
        NodeType::Prefix => {
            let p = cast::<Prefix>(body);
            out = out.saturating_add(subtree_footprint(frame, p.child as u16)?);
        }
        NodeType::Node4 => {
            let n = cast::<Node4>(body);
            for i in 0..(n.count as usize).min(4) {
                out = out.saturating_add(subtree_footprint(frame, n.children[i] as u16)?);
            }
        }
        NodeType::Node16 => {
            let n = cast::<Node16>(body);
            for i in 0..(n.count as usize).min(16) {
                out = out.saturating_add(subtree_footprint(frame, n.children[i] as u16)?);
            }
        }
        NodeType::Node48 => {
            let n = cast::<Node48>(body);
            for c in &n.children {
                if *c != 0 {
                    out = out.saturating_add(subtree_footprint(frame, *c as u16)?);
                }
            }
        }
        NodeType::Node256 => {
            let n = cast::<Node256>(body);
            for c in &n.children {
                if *c != 0 {
                    out = out.saturating_add(subtree_footprint(frame, *c as u16)?);
                }
            }
        }
    }
    Ok(out)
}

impl SubtreeFootprint {
    fn saturating_add(mut self, rhs: Self) -> Self {
        self.nodes = self.nodes.saturating_add(rhs.nodes);
        self.bytes = self.bytes.saturating_add(rhs.bytes);
        self
    }
}

/// Pick an occupancy-aware non-`BlobNode` subtree below
/// `start_slot`. Direct children are considered first; if a child
/// is already larger than the target child fill, the search descends
/// inside that child to find a healthier prefix boundary.
///
/// **Heuristic rationale:**
/// - Skipping `Blob` children avoids spillover-stutter (previously-
///   migrated children would otherwise get re-migrated into
///   wrapper blobs without freeing any actual data).
/// - Choosing a subtree close to the target child fill ratio avoids
///   creating child blobs that are immediately full, which is what
///   turns path-shaped 2M+ put workloads into repeated blob hops.
/// - Among healthy fill-ratio candidates, prefer boundaries that
///   end on `/`. Object-store and filesystem keys are component-
///   shaped; cutting a child blob at a component boundary improves
///   top-route cache reuse and avoids long low-reuse prefix hops.
#[allow(clippy::too_many_lines)] // intentional — one match over NodeType arms
fn pick_victim_subtree(frame: &BlobFrame<'_>, start_slot: u16) -> Result<Victim> {
    let mut best: Option<VictimCandidate> = None;
    collect_victim_candidates(frame, start_slot, 0, &mut best)?;
    best.map(|candidate| candidate.victim)
        .ok_or(Error::NotYetImplemented(
            "spillover: no non-Blob subtree to migrate",
        ))
}

#[allow(clippy::too_many_lines)] // one match over NodeType arms
fn collect_victim_candidates(
    frame: &BlobFrame<'_>,
    current: u16,
    depth: usize,
    best: &mut Option<VictimCandidate>,
) -> Result<()> {
    let ntype = ntype_of(frame.as_ref(), current)?;
    match ntype {
        NodeType::Node4 => {
            let n = read_node4(frame.as_ref(), current)?;
            for i in 0..(n.count as usize).min(4) {
                let child_depth = depth + 1;
                visit_child_edge(
                    frame,
                    Victim {
                        parent_slot: current,
                        kind: VictimEdgeKind::Inner(NodeType::Node4),
                        byte: n.keys[i],
                        victim_slot: n.children[i] as u16,
                        via_header_root: false,
                    },
                    boundary_quality_for_byte(n.keys[i]),
                    child_depth,
                    best,
                )?;
            }
        }
        NodeType::Node16 => {
            let n = read_node16(frame.as_ref(), current)?;
            for i in 0..(n.count as usize).min(16) {
                let child_depth = depth + 1;
                visit_child_edge(
                    frame,
                    Victim {
                        parent_slot: current,
                        kind: VictimEdgeKind::Inner(NodeType::Node16),
                        byte: n.keys[i],
                        victim_slot: n.children[i] as u16,
                        via_header_root: false,
                    },
                    boundary_quality_for_byte(n.keys[i]),
                    child_depth,
                    best,
                )?;
            }
        }
        NodeType::Node48 => {
            let n = read_node48(frame.as_ref(), current)?;
            for b in 0..256usize {
                let idx = n.index[b];
                if idx == 0 {
                    continue;
                }
                let ci = idx as usize - 1;
                if ci >= 48 {
                    return Err(Error::node_corrupt(
                        "collect_victim_candidates: Node48 index out of range",
                    ));
                }
                let child_depth = depth + 1;
                visit_child_edge(
                    frame,
                    Victim {
                        parent_slot: current,
                        kind: VictimEdgeKind::Inner(NodeType::Node48),
                        byte: b as u8,
                        victim_slot: n.children[ci] as u16,
                        via_header_root: false,
                    },
                    boundary_quality_for_byte(b as u8),
                    child_depth,
                    best,
                )?;
            }
        }
        NodeType::Node256 => {
            let n = read_node256(frame.as_ref(), current)?;
            for (b, &child) in n.children.iter().enumerate() {
                if child == 0 {
                    continue;
                }
                let child_depth = depth + 1;
                visit_child_edge(
                    frame,
                    Victim {
                        parent_slot: current,
                        kind: VictimEdgeKind::Inner(NodeType::Node256),
                        byte: b as u8,
                        victim_slot: child as u16,
                        via_header_root: false,
                    },
                    boundary_quality_for_byte(b as u8),
                    child_depth,
                    best,
                )?;
            }
        }
        NodeType::Prefix => {
            let p = read_prefix(frame.as_ref(), current)?;
            let plen = p.prefix_len as usize;
            let prefix = &p.bytes[..plen.min(p.bytes.len())];
            let child_depth = depth + plen;
            visit_child_edge(
                frame,
                Victim {
                    parent_slot: current,
                    kind: VictimEdgeKind::Prefix,
                    byte: 0,
                    victim_slot: p.child as u16,
                    via_header_root: false,
                },
                boundary_quality_for_prefix(prefix),
                child_depth,
                best,
            )?;
        }
        NodeType::Leaf | NodeType::EmptyRoot | NodeType::Blob => {}
        NodeType::Invalid => {
            return Err(Error::node_corrupt("collect_victim_candidates: Invalid"));
        }
    }
    Ok(())
}

fn visit_child_edge(
    frame: &BlobFrame<'_>,
    victim: Victim,
    boundary: BoundaryQuality,
    boundary_depth: usize,
    best: &mut Option<VictimCandidate>,
) -> Result<()> {
    let child_ntype = ntype_of(frame.as_ref(), victim.victim_slot)?;
    match child_ntype {
        NodeType::Invalid => {
            return Err(Error::node_corrupt("visit_child_edge: Invalid child"));
        }
        NodeType::Blob => return Ok(()),
        _ => {}
    }

    let footprint = subtree_footprint(frame, victim.victim_slot)?;
    let candidate = VictimCandidate {
        victim,
        footprint,
        boundary,
        boundary_depth,
    };
    if best
        .as_ref()
        .is_none_or(|current| candidate_is_better(candidate, *current))
    {
        *best = Some(candidate);
    }
    if footprint.bytes > spillover_target_child_bytes() {
        collect_victim_candidates(frame, victim.victim_slot, boundary_depth, best)?;
    }
    Ok(())
}

fn boundary_quality_for_byte(byte: u8) -> BoundaryQuality {
    if byte == b'/' {
        BoundaryQuality::PathComponent
    } else {
        BoundaryQuality::Arbitrary
    }
}

fn boundary_quality_for_prefix(prefix: &[u8]) -> BoundaryQuality {
    prefix
        .last()
        .copied()
        .map_or(BoundaryQuality::Arbitrary, boundary_quality_for_byte)
}

fn candidate_is_better(candidate: VictimCandidate, current: VictimCandidate) -> bool {
    let c = candidate.footprint;
    let b = current.footprint;
    let target = spillover_target_child_bytes();
    let min = spillover_min_child_bytes();
    let c_in_band = c.bytes >= min && c.bytes <= target;
    let b_in_band = b.bytes >= min && b.bytes <= target;
    if c_in_band != b_in_band {
        return c_in_band;
    }
    if c_in_band {
        return candidate_tie_in_band(
            candidate,
            current,
            c.bytes.abs_diff(target),
            b.bytes.abs_diff(target),
        );
    }

    let c_below = c.bytes < min;
    let b_below = b.bytes < min;
    if c_below && b_below {
        return candidate_tie(candidate, current, b.bytes, c.bytes);
    }

    let c_over = c.bytes > target;
    let b_over = b.bytes > target;
    if c_over && b_over {
        return candidate_tie(candidate, current, c.bytes, b.bytes);
    }

    candidate_tie(
        candidate,
        current,
        c.bytes.abs_diff(target),
        b.bytes.abs_diff(target),
    )
}

fn candidate_tie_in_band(
    candidate: VictimCandidate,
    current: VictimCandidate,
    candidate_score: u32,
    current_score: u32,
) -> bool {
    if candidate.boundary != current.boundary {
        return candidate.boundary == BoundaryQuality::PathComponent;
    }
    candidate_tie(candidate, current, candidate_score, current_score)
}

fn candidate_tie(
    candidate: VictimCandidate,
    current: VictimCandidate,
    candidate_score: u32,
    current_score: u32,
) -> bool {
    if candidate_score != current_score {
        return candidate_score < current_score;
    }
    if candidate.boundary != current.boundary {
        return candidate.boundary == BoundaryQuality::PathComponent;
    }
    if candidate.boundary_depth != current.boundary_depth {
        return candidate.boundary_depth < current.boundary_depth;
    }
    candidate.footprint.nodes > current.footprint.nodes
}

/// Recursively free every slot of the subtree rooted at `root` in
/// `frame`. Used by spillover to reclaim source-side slot entries
/// after `make_blob_from_node` has copied them out.
pub(super) fn free_subtree(frame: &mut BlobFrame<'_>, root: u16) -> Result<()> {
    let ntype = ntype_of(frame.as_ref(), root)?;
    // Snapshot the body bytes before mutating the slot table so the
    // following `frame.free_node` calls can't invalidate them.
    let body_copy = frame
        .body_of_slot(root)
        .ok_or(Error::node_corrupt("free_subtree: body resolution failed"))?
        .to_vec();

    match ntype {
        NodeType::Invalid => {
            return Err(Error::node_corrupt("free_subtree: Invalid in source"));
        }
        NodeType::Leaf | NodeType::EmptyRoot | NodeType::Blob => {}
        NodeType::Prefix => {
            let p = cast::<Prefix>(&body_copy);
            free_subtree(frame, p.child as u16)?;
        }
        NodeType::Node4 => {
            let n = cast::<Node4>(&body_copy);
            for i in 0..(n.count as usize).min(4) {
                free_subtree(frame, n.children[i] as u16)?;
            }
        }
        NodeType::Node16 => {
            let n = cast::<Node16>(&body_copy);
            for i in 0..(n.count as usize).min(16) {
                free_subtree(frame, n.children[i] as u16)?;
            }
        }
        NodeType::Node48 => {
            let n = cast::<Node48>(&body_copy);
            for c in &n.children {
                if *c != 0 {
                    free_subtree(frame, *c as u16)?;
                }
            }
        }
        NodeType::Node256 => {
            let n = cast::<Node256>(&body_copy);
            for c in &n.children {
                if *c != 0 {
                    free_subtree(frame, *c as u16)?;
                }
            }
        }
    }

    frame.free_node(root)?;
    Ok(())
}

/// Produce a fresh 128-bit blob GUID with cross-process,
/// cross-restart uniqueness — UUIDv7-ish layout:
///
/// - **bytes 0..8** — `nanos_since_epoch` big-endian: time-orders
///   GUIDs for debug-friendly manifest dumps.
/// - **bytes 8..12** — per-process atomic counter big-endian:
///   resolves ties when many GUIDs are minted in the same
///   nanosecond.
/// - **bytes 12..15** — three random bytes from the OS entropy
///   source (`getrandom` on Linux, `getentropy` on the BSDs).
///   Closes the cross-process collision class "process A
///   crashes, process B starts on the same machine, OS reuses
///   pid, counter resets to 1 → identical GUID; new spillover
///   overwrites the crashed process's orphan blob in store".
/// - **byte 15** — magic tag `0xD4` so a fresh GUID can never
///   collide with `ROOT_BLOB_GUID = [0; 16]`.
///
/// Time-based prefix doesn't compromise privacy here: the GUID
/// lives inside an internal `manifest.bin` and never escapes the
/// process.
pub(super) fn fresh_blob_guid() -> BlobGuid {
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{SystemTime, UNIX_EPOCH};
    static COUNTER: AtomicU64 = AtomicU64::new(1);

    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_nanos() as u64);
    let c = COUNTER.fetch_add(1, Ordering::Relaxed) as u32;

    let mut tail = [0u8; 3];
    if !fill_os_entropy(&mut tail) {
        // Fallback: derive from nanos + counter via a 64-bit
        // mixer. Deterministic-but-non-colliding even under
        // sandbox restrictions that block `getrandom`/
        // `getentropy`. Time prefix still dominates uniqueness
        // across restarts, so this only ever weakens the
        // intra-tick tiebreaker.
        let m = nanos.wrapping_mul(0x9E37_79B9_7F4A_7C15) ^ u64::from(c);
        tail[0] = (m >> 16) as u8;
        tail[1] = (m >> 24) as u8;
        tail[2] = (m >> 32) as u8;
    }

    let mut g = [0u8; 16];
    g[0..8].copy_from_slice(&nanos.to_be_bytes());
    g[8..12].copy_from_slice(&c.to_be_bytes());
    g[12] = tail[0];
    g[13] = tail[1];
    g[14] = tail[2];
    g[15] = 0xD4; // tag — see fn doc
    g
}

/// Best-effort OS entropy read. Returns `true` on full fill.
///
/// holt is Unix-only (see project memory). Linux uses
/// `getrandom(2)`; the BSD family (macOS, FreeBSD, OpenBSD,
/// NetBSD) uses `getentropy(2)`. Both syscalls are blocking and
/// return cryptographically-strong bytes; we don't need crypto
/// strength here, only "different between processes / restarts".
fn fill_os_entropy(buf: &mut [u8]) -> bool {
    #[cfg(target_os = "linux")]
    unsafe {
        let r = libc::getrandom(buf.as_mut_ptr().cast(), buf.len(), 0);
        r >= 0 && (r as usize) == buf.len()
    }
    #[cfg(any(
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd"
    ))]
    unsafe {
        // `getentropy` max is 256 bytes per call; our 3-byte read
        // is comfortably under.
        libc::getentropy(buf.as_mut_ptr().cast(), buf.len()) == 0
    }
    #[cfg(not(any(
        target_os = "linux",
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd"
    )))]
    {
        let _ = buf;
        false
    }
}

#[cfg(test)]
mod tests {
    use super::super::insert::insert;
    use super::*;
    use crate::layout::PAGE_SIZE;
    use crate::store::BlobFrame;

    fn candidate(bytes: u32, nodes: u32) -> VictimCandidate {
        candidate_with_boundary(bytes, nodes, BoundaryQuality::Arbitrary, 16)
    }

    fn path_candidate(bytes: u32, nodes: u32) -> VictimCandidate {
        candidate_with_boundary(bytes, nodes, BoundaryQuality::PathComponent, 16)
    }

    fn candidate_with_boundary(
        bytes: u32,
        nodes: u32,
        boundary: BoundaryQuality,
        boundary_depth: usize,
    ) -> VictimCandidate {
        VictimCandidate {
            victim: Victim {
                parent_slot: 0,
                kind: VictimEdgeKind::Prefix,
                byte: 0,
                victim_slot: 0,
                via_header_root: false,
            },
            footprint: SubtreeFootprint { nodes, bytes },
            boundary,
            boundary_depth,
        }
    }

    #[test]
    fn spillover_scoring_prefers_target_band_over_largest() {
        let target = spillover_target_child_bytes();
        assert!(candidate_is_better(
            candidate(target - 1024, 10),
            candidate(target + 80_000, 100),
        ));
        assert!(!candidate_is_better(
            candidate(target + 80_000, 100),
            candidate(target - 1024, 10),
        ));
    }

    #[test]
    fn spillover_scoring_avoids_tiny_and_overfull_children() {
        let min = spillover_min_child_bytes();
        let target = spillover_target_child_bytes();

        assert!(candidate_is_better(
            candidate(min - 1024, 20),
            candidate(min / 2, 100),
        ));
        assert!(candidate_is_better(
            candidate(target + 1024, 20),
            candidate(target + 90_000, 100),
        ));
    }

    #[test]
    fn spillover_scoring_uses_node_count_only_as_tie_breaker() {
        let target = spillover_target_child_bytes();
        assert!(candidate_is_better(
            candidate(target - 4096, 20),
            candidate(target - 4096, 10),
        ));
    }

    #[test]
    fn spillover_scoring_prefers_path_boundary_within_target_band() {
        let target = spillover_target_child_bytes();
        assert!(candidate_is_better(
            path_candidate(target - 32_000, 10),
            candidate(target - 1024, 100),
        ));
    }

    #[test]
    fn spillover_scoring_keeps_fill_band_before_path_boundary() {
        let min = spillover_min_child_bytes();
        let target = spillover_target_child_bytes();
        assert!(candidate_is_better(
            candidate(target - 1024, 10),
            path_candidate(min - 1024, 100),
        ));
    }

    fn put(frame: &mut BlobFrame<'_>, key: &[u8], value: &[u8], seq: u64) {
        let root = frame.header().root_slot;
        insert(frame, root, key, value, seq).unwrap();
    }

    #[test]
    fn victim_search_descends_into_overfull_path_branch() {
        let mut buf = vec![0u8; PAGE_SIZE as usize];
        BlobFrame::init(&mut buf, [0x31; 16]).unwrap();
        let mut frame = BlobFrame::wrap(&mut buf);
        let value = vec![0x5A; 1024];

        let mut seq = 1u64;
        for i in 0..240u32 {
            let key = format!("a/x/file-{i:06}").into_bytes();
            put(&mut frame, &key, &value, seq);
            seq += 1;
        }
        for i in 0..120u32 {
            let key = format!("a/y/file-{i:06}").into_bytes();
            put(&mut frame, &key, &value, seq);
            seq += 1;
        }
        put(&mut frame, b"b/tiny", b"v", seq);

        let victim = pick_victim_subtree(&frame, frame.header().root_slot).unwrap();
        let footprint = subtree_footprint(&frame, victim.victim_slot).unwrap();

        assert!(
            footprint.bytes >= spillover_min_child_bytes(),
            "victim too small: {footprint:?}",
        );
        assert!(
            footprint.bytes <= spillover_target_child_bytes(),
            "victim should be a nested in-band branch, not the overfull direct branch: {footprint:?}",
        );
        assert_eq!(victim.byte, b'x');
    }
}