grit-core 0.2.4

Embedded, bi-temporal property graph for agent memory: one SQLite file, in-process, deterministic
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
//! Migration tests (Design Invariant 8): open + migrate fixture databases
//! frozen from every released schema version. `fixtures/v1.db` was generated
//! at v0.1.0 (deterministic content touching every table) and must stay
//! openable by every future release; `fixtures/v2.db` was frozen at v0.2.0
//! by `generate_v2_fixture` below (run with `-- --ignored` once per release;
//! it refuses to overwrite an existing fixture).
//!
//! When SCHEMA_VERSION grows: add the migration, freeze a new fixture, and
//! add a case here — never edit an existing fixture.

use std::sync::Arc;

use grit_core::{Budget, Grit, ManualClock, Options, Query, Traversal};
use uuid::Uuid;

fn open_fixture_copy(dir: &tempfile::TempDir, name: &str) -> Grit {
    // Fixtures are immutable artifacts; work on a copy (opening creates WAL
    // sidecars and a future version would migrate in place).
    let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name);
    let dst = dir.path().join(name);
    std::fs::copy(&src, &dst).unwrap();
    Grit::open(
        &dst,
        Options::new("migration-test").clock(Arc::new(ManualClock::new(2_000_000))),
    )
    .unwrap()
}

#[test]
fn v1_fixture_opens_and_reads() {
    let dir = tempfile::tempdir().unwrap();
    let g = open_fixture_copy(&dir, "v1.db");

    // Exact counts frozen with the fixture.
    let stats = g.stats().unwrap();
    assert_eq!(
        (
            stats.nodes,
            stats.edges,
            stats.episodes,
            stats.mentions,
            stats.oplog,
            stats.purged
        ),
        (5, 2, 1, 2, 12, 1)
    );

    // The graph is queryable: FTS, traversal, provenance, bi-temporal state.
    let hits = g
        .search(Query::text("fixtures").budget(Budget::items(5)))
        .unwrap();
    assert!(!hits.is_empty(), "episode content must be FTS-searchable");

    let n0 = Uuid::from_u128(1);
    let sub = g.traverse(&[n0], &Traversal::default().depth(1)).unwrap();
    assert_eq!(sub.edges.len(), 1, "n0 -R-> n1 must survive");
    assert_eq!(g.mentions_of(n0).unwrap().len(), 1);

    // Merge audit pointer and purge tombstone survived.
    let merged = g.node(Uuid::from_u128(6)).unwrap().unwrap();
    assert_eq!(merged.merged_into, Some(Uuid::from_u128(5)));
    assert!(
        g.node(Uuid::from_u128(4)).unwrap().is_none(),
        "purged node stays gone"
    );

    // The invalidated edge is belief-versioned: gone now, present before the
    // invalidation was recorded.
    let e2 = Uuid::from_u128(0x101);
    let edge = g.edge(e2).unwrap().unwrap();
    assert_eq!(edge.invalid_at, Some(1_000_500));

    // The v1 file migrated up to head on open.
    assert_eq!(grit_core::SCHEMA_VERSION, 5);

    // v5 rebuilds the vec tables with a group_id partition; the one vector
    // frozen in the v1 fixture (node n0, group g0, dim 4) must survive the
    // stash-and-recreate round trip...
    let vec = g.get_node_embedding(n0).unwrap();
    assert_eq!(
        vec.as_ref().map(Vec::len),
        Some(4),
        "the v1 fixture's vector must survive the v5 rebuild"
    );

    // And new writes still work post-open — including v2's UpdateNode
    // against the migration-created node_updates table.
    g.apply(grit_core::GraphOp::AddNode {
        id: g.new_id(),
        kind: "k".into(),
        name: "post-migration write".into(),
        summary: String::new(),
        attrs: serde_json::json!({}),
        group_id: String::new(),
    })
    .unwrap();
    assert_eq!(g.stats().unwrap().nodes, 6);
    g.apply(grit_core::GraphOp::UpdateNode {
        id: n0,
        name: None,
        summary: Some("post-migration summary".into()),
        kind: None,
        attrs: None,
    })
    .unwrap();
    assert_eq!(
        g.node(n0).unwrap().unwrap().summary,
        "post-migration summary"
    );

    // ...and the rebuilt vector lands in its node's partition (raw SQL —
    // partition placement is a migration guarantee, same precedent as the
    // trigram rebuild check in the v3 test).
    drop(g);
    let conn = rusqlite::Connection::open(dir.path().join("v1.db")).unwrap();
    let group: String = conn
        .query_row(
            "SELECT group_id FROM vec_nodes WHERE id = ?1",
            [n0.to_string()],
            |r| r.get(0),
        )
        .unwrap();
    assert_eq!(group, "g0", "migrated vector must carry its node's group");
}

