mushroomdb 0.9.2

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

fn tmp(name: &str) -> std::path::PathBuf {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    std::env::temp_dir().join(format!("mdb-memrem-{name}-{}-{nanos}", std::process::id()))
}

fn store(name: &str) -> GraphDb<core_storage::fs::RealFs> {
    let mut db = GraphDb::open(&tmp(name)).unwrap();
    db.apply_schema(&memory_defaults()).unwrap();
    db
}

fn input<'a>(text: &'a str, about: &'a [String]) -> RememberInput<'a> {
    RememberInput {
        text,
        about,
        kind: "note",
        ts: 1_759_000_000,
        source: None,
        entities: &[],
        facts: &[],
    }
}

#[test]
fn an_unknown_subject_becomes_provisional_instead_of_an_error() {
    let mut db = store("provisional");
    let about = vec!["reid".to_string()];
    let report = remember(&mut db, &input("Reid reviewed the copy", &about)).expect("remember");
    assert_eq!(report.provisional, vec!["reid".to_string()]);
    assert_eq!(
        db.get_prop("reid", PROVISIONAL_PROP),
        Some(Value::Bool(true)),
        "the stub must be marked provisional"
    );
}

#[test]
fn describing_the_subject_later_clears_provisional() {
    let mut db = store("fillin");
    let about = vec!["reid".to_string()];
    remember(&mut db, &input("Reid reviewed the copy", &about)).unwrap();
    let created = describe_entity(
        &mut db,
        "reid",
        Some("Person"),
        &[("name".to_string(), Value::Str("Reid".into()))],
    )
    .unwrap();
    assert!(!created, "the provisional stub already existed");
    assert_eq!(
        db.get_prop("reid", PROVISIONAL_PROP),
        None,
        "a described subject is no longer provisional"
    );
}

#[test]
fn an_existing_subject_is_matched_not_created() {
    let mut db = store("matched");
    describe_entity(
        &mut db,
        "matthew",
        Some("Person"),
        &[("name".to_string(), Value::Str("Matthew".into()))],
    )
    .unwrap();
    let about = vec!["matthew".to_string()];
    let report = remember(&mut db, &input("Matthew prefers brevity", &about)).unwrap();
    assert!(report.provisional.is_empty(), "{report:?}");
    assert_eq!(report.matched, 1, "{report:?}");
}

#[test]
fn entities_and_facts_land_in_one_commit() {
    let mut db = store("structured");
    let before = db.stats().nodes_live;
    let entities = vec![
        EntityIn {
            key: "matthew".into(),
            label: "Person".into(),
            props: BTreeMap::new(),
            aliases: Vec::new(),
        },
        EntityIn {
            key: "v0.7".into(),
            label: "Release".into(),
            props: BTreeMap::new(),
            aliases: Vec::new(),
        },
    ];
    let facts = vec![FactIn {
        subject: "matthew".into(),
        predicate: "WANTS".into(),
        object: "v0.7".into(),
    }];
    let report = remember(
        &mut db,
        &RememberInput {
            text: "Matthew wants 0.7 to focus on the write path",
            about: &[],
            kind: "note",
            ts: 1_759_000_000,
            source: Some("session:abc"),
            entities: &entities,
            facts: &facts,
        },
    )
    .expect("remember");
    assert_eq!(report.created, 2, "{report:?}");
    // note + 2 entities
    assert_eq!(db.stats().nodes_live, before + 3);
    assert_eq!(
        db.get_prop(&report.note, "source"),
        Some(Value::Str("session:abc".into())),
        "caller-supplied provenance must be stored, not overwritten with \"agent\""
    );
}

