macrame-db 0.7.0

A Bitemporal Graph Ledger on libSQL · Embedded knowledge database
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
#[path = "common/harness.rs"]
mod harness;

use harness::TestHarness;
use macrame::error::DbError;
use macrame::integrity::{audit_current, rebuild_current};
use macrame::schema::migrations;

#[tokio::test]
async fn test_schema_initialization_and_version() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();

    migrations::run(&conn).await.unwrap();

    let version: u32 = conn
        .query("PRAGMA user_version", ())
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();

    assert_eq!(version, macrame::schema::SCHEMA_VERSION);
}

#[tokio::test]
async fn test_trg_links_current_sync() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    // Insert concepts
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'Node 1', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    )
    .await
    .unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c2', 'Node 2', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    )
    .await
    .unwrap();

    // Insert link assertion
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    )
    .await
    .unwrap();

    // Verify automatic sync into links_current
    let mut rows = conn
        .query(
            "SELECT source_id, target_id, edge_type FROM links_current WHERE source_id = 'c1'",
            (),
        )
        .await
        .unwrap();
    let row = rows.next().await.unwrap().unwrap();
    let src: String = row.get(0).unwrap();
    let tgt: String = row.get(1).unwrap();
    let edge_type: String = row.get(2).unwrap();

    assert_eq!(src, "c1");
    assert_eq!(tgt, "c2");
    assert_eq!(edge_type, "KNOWS");

    // Verify transaction_log entry
    let log_count: i64 = conn
        .query(
            "SELECT COUNT(*) FROM transaction_log WHERE table_name = 'links'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(log_count, 1);
}

#[tokio::test]
async fn test_trg_links_single_open_violation() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'Node 1', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c2', 'Node 2', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // First open interval
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // Second open interval with distinct valid_from must be rejected by trg_links_single_open
    let res = conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-02-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-02-01T00:00:00.000000Z')",
        (),
    ).await;

    assert!(res.is_err());
    let err_str = res.err().unwrap().to_string();
    assert!(
        err_str.contains("open interval"),
        "Expected single open interval error, got: {err_str}"
    );
}

#[tokio::test]
async fn test_trg_concepts_monotonic_ra_violation() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'Original Title', '2026-01-01T00:00:00.000000Z', '2026-01-01T12:00:00.000000Z')",
        (),
    ).await.unwrap();

    // Attempt non-advancing recorded_at update
    let res = conn.execute(
        "UPDATE concepts SET title = 'Updated Title', recorded_at = '2026-01-01T10:00:00.000000Z' WHERE id = 'c1'",
        (),
    ).await;

    assert!(res.is_err());
    let err_str = res.err().unwrap().to_string();
    assert!(
        err_str.contains("strictly increasing"),
        "Expected monotonic recorded_at error, got: {err_str}"
    );
}

#[tokio::test]
async fn test_delete_guard_triggers() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'Title', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // Concepts are never physically archived (D-022): the guard is unconditional.
    let res = conn
        .execute("DELETE FROM concepts WHERE id = 'c1'", ())
        .await;
    assert!(res.is_err());
    let err_str = res.err().unwrap().to_string();
    assert!(
        err_str.contains("never physically archived"),
        "Expected unconditional concepts delete guard, got: {err_str}"
    );

    // BEFORE DELETE is a *row* trigger: it cannot fire on an empty table, so
    // both guarded tables need at least one row for this to prove anything.
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c2', 'Title', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // links and transaction_log are guarded by the archive-session marker.
    for table in ["links", "transaction_log"] {
        let res = conn.execute(&format!("DELETE FROM {table}"), ()).await;
        assert!(res.is_err(), "{table} delete should be blocked");
        let err_str = res.err().unwrap().to_string();
        assert!(
            err_str.contains("outside archive session"),
            "Expected archive-session guard on {table}, got: {err_str}"
        );
    }
}

