oficina / fichas Public

Restore-proof item ids and cursors; close three test gaps (Astra review)

Astra (GPT-6) reproduced it on 155792a: restore an older database, create
a different card, and it reuses the old card's id, revision and event
position. S1 answered an unchanged empty page, S2 VISIBLE for memoria's
old copy, S3 the new text under the old identity.

- item_id is now "<card id>.<card created_at unix nanos>", one canonical
  form; S2 and S3 require both parts to match the live card, else
  NOT_VISIBLE / ErrNotAvailable. created_at is written once and never
  updated, already plaintext, and needs no migration; a random nonce
  column was not worth a migration and backfill for what it adds.
- The cursor is "<event id>.<event created_at unix nanos>"; every S1
  request checks the event at that id still carries that stamp, else 503.
  Same cursor at the tip. Replaces the ahead-of-the-log check.
- S3's post-read revision re-read failing is an error (503), never the
  404 refusal.
- Tests: the restore-and-recreate scenario (S2 NOT_VISIBLE, S3 refused,
  S1 loud, the collision proved first); a card owned by another member is
  VISIBLE; revisions 0 and -1 are UNKNOWN; a failed re-read is a 503; an
  event naming a card with no row fails the feed.
- Spec §6.2-§6.4 and §10: what the stamps protect, what they do not (a
  pre-restore card edited back to a revision memoria holds), and that a
  restore needs a full consumer reset, not a cursor reset.

