motedb 0.2.0

AI-native embedded multimodal database for embodied intelligence (robots, AR glasses, industrial arms).
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
//! Compaction & Data Integrity Tests
//!
//! Validates that LSM compaction preserves all data correctly.
//! Covers the P0 bug where merge_sstables() skipped overlapping SSTables
//! (max_open=4 limit) but run_compaction() still removed them from metadata.
//!
//! Run:
//!   cargo test --test test_compaction_integrity -- --test-threads=1
//!   cargo test --test test_compaction_integrity --profile release-test -- --test-threads=1

use motedb::{Database, DBConfig, StreamingQueryResult};
use motedb::types::Value;
use tempfile::TempDir;

// ── Helpers ──────────────────────────────────────────────────────────

fn exec(db: &Database, sql: &str) -> motedb::sql::QueryResult {
    db.execute(sql).expect("execute SQL").materialize().expect("materialize")
}

fn count_rows(db: &Database) -> usize {
    let mut count = 0;
    let mut result = db.execute("SELECT id FROM t").unwrap();
    if let StreamingQueryResult::SelectStreaming { ref mut rows, .. } = result {
        while let Some(Ok(_)) = rows.next() { count += 1; }
    }
    count
}

fn get_row(db: &Database, id: i64) -> Option<Vec<Value>> {
    let sql = format!("SELECT * FROM t WHERE id = {}", id);
    let result = exec(db, &sql);
    match result {
        motedb::sql::QueryResult::Select { rows, .. } => rows.into_iter().next(),
        _ => None,
    }
}

fn get_val(db: &Database, id: i64) -> String {
    let row = get_row(db, id).unwrap_or_else(|| panic!("Row {} should exist", id));
    match &row[1] {
        Value::Text(s) => s.clone(),
        other => panic!("Row {} col 1 expected Text, got {:?}", id, other),
    }
}

fn wait_for_compaction() {
    std::thread::sleep(std::time::Duration::from_secs(5));
}

fn make_db() -> (TempDir, Database) {
    let dir = TempDir::new().unwrap();
    let db = Database::create_with_config(dir.path(), DBConfig::for_edge()).unwrap();
    (dir, db)
}

fn create_table(db: &Database) {
    exec(db, "CREATE TABLE t (id INTEGER PRIMARY KEY, status TEXT, amount FLOAT)");
}

fn lsm_dir_for(dir: &TempDir) -> std::path::PathBuf {
    dir.path().with_extension("mote").join("lsm")
}

fn count_sst_files(dir: &TempDir) -> usize {
    let lsm = lsm_dir_for(dir);
    std::fs::read_dir(&lsm).unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().and_then(|s| s.to_str()) == Some("sst"))
        .count()
}

// ── Category 1: Compaction Data Integrity ─────────────────────────────

#[test]
fn test_compaction_preserves_all_rows() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Insert 10K rows, flushing every 2000 to create 5 SSTables
    for batch in 0..5i64 {
        let start = batch * 2000 + 1;
        let end = start + 2000;
        for i in start..end {
            exec(&db, &format!("INSERT INTO t VALUES ({}, 'v_{}', 0.0)", i, i));
        }
        db.flush().unwrap();
    }

    wait_for_compaction();

    let count = count_rows(&db);
    assert_eq!(count, 10000, "After compaction: expected 10000 rows, got {}", count);

    // PK spot-check: every 100th row
    for i in (1..=10000).step_by(100) {
        let row = get_row(&db, i).unwrap_or_else(|| panic!("Row {} missing after compaction", i));
        assert!(row.len() >= 2, "Row {} has too few columns", i);
    }
}

