semantic-memory 0.5.1

Local-first hybrid semantic search (SQLite + FTS5 + usearch 2.25) with bitemporal truth and typed receipts
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
//! HNSW persistence tests: keymap survival across reopen, deletion persistence,
//! explicit flush, rebuild, and graceful reopen.
//!
//! Only compiled when the `hnsw` feature is enabled.

#![cfg(feature = "hnsw")]

use semantic_memory::{
    MemoryConfig, MemoryStore, MockEmbedder, SearchSource, SearchSourceType, StoragePaths,
    VerifyMode,
};
use tempfile::TempDir;

fn test_store() -> (MemoryStore, TempDir) {
    let tmp = TempDir::new().unwrap();
    let config = MemoryConfig {
        base_dir: tmp.path().to_path_buf(),
        ..Default::default()
    };
    let embedder = Box::new(MockEmbedder::new(768));
    let store = MemoryStore::open_with_embedder(config, embedder).unwrap();
    (store, tmp)
}

fn reopen_store(base_dir: &std::path::Path) -> MemoryStore {
    let config = MemoryConfig {
        base_dir: base_dir.to_path_buf(),
        ..Default::default()
    };
    let embedder = Box::new(MockEmbedder::new(768));
    MemoryStore::open_with_embedder(config, embedder).unwrap()
}

/// 2.1 — After adding facts, closing, and reopening the store on the same
/// directory, FTS search should still find the persisted facts with correct IDs.
#[tokio::test]
async fn keymap_survives_reopen() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();

    // Collect fact IDs so we can verify one after reopen.
    let mut fact_ids = Vec::new();

    // First open: add 10 facts.
    {
        let store = reopen_store(&base_dir);
        for i in 0..10 {
            let id = store
                .add_fact(
                    "persist",
                    &format!("Persistence fact number {}", i),
                    None,
                    None,
                )
                .await
                .unwrap();
            fact_ids.push(id);
        }
    } // store dropped — should flush to disk

    // Second open: search for one of the facts.
    {
        let store = reopen_store(&base_dir);

        let results = store
            .search_fts_only(
                "Persistence fact number 7",
                Some(10),
                None,
                Some(&[SearchSourceType::Facts]),
            )
            .await
            .unwrap();

        assert!(
            !results.is_empty(),
            "Should find persisted fact after reopen"
        );

        // Verify the correct fact_id is present in results.
        let found_ids: Vec<&str> = results
            .iter()
            .filter_map(|r| match &r.source {
                SearchSource::Fact { fact_id, .. } => Some(fact_id.as_str()),
                _ => None,
            })
            .collect();

        assert!(
            found_ids.contains(&fact_ids[7].as_str()),
            "Expected fact_id {} in results, got {:?}",
            fact_ids[7],
            found_ids
        );
    }
}

/// 2.2 — After adding 10 facts, deleting 3, closing, and reopening, the deleted
/// facts should not appear in search while the remaining ones should.
#[tokio::test]
async fn deletions_survive_reopen() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();

    let mut fact_ids = Vec::new();

    // First open: add 10 facts, delete 3.
    {
        let store = reopen_store(&base_dir);

        for i in 0..10 {
            let id = store
                .add_fact(
                    "deletion",
                    &format!("Deletable fact item {}", i),
                    None,
                    None,
                )
                .await
                .unwrap();
            fact_ids.push(id);
        }

        // Delete facts 0, 1, 2.
        for id in &fact_ids[0..3] {
            store.delete_fact(id).await.unwrap();
        }
    } // store dropped

    // Second open: verify deletions persisted.
    {
        let store = reopen_store(&base_dir);

        // Deleted facts should NOT appear.
        for (i, _fact_id) in fact_ids.iter().enumerate().take(3) {
            let query = format!("Deletable fact item {}", i);
            let results = store
                .search_fts_only(&query, Some(10), None, Some(&[SearchSourceType::Facts]))
                .await
                .unwrap();

            let has_deleted_id = results.iter().any(|r| match &r.source {
                SearchSource::Fact { fact_id, .. } => fact_id == &fact_ids[i],
                _ => false,
            });

            assert!(
                !has_deleted_id,
                "Deleted fact {} should not appear after reopen",
                fact_ids[i]
            );
        }

        // Remaining facts (3..10) should still be findable.
        let results = store
            .search_fts_only(
                "Deletable fact item",
                Some(20),
                None,
                Some(&[SearchSourceType::Facts]),
            )
            .await
            .unwrap();

        assert_eq!(
            results.len(),
            7,
            "Should have exactly 7 remaining facts after deleting 3 of 10"
        );
    }
}

