edgestore 1.0.1

Local-first embedded KV + vector database in Rust
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
/// Integration tests for Phase 3 success criteria — deathtime-cohort compaction.
///
/// Each test targets one of the five Phase 3 success criteria:
///   SC1 (COMPACT-04): TTL expiry → compact → live_records_relocated == 0
///   SC2 (COMPACT-05): Range scan merges 3+ overlapping segments with LWW
///   SC3 (COMPACT-06): Snapshot pins survive compaction; pins released on drop
///   SC4 (COMPACT-04): compaction_write_budget_bytes stops mid-cycle
///   SC5 (COMPACT-07): merkle_root on output segment matches recomputed value

use std::collections::HashSet;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use edgestore::compactor::Compactor;
use edgestore::manifest::Manifest;
use edgestore::segment::SegmentReader;
use edgestore::{CompactionStats, EdgestoreConfig, Engine};
use tempfile::TempDir;

// ── Helper ─────────────────────────────────────────────────────────────────

fn open_engine_small_segments(dir: &TempDir) -> Engine {
    let mut cfg = EdgestoreConfig::new(dir.path());
    // Very small threshold so memtable flushes after just a few keys
    cfg.segment_size_bytes = 512;
    Engine::open(cfg).unwrap()
}

fn now_nanos() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as i64
}

fn open_manifest(dir: &TempDir) -> Manifest {
    Manifest::open(&dir.path().join("manifest.mf")).unwrap()
}

// ── SC1: TTL expiry → compact → zero live relocation ───────────────────────

/// Success Criterion 1 (COMPACT-04): Records written with TTL=1 expire after 1 second.
/// After expiry, compact_once must produce live_records_relocated == 0 and remove segments.
///
/// Strategy: use Engine::compact_once() with TTL=1s and sleep(2s) so wall-clock passes.
/// Also set segment_size_bytes small to force flush during the put loop.
#[test]
fn test_ttl_expiry_zero_live_relocation() {
    let dir = TempDir::new().unwrap();
    let mut cfg = EdgestoreConfig::new(dir.path());
    cfg.segment_size_bytes = 512; // force frequent flushes
    cfg.compaction_write_budget_bytes = u64::MAX;
    let mut engine = Engine::open(cfg).unwrap();

    // Write 20 keys with TTL=1s — automatic flushes will occur due to small segment_size
    for i in 0u32..20 {
        engine
            .put_with_ttl(b"ns", format!("key-{:04}", i).as_bytes(), b"value", 1)
            .unwrap();
    }

    // Explicit flush of any remaining memtable entries (ignore error if empty)
    let _ = engine.flush_to_segments();

    // Sanity: some segments should exist
    let initial_segments = {
        let m = open_manifest(&dir);
        m.list_segments().len()
    };
    assert!(
        initial_segments >= 1,
        "expected at least 1 segment after writes, got {}",
        initial_segments
    );

    // Wait for TTL to expire
    std::thread::sleep(Duration::from_secs(2));

    // Run compaction via Engine (wall clock — records now expired)
    let stats = engine.compact_once().unwrap();

    // SC1 assertion: zero live records relocated (all records expired)
    assert_eq!(
        stats.live_records_relocated, 0,
        "COMPACT-04: all TTL=1s records should be dead after 2s sleep; live_records_relocated must be 0, got {}",
        stats.live_records_relocated
    );

    // Additional assertions
    assert!(
        stats.segments_removed >= 1,
        "at least 1 segment should be removed after compaction, got {}",
        stats.segments_removed
    );
    assert!(
        stats.cohorts_collected >= 1,
        "at least 1 cohort should be collected, got {}",
        stats.cohorts_collected
    );
}

// ── SC2: Range scan across 3+ overlapping segments with LWW ────────────────

