holt 0.3.3

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
//! Background checkpointer — three threads coordinating
//! through a bounded I/O queue + per-thread stop signals.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────────────────────────────────────────────────┐
//! │ checkpoint_thread (planner / orchestrator)               │
//! │   park_timeout(idle_interval)                            │
//! │     ├─ run_merge_pass                                    │
//! │     ├─ snapshot_dirty + journal.flush                    │
//! │     ├─ submit one CheckpointEpoch                        │
//! │     ├─ reap completed epochs in FIFO order               │
//! │     └─ journal.truncate iff pipeline empty + clean BM     │
//! └────────┬─────────────────────────────────────────────────┘
//!          │ IoTask (bounded crossbeam channel)
//!//! ┌──────────────────────────────────────────────────────────┐
//! │ io_thread (I/O executor)                                 │
//! │   recv IoTask -> write batch / sync / pending deletes     │
//! │                                                          │
//! │   ── Unix:  pread/pwritev through FileBlobStore           │
//! │   ── Linux: io_uring fixed-file/fixed-buffer fast path   │
//! └──────────────────────────────────────────────────────────┘
//!
//! ┌──────────────────────────────────────────────────────────┐
//! │ eviction_thread (independent cadence)                    │
//! │   park_timeout(eviction_interval)                        │
//! │     scan cache, drop cold non-dirty entries              │
//! │     using BufferManager::clock_tick + last_touched       │
//! └──────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Industrial references
//!
//! Mirrors the FractalBit ancestor's three-thread structure
//! (`checkpoint_thread` / `bss_io_thread` / `eviction_thread`).
//! The split-by-responsibility pattern also lines up with:
//!
//! - **sled** (`Flusher` thread) — `Arc<AtomicBool>` shutdown
//!   flag, parked between rounds.
//! - **fjall** (`FlushManager` + queue) — bounded queue between
//!   planner and I/O executor; never trim the journal until the
//!   corresponding flush succeeds.
//! - **LeanStore** — round-driven dirty-set drain on the planner
//!   thread.
//!
//! Three threads (rather than a single one) buy:
//!
//! 1. **Writers don't sit behind checkpoint I/O** — the planner
//!    snapshots dirty state, flushes WAL, clones bytes, then releases
//!    the commit gate while epoch I/O continues in the worker.
//! 2. **io_uring fit** — the I/O thread is the natural home for
//!    the SQE submit + CQE poll loop on the Linux fast path.
//! 3. **Eviction is decoupled** — runs on its own cadence
//!    against its own clock; doesn't compete with the planner
//!    for BM mutex time.
//!
//! ## Shutdown
//!
//! `Checkpointer::Drop`:
//!
//! 1. Set `checkpoint_stop`; unpark + join the planner thread so
//!    no new rounds start.
//! 2. Run one final synchronous round on the calling thread
//!    (still uses the I/O queue). Closes the window between the
//!    planner's last round and the Tree handle's drop — writes
//!    that landed in that window are otherwise lost when the
//!    BM/journal `Arc`s drop.
//! 3. Send `IoTask::Stop`; join the I/O thread.
//! 4. Set `eviction_stop`; unpark + join the eviction thread.

mod eviction;
mod io;
mod round;

use crossbeam_channel::{bounded, Sender};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;

use std::thread::{self, JoinHandle};
use std::time::Duration;

use crate::concurrency::{CommitGate, MaintenanceGate};
use crate::journal::group_commit::Journal;
use crate::store::BufferManager;

use self::io::IoTask;

// ---------- public config ----------