#[test]
fn test_compaction_with_overlapping_keys() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Round 1: INSERT 100 rows
    for i in 1..=100i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'initial', 0.0)", i));
    }
    db.flush().unwrap();

    // Round 2: UPDATE rows 1-50
    for i in 1..=50i64 {
        exec(&db, &format!("UPDATE t SET status = 'v1' WHERE id = {}", i));
    }
    db.flush().unwrap();

    // Round 3: UPDATE rows 1-25 again
    for i in 1..=25i64 {
        exec(&db, &format!("UPDATE t SET status = 'v2' WHERE id = {}", i));
    }
    db.flush().unwrap();

    wait_for_compaction();
    db.flush().unwrap();

    // Retry loop for compaction settling
    let mut ok = false;
    for attempt in 0..8 {
        let count = count_rows(&db);
        if count != 100 {
            eprintln!("Attempt {}: count={}, waiting...", attempt, count);
            std::thread::sleep(std::time::Duration::from_secs(3));
            db.flush().unwrap();
            continue;
        }
        let mut all_correct = true;
        for i in 1..=25i64 {
            if get_val(&db, i) != "v2" { all_correct = false; break; }
        }
        if all_correct {
            for i in 26..=50i64 {
                if get_val(&db, i) != "v1" { all_correct = false; break; }
            }
        }
        if all_correct {
            for i in 51..=100i64 {
                if get_val(&db, i) != "initial" { all_correct = false; break; }
            }
        }
        if all_correct { ok = true; break; }
        eprintln!("Attempt {}: values not yet correct, waiting...", attempt);
        std::thread::sleep(std::time::Duration::from_secs(3));
        db.flush().unwrap();
    }

    assert!(ok, "Compaction did not settle with correct values after 8 attempts");
    assert_eq!(count_rows(&db), 100, "Should have 100 rows after compaction");
}

#[test]
fn test_compaction_after_delete() {
    let (_dir, db) = make_db();
    create_table(&db);

    for i in 1..=500i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'active', {})", i, i));
    }
    db.flush().unwrap();

    // Delete first half
    for i in 1..=250i64 {
        exec(&db, &format!("DELETE FROM t WHERE id = {}", i));
    }
    db.flush().unwrap();

    wait_for_compaction();

    assert_eq!(count_rows(&db), 250, "Should have 250 rows after delete + compaction");
    assert!(get_row(&db, 1).is_none(), "Deleted row 1 should be gone");
    assert!(get_row(&db, 250).is_none(), "Deleted row 250 should be gone");
    assert!(get_row(&db, 251).is_some(), "Row 251 should exist");
    assert!(get_row(&db, 500).is_some(), "Row 500 should exist");
}

#[test]
fn test_compaction_tombstone_propagation() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Insert, flush, verify present
    exec(&db, "INSERT INTO t VALUES (42, 'alive', 1.0)");
    db.flush().unwrap();
    assert!(get_row(&db, 42).is_some(), "Row should exist after flush");

    // Delete, flush, verify gone
    exec(&db, "DELETE FROM t WHERE id = 42");
    db.flush().unwrap();

    wait_for_compaction();

    assert!(get_row(&db, 42).is_none(), "Row should be gone after tombstone compaction");
    assert_eq!(count_rows(&db), 0, "Table should be empty");
}

#[test]
fn test_multi_level_compaction() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Write 10K rows in 5 batches with interleaved flush+sleep
    for batch in 0..5i64 {
        let start = batch * 2000 + 1;
        let end = start + 2000;
        for i in start..end {
            exec(&db, &format!("INSERT INTO t VALUES ({}, 'data', {:.1})", i, i as f64));
        }
        db.flush().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(500));
    }

    wait_for_compaction();

    let count = count_rows(&db);
    assert_eq!(count, 10000, "All 10000 rows should survive multi-level compaction, got {}", count);

    // Spot-check
    for i in (1..=10000).step_by(200) {
        assert!(get_row(&db, i).is_some(), "Row {} missing", i);
    }
}

// ── Category 2: Concurrent Operations ─────────────────────────────────

#[test]
fn test_concurrent_writes_and_scan() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Pre-insert baseline
    for i in 1..=1000i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'base', 0.0)", i));
    }
    db.flush().unwrap();

    let scan_counts = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));

    std::thread::scope(|s| {
        let db = &db;
        let counts = scan_counts.clone();

        // Writer: inserts rows 1001-3000
        s.spawn(move || {
            for i in 1001..=3000i64 {
                exec(db, &format!("INSERT INTO t VALUES ({}, 'new', 0.0)", i));
            }
        });

        // Reader: scan 10 times
        s.spawn(move || {
            for _ in 0..10 {
                let c = count_rows(db);
                counts.lock().unwrap().push(c);
            }
        });
    });

    // All scans should see at least the baseline 1000 rows
    let counts = scan_counts.lock().unwrap();
    for (i, &c) in counts.iter().enumerate() {
        assert!(c >= 1000, "Scan {} saw {} rows, expected >= 1000", i, c);
    }

    // Final count should be 3000
    let final_count = count_rows(&db);
    assert_eq!(final_count, 3000, "Final count should be 3000, got {}", final_count);
}

