lora-database 0.5.6

LoraDB — embeddable in-memory graph database with Cypher query support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
//! Integration tests for the WAL-aware Database constructors.
//!
//! These exercise the seam between `Database<InMemoryGraph>` and
//! `lora-wal::Wal` end-to-end: a real query path drives mutations
//! through the engine, the WAL captures them under the store write lock,
//! and a fresh process (modelled by dropping + re-opening the
//! database) recovers them via replay.

use std::io::Write;
use std::path::{Path, PathBuf};

use lora_database::{
    resolve_database_path, Database, DatabaseName, DatabaseOpenOptions, ExecuteOptions,
    ResultFormat,
};
use lora_store::{MutationEvent, Properties, PropertyValue};
use lora_wal::{Lsn, SyncMode, Wal, WalConfig};

// ---------------------------------------------------------------------------
// Test scaffolding
// ---------------------------------------------------------------------------

/// Per-test scratch directory. Roll our own (matching the snapshot
/// tests' helper) so we don't take a `tempfile` dev-dependency.
struct TmpDir {
    path: PathBuf,
}

impl TmpDir {
    fn new(tag: &str) -> Self {
        let mut path = std::env::temp_dir();
        path.push(format!(
            "lora-db-wal-{}-{}-{}",
            tag,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&path).unwrap();
        Self { path }
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TmpDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

fn copy_dir_all(from: &Path, to: &Path) {
    std::fs::create_dir_all(to).unwrap();
    for entry in std::fs::read_dir(from).unwrap() {
        let entry = entry.unwrap();
        let from_path = entry.path();
        let to_path = to.join(entry.file_name());
        if from_path.is_dir() {
            copy_dir_all(&from_path, &to_path);
        } else {
            std::fs::copy(&from_path, &to_path).unwrap();
        }
    }
}

fn write_archive_without_manifest(path: &Path) {
    let file = std::fs::File::create(path).unwrap();
    let mut zip = zip::ZipWriter::new(file);
    let options = zip::write::FileOptions::default()
        .compression_method(zip::CompressionMethod::Stored)
        .unix_permissions(0o644);
    zip.start_file("wal/0000000001.wal", options).unwrap();
    zip.write_all(b"not-a-real-wal").unwrap();
    zip.finish().unwrap();
}

fn rows() -> Option<ExecuteOptions> {
    Some(ExecuteOptions {
        format: ResultFormat::Rows,
    })
}

fn enabled(dir: &Path) -> WalConfig {
    WalConfig::Enabled {
        dir: dir.to_path_buf(),
        sync_mode: SyncMode::PerCommit,
        segment_target_bytes: 8 * 1024 * 1024,
    }
}

fn group_enabled(dir: &Path) -> WalConfig {
    WalConfig::Enabled {
        dir: dir.to_path_buf(),
        sync_mode: SyncMode::Group {
            interval_ms: 60_000,
        },
        segment_target_bytes: 8 * 1024 * 1024,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[test]
fn disabled_config_behaves_like_in_memory() {
    let db = Database::open_with_wal(WalConfig::Disabled).unwrap();
    db.execute("CREATE (:User {id: 1})", rows()).unwrap();
    assert_eq!(db.node_count(), 1);
    assert!(db.wal().is_none());
}

#[test]
fn database_name_validation_accepts_only_portable_names() {
    for valid in [
        "app",
        "app.loradb",
        "tenant_01",
        "tenant+01",
        "a-b",
        "A123",
        "./database-dir/application",
        "database_dir/app.loradb",
    ] {
        assert!(
            DatabaseName::parse(valid).is_ok(),
            "{valid} should be valid"
        );
    }

    for invalid in [
        "",
        ".",
        "..",
        "../x",
        "/absolute/app",
        "x//y",
        "a-b.c",
        "app.txt",
        "has space",
        "ümlaut",
    ] {
        assert!(
            DatabaseName::parse(invalid).is_err(),
            "{invalid:?} should be invalid"
        );
    }
}

#[test]
fn named_database_resolves_to_lora_root_under_database_dir() {
    let dir = TmpDir::new("named-path");
    let path = resolve_database_path("app_01", dir.path()).unwrap();
    assert_eq!(path, dir.path().join("app_01.loradb"));

    let path = resolve_database_path("./tenant-a/application", dir.path()).unwrap();
    assert_eq!(path, dir.path().join("tenant-a").join("application.loradb"));

    let path = resolve_database_path("tenant_b/app.loradb", dir.path()).unwrap();
    assert_eq!(path, dir.path().join("tenant_b").join("app.loradb"));
}

#[test]
fn named_database_persists_under_lora_root() {
    let dir = TmpDir::new("named-recover");

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions::default().with_database_dir(dir.path()),
        )
        .unwrap();
        db.execute("CREATE (:User {id: 1})", rows()).unwrap();
    }

    assert!(
        dir.path().join("app.loradb").is_file(),
        "named databases should persist as a portable .loradb archive file"
    );
    assert!(
        !dir.path().join("app.loradb.wal").exists(),
        "clean shutdown should remove the durable sidecar after archiving"
    );
    let bytes = std::fs::read(dir.path().join("app.loradb")).unwrap();
    assert_eq!(&bytes[..4], b"PK\x03\x04");
    let file = std::fs::File::open(dir.path().join("app.loradb")).unwrap();
    let mut zip = zip::ZipArchive::new(file).unwrap();
    assert!(zip.by_name("manifest.json").is_ok());
    assert!(zip.by_name("wal/0000000001.wal").is_ok());

    let db = Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    )
    .unwrap();
    assert_eq!(db.node_count(), 1);
}

#[test]
fn named_database_recovers_from_durable_sidecar_when_archive_lags() {
    let dir = TmpDir::new("named-sidecar-recover");
    let archive_path = dir.path().join("app.loradb");
    let sidecar_path = dir.path().join("app.loradb.wal");
    let saved_sidecar = dir.path().join("saved-sidecar");

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions {
                sync_mode: SyncMode::PerCommit,
                ..DatabaseOpenOptions::default().with_database_dir(dir.path())
            },
        )
        .unwrap();
        db.execute("CREATE (:N {id: 1})", rows()).unwrap();
    }
    let stale_archive = std::fs::read(&archive_path).unwrap();

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions {
                sync_mode: SyncMode::PerCommit,
                ..DatabaseOpenOptions::default().with_database_dir(dir.path())
            },
        )
        .unwrap();
        db.execute("CREATE (:N {id: 2})", rows()).unwrap();
        copy_dir_all(&sidecar_path, &saved_sidecar);
    }

    std::fs::write(&archive_path, stale_archive).unwrap();
    copy_dir_all(&saved_sidecar, &sidecar_path);

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions::default().with_database_dir(dir.path()),
        )
        .unwrap();
        assert_eq!(db.node_count(), 2);
    }

    assert!(
        !sidecar_path.exists(),
        "clean recovery shutdown should archive and remove the sidecar"
    );
}