/// D-008 (revised): the marker created inside the archive transaction unlocks
/// the guards, is invisible to other connections, and cannot outlive the
/// transaction.
#[tokio::test]
async fn test_archive_session_marker_lifecycle() {
    use libsql::TransactionBehavior;

    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'N', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c2', 'N', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-01-01T00:00:00.000000Z', '2026-02-01T00:00:00.000000Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // Blocked before the session opens.
    assert!(conn.execute("DELETE FROM links", ()).await.is_err());

    let tx = conn
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .await
        .unwrap();
    tx.execute("CREATE TABLE macrame_archive_session (x)", ())
        .await
        .unwrap();

    // Permitted inside the session.
    tx.execute("DELETE FROM links", ()).await.unwrap();

    // Invisible to a second connection while uncommitted.
    let db2 = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn2 = db2.connect().unwrap();
    let seen: i64 = conn2
        .query(
            "SELECT COUNT(*) FROM sqlite_master WHERE name = 'macrame_archive_session'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(
        seen, 0,
        "uncommitted marker must not be visible to other connections"
    );

    tx.execute("DROP TABLE macrame_archive_session", ())
        .await
        .unwrap();
    tx.commit().await.unwrap();

    // Re-armed after commit, and the marker is not committed state.
    let after: i64 = conn
        .query(
            "SELECT COUNT(*) FROM sqlite_master WHERE name = 'macrame_archive_session'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(after, 0);

    // Re-populate: BEFORE DELETE cannot fire on an empty table.
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-03-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-03-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();
    assert!(conn.execute("DELETE FROM links", ()).await.is_err());
}

/// A rolled-back archive transaction must leave the guards armed.
#[tokio::test]
async fn test_archive_session_marker_rollback_rearms_guard() {
    use libsql::TransactionBehavior;

    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    // Give transaction_log a row, so the BEFORE DELETE row trigger can fire.
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'N', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    let tx = conn
        .transaction_with_behavior(TransactionBehavior::Immediate)
        .await
        .unwrap();
    tx.execute("CREATE TABLE macrame_archive_session (x)", ())
        .await
        .unwrap();
    tx.rollback().await.unwrap();

    let after: i64 = conn
        .query(
            "SELECT COUNT(*) FROM sqlite_master WHERE name = 'macrame_archive_session'",
            (),
        )
        .await
        .unwrap()
        .next()
        .await
        .unwrap()
        .unwrap()
        .get(0)
        .unwrap();
    assert_eq!(after, 0, "rollback must discard the marker");
    assert!(conn
        .execute("DELETE FROM transaction_log", ())
        .await
        .is_err());
}

#[tokio::test]
async fn test_audit_and_rebuild_current() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c1', 'Node 1', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('c2', 'Node 2', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'KNOWS', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // Verify zero drift initially
    let initial_drift = audit_current(&conn).await.unwrap();
    assert_eq!(initial_drift, 0);

    // Inject artificial corruption into links_current
    conn.execute(
        "INSERT INTO links_current (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'CORRUPT', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();

    // Audit must detect drift
    let audit_res = audit_current(&conn).await;
    assert!(audit_res.is_err());
    if let Err(DbError::CurrentDrift { n }) = audit_res {
        assert_eq!(n, 1);
    } else {
        panic!("Expected CurrentDrift error");
    }

    // Rebuild links_current
    let report = rebuild_current(&conn).await.unwrap();
    assert_eq!(report.drift_after, 0);

    // Audit must return 0 drift after rebuild
    let post_drift = audit_current(&conn).await.unwrap();
    assert_eq!(post_drift, 0);
}

/// Drift is a *symmetric* difference. The pre-0.5.4 audit chained
/// `EXCEPT`/`UNION` flatly, which SQLite parses left-associatively into
/// `A EXCEPT A` — a constant zero. It therefore certified any corruption as
/// clean. This exercises both directions independently and together, so a
/// regression to a one-sided or degenerate query cannot pass.
#[tokio::test]
async fn test_audit_detects_drift_in_both_directions() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    for id in ["c1", "c2"] {
        conn.execute(
            &format!("INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('{id}', 'N', '2026-01-01T00:00:00.000000Z', '2026-01-01T00:00:00.000000Z')"),
            (),
        ).await.unwrap();
    }
    for (etype, ra) in [
        ("A", "2026-01-01T00:00:00.000000Z"),
        ("B", "2026-01-02T00:00:00.000000Z"),
    ] {
        conn.execute(
            &format!("INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
                      VALUES ('c1', 'c2', '{etype}', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{{}}', '{ra}')"),
            (),
        ).await.unwrap();
    }
    assert_eq!(audit_current(&conn).await.unwrap(), 0);

    let drift_count = |res: macrame::Result<usize>| match res {
        Err(DbError::CurrentDrift { n }) => n,
        other => panic!("expected CurrentDrift, got {other:?}"),
    };

    // Direction 1: links_current is MISSING a row the projection has.
    // A one-sided `materialized EXCEPT projection` audit reports 0 here.
    conn.execute("DELETE FROM links_current WHERE edge_type = 'A'", ())
        .await
        .unwrap();
    assert_eq!(
        drift_count(audit_current(&conn).await),
        1,
        "missed materialisation must be drift"
    );

    // Direction 2: links_current ALSO has a row the projection does not.
    // Both halves are now non-empty, so the count must be their sum -- catching
    // a formulation that returns only one side.
    conn.execute(
        "INSERT INTO links_current (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('c1', 'c2', 'GHOST', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    ).await.unwrap();
    assert_eq!(
        drift_count(audit_current(&conn).await),
        2,
        "both directions must be summed"
    );

    // A stale row -- right key, wrong payload -- counts once in each direction,
    // because it is simultaneously a row the projection lacks and one it wants.
    conn.execute("DELETE FROM links_current WHERE edge_type = 'GHOST'", ())
        .await
        .unwrap();
    conn.execute(
        "UPDATE links_current SET weight = 99.0 WHERE edge_type = 'B'",
        (),
    )
    .await
    .unwrap();
    assert_eq!(drift_count(audit_current(&conn).await), 3);

    rebuild_current(&conn).await.unwrap();
    assert_eq!(
        audit_current(&conn).await.unwrap(),
        0,
        "rebuild must clear both directions"
    );
}

/// §4.1: every temporal column is exactly `YYYY-MM-DDTHH:MM:SS.ffffffZ`.
///
/// Enforced by CHECK rather than by convention, because the failure mode of a
/// mixed-precision column is silence: `'...T00:00:00Z' <= '...T00:00:00.000000Z'`
/// is FALSE, so a traversal predicated on it returns an empty set with no error.
#[tokio::test]
async fn test_non_canonical_timestamps_are_rejected_at_write_time() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    // The exact literal that used to be written freely, and that silently
    // mis-ordered against every microsecond-precision stamp it was compared to.
    for bad in [
        "2026-01-01T00:00:00Z",             // second precision
        "2026-01-01T00:00:00.000Z",         // milliseconds
        "2026-01-01T00:00:00.000000",       // no zone
        "2026-01-01T00:00:00.000000+01:00", // offset
        "2026-01-01 00:00:00.000000Z",      // space separator
        "not-a-timestamp",
    ] {
        let res = conn
            .execute(
                "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('x', 'N', ?1, '2026-01-01T00:00:00.000000Z')",
                libsql::params![bad],
            )
            .await;
        assert!(res.is_err(), "CHECK must reject valid_from = {bad:?}");
    }

    // The canonical form is accepted, and so is the canonical open sentinel.
    conn.execute(
        "INSERT INTO concepts (id, title, valid_from, valid_to, recorded_at) \
         VALUES ('ok', 'N', '2026-01-01T00:00:00.000000Z', '9999-12-31T23:59:59.999999Z', '2026-01-01T00:00:00.000000Z')",
        (),
    )
    .await
    .expect("canonical timestamps must be accepted");

    // links and transaction_log carry the same constraint.
    conn.execute(
        "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
         VALUES ('ok', 'ok', 'SELF', '2026-01-01T00:00:00Z', '9999-12-31T23:59:59.999999Z', 1.0, '{}', '2026-01-01T00:00:00.000000Z')",
        (),
    )
    .await
    .expect_err("links.valid_from must reject second precision");
}

/// The regression that made the precision defect concrete: a valid-time
/// predicate must match an edge asserted at the same instant.
#[tokio::test]
async fn test_valid_time_predicate_matches_edge_at_same_instant() {
    let harness = TestHarness::new();
    let db = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap();
    let conn = db.connect().unwrap();
    migrations::run(&conn).await.unwrap();

    let ts = "2026-01-01T00:00:00.000000Z";
    for id in ["c1", "c2"] {
        conn.execute(
            &format!("INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES ('{id}', 'N', '{ts}', '{ts}')"),
            (),
        ).await.unwrap();
    }
    conn.execute(
        &format!("INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, weight, properties, recorded_at) \
                  VALUES ('c1', 'c2', 'KNOWS', '{ts}', '9999-12-31T23:59:59.999999Z', 1.0, '{{}}', '{ts}')"),
        (),
    ).await.unwrap();

    // Half-open [valid_from, valid_to): the edge is live exactly at valid_from.
    let edges = macrame::temporal::query_as_of_edges(&conn, ts)
        .await
        .unwrap();
    assert_eq!(edges.len(), 1, "edge must be live at its own valid_from");
}

// ---------------------------------------------------------------------------
// T0.2 / D-077 — the archive no longer audits its own rebuild
// ---------------------------------------------------------------------------

/// `archive()` leaves `links_current` equal to the projection, **audited from
/// outside**.
///
/// D-077 stopped `archive()`'s internal `rebuild_within` from auditing itself:
/// with one definition of the projection (`LATEST_BELIEF_PROJECTION`) that check
/// compares a table against the query that just filled it, in the same
/// transaction, and it was two `EXCEPT` passes over the whole table under the
/// archive's write lock — measured at roughly **half** the entire repair.
///
/// The guarantee it used to provide has to come from somewhere, and this is the
/// somewhere: audit *after* the archive commits, from outside, which is a
/// stronger check than the tautological one it replaces. There is a property
/// test that does this over generated histories, but it lives behind the
/// `property-tests` feature — so plain `cargo test` would otherwise no longer
/// prove that an archive leaves a clean projection at all.
#[tokio::test]
async fn an_archive_leaves_no_drift_although_it_no_longer_checks_itself() {
    let harness = TestHarness::new();
    let conn = libsql::Builder::new_local(&harness.db_path)
        .build()
        .await
        .unwrap()
        .connect()
        .unwrap();
    migrations::run(&conn).await.unwrap();

    let t0 = "2026-01-01T00:00:00.000000Z";
    let t1 = "2026-02-01T00:00:00.000000Z";
    let t2 = "2026-03-01T00:00:00.000000Z";
    let open = "9999-12-31T23:59:59.999999Z";

    for id in ["a", "b", "c"] {
        conn.execute(
            "INSERT INTO concepts (id, title, valid_from, recorded_at) VALUES (?1, 'n', ?2, ?2)",
            libsql::params![id, t0],
        )
        .await
        .unwrap();
    }

    // Three shapes that must survive an archive differently: a superseded
    // assertion (archivable), the belief that superseded it (not), and a closed
    // interval old enough to go (archivable).
    let rows: [(&str, &str, &str, &str, &str); 3] = [
        ("a", "b", t0, open, t0),
        ("a", "b", t0, open, t1),
        ("b", "c", t0, t1, t0),
    ];
    for (src, tgt, vf, vt, rec) in rows {
        conn.execute(
            "INSERT INTO links (source_id, target_id, edge_type, valid_from, valid_to, \
             weight, properties, recorded_at) VALUES (?1, ?2, 'KNOWS', ?3, ?4, 1.0, '{}', ?5)",
            libsql::params![src, tgt, vf, vt, rec],
        )
        .await
        .unwrap();
    }

    assert_eq!(
        audit_current(&conn).await.unwrap(),
        0,
        "clean before archive"
    );

    let cold = harness.temp_dir.path().join("cold.db");
    let report = macrame::temporal::archive(&conn, t2, t2, &cold)
        .await
        .unwrap();
    assert!(
        report.links_archived > 0,
        "the fixture must actually archive something, or this proves nothing"
    );

    // The real assertion: the projection is intact, checked by the auditor the
    // rebuild is no longer allowed to call on itself.
    assert_eq!(
        audit_current(&conn).await.unwrap(),
        0,
        "archive left links_current drifted from the projection"
    );
}