semantic-memory 0.5.10

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
use semantic_memory::{
    AuthorityFaultStage, AuthorityPermit, ForgettingClosureRequestV1, ForgettingDispositionV1,
    GovernedAccessPurposeV1, GovernedAccessRequestV1, MemoryConfig, MemoryStore, MockEmbedder,
    ProjectionQuery, ReceiptMode, SearchContext, StateDependencyEdgeV1, StateView,
};
use stack_ids::ScopeKey;
use tempfile::TempDir;

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

fn permit(capability: &str) -> AuthorityPermit {
    AuthorityPermit::operator_system("principal:test", "forgetting-test", capability)
}

fn access() -> GovernedAccessRequestV1 {
    GovernedAccessRequestV1::new(
        "principal:test",
        "principal:test",
        GovernedAccessPurposeV1::Recall,
        "private",
    )
}

async fn append(store: &MemoryStore, key: &str, namespace: &str, content: &str) -> String {
    store
        .authority()
        .append(
            permit(AuthorityPermit::APPEND_CAPABILITY),
            key.into(),
            namespace.into(),
            content.into(),
            Some("forgetting-fixture".into()),
        )
        .await
        .unwrap()
        .affected_ids[0]
        .clone()
}

#[tokio::test]
async fn forget_closes_canonical_and_derived_access_paths() {
    let (store, _tmp) = test_store();
    let authority = store.authority();
    let ancestor = authority
        .append(
            permit(AuthorityPermit::APPEND_CAPABILITY),
            "forget-append-ancestor".into(),
            "private".into(),
            "forbidden canary alpha-7391".into(),
            Some("subject-request".into()),
        )
        .await
        .unwrap()
        .affected_ids[0]
        .clone();
    let derived = authority
        .append(
            permit(AuthorityPermit::APPEND_CAPABILITY),
            "forget-append-derived".into(),
            "private".into(),
            "summary laundering alpha-7391".into(),
            Some("derived-summary".into()),
        )
        .await
        .unwrap()
        .affected_ids[0]
        .clone();
    store
        .add_state_dependency_edge(
            StateDependencyEdgeV1::derived_from_state(
                format!("fact:{derived}"),
                format!("fact:{ancestor}"),
            ),
            1.0,
        )
        .await
        .unwrap();

    assert!(store.reembed_all().await.unwrap() >= 2);
    assert!(store.get_fact_embedding(&ancestor).await.unwrap().is_some());

    let mut context = SearchContext::default_now();
    context.receipt_mode = ReceiptMode::ReturnReceipt;
    context.request_id = Some("forget-replay-source".into());
    let replay_source = store
        .search_with_context("alpha-7391", Some(10), Some(&["private"]), None, context)
        .await
        .unwrap()
        .receipt
        .unwrap()
        .receipt_id;

    // Populate the ordinary in-process search cache before forgetting.
    assert!(!store
        .search("alpha-7391", Some(10), None, None)
        .await
        .unwrap()
        .is_empty());

    let receipt = authority
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "forget-closure-1".into(),
            ForgettingClosureRequestV1::new(
                vec![ancestor.clone()],
                "private",
                "subject erasure request",
                128,
            ),
        )
        .await
        .unwrap();

    assert_eq!(receipt.schema_version, "forgetting_closure_receipt_v1");
    assert_eq!(receipt.disposition, ForgettingDispositionV1::Applied);
    assert!(receipt.affected_canonical_ids.contains(&ancestor));
    assert!(receipt.affected_canonical_ids.contains(&derived));
    assert!(receipt.deferred_surfaces.is_empty());
    assert!(receipt.not_tested_surfaces.is_empty());
    assert!(receipt.verification.iter().all(|check| check.passed));
    assert_eq!(receipt.after_epoch.0, receipt.before_epoch.0 + 1);
    assert_eq!(
        authority
            .get_forgetting_receipt_by_idempotency_key("forget-closure-1")
            .await
            .unwrap(),
        Some(receipt.clone())
    );
    let receipt_json = serde_json::to_string(&receipt).unwrap();
    assert!(!receipt_json.contains("alpha-7391"));
    assert!(!receipt_json.contains("subject erasure request"));

    for id in [&ancestor, &derived] {
        let raw = store.get_fact_raw_compat(id).await.unwrap().unwrap();
        assert_eq!(raw.content, "[FORGOTTEN]");
        assert!(store.get_fact_embedding(id).await.unwrap().is_none());
        assert!(authority
            .get_fact_governed(id, access())
            .await
            .unwrap()
            .fact
            .is_none());
        assert!(authority
            .export_fact_governed(id, access())
            .await
            .unwrap()
            .fact
            .is_none());
        assert!(store
            .list_graph_edges_for_node(&format!("fact:{id}"))
            .await
            .unwrap()
            .is_empty());
    }

    for view in [
        StateView::Current,
        StateView::IncludeSuperseded,
        StateView::HistoricalAt("2999-01-01T00:00:00Z".into()),
    ] {
        let results = store
            .search_with_view("alpha-7391", Some(10), Some(&["private"]), None, view)
            .await
            .unwrap();
        assert!(results
            .iter()
            .all(|result| !result.content.contains("alpha-7391")));
    }
    assert!(store
        .search("alpha-7391", Some(10), None, None)
        .await
        .unwrap()
        .iter()
        .all(|result| !result.content.contains("alpha-7391")));
    assert!(matches!(
        store
            .replay_search_receipt(
                &replay_source,
                "alpha-7391",
                Some(10),
                Some(&["private"]),
                None,
            )
            .await,
        Err(semantic_memory::MemoryError::ForgettingClosureIncomplete { .. })
    ));
}