/// Fix round 1: a `facts[]` endpoint named nowhere else used to land as a
/// bare, unmarked `Entity` node — no `name`, no `provisional`, absent from
/// every report field — because the facts loop auto-created it through
/// `insert_edge_upsert`, which stamps no props at all. It must get exactly
/// the `about` path's treatment: a `name`, `provisional: true`, a place in
/// `report.provisional`, and a hit from the store's own `provisional` query.
#[test]
fn an_unnamed_fact_endpoint_becomes_provisional_too() {
    let mut db = store("fact-endpoint");
    let entities = vec![EntityIn {
        key: "matthew".into(),
        label: "Person".into(),
        props: BTreeMap::new(),
        aliases: Vec::new(),
    }];
    let facts = vec![FactIn {
        subject: "matthew".into(),
        predicate: "WANTS".into(),
        object: "v0.8-typoo".into(),
    }];
    let report = remember(
        &mut db,
        &RememberInput {
            text: "Matthew wants 0.8, typo and all",
            about: &[],
            kind: "note",
            ts: 1_759_000_001,
            source: None,
            entities: &entities,
            facts: &facts,
        },
    )
    .expect("remember");

    assert_eq!(
        report.provisional,
        vec!["v0.8-typoo".to_string()],
        "{report:?}"
    );
    assert_eq!(
        db.get_prop("v0.8-typoo", PROVISIONAL_PROP),
        Some(Value::Bool(true)),
        "an unnamed fact endpoint must be marked provisional"
    );
    assert_eq!(
        db.get_prop("v0.8-typoo", NAME_FIELD),
        Some(Value::Str("v0.8-typoo".into())),
        "an unnamed fact endpoint must carry a name"
    );

    // The same convention the `about` path and the first-run gate rely on:
    // a bare truthy predicate finds it.
    let rows = db
        .query(
            "MATCH (n) WHERE n.provisional RETURN n.id AS id",
            &BTreeMap::new(),
        )
        .expect("query");
    let ids: Vec<String> = (0..rows.len())
        .map(|i| match &rows.row(i)[0] {
            Some(Value::Str(s)) => s.clone(),
            other => panic!("expected a string id, got {other:?}"),
        })
        .collect();
    assert!(
        ids.contains(&"v0.8-typoo".to_string()),
        "the store's own provisional query must surface it: {ids:?}"
    );

    // `matthew` was named in `entities`: real, not stubbed, not reported.
    assert_eq!(
        db.get_prop("matthew", PROVISIONAL_PROP),
        None,
        "an entity explicitly described must never be marked provisional"
    );
}

/// Fix round 2: `entities[].label` is free-form — `memory_defaults()` only
/// declares full-text for `name` on the five built-in labels — so an entity
/// under any other label (the spec's own worked example is `Release`)
/// landed with a `name` `recall` could never reach: spec §1.1(b)'s defect,
/// reproduced through this release's own new feature. `remember` must
/// self-declare it, the same way it already does for `Note.text`.
#[test]
fn an_unseen_entity_label_becomes_searchable() {
    let mut db = store("unseen-label");
    let mut props = BTreeMap::new();
    props.insert("name".to_string(), Value::Str("v0.7".into()));
    let entities = vec![EntityIn {
        key: "v0.7".into(),
        label: "Release".into(),
        props,
        aliases: Vec::new(),
    }];
    remember(
        &mut db,
        &RememberInput {
            text: "Matthew wants 0.7 to focus on the write path",
            about: &[],
            kind: "note",
            ts: 1_759_000_002,
            source: None,
            entities: &entities,
            facts: &[],
        },
    )
    .expect("remember");

    assert!(
        db.fulltext_pairs()
            .contains(&("Release".to_string(), NAME_FIELD.to_string())),
        "an unseen entity label must be self-declared for full-text: {:?}",
        db.fulltext_pairs()
    );

    match recall_digest(&db, "v0.7", "test", 4_000) {
        RecallOutcome::Hits(digest) => assert!(
            digest.contains("v0.7"),
            "recall must find the entity it was just told about: {digest}"
        ),
        other => panic!("expected a hit, got {other:?}"),
    }
}