/// Background checkpointer policy + cadence.
///
/// The defaults enable the background thread group so file-backed
/// trees bound WAL growth and drain dirty blobs without requiring
/// callers to schedule [`crate::Tree::checkpoint`] manually.
#[derive(Debug, Clone)]
pub struct CheckpointConfig {
    /// Master switch. `true` (the default) spawns the planner, I/O,
    /// and eviction threads on tree open and stops them on tree drop.
    /// Set to `false` when callers want fully manual checkpointing
    /// through [`crate::Tree::checkpoint`].
    pub enabled: bool,
    /// Maximum interval between planner rounds. Smaller values
    /// = lower checkpoint latency, more wake-ups per second.
    ///
    /// Default 500 ms. The background checkpointer stays active
    /// by default, but avoids chasing every short write burst.
    pub idle_interval: Duration,
    /// Trigger an early round when the BufferManager's dirty
    /// blob count reaches this. Heuristic for "the dirty set is
    /// large enough that the next round is worth running before
    /// `idle_interval` elapses".
    ///
    /// Default 512. This bounds dirty growth without forcing an
    /// early checkpoint for a handful of hot blobs.
    pub dirty_blob_threshold: usize,
    /// Drain queued parent-merge candidates at the start of each
    /// round. The queue is populated by foreground spillovers and
    /// manual maintenance seeding, so idle rounds avoid walking
    /// every reachable blob just to rediscover that nothing can
    /// merge.
    ///
    /// Default `true` — keeping the blob tree in equilibrium
    /// against split/merge pressure is the whole point.
    pub auto_merge: bool,
    /// How often the eviction thread scans the cache.
    /// Default 1 s.
    pub eviction_interval: Duration,
    /// "Idle tick" threshold for the eviction thread. An entry
    /// whose `last_touched` lags the current BM clock by more
    /// than this is considered cold and evicted (unless dirty).
    ///
    /// Default 1024 — roughly "untouched for the last ~1024
    /// `pin`/`get_cached` operations".
    pub eviction_idle_ticks: u64,
    /// Bounded I/O queue capacity (depth of checkpoint I/O tasks
    /// in flight between the planner and the I/O thread).
    /// Bigger = more parallelism head-room for io_uring; smaller
    /// = tighter back-pressure on the planner.
    ///
    /// Default 16.
    pub io_queue_capacity: usize,
}

impl Default for CheckpointConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            idle_interval: Duration::from_millis(500),
            dirty_blob_threshold: 512,
            auto_merge: true,
            eviction_interval: Duration::from_secs(1),
            eviction_idle_ticks: 1024,
            io_queue_capacity: 16,
        }
    }
}

impl CheckpointConfig {
    /// Convenience constructor: enabled with default cadence.
    #[must_use]
    pub fn enabled() -> Self {
        Self::default()
    }
}

// ---------- internal shared state ----------

pub(super) struct Shared {
    pub(super) bm: Arc<BufferManager>,
    pub(super) journal: Option<Arc<Journal>>,
    /// Same writer-shared / checkpoint-exclusive publish barrier
    /// used by foreground persistent writers. Checkpoint rounds
    /// hold its exclusive side while draining dirty entries and
    /// cloning bytes so store writes never include unjournaled
    /// mutations.
    pub(super) commit_gate: Arc<CommitGate>,
    /// Shared structural gate with `Tree`: the merge pass enters
    /// the exclusive side so it cannot fold/delete a child blob
    /// while a foreground writer is lock-coupling through that
    /// edge.
    pub(super) maintenance_gate: Arc<MaintenanceGate>,
    pub(super) cfg: CheckpointConfig,

    /// Submit side of the bounded I/O queue. Cloned by the planner
    /// thread; the receiver lives inside `io::run`.
    pub(super) io_tx: Sender<IoTask>,

    // Per-thread stop signals (independent so Drop can stop them
    // in the right order without racing the queue).
    pub(super) checkpoint_stop: AtomicBool,
    pub(super) eviction_stop: AtomicBool,

    // Telemetry — written by the threads, read by `Checkpointer`
    // accessors.
    pub(super) rounds_attempted: AtomicU64,
    pub(super) rounds_succeeded: AtomicU64,
    pub(super) blobs_flushed: AtomicU64,
    pub(super) merges_total: AtomicU64,
    pub(super) truncates: AtomicU64,
    pub(super) evictions: AtomicU64,
    pub(super) last_dirty_count: AtomicUsize,
}

// ---------- handle ----------

/// Three-thread checkpointer handle. Dropping the handle signals
/// shutdown and joins all three threads in the documented order.
pub(crate) struct Checkpointer {
    shared: Arc<Shared>,
    checkpoint_handle: Option<JoinHandle<()>>,
    io_handle: Option<JoinHandle<()>>,
    eviction_handle: Option<JoinHandle<()>>,
}