/// Deterministic v2 fixture content: every table touched, including the
/// v2 node_updates machinery (a folded update AND a pending update whose
/// node never arrived). Shared by the generator and the assertions.
fn build_v2_content(g: &Grit) {
    use grit_core::GraphOp;
    let n = |i: u128| Uuid::from_u128(i);
    let e = |i: u128| Uuid::from_u128(0x100 + i);
    let ep = |i: u128| Uuid::from_u128(0x200 + i);
    for i in 1..=4u128 {
        g.apply(GraphOp::AddNode {
            id: n(i),
            kind: "k".into(),
            name: format!("node-{i}"),
            summary: String::new(),
            attrs: serde_json::json!({"i": i}),
            group_id: "g".into(),
        })
        .unwrap();
    }
    g.apply(GraphOp::AddEdge {
        id: e(1),
        src: n(1),
        dst: n(2),
        rel: "R".into(),
        fact: "node-1 relates to node-2".into(),
        attrs: serde_json::json!({}),
        group_id: "g".into(),
        valid_at: Some(1_000_000),
        invalid_at: None,
    })
    .unwrap();
    g.apply(GraphOp::AddEpisode {
        id: ep(1),
        source: "fixtures".into(),
        kind: String::new(),
        content: "episode exercising the v2 fixture tables".into(),
        occurred_at: 1_000_100,
        group_id: "g".into(),
        mentions: vec![n(1), e(1)],
    })
    .unwrap();
    g.apply(GraphOp::InvalidateEdge {
        edge_id: e(1),
        invalid_at: 1_000_500,
    })
    .unwrap();
    // v2: a folded update on a live node...
    g.apply(GraphOp::UpdateNode {
        id: n(1),
        name: Some("node-1 promoted".into()),
        summary: Some("updated summary".into()),
        kind: None,
        attrs: None,
    })
    .unwrap();
    // ...and a pending update whose node never arrives (out-of-order sync).
    g.apply(GraphOp::UpdateNode {
        id: n(9),
        name: None,
        summary: Some("pending until node-9 lands".into()),
        kind: None,
        attrs: None,
    })
    .unwrap();
    g.apply(GraphOp::MergeNodes {
        from: n(3),
        into: n(2),
    })
    .unwrap();
    g.apply(GraphOp::Purge { ids: vec![n(4)] }).unwrap();
    g.register_embedding_model("fixture-model", 4, "1").unwrap();
}

fn assert_v2_content(g: &Grit) {
    let n1 = Uuid::from_u128(1);
    let node = g.node(n1).unwrap().unwrap();
    assert_eq!(node.name, "node-1 promoted");
    assert_eq!(node.summary, "updated summary");
    assert_eq!(node.kind, "k", "untouched field keeps AddNode base");
    let merged = g.node(Uuid::from_u128(3)).unwrap().unwrap();
    assert_eq!(merged.merged_into, Some(Uuid::from_u128(2)));
    assert!(g.node(Uuid::from_u128(4)).unwrap().is_none());
    assert_eq!(
        g.edge(Uuid::from_u128(0x101)).unwrap().unwrap().invalid_at,
        Some(1_000_500)
    );
    // The updated name reaches FTS.
    let hits = g
        .search(Query::text("promoted").budget(Budget::items(5)))
        .unwrap();
    assert!(!hits.is_empty(), "updated node name must be FTS-searchable");
}