/// 2.3 — After adding facts and calling `flush_hnsw()` explicitly, the facts
/// should remain findable via search.
#[tokio::test]
async fn keymap_flush_on_explicit_flush() {
    let (store, _tmp) = test_store();

    let mut fact_ids = Vec::new();
    for i in 0..5 {
        let id = store
            .add_fact("flush", &format!("Flushed fact entry {}", i), None, None)
            .await
            .unwrap();
        fact_ids.push(id);
    }

    // Explicitly flush HNSW to persist graph + keymap.
    store.flush_hnsw().unwrap();

    // Verify all facts are still findable via FTS after flush.
    let results = store
        .search_fts_only(
            "Flushed fact entry",
            Some(10),
            None,
            Some(&[SearchSourceType::Facts]),
        )
        .await
        .unwrap();

    assert_eq!(
        results.len(),
        5,
        "All 5 facts should be findable after explicit flush_hnsw()"
    );

    // Verify each fact_id appears in results.
    let result_ids: Vec<String> = results
        .iter()
        .filter_map(|r| match &r.source {
            SearchSource::Fact { fact_id, .. } => Some(fact_id.clone()),
            _ => None,
        })
        .collect();

    for id in &fact_ids {
        assert!(
            result_ids.contains(id),
            "Fact {} should be present in search results after flush",
            id
        );
    }
}

/// 2.4 — After adding facts and calling `rebuild_hnsw_index()`, search should
/// still work both before and after a close/reopen cycle.
#[tokio::test]
async fn rebuild_preserves_keymap() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();

    let mut fact_ids = Vec::new();

    // First open: add facts, rebuild, verify search works.
    {
        let store = reopen_store(&base_dir);

        for i in 0..8 {
            let id = store
                .add_fact("rebuild", &format!("Rebuild test fact {}", i), None, None)
                .await
                .unwrap();
            fact_ids.push(id);
        }

        // Rebuild HNSW index from SQLite embeddings.
        store.rebuild_hnsw_index().await.unwrap();

        // Search should still work after rebuild.
        let results = store
            .search_fts_only(
                "Rebuild test fact",
                Some(10),
                None,
                Some(&[SearchSourceType::Facts]),
            )
            .await
            .unwrap();

        assert_eq!(
            results.len(),
            8,
            "All 8 facts should be findable after rebuild_hnsw_index()"
        );
    } // store dropped

    // Second open: search should still work after reopen.
    {
        let store = reopen_store(&base_dir);

        let results = store
            .search_fts_only(
                "Rebuild test fact",
                Some(10),
                None,
                Some(&[SearchSourceType::Facts]),
            )
            .await
            .unwrap();

        assert_eq!(
            results.len(),
            8,
            "All 8 facts should be findable after reopen post-rebuild"
        );

        // Verify a specific fact_id.
        let found_ids: Vec<String> = results
            .iter()
            .filter_map(|r| match &r.source {
                SearchSource::Fact { fact_id, .. } => Some(fact_id.clone()),
                _ => None,
            })
            .collect();

        assert!(
            found_ids.contains(&fact_ids[4]),
            "Fact {} should survive rebuild + reopen cycle",
            fact_ids[4]
        );
    }
}