#[test]
fn named_database_sync_makes_archive_immediately_portable() {
    let dir = TmpDir::new("named-sync-source");
    let portable_dir = TmpDir::new("named-sync-copy");

    let db = Database::open_named(
        "app",
        DatabaseOpenOptions {
            sync_mode: SyncMode::Group {
                interval_ms: 60_000,
            },
            ..DatabaseOpenOptions::default().with_database_dir(dir.path())
        },
    )
    .unwrap();
    db.execute("CREATE (:Synced {id: 1})", rows()).unwrap();
    db.sync().unwrap();

    std::fs::copy(
        dir.path().join("app.loradb"),
        portable_dir.path().join("app.loradb"),
    )
    .unwrap();

    let recovered = Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(portable_dir.path()),
    )
    .unwrap();
    assert_eq!(recovered.node_count(), 1);
}

#[test]
fn named_database_clear_persists_through_archive() {
    let dir = TmpDir::new("named-clear");

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions::default().with_database_dir(dir.path()),
        )
        .unwrap();
        db.execute("CREATE (:A {id: 1})-[:R]->(:B {id: 2})", rows())
            .unwrap();
        db.try_clear().unwrap();
        assert_eq!(db.node_count(), 0);
        assert_eq!(db.relationship_count(), 0);
    }

    let recovered = Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    )
    .unwrap();
    assert_eq!(recovered.node_count(), 0);
    assert_eq!(recovered.relationship_count(), 0);
}