#[test]
fn test_concurrent_flush_and_scan() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Insert 3000 rows (triggers auto-flush at ~2001)
    for i in 1..=3000i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'x', {})", i, i));
    }

    // Immediately scan repeatedly while auto-flush may be running
    let mut min_count = usize::MAX;
    let mut max_count = 0;
    for _ in 0..10 {
        let c = count_rows(&db);
        min_count = min_count.min(c);
        max_count = max_count.max(c);
    }

    // All scans should see at least 3000 (no data loss, maybe more from dedup artifacts)
    assert!(min_count >= 3000, "Min scan count {} < 3000", min_count);

    let final_count = count_rows(&db);
    assert_eq!(final_count, 3000, "Final count should be 3000, got {}", final_count);
}

#[test]
fn test_concurrent_compaction_and_point_get() {
    let (_dir, db) = make_db();
    create_table(&db);

    // Insert 5000 rows, flush to create SSTables and trigger compaction
    for i in 1..=5000i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'val_{}', {:.2})", i, i, i as f64 * 1.5));
    }
    db.flush().unwrap();

    // PK lookups while compaction may be running
    for i in (1..=5000).step_by(50) {
        let row = get_row(&db, i).unwrap_or_else(|| {
            panic!("Row {} should exist during compaction", i)
        });
        assert_eq!(row[0], Value::Integer(i), "Row {} has wrong id", i);
    }

    // Trigger another flush for more compaction
    for i in 1..=100i64 {
        exec(&db, &format!("UPDATE t SET status = 'updated' WHERE id = {}", i));
    }
    db.flush().unwrap();

    // Verify again
    for i in (1..=100).step_by(10) {
        assert_eq!(get_val(&db, i), "updated", "Row {} should be updated", i);
    }
    for i in (101..=5000).step_by(100) {
        assert_eq!(get_val(&db, i), format!("val_{}", i), "Row {} should be original", i);
    }

    assert_eq!(count_rows(&db), 5000, "All 5000 rows should be present");
}

// ── Category 3: Edge Cases ────────────────────────────────────────────

#[test]
fn test_many_small_sstables() {
    let (_dir, db) = make_db();
    create_table(&db);

    // 20 rounds of small inserts + flush = 20 SSTables
    for round in 0..20i64 {
        let base = round * 1000 + 1;
        for i in 0..10i64 {
            let id = base + i;
            exec(&db, &format!("INSERT INTO t VALUES ({}, 'small', 0.0)", id));
        }
        db.flush().unwrap();
    }

    wait_for_compaction();

    assert_eq!(count_rows(&db), 200, "Should have 200 rows across 20 SSTables, got {}", count_rows(&db));

    // Verify every row
    for round in 0..20i64 {
        let base = round * 1000 + 1;
        for i in 0..10i64 {
            let id = base + i;
            assert!(get_row(&db, id).is_some(), "Row {} missing", id);
        }
    }
}

#[test]
fn test_empty_table_scan() {
    let (_dir, db) = make_db();
    create_table(&db);

    assert_eq!(count_rows(&db), 0, "Empty table should have 0 rows");

    db.flush().unwrap();
    assert_eq!(count_rows(&db), 0, "Empty table after flush should have 0 rows");
}

#[test]
fn test_single_row_lifecycle() {
    let (_dir, db) = make_db();
    create_table(&db);

    // INSERT
    exec(&db, "INSERT INTO t VALUES (1, 'original', 10.0)");
    assert!(get_row(&db, 1).is_some(), "Row exists in memtable");
    assert_eq!(get_val(&db, 1), "original");

    // Flush to SSTable
    db.flush().unwrap();
    assert!(get_row(&db, 1).is_some(), "Row exists in SSTable");
    assert_eq!(get_val(&db, 1), "original");

    // UPDATE
    exec(&db, "UPDATE t SET status = 'updated' WHERE id = 1");
    assert_eq!(get_val(&db, 1), "updated");

    db.flush().unwrap();
    assert_eq!(get_val(&db, 1), "updated");

    // DELETE
    exec(&db, "DELETE FROM t WHERE id = 1");
    assert!(get_row(&db, 1).is_none(), "Row gone from memtable");

    db.flush().unwrap();
    assert!(get_row(&db, 1).is_none(), "Row gone after flush");

    wait_for_compaction();
    assert!(get_row(&db, 1).is_none(), "Row gone after compaction");
}