/// Success Criterion 2 (COMPACT-05): Writes across 3+ segments with a shared key
/// produce correct LWW-merged result from range().
///
/// Strategy:
///   1. Write "overlap_key" = "v1_old", flush (segment A)
///   2. Write many unique keys to force more flushes (segments B, C)
///   3. Write "overlap_key" = "v1_new" (in memtable or next segment)
///   4. Flush remaining memtable
///   5. range() must return "v1_new" for "overlap_key" (latest LSN wins)
#[test]
fn test_range_scan_overlapping_segments() {
    let dir = TempDir::new().unwrap();
    let mut engine = open_engine_small_segments(&dir);

    // Write the overlap key first (will be in an early segment)
    engine
        .put(b"ns", b"overlap_key", b"v1_old")
        .unwrap();

    // Flush to ensure this is in its own segment before the overwrite (ignore if empty)
    let _ = engine.flush_to_segments();

    // Write enough unique keys to produce additional segments
    for i in 0u32..60 {
        engine
            .put(b"ns", format!("unique-{:04}", i).as_bytes(), b"unique_val")
            .unwrap();
    }

    // Write the overlap key again with new value (newer LSN)
    engine
        .put(b"ns", b"overlap_key", b"v1_new")
        .unwrap();

    // Flush any remaining memtable (ignore error if empty)
    let _ = engine.flush_to_segments();

    // Verify we have multiple segments
    let seg_count = {
        let m = open_manifest(&dir);
        m.list_segments().len()
    };
    assert!(
        seg_count >= 2,
        "expected at least 2 segments for LWW overlap test, got {}",
        seg_count
    );

    // Do a range scan that includes "overlap_key" and the unique keys
    let results = engine
        .range(b"ns", b"", b"\xFF\xFF\xFF\xFF")
        .unwrap();

    // Verify overlap_key maps to the latest value
    let overlap = results
        .iter()
        .find(|(k, _)| k == b"overlap_key");
    assert!(
        overlap.is_some(),
        "overlap_key should be present in range results"
    );
    let (_, val) = overlap.unwrap();
    assert_eq!(
        val, b"v1_new",
        "COMPACT-05: LWW must return newest value for overlap_key; got {:?}",
        String::from_utf8_lossy(val)
    );

    // Verify no duplicates — each key should appear exactly once
    let mut key_counts = std::collections::HashMap::new();
    for (k, _) in &results {
        *key_counts.entry(k.clone()).or_insert(0u32) += 1;
    }
    for (k, count) in &key_counts {
        assert_eq!(
            *count, 1,
            "key {:?} appears {} times in range results (expected 1 — no duplicates)",
            String::from_utf8_lossy(k),
            count
        );
    }

    // Verify results are sorted
    let keys: Vec<&[u8]> = results.iter().map(|(k, _)| k.as_slice()).collect();
    let mut sorted_keys = keys.clone();
    sorted_keys.sort();
    assert_eq!(keys, sorted_keys, "range results must be sorted by key");
}

// ── SC3: Snapshot survives compaction; drop releases pins ───────────────────

/// Success Criterion 3 (COMPACT-06): A snapshot taken before compaction pins
/// its segments. Compaction runs but the snapshot data remains readable.
/// After drop, the snapshot's segments can be collected.
///
/// Strategy:
///   1. Write keys with TTL=1, flush to segments
///   2. Take snapshot BEFORE compaction
///   3. Sleep 2s so TTL expires
///   4. Run compact_once() — pinned segments survive
///   5. Assert snapshot.get() still returns original values
///   6. Drop snapshot
///   7. Run compact_once() again — now pins are released, segments collectible
#[test]
fn test_snapshot_survives_compaction() {
    let dir = TempDir::new().unwrap();
    let mut cfg = EdgestoreConfig::new(dir.path());
    cfg.segment_size_bytes = 512;
    cfg.compaction_write_budget_bytes = u64::MAX;
    let mut engine = Engine::open(cfg).unwrap();

    // Write keys with TTL=1s
    for i in 0u32..15 {
        engine
            .put_with_ttl(b"ns", format!("snap-key-{:04}", i).as_bytes(), b"snap-val", 1)
            .unwrap();
    }

    // Flush memtable to segment (ignore error if empty)
    let _ = engine.flush_to_segments();

    // Verify we have at least 1 segment before snapshot
    let seg_count_before = {
        let m = open_manifest(&dir);
        m.list_segments().len()
    };
    assert!(
        seg_count_before >= 1,
        "need at least 1 segment before snapshot, got {}",
        seg_count_before
    );

    // Take snapshot BEFORE compaction (pins current segments)
    let snapshot = engine.snapshot().unwrap();

    // Verify snapshot sees the keys
    let before_val = snapshot.get(b"ns", b"snap-key-0000").unwrap();
    assert_eq!(
        before_val,
        Some(b"snap-val".to_vec()),
        "snapshot should see key before compaction"
    );

    // Wait for TTL to expire
    std::thread::sleep(Duration::from_secs(2));

    // Run compaction — expired records, but segments pinned by snapshot
    let stats_first = engine.compact_once().unwrap();

    // The snapshot pins prevent segment removal — compaction may skip them
    // OR some non-pinned segments are removed if they exist.
    // Key assertion: snapshot data is still readable after compaction.
    let after_val = snapshot.get(b"ns", b"snap-key-0000").unwrap();
    assert_eq!(
        after_val,
        Some(b"snap-val".to_vec()),
        "COMPACT-06: snapshot must remain readable after compaction; got {:?}",
        after_val.as_deref().map(String::from_utf8_lossy)
    );

    // Verify all snapshot keys are readable
    for i in 0u32..15 {
        let key = format!("snap-key-{:04}", i);
        let val = snapshot.get(b"ns", key.as_bytes()).unwrap();
        assert_eq!(
            val,
            Some(b"snap-val".to_vec()),
            "snapshot key {} should still be readable after compaction",
            key
        );
    }

    // Drop snapshot — releases all pins
    drop(snapshot);

    // After drop, compact again — now the previously-pinned segments are collectible
    let stats_second = engine.compact_once().unwrap();

    // After pins are released, segments should be collectable (or already removed)
    // The second compaction should succeed without errors
    // If segments were not removed in first pass (all pinned), they should be removed now
    let _ = stats_first; // first pass stats already verified above
    let _ = stats_second; // second pass just needs to not error
}