/// The self-declare above is bounded: past `MAX_FULLTEXT_PAIRS` distinct
/// declared pairs, a new `entities[].label` is written normally but is not
/// made searchable, rather than growing the store's declared full-text
/// surface — and so every future re-open's rebuild cost — without limit on
/// caller-supplied strings.
#[test]
fn self_declaring_full_text_for_new_labels_is_bounded() {
    let mut db = store("many-labels");
    // Drive the declared surface past any reasonable cap with distinct
    // single-entity calls, each under its own throwaway label.
    for i in 0..64 {
        let mut props = BTreeMap::new();
        props.insert("name".to_string(), Value::Str(format!("thing-{i}")));
        let entities = vec![EntityIn {
            key: format!("thing-{i}"),
            label: format!("Kind{i}"),
            props,
            aliases: Vec::new(),
        }];
        remember(
            &mut db,
            &RememberInput {
                text: &format!("a note about thing {i}"),
                about: &[],
                kind: "note",
                ts: 1_759_100_000 + i,
                source: None,
                entities: &entities,
                facts: &[],
            },
        )
        .unwrap_or_else(|e| panic!("remember {i}: {e}"));
    }
    let pairs = db.fulltext_pairs();
    assert!(
        pairs.len() < 64 + 8,
        "the declared full-text surface must stay bounded, not grow with every \
         distinct caller-supplied label: {} pairs",
        pairs.len()
    );
    // Every entity was still written, whether or not it ended up searchable.
    assert!(db.has_node("thing-0"));
    assert!(db.has_node("thing-63"));
}

/// Fix round 3 / finding 4: spec §3.2 promises "a cap per commit, so a
/// malformed batch cannot flood the graph" — there was none. A batch right
/// at the cap (20, `MAX_PROVISIONAL_PER_COMMIT`) must be entirely unaffected
/// by it: every key stubbed, none refused.
#[test]
fn a_batch_at_the_provisional_cap_is_unaffected() {
    let mut db = store("cap-exact");
    let about: Vec<String> = (0..20).map(|i| format!("k{i}")).collect();
    let report = remember(&mut db, &input("twenty unknown subjects", &about)).unwrap();
    assert_eq!(report.provisional.len(), 20, "{report:?}");
    assert!(
        report.provisional_capped.is_empty(),
        "a batch exactly at the cap must not be capped: {report:?}"
    );
    for k in &about {
        assert_eq!(
            db.get_prop(k, PROVISIONAL_PROP),
            Some(Value::Bool(true)),
            "{k} must be stubbed"
        );
        assert!(
            db.node_edges(k)
                .unwrap()
                .iter()
                .any(|e| e.edge_type == "ABOUT"),
            "{k} must have its ABOUT edge"
        );
    }
}

/// A batch over the cap: the excess is refused, reported, and never gets a
/// node or an edge — but the note and every key under the cap still commit.
/// This is the exact defect fix round 3 closes: on the pre-fix binary, 40
/// stubs landed in one call with no cap, no warning, and no report field
/// naming any of them.
#[test]
fn a_batch_over_the_provisional_cap_refuses_and_reports_the_excess() {
    let mut db = store("cap-exceeded");
    let about: Vec<String> = (0..25).map(|i| format!("k{i}")).collect();
    let report = remember(&mut db, &input("twenty-five unknown subjects", &about)).unwrap();

    assert_eq!(report.provisional.len(), 20, "{report:?}");
    assert_eq!(report.provisional_capped.len(), 5, "{report:?}");
    assert_eq!(
        report.provisional_capped,
        about[20..].to_vec(),
        "the capped keys must be named, not just counted: {report:?}"
    );

    // Everything under the cap committed normally.
    for k in &about[..20] {
        assert_eq!(db.get_prop(k, PROVISIONAL_PROP), Some(Value::Bool(true)));
    }
    // Nothing over the cap was written at all — no node, hence no edge.
    for k in &about[20..] {
        assert!(!db.has_node(k), "{k} must not have been created");
    }
    // The note itself, and every key under the cap, still committed — one
    // caller mistake does not cost the whole write.
    assert!(db.has_node(&report.note), "the note must still be written");
}

#[test]
fn the_caller_owns_the_timestamp() {
    let mut db = store("ts");
    let report = remember(&mut db, &input("an imported fact", &[])).unwrap();
    assert_eq!(
        db.get_prop(&report.note, "ts"),
        Some(Value::Int(1_759_000_000)),
        "a fact imported from a transcript must not be stamped with import time"
    );
}

/// A store ingest-git wrote before 0.7 carries `about_<label>` rules: KeyMatch
/// on `Note.about`, deriving the `ABOUT` edges `remember` also writes itself.
/// Built here with the rule's own shape rather than from `repograph::rules`.
fn about_file_rule() -> mushroomdb::RuleDef {
    let predicate = mushroomdb::Predicate::KeyMatch {
        field: "about".into(),
    };
    mushroomdb::RuleDef {
        name: "about_file".into(),
        src_label: "Note".into(),
        dst_label: "File".into(),
        max_edges: Some(mushroomdb::default_max_edges(&predicate)),
        predicate,
        edge_type: "ABOUT".into(),
        weight_prop: None,
        approximate: false,
        via_label: None,
        via_edge: None,
        via_dir: None,
        namespace: None,
    }
}