#[test]
fn test_large_dataset_compaction() {
    let (_dir, db) = make_db();
    create_table(&db);

    // 20K rows in 4 batches
    for batch in 0..4i64 {
        let start = batch * 5000 + 1;
        let end = start + 5000;
        for i in start..end {
            exec(&db, &format!("INSERT INTO t VALUES ({}, 'v_{}', {:.2})", i, i, i as f64));
        }
        db.flush().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(300));
    }

    wait_for_compaction();
    assert_eq!(count_rows(&db), 20000, "Should have 20000 rows after compaction");

    // Spot-check
    for i in (1..=20000).step_by(500) {
        assert!(get_row(&db, i).is_some(), "Row {} missing", i);
    }

    // UPDATE first 2K rows
    for i in 1..=2000i64 {
        exec(&db, &format!("UPDATE t SET status = 'final' WHERE id = {}", i));
    }
    db.flush().unwrap();
    wait_for_compaction();

    assert_eq!(count_rows(&db), 20000, "Still 20000 after UPDATE");
    for i in (1..=2000).step_by(500) {
        assert_eq!(get_val(&db, i), "final", "Row {} should be updated", i);
    }
}

#[test]
fn test_delete_nonexistent_key() {
    let (_dir, db) = make_db();
    create_table(&db);

    exec(&db, "INSERT INTO t VALUES (1, 'here', 1.0)");

    // Delete nonexistent — should not error
    exec(&db, "DELETE FROM t WHERE id = 999");

    assert_eq!(count_rows(&db), 1, "Only row 1 should exist");
    assert!(get_row(&db, 1).is_some(), "Row 1 should still exist");
    assert!(get_row(&db, 999).is_none(), "Row 999 should not exist");
}

#[test]
fn test_update_then_scan_preserves_all() {
    let (_dir, db) = make_db();
    create_table(&db);

    // INSERT 5K
    for i in 1..=5000i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'pending', {:.2})", i, i as f64 * 10.0));
    }
    db.flush().unwrap();

    // UPDATE 1-2500
    for i in 1..=2500i64 {
        exec(&db, &format!("UPDATE t SET status = 'completed' WHERE id = {}", i));
    }
    db.flush().unwrap();

    // UPDATE 1-1000 again
    for i in 1..=1000i64 {
        exec(&db, &format!("UPDATE t SET status = 'final' WHERE id = {}", i));
    }
    db.flush().unwrap();

    // Retry loop: compaction may still be settling from earlier tests
    let mut ok = false;
    for attempt in 0..8 {
        db.flush().unwrap();
        let total = count_rows(&db);
        if total != 5000 {
            eprintln!("Attempt {}: count={}, waiting...", attempt, total);
            std::thread::sleep(std::time::Duration::from_secs(3));
            continue;
        }

        let mut final_count = 0u64;
        let mut completed_count = 0u64;
        let mut pending_count = 0u64;
        let mut result = db.execute("SELECT id, status FROM t").unwrap();
        if let StreamingQueryResult::SelectStreaming { ref mut rows, .. } = result {
            while let Some(Ok(row)) = rows.next() {
                match &row[1] {
                    Value::Text(s) if s == "final" => final_count += 1,
                    Value::Text(s) if s == "completed" => completed_count += 1,
                    Value::Text(s) if s == "pending" => pending_count += 1,
                    other => panic!("Unexpected status: {:?}", other),
                }
            }
        }

        if final_count == 1000 && completed_count == 1500 && pending_count == 2500 {
            ok = true;
            break;
        }
        eprintln!("Attempt {}: final={}, completed={}, pending={}", attempt, final_count, completed_count, pending_count);
        std::thread::sleep(std::time::Duration::from_secs(3));
    }

    assert!(ok, "Status distribution did not settle after 8 attempts");
}

// ── Category 4: Deferred Deletion ─────────────────────────────────────

#[test]
fn test_deferred_deletion_keeps_files_alive() {
    let (dir, db) = make_db();
    create_table(&db);

    // Batch 1: creates SSTable A
    for i in 1..=500i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'a', 0.0)", i));
    }
    db.flush().unwrap();

    // Batch 2: creates SSTable B → triggers compaction (2 SSTables >= threshold)
    for i in 501..=1000i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'b', 0.0)", i));
    }
    db.flush().unwrap();

    // Wait for compaction to merge A+B into C
    wait_for_compaction();

    // Source files A and B should still exist (deferred deletion)
    let file_count = count_sst_files(&dir);
    assert!(file_count >= 2, "Deferred deletion: expected >= 2 sst files, got {}", file_count);

    // Batch 3: creates SSTable D → triggers next compaction cycle
    // which will flush_pending_deletions() from the previous cycle
    for i in 1001..=1500i64 {
        exec(&db, &format!("INSERT INTO t VALUES ({}, 'c', 0.0)", i));
    }
    db.flush().unwrap();
    wait_for_compaction();

    assert_eq!(count_rows(&db), 1500, "All 1500 rows should be present");
}