#[test]
fn named_database_cleanup_only_removes_generated_temp_paths() {
    let dir = TmpDir::new("named-temp-cleanup");
    let unrelated_file = dir.path().join("app.loradb.user.tmp");
    let unrelated_dir = dir.path().join("app.loradb.wal.extract.user");
    let generated_file = dir.path().join("app.loradb.1.2.3.tmp");
    let generated_dir = dir.path().join("app.loradb.wal.extract.1.2.3");

    std::fs::write(&unrelated_file, b"keep").unwrap();
    std::fs::create_dir(&unrelated_dir).unwrap();
    std::fs::write(&generated_file, b"delete").unwrap();
    std::fs::create_dir(&generated_dir).unwrap();

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions::default().with_database_dir(dir.path()),
        )
        .unwrap();
        db.sync().unwrap();
    }

    assert!(unrelated_file.exists());
    assert!(unrelated_dir.exists());
    assert!(!generated_file.exists());
    assert!(!generated_dir.exists());
}

#[test]
fn named_database_rejects_invalid_archive_without_publishing_partial_sidecar() {
    let dir = TmpDir::new("named-invalid-archive");
    let archive_path = dir.path().join("app.loradb");
    let sidecar_path = dir.path().join("app.loradb.wal");
    write_archive_without_manifest(&archive_path);

    let err = match Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    ) {
        Ok(_) => panic!("invalid archive should fail to open"),
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("manifest"),
        "unexpected error: {err}"
    );
    assert!(
        !sidecar_path.exists(),
        "failed archive extraction must not leave a partial sidecar"
    );
}

#[test]
fn named_database_rejects_concurrent_archive_open() {
    let dir = TmpDir::new("named-concurrent-open");

    let first = Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    )
    .unwrap();

    let err = match Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    ) {
        Ok(_) => panic!("second archive open should fail"),
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("already open"),
        "unexpected error: {err}"
    );

    drop(first);
    let reopened = Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    )
    .unwrap();
    assert_eq!(reopened.node_count(), 0);
}

#[test]
fn named_database_recovers_write_burst_from_zip_archive() {
    let dir = TmpDir::new("named-burst");

    {
        let db = Database::open_named(
            "burst",
            DatabaseOpenOptions::default().with_database_dir(dir.path()),
        )
        .unwrap();
        for i in 0..250 {
            db.execute(&format!("CREATE (:Burst {{id: {i}}})"), rows())
                .unwrap();
        }
        assert_eq!(db.node_count(), 250);
    }

    let archive_path = dir.path().join("burst.loradb");
    assert!(archive_path.is_file());
    let file = std::fs::File::open(&archive_path).unwrap();
    let mut zip = zip::ZipArchive::new(file).unwrap();
    assert!(zip.by_name("manifest.json").is_ok());
    assert!(zip.by_name("wal/0000000001.wal").is_ok());

    let db = Database::open_named(
        "burst",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    )
    .unwrap();
    assert_eq!(db.node_count(), 250);
    let result = db
        .execute("MATCH (n:Burst) RETURN n.id AS id ORDER BY id", rows())
        .unwrap();
    let json = serde_json::to_value(&result).unwrap();
    let row_array = json["rows"].as_array().expect("rows array");
    assert_eq!(row_array.first().unwrap()["id"], serde_json::json!(0));
    assert_eq!(row_array.last().unwrap()["id"], serde_json::json!(249));
}

#[test]
fn named_database_final_archive_flush_captures_group_buffer() {
    let dir = TmpDir::new("named-group-final-flush");

    {
        let db = Database::open_named(
            "app",
            DatabaseOpenOptions {
                database_dir: dir.path().to_path_buf(),
                sync_mode: SyncMode::Group {
                    interval_ms: 60_000,
                },
                ..DatabaseOpenOptions::default()
            },
        )
        .unwrap();
        db.execute(
            "CREATE (:Person {name: 'Ada'})-[:KNOWS]->(:Person {name: 'Grace'})",
            rows(),
        )
        .unwrap();

        // Let the archive debounce worker run before the clean shutdown path.
        // The final archive flush on drop must still publish a complete,
        // reopenable archive.
        std::thread::sleep(std::time::Duration::from_millis(1_200));
    }

    let db = Database::open_named(
        "app",
        DatabaseOpenOptions::default().with_database_dir(dir.path()),
    )
    .unwrap();
    assert_eq!(db.node_count(), 2);
    assert_eq!(db.relationship_count(), 1);
}

