| 1 | package fichas |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/binary" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "log/slog" |
| 9 | "path/filepath" |
| 10 | "testing" |
| 11 | "testing/fstest" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/rastrillo/rastrillo/auth" |
| 15 | "amadan.net/rastrillo/rastrillo/db" |
| 16 | "amadan.net/rastrillo/rastrillo/migrate" |
| 17 | "amadan.net/rastrillo/rastrillo/sessions" |
| 18 | "gorm.io/gorm" |
| 19 | |
| 20 | "amadan.net/oficina/fichas/internal/fichas/seal" |
| 21 | "amadan.net/oficina/suite" |
| 22 | "amadan.net/oficina/suite/server" |
| 23 | ) |
| 24 | |
| 25 | // Card revisions and nonces are random positive int63s (spec §6.2, |
| 26 | // store.go nextRevision and randomPositive): never zero, never repeated |
| 27 | // between two cards made one after the other, never the current value. |
| 28 | // |
| 29 | // MUTATION-TESTED 2026-11-01, each reverted: revisions as a count |
| 30 | // (current + 1) → "two new cards"; as the clock under a frozen clock |
| 31 | // (max(current + 1, a fixed instant)) → "two new cards"; as the real clock |
| 32 | // (max(current + 1, now in microseconds)) → "repeated" (draws inside one |
| 33 | // microsecond); randomPositive without its sign mask → negative nonces, |
| 34 | // which the insert triggers refuse, so "creating" (and most of the |
| 35 | // package); a card's or an event's nonce left unset → likewise. The zero |
| 36 | // and equal-to-current redraws guard 2^-63 draws a real reader never hands |
| 37 | // a test; TestRedrawsHappen forces them. |
| 38 | func TestRevisionsAndNoncesAreRandom(t *testing.T) { |
| 39 | g, s := seeded(t) |
| 40 | a, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "A"}) |
| 41 | if err != nil { |
| 42 | t.Fatalf("creating: %v", err) |
| 43 | } |
| 44 | b, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "B"}) |
| 45 | if err != nil { |
| 46 | t.Fatalf("creating: %v", err) |
| 47 | } |
| 48 | if a.Revision == b.Revision || a.Nonce == b.Nonce { |
| 49 | t.Errorf("two new cards share a revision (%d, %d) or a nonce (%d, %d)", a.Revision, b.Revision, a.Nonce, b.Nonce) |
| 50 | } |
| 51 | seen := map[int64]bool{} |
| 52 | for i := 0; i < 2000; i++ { |
| 53 | r := nextRevision(int64(i)) |
| 54 | if r < 1 { |
| 55 | t.Fatalf("not positive: %d", r) |
| 56 | } |
| 57 | if r == int64(i) || seen[r] { |
| 58 | t.Fatalf("draw %d repeated %d", i, r) |
| 59 | } |
| 60 | seen[r] = true |
| 61 | } |
| 62 | var evs []Event |
| 63 | g.Find(&evs) |
| 64 | for _, e := range evs { |
| 65 | if e.Nonce < 1 { |
| 66 | t.Fatalf("event %d has nonce %d", e.ID, e.Nonce) |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | // The nonce columns are write-once and positive, in the schema itself |
| 72 | // (migrations/0005), not only by convention: no insert at zero or below, |
| 73 | // and no change after, up or down. |
| 74 | // |
| 75 | // MUTATION-TESTED 2026-11-01, each reverted: each of the four triggers |
| 76 | // disabled → its rows; the write-once triggers loosened to refuse only an |
| 77 | // increase (NEW.nonce > OLD.nonce) → "decreased"; the insert triggers |
| 78 | // loosened to refuse only zero (= 0) → "negative". |
| 79 | func TestNoncesAreWriteOnceInTheSchema(t *testing.T) { |
| 80 | g, a, _ := suiteWorld(t) |
| 81 | c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| 82 | for name, stmt := range map[string]string{ |
| 83 | "a card's nonce increased": "UPDATE cards SET nonce = nonce + 1 WHERE id = ?", |
| 84 | "a card's nonce decreased": "UPDATE cards SET nonce = nonce - 1 WHERE id = ?", |
| 85 | "an event's nonce increased": "UPDATE events SET nonce = nonce + 1 WHERE object_kind = 'card' AND object_id = ?", |
| 86 | "an event's nonce decreased": "UPDATE events SET nonce = nonce - 1 WHERE object_kind = 'card' AND object_id = ?", |
| 87 | "a card without one": "INSERT INTO cards (card_type_id, revision, nonce) SELECT card_type_id, 1, 0 FROM cards WHERE id = ?", |
| 88 | "a card with a negative one": "INSERT INTO cards (card_type_id, revision, nonce) SELECT card_type_id, 1, -5 FROM cards WHERE id = ?", |
| 89 | "an event without one": "INSERT INTO events (kind, object_kind, object_id, nonce) VALUES ('updated', 'card', ?, 0)", |
| 90 | "an event with a negative one": "INSERT INTO events (kind, object_kind, object_id, nonce) VALUES ('updated', 'card', ?, -5)", |
| 91 | } { |
| 92 | if err := g.Exec(stmt, c.ID).Error; err == nil { |
| 93 | t.Errorf("%s: the schema allowed it", name) |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | // frozen pins a database's clock — what stamps created_at — to one |
| 99 | // instant: a clock that stopped, or was set back to where it was when the |
| 100 | // backup was taken. |
| 101 | var frozen = time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC) |
| 102 | |
| 103 | // restorable is a producer over a database file, so it can be backed up |
| 104 | // and a backup opened in its place, with that database's clock frozen. |
| 105 | func restorable(t *testing.T, path string) (*gorm.DB, *app, *suiteProducer) { |
| 106 | t.Helper() |
| 107 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 108 | d, err := db.Open(path, logger) |
| 109 | if err != nil { |
| 110 | t.Fatal(err) |
| 111 | } |
| 112 | t.Cleanup(func() { d.Close() }) |
| 113 | d.G.Config.NowFunc = func() time.Time { return frozen } |
| 114 | if _, err := migrate.Apply(ctx(), d, BootSchema); err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | s := testSealer(t) |
| 118 | if err := Seed(d.G, s); err != nil { |
| 119 | t.Fatal(err) |
| 120 | } |
| 121 | var n int64 |
| 122 | d.G.Model(&Member{}).Count(&n) |
| 123 | if n == 0 { |
| 124 | pr, _ := s.Print("f_member", []byte("person-1@example.com")) |
| 125 | if err := d.G.Create(&Member{AddressPrint: pr}).Error; err != nil { |
| 126 | t.Fatal(err) |
| 127 | } |
| 128 | } |
| 129 | a := &app{sealer: s, owners: ParseOwners(admittedAsker)} |
| 130 | return d.G, a, producerFor(d.G, a) |
| 131 | } |
| 132 | |
| 133 | func backUp(t *testing.T, g *gorm.DB, to string) { |
| 134 | t.Helper() |
| 135 | if err := g.Exec("VACUUM INTO ?", to).Error; err != nil { |
| 136 | t.Fatalf("backing up: %v", err) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | func revisionOf(t *testing.T, g *gorm.DB, id int64) int64 { |
| 141 | t.Helper() |
| 142 | var c Card |
| 143 | if err := g.First(&c, id).Error; err != nil { |
| 144 | t.Fatal(err) |
| 145 | } |
| 146 | return c.Revision |
| 147 | } |
| 148 | |
| 149 | func askHeld(t *testing.T, p *suiteProducer, held suite.ItemRevision) suite.Authorization { |
| 150 | t.Helper() |
| 151 | got, err := p.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{held}) |
| 152 | if err != nil { |
| 153 | t.Fatal(err) |
| 154 | } |
| 155 | return got[0] |
| 156 | } |
| 157 | |
| 158 | // The gap the item id's nonce cannot close (spec §6.2): a card that |
| 159 | // predates the restore point keeps its id and nonce, so a revision issued |
| 160 | // after the backup must not be issued again after the restore. Back up, |
| 161 | // edit (memoria holds that revision), restore, edit again — on a frozen |
| 162 | // clock, which is what made clock revisions reissue. The held revision is |
| 163 | // not in the restored log, so it is UNKNOWN before the edit and after it, |
| 164 | // never VISIBLE, and S3 refuses it. |
| 165 | // |
| 166 | // MUTATION-TESTED 2026-11-01, each reverted: revisions as a count |
| 167 | // (current + 1) → "reissued", "after the edit" (VISIBLE for the abandoned |
| 168 | // copy), "S3"; as a frozen clock (max(current + 1, a fixed instant)) → the |
| 169 | // same three; every non-current revision STALE → "before the edit". (STALE |
| 170 | // read off the numbers is caught here only when the random held value |
| 171 | // happens to be the lower; TestSuiteRuleEveryBranch catches it every time.) |
| 172 | func TestSuiteRestoreCannotReissueAHeldRevision(t *testing.T) { |
| 173 | dir := t.TempDir() |
| 174 | live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db") |
| 175 | |
| 176 | g, a, p := restorable(t, live) |
| 177 | card := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| 178 | backUp(t, g, backup) |
| 179 | if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldNotes: "the text memoria holds"}); err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | held := suite.ItemRevision{ItemID: id(card), Revision: revisionOf(t, g, card.ID)} |
| 183 | if got := askHeld(t, p, held); got != suite.VISIBLE { |
| 184 | t.Fatalf("before the restore, the held revision: %s", got) |
| 185 | } |
| 186 | |
| 187 | g2, a2, p2 := restorable(t, backup) // the restore |
| 188 | if got := askHeld(t, p2, held); got != suite.UNKNOWN { |
| 189 | t.Errorf("before the edit: the restored card never had the held revision, got %s, want UNKNOWN", got) |
| 190 | } |
| 191 | if err := UpdateCard(ctx(), g2, a2.sealer, card.ID, Person(1), map[string]string{FieldNotes: "different text"}); err != nil { |
| 192 | t.Fatal(err) |
| 193 | } |
| 194 | if now := revisionOf(t, g2, card.ID); now == held.Revision { |
| 195 | t.Errorf("reissued: revision %d names the abandoned text and the new", now) |
| 196 | } |
| 197 | if got := askHeld(t, p2, held); got != suite.UNKNOWN { |
| 198 | t.Errorf("after the edit, the held revision: %s, want UNKNOWN (never VISIBLE)", got) |
| 199 | } |
| 200 | if body, err := p2.Content(ctx(), held.ItemID, held.Revision); !errors.Is(err, suite.ErrNotAvailable) { |
| 201 | t.Errorf("S3 for the held revision after the restore: served %q, %v", body, err) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | // The same, from a backup taken before this change shipped: the card's |
| 206 | // revisions there are the old small counts, and memoria holds the count |
| 207 | // the old code issued next. One edit after the restore must not land on |
| 208 | // it — a counter would, exactly — and the old history still reads STALE |
| 209 | // from the log. |
| 210 | // |
| 211 | // MUTATION-TESTED 2026-11-01, each reverted: revisions as a count → |
| 212 | // "reissued" and "after the edit" (VISIBLE); every non-current revision |
| 213 | // STALE → "before the edit". |
| 214 | func TestSuiteRestoreFromBeforeRandomRevisions(t *testing.T) { |
| 215 | dir := t.TempDir() |
| 216 | live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db") |
| 217 | |
| 218 | g, a, p := restorable(t, live) |
| 219 | // The old code: counted revisions, 1 then 2. |
| 220 | pinRevisions(t, func(current int64) int64 { return current + 1 }) |
| 221 | card := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| 222 | if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | backUp(t, g, backup) // the card at 2 |
| 226 | if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldNotes: "the text memoria holds"}); err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | held := suite.ItemRevision{ItemID: id(card), Revision: revisionOf(t, g, card.ID)} |
| 230 | if held.Revision != 3 || askHeld(t, p, held) != suite.VISIBLE { |
| 231 | t.Fatalf("the old code's held revision is %d", held.Revision) |
| 232 | } |
| 233 | |
| 234 | // The restore, onto this change. |
| 235 | pinRevisions(t, randomRevision) |
| 236 | g2, a2, p2 := restorable(t, backup) |
| 237 | if got := askHeld(t, p2, held); got != suite.UNKNOWN { |
| 238 | t.Errorf("before the edit: %s, want UNKNOWN", got) |
| 239 | } |
| 240 | if got := askHeld(t, p2, suite.ItemRevision{ItemID: held.ItemID, Revision: 1}); got != suite.STALE { |
| 241 | t.Errorf("an older count, in the restored log: %s, want STALE", got) |
| 242 | } |
| 243 | if err := UpdateCard(ctx(), g2, a2.sealer, card.ID, Person(1), map[string]string{FieldNotes: "different text"}); err != nil { |
| 244 | t.Fatal(err) |
| 245 | } |
| 246 | if now := revisionOf(t, g2, card.ID); now == held.Revision { |
| 247 | t.Errorf("reissued: revision %d", now) |
| 248 | } |
| 249 | if got := askHeld(t, p2, held); got == suite.VISIBLE { |
| 250 | t.Errorf("after the edit, the held revision is VISIBLE for different text") |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | // A card created after a restore, on a frozen clock, gets the old card's |
| 255 | // id, revision, event position AND created_at — which is why neither the |
| 256 | // item id nor the cursor is built from created_at. The nonces differ, so |
| 257 | // S2, S3 and S1 all refuse the held identity. |
| 258 | // |
| 259 | // MUTATION-TESTED 2026-11-01, each reverted: the item id built from |
| 260 | // created_at (in the feed, Rule and Content) → "S2", "S3"; the cursor |
| 261 | // built from the event's created_at → "S1". |
| 262 | func TestSuiteRestoreOnAFrozenClockCannotPassOffANewCard(t *testing.T) { |
| 263 | dir := t.TempDir() |
| 264 | live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db") |
| 265 | |
| 266 | g, a, p := restorable(t, live) |
| 267 | pinRevisions(t, func(current int64) int64 { return current + 1 }) // a collision on revision too |
| 268 | backUp(t, g, backup) // before the card |
| 269 | original := mustCard(t, g, a, map[string]string{FieldName: "The original, which memoria holds"}) |
| 270 | _, heldCursor := readFeed(t, p, "", 10) |
| 271 | |
| 272 | g2, a2, p2 := restorable(t, backup) |
| 273 | recreated := mustCard(t, g2, a2, map[string]string{FieldName: "A different card"}) |
| 274 | var origEv, newEv []Event |
| 275 | g.Where("object_kind = ?", ObjectCard).Find(&origEv) |
| 276 | g2.Where("object_kind = ?", ObjectCard).Find(&newEv) |
| 277 | if recreated.ID != original.ID || recreated.Revision != original.Revision || |
| 278 | !recreated.CreatedAt.Equal(original.CreatedAt) || len(origEv) != 1 || len(newEv) != 1 || |
| 279 | origEv[0].ID != newEv[0].ID || !origEv[0].CreatedAt.Equal(newEv[0].CreatedAt) { |
| 280 | t.Fatalf("the collision did not happen, so this proves nothing: %+v / %+v", original, recreated) |
| 281 | } |
| 282 | |
| 283 | held := suite.ItemRevision{ItemID: id(original), Revision: original.Revision} |
| 284 | if got := askHeld(t, p2, held); got != suite.NOT_VISIBLE { |
| 285 | t.Errorf("S2 for the held item: %s, want NOT_VISIBLE", got) |
| 286 | } |
| 287 | if body, err := p2.Content(ctx(), held.ItemID, held.Revision); !errors.Is(err, suite.ErrNotAvailable) { |
| 288 | t.Errorf("S3 for the held item: served %q, %v", body, err) |
| 289 | } |
| 290 | if f, err := p2.Feed(ctx(), heldCursor, 10); !errors.Is(err, server.ErrCursorReset) { |
| 291 | t.Errorf("S1 from the held cursor %q: %+v, %v; want server.ErrCursorReset", heldCursor, f, err) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // Migration 0005 gives every row that existed before it a nonce: a card or |
| 296 | // event left at 0 would carry an item id or a cursor that names nothing. |
| 297 | // Built by applying the migrations up to 0004, planting rows at 0, then |
| 298 | // applying the rest. |
| 299 | // |
| 300 | // MUTATION-TESTED 2026-11-01, each reverted: the cards backfill made a |
| 301 | // no-op → "card"; the events backfill made a no-op → "event"; either |
| 302 | // backfill a constant (nonce = 1) → "distinct". |
| 303 | func TestTheNonceBackfillCoversExistingRows(t *testing.T) { |
| 304 | before := fstest.MapFS{} |
| 305 | for _, name := range []string{"0001_init.sql", "0002_immutable_entries.sql", "0003_alter_card_types.sql", "0004_alter_cards.sql"} { |
| 306 | body, err := migrationFS.ReadFile("migrations/" + name) |
| 307 | if err != nil { |
| 308 | t.Fatal(err) |
| 309 | } |
| 310 | before["migrations/"+name] = &fstest.MapFile{Data: body} |
| 311 | } |
| 312 | old, err := migrate.FromFS(before, "fichas") |
| 313 | if err != nil { |
| 314 | t.Fatal(err) |
| 315 | } |
| 316 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 317 | d, err := db.Open(filepath.Join(t.TempDir(), "old.db"), logger) |
| 318 | if err != nil { |
| 319 | t.Fatal(err) |
| 320 | } |
| 321 | t.Cleanup(func() { d.Close() }) |
| 322 | if _, err := migrate.Apply(ctx(), d, migrate.Merge(sessions.Schema, auth.Schema, old)); err != nil { |
| 323 | t.Fatal(err) |
| 324 | } |
| 325 | if err := d.G.Exec("INSERT INTO card_types (key, scope) VALUES ('t_old', 'card')").Error; err != nil { |
| 326 | t.Fatal(err) |
| 327 | } |
| 328 | for _, stmt := range []string{ |
| 329 | "INSERT INTO cards (card_type_id, revision) SELECT id, 1 FROM card_types WHERE key = 't_old'", |
| 330 | "INSERT INTO cards (card_type_id, revision) SELECT id, 1 FROM card_types WHERE key = 't_old'", |
| 331 | "INSERT INTO events (kind, object_kind, object_id, revision) VALUES ('created', 'card', 1, 1)", |
| 332 | "INSERT INTO events (kind, object_kind, object_id, revision) VALUES ('created', 'card', 2, 1)", |
| 333 | } { |
| 334 | if err := d.G.Exec(stmt).Error; err != nil { |
| 335 | t.Fatalf("%s: %v", stmt, err) |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | if _, err := migrate.Apply(ctx(), d, BootSchema); err != nil { |
| 340 | t.Fatalf("applying 0005: %v", err) |
| 341 | } |
| 342 | var zeroCards, zeroEvents int64 |
| 343 | d.G.Model(&Card{}).Where("nonce < 1").Count(&zeroCards) |
| 344 | d.G.Model(&Event{}).Where("nonce < 1").Count(&zeroEvents) |
| 345 | if zeroCards != 0 { |
| 346 | t.Errorf("card: %d existing cards have no nonce after the backfill", zeroCards) |
| 347 | } |
| 348 | if zeroEvents != 0 { |
| 349 | t.Errorf("event: %d existing events have no nonce after the backfill", zeroEvents) |
| 350 | } |
| 351 | // Distinct, or the nonce protects nothing: two cards backfilled alike |
| 352 | // would share it. |
| 353 | for _, table := range []string{"cards", "events"} { |
| 354 | var total, distinct int64 |
| 355 | if err := d.G.Raw("SELECT COUNT(*), COUNT(DISTINCT nonce) FROM "+table).Row().Scan(&total, &distinct); err != nil { |
| 356 | t.Fatal(err) |
| 357 | } |
| 358 | if total < 2 || distinct != total { |
| 359 | t.Errorf("distinct: %s has %d rows and %d distinct nonces", table, total, distinct) |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | // Every write path that moves a card's revision takes it from the revision |
| 365 | // source, once, given the card's current revision, and logs exactly that |
| 366 | // value on the card's event. Pinned to draws no counter or clock would |
| 367 | // produce, so a path that went back to previous + 1 — or anything else of |
| 368 | // its own — is red here, path by path. Schema changes move no card and |
| 369 | // draw nothing. |
| 370 | // |
| 371 | // MUTATION-TESTED 2026-11-01, each reverted, each its own path: CreateCard |
| 372 | // at a counted 1 → "create"; UpdateCard, AddEntry, DeleteCard and the |
| 373 | // catalogue's kind upgrade each bumping by previous + 1 instead of |
| 374 | // bumpRevision → "update", "add entry", "delete", "catalogue upgrade"; |
| 375 | // bumpRevision logging previous + 1 while storing the draw → every path. |
| 376 | func TestEveryWritePathDrawsItsRevision(t *testing.T) { |
| 377 | g, s := seeded(t) |
| 378 | var asked []int64 |
| 379 | var last int64 |
| 380 | pinRevisions(t, func(current int64) int64 { |
| 381 | asked = append(asked, current) |
| 382 | last = 9_000_000_000_000 + int64(len(asked))*7_919 |
| 383 | return last |
| 384 | }) |
| 385 | var card Card |
| 386 | path := func(name string, run func() error) { |
| 387 | t.Helper() |
| 388 | before, prev := len(asked), card.Revision |
| 389 | if err := run(); err != nil { |
| 390 | t.Fatalf("%s: %v", name, err) |
| 391 | } |
| 392 | if len(asked) != before+1 { |
| 393 | t.Errorf("%s: drew %d revisions, want 1", name, len(asked)-before) |
| 394 | return |
| 395 | } |
| 396 | if asked[before] != prev { |
| 397 | t.Errorf("%s: the source was given %d, not the card's revision %d", name, asked[before], prev) |
| 398 | } |
| 399 | if err := g.First(&card, card.ID).Error; err != nil { |
| 400 | t.Fatal(err) |
| 401 | } |
| 402 | ev := events(t, g, ObjectCard, card.ID) |
| 403 | if card.Revision != last || ev[len(ev)-1].Revision != last { |
| 404 | t.Errorf("%s: card at %d, its event at %d; the draw was %d", name, card.Revision, ev[len(ev)-1].Revision, last) |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | path("create", func() (err error) { |
| 409 | card, err = CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Brightwater Labs"}) |
| 410 | return err |
| 411 | }) |
| 412 | path("update", func() error { |
| 413 | return UpdateCard(ctx(), g, s, card.ID, Person(1), map[string]string{FieldStage: "Lead"}) |
| 414 | }) |
| 415 | path("add entry", func() error { |
| 416 | _, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"}) |
| 417 | return err |
| 418 | }) |
| 419 | |
| 420 | // The catalogue's kind upgrade (TestSeedUpgradesDomainToAWebAddress's |
| 421 | // old world: Domain as Text, with a value typed the old way). |
| 422 | var fd FieldDef |
| 423 | g.Where("key = ?", FieldDomain).First(&fd) |
| 424 | g.Model(&FieldDef{}).Where("id = ?", fd.ID).Update("kind", KindText) |
| 425 | old := fd |
| 426 | old.Kind = KindText |
| 427 | sealed, _ := s.Seal(seal.PurposeValue, []byte("Brightwater.example/")) |
| 428 | pr, _ := printFor(s, old, "Brightwater.example/") |
| 429 | g.Create(&CardValue{CardID: card.ID, FieldDefID: fd.ID, SealedValue: sealed, Print: pr}) |
| 430 | path("catalogue upgrade", func() error { return Seed(g, s) }) |
| 431 | |
| 432 | before, prev := len(asked), card.Revision |
| 433 | added, err := AddField(ctx(), g, s, TypeCustomer, Person(1), FieldSpec{Label: "Region", Kind: KindText, Tier: TierSealed}) |
| 434 | if err != nil { |
| 435 | t.Fatal(err) |
| 436 | } |
| 437 | if err := UpdateField(ctx(), g, s, added.Key, Person(1), "Area", nil); err != nil { |
| 438 | t.Fatal(err) |
| 439 | } |
| 440 | if err := SetFace(ctx(), g, s, TypeCustomer, Person(1), []string{FieldStage}); err != nil { |
| 441 | t.Fatal(err) |
| 442 | } |
| 443 | if _, err := CreateType(ctx(), g, s, Person(1), "Supplier", "Suppliers"); err != nil { |
| 444 | t.Fatal(err) |
| 445 | } |
| 446 | if len(asked) != before || revisionOf(t, g, card.ID) != prev { |
| 447 | t.Errorf("schema changes drew %d revisions or moved the card", len(asked)-before) |
| 448 | } |
| 449 | |
| 450 | path("delete", func() error { return DeleteCard(ctx(), g, s, card.ID, Person(1)) }) |
| 451 | } |
| 452 | |
| 453 | // draws is a reader that hands randomPositive the given int64s, in order. |
| 454 | func draws(vals ...uint64) io.Reader { |
| 455 | var b []byte |
| 456 | for _, v := range vals { |
| 457 | b = binary.BigEndian.AppendUint64(b, v) |
| 458 | } |
| 459 | return bytes.NewReader(b) |
| 460 | } |
| 461 | |
| 462 | func pinRandomBytes(t *testing.T, r io.Reader) { |
| 463 | t.Helper() |
| 464 | old := randomBytes |
| 465 | randomBytes = r |
| 466 | t.Cleanup(func() { randomBytes = old }) |
| 467 | } |
| 468 | |
| 469 | // The redraw guards, forced: a draw of 0 — which the triggers refuse and |
| 470 | // memoria reads as "no revision" — is drawn again; so is a draw equal to |
| 471 | // the card's current revision. And the top bit is masked, so a draw is |
| 472 | // never negative. These are the 2^-63 cases a real reader never hands a |
| 473 | // test, so the reader is replaced. |
| 474 | // |
| 475 | // MUTATION-TESTED 2026-11-01, each reverted: randomPositive's zero redraw |
| 476 | // removed → "zero"; randomRevision's equal-to-current redraw removed → |
| 477 | // "current"; the sign mask removed → "top bit". |
| 478 | func TestRedrawsHappen(t *testing.T) { |
| 479 | pinRandomBytes(t, draws(0, 7)) |
| 480 | if got := randomPositive(); got != 7 { |
| 481 | t.Errorf("zero: drew %d, want 0 redrawn as 7", got) |
| 482 | } |
| 483 | pinRandomBytes(t, draws(42, 43)) |
| 484 | if got := randomRevision(42); got != 43 { |
| 485 | t.Errorf("current: drew %d for a card at 42, want 43", got) |
| 486 | } |
| 487 | pinRandomBytes(t, draws(1<<63|5)) |
| 488 | if got := randomPositive(); got != 5 { |
| 489 | t.Errorf("top bit: drew %d, want 5", got) |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | // A change's revision is redrawn while it is ANY revision the card's log |
| 494 | // holds, not only the current one (suite doctrine §6.6, revision 11, L4): a |
| 495 | // draw equal to a revision the card had before gives an old name to new |
| 496 | // bytes, and memoria, still holding that (item, revision) with the old |
| 497 | // text, would be told VISIBLE. Forced with pinned draws, since a real |
| 498 | // source collides with probability 2^-63. Also: a draw equal to the |
| 499 | // current revision is redrawn even where the log does not hold it (a card |
| 500 | // from before events carried revisions), and a source that never yields a |
| 501 | // fresh revision fails the write — loudly, with the card unmoved — rather |
| 502 | // than spinning in its transaction. |
| 503 | // |
| 504 | // MUTATION-TESTED 2026-11-02, each reverted: freshRevision's log check |
| 505 | // removed (only the current one refused, revision 10's rule) → "a prior |
| 506 | // revision", "never fresh"; the log query not restricted to this card → |
| 507 | // "another card's revision" (it redraws, and runs out of draws), and |
| 508 | // TestSuiteFeedIsTheEventLog, TestSuiteRuleEveryBranch and TestSuiteContent, |
| 509 | // whose pinned counts collide across cards; not restricted to card events |
| 510 | // → "an entry's event"; the equal-to-current check removed → "current, not |
| 511 | // in the log"; maxRevisionDraws' bound removed (an unbounded loop) → "never |
| 512 | // fresh" hangs until the test binary's timeout kills it (run with -timeout |
| 513 | // 20s); bumpRevision drawing with nextRevision directly, skipping |
| 514 | // freshRevision → "a prior revision", "current, in the log", "current, not |
| 515 | // in the log", "never fresh", and TestRevisionDrawHistoryFailureFailsTheWrite. |
| 516 | func TestRevisionsAreFreshAgainstTheWholeLog(t *testing.T) { |
| 517 | g, a, _ := suiteWorld(t) |
| 518 | // Each update writes different notes, so each is a change and draws. |
| 519 | update := func(notes string) error { |
| 520 | return UpdateCard(ctx(), g, a.sealer, firstCard(t, g).ID, Person(1), map[string]string{FieldNotes: notes}) |
| 521 | } |
| 522 | |
| 523 | drawing(t, 100, 200) |
| 524 | c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| 525 | mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"}) // at 200 |
| 526 | // c: 100. Move it to 300, so 100 is a prior revision and 300 current. |
| 527 | drawing(t, 300) |
| 528 | if err := update("first"); err != nil { |
| 529 | t.Fatal(err) |
| 530 | } |
| 531 | |
| 532 | cases := []struct { |
| 533 | name string |
| 534 | draws []int64 |
| 535 | want int64 |
| 536 | }{ |
| 537 | {"a prior revision", []int64{100, 400}, 400}, |
| 538 | {"another card's revision", []int64{200}, 200}, // not this card's: no redraw |
| 539 | {"current, in the log", []int64{200, 500}, 500}, |
| 540 | } |
| 541 | for _, tc := range cases { |
| 542 | drawing(t, tc.draws...) |
| 543 | if err := update(tc.name); err != nil { |
| 544 | t.Fatalf("%s: %v", tc.name, err) |
| 545 | } |
| 546 | if now := revisionOf(t, g, c.ID); now != tc.want { |
| 547 | t.Errorf("%s: the card moved to %d, want %d", tc.name, now, tc.want) |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | // An entry's own creation event is not a card event: its revision |
| 552 | // column is 0 today, so plant a value there to show it is not read as |
| 553 | // this card's history. |
| 554 | drawing(t, 600) // the entry moves the card |
| 555 | entry, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"}) |
| 556 | if err == nil { |
| 557 | err = g.Exec("UPDATE events SET revision = 777 WHERE object_kind = ? AND object_id = ?", ObjectEntry, entry.ID).Error |
| 558 | } |
| 559 | if err != nil { |
| 560 | t.Fatal(err) |
| 561 | } |
| 562 | if entry.ID != c.ID { |
| 563 | // The entry's event must share the card's object_id, or a query |
| 564 | // that forgot object_kind would miss it anyway and prove nothing. |
| 565 | t.Fatalf("entry %d and card %d: the ids do not coincide, so this case proves nothing", entry.ID, c.ID) |
| 566 | } |
| 567 | drawing(t, 777) |
| 568 | if err := update("an entry's event"); err != nil { |
| 569 | t.Fatalf("an entry's event: %v", err) |
| 570 | } |
| 571 | if now := revisionOf(t, g, c.ID); now != 777 { |
| 572 | t.Errorf("an entry's event: the card moved to %d, want 777 (an entry's event is not the card's log)", now) |
| 573 | } |
| 574 | |
| 575 | // The current revision, with the log not holding it. |
| 576 | if err := g.Exec("UPDATE events SET revision = 1 WHERE object_kind = ? AND object_id = ? AND revision = 777", ObjectCard, c.ID).Error; err != nil { |
| 577 | t.Fatal(err) |
| 578 | } |
| 579 | drawing(t, 777, 900) |
| 580 | if err := update("current, not in the log"); err != nil { |
| 581 | t.Fatalf("current, not in the log: %v", err) |
| 582 | } |
| 583 | if now := revisionOf(t, g, c.ID); now != 900 { |
| 584 | t.Errorf("current, not in the log: the card moved to %d, want 900", now) |
| 585 | } |
| 586 | |
| 587 | // A source that only ever answers revisions the log holds. |
| 588 | pinRevisions(t, func(int64) int64 { return 100 }) |
| 589 | if err := update("never fresh"); err == nil { |
| 590 | t.Errorf("never fresh: the write succeeded") |
| 591 | } |
| 592 | if now := revisionOf(t, g, c.ID); now != 900 { |
| 593 | t.Errorf("never fresh: the card moved to %d", now) |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | // firstCard is the oldest card, which TestRevisionsAreFreshAgainstTheWholeLog edits. |
| 598 | func firstCard(t *testing.T, g *gorm.DB) Card { |
| 599 | t.Helper() |
| 600 | var c Card |
| 601 | if err := g.Order("id").First(&c).Error; err != nil { |
| 602 | t.Fatal(err) |
| 603 | } |
| 604 | return c |
| 605 | } |
| 606 | |
| 607 | // A failed read of the card's revision history fails the write: never a |
| 608 | // draw taken as fresh because the log could not be asked, which is the |
| 609 | // reissue §6.6 forbids by another road. |
| 610 | // |
| 611 | // MUTATION-TESTED 2026-11-02, reverted: freshRevision's read error taken as |
| 612 | // "not held" (the draw returned) → "a failed history read". |
| 613 | func TestRevisionDrawHistoryFailureFailsTheWrite(t *testing.T) { |
| 614 | g, a, _ := suiteWorld(t) |
| 615 | c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| 616 | failing := false |
| 617 | if err := g.Callback().Query().Before("gorm:query").Register("test:fail_draw_history", func(tx *gorm.DB) { |
| 618 | if failing && tx.Statement.Table == "events" { |
| 619 | tx.AddError(errors.New("the disk went away")) |
| 620 | } |
| 621 | }); err != nil { |
| 622 | t.Fatal(err) |
| 623 | } |
| 624 | failing = true |
| 625 | err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldNotes: "changed"}) |
| 626 | failing = false |
| 627 | if err == nil { |
| 628 | t.Errorf("a failed history read: the write succeeded") |
| 629 | } |
| 630 | if now := revisionOf(t, g, c.ID); now != c.Revision { |
| 631 | t.Errorf("a failed history read: the card moved from %d to %d", c.Revision, now) |
| 632 | } |
| 633 | } |
| 634 | |