#[test]
fn v2_fixture_opens_and_reads() {
    let dir = tempfile::tempdir().unwrap();
    let g = open_fixture_copy(&dir, "v2.db");
    assert_v2_content(&g);
    // v3's episodes.kind backfills empty on migration.
    let eps = g.episodes_in_group("g").unwrap();
    assert_eq!(eps.len(), 1);
    assert_eq!(eps[0].kind, "", "pre-v3 episode gets the '' default");
    // The pending update folds when its node finally arrives.
    let n9 = Uuid::from_u128(9);
    g.apply(grit_core::GraphOp::AddNode {
        id: n9,
        kind: "k".into(),
        name: "node-9".into(),
        summary: String::new(),
        attrs: serde_json::json!({}),
        group_id: "g".into(),
    })
    .unwrap();
    assert_eq!(
        g.node(n9).unwrap().unwrap().summary,
        "pending until node-9 lands"
    );

    // The freeze went through export → import, which carries embedding_meta
    // but no vec tables (vectors are recomputable local state). Before v5,
    // re-registering the model never recreated the tables, so an imported
    // file could never store vectors again; registration now repairs them.
    let n1 = Uuid::from_u128(1);
    g.register_embedding_model("fixture-model", 4, "1").unwrap();
    g.set_node_embedding(n1, vec![1.0, 0.0, 0.0, 0.0]).unwrap();
    assert_eq!(
        g.get_node_embedding(n1).unwrap(),
        Some(vec![1.0, 0.0, 0.0, 0.0])
    );
}

/// v4 → v5 rebuilds existing vec tables with a `group_id` partition key. No
/// released fixture carries multi-group vector data (vectors are never
/// exported; v1.db froze exactly one), so this builds a CURRENT database and
/// surgically downgrades its vec tables to the v4 shape — raw SQL on frozen
/// DDL, the same "peek under the API" allowance the trigram rebuild check
/// uses.
#[test]
fn v4_vec_tables_rebuild_into_group_partitions() {
    fn f32s(v: &[f32]) -> Vec<u8> {
        v.iter().flat_map(|x| x.to_le_bytes()).collect()
    }
    use grit_core::GraphOp;

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("v4vec.db");
    let clock = Arc::new(ManualClock::new(1_000_000));
    let g = Grit::open(&path, Options::new("v4vec").clock(clock.clone())).unwrap();

    let a1 = Uuid::from_u128(1);
    let a2 = Uuid::from_u128(2);
    let b1 = Uuid::from_u128(3);
    let ea = Uuid::from_u128(0x100);
    for (id, name, group) in [
        (a1, "alpha-1", "a"),
        (a2, "alpha-2", "a"),
        (b1, "beta-1", "b"),
    ] {
        g.apply(GraphOp::AddNode {
            id,
            kind: "k".into(),
            name: name.into(),
            summary: String::new(),
            attrs: serde_json::json!({}),
            group_id: group.into(),
        })
        .unwrap();
    }
    g.apply(GraphOp::AddEdge {
        id: ea,
        src: a1,
        dst: a2,
        rel: "R".into(),
        fact: "alpha-1 relates to alpha-2".into(),
        attrs: serde_json::json!({}),
        group_id: "a".into(),
        valid_at: None,
        invalid_at: None,
    })
    .unwrap();
    g.register_embedding_model("m", 4, "1").unwrap();
    drop(g);

    // Downgrade: recreate the vec tables exactly as register_model wrote
    // them at v4 (no partition key), refill them — including an orphan row
    // whose base node never existed — and stamp the file v4.
    let conn = rusqlite::Connection::open(&path).unwrap();
    conn.execute_batch(
        "DROP TABLE vec_nodes;
         DROP TABLE vec_edges;
         CREATE VIRTUAL TABLE vec_nodes USING vec0(
             id TEXT PRIMARY KEY, embedding FLOAT[4] distance_metric=cosine);
         CREATE VIRTUAL TABLE vec_edges USING vec0(
             id TEXT PRIMARY KEY, embedding FLOAT[4] distance_metric=cosine);",
    )
    .unwrap();
    let orphan = Uuid::from_u128(0xdead);
    for (id, vec) in [
        (a1, [0.0f32, 1.0, 0.0, 0.0]),
        (a2, [0.0, 0.9, 0.1, 0.0]),
        (b1, [1.0, 0.0, 0.0, 0.0]),
        (orphan, [0.5, 0.5, 0.0, 0.0]),
    ] {
        conn.execute(
            "INSERT INTO vec_nodes (id, embedding) VALUES (?1, ?2)",
            rusqlite::params![id.to_string(), f32s(&vec)],
        )
        .unwrap();
    }
    conn.execute(
        "INSERT INTO vec_edges (id, embedding) VALUES (?1, ?2)",
        rusqlite::params![ea.to_string(), f32s(&[0.0, 1.0, 0.0, 0.0])],
    )
    .unwrap();
    conn.pragma_update(None, "user_version", 4).unwrap();
    drop(conn);

    // Reopen: the v5 step stashes, recreates, and refills the tables.
    let g = Grit::open(&path, Options::new("v4vec").clock(clock)).unwrap();
    assert_eq!(
        g.get_node_embedding(a1).unwrap(),
        Some(vec![0.0, 1.0, 0.0, 0.0]),
        "node vector must survive the rebuild"
    );
    assert_eq!(
        g.get_edge_embedding(ea).unwrap(),
        Some(vec![0.0, 1.0, 0.0, 0.0]),
        "edge vector must survive the rebuild"
    );
    assert_eq!(
        g.get_node_embedding(orphan).unwrap(),
        None,
        "orphan vectors (no base row) are dropped by the rebuild join"
    );

    // The migrated vectors are partitioned: a probe pointing straight at
    // b1's vector, searched in group "a", must surface the a-nodes (before
    // v5 the leg was a global top-k and the group filter came too late).
    let hits = g
        .search(
            Query::text("")
                .vector(vec![1.0, 0.0, 0.0, 0.0])
                .group("a")
                .budget(Budget::items(5)),
        )
        .unwrap();
    let node_ids: Vec<Uuid> = hits
        .iter()
        .filter_map(|h| match &h.target {
            grit_core::SearchTarget::Node(n) => Some(n.id),
            _ => None,
        })
        .collect();
    assert!(
        node_ids.contains(&a1) && node_ids.contains(&a2),
        "group-a nodes must be reachable through the partitioned vector leg, got {node_ids:?}"
    );
    assert!(
        !node_ids.contains(&b1),
        "group-b results must not leak into a group-a search"
    );
}