#[test]
fn fresh_open_then_crash_recover_replays_committed_writes() {
    let dir = TmpDir::new("recover");

    {
        let db = Database::open_with_wal(enabled(dir.path())).unwrap();
        db.execute("CREATE (:User {id: 1, name: 'alice'})", rows())
            .unwrap();
        db.execute("CREATE (:User {id: 2, name: 'bob'})", rows())
            .unwrap();
        // Drop without explicit close to model a crash; PerCommit
        // already fsync'd the commit markers, so the WAL is durable.
    }

    // Fresh process: empty graph + WAL on disk → recover replays.
    let db = Database::open_with_wal(enabled(dir.path())).unwrap();
    assert_eq!(db.node_count(), 2);

    // Confirm the property values made it through replay (not just
    // the right number of nodes).
    let result = db
        .execute("MATCH (u:User) RETURN u.id AS id ORDER BY id", rows())
        .unwrap();
    let json = serde_json::to_value(&result).unwrap();
    let row_array = json["rows"].as_array().expect("rows array");
    assert_eq!(row_array.len(), 2);
    assert_eq!(row_array[0]["id"], serde_json::json!(1));
    assert_eq!(row_array[1]["id"], serde_json::json!(2));
}

#[test]
fn read_only_queries_dont_block_recovery() {
    // A read-only query bracketed by arm/commit produces zero records
    // in the WAL. Recovery must handle that without spurious empty
    // events.
    let dir = TmpDir::new("read-only");

    {
        let db = Database::open_with_wal(enabled(dir.path())).unwrap();
        db.execute("CREATE (:Tag {v: 1})", rows()).unwrap();
        // Pure reads — should fire no mutation records.
        for _ in 0..5 {
            db.execute("MATCH (t:Tag) RETURN t", rows()).unwrap();
        }
        db.execute("CREATE (:Tag {v: 2})", rows()).unwrap();
    }

    let db = Database::open_with_wal(enabled(dir.path())).unwrap();
    assert_eq!(db.node_count(), 2);
}

/// Sum of every `*.wal` file size in `dir`. Used to prove the WAL
/// hot-path is byte-stable across a run of read-only queries.
fn wal_bytes(dir: &Path) -> u64 {
    let mut total = 0u64;
    for entry in std::fs::read_dir(dir).unwrap().flatten() {
        let p = entry.path();
        if p.extension().and_then(|s| s.to_str()) == Some("wal") {
            total += std::fs::metadata(&p).unwrap().len();
        }
    }
    total
}

#[test]
fn read_only_queries_do_not_grow_wal_or_advance_lsn() {
    // Regression test for the lazy-begin path: read-only queries
    // through `Database::execute_with_params` must not produce any
    // WAL records, fsyncs, or LSN advances. The user-visible cost
    // of running 200 reads should be 0 bytes added to the log.
    let dir = TmpDir::new("ro-no-grow");
    let db = Database::open_with_wal(enabled(dir.path())).unwrap();

    // One write to seed the WAL with at least one segment.
    db.execute("CREATE (:Tag {v: 1})", rows()).unwrap();

    let bytes_before = wal_bytes(dir.path());
    let lsn_before = db.wal().unwrap().wal().next_lsn();

    for _ in 0..200 {
        db.execute("MATCH (t:Tag) RETURN t", rows()).unwrap();
    }

    let bytes_after = wal_bytes(dir.path());
    let lsn_after = db.wal().unwrap().wal().next_lsn();

    assert_eq!(
        bytes_before,
        bytes_after,
        "200 read-only queries grew the WAL by {} bytes",
        bytes_after.saturating_sub(bytes_before)
    );
    assert_eq!(
        lsn_before, lsn_after,
        "200 read-only queries advanced next_lsn from {} to {}",
        lsn_before, lsn_after
    );
}

#[test]
fn aborted_query_does_not_persist_partial_mutation() {
    // The engine has no rollback, so a query that mutates and then
    // errors leaves partial in-memory state. The WAL must mark that
    // transaction aborted so recovery from a fresh process drops it.
    let dir = TmpDir::new("aborted");

    {
        let db = Database::open_with_wal(enabled(dir.path())).unwrap();
        db.execute("CREATE (:User {id: 1})", rows()).unwrap();

        // Pick a query that compiles but fails at execute time.
        // Creating a relationship with an unknown variable surfaces
        // a runtime error; specifics are less important than the
        // fact that the resulting Err triggers the abort branch.
        let bad = db.execute("MATCH (u:User) CREATE (u)-[:KNOWS]->(missing)", rows());
        // The query may either reject at semantic-analysis time
        // (Err) or succeed by creating the missing node implicitly,
        // depending on planner specifics. We tolerate both — the
        // assertion is on what *recovery* produces.
        let _ = bad;
    }

    // Recovery should produce a graph consistent with what was
    // committed. If the bad query was rejected pre-execute, only
    // the first User exists; if it succeeded, both nodes exist plus
    // the relationship. Either way, recovery state must equal a
    // fresh `Database::open_with_wal` reading the same WAL.
    let recovered = Database::open_with_wal(enabled(dir.path())).unwrap();
    let count = recovered.node_count();
    // Run the same CREATE on a *different* WAL-disabled DB and
    // compare counts to confirm reproducibility — we don't care
    // about the exact number, only that recovery is deterministic.
    drop(recovered);
    let again = Database::open_with_wal(enabled(dir.path())).unwrap();
    assert_eq!(again.node_count(), count);
}