#[test]
fn test_orphan_cleanup_on_open() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().to_path_buf();

    // Phase 1: Create DB, insert data, flush, close
    {
        let db = Database::create_with_config(&path, DBConfig::for_edge()).unwrap();
        exec(&db, "CREATE TABLE t (id INTEGER PRIMARY KEY, status TEXT)");
        for i in 1..=100i64 {
            exec(&db, &format!("INSERT INTO t VALUES ({}, 'ok')", i));
        }
        db.flush().unwrap();
        db.close().unwrap();
    }

    // Create an orphan .sst file
    let lsm = path.with_extension("mote").join("lsm");
    let orphan = lsm.join("l0_orphan_999999.sst");
    std::fs::write(&orphan, b"garbage data not a real sstable").unwrap();
    assert!(orphan.exists(), "Orphan file should exist before open");

    // Phase 2: Reopen — orphan should be cleaned up
    {
        let db = Database::open_with_config(&path, DBConfig::for_edge()).unwrap();
        assert!(!orphan.exists(), "Orphan SSTable should be cleaned up on open");

        let count = count_rows_via(&db, "SELECT id FROM t");
        assert_eq!(count, 100, "Original data should survive reopen");
    }
}

fn count_rows_via(db: &Database, sql: &str) -> usize {
    let mut count = 0;
    let mut result = db.execute(sql).unwrap();
    if let StreamingQueryResult::SelectStreaming { ref mut rows, .. } = result {
        while let Some(Ok(_)) = rows.next() { count += 1; }
    }
    count
}

// ── Category 5: Restart Recovery ──────────────────────────────────────

#[test]
fn test_data_survives_restart() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().to_path_buf();

    // Phase 1: Write
    {
        let db = Database::create_with_config(&path, DBConfig::for_edge()).unwrap();
        exec(&db, "CREATE TABLE t (id INTEGER PRIMARY KEY, status TEXT)");
        for i in 1..=5000i64 {
            exec(&db, &format!("INSERT INTO t VALUES ({}, 'val_{}')", i, i));
        }
        db.flush().unwrap();
        db.close().unwrap();
    }

    // Phase 2: Reopen and verify
    {
        let db = Database::open_with_config(&path, DBConfig::for_edge()).unwrap();
        let count = count_rows_via(&db, "SELECT id FROM t");
        assert_eq!(count, 5000, "All rows should survive restart, got {}", count);

        // Spot-check values
        for i in (1..=5000).step_by(100) {
            let sql = format!("SELECT * FROM t WHERE id = {}", i);
            let result = exec(&db, &sql);
            match result {
                motedb::sql::QueryResult::Select { rows, .. } => {
                    let row = rows.into_iter().next()
                        .unwrap_or_else(|| panic!("Row {} missing after restart", i));
                    assert_eq!(row[1], Value::Text(format!("val_{}", i)),
                        "Row {} value mismatch after restart", i);
                }
                _ => panic!("Expected Select result for row {}", i),
            }
        }
    }
}

#[test]
fn test_compaction_result_survives_restart() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().to_path_buf();

    // Phase 1: Write in batches to trigger compaction
    {
        let db = Database::create_with_config(&path, DBConfig::for_edge()).unwrap();
        exec(&db, "CREATE TABLE t (id INTEGER PRIMARY KEY, status TEXT)");
        for batch in 0..5i64 {
            let start = batch * 2000 + 1;
            let end = start + 2000;
            for i in start..end {
                exec(&db, &format!("INSERT INTO t VALUES ({}, 'data')", i));
            }
            db.flush().unwrap();
            std::thread::sleep(std::time::Duration::from_millis(500));
        }
        wait_for_compaction();
        db.close().unwrap();
    }

    // Phase 2: Reopen — data should have survived compaction + restart
    {
        let db = Database::open_with_config(&path, DBConfig::for_edge()).unwrap();
        let count = count_rows_via(&db, "SELECT id FROM t");
        assert_eq!(count, 10000, "All 10000 rows should survive compaction + restart, got {}", count);

        for i in (1..=10000).step_by(200) {
            let sql = format!("SELECT * FROM t WHERE id = {}", i);
            let result = exec(&db, &sql);
            match result {
                motedb::sql::QueryResult::Select { rows, .. } => {
                    assert!(rows.into_iter().next().is_some(), "Row {} missing after restart", i);
                }
                _ => panic!("Expected Select result for row {}", i),
            }
        }
    }
}