/// Deterministic v3 fixture content: the v2 content plus an episode
/// carrying a non-empty source-kind tag (the v3 column).
fn build_v3_content(g: &Grit) {
    build_v2_content(g);
    g.apply(grit_core::GraphOp::AddEpisode {
        id: Uuid::from_u128(0x202),
        source: "doc:profile.md".into(),
        kind: "text".into(),
        content: "a document-chunk episode exercising the v3 kind column".into(),
        occurred_at: 1_000_200,
        group_id: "g".into(),
        mentions: vec![Uuid::from_u128(1)],
    })
    .unwrap();
}

fn assert_v3_content(g: &Grit) {
    assert_v2_content(g);
    let eps = g.episodes_in_group("g").unwrap();
    assert_eq!(eps.len(), 2);
    assert_eq!(eps[0].kind, "", "v2-era episode keeps the '' default");
    assert_eq!(eps[1].kind, "text", "v3 kind round-trips");
    assert_eq!(eps[1].source, "doc:profile.md");
}

#[test]
fn v3_fixture_opens_and_reads() {
    let dir = tempfile::tempdir().unwrap();
    let g = open_fixture_copy(&dir, "v3.db");
    assert_v3_content(&g);

    // v4's migration must REBUILD the trigram mirrors from rows that
    // existed before the tables did. Search-level fusion has its own
    // tests; this asserts the migration mechanics directly (raw SQL —
    // the one place tests peek under the public API, because rebuild
    // correctness is a migration guarantee, not a search feature).
    drop(g);
    let conn = rusqlite::Connection::open(dir.path().join("v3.db")).unwrap();
    let hits: i64 = conn
        .query_row(
            "SELECT count(*) FROM nodes_fts_tri WHERE nodes_fts_tri MATCH 'promoted'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert!(hits >= 1, "trigram rebuild must index pre-v4 rows");
    let ep_hits: i64 = conn
        .query_row(
            "SELECT count(*) FROM episodes_fts_tri WHERE episodes_fts_tri MATCH 'fixture'",
            [],
            |r| r.get(0),
        )
        .unwrap();
    assert!(
        ep_hits >= 1,
        "episode trigram rebuild must index pre-v4 rows"
    );
}

/// Deterministic v4 fixture content: the v3 content plus CJK rows, so the
/// frozen artifact exercises trigram indexing of Han text forever.
fn build_v4_content(g: &Grit) {
    build_v3_content(g);
    use grit_core::GraphOp;
    let li = Uuid::from_u128(0x20);
    let bd = Uuid::from_u128(0x21);
    for (id, name) in [(li, "李雷"), (bd, "字节跳动")] {
        g.apply(GraphOp::AddNode {
            id,
            kind: "k".into(),
            name: name.into(),
            summary: String::new(),
            attrs: serde_json::json!({}),
            group_id: "g".into(),
        })
        .unwrap();
    }
    g.apply(GraphOp::AddEdge {
        id: Uuid::from_u128(0x120),
        src: li,
        dst: bd,
        rel: "WORKS_AT".into(),
        fact: "李雷在字节跳动担任数据工程师".into(),
        attrs: serde_json::json!({}),
        group_id: "g".into(),
        valid_at: Some(1_000_300),
        invalid_at: None,
    })
    .unwrap();
    g.apply(GraphOp::AddEpisode {
        id: Uuid::from_u128(0x203),
        source: "chat".into(),
        kind: "message".into(),
        content: "李雷说他在字节跳动的新工作很充实".into(),
        occurred_at: 1_000_300,
        group_id: "g".into(),
        mentions: vec![li],
    })
    .unwrap();
}

fn assert_v4_content(g: &Grit) {
    // v2 core content (assert_v3_content pins episodes.len() == 2, which
    // the v4 fixture's extra CJK episode outgrows — assert the v3 kinds
    // inline instead).
    assert_v2_content(g);
    let eps = g.episodes_in_group("g").unwrap();
    assert_eq!(eps.len(), 3);
    assert_eq!(eps[0].kind, "", "v2-era episode keeps the '' default");
    assert_eq!(eps[1].kind, "text");
    assert_eq!(eps[2].kind, "message");
    assert_eq!(eps[2].content, "李雷说他在字节跳动的新工作很充实");
    let li = g.node(Uuid::from_u128(0x20)).unwrap().unwrap();
    assert_eq!(li.name, "李雷");
    assert_eq!(
        g.edge(Uuid::from_u128(0x120)).unwrap().unwrap().fact,
        "李雷在字节跳动担任数据工程师"
    );
}

#[test]
fn v4_fixture_opens_and_reads() {
    let dir = tempfile::tempdir().unwrap();
    let g = open_fixture_copy(&dir, "v4.db");
    assert_v4_content(&g);
    // The frozen CJK content is reachable through the public search API —
    // the trigram mirrors survive the export → import freeze.
    let hits = g
        .search(Query::text("字节跳动").group("g").budget(Budget::items(5)))
        .unwrap();
    assert!(!hits.is_empty(), "frozen CJK content must be searchable");
}

/// One-time fixture freeze for a release; run manually:
/// `cargo test -p grit-core --test migration -- --ignored`.
#[test]
#[ignore = "fixture generator — run once per released schema version"]
fn generate_v2_fixture() {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/v2.db");
    assert!(
        !path.exists(),
        "fixtures are frozen artifacts — never regenerate {}",
        path.display()
    );
    let dir = tempfile::tempdir().unwrap();
    let work = dir.path().join("v2.db");
    let g = Grit::open(
        &work,
        Options::new("fixture-v2").clock(Arc::new(ManualClock::new(1_000_000))),
    )
    .unwrap();
    build_v2_content(&g);
    assert_v2_content(&g);
    // Freeze via export → import: a live Grit's WAL sidecar holds recent
    // writes, so copying the bare .db would lose them; import_jsonl builds
    // the fixture with one short-lived connection whose close checkpoints
    // the WAL, and export/import losslessness is itself under test
    // (basic.rs::export_import_roundtrip_is_lossless).
    let mut stream = Vec::new();
    g.export_jsonl(&mut stream).unwrap();
    grit_core::import_jsonl(&path, stream.as_slice()).unwrap();
    // Prove the frozen .db is complete on its own (the copy leaves any
    // sidecar behind, mirroring how tests consume fixtures).
    let check = tempfile::tempdir().unwrap();
    let g2 = open_fixture_copy(&check, "v2.db");
    assert_v2_content(&g2);
}

/// One-time fixture freeze for grit 0.2.3 (schema v4); run manually:
/// `cargo test -p grit-core --test migration -- --ignored`.
#[test]
#[ignore = "fixture generator — run once per released schema version"]
fn generate_v4_fixture() {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/v4.db");
    assert!(
        !path.exists(),
        "fixtures are frozen artifacts — never regenerate {}",
        path.display()
    );
    let dir = tempfile::tempdir().unwrap();
    let work = dir.path().join("v4.db");
    let g = Grit::open(
        &work,
        Options::new("fixture-v4").clock(Arc::new(ManualClock::new(1_000_000))),
    )
    .unwrap();
    build_v4_content(&g);
    assert_v4_content(&g);
    let mut stream = Vec::new();
    g.export_jsonl(&mut stream).unwrap();
    grit_core::import_jsonl(&path, stream.as_slice()).unwrap();
    let check = tempfile::tempdir().unwrap();
    let g2 = open_fixture_copy(&check, "v4.db");
    assert_v4_content(&g2);
}

/// Deterministic v5 fixture content: the v4 content plus stored vectors.
/// The export → import freeze deliberately drops the vectors (recomputable
/// local state, never exported) — setting them here exercises the v5
/// partitioned write path in the generator; the frozen artifact proves the
/// graph + embedding_meta side.
fn build_v5_content(g: &Grit) {
    build_v4_content(g);
    g.set_node_embedding(Uuid::from_u128(1), vec![1.0, 0.0, 0.0, 0.0])
        .unwrap();
    g.set_edge_embedding(Uuid::from_u128(0x120), vec![0.0, 1.0, 0.0, 0.0])
        .unwrap();
}

fn assert_v5_content(g: &Grit) {
    // The graph side is the v4 content; vectors never survive the freeze.
    assert_v4_content(g);
}

#[test]
fn v5_fixture_opens_and_reads() {
    let dir = tempfile::tempdir().unwrap();
    let g = open_fixture_copy(&dir, "v5.db");
    assert_v5_content(&g);
    // The frozen artifact carries embedding_meta but no vec tables (see
    // build_v5_content); registration recreates them partitioned, and the
    // group-filtered vector leg reaches re-embedded content.
    let n1 = Uuid::from_u128(1);
    g.register_embedding_model("fixture-model", 4, "1").unwrap();
    g.set_node_embedding(n1, vec![0.5, 0.5, 0.0, 0.0]).unwrap();
    let hits = g
        .search(
            Query::text("")
                .vector(vec![0.5, 0.5, 0.0, 0.0])
                .group("g")
                .budget(Budget::items(3)),
        )
        .unwrap();
    assert!(
        hits.iter().any(|h| match &h.target {
            grit_core::SearchTarget::Node(n) => n.id == n1,
            _ => false,
        }),
        "re-embedded node must be reachable through the partitioned vector leg"
    );
}

/// One-time fixture freeze for grit 0.2.4 (schema v5); run manually:
/// `cargo test -p grit-core --test migration -- --ignored`.
#[test]
#[ignore = "fixture generator — run once per released schema version"]
fn generate_v5_fixture() {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/v5.db");
    assert!(
        !path.exists(),
        "fixtures are frozen artifacts — never regenerate {}",
        path.display()
    );
    let dir = tempfile::tempdir().unwrap();
    let work = dir.path().join("v5.db");
    let g = Grit::open(
        &work,
        Options::new("fixture-v5").clock(Arc::new(ManualClock::new(1_000_000))),
    )
    .unwrap();
    build_v5_content(&g);
    assert_v5_content(&g);
    let mut stream = Vec::new();
    g.export_jsonl(&mut stream).unwrap();
    grit_core::import_jsonl(&path, stream.as_slice()).unwrap();
    let check = tempfile::tempdir().unwrap();
    let g2 = open_fixture_copy(&check, "v5.db");
    assert_v5_content(&g2);
}

/// One-time fixture freeze for grit 0.2.2 (schema v3); run manually:
/// `cargo test -p grit-core --test migration -- --ignored`.
#[test]
#[ignore = "fixture generator — run once per released schema version"]
fn generate_v3_fixture() {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/v3.db");
    assert!(
        !path.exists(),
        "fixtures are frozen artifacts — never regenerate {}",
        path.display()
    );
    let dir = tempfile::tempdir().unwrap();
    let work = dir.path().join("v3.db");
    let g = Grit::open(
        &work,
        Options::new("fixture-v3").clock(Arc::new(ManualClock::new(1_000_000))),
    )
    .unwrap();
    build_v3_content(&g);
    assert_v3_content(&g);
    let mut stream = Vec::new();
    g.export_jsonl(&mut stream).unwrap();
    grit_core::import_jsonl(&path, stream.as_slice()).unwrap();
    let check = tempfile::tempdir().unwrap();
    let g2 = open_fixture_copy(&check, "v3.db");
    assert_v3_content(&g2);
}