#[test]
fn failed_mutating_query_poisons_live_wal_handle_until_restart() {
    let dir = TmpDir::new("abort-poisons-live");

    {
        let db = Database::open_with_wal(enabled(dir.path())).unwrap();
        let err = db
            .execute("CREATE (a)-[:R]->(b) WITH a DELETE a", rows())
            .unwrap_err();
        assert!(
            err.to_string().contains("WAL poisoned"),
            "expected the failed mutating query to poison the live handle, got {err}"
        );

        let next = db.execute("RETURN 1 AS ok", rows()).unwrap_err();
        assert!(
            next.to_string().contains("WAL arm failed"),
            "expected future queries on the live handle to fail, got {next}"
        );
    }

    let recovered = Database::open_with_wal(enabled(dir.path())).unwrap();
    assert_eq!(
        recovered.node_count(),
        0,
        "recovery should discard the aborted create/delete transaction"
    );
}

#[test]
fn replay_preserves_ids_after_aborted_create_gap() {
    let dir = TmpDir::new("id-gap");

    {
        let (wal, replay) =
            Wal::open(dir.path(), SyncMode::PerCommit, 8 * 1024 * 1024, Lsn::ZERO).unwrap();
        assert!(replay.is_empty());

        let aborted = wal.begin().unwrap();
        wal.append(
            aborted,
            &MutationEvent::CreateNode {
                id: 0,
                labels: vec!["Discarded".into()],
                properties: Properties::new(),
            },
        )
        .unwrap();
        wal.abort(aborted).unwrap();
        wal.flush().unwrap();

        let create = wal.begin().unwrap();
        wal.append(
            create,
            &MutationEvent::CreateNode {
                id: 1,
                labels: vec!["Kept".into()],
                properties: Properties::new(),
            },
        )
        .unwrap();
        wal.commit(create).unwrap();
        wal.flush().unwrap();

        let set_name = wal.begin().unwrap();
        wal.append(
            set_name,
            &MutationEvent::SetNodeProperty {
                node_id: 1,
                key: "name".into(),
                value: PropertyValue::String("survivor".into()),
            },
        )
        .unwrap();
        wal.commit(set_name).unwrap();
        wal.flush().unwrap();
    }

    let db = Database::open_with_wal(enabled(dir.path())).unwrap();
    assert_eq!(db.node_count(), 1);

    let result = db
        .execute(
            "MATCH (n:Kept {name: 'survivor'}) RETURN n.name AS name",
            rows(),
        )
        .unwrap();
    let json = serde_json::to_value(&result).unwrap();
    let row_array = json["rows"].as_array().expect("rows array");
    assert_eq!(row_array.len(), 1);
    assert_eq!(row_array[0]["name"], serde_json::json!("survivor"));
}

#[test]
fn replay_rejects_relationship_with_missing_endpoint() {
    let dir = TmpDir::new("missing-endpoint");

    {
        let (wal, replay) =
            Wal::open(dir.path(), SyncMode::PerCommit, 8 * 1024 * 1024, Lsn::ZERO).unwrap();
        assert!(replay.is_empty());

        let tx = wal.begin().unwrap();
        wal.append(
            tx,
            &MutationEvent::CreateRelationship {
                id: 0,
                src: 10,
                dst: 11,
                rel_type: "BROKEN".into(),
                properties: Properties::new(),
            },
        )
        .unwrap();
        wal.commit(tx).unwrap();
        wal.flush().unwrap();
    }

    let err = match Database::open_with_wal(enabled(dir.path())) {
        Ok(_) => panic!("recovery should reject the malformed relationship"),
        Err(err) => err,
    };
    assert!(
        err.to_string().contains("missing source node 10"),
        "unexpected recovery error: {err}"
    );
}