/// 2.5 — Opening a store on a fresh directory, adding facts, closing, then
/// reopening should not crash regardless of keymap table state.
#[tokio::test]
async fn reopen_with_no_keymap_table_graceful() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();

    // First open: add facts.
    {
        let store = reopen_store(&base_dir);

        for i in 0..3 {
            store
                .add_fact(
                    "graceful",
                    &format!("Graceful reopen fact {}", i),
                    None,
                    None,
                )
                .await
                .unwrap();
        }
    } // store dropped

    // Second open: should not panic or error.
    let store = reopen_store(&base_dir);

    // Verify we can still search (data survived).
    let results = store
        .search_fts_only(
            "Graceful reopen fact",
            Some(10),
            None,
            Some(&[SearchSourceType::Facts]),
        )
        .await
        .unwrap();

    assert_eq!(
        results.len(),
        3,
        "All 3 facts should survive a close/reopen cycle"
    );
}

fn fixed_embedding(seed: f32) -> Vec<f32> {
    let mut embedding = vec![0.0; 768];
    embedding[0] = seed;
    embedding[1] = 1.0 - seed;
    embedding
}

#[cfg(feature = "testing")]
#[tokio::test]
async fn full_integrity_reports_missing_live_hnsw_key() {
    let (store, _tmp) = test_store();
    let fact_id = store
        .add_fact_with_embedding(
            "integrity",
            "missing key target",
            &fixed_embedding(0.25),
            None,
            None,
        )
        .await
        .unwrap();
    store.flush_hnsw().unwrap();

    store
        .raw_execute(
            "DELETE FROM hnsw_keymap WHERE item_key = ?1",
            vec![format!("fact:{fact_id}")],
        )
        .await
        .unwrap();

    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(report.issues.iter().any(|issue| {
        issue.contains("HNSW keymap missing live embedded SQLite row")
            && issue.contains(&format!("fact:{fact_id}"))
    }));
}

#[cfg(feature = "testing")]
#[tokio::test]
async fn full_integrity_reports_stale_or_wrong_domain_hnsw_key() {
    let (store, _tmp) = test_store();
    let fact_id = store
        .add_fact_with_embedding(
            "integrity",
            "wrong domain target",
            &fixed_embedding(0.35),
            None,
            None,
        )
        .await
        .unwrap();
    store.flush_hnsw().unwrap();

    store
        .raw_execute(
            "UPDATE hnsw_keymap SET item_key = ?1 WHERE item_key = ?2",
            vec!["bogus:not-live".to_string(), format!("fact:{fact_id}")],
        )
        .await
        .unwrap();

    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(report.issues.iter().any(|issue| {
        issue.contains("unsupported key domain") && issue.contains("bogus:not-live")
    }));
    assert!(report.issues.iter().any(|issue| {
        issue.contains("HNSW keymap missing live embedded SQLite row")
            && issue.contains(&format!("fact:{fact_id}"))
    }));
}

#[cfg(feature = "testing")]
#[tokio::test]
async fn full_integrity_reports_stale_valid_domain_hnsw_key() {
    let (store, _tmp) = test_store();
    let fact_id = store
        .add_fact_with_embedding(
            "integrity",
            "stale valid domain target",
            &fixed_embedding(0.55),
            None,
            None,
        )
        .await
        .unwrap();
    store.flush_hnsw().unwrap();

    store
        .raw_execute(
            "UPDATE hnsw_keymap SET item_key = ?1 WHERE item_key = ?2",
            vec!["fact:not-live".to_string(), format!("fact:{fact_id}")],
        )
        .await
        .unwrap();

    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(report.issues.iter().any(|issue| {
        issue.contains("stale active entry without live embedded SQLite row")
            && issue.contains("fact:not-live")
    }));
    assert!(report.issues.iter().any(|issue| {
        issue.contains("HNSW keymap missing live embedded SQLite row")
            && issue.contains(&format!("fact:{fact_id}"))
    }));
}

