oficina / fichas Public

Card revisions from the clock: a restore cannot reissue a revision memoria holds

Closes the restore gap spec §6.2 documented: a card that predates the
restore point keeps its id and stamp, so a per-card counter edited back up
to a revision memoria held named different text, and S2 said VISIBLE for
the abandoned copy.

nextRevision(prev) = max(prev + 1, now in unix microseconds), for every
bump and for creation (nextRevision(0)). Still int64 and strictly
increasing; ~1.8e15 stays inside 2^53, so JSON and JavaScript keep it
exact. After a restore the held revision reads UNKNOWN (card behind it) or
STALE (edited past it), and S3 refuses it, provided the clock was not set
back by more than the backup-to-restore time. Existing cards keep their
values until their next change. No schema change.

Every reader checked: contract release compares the hidden form revision
for equality only (unchanged), its page shows a longer number; store tests
asserting 1 and 2 now assert ordering and that the chain ends at the
card's revision (the contiguity test becomes 'unbroken'); suite tests pin
the clock at zero to keep readable revisions and the fixture's.

Tests: nextRevision's branches under a pinned clock; a new card's revision
is the clock; back up (VACUUM INTO), edit, restore, edit again on the real
clock: never VISIBLE, not reissued, S3 refused. Mutation-tested: prev + 1
alone, the clock alone, creation at 1, +1 at the bump site, ahead as
STALE all red; >= for > equivalent. Spec §6.2, §6.6, §10 updated, reset
procedure kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev e9a665b3004fa7ab98986249cae32a5ff6de4835 parent 7bfd4c4
7 files changed, +291 −51
  • docs/superpowers/specs/2026-09-19-fichas-design.md +51 −29
  • internal/fichas/models.go +9 −3
  • internal/fichas/store.go +31 −2
  • internal/fichas/store_test.go +29 −13
  • internal/fichas/suite_revision_test.go +138 −0
  • internal/fichas/suite_test.go +15 −0
  • internal/fichastest/suite_test.go +18 −4

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 f7ef8e8..e5c7d58 100644
--- a/docs/superpowers/specs/2026-09-19-fichas-design.md
+++ b/docs/superpowers/specs/2026-09-19-fichas-design.md
@@ -414,28 +414,50 @@ 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
+afterwards can get exactly the id and event position of a card memoria
+already holds — and, while revisions were counters, its revision 1 —
+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.
+**Revisions a restore cannot reproduce — the gap closed (amended
+2026-11-01, this session, as Docs did).** The stamps alone left one case: a
+card that predates the restore point keeps its id and stamp — correctly,
+it is the same card — so if memoria held a revision written *after* the
+restore point and the card was edited back up to that number, one
+`(item id, revision)` would name two texts, and S2 would say `VISIBLE` for
+the abandoned one. So a card's revision is no longer a counter. Every
+change sets it to **max(previous + 1, now in unix microseconds)**
+(store.go `nextRevision`; creation is `nextRevision(0)`): still an int64,
+still strictly increasing per card, and about 1.8e15, inside 2^53, so it
+survives JSON and JavaScript numbers. After a restore, memoria's held
+revision reads `UNKNOWN` while the restored card is behind it, and `STALE`
+once the card is edited past it; S3 refuses it either way. It is never
+`VISIBLE` for different text, because nothing after the restore can be
+issued that number again.
+
+**The clock assumption.** That holds as long as the server's clock has not
+been set back by more than the time between the backup and the restore. A
+larger rollback could land a post-restore edit exactly on a revision
+issued before it; `previous + 1` keeps revisions increasing either way, but
+cannot make them unique across two histories. Cards made before this
+change keep their small revisions until their next change, which jumps
+them to the clock.
+
+**What a revision now reveals.** When the card last changed, to the
+microsecond — what `updated_at`, already plaintext beside it (§4.2), says.
+The contract-release page shows it as "Source revision"; that is now a
+long number, and still only compared for equality.
+
+**The reset is kept.** A restore still rewrites the feed, so S1 still
+answers the consumer's cursor with a 503 (the cursor's stamp). On that
+503: **reset the consumer** — discard every item it holds from this
+instance and its cursor, and re-read from `""` — so held copies that S2
+now answers `STALE` or `UNKNOWN` are replaced rather than withheld for
+ever.
### 6.3 S2 — admission, keyed on the address
@@ -511,7 +533,9 @@ every other route keeps the check.
against `server.Routes` over the real producer and a real database,
through a test-only naming adapter: the fixture's item ids map to the
card ids seeded for them (and feed rows map back) (one Customer card per case, its name the case's
- `s3_body`, edited up to the case's revision; the deleted case deleted).
+ `s3_body`, edited up to the case's revision under a revision clock pinned
+at zero, so each edit is previous + 1 and the fixture's small revisions are
+reproduced exactly; the deleted case deleted).
`CheckAs` sends the fixture's asker and stranger as addresses with their
values unchanged; `pers_ana` is put on the owners list and `pers_bo` is
not. The harness also asks under `person_ref`, which Fichas must answer
@@ -691,18 +715,16 @@ 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,
- 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.
+ and closed 2026-11-01). Protected: a card recreated after a restore
+ cannot pass as one memoria holds (the item id's stamp); a feed position
+ rewritten by a restore is a 503, not a silent continuation (the cursor's
+ stamp); and a card edited after the restore cannot be issued a revision
+ memoria already holds (revisions from the clock), provided the clock was
+ not set back by more than the backup-to-restore time. 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.
- **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/models.go b/internal/fichas/models.go
index b7b4925..6d7e5c5 100644
--- a/internal/fichas/models.go
+++ b/internal/fichas/models.go
@@ -167,7 +167,10 @@ type Card struct {
// (S1: item_id, revision, gone, touched_at) and are plaintext so the
// feed can be served without unsealing and passes the plaintext-grep
// gate unaided. memoria §3.2 already concedes update timestamps as a
- // known leak; this is the same trade, made deliberately.
+ // known leak; this is the same trade, made deliberately. A revision is
+ // drawn from the clock in microseconds (store.go nextRevision), so it
+ // too says when the card last changed — what UpdatedAt beside it
+ // already says. The default only covers rows from before that.
Revision int64 `gorm:"not null;default:1"`
// not null with a default, because a nullable bool does not behave:
// with a NULL row, `gone = 0`, `gone != 1` and `NOT gone` all miss
@@ -324,8 +327,11 @@ type Event struct {
// CARD revision, which left the card's own revision chain with gaps
// that a contiguity check reads as broken.
ChildID int64
- // Revision is the object's revision AFTER this event. Restore needs
- // it to check the diff chain is contiguous, and it is what lets the
+ // Revision is the object's revision AFTER this event. Card revisions
+ // are drawn from the clock (store.go nextRevision), so a card's chain
+ // is strictly increasing rather than counting 1, 2, 3; it is unbroken
+ // when every card revision has its event, which every write path
+ // guarantees by logging in the same transaction. It is what lets the
// log answer "at what revision" for S1 rather than reading the
// current card row.
Revision int64
diff --git a/internal/fichas/store.go b/internal/fichas/store.go
index 481c657..e600956 100644
--- a/internal/fichas/store.go
+++ b/internal/fichas/store.go
@@ -252,6 +252,35 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel
return changed, detail, nil
}
+// revisionClock is the wall clock revisions are drawn from, in unix
+// MICROseconds. A variable so tests can pin it; nothing else sets it.
+var revisionClock = func() int64 { return time.Now().UnixMicro() }
+
+// nextRevision is the revision after prev: max(prev + 1, now in unix
+// microseconds). Spec §6.2.
+//
+// Why a clock and not a counter: a per-card counter restored from an older
+// backup hands out the same numbers again. A card at 7 when backed up,
+// edited to 9 (which memoria then holds), restored to 7 and edited twice
+// more is at 9 again with different text, and S2 would answer VISIBLE for
+// memoria's abandoned copy. Drawn from the clock, the post-restore edits
+// land on revisions after anything issued before the restore — so
+// memoria's held revision reads STALE, or UNKNOWN if the restored card has
+// not yet caught up — never VISIBLE for different text. That holds as long
+// as the clock has not been set back by more than the time between the
+// backup and the restore.
+//
+// prev + 1 keeps it strictly increasing when two changes land in the same
+// microsecond, or the clock steps back a little. Still int64: unix
+// microseconds are about 1.8e15, inside 2^53, so a revision survives JSON
+// and JavaScript numbers exactly.
+func nextRevision(prev int64) int64 {
+ if now := revisionClock(); now > prev+1 {
+ return now
+ }
+ return prev + 1
+}
+
// bumpRevision moves a card's revision, guarded on the revision it read.
//
// The guard makes the invariant LOCAL. Concurrent updates are safe today
@@ -260,7 +289,7 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel
// the log would stop being a truthful account of what happened. Costs one
// clause.
func bumpRevision(tx *gorm.DB, card *Card, extra map[string]any) error {
- next := card.Revision + 1
+ next := nextRevision(card.Revision)
set := map[string]any{"revision": next, "updated_at": time.Now()}
for k, v := range extra {
set[k] = v
@@ -291,7 +320,7 @@ func CreateCard(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string
return err
}
- card = Card{CardTypeID: ct.ID, OwnerID: actor.memberID, Revision: 1}
+ card = Card{CardTypeID: ct.ID, OwnerID: actor.memberID, Revision: nextRevision(0)}
if err := tx.Create(&card).Error; err != nil {
return fmt.Errorf("fichas: creating the card: %w", err)
}
diff --git a/internal/fichas/store_test.go b/internal/fichas/store_test.go
index db6591d..d24b1b9 100644
--- a/internal/fichas/store_test.go
+++ b/internal/fichas/store_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"testing"
+ "time"
"amadan.net/oficina/fichas/internal/fichas/seal"
"gorm.io/gorm"
@@ -43,6 +44,7 @@ func events(t *testing.T, g *gorm.DB, kind string, id int64) []Event {
func TestCreateCardSealsAndLogs(t *testing.T) {
g, s := seeded(t)
+ before := time.Now().UnixMicro()
card, err := CreateCard(ctx(), g, s, TypeCustomer, Person(7), map[string]string{
FieldName: "Cnoc Teoranta",
FieldEmail: "ana@example.com",
@@ -51,7 +53,8 @@ func TestCreateCardSealsAndLogs(t *testing.T) {
if err != nil {
t.Fatalf("CreateCard: %v", err)
}
- if card.ID == 0 || card.Revision != 1 || card.OwnerID == nil || *card.OwnerID != 7 {
+ // A new card's revision is the clock in microseconds (nextRevision).
+ if card.ID == 0 || card.Revision < before || card.Revision > time.Now().UnixMicro() || card.OwnerID == nil || *card.OwnerID != 7 {
t.Fatalf("card is %+v", card)
}
@@ -74,7 +77,7 @@ func TestCreateCardSealsAndLogs(t *testing.T) {
}
ev := events(t, g, ObjectCard, card.ID)
- if len(ev) != 1 || ev[0].Kind != EventCreated || ev[0].ActorID == nil || *ev[0].ActorID != 7 || ev[0].Revision != 1 {
+ if len(ev) != 1 || ev[0].Kind != EventCreated || ev[0].ActorID == nil || *ev[0].ActorID != 7 || ev[0].Revision != card.Revision {
t.Fatalf("events are %+v", ev)
}
var changed []int64
@@ -136,8 +139,11 @@ func TestUpdateCardLogsBeforeAndAfter(t *testing.T) {
t.Fatalf("%d events after one update, want 2", len(ev))
}
last := ev[1]
- if last.Kind != EventUpdated || last.ActorID == nil || *last.ActorID != 2 || last.Revision != 2 {
- t.Fatalf("update event is %+v", last)
+ var reread Card
+ g.First(&reread, card.ID)
+ if last.Kind != EventUpdated || last.ActorID == nil || *last.ActorID != 2 ||
+ last.Revision <= card.Revision || last.Revision != reread.Revision {
+ t.Fatalf("update event is %+v (card created at %d, now at %d)", last, card.Revision, reread.Revision)
}
raw, err := s.Open(seal.PurposeEventPayload, last.PayloadSealed)
if err != nil {
@@ -166,8 +172,8 @@ func TestUpdateCardWithNoChangeWritesNoEvent(t *testing.T) {
}
var reread Card
g.First(&reread, card.ID)
- if reread.Revision != 1 {
- t.Fatalf("a no-op update bumped the revision to %d", reread.Revision)
+ if reread.Revision != card.Revision {
+ t.Fatalf("a no-op update moved the revision from %d to %d", card.Revision, reread.Revision)
}
}
@@ -218,8 +224,8 @@ func TestAddEntryLogsAndMovesTheCardRevision(t *testing.T) {
var reread Card
g.First(&reread, card.ID)
- if reread.Revision != 2 {
- t.Fatalf("card revision is %d after an entry landed, want 2", reread.Revision)
+ if reread.Revision <= card.Revision {
+ t.Fatalf("card revision is %d after an entry landed, was %d", reread.Revision, card.Revision)
}
if n := len(events(t, g, ObjectEntry, entry.ID)); n != 1 {
t.Fatalf("%d events for the entry, want 1", n)
@@ -288,8 +294,10 @@ func TestAnActorIsAPersonOrADeclaredAppAction(t *testing.T) {
// Finding 9: an entry landing used to consume a CARD revision while being
// logged under object_kind=entry, which left the card's own chain with
-// gaps that a contiguity check reads as broken.
-func TestTheCardsRevisionChainIsContiguous(t *testing.T) {
+// gaps. Revisions come from the clock now (nextRevision), so the chain does
+// not count 1, 2, 3: it is unbroken when every card event's revision is
+// strictly after the one before, and the last is the card's own.
+func TestTheCardsRevisionChainIsUnbroken(t *testing.T) {
g, s := seeded(t)
card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"})
if _, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "called"}); err != nil {
@@ -300,11 +308,19 @@ func TestTheCardsRevisionChainIsContiguous(t *testing.T) {
}
ev := events(t, g, ObjectCard, card.ID)
- for i, e := range ev {
- if e.Revision != int64(i+1) {
- t.Fatalf("card event %d is at revision %d; the chain has a gap", i, e.Revision)
+ if len(ev) != 3 {
+ t.Fatalf("%d card events, want 3 (created, entry, update)", len(ev))
+ }
+ for i := 1; i < len(ev); i++ {
+ if ev[i].Revision <= ev[i-1].Revision {
+ t.Fatalf("card event %d is at revision %d, not after %d", i, ev[i].Revision, ev[i-1].Revision)
}
}
+ var reread Card
+ g.First(&reread, card.ID)
+ if ev[len(ev)-1].Revision != reread.Revision {
+ t.Fatalf("the chain ends at %d and the card is at %d", ev[len(ev)-1].Revision, reread.Revision)
+ }
if ev[1].Kind != EventEntryAdded || ev[1].ChildID == 0 {
t.Fatalf("the entry landing is not named on the card's chain: %+v", ev[1])
}
diff --git a/internal/fichas/suite_revision_test.go b/internal/fichas/suite_revision_test.go
new file mode 100644
index 0000000..8ae8f36
--- /dev/null
+++ b/internal/fichas/suite_revision_test.go
@@ -0,0 +1,138 @@
+package fichas
+
+import (
+ "errors"
+ "io"
+ "log/slog"
+ "path/filepath"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/db"
+ "amadan.net/rastrillo/rastrillo/migrate"
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/suite"
+)
+
+// Card revisions come from the clock (spec §6.2, store.go nextRevision):
+// max(prev + 1, now in unix microseconds).
+//
+// MUTATION-TESTED 2026-11-01, each reverted: nextRevision as prev + 1 alone
+// → "the clock ahead" and "a new card"; as the clock alone → "the clock
+// behind" and "the clock equal"; >= for > (the clock at exactly prev + 1)
+// → none, an equivalent mutant (both branches give prev + 1 there).
+func TestRevisionsComeFromTheClock(t *testing.T) {
+ for name, c := range map[string]struct{ prev, now, want int64 }{
+ "the clock ahead": {prev: 7, now: 1_000, want: 1_000},
+ "the clock behind": {prev: 1_000, now: 7, want: 1_001},
+ "the clock equal": {prev: 1_000, now: 1_000, want: 1_001},
+ } {
+ pinRevisionClock(t, func() int64 { return c.now })
+ if got := nextRevision(c.prev); got != c.want {
+ t.Errorf("%s: nextRevision(%d) with the clock at %d is %d, want %d", name, c.prev, c.now, got, c.want)
+ }
+ }
+
+ pinRevisionClock(t, func() int64 { return 1_793_000_000_000_000 })
+ g, s := seeded(t)
+ card, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if card.Revision != 1_793_000_000_000_000 {
+ t.Errorf("a new card is at revision %d, want the clock", card.Revision)
+ }
+}
+
+// restorable is a producer over a database file, so it can be backed up
+// and a backup opened in its place.
+func restorable(t *testing.T, path string) (*gorm.DB, *app, *suiteProducer) {
+ t.Helper()
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ d, err := db.Open(path, logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { d.Close() })
+ if _, err := migrate.Apply(ctx(), d, BootSchema); err != nil {
+ t.Fatal(err)
+ }
+ s := testSealer(t)
+ if err := Seed(d.G, s); err != nil {
+ t.Fatal(err)
+ }
+ var n int64
+ d.G.Model(&Member{}).Count(&n)
+ if n == 0 {
+ pr, _ := s.Print("f_member", []byte("person-1@example.com"))
+ if err := d.G.Create(&Member{AddressPrint: pr}).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ a := &app{sealer: s, owners: ParseOwners(admittedAsker)}
+ return d.G, a, producerFor(d.G, a)
+}
+
+func revisionOf(t *testing.T, g *gorm.DB, id int64) int64 {
+ t.Helper()
+ var c Card
+ if err := g.First(&c, id).Error; err != nil {
+ t.Fatal(err)
+ }
+ return c.Revision
+}
+
+// The gap the item id's stamp could not close (spec §6.2): a card that
+// predates the restore point keeps its id and stamp, so a per-card counter
+// would hand memoria's held revision out again for different text, and S2
+// would answer VISIBLE. On the real clock: back up, edit (memoria holds
+// that revision), restore, and the held revision is UNKNOWN (the restored
+// card is behind it); edit again, and it is STALE, and was not reissued.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: nextRevision as prev + 1
+// alone → "reissued", "S2 after the edit" (VISIBLE for the abandoned copy)
+// and "S3 for the held revision" (the new text served under it); the bump
+// as card.Revision + 1 at its call site → the same three; Rule's ahead
+// case answering STALE → "S2 before the edit".
+func TestSuiteRestoreCannotReissueAHeldRevision(t *testing.T) {
+ dir := t.TempDir()
+ live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db")
+
+ g, a, p := restorable(t, live)
+ card := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ if err := g.Exec("VACUUM INTO ?", backup).Error; err != nil {
+ t.Fatalf("backing up: %v", err)
+ }
+ if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldNotes: "the text memoria holds"}); err != nil {
+ t.Fatal(err)
+ }
+ held := suite.ItemRevision{ItemID: id(card), Revision: revisionOf(t, g, card.ID)}
+ if got, _ := p.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{held}); got[0] != suite.VISIBLE {
+ t.Fatalf("before the restore, the held revision: %s", got[0])
+ }
+
+ // The restore: the backup is the live database now.
+ g2, a2, p2 := restorable(t, backup)
+ if got, _ := p2.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{held}); got[0] != suite.UNKNOWN {
+ t.Errorf("S2 before the edit: the restored card is behind the held revision, got %s, want UNKNOWN", got[0])
+ }
+ if err := UpdateCard(ctx(), g2, a2.sealer, card.ID, Person(1), map[string]string{FieldNotes: "different text"}); err != nil {
+ t.Fatal(err)
+ }
+ now := revisionOf(t, g2, card.ID)
+ if now == held.Revision {
+ t.Errorf("reissued: revision %d names the abandoned text and the new", now)
+ }
+ if now < held.Revision {
+ t.Errorf("after the restore the card is at %d, before the held %d: the clock went back", now, held.Revision)
+ }
+ got, err := p2.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{held})
+ if err != nil || got[0] == suite.VISIBLE {
+ t.Errorf("S2 after the edit, for the held revision: %v, %v; never VISIBLE", got, err)
+ } else if got[0] != suite.STALE {
+ t.Errorf("S2 after the edit, for the held revision: %s, want STALE", got[0])
+ }
+ if body, err := p2.Content(ctx(), held.ItemID, held.Revision); !errors.Is(err, suite.ErrNotAvailable) {
+ t.Errorf("S3 for the held revision after the restore: served %q, %v", body, err)
+ }
+}
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go
index 08b0a72..ed65243 100644
--- a/internal/fichas/suite_test.go
+++ b/internal/fichas/suite_test.go
@@ -28,13 +28,28 @@ func producerFor(g *gorm.DB, a *app) *suiteProducer {
return &suiteProducer{g: g, sealer: a.sealer, admit: a.Admit}
}
+// suiteWorld pins the revision clock at zero, behind every revision, so
+// nextRevision takes its prev + 1 branch and cards count 1, 2, 3. These
+// tests are about what S1, S2 and S3 answer for a revision, and readable
+// numbers keep them so; the custody fixture's fixed revisions need it too.
+// The clock branch has its own tests (suite_revision_test.go), on the real
+// clock.
func suiteWorld(t *testing.T) (*gorm.DB, *app, *suiteProducer) {
t.Helper()
+ pinRevisionClock(t, func() int64 { return 0 })
g, s := seeded(t)
a := &app{sealer: s, owners: ParseOwners(admittedAsker)}
return g, a, producerFor(g, a)
}
+// pinRevisionClock sets the revision clock for one test and puts it back.
+func pinRevisionClock(t testing.TB, now func() int64) {
+ t.Helper()
+ old := revisionClock
+ revisionClock = now
+ t.Cleanup(func() { revisionClock = old })
+}
+
func mustCard(t *testing.T, g *gorm.DB, a *app, values map[string]string) Card {
t.Helper()
return mustCardBy(t, g, a, Person(1), values)
diff --git a/internal/fichastest/suite_test.go b/internal/fichastest/suite_test.go
index 727e841..eeca097 100644
--- a/internal/fichastest/suite_test.go
+++ b/internal/fichastest/suite_test.go
@@ -11,8 +11,10 @@ import (
"net/url"
"path/filepath"
"regexp"
+ "strconv"
"strings"
"testing"
+ "time"
"amadan.net/rastrillo/rastrillo/db"
@@ -212,24 +214,36 @@ func TestSuiteServesACardMadeThroughTheApp(t *testing.T) {
t.Fatalf("creating a card: %d", rec.Code)
}
+ before := time.Now().UnixMicro()
+ if rec := post(t, h, "/cards", url.Values{"f_name": {"Second card"}}); rec.Code != http.StatusSeeOther {
+ t.Fatalf("creating a second card: %d", rec.Code)
+ }
rec := call(h, "GET", suite.RouteS1, suiteToken, nil)
feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes())
- if err != nil || len(feed.Rows) != 1 || feed.Rows[0].Revision != 1 || feed.Rows[0].Gone {
+ if err != nil || len(feed.Rows) != 2 || feed.Rows[0].Gone {
t.Fatalf("S1: %+v, %v", feed, err)
}
- item := feed.Rows[0].ItemID
+ // Revisions are the clock in microseconds (spec §6.2), through the
+ // whole app: the second card's is no earlier than the moment before it
+ // was made, and both are far past any count of edits.
+ if feed.Rows[1].Revision < before || feed.Rows[0].Revision < 1_000_000_000_000_000 {
+ t.Errorf("S1 revisions %d and %d are not the clock in microseconds (second made after %d)",
+ feed.Rows[0].Revision, feed.Rows[1].Revision, before)
+ }
+ item, rev := feed.Rows[0].ItemID, feed.Rows[0].Revision
+ revision := strconv.FormatInt(rev, 10)
// "<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)
+ rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision="+revision, suiteToken, nil)
if rec.Code != http.StatusOK || rec.Body.String() != "Cnoc Teoranta\nEmail: orders@cnoc.example" ||
!strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") {
t.Errorf("S3: %d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type"))
}
- pairs := []suite.ItemRevision{{ItemID: item, Revision: 1}}
+ pairs := []suite.ItemRevision{{ItemID: item, Revision: rev}}
rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, strings.ToUpper(TestOwner), pairs...))
if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.VISIBLE {
t.Errorf("S2 for the admitted owner (sent in upper case): %s", got[0])