#[test]
fn checkpoint_truncates_segments_and_recovery_uses_snapshot() {
    let wal_dir = TmpDir::new("ckpt-wal");
    let snap_dir = TmpDir::new("ckpt-snap");
    let snap_path = snap_dir.path().join("snapshot.bin");

    let db = Database::open_with_wal(enabled(wal_dir.path())).unwrap();
    for i in 0..10 {
        db.execute(&format!("CREATE (:N {{i: {}}})", i), rows())
            .unwrap();
    }

    let meta = db.checkpoint_to(&snap_path).unwrap();
    assert_eq!(meta.node_count, 10);
    assert!(
        meta.wal_lsn.is_some(),
        "checkpoint must stamp a wal_lsn into the snapshot header"
    );

    // Add a couple more mutations after the checkpoint.
    db.execute("CREATE (:N {i: 100})", rows()).unwrap();
    db.execute("CREATE (:N {i: 101})", rows()).unwrap();
    drop(db);

    // Recover from snapshot + WAL. The snapshot covers events
    // 0..=9; the WAL contributes 100, 101.
    let recovered = Database::recover(&snap_path, enabled(wal_dir.path())).unwrap();
    assert_eq!(recovered.node_count(), 12);
}

#[test]
fn group_mode_checkpoint_uses_fsynced_fence() {
    let wal_dir = TmpDir::new("group-ckpt-wal");
    let snap_dir = TmpDir::new("group-ckpt-snap");
    let snap_path = snap_dir.path().join("snapshot.bin");

    {
        let db = Database::open_with_wal(group_enabled(wal_dir.path())).unwrap();
        db.execute("CREATE (:N {i: 1})", rows()).unwrap();
        let meta = db.checkpoint_to(&snap_path).unwrap();
        assert!(
            meta.wal_lsn.unwrap_or_default() > 0,
            "checkpoint should stamp a non-zero WAL fence"
        );
    }

    let recovered = Database::recover(&snap_path, group_enabled(wal_dir.path())).unwrap();
    assert_eq!(recovered.node_count(), 1);
}

#[test]
fn recover_with_missing_snapshot_falls_back_to_wal_only() {
    let wal_dir = TmpDir::new("missing-snap-wal");
    let snap_dir = TmpDir::new("missing-snap-snap");
    let absent = snap_dir.path().join("does-not-exist.bin");

    {
        let db = Database::open_with_wal(enabled(wal_dir.path())).unwrap();
        db.execute("CREATE (:Z {v: 1})", rows()).unwrap();
        db.execute("CREATE (:Z {v: 2})", rows()).unwrap();
    }

    let db = Database::recover(&absent, enabled(wal_dir.path())).unwrap();
    assert_eq!(db.node_count(), 2);
}

#[test]
fn recover_with_disabled_wal_only_loads_snapshot() {
    let snap_dir = TmpDir::new("disabled-recover");
    let snap_path = snap_dir.path().join("seed.bin");

    {
        let db = Database::in_memory();
        db.execute("CREATE (:Seed {x: 1})", rows()).unwrap();
        db.execute("CREATE (:Seed {x: 2})", rows()).unwrap();
        db.save_snapshot_to(&snap_path).unwrap();
    }

    let db = Database::recover(&snap_path, WalConfig::Disabled).unwrap();
    assert_eq!(db.node_count(), 2);
    assert!(db.wal().is_none());
}

#[test]
fn clear_brackets_through_wal() {
    // `Database::clear` must not poison the recorder by firing a
    // `Clear` event with no active transaction.
    let dir = TmpDir::new("clear");

    {
        let db = Database::open_with_wal(enabled(dir.path())).unwrap();
        db.execute("CREATE (:A {v: 1})", rows()).unwrap();
        db.execute("CREATE (:A {v: 2})", rows()).unwrap();
        db.clear();
        assert_eq!(db.node_count(), 0);
        // Subsequent query must succeed — the recorder is not
        // poisoned.
        db.execute("CREATE (:B {v: 3})", rows()).unwrap();
    }

    let db = Database::open_with_wal(enabled(dir.path())).unwrap();
    assert_eq!(db.node_count(), 1);
}

#[test]
fn checkpoint_requires_wal() {
    let snap_dir = TmpDir::new("no-wal-ckpt");
    let snap_path = snap_dir.path().join("snap.bin");

    let db = Database::in_memory();
    let err = db.checkpoint_to(&snap_path).unwrap_err();
    assert!(err.to_string().contains("WAL"));
}