#[test]
fn remembering_the_same_note_twice_about_a_rule_linked_node_succeeds() {
    let mut db = store("about-rule");
    db.insert_node("File", "src/zanzibar.rs", vec![]).unwrap();
    db.create_rule(about_file_rule()).unwrap();
    let about = vec!["src/zanzibar.rs".to_string()];

    let first = remember(&mut db, &input("the router lives here", &about)).expect("first");
    // Content-addressed: the same text and ts is the same note, and its ABOUT
    // edge is now the rule's. Saying it again must not be an error.
    let second = remember(&mut db, &input("the router lives here", &about)).expect("second");
    assert_eq!(first.note, second.note);

    let about_edges: Vec<_> = db
        .node_edges(&first.note)
        .unwrap()
        .into_iter()
        .filter(|e| e.edge_type == "ABOUT")
        .collect();
    assert_eq!(about_edges.len(), 1, "{about_edges:?}");
    assert!(about_edges[0].derived, "the rule owns the edge");
    // `derived` counts what this commit's rules produced on the note: the
    // first call's rule derived the edge, the second derived nothing.
    assert_eq!((first.derived, second.derived), (1, 0));
}

// ── an empty key (defect 76) ─────────────────────────────────────────────────

/// Everything a refused `remember` could have moved.
#[derive(Debug, PartialEq)]
struct Written {
    nodes_live: usize,
    edges: u64,
    commit_seq: u64,
    fulltext: Vec<(String, String)>,
    notes: usize,
}

fn written(db: &GraphDb<core_storage::fs::RealFs>) -> Written {
    let stats = db.stats();
    Written {
        nodes_live: stats.nodes_live,
        edges: stats.edges,
        commit_seq: db.commit_seq(),
        fulltext: db.fulltext_pairs(),
        notes: db.nodes_with_label("Note").len(),
    }
}

/// A `remember` naming `key` in `about`, as a fact's subject, as a fact's
/// object and as an entity's key — one call each, every one of them refused
/// with a message naming the argument and the position, and nothing written:
/// not the note, not the entity under an unseen label beside the bad key, not
/// that label's full-text pair.
fn assert_every_argument_refuses(name: &str, key: &str, reason: &str) {
    let mut db = store(name);
    remember(&mut db, &input("Ada wrote the first one", &["ada".into()])).unwrap();
    let before = written(&db);

    let good = EntityIn {
        key: "v0.7".into(),
        label: "Release".into(),
        props: BTreeMap::new(),
        aliases: vec![],
    };
    let bad_entity = EntityIn {
        key: key.into(),
        label: "Person".into(),
        props: BTreeMap::new(),
        aliases: vec![],
    };
    let fact = |subject: &str, object: &str| FactIn {
        subject: subject.into(),
        predicate: "KNOWS".into(),
        object: object.into(),
    };

    let about = vec!["ada".to_string(), key.to_string()];
    let cases = vec![
        ("about[1]", about, vec![good.clone()], vec![]),
        (
            "facts[1].subject",
            vec![],
            vec![good.clone()],
            vec![fact("ada", "v0.7"), fact(key, "ada")],
        ),
        (
            "facts[0].object",
            vec![],
            vec![good.clone()],
            vec![fact("ada", key)],
        ),
        ("entities[1].key", vec![], vec![good, bad_entity], vec![]),
    ];
    for (argument, about, entities, facts) in cases {
        let refused = remember(
            &mut db,
            &RememberInput {
                entities: &entities,
                facts: &facts,
                ..input("a note that must not land", &about)
            },
        );
        match refused {
            Err(mushroomdb::GraphError::IngestError { detail }) => assert_eq!(
                detail,
                format!("remember: {argument} must not be {reason}, got {key:?}")
            ),
            other => panic!("{argument}: expected the empty-key refusal, got {other:?}"),
        }
        assert_eq!(written(&db), before, "{argument}: a refusal writes nothing");
        assert!(!db.has_node(key), "{argument}: no node keyed {key:?}");
        assert!(!db.has_node("v0.7"), "{argument}: all-or-nothing");
    }
}