impl Checkpointer {
    /// Spawn the three checkpointer threads bound to `bm` +
    /// optional journal. Returns `None` if `cfg.enabled == false` —
    /// the caller (typically `Tree::open_inner`) falls back to
    /// synchronous checkpointing in that case.
    #[must_use]
    pub(crate) fn spawn(
        bm: Arc<BufferManager>,
        journal: Option<Arc<Journal>>,
        maintenance_gate: Arc<MaintenanceGate>,
        commit_gate: Arc<CommitGate>,
        cfg: CheckpointConfig,
    ) -> Option<Self> {
        if !cfg.enabled {
            return None;
        }
        let (io_tx, io_rx) = bounded::<IoTask>(cfg.io_queue_capacity.max(1));
        let shared = Arc::new(Shared {
            bm,
            journal,
            commit_gate,
            maintenance_gate,
            cfg,
            io_tx,
            checkpoint_stop: AtomicBool::new(false),
            eviction_stop: AtomicBool::new(false),
            rounds_attempted: AtomicU64::new(0),
            rounds_succeeded: AtomicU64::new(0),
            blobs_flushed: AtomicU64::new(0),
            merges_total: AtomicU64::new(0),
            truncates: AtomicU64::new(0),
            evictions: AtomicU64::new(0),
            last_dirty_count: AtomicUsize::new(0),
        });

        let io_handle = {
            let s = Arc::clone(&shared);
            thread::Builder::new()
                .name("holt-ckpt-io".to_owned())
                .spawn(move || io::run(&s, io_rx))
                .expect("OS rejected thread spawn for holt-ckpt-io")
        };
        let checkpoint_handle = {
            let s = Arc::clone(&shared);
            thread::Builder::new()
                .name("holt-ckpt-planner".to_owned())
                .spawn(move || checkpoint_main(&s))
                .expect("OS rejected thread spawn for holt-ckpt-planner")
        };
        let eviction_handle = {
            let s = Arc::clone(&shared);
            thread::Builder::new()
                .name("holt-ckpt-eviction".to_owned())
                .spawn(move || eviction::run(&s))
                .expect("OS rejected thread spawn for holt-ckpt-eviction")
        };

        Some(Self {
            shared,
            checkpoint_handle: Some(checkpoint_handle),
            io_handle: Some(io_handle),
            eviction_handle: Some(eviction_handle),
        })
    }

    /// Unpark the planner so it runs a round at the next park
    /// boundary (without waiting out the remainder of
    /// `idle_interval`). Safe to call from any thread; no-op if
    /// the planner is already running.
    ///
    /// Test hook for waking the planner without waiting out the
    /// remainder of `idle_interval`.
    #[cfg(test)]
    pub(crate) fn wake(&self) {
        if let Some(h) = &self.checkpoint_handle {
            h.thread().unpark();
        }
    }

    /// Number of rounds the planner has attempted.
    #[must_use]
    pub(crate) fn rounds_attempted(&self) -> u64 {
        self.shared.rounds_attempted.load(Ordering::Relaxed)
    }

    /// Number of rounds that completed without error.
    #[must_use]
    pub(crate) fn rounds_succeeded(&self) -> u64 {
        self.shared.rounds_succeeded.load(Ordering::Relaxed)
    }

    /// Total blobs flushed across all rounds.
    #[must_use]
    pub(crate) fn blobs_flushed(&self) -> u64 {
        self.shared.blobs_flushed.load(Ordering::Relaxed)
    }

    /// WAL truncates performed across all rounds.
    #[must_use]
    pub(crate) fn truncates(&self) -> u64 {
        self.shared.truncates.load(Ordering::Relaxed)
    }

    /// `BlobNode` crossings folded back into parents.
    #[must_use]
    pub(crate) fn merges_total(&self) -> u64 {
        self.shared.merges_total.load(Ordering::Relaxed)
    }

    /// Cache entries evicted by the eviction thread.
    #[must_use]
    pub(crate) fn evictions(&self) -> u64 {
        self.shared.evictions.load(Ordering::Relaxed)
    }
}

