| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "mime/multipart" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/url" |
| 11 | "strings" |
| 12 | "sync/atomic" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/home/roster" |
| 17 | "amadan.net/oficina/home/teammode" |
| 18 | "amadan.net/oficina/suite" |
| 19 | |
| 20 | "amadan.net/oficina/memoria/internal/memoria/notion" |
| 21 | ) |
| 22 | |
| 23 | // lapsingGuard makes team-mode writes' lease run out between the write and |
| 24 | // its commit: the directory goes down and the clock passes the lease |
| 25 | // inside the transaction, so the guard's after-check reads Unknown. With |
| 26 | // at > 0 only the at-th guarded call lapses (counting from 1); with 0, |
| 27 | // every one. |
| 28 | func lapsingGuard(t *testing.T, f *teamFixture, at int32) func(context.Context, func(roster.State) error, func() error) error { |
| 29 | t.Helper() |
| 30 | var n atomic.Int32 |
| 31 | teamGuard = func(ctx context.Context, authorize func(roster.State) error, write func() error) error { |
| 32 | return teammode.Guard(ctx, authorize, func() error { |
| 33 | err := write() |
| 34 | if k := n.Add(1); at == 0 || k == at { |
| 35 | f.dir.SetDown(true) |
| 36 | f.clock.Step(roster.MaximumAge + time.Second) |
| 37 | } |
| 38 | return err |
| 39 | }) |
| 40 | } |
| 41 | t.Cleanup(func() { teamGuard = teammode.Guard }) |
| 42 | return teamGuard |
| 43 | } |
| 44 | |
| 45 | // emptySource is a Notion with nothing in it, for the connector routes. |
| 46 | type emptySource struct{} |
| 47 | |
| 48 | func (emptySource) Roots(context.Context) ([]notion.Ref, []notion.Ref, error) { return nil, nil, nil } |
| 49 | func (emptySource) Fetch(context.Context, notion.Ref) (*notion.Content, error) { |
| 50 | return nil, errors.New("no pages") |
| 51 | } |
| 52 | |
| 53 | // multipartBody is a create-content form: fields, and files by name. |
| 54 | func multipartBody(t *testing.T, fields, files map[string]string) (string, string) { |
| 55 | t.Helper() |
| 56 | var b bytes.Buffer |
| 57 | w := multipart.NewWriter(&b) |
| 58 | for k, v := range fields { |
| 59 | w.WriteField(k, v) |
| 60 | } |
| 61 | for name, body := range files { |
| 62 | part, err := w.CreateFormFile("file", name) |
| 63 | if err != nil { |
| 64 | t.Fatal(err) |
| 65 | } |
| 66 | part.Write([]byte(body)) |
| 67 | } |
| 68 | w.Close() |
| 69 | return b.String(), w.FormDataContentType() |
| 70 | } |
| 71 | |
| 72 | func (f *teamFixture) multipart(path string, fields, files map[string]string) *httptest.ResponseRecorder { |
| 73 | body, ct := multipartBody(f.t, fields, files) |
| 74 | r := httptest.NewRequest("POST", homeTestOrigin+path, strings.NewReader(body)) |
| 75 | r.Header.Set("Content-Type", ct) |
| 76 | r.Header.Set("Origin", homeTestOrigin) |
| 77 | r.Header.Set("Accept", "text/html") |
| 78 | for _, c := range f.cookies { |
| 79 | r.AddCookie(c) |
| 80 | } |
| 81 | return f.send(r) |
| 82 | } |
| 83 | |
| 84 | // teamSnapshot is what a refused write must leave exactly as it was: every |
| 85 | // table a person's write reaches, and the one sealed column one of them |
| 86 | // updates in place. |
| 87 | type teamSnapshot struct { |
| 88 | documents, chunks, reports, feedback, connectors, runs, pages int |
| 89 | feedbackSealed, connectorSealed string |
| 90 | searchable bool |
| 91 | } |
| 92 | |
| 93 | func (f *teamFixture) snapshot() teamSnapshot { |
| 94 | f.t.Helper() |
| 95 | s := teamSnapshot{ |
| 96 | documents: f.count("documents"), chunks: f.count("chunks"), reports: f.count("fact_reports"), |
| 97 | feedback: f.count("answer_feedbacks"), connectors: f.count("connectors"), runs: f.count("sync_runs"), pages: f.count("source_pages"), |
| 98 | } |
| 99 | var sealed []byte |
| 100 | f.d.Writer().QueryRow("SELECT sealed_feedback FROM answer_feedbacks ORDER BY id LIMIT 1").Scan(&sealed) |
| 101 | s.feedbackSealed = string(sealed) |
| 102 | var token []byte |
| 103 | f.d.Writer().QueryRow("SELECT sealed_token FROM connectors ORDER BY id LIMIT 1").Scan(&token) |
| 104 | s.connectorSealed = string(token) |
| 105 | page, err := f.app.store.Search(context.Background(), suite.Subject{Kind: suite.SubjectPersonRef, Value: teamSubject('a')}, "nebula", 25) |
| 106 | s.searchable = err == nil && len(page.Results) > 0 |
| 107 | return s |
| 108 | } |
| 109 | |
| 110 | // Every write route, with the lease lapsing between the write and its |
| 111 | // commit: each answers the retryable 503, and nothing any of them wrote |
| 112 | // survived — the database is read back, not just the status (Fable's #53 |
| 113 | // required test 2, for Memoria), and the deleted document is still found. |
| 114 | // |
| 115 | // MUTATION-TESTED 2026-10-30, each seen red and reverted: Store.guard |
| 116 | // returning write() in team mode (every route); guard's after-check |
| 117 | // dropped in teammode.Guard's place (every route); Ingest's transaction |
| 118 | // unguarded ("paste", "upload", "native note"); DeleteReport and |
| 119 | // DeleteFeedback through the outer handle ("report delete", "feedback |
| 120 | // delete"); connector writes guarded as memberWrite (see the owner test). |
| 121 | func TestTeamEveryWriteRouteRefusesALapseBeforeCommit(t *testing.T) { |
| 122 | f := newTeamFixture(t) |
| 123 | f.app.UseFakeSource(emptySource{}, func(context.Context, string) (string, error) { return "workspace", nil }) |
| 124 | f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| 125 | doc := f.ingest("office", "Office", "## Office Address\n\nThe office phone number is:\n+353 (0)1 547 7854\n") |
| 126 | // Two people: every route a member may use runs as a roster MEMBER, |
| 127 | // and only the connector routes as the roster owner — so a write |
| 128 | // guarded as an owner's by mistake is refused on its success half. |
| 129 | f.member(teamSubject('o'), "owner") |
| 130 | f.member(teamSubject('a'), "member") |
| 131 | member := f.asMember(teamSubject('a')) |
| 132 | asker := suite.Subject{Kind: suite.SubjectPersonRef, Value: teamSubject('a')} |
| 133 | |
| 134 | // The rows the delete and update routes act on, written under the |
| 135 | // real guard as the member. |
| 136 | if err := f.app.store.SaveCorrection(member, asker, "office phone number", "phone", "none", "first"); err != nil { |
| 137 | t.Fatal(err) |
| 138 | } |
| 139 | handle, err := f.app.store.sealFeedbackHandle(feedbackHandle{Asker: teamSubject('a'), Query: "nebula"}) |
| 140 | if err != nil { |
| 141 | t.Fatal(err) |
| 142 | } |
| 143 | fid, _, err := f.app.store.SaveFeedback(member, asker, handle, "down") |
| 144 | if err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | if err := f.app.store.SaveConnector(f.asMember(teamSubject('o')), "notion", "secret-token", "workspace"); err != nil { |
| 148 | t.Fatal(err) |
| 149 | } |
| 150 | var report int64 |
| 151 | f.d.Writer().QueryRow("SELECT id FROM fact_reports LIMIT 1").Scan(&report) |
| 152 | lapsing := lapsingGuard(t, f, 0) |
| 153 | |
| 154 | routes := []struct { |
| 155 | name string |
| 156 | do func() *httptest.ResponseRecorder |
| 157 | owner bool |
| 158 | }{ |
| 159 | {"paste", func() *httptest.ResponseRecorder { |
| 160 | return f.multipart("/documents", map[string]string{"title": "Pasted", "body": "nebula pasted"}, nil) |
| 161 | }, false}, |
| 162 | {"upload", func() *httptest.ResponseRecorder { |
| 163 | return f.multipart("/documents", nil, map[string]string{"nebula.txt": "nebula uploaded"}) |
| 164 | }, false}, |
| 165 | {"correction", func() *httptest.ResponseRecorder { |
| 166 | return f.form("/facts/correct", url.Values{"q": {"office phone number"}, "kind": {"phone"}, "choice": {"none"}, "note": {"x"}}.Encode()) |
| 167 | }, false}, |
| 168 | {"report delete", func() *httptest.ResponseRecorder { return f.form("/reports/"+itoa64(report)+"/delete", "") }, false}, |
| 169 | {"feedback", func() *httptest.ResponseRecorder { |
| 170 | return f.form("/answer/feedback", url.Values{"handle": {handle}, "verdict": {"up"}}.Encode()) |
| 171 | }, false}, |
| 172 | {"feedback note", func() *httptest.ResponseRecorder { |
| 173 | return f.form("/answer/feedback/"+itoa64(fid), url.Values{"note": {"changed"}}.Encode()) |
| 174 | }, false}, |
| 175 | {"feedback delete", func() *httptest.ResponseRecorder { return f.form("/answer/feedback/"+itoa64(fid)+"/delete", "") }, false}, |
| 176 | {"native note", func() *httptest.ResponseRecorder { |
| 177 | return f.json("POST", "/api/native/notes", `{"title":"Note","body":"nebula noted"}`) |
| 178 | }, false}, |
| 179 | {"connector save", func() *httptest.ResponseRecorder { |
| 180 | return f.form("/connectors/notion", url.Values{"token": {"another-token"}}.Encode()) |
| 181 | }, true}, |
| 182 | {"connector sync", func() *httptest.ResponseRecorder { return f.form("/connectors/notion/sync", "") }, true}, |
| 183 | {"connector disconnect", func() *httptest.ResponseRecorder { return f.form("/connectors/notion/disconnect", "") }, true}, |
| 184 | {"delete", func() *httptest.ResponseRecorder { return f.form("/documents/"+itoa64(doc)+"/delete", "") }, false}, |
| 185 | } |
| 186 | for _, route := range routes { |
| 187 | t.Run(route.name, func(t *testing.T) { |
| 188 | who, role := teamSubject('a'), "member" |
| 189 | if route.owner { |
| 190 | who, role = teamSubject('o'), "owner" |
| 191 | } |
| 192 | f.member(who, role) |
| 193 | f.renewed() |
| 194 | before := f.snapshot() |
| 195 | if !before.searchable { |
| 196 | t.Fatal("the fixture's document is not searchable before the route") |
| 197 | } |
| 198 | got := route.do() |
| 199 | if got.Code != http.StatusServiceUnavailable || got.Header().Get("Retry-After") == "" || got.Header().Get("Cache-Control") != "no-store" { |
| 200 | t.Fatalf("%s with a lapse before commit = %d %v, want a retryable no-store 503:\n%s", route.name, got.Code, got.Header(), got.Body.String()) |
| 201 | } |
| 202 | if after := f.snapshot(); after != before { |
| 203 | t.Fatalf("%s: a refused write changed the database\nbefore %+v\nafter %+v", route.name, before, after) |
| 204 | } |
| 205 | // The presence half: the same request under the real guard |
| 206 | // writes, so the refusal above was the lapse and not a route |
| 207 | // that writes nothing. |
| 208 | teamGuard = teammode.Guard |
| 209 | defer func() { teamGuard = lapsing }() |
| 210 | f.renewed() |
| 211 | f.member(who, role) |
| 212 | if got := route.do(); got.Code >= 400 { |
| 213 | t.Fatalf("%s under the real guard = %d:\n%s", route.name, got.Code, got.Body.String()) |
| 214 | } |
| 215 | if route.name == "connector sync" && !f.app.WaitForSync(1, 5*time.Second) { |
| 216 | t.Fatal("the sync run did not finish") |
| 217 | } |
| 218 | if after := f.snapshot(); after == before { |
| 219 | t.Fatalf("%s under the real guard changed nothing; the refusal proves nothing", route.name) |
| 220 | } |
| 221 | }) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // Delete's index removal precedes its transaction (AGENTS.md), so a |
| 226 | // standing that holds for the pre-check and lapses inside the transaction |
| 227 | // must put the passages back: the refused delete leaves the document |
| 228 | // whole AND findable, not stored-but-unfindable until the next boot. |
| 229 | // |
| 230 | // MUTATION-TESTED 2026-10-30: the re-index after a standing refusal |
| 231 | // removed → "not findable"; the pre-check removed → still green here (the |
| 232 | // in-transaction guard and the re-index cover it), red in the table above. |
| 233 | func TestTeamRefusedDeleteKeepsTheDocumentFindable(t *testing.T) { |
| 234 | f := newTeamFixture(t) |
| 235 | doc := f.ingest("plan", "Nebula plan", "The nebula plan is ready.") |
| 236 | f.member(teamSubject('a'), "member") |
| 237 | lapsingGuard(t, f, 2) // the pre-check holds; the transaction's lapses |
| 238 | if got := f.form("/documents/"+itoa64(doc)+"/delete", ""); got.Code != http.StatusServiceUnavailable { |
| 239 | t.Fatalf("delete lapsing in its transaction = %d, want 503", got.Code) |
| 240 | } |
| 241 | if f.count("documents") != 1 { |
| 242 | t.Fatal("the document was deleted") |
| 243 | } |
| 244 | if s := f.snapshot(); !s.searchable { |
| 245 | t.Fatal("a refused delete left the document stored but not findable") |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | // In team mode a person's write with no standing on its context is |
| 250 | // refused (closed), and the instance's own work — a connector run, a |
| 251 | // sibling poll — is a systemWrite and is not guarded. Outside team mode |
| 252 | // the guard is the write path exactly as it was. |
| 253 | // |
| 254 | // MUTATION-TESTED 2026-10-30: guard letting a context with no Access |
| 255 | // through → "no standing"; systemWrite not honoured → "system". |
| 256 | func TestTeamWritesNeedStandingAndSystemWorkDoesNot(t *testing.T) { |
| 257 | f := newTeamFixture(t) |
| 258 | spec := IngestSpec{Source: "upload", Key: "k", Title: "Nebula", Body: "nebula"} |
| 259 | if _, err := f.app.store.Ingest(context.Background(), spec); !errors.Is(err, teammode.ErrUnavailable) { |
| 260 | t.Fatalf("no standing: ingest = %v, want ErrUnavailable", err) |
| 261 | } |
| 262 | if f.count("documents") != 0 { |
| 263 | t.Fatal("no standing: a document was stored") |
| 264 | } |
| 265 | if _, err := f.app.store.Ingest(systemWrite(context.Background()), spec); err != nil { |
| 266 | t.Fatalf("system: ingest = %v", err) |
| 267 | } |
| 268 | // A systemWrite drops whatever Access the context carried, so a run |
| 269 | // that outlives its request is not bound to that request's lease. |
| 270 | f.member(teamSubject('a'), "owner") |
| 271 | ctx := systemWrite(f.asMember(teamSubject('a'))) |
| 272 | if _, ok := teammode.FromContext(ctx); ok { |
| 273 | t.Fatal("a systemWrite kept the request's Access") |
| 274 | } |
| 275 | |
| 276 | off := storeForTest(t) |
| 277 | if _, err := off.Ingest(context.Background(), spec); err != nil { |
| 278 | t.Fatalf("team mode off: ingest = %v", err) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // The connectors are the roster owner's inside the write too: a member's |
| 283 | // standing commits no connector write, whatever reached the store. |
| 284 | // |
| 285 | // MUTATION-TESTED 2026-10-30: authorizeFor ignoring ownerWrite → red. |
| 286 | func TestTeamConnectorWritesNeedTheOwnerRole(t *testing.T) { |
| 287 | f := newTeamFixture(t) |
| 288 | f.member(teamSubject('m'), "member") |
| 289 | member := f.asMember(teamSubject('m')) |
| 290 | if err := f.app.store.SaveConnector(member, "notion", "t", "w"); !errors.Is(err, teammode.ErrNotMember) { |
| 291 | t.Fatalf("a member's connector save = %v, want ErrNotMember", err) |
| 292 | } |
| 293 | if _, err := f.app.store.StartRun(member, 1); !errors.Is(err, teammode.ErrNotMember) { |
| 294 | t.Fatalf("a member's sync start = %v, want ErrNotMember", err) |
| 295 | } |
| 296 | if err := f.app.store.DeleteConnector(member, "notion"); !errors.Is(err, teammode.ErrNotMember) { |
| 297 | t.Fatalf("a member's disconnect = %v, want ErrNotMember", err) |
| 298 | } |
| 299 | if f.count("connectors") != 0 || f.count("sync_runs") != 0 { |
| 300 | t.Fatal("a member's connector write landed") |
| 301 | } |
| 302 | f.member(teamSubject('o'), "owner") |
| 303 | if err := f.app.store.SaveConnector(f.asMember(teamSubject('o')), "notion", "t", "w"); err != nil { |
| 304 | t.Fatalf("an owner's connector save = %v", err) |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | // Fable's N1 (#32): every write `guarded` runs is INSIDE Guard — checked |
| 309 | // without the lapsing seam, whose wrapper sits around whatever is handed to |
| 310 | // Guard and so cannot tell "authorize, write, authorize" from "authorize, |
| 311 | // authorize, write" (M27 survived the route table that way). Here the |
| 312 | // write's own body lapses the standing, so only an after-check that runs |
| 313 | // after the write can refuse it, and the row must be absent. The same for |
| 314 | // guard, which Ingest and Delete call around their bodies. |
| 315 | // |
| 316 | // MUTATION-TESTED 2026-10-30: M27 (guarded runs Guard with a no-op write, |
| 317 | // then writes in the same transaction) → "guarded"; guard calling write |
| 318 | // after teamGuard → "guard". |
| 319 | func TestTeamGuardedWritesRunInsideGuard(t *testing.T) { |
| 320 | f := newTeamFixture(t) |
| 321 | f.member(teamSubject('a'), "member") |
| 322 | insert := func(db *gormTx, n string) error { |
| 323 | return db.Create(&FactReport{ReporterPrint: n, SealedReport: []byte{1}}).Error |
| 324 | } |
| 325 | rows := func(n string) int { |
| 326 | var c int |
| 327 | f.d.Writer().QueryRow("SELECT COUNT(*) FROM fact_reports WHERE reporter_print=?", n).Scan(&c) |
| 328 | return c |
| 329 | } |
| 330 | |
| 331 | // The presence half: a write whose standing holds commits. |
| 332 | if err := f.app.store.guarded(f.asMember(teamSubject('a')), memberWrite, func(db *gormTx) error { return insert(db, "kept") }); err != nil || rows("kept") != 1 { |
| 333 | t.Fatalf("a write under standing = %v, %d rows", err, rows("kept")) |
| 334 | } |
| 335 | |
| 336 | f.renewed() |
| 337 | err := f.app.store.guarded(f.asMember(teamSubject('a')), memberWrite, func(db *gormTx) error { |
| 338 | f.expired() |
| 339 | return insert(db, "guarded") |
| 340 | }) |
| 341 | if !errors.Is(err, teammode.ErrUnavailable) || rows("guarded") != 0 { |
| 342 | t.Fatalf("guarded: a write that lapsed its own standing = %v, %d rows; want refused and absent", err, rows("guarded")) |
| 343 | } |
| 344 | |
| 345 | f.recovered() |
| 346 | err = f.app.store.db.G.Transaction(func(tx *gormTx) error { |
| 347 | return f.app.store.guard(f.asMember(teamSubject('a')), memberWrite, func() error { |
| 348 | f.expired() |
| 349 | return insert(tx, "guard") |
| 350 | }) |
| 351 | }) |
| 352 | if !errors.Is(err, teammode.ErrUnavailable) || rows("guard") != 0 { |
| 353 | t.Fatalf("guard: a write that lapsed its own standing = %v, %d rows; want refused and absent", err, rows("guard")) |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | // Fable's N2 (#32): an owner write whose lease lapses between Guard's |
| 358 | // standing and the role read is Unknown — the retryable 503 — not a 404; |
| 359 | // a member's owner write is still a definite no. |
| 360 | // |
| 361 | // MUTATION-TESTED 2026-10-30: the State re-check in authorizeFor removed → |
| 362 | // "lapsed owner". |
| 363 | func TestTeamOwnerWriteLapsingAtTheRoleIsUnavailable(t *testing.T) { |
| 364 | f := newTeamFixture(t) |
| 365 | f.member(teamSubject('o'), "owner") |
| 366 | f.member(teamSubject('m'), "member") |
| 367 | member := f.app.team.Access(context.Background(), teamSubject('m')) |
| 368 | if err := authorizeFor(ownerWrite, member)(roster.Member); !errors.Is(err, teammode.ErrNotMember) { |
| 369 | t.Fatalf("member's owner write = %v, want ErrNotMember", err) |
| 370 | } |
| 371 | owner := f.app.team.Access(context.Background(), teamSubject('o')) |
| 372 | if err := authorizeFor(ownerWrite, owner)(roster.Member); err != nil { |
| 373 | t.Fatalf("owner's owner write = %v", err) |
| 374 | } |
| 375 | f.expired() |
| 376 | // Guard read Member a moment ago; the role read finds the lease gone. |
| 377 | if err := authorizeFor(ownerWrite, owner)(roster.Member); !errors.Is(err, teammode.ErrUnavailable) { |
| 378 | t.Fatalf("lapsed owner: owner write = %v, want ErrUnavailable", err) |
| 379 | } |
| 380 | } |
| 381 | |