#[test]
fn an_empty_key_is_refused_wherever_remember_takes_one() {
    assert_every_argument_refuses("empty-key", "", "empty or only whitespace");
}

#[test]
fn a_whitespace_only_key_is_refused_the_same_way() {
    assert_every_argument_refuses("blank-key", " \t\n", "empty or only whitespace");
}

/// The refusal is for a key with nothing in it. A padded key is a different,
/// recorded behaviour and is stored as given.
#[test]
fn a_padded_key_is_still_taken_as_given() {
    let mut db = store("padded-key");
    let about = vec![" reid ".to_string()];
    let report = remember(&mut db, &input("Reid reviewed the copy", &about)).expect("remember");
    assert_eq!(report.provisional, about);
    assert!(db.has_node(" reid "));
}

/// `describe_entity` is the other door into the memory write path: it creates
/// a node under whatever key it is handed.
#[test]
fn describing_an_empty_key_is_refused() {
    let mut db = store("describe-empty");
    let before = written(&db);
    for key in ["", "  "] {
        match describe_entity(&mut db, key, Some("Person"), &[]) {
            Err(mushroomdb::GraphError::IngestError { detail }) => {
                assert_eq!(
                    detail,
                    format!("key must not be empty or only whitespace, got {key:?}")
                )
            }
            other => panic!("expected the empty-key refusal, got {other:?}"),
        }
        assert!(!db.has_node(key));
    }
    assert_eq!(written(&db), before);
}

/// A store written before the refusal existed can hold a node keyed by the
/// empty string, with notes linked to it. Nothing migrates it: the store
/// reopens, and `recall`, `schema` and `stats` answer with it present.
#[test]
fn a_store_that_already_holds_an_empty_key_node_still_opens_and_answers() {
    use mushroomdb::memory::brief::BriefOptions;
    use mushroomdb::memory::recall::recall_rows;
    use mushroomdb::memory::schema::{provisional_keys, render_schema, schema_report};

    let path = tmp("legacy-empty-key");
    {
        let mut db = GraphDb::open(&path).unwrap();
        db.apply_schema(&memory_defaults()).unwrap();
        // What 0.7.0's `remember` wrote for `about: [""]`, through the raw
        // write path this fix does not close.
        db.insert_node(
            "Entity",
            "",
            vec![
                (NAME_FIELD.to_string(), Value::Str(String::new())),
                (PROVISIONAL_PROP.to_string(), Value::Bool(true)),
            ],
        )
        .unwrap();
        db.insert_node(
            "Note",
            "note:legacy",
            vec![
                (
                    "text".to_string(),
                    Value::Str("zanzibar is the router".into()),
                ),
                ("kind".to_string(), Value::Str("note".into())),
                ("ts".to_string(), Value::Int(1_759_000_000)),
                (
                    "about".to_string(),
                    Value::List(vec![Value::Str(String::new())]),
                ),
            ],
        )
        .unwrap();
        db.insert_edge("ABOUT", "note:legacy", "").unwrap();
    }

    let mut db = GraphDb::open(&path).expect("the store reopens");
    assert!(db.has_node(""));
    let stats = db.stats();
    assert_eq!((stats.nodes_live, stats.edges), (2, 1));

    let rows = recall_rows(&db, "zanzibar");
    assert!(rows.indexed);
    assert_eq!(
        rows.hits.iter().map(|h| h.key.as_str()).collect::<Vec<_>>(),
        ["note:legacy"]
    );
    match recall_digest(&db, "zanzibar", "test", 4_000) {
        RecallOutcome::Hits(digest) => assert!(digest.contains("zanzibar"), "{digest}"),
        other => panic!("expected a hit, got {other:?}"),
    }

    assert_eq!(provisional_keys(&db), vec![String::new()]);
    let rendered = render_schema(&schema_report(&db, &BriefOptions::default()));
    assert!(rendered.contains("Entity"), "{rendered}");

    // A new note about a real key lands beside it; naming it again does not.
    remember(&mut db, &input("Reid reviewed the copy", &["reid".into()])).expect("remember");
    assert!(remember(&mut db, &input("more of the same", &[String::new()])).is_err());
}