impl Drop for Checkpointer {
    fn drop(&mut self) {
        // 1. Stop the planner so no new rounds start.
        self.shared.checkpoint_stop.store(true, Ordering::SeqCst);
        if let Some(h) = self.checkpoint_handle.take() {
            h.thread().unpark();
            let _ = h.join();
        }

        // 2. Run one final synchronous round on this thread.
        //    The planner is joined, writers are gone (last Tree
        //    clone is dropping). I/O thread is still alive
        //    serving the round's submissions.
        if let Err(e) = round::run_round_sync(&self.shared) {
            eprintln!("holt: final checkpoint round during shutdown failed: {e}");
        }

        // 3. Stop the I/O thread.
        let _ = self.shared.io_tx.send(IoTask::Stop);
        if let Some(h) = self.io_handle.take() {
            let _ = h.join();
        }

        // 4. Stop the eviction thread.
        self.shared.eviction_stop.store(true, Ordering::SeqCst);
        if let Some(h) = self.eviction_handle.take() {
            h.thread().unpark();
            let _ = h.join();
        }
    }
}

// ---------- checkpoint_thread main loop ----------

fn checkpoint_main(shared: &Arc<Shared>) {
    let mut pipeline = round::Pipeline::new(shared.cfg.io_queue_capacity);
    loop {
        if shared.checkpoint_stop.load(Ordering::Acquire) {
            break;
        }
        if let Err(e) = pipeline.reap_ready(shared) {
            eprintln!("holt: checkpoint epoch failed: {e}");
        }
        let has_pressure = shared.bm.dirty_count() >= shared.cfg.dirty_blob_threshold.max(1)
            || shared.bm.pending_delete_count() != 0;
        if !has_pressure {
            if !pipeline.is_empty() {
                thread::park_timeout(shared.cfg.idle_interval.min(Duration::from_millis(1)));
                continue;
            }
            thread::park_timeout(shared.cfg.idle_interval);
        }
        if shared.checkpoint_stop.load(Ordering::Acquire) {
            break;
        }
        loop {
            if let Err(e) = round::run_round(shared, &mut pipeline) {
                // Round failed; restored dirty entries (where
                // applicable) are still in the map for the next try.
                eprintln!("holt: checkpoint round failed: {e}");
                break;
            }
            if !pipeline.has_room()
                || shared.bm.dirty_count() < shared.cfg.dirty_blob_threshold.max(1)
                || shared.checkpoint_stop.load(Ordering::Acquire)
            {
                break;
            }
        }
    }
    if let Err(e) = pipeline.drain(shared) {
        eprintln!("holt: checkpoint pipeline drain during shutdown failed: {e}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api::errors::Result;
    use crate::layout::BlobGuid;
    use crate::store::blob_store::{AlignedBlobBuf, BlobStore, MemoryBlobStore};
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};
    use std::time::Instant;

    fn make_bm() -> Arc<BufferManager> {
        Arc::new(BufferManager::new(Arc::new(MemoryBlobStore::new()), 8))
    }

    fn maintenance_gate() -> Arc<MaintenanceGate> {
        Arc::new(MaintenanceGate::new())
    }

    fn commit_gate() -> Arc<CommitGate> {
        Arc::new(CommitGate::new())
    }

    struct BlockingBatchStore {
        inner: MemoryBlobStore,
        release: AtomicBool,
        started: AtomicUsize,
    }

    impl BlockingBatchStore {
        fn new() -> Self {
            Self {
                inner: MemoryBlobStore::new(),
                release: AtomicBool::new(false),
                started: AtomicUsize::new(0),
            }
        }

        fn release(&self) {
            self.release.store(true, AtomicOrdering::Release);
        }

        fn started(&self) -> usize {
            self.started.load(AtomicOrdering::Acquire)
        }
    }

    impl BlobStore for BlockingBatchStore {
        fn read_blob(&self, guid: BlobGuid, dst: &mut AlignedBlobBuf) -> Result<()> {
            self.inner.read_blob(guid, dst)
        }

        fn write_blob(&self, guid: BlobGuid, src: &AlignedBlobBuf) -> Result<()> {
            self.inner.write_blob(guid, src)
        }

        fn write_blobs_with_data_sync(&self, writes: &[(BlobGuid, &AlignedBlobBuf)]) -> Result<()> {
            if !writes.is_empty() {
                self.started.fetch_add(1, AtomicOrdering::AcqRel);
                while !self.release.load(AtomicOrdering::Acquire) {
                    thread::sleep(Duration::from_millis(1));
                }
            }
            self.inner.write_blobs_with_data_sync(writes)
        }

        fn delete_blob(&self, guid: BlobGuid) -> Result<()> {
            self.inner.delete_blob(guid)
        }

        fn list_blobs(&self) -> Result<Vec<BlobGuid>> {
            self.inner.list_blobs()
        }

        fn flush(&self) -> Result<()> {
            self.inner.flush()
        }

        fn needs_flush(&self) -> bool {
            self.inner.needs_flush()
        }
    }

    /// Tests that don't construct a real Tree skip the merge pass —
    /// `collect_blob_guids` would otherwise try to pin a
    /// non-existent root.
    fn no_merge_cfg() -> CheckpointConfig {
        CheckpointConfig {
            auto_merge: false,
            ..CheckpointConfig::enabled()
        }
    }

    #[test]
    fn disabled_config_spawns_nothing() {
        let bm = make_bm();
        let cfg = CheckpointConfig {
            enabled: false,
            ..CheckpointConfig::default()
        };
        assert!(!cfg.enabled);
        let ck = Checkpointer::spawn(bm, None, maintenance_gate(), commit_gate(), cfg);
        assert!(ck.is_none());
    }

    #[test]
    fn spawn_and_drop_is_leak_free() {
        let bm = make_bm();
        let ck = Checkpointer::spawn(bm, None, maintenance_gate(), commit_gate(), no_merge_cfg())
            .expect("spawn");
        // Give threads a tick to actually park.
        thread::sleep(Duration::from_millis(50));
        drop(ck);
        // If shutdown deadlocked, this test would hang on the test
        // harness's per-test timeout.
    }

    #[test]
    fn round_drains_dirty_set_via_io_queue() {
        let bm = make_bm();
        // Prime a cached entry so snapshot_bytes returns Some.
        let mut scratch = crate::store::blob_store::AlignedBlobBuf::zeroed();
        scratch.as_mut_slice()[100] = 0xAB;
        bm.write_blob([0x42; 16], &scratch).unwrap();
        let _pin = bm.pin([0x42; 16]).unwrap();
        bm.mark_dirty([0x42; 16], 10);
        assert_eq!(bm.dirty_count(), 1);

        let ck = Checkpointer::spawn(
            Arc::clone(&bm),
            None,
            maintenance_gate(),
            commit_gate(),
            no_merge_cfg(),
        )
        .expect("spawn");
        // Wait for at least one round to drain the dirty set.
        let deadline = Instant::now() + Duration::from_secs(2);
        loop {
            if bm.dirty_count() == 0 && ck.blobs_flushed() >= 1 {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "checkpoint round didn't drain dirty in time"
            );
            thread::sleep(Duration::from_millis(10));
        }
        drop(ck);
    }

    #[test]
    fn wake_short_circuits_idle_wait() {
        let bm = make_bm();
        let mut cfg = no_merge_cfg();
        cfg.idle_interval = Duration::from_secs(10);
        let ck = Checkpointer::spawn(
            Arc::clone(&bm),
            None,
            maintenance_gate(),
            commit_gate(),
            cfg,
        )
        .expect("spawn");

        // Need a cached blob so snapshot_bytes finds it.
        let scratch = crate::store::blob_store::AlignedBlobBuf::zeroed();
        bm.write_blob([0x01; 16], &scratch).unwrap();
        let _pin = bm.pin([0x01; 16]).unwrap();
        bm.mark_dirty([0x01; 16], 1);
        ck.wake();

        let deadline = Instant::now() + Duration::from_secs(2);
        loop {
            if ck.rounds_succeeded() >= 1 && bm.dirty_count() == 0 {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "checkpointer never drained dirty set after wake"
            );
            thread::sleep(Duration::from_millis(5));
        }
    }

    #[test]
    fn planner_queues_second_epoch_while_first_io_is_blocked() {
        let store = Arc::new(BlockingBatchStore::new());
        let bm = Arc::new(BufferManager::new(store.clone(), 8));
        let scratch = crate::store::blob_store::AlignedBlobBuf::zeroed();
        bm.write_blob([0x21; 16], &scratch).unwrap();
        bm.write_blob([0x22; 16], &scratch).unwrap();
        let _pin1 = bm.pin([0x21; 16]).unwrap();
        let _pin2 = bm.pin([0x22; 16]).unwrap();
        bm.mark_dirty([0x21; 16], 1);

        let mut cfg = no_merge_cfg();
        cfg.idle_interval = Duration::from_millis(10);
        cfg.dirty_blob_threshold = 1;
        cfg.io_queue_capacity = 2;
        let ck = Checkpointer::spawn(
            Arc::clone(&bm),
            None,
            maintenance_gate(),
            commit_gate(),
            cfg,
        )
        .expect("spawn");

        let deadline = Instant::now() + Duration::from_secs(2);
        while store.started() == 0 {
            assert!(
                Instant::now() < deadline,
                "first checkpoint epoch never entered store write"
            );
            thread::sleep(Duration::from_millis(5));
        }

        bm.mark_dirty([0x22; 16], 2);
        ck.wake();

        let mut queued_second = false;
        let deadline = Instant::now() + Duration::from_secs(2);
        while Instant::now() < deadline {
            if ck.rounds_attempted() >= 2 {
                queued_second = true;
                break;
            }
            thread::sleep(Duration::from_millis(5));
        }
        store.release();
        assert!(
            queued_second,
            "planner did not submit a second epoch while first I/O was blocked"
        );

        let deadline = Instant::now() + Duration::from_secs(2);
        loop {
            if bm.dirty_count() == 0 && ck.blobs_flushed() >= 2 {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "queued checkpoint epochs did not drain"
            );
            thread::sleep(Duration::from_millis(5));
        }
        drop(ck);
    }

    #[test]
    fn eviction_thread_drops_cold_entries_only_under_capacity_pressure() {
        let bm = Arc::new(BufferManager::new(Arc::new(MemoryBlobStore::new()), 1));
        // Prime two cached entries and let the first go cold. With
        // capacity=1, exactly one cold entry may be evicted.
        let scratch = crate::store::blob_store::AlignedBlobBuf::zeroed();
        bm.write_blob([0xEE; 16], &scratch).unwrap();
        let cold = bm.pin([0xEE; 16]).unwrap();
        bm.write_blob([0xEF; 16], &scratch).unwrap();
        let _hot = bm.pin([0xEF; 16]).unwrap();
        // Drop the pin so try_evict_cold sees strong_count == 1.
        drop(cold);
        assert_eq!(bm.cached_count(), 2);

        // Bump the clock past the eviction threshold by hitting
        // get_cached for some other GUID a bunch of times.
        for _ in 0..5 {
            let _ = bm.pin([0xFF; 16]); // doesn't exist; just a tick advance
            let _ = bm.cached_count();
        }

        let cfg = CheckpointConfig {
            // Aggressive eviction for this test.
            eviction_interval: Duration::from_millis(20),
            eviction_idle_ticks: 1, // immediately stale after one tick advance
            ..no_merge_cfg()
        };
        let ck = Checkpointer::spawn(
            Arc::clone(&bm),
            None,
            maintenance_gate(),
            commit_gate(),
            cfg,
        )
        .expect("spawn");

        let deadline = Instant::now() + Duration::from_secs(2);
        loop {
            if ck.evictions() >= 1 {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "eviction thread didn't drop a cold entry in time"
            );
            thread::sleep(Duration::from_millis(20));
        }
        drop(ck);
    }

    #[test]
    fn eviction_thread_keeps_cold_entries_when_cache_fits() {
        let bm = make_bm();
        let scratch = crate::store::blob_store::AlignedBlobBuf::zeroed();
        bm.write_blob([0xEE; 16], &scratch).unwrap();
        let _ = bm.pin([0xEE; 16]).unwrap();
        assert_eq!(bm.cached_count(), 1);

        for _ in 0..5 {
            let _ = bm.pin([0xFF; 16]);
            let _ = bm.cached_count();
        }

        let cfg = CheckpointConfig {
            eviction_interval: Duration::from_millis(20),
            eviction_idle_ticks: 1,
            ..no_merge_cfg()
        };
        let ck = Checkpointer::spawn(
            Arc::clone(&bm),
            None,
            maintenance_gate(),
            commit_gate(),
            cfg,
        )
        .expect("spawn");

        thread::sleep(Duration::from_millis(120));
        assert_eq!(ck.evictions(), 0);
        assert_eq!(bm.cached_count(), 1);
        drop(ck);
    }
}