// ── SC4: Write budget enforced; compaction stops mid-cycle ──────────────────

/// Success Criterion 4 (COMPACT-04 bounded): compaction_write_budget_bytes = 0
/// causes the compaction loop to stop before processing any cohort that would
/// write bytes. Fully-expired cohorts write 0 bytes so may still be collected.
///
/// Strategy using Compactor directly for precise control:
///   1. Write records with TTL=0 (permanent, live records that would be relocated)
///   2. Flush to multiple segments in different cohorts
///   3. Use Compactor with write_budget_bytes=1 and now_nanos = far future
///      (all cohorts partially expired — they have live ttl=0 records but we set
///      now_nanos past death_time to simulate expiry, so all become fully-expired)
///
/// Simpler approach: use Engine::compact_once with compaction_write_budget_bytes=1
/// and write records that form partially-expired cohorts (mix of live + expired).
/// budget=1 stops after first output write attempt.
///
/// Note: The budget check in compact_cycle is: if bytes_written >= write_budget_bytes { break }
/// This check runs BEFORE each cohort. With budget=0, 0 >= 0 is true immediately, so
/// NO cohorts are processed. With budget=1, the first fully-expired cohort (0 bytes written)
/// passes, but a partial cohort that writes N>0 bytes would then trip 0+N >= 1 on next iteration.
///
/// Test design: create only partially-expired cohorts (with live records) so the compactor
/// would need to write bytes for each. With budget=1, after writing the first cohort's
/// output (bytes_written > 0), the next cohort's budget check trips.
/// But wait — budget check is BEFORE processing, not after. So:
///   - Iteration 0: bytes_written=0, budget=1: 0 >= 1 is FALSE → process cohort 0 → writes N bytes
///   - Iteration 1: bytes_written=N > 0 >= 1 is TRUE → break → cohort 1 not processed
///
/// With 3+ cohorts that each have live records, budget=1 should stop after cohort 0.
#[test]
fn test_compaction_write_budget_enforced() {
    let dir = TempDir::new().unwrap();

    // Use Compactor directly so we can control now_nanos precisely
    // Write segments with different cohort windows (different timestamps)
    let manifest_path = dir.path().join("manifest.mf");
    let mut manifest = Manifest::open(&manifest_path).unwrap();

    let cohort_window_secs: u64 = 3600;

    // Create 3 cohorts, each with 1 segment containing 5 live (ttl=0) records
    // Cohort 0: write_time in hour 0 (0 - 3599s)
    // Cohort 1: write_time in hour 1 (3600 - 7199s)
    // Cohort 2: write_time in hour 2 (7200 - 10799s)
    // All records have ttl=0 → death_time = write_time + cohort_window_secs nanos
    // We set now_nanos to be BEFORE all death_times → cohorts are partially expired
    // (not fully expired, since now_nanos < max_death_time)
    // Records with ttl=0 have death_time = write_time_nanos + 3600*1e9
    // Hour 0: write at 1s (nanos=1e9) → death_time = 1e9 + 3600e9 = 3601e9
    // With now_nanos = 3601e9 + 1 → hour 0 is fully expired too... so use:
    // now_nanos = 2e9 (2 seconds) → death_time of hour 0 = 3601e9 → not expired
    //
    // Actually for partially-expired cohorts that force bytes-written, we need:
    // - Some records alive (death_time > now_nanos) → survivors → bytes written
    // - Use ttl=0 records: death_time = write_time + 3600s
    // - write_time far in future to ensure alive: write_time_nanos = far future
    //
    // Simplest: write records with ttl=0 at current time → death_time = now + 3600s
    // All will be alive when compact runs. But is_fully_expired = false.
    // compact_partial_cohort will write survivors → bytes_written > 0.
    // With budget=1: first cohort writes, second cohort trips budget check.

    let now = now_nanos();

    for cohort_idx in 0u64..3 {
        let seg_id = cohort_idx;
        // Place records in different cohort buckets by using different write times
        // Cohort bucket = floor(write_time_secs / cohort_window_secs)
        // Cohort 0: write_time_secs in [0*3600, 1*3600)
        // Cohort 1: write_time_secs in [1*3600, 2*3600)
        // Cohort 2: write_time_secs in [2*3600, 3*3600)
        // Use write_time_nanos = cohort_idx * 3600 * 1e9 + 1800 * 1e9 (midpoint)
        // death_time = write_time_nanos + 3600*1e9 (far in past)
        //
        // But we want them partially expired (not fully) at our now_nanos.
        // Actually we want compact_partial_cohort to run and write output.
        // For that, death_time > now_nanos for at least some records.
        //
        // Use write_time far in future relative to "now" so records are alive:
        let write_time_nanos = now + (cohort_idx as i64 + 1) * 3_600_000_000_000_i64;
        let ttl: u32 = 0; // ttl=0 → death_time = write_time + cohort_window_nanos

        use edgestore::types::{encode_key, MemEntry, Operation};
        let entries: Vec<(Vec<u8>, MemEntry)> = (0..5u64)
            .map(|j| {
                let key = encode_key(
                    b"ns",
                    format!("cohort{}-key{}", cohort_idx, j).as_bytes(),
                );
                let entry = MemEntry {
                    key: key.clone(),
                    value: Some(format!("val-{}-{}", cohort_idx, j).into_bytes()),
                    op: Operation::Put,
                    lsn: cohort_idx * 10 + j + 1,
                    timestamp: write_time_nanos,
                    ttl,
                };
                (key, entry)
            })
            .collect();

        // Sort entries by key (SegmentWriter requirement)
        let mut sorted = entries;
        sorted.sort_by(|(a, _), (b, _)| a.cmp(b));

        let mut writer = edgestore::segment::SegmentWriter::new(
            dir.path().to_path_buf(),
            seg_id,
            cohort_window_secs,
        );
        let meta = writer.flush(&sorted).unwrap();
        manifest.add_segment(meta).unwrap();
    }

    assert_eq!(manifest.list_segments().len(), 3, "should have 3 segments");

    // Create compactor with write_budget_bytes = 1
    // now_nanos = current time (far past the write_time, so is_fully_expired = false
    // for cohorts whose death_time is in the future)
    // Actually with write_time in future, death_time = write_time + 3600s even further future
    // → is_fully_expired = false for all cohorts at current now_nanos
    // → compact_partial_cohort runs, writes survivors, bytes_written > 0
    // → with budget=1, after first cohort processes, second cohort trips the check
    let compactor = Compactor::new(dir.path().to_path_buf(), 1, cohort_window_secs);
    let pinned: HashSet<u64> = HashSet::new();

    let stats = compactor
        .compact_cycle(&mut manifest, now_nanos(), &pinned)
        .unwrap();

    // With budget=1 and cohorts requiring partial compaction (some bytes written),
    // at most 1 cohort should be fully processed before budget is exhausted.
    // After the first partial cohort writes > 0 bytes, the budget check will fire.
    assert!(
        stats.cohorts_collected <= 2,
        "COMPACT-04: write budget should stop compaction early; cohorts_collected={} (expected <= 2)",
        stats.cohorts_collected
    );

    // Some segments should remain unprocessed
    let remaining = manifest.list_segments().len();
    assert!(
        remaining >= 1,
        "some segments should remain after budget-bounded compaction, got {}",
        remaining
    );
}