// ── an empty predicate or label (defect 77) ──────────────────────────────────

/// A fact's `predicate` becomes an edge type and an entity's `label` a node
/// label and a full-text declaration. One with nothing in it refuses the whole
/// call — the valid entity, the valid fact and the unseen label's full-text
/// pair beside it included.
fn assert_a_blank_predicate_or_label_refuses(name: &str, blank: &str) {
    let mut db = store(name);
    remember(&mut db, &input("Ada wrote the first one", &["ada".into()])).unwrap();
    let before = written(&db);

    let good = EntityIn {
        key: "v0.7".into(),
        label: "Release".into(),
        props: BTreeMap::new(),
        aliases: vec![],
    };
    let unlabelled = EntityIn {
        key: "widget".into(),
        label: blank.into(),
        props: BTreeMap::new(),
        aliases: vec![],
    };
    let fact = |predicate: &str| FactIn {
        subject: "ada".into(),
        predicate: predicate.into(),
        object: "v0.7".into(),
    };

    let cases = vec![
        (
            "facts[1].predicate",
            vec![good.clone()],
            vec![fact("WORKS_ON"), fact(blank)],
        ),
        (
            "entities[1].label",
            vec![good, unlabelled],
            vec![fact("WORKS_ON")],
        ),
    ];
    for (argument, entities, facts) in cases {
        let refused = remember(
            &mut db,
            &RememberInput {
                entities: &entities,
                facts: &facts,
                ..input("a note that must not land", &["ada".into()])
            },
        );
        match refused {
            Err(mushroomdb::GraphError::IngestError { detail }) => assert_eq!(
                detail,
                format!("remember: {argument} must not be empty or only whitespace, got {blank:?}")
            ),
            other => panic!("{argument}: expected the refusal, got {other:?}"),
        }
        assert_eq!(written(&db), before, "{argument}: a refusal writes nothing");
        assert!(!db.has_node("v0.7"), "{argument}: all-or-nothing");
        assert!(!db.has_node("widget"), "{argument}: all-or-nothing");
    }
}

#[test]
fn an_empty_predicate_or_label_is_refused_and_nothing_is_written() {
    assert_a_blank_predicate_or_label_refuses("empty-type", "");
}

#[test]
fn a_whitespace_only_predicate_or_label_is_refused_the_same_way() {
    assert_a_blank_predicate_or_label_refuses("blank-type", " \t\n");
}

/// `describe_entity` uses its label only to create, and refuses one with
/// nothing in it either way.
#[test]
fn describing_under_an_empty_label_is_refused() {
    let mut db = store("describe-empty-label");
    let before = written(&db);
    for label in ["", "  "] {
        match describe_entity(&mut db, "widget", Some(label), &[]) {
            Err(mushroomdb::GraphError::IngestError { detail }) => assert_eq!(
                detail,
                format!("label must not be empty or only whitespace, got {label:?}")
            ),
            other => panic!("expected the empty-label refusal, got {other:?}"),
        }
    }
    assert!(!db.has_node("widget"));
    assert_eq!(written(&db), before);
}