#[cfg(feature = "testing")]
#[tokio::test]
async fn full_integrity_catches_swapped_hnsw_key_ids_when_counts_match() {
    let (store, _tmp) = test_store();
    let first_id = store
        .add_fact_with_embedding(
            "integrity",
            "first swapped vector target",
            &fixed_embedding(0.10),
            None,
            None,
        )
        .await
        .unwrap();
    let second_id = store
        .add_fact_with_embedding(
            "integrity",
            "second swapped vector target",
            &fixed_embedding(0.90),
            None,
            None,
        )
        .await
        .unwrap();
    store.flush_hnsw().unwrap();

    let first_key = format!("fact:{first_id}");
    let second_key = format!("fact:{second_id}");
    let temporary_key = format!("fact:{first_id}-swap-temp");
    store
        .raw_execute(
            "UPDATE hnsw_keymap SET item_key = ?1 WHERE item_key = ?2",
            vec![temporary_key.clone(), first_key.clone()],
        )
        .await
        .unwrap();
    store
        .raw_execute(
            "UPDATE hnsw_keymap SET item_key = ?1 WHERE item_key = ?2",
            vec![first_key.clone(), second_key.clone()],
        )
        .await
        .unwrap();
    store
        .raw_execute(
            "UPDATE hnsw_keymap SET item_key = ?1 WHERE item_key = ?2",
            vec![second_key.clone(), temporary_key],
        )
        .await
        .unwrap();

    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.issues.iter().any(|issue| {
            issue.contains("vector does not match the authoritative SQLite embedding")
                && (issue.contains(&first_key) || issue.contains(&second_key))
        }),
        "expected swapped key/vector mismatch, got {:?}",
        report.issues
    );
    assert!(
        !report
            .issues
            .iter()
            .any(|issue| issue.contains("HNSW keymap drift:")),
        "count parity should remain intact for this corruption: {:?}",
        report.issues
    );
}

#[tokio::test]
async fn unsupported_hnsw_sidecar_version_rebuilds_from_sqlite_on_reopen() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();
    let fact_id;

    {
        let store = reopen_store(&base_dir);
        fact_id = store
            .add_fact_with_embedding(
                "integrity",
                "unsupported sidecar version target",
                &fixed_embedding(0.45),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    let mut graph_bytes = std::fs::read(paths.hnsw_graph_path()).unwrap();
    graph_bytes[4..6].copy_from_slice(&99u16.to_le_bytes());
    std::fs::write(paths.hnsw_graph_path(), graph_bytes).unwrap();

    let store = reopen_store(&base_dir);
    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.ok,
        "reopen should rebuild unsupported HNSW sidecar from SQLite: {:?}",
        report.issues
    );

    let results = store
        .search_fts_only(
            "unsupported sidecar version target",
            Some(5),
            None,
            Some(&[SearchSourceType::Facts]),
        )
        .await
        .unwrap();
    assert!(results.iter().any(|result| {
        matches!(
            &result.source,
            SearchSource::Fact { fact_id: found, .. } if found == &fact_id
        )
    }));
}

#[tokio::test]
async fn wrong_hnsw_sidecar_dimension_rebuilds_from_sqlite_on_reopen() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();

    {
        let store = reopen_store(&base_dir);
        store
            .add_fact_with_embedding(
                "integrity",
                "wrong sidecar dimension target",
                &fixed_embedding(0.65),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    let mut data_bytes = std::fs::read(paths.hnsw_data_path()).unwrap();
    data_bytes[8..12].copy_from_slice(&123u32.to_le_bytes());
    std::fs::write(paths.hnsw_data_path(), data_bytes).unwrap();

    let store = reopen_store(&base_dir);
    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.ok,
        "reopen should rebuild wrong-dimension HNSW sidecar from SQLite: {:?}",
        report.issues
    );
}