#[tokio::test]
async fn cycles_and_shared_derivations_close_once_without_collateral_deletion() {
    let (store, _tmp) = test_store();
    let root = append(&store, "cycle-root", "private", "cycle root canary").await;
    let shared = append(&store, "cycle-shared", "private", "shared derived canary").await;
    let cycle = append(&store, "cycle-node", "private", "cycle derived canary").await;
    let unrelated = append(&store, "cycle-unrelated", "private", "unrelated survives").await;
    for edge in [
        StateDependencyEdgeV1::derived_from_state(format!("fact:{shared}"), format!("fact:{root}")),
        StateDependencyEdgeV1::derived_from_state(format!("fact:{cycle}"), format!("fact:{root}")),
        StateDependencyEdgeV1::derived_from_state(
            format!("fact:{shared}"),
            format!("fact:{cycle}"),
        ),
        StateDependencyEdgeV1::derived_from_state(
            format!("fact:{cycle}"),
            format!("fact:{shared}"),
        ),
    ] {
        store.add_state_dependency_edge(edge, 1.0).await.unwrap();
    }

    let receipt = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "cycle-forget".into(),
            ForgettingClosureRequestV1::new(vec![root.clone()], "private", "cycle request", 32),
        )
        .await
        .unwrap();
    let affected = receipt
        .affected_canonical_ids
        .iter()
        .cloned()
        .collect::<std::collections::BTreeSet<_>>();
    assert_eq!(
        affected,
        [cycle, root, shared]
            .into_iter()
            .collect::<std::collections::BTreeSet<_>>()
    );
    assert_eq!(
        store
            .get_fact_raw_compat(&unrelated)
            .await
            .unwrap()
            .unwrap()
            .content,
        "unrelated survives"
    );
}

#[tokio::test]
async fn budget_and_scope_boundaries_fail_closed_before_mutation() {
    let (store, _tmp) = test_store();
    let root = append(&store, "bounded-root", "private", "bounded root").await;
    let derived = append(&store, "bounded-derived", "private", "bounded derived").await;
    store
        .add_state_dependency_edge(
            StateDependencyEdgeV1::derived_from_state(
                format!("fact:{derived}"),
                format!("fact:{root}"),
            ),
            1.0,
        )
        .await
        .unwrap();

    let exhausted = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "bounded-budget".into(),
            ForgettingClosureRequestV1::new(vec![root.clone()], "private", "bounded request", 1),
        )
        .await;
    assert!(matches!(
        exhausted,
        Err(semantic_memory::MemoryError::ForgettingBudgetExceeded { .. })
    ));
    assert_eq!(
        store
            .get_fact_raw_compat(&root)
            .await
            .unwrap()
            .unwrap()
            .content,
        "bounded root"
    );

    let wrong_namespace = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "bounded-scope".into(),
            ForgettingClosureRequestV1::new(vec![root.clone()], "other", "wrong scope", 8),
        )
        .await;
    assert!(matches!(
        wrong_namespace,
        Err(semantic_memory::MemoryError::ForgettingClosureIncomplete { .. })
    ));
    assert_eq!(
        store
            .get_fact_raw_compat(&derived)
            .await
            .unwrap()
            .unwrap()
            .content,
        "bounded derived"
    );

    let other_principal = store
        .authority()
        .append(
            AuthorityPermit::operator_system(
                "principal:other",
                "forgetting-test-other",
                AuthorityPermit::APPEND_CAPABILITY,
            ),
            "bounded-other-principal".into(),
            "private".into(),
            "other principal survives".into(),
            None,
        )
        .await
        .unwrap()
        .affected_ids[0]
        .clone();
    store
        .add_state_dependency_edge(
            StateDependencyEdgeV1::derived_from_state(
                format!("fact:{other_principal}"),
                format!("fact:{root}"),
            ),
            1.0,
        )
        .await
        .unwrap();
    let cross_principal = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "bounded-principal".into(),
            ForgettingClosureRequestV1::new(vec![root.clone()], "private", "principal boundary", 8),
        )
        .await;
    assert!(matches!(
        cross_principal,
        Err(semantic_memory::MemoryError::ForgettingClosureIncomplete { .. })
    ));
    assert_eq!(
        store
            .get_fact_raw_compat(&other_principal)
            .await
            .unwrap()
            .unwrap()
            .content,
        "other principal survives"
    );
}

