Tests that pin what review found loose; claims stated as probabilities (Astra)
Astra reviewed 665e5a1: no production defect under consistent whole-database restores; tests and claims too loose. - S2: a card that moved 1000 -> 500 is STALE at 1000 (history AND asked < current used to pass); a wrong nonce with a historical revision is NOT_VISIBLE and S3 refuses it; a failed history query is an error, a 503, never a quiet UNKNOWN or STALE. - Every write path draws its revision from the source and logs exactly that draw: create, update, add entry, delete, the catalogue's kind upgrade, each checked against a pinned source; schema changes (add or rename a field, set the face, create a type) draw nothing. - randomPositive reads through a test seam (randomBytes, crypto/rand by default; a broken substitute panics rather than fall back). The zero redraw, the equal-to-current redraw and the sign mask are forced and checked: they were not equivalent mutants. - Schema: a negative nonce insert and a nonce decrease are refused, not only zero and increases. The backfill gives distinct nonces. - Spec §6.2/§10 and comments: reissue has negligible probability (2^-63 per draw), not 'never'; the protection assumes consistent whole-database restores (Astra's value-only restore changed S3 text under a VISIBLE S2) and forward-only migrations. Mutation-tested: 18 new mutations, all red.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+309
−33
docs/superpowers/specs/2026-09-19-fichas-design.md+32 −13internal/fichas/models.go+5 −4internal/fichas/store.go+15 −4internal/fichas/suite_revision_test.go+167 −12internal/fichas/suite_test.go+90 −0
CI passed — run details
diff --git a/docs/superpowers/specs/2026-09-19-fichas-design.md b/docs/superpowers/specs/2026-09-19-fichas-design.md| index b0bb341..bd02e05 100644 |
| --- a/docs/superpowers/specs/2026-09-19-fichas-design.md |
| +++ b/docs/superpowers/specs/2026-09-19-fichas-design.md |
| @@ -423,14 +423,14 @@ answer an unchanged empty page, S2 `VISIBLE` for memoria's old copy, and |
| S3 the new card's text under the old identity. The first fix stamped ids |
| with `created_at`; on a clock that is frozen, or set back to where it |
| stood at the backup, a recreated card gets that too. A random nonce it |
| -cannot get: the old item id is `NOT_VISIBLE` in S2 and refused in S3, and |
| -the event at the old cursor carries another nonce (or is gone), so S1 is |
| -a 503. |
| +gets again only with negligible probability (2^-63 per draw): the old |
| +item id is `NOT_VISIBLE` in S2 and refused in S3, and the event at the old |
| +cursor carries another nonce (or is gone), so S1 is a 503. |
| **Revisions are random, and their order is the log's (amended 2026-11-01, |
| this session, as Docs did).** The nonces leave one case: a card that |
| predates the restore point keeps its id and nonce — correctly, it is the |
| -same card — so a revision issued *after* the backup must never be issued |
| +same card — so a revision issued *after* the backup must not be issued |
| again after the restore, or one `(item id, revision)` names two texts and |
| S2 says `VISIBLE` for the abandoned one. A counter reissues exactly. A |
| clock does too: frozen, or behind by less than the backup's age, and |
| @@ -438,10 +438,12 @@ clock does too: frozen, or behind by less than the backup's age, and |
| clock scheme still holds the counter's small values. So **every revision |
| Fichas issues — creation and every change — is a fresh random positive |
| int63** from crypto/rand (store.go `nextRevision`), redrawn in the |
| -vanishing case that it equals the card's current one. It is never |
| -reissued, so memoria's held revision after a restore is `UNKNOWN` (the |
| -restored log never issued it) and S3 refuses it — never `VISIBLE` for |
| -different text, whatever the clock did. Cards from before keep their |
| +vanishing case that it equals the card's current one (and when it is 0). |
| +A reissue has negligible probability — 2^-63 per draw — so memoria's held |
| +revision after a restore is `UNKNOWN` (the restored log never issued it) |
| +and S3 refuses it: not `VISIBLE` for different text, whatever the clock |
| +did. Every write path draws from that one source and logs exactly the |
| +value it drew; a test pins the source and checks each path. Cards from before keep their |
| small counted revisions until their next change; those were issued |
| before and are in the log, and the risk was only ever reissuing, so they |
| need no backfill. |
| @@ -459,6 +461,21 @@ does; it is only compared for equality. The contract-release page shows |
| it as "Source revision", a long number, likewise compared only for |
| equality. |
| +**What this assumes.** Two things, and nothing about the clock: |
| + |
| +- **A restore is a consistent copy of the whole database** — every table |
| + from one moment, as a backup or a Litestream restore gives. A partial |
| + or value-only restore breaks it: Astra's probe (2026-11-01) put back old |
| + card values while leaving the card's row and log alone, and S3's text |
| + changed while S2 still said `VISIBLE` for the same `(item id, |
| + revision)`. Nothing in Fichas restores that way; nothing must. |
| +- **Migrations run forward only** (AGENTS.md: applied once each, never |
| + re-run or reversed). A migration that rewrote revisions or nonces — |
| + reassigning small values, or recomputing them — could reissue one |
| + memoria holds, which is how Astra showed a backfill reissuing on Docs. |
| + 0005 only fills nonces that were 0, and its triggers refuse any later |
| + change. |
| + |
| **The reset is kept.** A restore still rewrites the feed, so S1 still |
| answers the consumer's cursor with a 503 (the cursor's nonce). On that |
| 503: **reset the consumer** — discard every item it holds from this |
| @@ -726,11 +743,13 @@ sealed or sealed+print only. |
| (`memoria/ZDR-TREAT-AS-LOCAL.md` §6). Not a blocker at one user; a |
| blocker at the second team. |
| - **S1 after a restore from backup** (§6.2; revised after Astra's review, |
| - and closed 2026-11-01). Protected, with no assumption about the clock: |
| - a card recreated after a restore cannot pass as one memoria holds (the |
| - item id's nonce); a feed position rewritten by a restore is a 503, not a |
| - silent continuation (the cursor's nonce); and a card edited after the |
| - restore cannot be issued a revision memoria already holds (random |
| + and closed 2026-11-01). Protected, with no assumption about the clock, |
| + for consistent whole-database restores and forward-only migrations |
| + (§6.2): a card recreated after a restore passes as one memoria holds |
| + only with negligible probability (the item id's random nonce); a feed |
| + position rewritten by a restore is a 503, not a silent continuation (the |
| + cursor's nonce); and a card edited after the restore reissues a |
| + revision memoria holds only with probability 2^-63 per draw (random |
| revisions, ordered by the log). The reset is |
| manual today: on a Fichas S1 503 after a restore, discard everything |
| memoria holds from this instance plus its cursor, and re-read from `""`. |
diff --git a/internal/fichas/models.go b/internal/fichas/models.go| index f5788c1..815533c 100644 |
| --- a/internal/fichas/models.go |
| +++ b/internal/fichas/models.go |
| @@ -170,15 +170,16 @@ type Card struct { |
| // known leak; this is the same trade, made deliberately. |
| // |
| // A revision is a random positive int63 (store.go nextRevision), not a |
| - // counter, so a database restored from an older backup can never hand |
| - // one out again (spec §6.2). Only equality means anything: the order |
| + // counter, so a database restored from an older backup hands one out |
| + // again only with negligible probability, 2^-63 per draw (spec §6.2; |
| + // it assumes whole-database restores). Only equality means anything: the order |
| // of a card's revisions is its event log's. Cards from before keep |
| // their small counted values until their next change. |
| Revision int64 `gorm:"not null;default:1"` |
| // Nonce is the card's half of its suite item id, "<id>.<nonce>": a |
| // random positive int63 written once at creation. After a restore a |
| - // new card can be given an old card's id; it cannot be given its |
| - // nonce. Plaintext under §4.1 case 1. Write-once and never zero, |
| + // new card can be given an old card's id; its nonce matches only with |
| + // probability 2^-63. Plaintext under §4.1 case 1. Write-once and positive, |
| // enforced by triggers (migrations/0005). |
| Nonce int64 `gorm:"not null;default:0"` |
| // not null with a default, because a nullable bool does not behave: |
diff --git a/internal/fichas/store.go b/internal/fichas/store.go| index 85e0a79..c09c65a 100644 |
| --- a/internal/fichas/store.go |
| +++ b/internal/fichas/store.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/binary" |
| "encoding/json" |
| "fmt" |
| + "io" |
| "sort" |
| "strings" |
| "time" |
| @@ -255,6 +256,11 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel |
| return changed, detail, nil |
| } |
| +// randomBytes is where randomPositive draws from: crypto/rand. A variable |
| +// so a test can force the draws its redraw guards exist for; nothing else |
| +// sets it. |
| +var randomBytes io.Reader = rand.Reader |
| + |
| // randomPositive is a random positive int63 from crypto/rand: a card's |
| // revisions and the nonces in its item id and the feed's cursor (spec |
| // §6.2). Zero, which the triggers in migrations/0005 refuse and which |
| @@ -262,7 +268,12 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel |
| func randomPositive() int64 { |
| var b [8]byte |
| for { |
| - rand.Read(b[:]) // never fails: crypto/rand aborts the process rather than return short |
| + if _, err := io.ReadFull(randomBytes, b[:]); err != nil { |
| + // crypto/rand does not fail (it aborts the process instead), |
| + // so this is a broken substitute: never fall back to anything |
| + // guessable. |
| + panic("fichas: no randomness: " + err.Error()) |
| + } |
| if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 { |
| return n |
| } |
| @@ -281,9 +292,9 @@ var newRevision = randomRevision |
| // older backup and a counter hands the same numbers out again for |
| // different text — S2 then says VISIBLE for the abandoned copy. A clock |
| // does the same if it is frozen, or behind by less than the backup's age. |
| -// A random revision is never reissued; memoria compares revisions only |
| -// for equality, and the ORDER of a card's revisions is its event log's, |
| -// which S2 reads for STALE. |
| +// A random revision is reissued only with negligible probability (2^-63 per |
| +// draw); memoria compares revisions only for equality, and the ORDER of a |
| +// card's revisions is its event log's, which S2 reads for STALE. |
| func randomRevision(current int64) int64 { |
| for { |
| if r := randomPositive(); r != current { |
diff --git a/internal/fichas/suite_revision_test.go b/internal/fichas/suite_revision_test.go| index db2ddd4..a80ff9a 100644 |
| --- a/internal/fichas/suite_revision_test.go |
| +++ b/internal/fichas/suite_revision_test.go |
| @@ -1,6 +1,8 @@ |
| package fichas |
| import ( |
| + "bytes" |
| + "encoding/binary" |
| "errors" |
| "io" |
| "log/slog" |
| @@ -15,6 +17,7 @@ import ( |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "gorm.io/gorm" |
| + "amadan.net/oficina/fichas/internal/fichas/seal" |
| "amadan.net/oficina/suite" |
| ) |
| @@ -28,10 +31,9 @@ import ( |
| // (max(current + 1, now in microseconds)) → "repeated" (draws inside one |
| // microsecond); randomPositive without its sign mask → negative nonces, |
| // which the insert triggers refuse, so "creating" (and most of the |
| -// package); a card's or an event's nonce left unset → likewise. Two |
| -// mutants survive and are equivalent: randomPositive's zero redraw and |
| -// randomRevision's equal-to-current redraw removed — each guards a 2^-63 |
| -// draw no test can force. |
| +// package); a card's or an event's nonce left unset → likewise. The zero |
| +// and equal-to-current redraws guard 2^-63 draws a real reader never hands |
| +// a test; TestRedrawsHappen forces them. |
| func TestRevisionsAndNoncesAreRandom(t *testing.T) { |
| g, s := seeded(t) |
| a, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "A"}) |
| @@ -65,16 +67,26 @@ func TestRevisionsAndNoncesAreRandom(t *testing.T) { |
| } |
| } |
| -// The nonce columns are write-once and never zero, in the schema itself |
| -// (migrations/0005), not only by convention. |
| +// The nonce columns are write-once and positive, in the schema itself |
| +// (migrations/0005), not only by convention: no insert at zero or below, |
| +// and no change after, up or down. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: each of the four triggers |
| +// disabled → its rows; the write-once triggers loosened to refuse only an |
| +// increase (NEW.nonce > OLD.nonce) → "decreased"; the insert triggers |
| +// loosened to refuse only zero (= 0) → "negative". |
| func TestNoncesAreWriteOnceInTheSchema(t *testing.T) { |
| g, a, _ := suiteWorld(t) |
| c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| for name, stmt := range map[string]string{ |
| - "a card's nonce moved": "UPDATE cards SET nonce = nonce + 1 WHERE id = ?", |
| - "an event's nonce moved": "UPDATE events SET nonce = nonce + 1 WHERE object_kind = 'card' AND object_id = ?", |
| - "a card without one": "INSERT INTO cards (card_type_id, revision, nonce) SELECT card_type_id, 1, 0 FROM cards WHERE id = ?", |
| - "an event without one": "INSERT INTO events (kind, object_kind, object_id, nonce) VALUES ('updated', 'card', ?, 0)", |
| + "a card's nonce increased": "UPDATE cards SET nonce = nonce + 1 WHERE id = ?", |
| + "a card's nonce decreased": "UPDATE cards SET nonce = nonce - 1 WHERE id = ?", |
| + "an event's nonce increased": "UPDATE events SET nonce = nonce + 1 WHERE object_kind = 'card' AND object_id = ?", |
| + "an event's nonce decreased": "UPDATE events SET nonce = nonce - 1 WHERE object_kind = 'card' AND object_id = ?", |
| + "a card without one": "INSERT INTO cards (card_type_id, revision, nonce) SELECT card_type_id, 1, 0 FROM cards WHERE id = ?", |
| + "a card with a negative one": "INSERT INTO cards (card_type_id, revision, nonce) SELECT card_type_id, 1, -5 FROM cards WHERE id = ?", |
| + "an event without one": "INSERT INTO events (kind, object_kind, object_id, nonce) VALUES ('updated', 'card', ?, 0)", |
| + "an event with a negative one": "INSERT INTO events (kind, object_kind, object_id, nonce) VALUES ('updated', 'card', ?, -5)", |
| } { |
| if err := g.Exec(stmt, c.ID).Error; err == nil { |
| t.Errorf("%s: the schema allowed it", name) |
| @@ -144,7 +156,7 @@ func askHeld(t *testing.T, p *suiteProducer, held suite.ItemRevision) suite.Auth |
| // The gap the item id's nonce cannot close (spec §6.2): a card that |
| // predates the restore point keeps its id and nonce, so a revision issued |
| -// after the backup must never be issued again after the restore. Back up, |
| +// after the backup must not be issued again after the restore. Back up, |
| // edit (memoria holds that revision), restore, edit again — on a frozen |
| // clock, which is what made clock revisions reissue. The held revision is |
| // not in the restored log, so it is UNKNOWN before the edit and after it, |
| @@ -285,7 +297,8 @@ func TestSuiteRestoreOnAFrozenClockCannotPassOffANewCard(t *testing.T) { |
| // applying the rest. |
| // |
| // MUTATION-TESTED 2026-11-01, each reverted: the cards backfill made a |
| -// no-op → "card"; the events backfill made a no-op → "event". |
| +// no-op → "card"; the events backfill made a no-op → "event"; either |
| +// backfill a constant (nonce = 1) → "distinct". |
| func TestTheNonceBackfillCoversExistingRows(t *testing.T) { |
| before := fstest.MapFS{} |
| for _, name := range []string{"0001_init.sql", "0002_immutable_entries.sql", "0003_alter_card_types.sql", "0004_alter_cards.sql"} { |
| @@ -312,8 +325,10 @@ func TestTheNonceBackfillCoversExistingRows(t *testing.T) { |
| t.Fatal(err) |
| } |
| for _, stmt := range []string{ |
| + "INSERT INTO cards (card_type_id, revision) SELECT id, 1 FROM card_types WHERE key = 't_old'", |
| "INSERT INTO cards (card_type_id, revision) SELECT id, 1 FROM card_types WHERE key = 't_old'", |
| "INSERT INTO events (kind, object_kind, object_id, revision) VALUES ('created', 'card', 1, 1)", |
| + "INSERT INTO events (kind, object_kind, object_id, revision) VALUES ('created', 'card', 2, 1)", |
| } { |
| if err := d.G.Exec(stmt).Error; err != nil { |
| t.Fatalf("%s: %v", stmt, err) |
| @@ -332,4 +347,144 @@ func TestTheNonceBackfillCoversExistingRows(t *testing.T) { |
| if zeroEvents != 0 { |
| t.Errorf("event: %d existing events have no nonce after the backfill", zeroEvents) |
| } |
| + // Distinct, or the nonce protects nothing: two cards backfilled alike |
| + // would share it. |
| + for _, table := range []string{"cards", "events"} { |
| + var total, distinct int64 |
| + if err := d.G.Raw("SELECT COUNT(*), COUNT(DISTINCT nonce) FROM "+table).Row().Scan(&total, &distinct); err != nil { |
| + t.Fatal(err) |
| + } |
| + if total < 2 || distinct != total { |
| + t.Errorf("distinct: %s has %d rows and %d distinct nonces", table, total, distinct) |
| + } |
| + } |
| +} |
| + |
| +// Every write path that moves a card's revision takes it from the revision |
| +// source, once, given the card's current revision, and logs exactly that |
| +// value on the card's event. Pinned to draws no counter or clock would |
| +// produce, so a path that went back to previous + 1 — or anything else of |
| +// its own — is red here, path by path. Schema changes move no card and |
| +// draw nothing. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted, each its own path: CreateCard |
| +// at a counted 1 → "create"; UpdateCard, AddEntry, DeleteCard and the |
| +// catalogue's kind upgrade each bumping by previous + 1 instead of |
| +// bumpRevision → "update", "add entry", "delete", "catalogue upgrade"; |
| +// bumpRevision logging previous + 1 while storing the draw → every path. |
| +func TestEveryWritePathDrawsItsRevision(t *testing.T) { |
| + g, s := seeded(t) |
| + var asked []int64 |
| + var last int64 |
| + pinRevisions(t, func(current int64) int64 { |
| + asked = append(asked, current) |
| + last = 9_000_000_000_000 + int64(len(asked))*7_919 |
| + return last |
| + }) |
| + var card Card |
| + path := func(name string, run func() error) { |
| + t.Helper() |
| + before, prev := len(asked), card.Revision |
| + if err := run(); err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + if len(asked) != before+1 { |
| + t.Errorf("%s: drew %d revisions, want 1", name, len(asked)-before) |
| + return |
| + } |
| + if asked[before] != prev { |
| + t.Errorf("%s: the source was given %d, not the card's revision %d", name, asked[before], prev) |
| + } |
| + if err := g.First(&card, card.ID).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + ev := events(t, g, ObjectCard, card.ID) |
| + if card.Revision != last || ev[len(ev)-1].Revision != last { |
| + t.Errorf("%s: card at %d, its event at %d; the draw was %d", name, card.Revision, ev[len(ev)-1].Revision, last) |
| + } |
| + } |
| + |
| + path("create", func() (err error) { |
| + card, err = CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Brightwater Labs"}) |
| + return err |
| + }) |
| + path("update", func() error { |
| + return UpdateCard(ctx(), g, s, card.ID, Person(1), map[string]string{FieldStage: "Lead"}) |
| + }) |
| + path("add entry", func() error { |
| + _, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"}) |
| + return err |
| + }) |
| + |
| + // The catalogue's kind upgrade (TestSeedUpgradesDomainToAWebAddress's |
| + // old world: Domain as Text, with a value typed the old way). |
| + var fd FieldDef |
| + g.Where("key = ?", FieldDomain).First(&fd) |
| + g.Model(&FieldDef{}).Where("id = ?", fd.ID).Update("kind", KindText) |
| + old := fd |
| + old.Kind = KindText |
| + sealed, _ := s.Seal(seal.PurposeValue, []byte("Brightwater.example/")) |
| + pr, _ := printFor(s, old, "Brightwater.example/") |
| + g.Create(&CardValue{CardID: card.ID, FieldDefID: fd.ID, SealedValue: sealed, Print: pr}) |
| + path("catalogue upgrade", func() error { return Seed(g, s) }) |
| + |
| + before, prev := len(asked), card.Revision |
| + added, err := AddField(ctx(), g, s, TypeCustomer, Person(1), FieldSpec{Label: "Region", Kind: KindText, Tier: TierSealed}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := UpdateField(ctx(), g, s, added.Key, Person(1), "Area", nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := SetFace(ctx(), g, s, TypeCustomer, Person(1), []string{FieldStage}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := CreateType(ctx(), g, s, Person(1), "Supplier", "Suppliers"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(asked) != before || revisionOf(t, g, card.ID) != prev { |
| + t.Errorf("schema changes drew %d revisions or moved the card", len(asked)-before) |
| + } |
| + |
| + path("delete", func() error { return DeleteCard(ctx(), g, s, card.ID, Person(1)) }) |
| +} |
| + |
| +// draws is a reader that hands randomPositive the given int64s, in order. |
| +func draws(vals ...uint64) io.Reader { |
| + var b []byte |
| + for _, v := range vals { |
| + b = binary.BigEndian.AppendUint64(b, v) |
| + } |
| + return bytes.NewReader(b) |
| +} |
| + |
| +func pinRandomBytes(t *testing.T, r io.Reader) { |
| + t.Helper() |
| + old := randomBytes |
| + randomBytes = r |
| + t.Cleanup(func() { randomBytes = old }) |
| +} |
| + |
| +// The redraw guards, forced: a draw of 0 — which the triggers refuse and |
| +// memoria reads as "no revision" — is drawn again; so is a draw equal to |
| +// the card's current revision. And the top bit is masked, so a draw is |
| +// never negative. These are the 2^-63 cases a real reader never hands a |
| +// test, so the reader is replaced. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: randomPositive's zero redraw |
| +// removed → "zero"; randomRevision's equal-to-current redraw removed → |
| +// "current"; the sign mask removed → "top bit". |
| +func TestRedrawsHappen(t *testing.T) { |
| + pinRandomBytes(t, draws(0, 7)) |
| + if got := randomPositive(); got != 7 { |
| + t.Errorf("zero: drew %d, want 0 redrawn as 7", got) |
| + } |
| + pinRandomBytes(t, draws(42, 43)) |
| + if got := randomRevision(42); got != 43 { |
| + t.Errorf("current: drew %d for a card at 42, want 43", got) |
| + } |
| + pinRandomBytes(t, draws(1<<63|5)) |
| + if got := randomPositive(); got != 5 { |
| + t.Errorf("top bit: drew %d, want 5", got) |
| + } |
| } |
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go| index fcb49c4..bef4879 100644 |
| --- a/internal/fichas/suite_test.go |
| +++ b/internal/fichas/suite_test.go |
| @@ -1,6 +1,8 @@ |
| package fichas |
| import ( |
| + "bytes" |
| + "encoding/json" |
| "errors" |
| "net/http/httptest" |
| "slices" |
| @@ -364,6 +366,94 @@ func TestSuiteRuleEveryBranch(t *testing.T) { |
| check("not admitted", address("bo@example.com"), all(suite.NOT_VISIBLE)) |
| } |
| +// drawing pins card revisions to the given draws, in order, and fails the |
| +// test if a path asks for more than it was given. |
| +func drawing(t *testing.T, draws ...int64) { |
| + t.Helper() |
| + pinRevisions(t, func(int64) int64 { |
| + if len(draws) == 0 { |
| + t.Fatal("a revision was drawn that the test did not provide") |
| + } |
| + d := draws[0] |
| + draws = draws[1:] |
| + return d |
| + }) |
| +} |
| + |
| +// STALE is "this card's log once issued it", never "it is smaller": random |
| +// revisions go down as often as up. A card that moved 1000 → 500 is STALE |
| +// at 1000. A historical revision under someone else's nonce is a different |
| +// card's, and NOT_VISIBLE, never STALE. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: STALE requiring the log AND |
| +// asked < current → "1000 after 1000 → 500"; the history lookup consulted |
| +// before the nonce check (a reused id's history read as this card's) → |
| +// "a wrong nonce with a historical revision". |
| +func TestSuiteStaleIsTheLogNotTheNumbers(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + drawing(t, 1000, 500) |
| + c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now := revisionOf(t, g, c.ID); now != 500 { |
| + t.Fatalf("the card is at %d, want 500", now) |
| + } |
| + wrongNonce := itemID(c.ID, c.Nonce+1) |
| + pairs := []suite.ItemRevision{ |
| + {ItemID: id(c), Revision: 1000}, |
| + {ItemID: id(c), Revision: 500}, |
| + {ItemID: wrongNonce, Revision: 1000}, |
| + } |
| + got, err := p.Rule(ctx(), address(admittedAsker), pairs) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i, want := range []suite.Authorization{suite.STALE, suite.VISIBLE, suite.NOT_VISIBLE} { |
| + name := []string{"1000 after 1000 → 500", "500, current", "a wrong nonce with a historical revision"}[i] |
| + if got[i] != want { |
| + t.Errorf("%s: %s, want %s", name, got[i], want) |
| + } |
| + } |
| + if body, err := p.Content(ctx(), wrongNonce, 1000); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("S3, a wrong nonce with a historical revision: %q, %v", body, err) |
| + } |
| +} |
| + |
| +// A failed read of a card's history is an error — a 503, UNKNOWN for the |
| +// whole call on memoria's side, and logged — never a quiet UNKNOWN or STALE |
| +// per pair, which would read as Fichas's verdict. |
| +// |
| +// MUTATION-TESTED 2026-11-01, reverted: pastRevisions' query error |
| +// swallowed (an empty history returned) → "a failed history read" and |
| +// "through the server". |
| +func TestSuiteRuleHistoryFailureIsAnError(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + if err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + failing := false |
| + if err := g.Callback().Query().Before("gorm:query").Register("test:fail_history", func(tx *gorm.DB) { |
| + if failing && tx.Statement.Table == "events" { |
| + tx.AddError(errors.New("the disk went away")) |
| + } |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + failing = true |
| + pair := []suite.ItemRevision{{ItemID: id(c), Revision: 1}} // historical: needs the log |
| + if got, err := p.Rule(ctx(), address(admittedAsker), pair); err == nil { |
| + t.Errorf("a failed history read: answered %v, want an error", got) |
| + } |
| + body, _ := json.Marshal(suite.S2Request{Asker: address(admittedAsker), Pairs: pair}) |
| + rec := httptest.NewRecorder() |
| + server.Routes(p, nil).ServeHTTP(rec, httptest.NewRequest("POST", suite.RouteS2, bytes.NewReader(body))) |
| + if rec.Code != 503 { |
| + t.Errorf("through the server: %d, want 503", rec.Code) |
| + } |
| +} |
| + |
| // Never cached: the same question asked twice is answered from the world as |
| // it is at each call — a revision that moved, and an admission list that |
| // changed. |