// ── SC5: merkle_root on output segment matches recomputed value ─────────────

/// Success Criterion 5 (COMPACT-07): After compaction produces an output segment,
/// its merkle_root matches the value we recompute from the segment's keys.
///
/// The merkle_root computation (from SegmentWriter::flush):
///   1. Collect all keys from the output segment entries
///   2. For each key: hash = blake3::hash(key).as_bytes()  → [u8; 32]
///   3. Sort the [u8; 32] hashes
///   4. Feed them all through blake3::Hasher in sorted order
///   5. Finalize → merkle_root
///
/// Strategy:
///   1. Write records with a mix of live (ttl=0) and dead (ttl=1, expired) entries
///   2. Run compact_partial_cohort with Compactor directly
///   3. Open the output segment via SegmentReader
///   4. Read all keys from the output segment
///   5. Recompute merkle_root and assert == meta.merkle_root
#[test]
fn test_merkle_root_correct_after_compaction() {
    let dir = TempDir::new().unwrap();

    let manifest_path = dir.path().join("manifest.mf");
    let mut manifest = Manifest::open(&manifest_path).unwrap();

    let cohort_window_secs: u64 = 3600;
    let write_time_nanos: i64 = 3_600_000_000_000; // 1 hour in nanos
    // now_nanos = write_time + 2s → kills ttl=1 records, keeps ttl=0 records
    let now_nanos_compact: i64 = write_time_nanos + 2_000_000_000;

    use edgestore::compactor::CohortInfo;
    use edgestore::types::{encode_key, MemEntry, Operation};

    // Write a segment with 3 dead (ttl=1) + 4 alive (ttl=0) records
    let entries: Vec<(Vec<u8>, MemEntry)> = {
        let mut v = vec![];
        for i in 0u64..3 {
            let key = encode_key(b"ns", format!("dead-{:04}", i).as_bytes());
            v.push((
                key.clone(),
                MemEntry {
                    key: key.clone(),
                    value: Some(b"dead-val".to_vec()),
                    op: Operation::Put,
                    lsn: i + 1,
                    timestamp: write_time_nanos,
                    ttl: 1,
                },
            ));
        }
        for i in 0u64..4 {
            let key = encode_key(b"ns", format!("live-{:04}", i).as_bytes());
            v.push((
                key.clone(),
                MemEntry {
                    key: key.clone(),
                    value: Some(b"live-val".to_vec()),
                    op: Operation::Put,
                    lsn: 100 + i,
                    timestamp: write_time_nanos,
                    ttl: 0,
                },
            ));
        }
        v.sort_by(|(a, _), (b, _)| a.cmp(b));
        v
    };

    let mut writer =
        edgestore::segment::SegmentWriter::new(dir.path().to_path_buf(), 0, cohort_window_secs);
    let meta0 = writer.flush(&entries).unwrap();
    manifest.add_segment(meta0.clone()).unwrap();

    // Build cohort info for compact_partial_cohort
    let cohort = CohortInfo {
        cohort_bucket: meta0.cohort_bucket,
        segment_ids: vec![0],
        max_death_time_nanos: meta0.death_time,
        total_records: meta0.record_count,
        dead_record_estimate: 0,
        is_fully_expired: false,
    };

    let compactor = Compactor::new(dir.path().to_path_buf(), u64::MAX, cohort_window_secs);
    let mut stats = CompactionStats::default();

    compactor
        .compact_partial_cohort(&mut manifest, &cohort, now_nanos_compact, 1, &mut stats)
        .unwrap();

    // The output segment should be segment ID 1
    assert_eq!(
        manifest.list_segments().len(),
        1,
        "should have exactly 1 output segment after compaction"
    );
    let output_meta = &manifest.list_segments()[0];
    let output_seg_id = output_meta.segment_id;
    assert_eq!(output_seg_id, 1, "output segment should have id=1");

    // Open the output segment and read all keys
    let reader = SegmentReader::open(dir.path().to_path_buf(), output_seg_id).unwrap();
    let stored_merkle_root = reader.meta.merkle_root.clone();

    // Read all entries from the output segment via full range scan
    let all_entries = reader.range_scan(&[], &[0xFFu8; 256]).unwrap();
    assert!(
        !all_entries.is_empty(),
        "output segment should have surviving entries"
    );

    // Recompute merkle_root using the same algorithm as SegmentWriter::flush:
    //   1. Collect keys from output segment entries
    //   2. blake3::hash(key) → [u8; 32]
    //   3. Sort the hashes
    //   4. Chain through blake3::Hasher
    //   5. Finalize
    let mut key_hashes: Vec<[u8; 32]> = all_entries
        .iter()
        .map(|(k, _)| *blake3::hash(k).as_bytes())
        .collect();
    key_hashes.sort_unstable();
    let mut hasher = blake3::Hasher::new();
    for h in &key_hashes {
        hasher.update(h);
    }
    let recomputed_root = hasher.finalize().as_bytes().to_vec();

    assert_eq!(
        stored_merkle_root, recomputed_root,
        "COMPACT-07: merkle_root in output segment meta must match recomputed value"
    );

    // Also verify stats
    assert_eq!(stats.live_records_relocated, 4, "4 live records should be relocated");
    assert_eq!(stats.segments_written, 1);
}