/// A store written before the refusal existed can hold an edge whose type is
/// the empty string, a node under the empty label and the full-text pair
/// `remember` declared for that label. Nothing migrates them: the store
/// reopens and `recall`, `schema` and `stats` answer with them present.
#[test]
fn a_store_that_already_holds_an_empty_type_edge_and_label_still_opens_and_answers() {
    use mushroomdb::memory::brief::BriefOptions;
    use mushroomdb::memory::forget::{forget, ForgetTarget};
    use mushroomdb::memory::recall::recall_rows;
    use mushroomdb::memory::schema::{render_schema, schema_report};

    let path = tmp("legacy-empty-type");
    {
        let mut db = GraphDb::open(&path).unwrap();
        db.apply_schema(&memory_defaults()).unwrap();
        remember(&mut db, &input("zanzibar is the router", &["ada".into()])).unwrap();
        // What 0.7.0's `remember` wrote for `predicate: ""` and `label: ""`,
        // through the raw write path this fix does not close.
        db.insert_node("Entity", "bob", vec![]).unwrap();
        db.insert_edge("", "ada", "bob").unwrap();
        db.enable_fulltext("", NAME_FIELD).unwrap();
        db.insert_node(
            "",
            "widget",
            vec![(NAME_FIELD.to_string(), Value::Str("Widget".into()))],
        )
        .unwrap();
    }

    let mut db = GraphDb::open(&path).expect("the store reopens");
    let stats = db.stats();
    assert_eq!((stats.nodes_live, stats.edges), (4, 2));
    assert!(db
        .fulltext_pairs()
        .contains(&(String::new(), NAME_FIELD.to_string())));

    let rows = recall_rows(&db, "zanzibar");
    assert!(rows.indexed);
    assert_eq!(rows.hits.len(), 1);
    assert_eq!(
        recall_rows(&db, "widget")
            .hits
            .iter()
            .map(|h| (h.key.as_str(), h.label.as_str()))
            .collect::<Vec<_>>(),
        [("widget", "")]
    );
    let rendered = render_schema(&schema_report(&db, &BriefOptions::default()));
    assert!(rendered.contains("Entity"), "{rendered}");

    // Naming either again is refused; `forget` removes both.
    let again = FactIn {
        subject: "ada".into(),
        predicate: String::new(),
        object: "bob".into(),
    };
    assert!(remember(
        &mut db,
        &RememberInput {
            facts: &[again],
            ..input("more of the same", &[])
        }
    )
    .is_err());
    let gone = forget(
        &mut db,
        &ForgetTarget::Fact {
            subject: "ada".into(),
            predicate: String::new(),
            object: "bob".into(),
        },
    )
    .expect("forget retracts the empty-type edge");
    assert!(gone.changed);
    forget(
        &mut db,
        &ForgetTarget::Node {
            key: "widget".into(),
        },
    )
    .expect("forget removes the empty-label node");
    let stats = db.stats();
    assert_eq!((stats.nodes_live, stats.edges), (3, 1));
}

/// A stub takes its key as its name, so each word of the key becomes an
/// alias, and a long key — a sentence, a URL with a slug — implies more than
/// a node may carry (`MAX_ALIASES`, defect 53). The stub is still written, as
/// an unknown subject always is, and carries its whole key as its one alias.
#[test]
fn a_stub_whose_key_implies_more_aliases_than_the_cap_carries_only_its_key() {
    use mushroomdb::memory::identity::{ALIASES_FIELD, MAX_ALIASES};

    let mut db = store("stub-alias-cap");
    let aliases_of =
        |db: &GraphDb<core_storage::fs::RealFs>, key: &str| match db.get_prop(key, ALIASES_FIELD) {
            Some(Value::List(aliases)) => aliases,
            other => panic!("expected {key}'s aliases, got {other:?}"),
        };

    let words: Vec<String> = (0..32).map(|i| format!("w{i}")).collect();
    let long = words.join(" ");
    let url = "https://news.example.com/2026/10/13/a-long-slug-about-graph-databases-and-agent-\
               memory-that-goes-on-for-quite-a-while-longer-than-anyone-would-type?utm_source=\
               newsletter&utm_medium=email&utm_campaign=october&ref=home&page=2&sort=new";
    let report = remember(
        &mut db,
        &RememberInput {
            facts: &[FactIn {
                subject: url.into(),
                predicate: "CITES".into(),
                object: "ada".into(),
            }],
            ..input("a note about a long key", std::slice::from_ref(&long))
        },
    )
    .expect("a long key is stubbed, not refused");
    assert!(report.provisional.contains(&long), "{report:?}");
    assert!(report.provisional.contains(&url.to_string()), "{report:?}");
    assert_eq!(aliases_of(&db, &long), vec![Value::Str(long.clone())]);
    assert_eq!(aliases_of(&db, url), vec![Value::Str(url.to_lowercase())]);

    // One word fewer is exactly the cap — the key is its own canonical name,
    // so it counts once — and its words are aliases as before.
    let at_cap = words[..31].join(" ");
    remember(
        &mut db,
        &input("thirty-one words", std::slice::from_ref(&at_cap)),
    )
    .expect("at the cap");
    assert_eq!(aliases_of(&db, &at_cap).len(), MAX_ALIASES);
}