#[tokio::test]
async fn idempotency_is_exact_and_conflicting_retries_fail_closed() {
    let (store, _tmp) = test_store();
    let root = append(&store, "idem-root", "private", "idempotent canary").await;
    let request =
        ForgettingClosureRequestV1::new(vec![root.clone()], "private", "idempotent request", 8);
    let first = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "idem-forget".into(),
            request.clone(),
        )
        .await
        .unwrap();
    let replay = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "idem-forget".into(),
            request,
        )
        .await
        .unwrap();
    assert_eq!(first, replay);
    let conflict = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "idem-forget".into(),
            ForgettingClosureRequestV1::new(vec![root], "private", "different reason", 8),
        )
        .await;
    assert!(matches!(
        conflict,
        Err(semantic_memory::MemoryError::AuthorityIdempotencyConflict { .. })
    ));
}

#[tokio::test]
async fn injected_fault_rolls_back_scrubbing_invalidations_epochs_and_receipt() {
    let (store, _tmp) = test_store();
    let root = append(&store, "rollback-root", "private", "rollback canary").await;
    store
        .authority()
        .set_fault(Some(AuthorityFaultStage::AfterForgettingMutation));
    let result = store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "rollback-forget".into(),
            ForgettingClosureRequestV1::new(vec![root.clone()], "private", "rollback request", 8),
        )
        .await;
    assert!(matches!(
        result,
        Err(semantic_memory::MemoryError::AuthorityFaultInjected {
            stage: AuthorityFaultStage::AfterForgettingMutation
        })
    ));
    assert_eq!(
        store
            .get_fact_raw_compat(&root)
            .await
            .unwrap()
            .unwrap()
            .content,
        "rollback canary"
    );
    assert!(
        store.get_fact_embedding(&root).await.unwrap().is_some(),
        "failed forgetting must preserve the governed fact embedding"
    );
    assert!(!store
        .search("rollback canary", Some(4), Some(&["private"]), None)
        .await
        .unwrap()
        .is_empty());
}

#[tokio::test]
async fn projection_derivations_are_hidden_after_ancestor_forgetting() {
    let (store, _tmp) = test_store();
    let root = append(&store, "projection-root", "private", "projection ancestor").await;
    store
        .raw_execute(
            "INSERT INTO claim_versions
             (claim_version_id, claim_id, projection_family, subject_entity_id, predicate,
              object_anchor, scope_namespace, source_envelope_id, source_authority, content)
             VALUES (?1, ?2, 'test', 'entity-1', 'contains', ?3, 'private', 'env-1',
                     'test', ?4)",
            vec![
                "claim-v1".into(),
                "claim-1".into(),
                "\"projection ancestor\"".into(),
                "derived projection forbidden canary".into(),
            ],
        )
        .await
        .unwrap();
    store
        .raw_execute(
            "INSERT INTO derivation_edges
             (source_kind, source_id, target_kind, target_id, derivation_type)
             VALUES ('fact', ?1, 'claim_version', 'claim-v1', 'derived_from_fact')",
            vec![root.clone()],
        )
        .await
        .unwrap();
    assert_eq!(
        store
            .query_claim_versions(ProjectionQuery::new(ScopeKey::namespace_only("private")))
            .await
            .unwrap()
            .len(),
        1
    );

    store
        .authority()
        .forget(
            permit(AuthorityPermit::FORGET_CAPABILITY),
            "projection-forget".into(),
            ForgettingClosureRequestV1::new(vec![root], "private", "projection request", 16),
        )
        .await
        .unwrap();
    assert!(store
        .query_claim_versions(ProjectionQuery::new(ScopeKey::namespace_only("private")))
        .await
        .unwrap()
        .is_empty());
}