oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "context"
5 "fmt"
6 "io"
7 "log/slog"
8 "path/filepath"
9 "reflect"
10 "strings"
11 "testing"
12
13 "amadan.net/rastrillo/rastrillo/db"
14 "amadan.net/rastrillo/rastrillo/migrate"
15
16 "amadan.net/oficina/suite"
17
18 "amadan.net/oficina/memoria/internal/memoria/index"
19 "amadan.net/oficina/memoria/internal/memoria/seal"
20 "amadan.net/oficina/memoria/internal/memoria/sibling"
21)
22
23// fixedCustody rules every candidate the same way and records what it was
24// asked. It is the seam that lets §4.1's table be exercised end to end
25// without a live sibling.
26type fixedCustody struct {
27 calls int
28 // apps is the configured roster. A source not in it does not resolve.
29 apps map[string]sibling.Sibling
30 give suite.Authorization
31 // asked is what reached the client: the asker, and the pairs.
32 asker suite.Subject
33 pairs []suite.ItemRevision
34}
35
36func (f *fixedCustody) Sibling(source string) (sibling.Sibling, bool) {
37 s, ok := f.apps[source]
38 return s, ok
39}
40
41func (f *fixedCustody) Rule(ctx context.Context, asker suite.Subject, cands []sibling.Candidate) []sibling.Disposition {
42 f.calls++
43 f.asker = asker
44 out := make([]sibling.Disposition, len(cands))
45 for i, c := range cands {
46 f.pairs = append(f.pairs, c.Item)
47 out[i] = sibling.Decide(f.give)
48 }
49 return out
50}
51
52func docsRoster() map[string]sibling.Sibling {
53 return map[string]sibling.Sibling{
54 "Docs": {Name: "Docs", BaseURL: "https://docs.example", Token: "t"},
55 }
56}
57
58// storeWithASiblingDocument seeds one document owned by Docs and one owned
59// by memoria, both matching the same query.
60//
61// **Two documents, not one, and that is the presence assertion.** A test
62// with only a sibling document cannot tell "the ruling withheld it" from
63// "the search found nothing"; the memoria-owned row is the control that
64// stays on the page in every case below, so an empty result is always
65// attributable.
66func storeWithASiblingDocument(t *testing.T, custody Custody) *Store {
67 t.Helper()
68 s := storeForTest(t)
69 s.custody = custody
70 ctx := context.Background()
71 if _, err := s.Ingest(ctx, IngestSpec{
72 Source: "Docs", Key: "docs/handbook", Title: "Handbook",
73 Body: "The quarterly planning process runs in March.",
74 ItemID: "docs-item-991",
75 SiblingRevision: 7,
76 }); err != nil {
77 t.Fatalf("ingest sibling doc: %v", err)
78 }
79 if _, err := s.Ingest(ctx, IngestSpec{
80 Source: "upload", Key: "notes.txt", Title: "Notes",
81 Body: "My own notes on the quarterly planning process.",
82 }); err != nil {
83 t.Fatalf("ingest owned doc: %v", err)
84 }
85 return s
86}
87
88// §4.1 end to end, through the only method that returns a renderable
89// passage.
90//
91// This is the gate the sibling package's unit tests cannot be: they prove
92// `Decide` maps values and `Rule` fans out, and neither proves that the
93// thing which actually renders a page consults either. The failure they
94// leave open is a `Search` that computes a disposition and ignores it.
95//
96// MUTATION-TESTED 2026-09-06, each verified red then reverted:
97//
98// Search returns `out` without calling rule()
99// -> every withholding case red
100// rule() keeps a passage when d.Notices() rather than d.Renders()
101// -> VISIBLE case red, NOT_VISIBLE case red
102// rule() treats an unresolvable source as memoria-owned
103// -> the unconfigured-sibling case red
104// rule() skips the nil-custody branch
105// -> nil case red (and it renders, which is the disclosure)
106// Search asks about the memoria-owned document too
107// -> the pairs assertion red
108func TestASiblingPassageIsNeverSpokenUnruled(t *testing.T) {
109 ctx := context.Background()
110
111 for _, c := range []struct {
112 name string
113 give suite.Authorization
114 wantSibling bool
115 wantNotice string
116 }{
117 {"VISIBLE renders", suite.VISIBLE, true, ""},
118 {"NOT_VISIBLE omits silently", suite.NOT_VISIBLE, false, ""},
119 {"STALE withholds loudly", suite.STALE, false, "Docs has moved on from 1 result; refetching."},
120 {"UNKNOWN withholds loudly", suite.UNKNOWN, false, "Docs did not answer; 1 result withheld."},
121 } {
122 t.Run(c.name, func(t *testing.T) {
123 cus := &fixedCustody{apps: docsRoster(), give: c.give}
124 s := storeWithASiblingDocument(t, cus)
125
126 page, err := s.Search(ctx, testAsker, "quarterly planning", 10)
127 if err != nil {
128 t.Fatalf("search: %v", err)
129 }
130
131 var sawSibling, sawOwned bool
132 for _, r := range page.Results {
133 switch r.Source {
134 case "Docs":
135 sawSibling = true
136 case "upload":
137 sawOwned = true
138 }
139 }
140 // The control. Without it, every "the sibling passage is not
141 // here" assertion below is satisfied by a search that found
142 // nothing at all.
143 if !sawOwned {
144 t.Fatal("memoria's own document did not render, so this test " +
145 "cannot tell withholding from an empty search")
146 }
147 if sawSibling != c.wantSibling {
148 t.Errorf("sibling passage rendered = %v, want %v", sawSibling, c.wantSibling)
149 }
150
151 switch c.wantNotice {
152 case "":
153 if len(page.Notices) != 0 {
154 t.Errorf("notices = %v, want none — %q is not a loud value",
155 page.Notices, c.give)
156 }
157 default:
158 if len(page.Notices) != 1 || page.Notices[0] != c.wantNotice {
159 t.Errorf("notices = %v, want [%q]", page.Notices, c.wantNotice)
160 }
161 }
162
163 // The question that went out names the sibling's own
164 // coordinate and this person — and names memoria's own
165 // document to nobody, because §4.2 makes memoria its app of
166 // record and there is nobody else to ask.
167 if len(cus.pairs) != 1 {
168 t.Fatalf("asked about %d items, want 1: memoria's own content "+
169 "has no app of record to ask", len(cus.pairs))
170 }
171 want := suite.ItemRevision{ItemID: "docs-item-991", Revision: 7}
172 if cus.pairs[0] != want {
173 t.Errorf("asked about %+v, want %+v", cus.pairs[0], want)
174 }
175 if cus.asker != testAsker {
176 t.Errorf("asked on behalf of %+v, want %+v", cus.asker, testAsker)
177 }
178 })
179 }
180}
181
182// The two ways there is nobody to ask, which must not become "nobody
183// objects".
184//
185// A sibling dropped from configuration leaves its documents in the store.
186// So does an instance wired without any custody at all. In both, memoria
187// holds a passage whose app of record it cannot reach — and the tempting
188// reading, that an unreachable owner imposes no restriction, is the
189// disclosure §4.1 exists to prevent.
190//
191// MUTATION-TESTED 2026-09-06: make either branch fall through to
192// rendering and the matching case goes red, showing the sibling passage on
193// the page. Reverted.
194func TestNobodyToAskIsNotNobodyObjecting(t *testing.T) {
195 ctx := context.Background()
196
197 t.Run("a source with no configured app of record", func(t *testing.T) {
198 // The roster knows Sheets. The document came from Docs.
199 cus := &fixedCustody{
200 apps: map[string]sibling.Sibling{"Sheets": {Name: "Sheets"}},
201 give: suite.VISIBLE,
202 }
203 s := storeWithASiblingDocument(t, cus)
204
205 page, err := s.Search(ctx, testAsker, "quarterly planning", 10)
206 if err != nil {
207 t.Fatalf("search: %v", err)
208 }
209 assertOnlyOwnedRendered(t, page)
210 if len(cus.pairs) != 0 {
211 t.Errorf("asked %d questions of a sibling that is not configured", len(cus.pairs))
212 }
213 })
214
215 t.Run("no custody at all", func(t *testing.T) {
216 s := storeWithASiblingDocument(t, nil)
217 page, err := s.Search(ctx, testAsker, "quarterly planning", 10)
218 if err != nil {
219 t.Fatalf("search: %v", err)
220 }
221 assertOnlyOwnedRendered(t, page)
222 })
223}
224
225func assertOnlyOwnedRendered(t *testing.T, page Page) {
226 t.Helper()
227 var sawOwned bool
228 for _, r := range page.Results {
229 if r.Source == "Docs" {
230 t.Errorf("a passage from an app of record memoria cannot reach was "+
231 "spoken: %q. An unreachable owner is not an absent one", r.Title)
232 }
233 if r.Source == "upload" {
234 sawOwned = true
235 }
236 }
237 if !sawOwned {
238 t.Fatal("memoria's own document did not render, so this proves nothing")
239 }
240 if len(page.Notices) != 1 || !strings.Contains(page.Notices[0], "did not answer") {
241 t.Errorf("notices = %v, want one saying Docs did not answer — a passage "+
242 "dropped without a notice is a page that reads as complete", page.Notices)
243 }
244}
245
246// A search with nobody on it is refused, not answered.
247//
248// §4.1's question is "may THIS PERSON read this passage", and there is no
249// answer to it for nobody. Refusing here rather than sending an empty
250// subject also keeps the failure on memoria's side of the wire, where it
251// can be read, instead of arriving at a sibling as an unanswerable call.
252//
253// MUTATION-TESTED 2026-09-06: drop the guard and the search returns
254// memoria-owned passages to an unidentified caller. Red. Reverted.
255func TestASearchWithNoAskerIsRefused(t *testing.T) {
256 s := storeWithASiblingDocument(t, &fixedCustody{apps: docsRoster(), give: suite.VISIBLE})
257 page, err := s.Search(context.Background(), suite.Subject{}, "quarterly planning", 10)
258 if err == nil {
259 t.Fatalf("a search with no asker returned %d results", len(page.Results))
260 }
261 if len(page.Results) != 0 {
262 t.Errorf("a refused search still returned passages: %d", len(page.Results))
263 }
264}
265
266// Both or neither: a sibling document needs an item id and a revision.
267//
268// Either half alone is worse than neither. An item id with revision 0 asks
269// a sibling about a body it never issued; a revision with no item id is a
270// document nothing can be asked about, which would then render as
271// memoria's own.
272//
273// MUTATION-TESTED 2026-09-06: default the missing half instead of
274// refusing, and both cases go red — the second one by rendering a sibling
275// document with no ruling at all. Reverted.
276func TestASiblingDocumentNeedsBothHalvesOfItsCoordinate(t *testing.T) {
277 ctx := context.Background()
278 for _, c := range []struct {
279 name string
280 spec IngestSpec
281 }{
282 {"an item id with no revision", IngestSpec{
283 Source: "Docs", Key: "k1", Title: "T", Body: "body", ItemID: "docs-1",
284 }},
285 {"a revision with no item id", IngestSpec{
286 Source: "Docs", Key: "k2", Title: "T", Body: "body", SiblingRevision: 4,
287 }},
288 } {
289 t.Run(c.name, func(t *testing.T) {
290 s := storeForTest(t)
291 if _, err := s.Ingest(ctx, c.spec); err == nil {
292 t.Error("stored a half-coordinated sibling document")
293 }
294 })
295 }
296
297 t.Run("both halves store", func(t *testing.T) {
298 // Without this the two refusals above are satisfied by an Ingest
299 // that refuses every sibling document.
300 s := storeForTest(t)
301 if _, err := s.Ingest(ctx, IngestSpec{
302 Source: "Docs", Key: "k3", Title: "T", Body: "body",
303 ItemID: "docs-3", SiblingRevision: 9,
304 }); err != nil {
305 t.Errorf("a fully-coordinated sibling document was refused: %v", err)
306 }
307 })
308}
309
310// storeForTest is a store with a real database and a real index and no
311// custody set — the caller supplies whatever apps of record the test is
312// about.
313func storeForTest(t *testing.T) *Store {
314 t.Helper()
315 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
316 d, err := db.Open(filepath.Join(t.TempDir(), "store.db"), logger)
317 if err != nil {
318 t.Fatalf("db.Open: %v", err)
319 }
320 t.Cleanup(func() { d.Close() })
321 if _, err := migrate.Apply(context.Background(), d, BootSchema); err != nil {
322 t.Fatalf("migrate: %v", err)
323 }
324 dek := make([]byte, 32)
325 for i := range dek {
326 dek[i] = byte(i*11 + 3)
327 }
328 sealer, err := seal.New(dek)
329 if err != nil {
330 t.Fatalf("seal.New: %v", err)
331 }
332 ix, err := index.Open()
333 if err != nil {
334 t.Fatalf("index.Open: %v", err)
335 }
336 t.Cleanup(func() { ix.Close() })
337 return NewStore(d, sealer, ix, nil)
338}
339
340// A page's notices are in a fixed order, and the order is the reader's.
341//
342// **This is here because the first version was not.** `rule()` built its
343// unresolved-source notices by ranging a `map[int]string`, so a page with
344// two unreachable apps listed them differently on every reload — Go
345// randomises map iteration exactly so that this surfaces, and it did. A
346// notice that moves is a notice a reader stops trusting.
347//
348// The order asserted is the order the results themselves are in, which is
349// the order the reader meets the passages the lines are about.
350//
351// MUTATION-TESTED 2026-09-06, each verified red then reverted:
352//
353// build the notices from a map keyed by result index
354// -> flaky, then red at -count=20 (the failure the fix is for)
355// sort the notices alphabetically
356// -> red: Sheets would precede Wiki regardless of the ranking
357// record only the dropped passages, not every result
358// -> green here, and that is fine — Record ignores a Render. Kept in
359// this list so the next reader knows it was tried and why it is
360// not a finding.
361func TestNoticesAreInResultOrder(t *testing.T) {
362 // Two apps, neither on the roster, so both are unreachable and both
363 // have something to say. Wiki's document scores first because the
364 // query words are denser in it.
365 cus := &fixedCustody{apps: map[string]sibling.Sibling{}, give: suite.VISIBLE}
366 s := storeForTest(t)
367 s.custody = cus
368 ctx := context.Background()
369 for _, d := range []struct {
370 source, key, title, body, item string
371 }{
372 {"Wiki", "wiki/1", "Wiki", "Quarterly planning, quarterly planning, quarterly planning.", "wiki-1"},
373 {"Sheets", "sheets/1", "Sheet", "A note about quarterly planning somewhere in a longer document that dilutes it considerably with many other words.", "sheets-1"},
374 } {
375 if _, err := s.Ingest(ctx, IngestSpec{
376 Source: d.source, Key: d.key, Title: d.title, Body: d.body,
377 ItemID: d.item, SiblingRevision: 3,
378 }); err != nil {
379 t.Fatalf("ingest %s: %v", d.source, err)
380 }
381 }
382
383 want := []string{
384 "Wiki did not answer; 1 result withheld.",
385 "Sheets did not answer; 1 result withheld.",
386 }
387 for i := 0; i < 20; i++ {
388 page, err := s.Search(ctx, testAsker, "quarterly planning", 10)
389 if err != nil {
390 t.Fatalf("search: %v", err)
391 }
392 if len(page.Results) != 0 {
393 t.Fatalf("run %d: %d passages rendered from two unreachable apps",
394 i, len(page.Results))
395 }
396 if !reflect.DeepEqual(page.Notices, want) {
397 t.Fatalf("run %d: notices = %v, want %v — a page whose notices "+
398 "reorder between reloads is a page a reader learns to skip",
399 i, page.Notices, want)
400 }
401 }
402}
403
404// **A count in a notice counts passages, not documents**, and this pins it
405// because nothing did.
406//
407// The two readings differ the moment a document contributes more than one
408// chunk, which is the ordinary case. "3 results withheld" for a
409// three-passage document is right, because the page counts results and a
410// result is a passage — the reader is being told how much shorter their
411// page is, not how many files exist. A review found the choice unmade:
412// recording per distinct pair instead of per candidate left every test
413// green and quietly changed the sentence.
414//
415// MUTATION-TESTED 2026-09-06, each verified red then reverted:
416//
417// Store.rule records per distinct (item, revision) instead of per result
418// -> "1 result withheld"; red
419// Record is moved after the keep check so only drops are recorded
420// -> green, and correctly so: Record ignores a Render. Listed here so
421// the next reader knows it was tried and is not a finding.
422func TestAWithholdingCountCountsPassages(t *testing.T) {
423 ctx := context.Background()
424
425 // One document that chunks into several passages, all of which carry
426 // the same (item_id, revision). Paragraphs, because the chunker splits
427 // on them — a first version repeated one long line and produced a
428 // single chunk, which made the assertion below vacuous.
429 var body strings.Builder
430 for i := 0; i < 12; i++ {
431 body.WriteString("The quarterly planning process runs in March. ")
432 body.WriteString(strings.Repeat("Supporting detail follows in some length. ", 20))
433 body.WriteString("\n\n")
434 }
435 seed := func(t *testing.T, give suite.Authorization) (*Store, *fixedCustody) {
436 t.Helper()
437 cus := &fixedCustody{apps: docsRoster(), give: give}
438 s := storeForTest(t)
439 s.custody = cus
440 if _, err := s.Ingest(ctx, IngestSpec{
441 Source: "Docs", Key: "docs/long", Title: "Long",
442 Body: body.String(), ItemID: "docs-long", SiblingRevision: 2,
443 }); err != nil {
444 t.Fatalf("ingest: %v", err)
445 }
446 return s, cus
447 }
448
449 // **How many passages this document contributes is asked, not
450 // assumed.** Chunking is the chunker's business and it changes; a test
451 // that hard-codes the number tests the chunker by accident and goes
452 // green on 1 when the assertion needs >1 to mean anything.
453 visible, _ := seed(t, suite.VISIBLE)
454 shown, err := visible.Search(ctx, testAsker, "quarterly planning", 10)
455 if err != nil {
456 t.Fatalf("search: %v", err)
457 }
458 passages := len(shown.Results)
459 if passages < 2 {
460 t.Fatalf("the fixture document contributes %d passage(s); with fewer "+
461 "than 2 this test cannot tell passages from documents", passages)
462 }
463
464 withheld, cus := seed(t, suite.UNKNOWN)
465 page, err := withheld.Search(ctx, testAsker, "quarterly planning", 10)
466 if err != nil {
467 t.Fatalf("search: %v", err)
468 }
469 if len(page.Results) != 0 {
470 t.Fatalf("%d passages rendered from an UNKNOWN sibling", len(page.Results))
471 }
472 // The store hands the client **one candidate per passage**, and the
473 // pairs are identical because they are the same document. Collapsing
474 // them into one question is the client's job (`sibling.Client.Rule`,
475 // and TestOneDocumentIsAskedAboutOnce is where that is gated) — it has
476 // to be, because the client is what knows about batches and the wire.
477 //
478 // Keeping the store's side one-per-passage is what makes the mapping
479 // back from answers to results a plain index, which is the thing that
480 // must not go wrong. Asserted here so the division is written down
481 // rather than inferred from whichever test happens to fail.
482 if len(cus.pairs) != passages {
483 t.Errorf("the store offered %d candidates for %d passages of one "+
484 "document, want one each", len(cus.pairs), passages)
485 }
486 for _, p := range cus.pairs {
487 if want := (suite.ItemRevision{ItemID: "docs-long", Revision: 2}); p != want {
488 t.Errorf("candidate %+v, want %+v — every passage of a document "+
489 "carries that document's coordinate", p, want)
490 }
491 }
492 want := []string{fmt.Sprintf("Docs did not answer; %d results withheld.", passages)}
493 if !reflect.DeepEqual(page.Notices, want) {
494 t.Errorf("notices = %v, want %v — the count is passages, which is what "+
495 "the page calls results, and not documents", page.Notices, want)
496 }
497}
498
499// Two siblings both withholding on one page, which is §6.5's ordinary
500// cold-wake case and had no fixture at all.
501//
502// It is here for two reasons. The obvious one is the copy: two apps, two
503// lines, in result order. The other is that this is the shape that makes a
504// concurrency bug in notice accumulation observable — a reviewer moved the
505// recording inside the fan-out goroutines and it stayed green under
506// `-race` purely because no test ever had two loud siblings at once. The
507// aggregation has since moved out of the concurrent path entirely, and
508// this runs with `-race` in CI so the fixture is there if it ever moves
509// back.
510func TestTwoSiblingsWithholdingOnOnePage(t *testing.T) {
511 // Neither on the roster, so both are unreachable.
512 cus := &fixedCustody{apps: map[string]sibling.Sibling{}, give: suite.VISIBLE}
513 s := storeForTest(t)
514 s.custody = cus
515 ctx := context.Background()
516 for _, d := range []struct{ source, key, body, item string }{
517 {"Sheets", "s/1", "Quarterly planning, quarterly planning, quarterly planning, quarterly planning.", "s-1"},
518 {"Sheets", "s/2", "Quarterly planning, quarterly planning, quarterly planning.", "s-2"},
519 {"Docs", "d/1", "A shorter note on quarterly planning buried in a great many other unrelated words indeed.", "d-1"},
520 } {
521 if _, err := s.Ingest(ctx, IngestSpec{
522 Source: d.source, Key: d.key, Title: d.key, Body: d.body,
523 ItemID: d.item, SiblingRevision: 1,
524 }); err != nil {
525 t.Fatalf("ingest %s: %v", d.key, err)
526 }
527 }
528
529 page, err := s.Search(ctx, testAsker, "quarterly planning", 10)
530 if err != nil {
531 t.Fatalf("search: %v", err)
532 }
533 if len(page.Results) != 0 {
534 t.Fatalf("%d passages rendered from two unreachable apps", len(page.Results))
535 }
536 want := []string{
537 "Sheets did not answer; 2 results withheld.",
538 "Docs did not answer; 1 result withheld.",
539 }
540 if !reflect.DeepEqual(page.Notices, want) {
541 t.Errorf("notices = %v, want %v — grouped per app, counted per "+
542 "passage, ordered by the results they are about",
543 page.Notices, want)
544 }
545}
546
547// storeAt is storeForTest over a directory the caller keeps, so a test can
548// close one Store and open another over the same database — which is what
549// a wake is, and the only way to assert that anything is durable rather
550// than in memory.
551func storeAt(t *testing.T, dir string) *Store {
552 t.Helper()
553 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
554 d, err := db.Open(filepath.Join(dir, "store.db"), logger)
555 if err != nil {
556 t.Fatalf("db.Open: %v", err)
557 }
558 t.Cleanup(func() { d.Close() })
559 if _, err := migrate.Apply(context.Background(), d, BootSchema); err != nil {
560 t.Fatalf("migrate: %v", err)
561 }
562 // The SAME key both times. A fresh DEK would make every sealed row
563 // unreadable, and the test would then be asserting that a restart
564 // loses the counters rather than keeps them.
565 dek := make([]byte, 32)
566 for i := range dek {
567 dek[i] = byte(i*11 + 3)
568 }
569 sealer, err := seal.New(dek)
570 if err != nil {
571 t.Fatalf("seal.New: %v", err)
572 }
573 ix, err := index.Open()
574 if err != nil {
575 t.Fatalf("index.Open: %v", err)
576 }
577 t.Cleanup(func() { ix.Close() })
578 return NewStore(d, sealer, ix, nil)
579}
580