#[tokio::test]
async fn hnsw_manifest_written_after_graph_and_data() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();
    {
        let store = reopen_store(&base_dir);
        store
            .add_fact_with_embedding(
                "integrity",
                "manifest written target",
                &fixed_embedding(0.42),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    assert!(paths.hnsw_graph_path().exists());
    assert!(paths.hnsw_data_path().exists());
    assert!(paths.hnsw_manifest_path().exists());

    let manifest: serde_json::Value =
        serde_json::from_slice(&std::fs::read(paths.hnsw_manifest_path()).unwrap()).unwrap();
    assert_eq!(manifest["schema_version"], 1);
    assert_eq!(manifest["basename"], "memory");
    assert_eq!(manifest["graph_file_name"], "memory.hnsw.graph");
    assert_eq!(manifest["data_file_name"], "memory.hnsw.data");
    assert_eq!(manifest["dimensions"], 768);
    assert_eq!(manifest["vector_count"], 1);
    assert!(manifest["graph_digest"]
        .as_str()
        .unwrap()
        .starts_with("blake3:"));
    assert!(manifest["data_digest"]
        .as_str()
        .unwrap()
        .starts_with("blake3:"));
}

#[tokio::test]
async fn hnsw_manifest_graph_digest_mismatch_rebuilds_from_sqlite() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();
    let fact_id;
    {
        let store = reopen_store(&base_dir);
        fact_id = store
            .add_fact_with_embedding(
                "integrity",
                "graph digest mismatch target",
                &fixed_embedding(0.11),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    let mut graph = std::fs::read(paths.hnsw_graph_path()).unwrap();
    graph.push(0xff);
    std::fs::write(paths.hnsw_graph_path(), graph).unwrap();

    let store = reopen_store(&base_dir);
    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.ok,
        "graph digest mismatch should rebuild from SQLite: {:?}",
        report.issues
    );
    let results = store
        .search_fts_only(
            "graph digest mismatch target",
            Some(5),
            None,
            Some(&[SearchSourceType::Facts]),
        )
        .await
        .unwrap();
    assert!(results.iter().any(|result| {
        matches!(
            &result.source,
            SearchSource::Fact { fact_id: found, .. } if found == &fact_id
        )
    }));
}

#[tokio::test]
async fn hnsw_manifest_data_digest_mismatch_rebuilds_from_sqlite() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();
    {
        let store = reopen_store(&base_dir);
        store
            .add_fact_with_embedding(
                "integrity",
                "data digest mismatch target",
                &fixed_embedding(0.21),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    let mut data = std::fs::read(paths.hnsw_data_path()).unwrap();
    let last = data.len().saturating_sub(1);
    data[last] ^= 0xff;
    std::fs::write(paths.hnsw_data_path(), data).unwrap();

    let store = reopen_store(&base_dir);
    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.ok,
        "data digest mismatch should rebuild from SQLite: {:?}",
        report.issues
    );
}

#[tokio::test]
async fn hnsw_manifest_points_to_missing_file_rebuilds_from_sqlite() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();
    {
        let store = reopen_store(&base_dir);
        store
            .add_fact_with_embedding(
                "integrity",
                "manifest missing file target",
                &fixed_embedding(0.31),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    let mut manifest: serde_json::Value =
        serde_json::from_slice(&std::fs::read(paths.hnsw_manifest_path()).unwrap()).unwrap();
    manifest["data_file_name"] = serde_json::Value::String("missing.hnsw.data".to_string());
    std::fs::write(
        paths.hnsw_manifest_path(),
        serde_json::to_vec_pretty(&manifest).unwrap(),
    )
    .unwrap();

    let store = reopen_store(&base_dir);
    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.ok,
        "manifest file mismatch should rebuild from SQLite: {:?}",
        report.issues
    );
}

#[tokio::test]
async fn legacy_hnsw_sidecar_without_manifest_loads_deterministically() {
    let tmp = TempDir::new().unwrap();
    let base_dir = tmp.path().to_path_buf();
    {
        let store = reopen_store(&base_dir);
        store
            .add_fact_with_embedding(
                "integrity",
                "legacy no manifest target",
                &fixed_embedding(0.41),
                None,
                None,
            )
            .await
            .unwrap();
        store.flush_hnsw().unwrap();
    }

    let paths = StoragePaths::new(&base_dir);
    std::fs::remove_file(paths.hnsw_manifest_path()).unwrap();

    let store = reopen_store(&base_dir);
    let report = store.verify_integrity(VerifyMode::Full).await.unwrap();
    assert!(
        report.ok,
        "legacy no-manifest sidecar should load or rebuild deterministically: {:?}",
        report.issues
    );
}