/// A key of only characters that print as nothing — a zero-width space, a
/// control character, a byte-order mark — names nothing either (defect 78).
/// The definition is the digest's: what `sanitize` turns into spaces.
#[test]
fn a_key_with_no_visible_character_is_refused_the_same_way() {
    for (i, key) in ["\u{200b}", "\u{1}", "\u{feff}", " \u{200b}\u{202e}\t"]
        .iter()
        .enumerate()
    {
        assert_every_argument_refuses(
            &format!("invisible-key-{i}"),
            key,
            "only invisible characters",
        );
    }
}

/// The refusal is for a key with nothing to see in it. One that carries an
/// invisible character beside text is stored as given, as a padded key is.
#[test]
fn a_key_with_an_invisible_character_beside_text_is_still_taken_as_given() {
    let mut db = store("zero-width-beside-text");
    let about = vec!["re\u{200b}id".to_string()];
    let report = remember(&mut db, &input("Reid reviewed the copy", &about)).expect("remember");
    assert_eq!(report.provisional, about);
    assert!(db.has_node("re\u{200b}id"));
}

/// `matched` counts every key the call named that the store already held: a
/// fact's endpoint as much as an `about` key (defect 48). Each key counts
/// once, however many arguments name it.
#[test]
fn a_fact_endpoint_that_already_exists_is_counted_as_matched() {
    let mut db = store("matched-fact-endpoints");
    remember(
        &mut db,
        &input("Ada and Bob met", &["ada".into(), "bob".into()]),
    )
    .unwrap();
    let fact = |subject: &str, object: &str| FactIn {
        subject: subject.into(),
        predicate: "KNOWS".into(),
        object: object.into(),
    };

    // Both endpoints exist; `carol` does not and is stubbed.
    let facts = [fact("ada", "bob"), fact("bob", "carol")];
    let report = remember(
        &mut db,
        &RememberInput {
            facts: &facts,
            ..input("Ada knows Bob, who knows Carol", &[])
        },
    )
    .expect("remember");
    assert_eq!(report.matched, 2, "{report:?}");
    assert_eq!(report.provisional, vec!["carol".to_string()]);

    // Named in `about` and in a fact, `ada` is still one match.
    let facts = [fact("ada", "bob")];
    let report = remember(
        &mut db,
        &RememberInput {
            facts: &facts,
            ..input("Ada knows Bob, again", &["ada".into()])
        },
    )
    .expect("remember");
    assert_eq!(report.matched, 2, "{report:?}");
}

/// Defect 64: an `entities[]` entry whose key is already stored under a
/// different label matches the stored node, and its own label is not used —
/// so full-text is not declared on it. It used to be, at one pair against the
/// cap for a label with no node in the store. A new key under the same label
/// in the same call still declares it.
#[test]
fn a_label_the_store_disagrees_with_is_not_declared_full_text() {
    let mut db = store("label-disagrees");
    db.insert_node(
        "Person",
        "ada",
        vec![(NAME_FIELD.into(), Value::Str("Ada".into()))],
    )
    .unwrap();
    let entity = |key: &str, label: &str| EntityIn {
        key: key.into(),
        label: label.into(),
        props: BTreeMap::from([("role".to_string(), Value::Str("founder".into()))]),
        aliases: Vec::new(),
    };
    let org_name = ("Guild".to_string(), NAME_FIELD.to_string());

    let entities = vec![entity("ada", "Guild")];
    let report = remember(
        &mut db,
        &RememberInput {
            entities: &entities,
            ..input("Ada founded it", &[])
        },
    )
    .expect("remember");
    assert_eq!((report.matched, report.created), (1, 0), "{report:?}");
    assert_eq!(db.node_info("ada").unwrap().label, "Person");
    assert!(
        report.fulltext_declared.is_empty(),
        "nothing was written under Guild: {report:?}"
    );
    assert!(!db.fulltext_pairs().contains(&org_name));

    let entities = vec![entity("ada", "Guild"), entity("masons", "Guild")];
    let report = remember(
        &mut db,
        &RememberInput {
            entities: &entities,
            ..input("Ada founded the masons", &[])
        },
    )
    .expect("remember");
    assert_eq!((report.matched, report.created), (1, 1), "{report:?}");
    assert_eq!(report.fulltext_declared, vec!["Guild".to_string()]);
    assert!(db.fulltext_pairs().contains(&org_name));
}