Mutation-tested: 39 mutations, 37 red; the 2 survivors are equivalent
and recorded in the cursor test's comment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev d3f63a45b8f0425a9e9d61ff3f2095cd52822f10 parent c0bbf02
5 files changed, +385 −116
  • docs/superpowers/specs/2026-09-19-fichas-design.md +72 −32
  • internal/fichas/suite.go +111 −43
  • internal/fichas/suite_conformance_test.go +4 −3
  • internal/fichas/suite_test.go +194 −35
  • internal/fichastest/suite_test.go +4 −3

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 24646c7..f7ef8e8 100644
--- a/docs/superpowers/specs/2026-09-19-fichas-design.md
+++ b/docs/superpowers/specs/2026-09-19-fichas-design.md
@@ -381,33 +381,61 @@ else:
entry's own `created` row (`object_kind = entry`, no revision) is skipped
— the card row beside it already carries the bump. Type and field events
are not items.
-- **A row is** `(card id, events.revision, events.kind = deleted,
+- **A row is** `(item id, events.revision, events.kind = deleted,
events.created_at)`: the card's revision *after* that event, whether it
made the card gone, and when. All four are plaintext already under §4.1
case 1 and §4.2; serving S1 unseals nothing, and no row carries a title,
a value, an owner or an actor.
- **History is replayed, not collapsed.** A card edited three times since
the cursor yields three rows; the consumer keeps the last.
-- **The cursor** is the decimal id of the last row returned. `""` is the
- beginning. At the tip the page is `rows: []` and the same cursor — except
- that `""` at an empty log answers `"0"`, because the contract refuses an
- empty cursor, and the next poll gets `"0"` back. `events.id` is
- `AUTOINCREMENT` and SQLite has one writer, so ids are committed in order
- and never reused: a cursor can never step past a row that commits later
- with a lower id.
-- **A cursor Fichas could not have issued is an error, never a page.** One
- that is not a canonical non-negative decimal, or that is ahead of the
- log's highest id (the database restored from an older backup), makes the
- feed fail, which §6.5 turns into a 503. An empty page there would stall
- the consumer silently on a log that has gone backwards; a 503 is loud.
- Whether it should instead re-announce from the beginning is §10's.
-
-**item_id is the card id as a canonical decimal string** — `"42"`, never
-`"042"` or `"+42"`, so one card has exactly one id on the wire. It is
-structural (§4.1 case 2), never content; `cards.id` is `AUTOINCREMENT` and
-cards are never deleted as rows (`DeleteCard` marks them gone), so an id is
-never reused for a different card. It tells the consumer roughly how many
-cards were ever made, which a consumer that holds every card knows anyway.
+- **The cursor** is `"<event id>.<that event's created_at, unix
+ nanoseconds>"` for the last row returned. `""` and `"0"` are the
+ beginning. At the tip the page is `rows: []` and the same cursor —
+ except that `""` answers `"0"`, because the contract refuses an empty
+ cursor, and the next poll gets `"0"` back. Within one database history,
+ `events.id` is `AUTOINCREMENT` and SQLite has one writer, so ids are
+ committed in order: a cursor can never step past a row that commits
+ later with a lower id.
+- **Every request checks the cursor's stamp.** The event at the cursor's
+ id must still exist, be a card event, and carry that `created_at`.
+ Otherwise the feed fails, which §6.5 turns into a 503 — loud, never a
+ page. A cursor that is not in the canonical form fails the same way.
+
+**item_id is `"<card id>.<card created_at, unix nanoseconds>"`** — e.g.
+`"42.1793571162737001000"` — both parts canonical positive decimals, so one
+card has exactly one id on the wire (`"042.…"`, `"+42.…"` and a bare
+`"42"` are not it). Both parts are structural and already plaintext (§4.1
+case 2, §4.2), never content. `created_at` is written once, by the insert,
+and never updated (`bumpRevision` moves only `revision`, `updated_at` and
+`gone`); stored as text, it round-trips to the nanosecond the clock
+supplied. It tells the consumer when each card was made, which the feed's
+first row for it already says.
+
+**Why the stamps (Astra review, 2026-11-01).** "An id is never reused" is
+true only within one database history. Restore an older backup and
+`AUTOINCREMENT` starts again from the backup's counters: a card created
+afterwards can get exactly the id, revision 1 and event position of a card
+memoria already holds, with different text. With bare ids, S1 would then
+answer an unchanged empty page, S2 would answer `VISIBLE` for memoria's old
+copy, and S3 would serve the new card's text under the old identity. The
+stamps make that impossible: the new card's `created_at` differs, so the
+old item id is `NOT_VISIBLE` in S2 and refused in S3, and the event at the
+old cursor carries a different stamp (or is gone), so S1 is a 503.
+
+**What the stamps do not protect, and the reset.** A card that predates the
+restore point keeps its id and stamp — correctly, it is the same card. If
+memoria held a revision of it written *after* the restore point, and the
+card is edited again after the restore up to that same revision number,
+the same `(item id, revision)` names different text. S2 cannot tell them
+apart, so until memoria is reset it answers `VISIBLE` for the abandoned
+copy. S1 does go loud in exactly that case: memoria's cursor is at or past
+the event that wrote the abandoned revision, and the restore dropped it.
+So **a Fichas 503 on S1 after a restore means: reset the consumer** —
+discard every item it holds from this instance and its cursor, and
+re-read from `""`. Resetting the cursor alone is not enough. Closing the
+gap in S2 itself would need revisions that a restore cannot reproduce
+(e.g. event timestamps rather than a per-card counter), which the custody
+fixture's fixed revision numbers cannot express; §10.
### 6.3 S2 — admission, keyed on the address
@@ -420,20 +448,23 @@ pair, in order:
|---|---|
| kind `person_ref` — a kind Fichas does not key on | `UNKNOWN`, every pair |
| `address`, not admitted (`Admit`: the `FICHAS_OWNERS` list, the one predicate sign-in and every session already run) | `NOT_VISIBLE`, every pair |
-| admitted; card gone, unknown, or an id that is not a canonical card id | `NOT_VISIBLE` |
+| admitted; card gone, unknown, an id not in the canonical `<card id>.<stamp>` form, or a stamp that is not this card's `created_at` (a different card under a reused id) | `NOT_VISIBLE` |
| admitted; asked revision = current | `VISIBLE` |
| admitted; 1 ≤ asked revision < current | `STALE` |
-| admitted; asked revision > current, or < 1 (a revision the log never issued) | `UNKNOWN` |
+| admitted; asked revision > current, or < 1 — zero or negative (a revision the log never issued) | `UNKNOWN` |
Nothing is cached: admission and every card's revision are read per call.
### 6.4 S3 — the card as plain text
-Current revision only; anything else — gone, unknown id, a revision that
-is not current — is `suite.ErrNotAvailable`, which §6.5's package answers
-with its one empty 404. The revision is checked before the card is read and
-again after, so an edit that lands mid-read is refused rather than served
-under the old number.
+Current revision only; anything else — gone, unknown id, a stamp that is
+not this card's (§6.2), a revision that is not current — is
+`suite.ErrNotAvailable`, which §6.5's package answers with its one empty
+404. The revision is checked before the card is read and again after, so
+an edit that lands mid-read is refused rather than served under the old
+number. A database failure on that second read is an error, answered 503
+and retried by the consumer — never the 404, which tells it the card is
+gone.
The body, lines joined by `\n` with no trailing newline:
@@ -659,10 +690,19 @@ sealed or sealed+print only.
retention one, and TensorX's zero-retention posture does not answer it
(`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). A consumer's cursor ahead of
- the log is a 503 today — loud, and stuck until someone resets the
- consumer. Re-announcing from the beginning would heal itself but replays
- every card's history. Open for Paul; added 2026-11-01.
+- **S1 after a restore from backup** (§6.2; revised after Astra's review,
+ 2026-11-01). What is protected: a card recreated after a restore cannot
+ pass as one memoria holds (the item id's stamp), and a feed position
+ rewritten by a restore is a 503 rather than a silent continuation (the
+ cursor's stamp). What is not: a card that predates the restore point and
+ is edited back up to a revision memoria already holds names different
+ text under the same `(item id, revision)`, and S2 says `VISIBLE` for
+ the abandoned copy until memoria is reset. 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 `""`. Open for
+ Paul: whether memoria should do that by itself on a persistent S1 503,
+ and whether Fichas revisions should become restore-proof (event
+ timestamps), at the cost of the fixture's fixed revision numbers.
- **A field rename and memoria's copy** (§6.4). Renaming a field moves no
card's revision, so memoria keeps the old label in its copy of each card
until that card next changes. Bumping every card of the type on a rename
diff --git a/internal/fichas/suite.go b/internal/fichas/suite.go
index 96a69e1..4f5a625 100644
--- a/internal/fichas/suite.go
+++ b/internal/fichas/suite.go
@@ -35,64 +35,112 @@ type suiteProducer struct {
var _ server.Producer = (*suiteProducer)(nil)
// Feed pages the events table (spec §6.2): card events after the cursor,
-// in id order, one row each. The cursor is the last row's event id.
+// in id order, one row each.
+//
+// The cursor is "<event id>.<that event's created_at, unix nanoseconds>",
+// and the stamp is checked on every request. After a restore from an older
+// backup, AUTOINCREMENT hands the same event ids out again to different
+// events; a bare id would then continue silently from a position that now
+// means something else. A stamp that no longer matches is an error — a 503,
+// loud — never a page.
func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
- after, err := parseCursor(cursor)
+ after, stamp, err := parseCursor(cursor)
if err != nil {
return suite.Feed{}, err
}
+ g := p.g.WithContext(ctx)
+ if after > 0 {
+ var at []Event
+ if err := g.Model(&Event{}).Select("id", "created_at").
+ Where("id = ? AND object_kind = ?", after, ObjectCard).Find(&at).Error; err != nil {
+ return suite.Feed{}, fmt.Errorf("fichas: reading the feed cursor's event: %w", err)
+ }
+ if len(at) != 1 || at[0].CreatedAt.UnixNano() != stamp {
+ return suite.Feed{}, fmt.Errorf("fichas: feed cursor %q names an event this log does not hold; it was rewritten by a restore, so the consumer must be reset", cursor)
+ }
+ }
var evs []Event
- // Only the four plaintext columns the row needs: nothing sealed is
- // read, so nothing sealed can reach a row.
- if err := p.g.WithContext(ctx).Model(&Event{}).
+ // Only plaintext columns: nothing sealed is read, so nothing sealed can
+ // reach a row.
+ if err := g.Model(&Event{}).
Select("id", "kind", "object_id", "revision", "created_at").
Where("id > ? AND object_kind = ?", after, ObjectCard).
Order("id").Limit(limit).Find(&evs).Error; err != nil {
return suite.Feed{}, fmt.Errorf("fichas: reading the feed: %w", err)
}
if len(evs) == 0 {
- // At the tip, the same cursor — unless it is ahead of the log,
- // which means the log went backwards (a restore). An empty page
- // there would stall the consumer silently, so it is an error.
- var latest int64
- if err := p.g.WithContext(ctx).Model(&Event{}).
- Select("COALESCE(MAX(id), 0)").Scan(&latest).Error; err != nil {
- return suite.Feed{}, fmt.Errorf("fichas: reading the log's tip: %w", err)
- }
- if after > latest {
- return suite.Feed{}, fmt.Errorf("fichas: feed cursor %d is ahead of the log (%d)", after, latest)
+ // At the tip: the same cursor, and no rows. "" becomes "0", the
+ // beginning, because the contract refuses an empty cursor.
+ if cursor == "" {
+ cursor = "0"
}
- return suite.Feed{Cursor: strconv.FormatInt(after, 10), Rows: []suite.FeedRow{}}, nil
+ return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil
+ }
+ stamps, err := p.cardStamps(ctx, evs)
+ if err != nil {
+ return suite.Feed{}, err
}
rows := make([]suite.FeedRow, len(evs))
for i, e := range evs {
+ created, ok := stamps[e.ObjectID]
+ if !ok {
+ // Card rows are never deleted, so an event for a card with no
+ // row is a log this code did not write. Loud, not skipped.
+ return suite.Feed{}, fmt.Errorf("fichas: event %d names card %d, which has no row", e.ID, e.ObjectID)
+ }
rows[i] = suite.FeedRow{
- ItemID: strconv.FormatInt(e.ObjectID, 10),
+ ItemID: itemID(e.ObjectID, created),
Revision: e.Revision,
Gone: e.Kind == EventDeleted,
TouchedAt: e.CreatedAt,
}
}
- return suite.Feed{Cursor: strconv.FormatInt(evs[len(evs)-1].ID, 10), Rows: rows}, nil
+ last := evs[len(evs)-1]
+ return suite.Feed{Cursor: stampedID(last.ID, last.CreatedAt.UnixNano()), Rows: rows}, nil
}
-// parseCursor reads a cursor Fichas issued: "" is the beginning, anything
-// else a canonical non-negative decimal. Anything else was not issued here
-// and is an error, never a guess.
-func parseCursor(c string) (int64, error) {
- if c == "" {
- return 0, nil
+// cardStamps is each card's creation stamp, for the cards a page names.
+func (p *suiteProducer) cardStamps(ctx context.Context, evs []Event) (map[int64]int64, error) {
+ ids := make([]int64, 0, len(evs))
+ for _, e := range evs {
+ ids = append(ids, e.ObjectID)
}
- n, err := strconv.ParseInt(c, 10, 64)
- if err != nil || n < 0 || strconv.FormatInt(n, 10) != c {
- return 0, fmt.Errorf("fichas: feed cursor %q was not issued by fichas", c)
+ var cards []Card
+ if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "created_at").
+ Where("id IN ?", ids).Find(&cards).Error; err != nil {
+ return nil, fmt.Errorf("fichas: reading card stamps: %w", err)
}
- return n, nil
+ out := make(map[int64]int64, len(cards))
+ for _, c := range cards {
+ out[c.ID] = c.CreatedAt.UnixNano()
+ }
+ return out, nil
}
-// parseItemID reads an item id: a card id as a canonical decimal, so one
-// card has exactly one id on the wire ("042" and "+42" are not card 42).
-func parseItemID(s string) (int64, bool) {
+// itemID is a card's id on the wire: "<card id>.<card created_at, unix
+// nanoseconds>". The id alone is not enough: after a restore from an older
+// backup, a card created afterwards can be given the id, revision and event
+// position of one the consumer already holds. created_at is written once,
+// at insert, and never updated, so the pair names one card in one history.
+func itemID(cardID, created int64) string { return stampedID(cardID, created) }
+
+func stampedID(id, stamp int64) string {
+ return strconv.FormatInt(id, 10) + "." + strconv.FormatInt(stamp, 10)
+}
+
+// parseStamped reads "<id>.<stamp>", both canonical positive decimals, so a
+// value has exactly one spelling ("042.7", "+42.7", "42" are not 42.7).
+func parseStamped(s string) (id, stamp int64, ok bool) {
+ head, tail, found := strings.Cut(s, ".")
+ if !found {
+ return 0, 0, false
+ }
+ id, ok1 := canonicalPositive(head)
+ stamp, ok2 := canonicalPositive(tail)
+ return id, stamp, ok1 && ok2
+}
+
+func canonicalPositive(s string) (int64, bool) {
n, err := strconv.ParseInt(s, 10, 64)
if err != nil || n < 1 || strconv.FormatInt(n, 10) != s {
return 0, false
@@ -100,6 +148,20 @@ func parseItemID(s string) (int64, bool) {
return n, true
}
+// parseCursor reads a cursor Fichas issued: "" or "0" is the beginning,
+// anything else "<event id>.<stamp>". Anything else was not issued here and
+// is an error, never a guess.
+func parseCursor(c string) (after, stamp int64, err error) {
+ if c == "" || c == "0" {
+ return 0, 0, nil
+ }
+ after, stamp, ok := parseStamped(c)
+ if !ok {
+ return 0, 0, fmt.Errorf("fichas: feed cursor %q was not issued by fichas", c)
+ }
+ return after, stamp, nil
+}
+
// Rule is S2 (spec §6.3). Fichas is lone-shape only, so it keys on an
// address; a person_ref is a kind it cannot read and answers UNKNOWN,
// loudly, rather than NOT_VISIBLE, which a consumer may act on silently.
@@ -121,31 +183,32 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
ids := make([]int64, 0, len(pairs))
for _, pr := range pairs {
- if id, ok := parseItemID(pr.ItemID); ok {
+ if id, _, ok := parseStamped(pr.ItemID); ok {
ids = append(ids, id)
}
}
- current := map[int64]int64{} // live cards only: id → revision
+ live := map[int64]Card{} // live cards only
if len(ids) > 0 {
var cards []Card
- if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision").
+ if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision", "created_at").
Where("id IN ? AND gone = ?", ids, false).Find(&cards).Error; err != nil {
return nil, fmt.Errorf("fichas: reading revisions: %w", err)
}
for _, c := range cards {
- current[c.ID] = c.Revision
+ live[c.ID] = c
}
}
for i, pr := range pairs {
- id, ok := parseItemID(pr.ItemID)
- rev, live := current[id]
+ id, stamp, ok := parseStamped(pr.ItemID)
+ c, found := live[id]
switch {
- case !ok || !live:
+ case !ok || !found || c.CreatedAt.UnixNano() != stamp:
+ // Gone, unknown, or a different card under a reused id.
out[i] = suite.NOT_VISIBLE
- case pr.Revision == rev:
+ case pr.Revision == c.Revision:
out[i] = suite.VISIBLE
- case pr.Revision >= 1 && pr.Revision < rev:
+ case pr.Revision >= 1 && pr.Revision < c.Revision:
out[i] = suite.STALE
default:
// Ahead of the log (a restore), or below 1, which it never
@@ -159,7 +222,7 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
// Content is S3 (spec §6.4): the card's text at its current revision, and
// suite.ErrNotAvailable for anything else.
func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) {
- id, ok := parseItemID(itemID)
+ id, stamp, ok := parseStamped(itemID)
if !ok {
return nil, suite.ErrNotAvailable
}
@@ -176,7 +239,9 @@ func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int
// check pins where the read STARTED: without it, an edit landing
// mid-read that produces the asked revision passes the second check
// with the old row's values under the new number.
- if cv.Card.Revision != revision {
+ if cv.Card.CreatedAt.UnixNano() != stamp || cv.Card.Revision != revision {
+ // A different card under a reused id (a restore), or another
+ // revision.
return nil, suite.ErrNotAvailable
}
body := cardText(cv)
@@ -186,7 +251,10 @@ func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int
// unchanged now, everything above was read at that revision.
var now Card
if err := p.g.WithContext(ctx).Select("id", "revision").First(&now, id).Error; err != nil {
- return nil, err
+ // Not ErrNotAvailable: a failed read is not a refusal, and the
+ // card was there a moment ago. An error is a 503, which the
+ // consumer retries.
+ return nil, fmt.Errorf("fichas: re-reading card %d's revision: %w", id, err)
}
if now.Revision != revision {
return nil, suite.ErrNotAvailable
diff --git a/internal/fichas/suite_conformance_test.go b/internal/fichas/suite_conformance_test.go
index 31e6e15..0d00331 100644
--- a/internal/fichas/suite_conformance_test.go
+++ b/internal/fichas/suite_conformance_test.go
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"slices"
- "strconv"
"testing"
"amadan.net/oficina/suite"
@@ -86,7 +85,9 @@ func (n fixtureNames) name(id string) string {
// removed → 21 (wrong kind answered NOT_VISIBLE); gone cards answered in
// Rule → 15; the title repeated as a "Name:" line → 20; feed rows never
// gone → 13; feed rows at revision 1 → 20; one-row pages under a cursor
-// that never settles → 13 (no tip); a revision ahead answered STALE → 16.
+// that never settles → red (re-run after the stamped cursor: the junk
+// cursor is now refused outright); a revision ahead answered STALE → 16.
+// Counts re-measured after item ids and cursors gained their stamps.
// One survivor here: the next cursor taken from a page's FIRST row repeats
// rows but still ends on the right state, which is all the harness reads;
// TestSuiteFeedIsTheEventLog catches it.
@@ -133,7 +134,7 @@ func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
if err := g.First(&now, card.ID).Error; err != nil || now.Revision != c.Revision || now.Gone != gone {
t.Fatalf("seeding %s: card is %+v (%v), want revision %d gone %v", c.ItemID, now, err, c.Revision, gone)
}
- ids[c.ItemID] = strconv.FormatInt(card.ID, 10)
+ ids[c.ItemID] = id(now)
}
// CheckAs sends the fixture's asker and stranger as addresses with
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go
index 5a8b1eb..ef895e6 100644
--- a/internal/fichas/suite_test.go
+++ b/internal/fichas/suite_test.go
@@ -2,6 +2,7 @@ package fichas
import (
"errors"
+ "net/http/httptest"
"slices"
"strconv"
"strings"
@@ -10,6 +11,7 @@ import (
"gorm.io/gorm"
"amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/server"
)
// The producer half of the suite contract (spec §6). These drive the
@@ -34,14 +36,29 @@ func suiteWorld(t *testing.T) (*gorm.DB, *app, *suiteProducer) {
func mustCard(t *testing.T, g *gorm.DB, a *app, values map[string]string) Card {
t.Helper()
- c, err := CreateCard(ctx(), g, a.sealer, TypeCustomer, Person(1), values)
+ return mustCardBy(t, g, a, Person(1), values)
+}
+
+// mustCardBy creates a card as actor and returns it as the database holds
+// it, so its created_at — half of its item id — is the stored value.
+func mustCardBy(t *testing.T, g *gorm.DB, a *app, actor Actor, values map[string]string) Card {
+ t.Helper()
+ c, err := CreateCard(ctx(), g, a.sealer, TypeCustomer, actor, values)
if err != nil {
t.Fatalf("CreateCard: %v", err)
}
- return c
+ var stored Card
+ if err := g.First(&stored, c.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ return stored
}
-func id(c Card) string { return strconv.FormatInt(c.ID, 10) }
+// id is a card's item id: "<card id>.<created_at unix nanos>".
+func id(c Card) string { return itemID(c.ID, c.CreatedAt.UnixNano()) }
+
+// bare is the card id alone, which is not an item id.
+func bare(c Card) string { return strconv.FormatInt(c.ID, 10) }
func address(v string) suite.Subject { return suite.Subject{Kind: suite.SubjectAddress, Value: v} }
@@ -179,25 +196,38 @@ func TestSuiteFeedOnAnEmptyLog(t *testing.T) {
}
// A cursor Fichas could not have issued is an error (the server makes it a
-// 503), never a page: not a canonical decimal, or ahead of the log — a
-// restore from an older backup, where an empty page would stall the
-// consumer silently.
+// 503), never a page: not "<event id>.<stamp>" in canonical form, ahead of
+// the log, or naming an event whose stamp the log does not hold — a
+// restore from an older backup, where a page would continue silently from
+// a position that now means something else.
//
-// MUTATION-TESTED 2026-11-01, each reverted: the canonical-form check
-// removed ("007", "+5" accepted) → "007"/"+5"; the ahead-of-the-log check
-// removed → "ahead"; a negative accepted → "-1".
+// MUTATION-TESTED 2026-11-01, each reverted: the canonical check removed
+// from canonicalPositive → "leading zero"/"plus"; a bare event id accepted
+// as a cursor AND the lookup skipped for it → "no stamp"; the cursor's
+// event lookup skipped → "ahead"/"wrong stamp"; the stamp comparison
+// removed → "wrong stamp". Two mutants survive and are equivalent: a bare
+// id parsed as stamp 0 (the lookup then refuses it), and canonicalPositive's
+// n < 1 bound removed (no event or card has a zero or negative id or
+// stamp, so the lookup refuses those too).
func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
g, a, p := suiteWorld(t)
mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
_, tip := readFeed(t, p, "", 10)
- n, _ := strconv.ParseInt(tip, 10, 64)
+ n, stamp, ok := parseStamped(tip)
+ if !ok {
+ t.Fatalf("the tip %q is not <event id>.<stamp>", tip)
+ }
for name, c := range map[string]string{
- "letters": "abc",
- "-1": "-1",
- "007": "007",
- "+5": "+5",
- "spaces": " 5",
- "ahead": strconv.FormatInt(n+1000, 10),
+ "letters": "abc",
+ "-1": "-1",
+ "no stamp": strconv.FormatInt(n, 10),
+ "leading zero": "0" + tip,
+ "plus": "+" + tip,
+ "stamp zero": stampedID(n, 0),
+ "three parts": tip + ".1",
+ "spaces": " " + tip,
+ "ahead": stampedID(n+1000, stamp),
+ "wrong stamp": stampedID(n, stamp+1),
} {
if f, err := p.Feed(ctx(), c, 10); err == nil {
t.Errorf("%s: cursor %q answered %+v, want an error", name, c, f)
@@ -210,10 +240,12 @@ func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
// MUTATION-TESTED 2026-11-01, each reverted: the person_ref branch removed
// (a person_ref falls to admission and answers NOT_VISIBLE) → "person_ref";
// admission skipped → "not admitted"; the gone filter dropped from the
-// revision query → "gone"; STALE's lower bound removed (revision 0 is
-// STALE) → "revision 0"; the > current case answering STALE →
-// "ahead"; == current answering STALE → "current"; parseItemID's canonical
-// check removed ("03" is card 3) → "not canonical".
+// revision query → "gone"; STALE's lower bound removed (0 and negatives
+// are STALE) → "revision 0"/"negative revision"; the lower bound loosened
+// to >= 0 → "revision 0"; the > current case answering STALE → "ahead";
+// == current answering STALE → "current"; the canonical check removed →
+// "not canonical"; the stamp comparison removed → "wrong stamp"; the
+// query restricted to owner_id = 1 → "owned by another member".
func TestSuiteRuleEveryBranch(t *testing.T) {
g, a, p := suiteWorld(t)
live := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
@@ -227,19 +259,27 @@ func TestSuiteRuleEveryBranch(t *testing.T) {
if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil {
t.Fatal(err)
}
- padded := "0" + id(live)
+ // Owner is provenance, not authority: a card another member made is
+ // every admitted person's.
+ theirs := mustCardBy(t, g, a, Person(2), map[string]string{FieldName: "Their card"})
+ wrongStamp := itemID(live.ID, live.CreatedAt.UnixNano()+1)
pairs := []suite.ItemRevision{
- {ItemID: id(live), Revision: 3}, // current
- {ItemID: id(live), Revision: 2}, // behind
- {ItemID: id(live), Revision: 4}, // ahead
- {ItemID: id(live), Revision: 0}, // revision 0
- {ItemID: id(gone), Revision: 2}, // gone, at its last revision
- {ItemID: "999999", Revision: 1}, // unknown
- {ItemID: "doc-team", Revision: 1}, // not a card id
- {ItemID: padded, Revision: 3}, // not canonical
- }
- names := []string{"current", "behind", "ahead", "revision 0", "gone", "unknown", "not a card id", "not canonical"}
+ {ItemID: id(live), Revision: 3}, // current
+ {ItemID: id(live), Revision: 2}, // behind
+ {ItemID: id(live), Revision: 4}, // ahead
+ {ItemID: id(live), Revision: 0}, // revision 0
+ {ItemID: id(live), Revision: -1}, // negative revision
+ {ItemID: id(gone), Revision: 2}, // gone, at its last revision
+ {ItemID: "999999.1", Revision: 1}, // unknown
+ {ItemID: "doc-team", Revision: 1}, // not a card id
+ {ItemID: "0" + id(live), Revision: 3}, // not canonical
+ {ItemID: bare(live), Revision: 3}, // no stamp
+ {ItemID: wrongStamp, Revision: 3}, // wrong stamp
+ {ItemID: id(theirs), Revision: 1}, // owned by another member
+ }
+ names := []string{"current", "behind", "ahead", "revision 0", "negative revision", "gone", "unknown",
+ "not a card id", "not canonical", "no stamp", "wrong stamp", "owned by another member"}
check := func(what string, asker suite.Subject, want []suite.Authorization) {
t.Helper()
@@ -265,8 +305,9 @@ func TestSuiteRuleEveryBranch(t *testing.T) {
}
check("admitted", address(admittedAsker), []suite.Authorization{
- suite.VISIBLE, suite.STALE, suite.UNKNOWN, suite.UNKNOWN,
+ suite.VISIBLE, suite.STALE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN,
suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE,
+ suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.VISIBLE,
})
// A kind Fichas does not key on is UNKNOWN — loud — even when its value
// happens to be an admitted address.
@@ -315,8 +356,8 @@ func TestSuiteRuleIsNeverCached(t *testing.T) {
// (any revision served) → "an older revision"/"a newer revision"; the
// title field repeated as a "Name:" line → "text"; empty fields emitted as
// "Label: " → "text"; entries left out → "text"; a trailing newline →
-// "text"/"title only"; parseItemID's canonical check removed → "not
-// canonical".
+// "text"/"title only"; the canonical check removed → "not canonical"; the
+// stamp comparison removed → "wrong stamp".
func TestSuiteContent(t *testing.T) {
g, a, p := suiteWorld(t)
c := mustCard(t, g, a, map[string]string{
@@ -368,9 +409,11 @@ func TestSuiteContent(t *testing.T) {
"a newer revision": {id(c), 4},
"gone": {id(gone), 2},
"gone, its old revision": {id(gone), 1},
- "unknown": {"999999", 1},
+ "unknown": {"999999.1", 1},
"not a card id": {"doc-team", 1},
"not canonical": {"0" + id(c), 3},
+ "no stamp": {bare(c), 3},
+ "wrong stamp": {itemID(c.ID, c.CreatedAt.UnixNano()+1), 3},
} {
if body, err := p.Content(ctx(), q.item, q.rev); !errors.Is(err, suite.ErrNotAvailable) || body != nil {
t.Errorf("%s: %q, %v; want ErrNotAvailable and no body", name, body, err)
@@ -419,6 +462,122 @@ func TestSuiteContentRefusesAnEditMidRead(t *testing.T) {
}
}
+// A restore from an older backup, and a different card created after it,
+// reproduce the old card's id, revision and event position exactly (Astra,
+// 2026-11-01). memoria still holds the old card's item id, its text and its
+// feed cursor. None of the three may carry on as if nothing happened: S2
+// does not vouch for the old item, S3 does not serve the new card's text
+// under it, and S1 refuses the old cursor loudly.
+//
+// Modelled with two databases seeded alike: "before" is the backup, taken
+// before the original card existed; "after" is the live database that went
+// on to hold it. The test first proves the collision is real.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: Rule's stamp comparison
+// removed → "S2"; Content's stamp comparison removed → "S3"; the cursor's
+// stamp comparison removed → "S1"; the cursor's event lookup skipped
+// entirely → "S1".
+func TestSuiteRestoreCannotPassOffANewCardAsAnOldOne(t *testing.T) {
+ gBefore, aBefore, pBefore := suiteWorld(t)
+ gAfter, aAfter, pAfter := suiteWorld(t)
+
+ original := mustCard(t, gAfter, aAfter, map[string]string{FieldName: "The original, which memoria holds"})
+ held := id(original)
+ _, heldCursor := readFeed(t, pAfter, "", 10)
+ if got, _ := pAfter.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}}); got[0] != suite.VISIBLE {
+ t.Fatalf("before the restore, the held item: %s", got[0])
+ }
+
+ // The restore: the live database is now "before", and a different card
+ // is made in it.
+ recreated := mustCardBy(t, gBefore, aBefore, Person(2), map[string]string{FieldName: "A different card"})
+ var origEv, newEv []Event
+ gAfter.Where("object_kind = ?", ObjectCard).Find(&origEv)
+ gBefore.Where("object_kind = ?", ObjectCard).Find(&newEv)
+ if recreated.ID != original.ID || recreated.Revision != original.Revision ||
+ len(origEv) != 1 || len(newEv) != 1 || origEv[0].ID != newEv[0].ID {
+ t.Fatalf("the collision did not happen, so this proves nothing: card %d/%d rev %d/%d, events %+v %+v",
+ original.ID, recreated.ID, original.Revision, recreated.Revision, origEv, newEv)
+ }
+ if id(recreated) == held {
+ t.Fatal("the recreated card has the held item id: the clock did not move")
+ }
+
+ got, err := pBefore.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}})
+ if err != nil || got[0] != suite.NOT_VISIBLE {
+ t.Errorf("S2 for the held item after the restore: %v, %v; want NOT_VISIBLE", got, err)
+ }
+ if body, err := pBefore.Content(ctx(), held, 1); !errors.Is(err, suite.ErrNotAvailable) {
+ t.Errorf("S3 for the held item after the restore: served %q, %v; want ErrNotAvailable", body, err)
+ }
+ if f, err := pBefore.Feed(ctx(), heldCursor, 10); err == nil {
+ t.Errorf("S1 from the held cursor %q after the restore: %+v; want an error (a 503), not a page", heldCursor, f)
+ }
+ // The new card is served under its own id.
+ if body, err := pBefore.Content(ctx(), id(recreated), 1); err != nil || string(body) != "A different card" {
+ t.Errorf("S3 for the new card under its own id: %q, %v", body, err)
+ }
+}
+
+// A database failure on S3's final revision re-read is an error, which the
+// server answers 503 and the consumer retries — never ErrNotAvailable, the
+// refusal that tells memoria the card is gone.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the re-read's error mapped to
+// suite.ErrNotAvailable → "a refusal" and "404".
+func TestSuiteContentReReadFailureIsAnError(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ cardsQueries := 0
+ if err := g.Callback().Query().Before("gorm:query").Register("test:fail_reread", func(tx *gorm.DB) {
+ if tx.Statement.Table != "cards" {
+ return
+ }
+ // LoadCard reads the card first; the re-read is the second.
+ if cardsQueries++; cardsQueries == 2 {
+ tx.AddError(errors.New("the disk went away"))
+ }
+ }); err != nil {
+ t.Fatal(err)
+ }
+ _, err := p.Content(ctx(), id(c), 1)
+ if cardsQueries < 2 {
+ t.Fatal("the re-read never ran; the test proves nothing")
+ }
+ if err == nil || errors.Is(err, suite.ErrNotAvailable) {
+ t.Errorf("a failed re-read: %v; want an error that is not a refusal", err)
+ }
+
+ cardsQueries = 0
+ rec := httptest.NewRecorder()
+ server.Routes(p, nil).ServeHTTP(rec, httptest.NewRequest("GET", suite.RouteS3+"/"+id(c)+"?revision=1", nil))
+ if rec.Code != 503 {
+ t.Errorf("through the server: %d, want 503 (404 is a refusal)", rec.Code)
+ }
+}
+
+// An event naming a card with no row is a database this code did not
+// write: the cards_are_not_hard_deleted trigger (migration 0002) refuses
+// the delete, so the test drops it on its own temporary database to build
+// one. The feed fails loudly rather than skip the row, which would move
+// the consumer's cursor past a change it never saw.
+//
+// MUTATION-TESTED 2026-11-01, reverted: the missing-row check skipped →
+// "a card with no row".
+func TestSuiteFeedRefusesAnEventWithNoCard(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ if err := g.Exec("DROP TRIGGER cards_are_not_hard_deleted").Error; err != nil {
+ t.Fatal(err)
+ }
+ if err := g.Exec("DELETE FROM cards WHERE id = ?", c.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if f, err := p.Feed(ctx(), "", 10); err == nil {
+ t.Errorf("a card with no row: %+v, want an error", f)
+ }
+}
+
// Every suite route sits under the one prefix the app mounts and exempts.
func TestSuiteRoutesSitUnderThePrefix(t *testing.T) {
for _, r := range []string{suite.RouteS1, suite.RouteS2, suite.RouteS3} {
diff --git a/internal/fichastest/suite_test.go b/internal/fichastest/suite_test.go
index 0f177f2..727e841 100644
--- a/internal/fichastest/suite_test.go
+++ b/internal/fichastest/suite_test.go
@@ -10,7 +10,7 @@ import (
"net/http/httptest"
"net/url"
"path/filepath"
- "strconv"
+ "regexp"
"strings"
"testing"
@@ -218,8 +218,9 @@ func TestSuiteServesACardMadeThroughTheApp(t *testing.T) {
t.Fatalf("S1: %+v, %v", feed, err)
}
item := feed.Rows[0].ItemID
- if _, err := strconv.ParseInt(item, 10, 64); err != nil {
- t.Errorf("item_id %q is not a card id", item)
+ // "<card id>.<created_at unix nanos>" (spec §6.2).
+ if !regexp.MustCompile(`^[1-9][0-9]*\.[1-9][0-9]*$`).MatchString(item) {
+ t.Errorf("item_id %q is not <card id>.<stamp>", item)
}
rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision=1", suiteToken, nil)