oficina / fichas Public

Fichas: adopt suite contract revision 11 (91affa1)

- Pin amadan.net/oficina/suite at 91affa1 (revision 11).
- S1: a cursor this log does not recognise (unparseable, naming no card
  event this log holds, or carrying another nonce) is server.ErrCursorReset,
  answered 409 {"code":"CURSOR_RESET"}, not a 503. A failed read of the
  cursor's event stays an error (503).
- Revisions: a change's revision is redrawn while it equals ANY revision
  the card's log holds, not only the current one (doctrine §6.6, L4); a
  failed history read fails the write; a source that never yields a fresh
  revision fails it after eight draws instead of spinning.
- Conformance runs through conformance.CheckProducer (server.Handler
  behind a minted token), seeds the fixture's prior_revision/revision, pins
  the nine case ids, and expects exactly the twelve inexpressible failures
  in the harness's revision-11 words. No test calls server.Routes.
- fichastest: every suite response through rastrillo.Handler around App
  carries no-store and Vary: Authorization; the reset is the exact 409.

Every guard added or changed is mutation-tested 2026-11-02 and recorded
in its test comment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 84fbcccf7fb527f3b80194866824272c44ad63dd parent c837d28
8 files changed, +441 −84
  • go.mod +1 −1
  • go.sum +2 −4
  • internal/fichas/store.go +43 −2
  • internal/fichas/suite.go +30 −18
  • internal/fichas/suite_conformance_test.go +76 −39
  • internal/fichas/suite_revision_test.go +145 −2
  • internal/fichas/suite_test.go +84 −18
  • internal/fichastest/suite_test.go +60 −0
diff --git a/go.mod b/go.mod
index 78785be..69f362c 100644
--- a/go.mod
+++ b/go.mod
@@ -6,7 +6,7 @@ toolchain go1.26.5
require (
amadan.net/oficina/estilo.git v0.0.0-20261001113457-a264aa5b9540
- amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990
+ amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327
github.com/chromedp/chromedp v0.14.2
diff --git a/go.sum b/go.sum
index da38446..965dc9c 100644
--- a/go.sum
+++ b/go.sum
@@ -1,9 +1,7 @@
amadan.net/oficina/estilo.git v0.0.0-20261001113457-a264aa5b9540 h1:lG6hyBqz13XGisiyhKMHzPoBK6QP8weHQ02je/2gquk=
amadan.net/oficina/estilo.git v0.0.0-20261001113457-a264aa5b9540/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
-amadan.net/oficina/suite v0.0.0-20261101215312-983114acce54 h1:h2/Pv6hQ/F6CvEqv5wgrxhlYn7/fqoDrNAR0Tqnv6VQ=
-amadan.net/oficina/suite v0.0.0-20261101215312-983114acce54/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w=
-amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990 h1:LXUZq/L5aJ700z9A//W5G04O/lxsUSRZrBK1mrBEIP4=
-amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w=
+amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4 h1:BP+KHZTSgL7HDCz9IL/gxKXmbmXQpclUlJIyQEY/N2E=
+amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4/go.mod h1:Xgw0N+DBiDzkhQHm/nIhgumfaiMElDg/KIFD1OxTm5w=
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd h1:jlFSt95M1ontOg+VePU+kIJpChtWqDQAbnmlxqCnbgc=
amadan.net/rastrillo/rastrillo v0.26.1-0.20260908075707-29e4491631bd/go.mod h1:RpyHVPD0udcSfHJroY0KZE/FUjgw6Tvfo8SJm2qeZGE=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
diff --git a/internal/fichas/store.go b/internal/fichas/store.go
index c09c65a..f51d45e 100644
--- a/internal/fichas/store.go
+++ b/internal/fichas/store.go
@@ -303,9 +303,47 @@ func randomRevision(current int64) int64 {
}
}
-// nextRevision is the revision a change to a card at current moves it to.
+// nextRevision is a draw for the revision a change to a card at current
+// moves it to. A new card takes it as it comes: it has no log yet, so there
+// is nothing to collide with (its id is fresh — AUTOINCREMENT never hands
+// out an id this database has used, and cards are never hard-deleted). A
+// change to an existing card goes through freshRevision.
func nextRevision(current int64) int64 { return newRevision(current) }
+// maxRevisionDraws bounds freshRevision. A real draw collides with a card's
+// log with probability (log length) × 2^-63, so a second draw is already
+// beyond anything that happens; the bound exists so that a broken source —
+// one that keeps answering a revision the log holds — fails the write
+// loudly instead of spinning inside its transaction.
+const maxRevisionDraws = 8
+
+// freshRevision draws card's next revision and redraws it while it is any
+// revision the card's log holds, not only the current one (suite doctrine
+// §6.6, revision 11, L4). A draw equal to a revision the card had before
+// would give an old name to new bytes: memoria may still hold that
+// (item, revision) with the old text, and S2 would call it VISIBLE. The log
+// is the card's own card-kind events, read inside the write's transaction,
+// so a revision cannot be added between the check and the write (SQLite has
+// one writer).
+func freshRevision(tx *gorm.DB, card *Card) (int64, error) {
+ for range maxRevisionDraws {
+ next := nextRevision(card.Revision)
+ if next == card.Revision {
+ continue
+ }
+ var held int64
+ if err := tx.Model(&Event{}).
+ Where("object_kind = ? AND object_id = ? AND revision = ?", ObjectCard, card.ID, next).
+ Count(&held).Error; err != nil {
+ return 0, fmt.Errorf("fichas: reading card %d's revision history: %w", card.ID, err)
+ }
+ if held == 0 {
+ return next, nil
+ }
+ }
+ return 0, fmt.Errorf("fichas: no revision for card %d after %d draws that its log does not already hold", card.ID, maxRevisionDraws)
+}
+
// bumpRevision moves a card's revision, guarded on the revision it read.
//
// The guard makes the invariant LOCAL. Concurrent updates are safe today
@@ -314,7 +352,10 @@ func nextRevision(current int64) int64 { return newRevision(current) }
// 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 := nextRevision(card.Revision)
+ next, err := freshRevision(tx, card)
+ if err != nil {
+ return err
+ }
set := map[string]any{"revision": next, "updated_at": time.Now()}
for k, v := range extra {
set[k] = v
diff --git a/internal/fichas/suite.go b/internal/fichas/suite.go
index ff7c476..1753236 100644
--- a/internal/fichas/suite.go
+++ b/internal/fichas/suite.go
@@ -15,9 +15,10 @@ import (
)
// suiteProducer is Fichas' half of the suite contract (spec §6; suite
-// doctrine revision 10, pinned at 983114a, §6.5). server.Handler owns the wire —
-// the bearer check, the decoding, the one S3 refusal — and this owns only
-// what Fichas knows: its log, its admission list, and a card's text.
+// doctrine revision 11, pinned at 91affa1, §6.5 and §6.6). server.Handler
+// owns the wire — the bearer check, the decoding, the cache headers, the
+// cursor reset's 409 and the one S3 refusal — and this owns only what Fichas
+// knows: its log, its admission list, and a card's text.
//
// Paul, 2026-11-01: "Hold private too, check per person." Fichas has no
// sharing ladder — every admitted person sees every card that is not gone
@@ -41,12 +42,26 @@ var _ server.Producer = (*suiteProducer)(nil)
// 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 nonce that no longer matches is an error — a 503,
-// loud — never a page.
+// means something else. The nonce is drawn at random per event and written
+// with it (migrations/0005, logEvent), which is the stamp doctrine §6.6
+// requires: a restored log holds only the nonces of the events it has.
+//
+// A cursor this log does not recognise is server.ErrCursorReset, which the
+// package answers 409 {"code":"CURSOR_RESET"} and the consumer reads as
+// "start over from the beginning" (doctrine §6.6, revision 11): one that
+// does not parse, one whose event is not a card event this log holds —
+// restored away, issued by another log, or ahead of the tip — and one whose
+// event carries another nonce. Fichas expires and compacts nothing (the
+// events table is append-only, §5), so an expired cursor is the same case:
+// were events ever pruned, a cursor naming a pruned one finds no event and
+// is reset. Never a page, and never a 503: a 503 stalls the consumer for
+// ever, which is what revision 10's Fichas did. A failed READ is still an
+// error — a 503 the consumer retries — because a database that did not
+// answer has not said the cursor is wrong.
func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
- after, stamp, err := parseCursor(cursor)
- if err != nil {
- return suite.Feed{}, err
+ after, stamp, ok := parseCursor(cursor)
+ if !ok {
+ return suite.Feed{}, server.ErrCursorReset
}
g := p.g.WithContext(ctx)
if after > 0 {
@@ -56,7 +71,8 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui
return suite.Feed{}, fmt.Errorf("fichas: reading the feed cursor's event: %w", err)
}
if len(at) != 1 || at[0].Nonce != 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)
+ // Restored away, another log's, or ahead of the tip.
+ return suite.Feed{}, server.ErrCursorReset
}
}
var evs []Event
@@ -150,17 +166,13 @@ func canonicalPositive(s string) (int64, bool) {
}
// 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) {
+// anything else "<event id>.<stamp>". Anything else was not issued here: not
+// ok, which Feed answers with the reset, never a guess.
+func parseCursor(c string) (after, stamp int64, ok bool) {
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 0, 0, true
}
- return after, stamp, nil
+ return parseStamped(c)
}
// Rule is S2 (spec §6.3). Fichas is lone-shape only, so it keys on an
diff --git a/internal/fichas/suite_conformance_test.go b/internal/fichas/suite_conformance_test.go
index 8c6978a..e3ae9ae 100644
--- a/internal/fichas/suite_conformance_test.go
+++ b/internal/fichas/suite_conformance_test.go
@@ -15,7 +15,7 @@ import (
// world. It RENAMES and decides nothing: the fixture's item ids become the
// card ids seeded for them, and back again in feed rows (spec §6.7 — a
// fixture id is a name, not an id Fichas could allocate). The askers need
-// no renaming: conformance.CheckAs sends them as addresses. Every answer is
+// no renaming: conformance.CheckProducer sends them as addresses. Every answer is
// the real producer's, over a real database.
type fixtureNames struct {
inner server.Producer
@@ -58,45 +58,78 @@ func (n fixtureNames) name(id string) string {
return id
}
-// The suite's own conformance harness, run as an address-keyed app
-// (conformance.CheckAs, suite.SubjectAddress) against Fichas' real producer
-// over a world seeded from the custody fixture: one Customer card per case,
-// named with the case's s3_body (so S3's exact-body check is a real check
-// of the text shape: a card with only a title is exactly its title), the
-// deleted case deleted, and each card's random revisions then set to the
-// case's revision and the one before it (see the seeding below). The harness also
-// asks under person_ref, a kind Fichas does not key on, and requires
-// UNKNOWN; follows S1 to its tip; and refuses S3 one revision either side.
+// The suite's own conformance harness — conformance.CheckProducer, revision
+// 11's entry point for an app built on suite/server — run as an
+// address-keyed app (suite.SubjectAddress) against Fichas' real producer
+// over a world seeded from the custody fixture. CheckProducer mounts the
+// producer through server.Handler behind a token it mints, exactly as
+// app.go mounts it, and requires the 401 without it; nothing here calls
+// the deprecated, unauthenticated server.Routes. It covers Handler and the
+// producer only: the middleware in front of Handler in production
+// (rastrillo's recovery and security headers, and app.go's outer mux) is
+// fichastest/suite_test.go's to test (doctrine §6.5).
+//
+// The world: one Customer card per case, named with the case's s3_body (so
+// S3's exact-body check is a real check of the text shape: a card with
+// only a title is exactly its title), the deleted case deleted, and each
+// card's random revisions then set to the case's prior_revision and
+// revision (see the seeding below); its unknown_revision is never issued.
+// The harness also asks under person_ref, a kind Fichas does not key on,
+// and requires UNKNOWN; asks S2 about an id Fichas does not know; follows
+// S1 to its tip and asks it from a cursor no log issued (the reset, 409);
+// refuses S3 at both other revisions, with no revision, a malformed one, 0
+// and on POST; and holds every response to no-store and Vary:
+// Authorization.
//
// The fixture describes a sharing ladder Fichas does not have (spec §6.7):
// every admitted person sees every card. So four cases — guest-only,
// link-shared private, moved to private, link added late — expect
// NOT_VISIBLE for the fixture's asker where Fichas, correctly for Fichas,
-// answers VISIBLE at the current revision, STALE one behind and UNKNOWN one
-// ahead (a member may open the card, so a revision the log never issued is
-// UNKNOWN for them, §4.3). This test asserts the failures are EXACTLY those
-// twelve: any other failure, or one of these passing, is red, so a change
-// to the fixture on the suite branch (983114a, review round 2) is noticed
-// here rather than absorbed.
+// answers VISIBLE at the current revision, STALE at the prior revision and
+// UNKNOWN at the never-issued one (a member may open the card, so a
+// revision the log never issued is UNKNOWN for them, §4.3). This test
+// asserts the failures are EXACTLY those twelve, in the harness's own words
+// at 91affa1: any other failure, or one of these passing, is red. And it
+// pins the fixture's nine case ids, so a case added or withdrawn on the
+// suite side (doc-owner-left was withdrawn at 91affa1 pending Paul's
+// ruling; were it restored, Fichas could not express it either: a private
+// card owned by someone no longer admitted is still every member's) is
+// noticed here and the seeding re-read, rather than absorbed.
//
-// MUTATION-TESTED 2026-11-01 against 983114a, each reverted, by how many
-// failures the harness then reports (12 expected): both of Content's
-// revision checks removed → 28 (S3 served at revision ±1); a trailing
+// MUTATION-TESTED 2026-11-01 against 983114a, through CheckAs over
+// server.Routes, by how many failures the harness then reported (12
+// expected): both of Content's revision checks removed → 28; a trailing
// newline on the text → 20; admission skipped → 36; the person_ref branch
-// 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 → 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.
+// removed → 21; 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; a revision ahead answered STALE → 16.
+//
+// MUTATION-TESTED 2026-11-02 against 91affa1, through CheckProducer, each
+// reverted, same measure (12 expected): both of Content's revision checks
+// removed → 28; a trailing newline on the text → 20; admission skipped →
+// 36; the person_ref branch removed → 21; 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; every revision that is not current
+// answered STALE → 16; STALE read off the numbers (1 <= asked < current)
+// instead of the log → 15 (the three openable cases whose unknown_revision
+// sits below the current one; revision 10's harness could not see this);
+// an id Rule cannot find answered VISIBLE (failing open) → 16; an
+// unparseable cursor answered with a plain error, revision 10's 503,
+// instead of the reset → 13.
func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
f, err := suite.LoadCustodyFixture()
if err != nil {
t.Fatal(err)
}
+ var names []string
+ for _, c := range f.Cases {
+ names = append(names, c.ItemID)
+ }
+ if want := []string{"doc-team", "doc-private", "doc-granted", "doc-guest", "doc-link",
+ "doc-team-link", "doc-deleted", "doc-was-team", "doc-link-added-late"}; !slices.Equal(names, want) {
+ t.Fatalf("the custody fixture's cases changed (spec §6.7 and the seeding below were written for nine):\n got %v\nwant %v", names, want)
+ }
+
g, a, p := suiteWorld(t)
// The real, random revisions (suiteWorld pins a count for readability).
pinRevisions(t, randomRevision)
@@ -106,11 +139,15 @@ func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
gone := c.Rung == suite.RungDeleted
// Two real changes, so the card has a history: created, then
// renamed to its s3_body (or deleted). Random revisions cannot be
- // edited into the fixture's numbers, so they are then set
- // directly, the card and its two events together: the last event
- // at the fixture's revision R, and the one before at R - 1, so the
- // harness's "one behind" is in this card's log (STALE) and "one
- // ahead" is not (UNKNOWN).
+ // edited into the fixture's names, so they are then set directly,
+ // the card and its two events together: the first event at the
+ // case's prior_revision and the last at its revision — the
+ // fixture's own names, never computed (doctrine §6.6) — so the
+ // prior revision is in this card's log (STALE) and the unknown one
+ // is not (UNKNOWN).
+ if c.PriorRevision == c.Revision || c.UnknownRevision == c.Revision || c.UnknownRevision == c.PriorRevision {
+ t.Fatalf("seeding %s: the fixture's revisions are not three different names", c.ItemID)
+ }
card := mustCard(t, g, a, map[string]string{FieldName: "draft"})
if gone {
if err := DeleteCard(ctx(), g, a.sealer, card.ID, Person(1)); err != nil {
@@ -127,7 +164,7 @@ func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
table string
id int64
rev int64
- }{{"events", evs[0].ID, c.Revision - 1}, {"events", evs[1].ID, c.Revision}, {"cards", card.ID, c.Revision}} {
+ }{{"events", evs[0].ID, c.PriorRevision}, {"events", evs[1].ID, c.Revision}, {"cards", card.ID, c.Revision}} {
if err := g.Exec("UPDATE "+set.table+" SET revision = ? WHERE id = ?", set.rev, set.id).Error; err != nil {
t.Fatal(err)
}
@@ -139,11 +176,11 @@ func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
ids[c.ItemID] = id(now)
}
- // CheckAs sends the fixture's asker and stranger as addresses with
- // their values unchanged: pers_ana is put on the owners list, as
+ // CheckProducer sends the fixture's asker and stranger as addresses
+ // with their values unchanged: pers_ana is put on the owners list, as
// FICHAS_OWNERS would, and pers_bo is not.
a.owners = ParseOwners(f.Asker.Value)
- report := conformance.CheckAs(server.Routes(fixtureNames{inner: p, ids: ids}, nil), suite.SubjectAddress)
+ report := conformance.CheckProducer(fixtureNames{inner: p, ids: ids}, suite.SubjectAddress)
if report.Checked == 0 {
t.Fatal("conformance checked nothing")
}
@@ -152,8 +189,8 @@ func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) {
for _, item := range []string{"doc-guest", "doc-link", "doc-was-team", "doc-link-added-late"} {
want = append(want,
fmt.Sprintf("S2 %s asked for the fixture's asker, at the current revision: got VISIBLE, want NOT_VISIBLE", item),
- fmt.Sprintf("S2 %s asked for the fixture's asker, one revision behind: got STALE, want NOT_VISIBLE", item),
- fmt.Sprintf("S2 %s asked for the fixture's asker, one revision ahead: got UNKNOWN, want NOT_VISIBLE", item))
+ fmt.Sprintf("S2 %s asked for the fixture's asker, at a prior revision the log holds: got STALE, want NOT_VISIBLE", item),
+ fmt.Sprintf("S2 %s asked for the fixture's asker, at a revision the log never issued: got UNKNOWN, want NOT_VISIBLE", item))
}
got := slices.Clone(report.Failures)
slices.Sort(got)
diff --git a/internal/fichas/suite_revision_test.go b/internal/fichas/suite_revision_test.go
index a80ff9a..af73990 100644
--- a/internal/fichas/suite_revision_test.go
+++ b/internal/fichas/suite_revision_test.go
@@ -19,6 +19,7 @@ import (
"amadan.net/oficina/fichas/internal/fichas/seal"
"amadan.net/oficina/suite"
+ "amadan.net/oficina/suite/server"
)
// Card revisions and nonces are random positive int63s (spec §6.2,
@@ -286,8 +287,8 @@ func TestSuiteRestoreOnAFrozenClockCannotPassOffANewCard(t *testing.T) {
if body, err := p2.Content(ctx(), held.ItemID, held.Revision); !errors.Is(err, suite.ErrNotAvailable) {
t.Errorf("S3 for the held item: served %q, %v", body, err)
}
- if f, err := p2.Feed(ctx(), heldCursor, 10); err == nil {
- t.Errorf("S1 from the held cursor %q: %+v; want an error", heldCursor, f)
+ if f, err := p2.Feed(ctx(), heldCursor, 10); !errors.Is(err, server.ErrCursorReset) {
+ t.Errorf("S1 from the held cursor %q: %+v, %v; want server.ErrCursorReset", heldCursor, f, err)
}
}
@@ -488,3 +489,145 @@ func TestRedrawsHappen(t *testing.T) {
t.Errorf("top bit: drew %d, want 5", got)
}
}
+
+// A change's revision is redrawn while it is ANY revision the card's log
+// holds, not only the current one (suite doctrine §6.6, revision 11, L4): a
+// draw equal to a revision the card had before gives an old name to new
+// bytes, and memoria, still holding that (item, revision) with the old
+// text, would be told VISIBLE. Forced with pinned draws, since a real
+// source collides with probability 2^-63. Also: a draw equal to the
+// current revision is redrawn even where the log does not hold it (a card
+// from before events carried revisions), and a source that never yields a
+// fresh revision fails the write — loudly, with the card unmoved — rather
+// than spinning in its transaction.
+//
+// MUTATION-TESTED 2026-11-02, each reverted: freshRevision's log check
+// removed (only the current one refused, revision 10's rule) → "a prior
+// revision", "never fresh"; the log query not restricted to this card →
+// "another card's revision" (it redraws, and runs out of draws), and
+// TestSuiteFeedIsTheEventLog, TestSuiteRuleEveryBranch and TestSuiteContent,
+// whose pinned counts collide across cards; not restricted to card events
+// → "an entry's event"; the equal-to-current check removed → "current, not
+// in the log"; maxRevisionDraws' bound removed (an unbounded loop) → "never
+// fresh" hangs until the test binary's timeout kills it (run with -timeout
+// 20s); bumpRevision drawing with nextRevision directly, skipping
+// freshRevision → "a prior revision", "current, in the log", "current, not
+// in the log", "never fresh", and TestRevisionDrawHistoryFailureFailsTheWrite.
+func TestRevisionsAreFreshAgainstTheWholeLog(t *testing.T) {
+ g, a, _ := suiteWorld(t)
+ // Each update writes different notes, so each is a change and draws.
+ update := func(notes string) error {
+ return UpdateCard(ctx(), g, a.sealer, firstCard(t, g).ID, Person(1), map[string]string{FieldNotes: notes})
+ }
+
+ drawing(t, 100, 200)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"}) // at 200
+ // c: 100. Move it to 300, so 100 is a prior revision and 300 current.
+ drawing(t, 300)
+ if err := update("first"); err != nil {
+ t.Fatal(err)
+ }
+
+ cases := []struct {
+ name string
+ draws []int64
+ want int64
+ }{
+ {"a prior revision", []int64{100, 400}, 400},
+ {"another card's revision", []int64{200}, 200}, // not this card's: no redraw
+ {"current, in the log", []int64{200, 500}, 500},
+ }
+ for _, tc := range cases {
+ drawing(t, tc.draws...)
+ if err := update(tc.name); err != nil {
+ t.Fatalf("%s: %v", tc.name, err)
+ }
+ if now := revisionOf(t, g, c.ID); now != tc.want {
+ t.Errorf("%s: the card moved to %d, want %d", tc.name, now, tc.want)
+ }
+ }
+
+ // An entry's own creation event is not a card event: its revision
+ // column is 0 today, so plant a value there to show it is not read as
+ // this card's history.
+ drawing(t, 600) // the entry moves the card
+ entry, err := AddEntry(ctx(), g, a.sealer, c.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "rang them"})
+ if err == nil {
+ err = g.Exec("UPDATE events SET revision = 777 WHERE object_kind = ? AND object_id = ?", ObjectEntry, entry.ID).Error
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if entry.ID != c.ID {
+ // The entry's event must share the card's object_id, or a query
+ // that forgot object_kind would miss it anyway and prove nothing.
+ t.Fatalf("entry %d and card %d: the ids do not coincide, so this case proves nothing", entry.ID, c.ID)
+ }
+ drawing(t, 777)
+ if err := update("an entry's event"); err != nil {
+ t.Fatalf("an entry's event: %v", err)
+ }
+ if now := revisionOf(t, g, c.ID); now != 777 {
+ t.Errorf("an entry's event: the card moved to %d, want 777 (an entry's event is not the card's log)", now)
+ }
+
+ // The current revision, with the log not holding it.
+ if err := g.Exec("UPDATE events SET revision = 1 WHERE object_kind = ? AND object_id = ? AND revision = 777", ObjectCard, c.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ drawing(t, 777, 900)
+ if err := update("current, not in the log"); err != nil {
+ t.Fatalf("current, not in the log: %v", err)
+ }
+ if now := revisionOf(t, g, c.ID); now != 900 {
+ t.Errorf("current, not in the log: the card moved to %d, want 900", now)
+ }
+
+ // A source that only ever answers revisions the log holds.
+ pinRevisions(t, func(int64) int64 { return 100 })
+ if err := update("never fresh"); err == nil {
+ t.Errorf("never fresh: the write succeeded")
+ }
+ if now := revisionOf(t, g, c.ID); now != 900 {
+ t.Errorf("never fresh: the card moved to %d", now)
+ }
+}
+
+// firstCard is the oldest card, which TestRevisionsAreFreshAgainstTheWholeLog edits.
+func firstCard(t *testing.T, g *gorm.DB) Card {
+ t.Helper()
+ var c Card
+ if err := g.Order("id").First(&c).Error; err != nil {
+ t.Fatal(err)
+ }
+ return c
+}
+
+// A failed read of the card's revision history fails the write: never a
+// draw taken as fresh because the log could not be asked, which is the
+// reissue §6.6 forbids by another road.
+//
+// MUTATION-TESTED 2026-11-02, reverted: freshRevision's read error taken as
+// "not held" (the draw returned) → "a failed history read".
+func TestRevisionDrawHistoryFailureFailsTheWrite(t *testing.T) {
+ g, a, _ := suiteWorld(t)
+ c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ failing := false
+ if err := g.Callback().Query().Before("gorm:query").Register("test:fail_draw_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
+ err := UpdateCard(ctx(), g, a.sealer, c.ID, Person(1), map[string]string{FieldNotes: "changed"})
+ failing = false
+ if err == nil {
+ t.Errorf("a failed history read: the write succeeded")
+ }
+ if now := revisionOf(t, g, c.ID); now != c.Revision {
+ t.Errorf("a failed history read: the card moved from %d to %d", c.Revision, now)
+ }
+}
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go
index bef4879..bc6ddee 100644
--- a/internal/fichas/suite_test.go
+++ b/internal/fichas/suite_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"net/http/httptest"
+ "net/url"
"slices"
"strconv"
"strings"
@@ -81,6 +82,26 @@ 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} }
+// testToken is the bearer serve mounts the producer behind.
+const testToken = "a-token-for-the-producer-tests"
+
+// serve mounts p exactly as the app does — server.Handler, behind a
+// consumer token — and answers one request carrying that token. Not
+// server.Routes, which revision 11 deprecates: it is the routes with no
+// bearer check, and nothing new may call it (doctrine §6.5).
+func serve(t *testing.T, p server.Producer, method, target string, body []byte) *httptest.ResponseRecorder {
+ t.Helper()
+ h := server.Handler(p, []server.Consumer{{
+ ID: "memoria",
+ Tokens: []server.Token{{Epoch: 1, SHA256: server.TokenHash(testToken)}},
+ }}, nil)
+ req := httptest.NewRequest(method, target, bytes.NewReader(body))
+ req.Header.Set("Authorization", "Bearer "+testToken)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+}
+
// readFeed pages from cursor to the tip, limit rows a page, and returns
// every row and the tip's cursor.
func readFeed(t *testing.T, p *suiteProducer, cursor string, limit int) ([]suite.FeedRow, string) {
@@ -214,11 +235,15 @@ 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 "<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.
+// A cursor Fichas could not have issued is server.ErrCursorReset — the
+// package's 409 {"code":"CURSOR_RESET"}, which tells the consumer to start
+// over from "" (doctrine §6.6, revision 11) — never a page and never a
+// plain error (a 503, which stalls the consumer for ever): 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. Through the server, the reset is exactly the fixed
+// 409, and the beginning is never reset.
//
// MUTATION-TESTED 2026-11-01, each reverted: the canonical check removed
// from canonicalPositive → "leading zero"/"plus"; a bare event id accepted
@@ -231,6 +256,17 @@ func TestSuiteFeedOnAnEmptyLog(t *testing.T) {
// stamped event that is not a card's would have been accepted). One mutant
// survives and is equivalent: a bare id parsed as stamp 0, which the lookup
// then refuses.
+//
+// MUTATION-TESTED 2026-11-02 (revision 11), each reverted: a parse failure
+// returned as a plain error (revision 10's 503) → every malformed case
+// ("letters" to "three parts", "zero id", "negative id"), and the
+// conformance harness's never-issued cursor; a missing event or a stamp
+// mismatch returned as a plain error → "ahead", "wrong stamp", "through the
+// server" (503), "a catalogue event" and both restore tests' S1; the stamp
+// comparison removed again → "wrong stamp", "through the server" (200, a
+// page) and both restore tests; "" and "0" answered with the reset → this
+// test, TestSuiteFeedOnAnEmptyLog, TestSuiteFeedIsTheEventLog and every
+// other test that reads the feed.
func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
g, a, p := suiteWorld(t)
mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
@@ -253,10 +289,14 @@ func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
"zero id": "0.1",
"negative id": "-1.1",
} {
- if f, err := p.Feed(ctx(), c, 10); err == nil {
- t.Errorf("%s: cursor %q answered %+v, want an error", name, c, f)
+ if f, err := p.Feed(ctx(), c, 10); !errors.Is(err, server.ErrCursorReset) {
+ t.Errorf("%s: cursor %q answered %+v, %v; want server.ErrCursorReset", name, c, f, err)
}
}
+ rec := serve(t, p, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(stampedID(n, stamp+1)), nil)
+ if rec.Code != suite.CursorResetStatus || strings.TrimSpace(rec.Body.String()) != suite.CursorResetBody {
+ t.Errorf("through the server: %d %q, want %d %s", rec.Code, rec.Body.String(), suite.CursorResetStatus, suite.CursorResetBody)
+ }
// A catalogue event, correctly stamped, is still not a feed position:
// the feed is card events only, so its ids are not positions in it.
@@ -269,8 +309,37 @@ func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) {
t.Fatal(err)
}
c := stampedID(stored.ID, stored.Nonce)
- if f, err := p.Feed(ctx(), c, 10); err == nil {
- t.Errorf("a catalogue event: cursor %q answered %+v, want an error", c, f)
+ if f, err := p.Feed(ctx(), c, 10); !errors.Is(err, server.ErrCursorReset) {
+ t.Errorf("a catalogue event: cursor %q answered %+v, %v; want server.ErrCursorReset", c, f, err)
+ }
+}
+
+// A failed read of the cursor's event is an error — a 503, which the
+// consumer retries — and never the reset: a database that did not answer
+// has not said the cursor is wrong, and a reset destroys the consumer's
+// whole copy of this instance (doctrine §6.6).
+//
+// MUTATION-TESTED 2026-11-02, reverted: the cursor lookup's read error
+// mapped to server.ErrCursorReset → "a failed cursor read" and "through the
+// server" (409).
+func TestSuiteFeedCursorReadFailureIsNotAReset(t *testing.T) {
+ g, a, p := suiteWorld(t)
+ mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"})
+ _, tip := readFeed(t, p, "", 10)
+ failing := false
+ if err := g.Callback().Query().Before("gorm:query").Register("test:fail_cursor", 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
+ if f, err := p.Feed(ctx(), tip, 10); err == nil || errors.Is(err, server.ErrCursorReset) {
+ t.Errorf("a failed cursor read: %+v, %v; want an error that is not the reset", f, err)
+ }
+ if rec := serve(t, p, "GET", suite.RouteS1+"?cursor="+url.QueryEscape(tip), nil); rec.Code != 503 {
+ t.Errorf("through the server: %d %q, want 503", rec.Code, rec.Body.String())
}
}
@@ -447,9 +516,7 @@ func TestSuiteRuleHistoryFailureIsAnError(t *testing.T) {
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 {
+ if rec := serve(t, p, "POST", suite.RouteS2, body); rec.Code != 503 {
t.Errorf("through the server: %d, want 503", rec.Code)
}
}
@@ -606,7 +673,8 @@ func TestSuiteContentRefusesAnEditMidRead(t *testing.T) {
// 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.
+// under it, and S1 answers the old cursor with the reset (doctrine §6.6),
+// which sends memoria back to "" to re-read this instance.
//
// Modelled with two databases seeded alike: "before" is the backup, taken
// before the original card existed; "after" is the live database that went
@@ -649,8 +717,8 @@ func TestSuiteRestoreCannotPassOffANewCardAsAnOldOne(t *testing.T) {
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)
+ if f, err := pBefore.Feed(ctx(), heldCursor, 10); !errors.Is(err, server.ErrCursorReset) {
+ t.Errorf("S1 from the held cursor %q after the restore: %+v, %v; want server.ErrCursorReset, not a page", heldCursor, f, err)
}
// 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" {
@@ -688,9 +756,7 @@ func TestSuiteContentReReadFailureIsAnError(t *testing.T) {
}
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 {
+ if rec := serve(t, p, "GET", suite.RouteS3+"/"+id(c)+"?revision=1", nil); rec.Code != 503 {
t.Errorf("through the server: %d, want 503 (404 is a refusal)", rec.Code)
}
}
diff --git a/internal/fichastest/suite_test.go b/internal/fichastest/suite_test.go
index 465edb3..fcbb6c1 100644
--- a/internal/fichastest/suite_test.go
+++ b/internal/fichastest/suite_test.go
@@ -4,6 +4,7 @@ import (
"bytes"
"encoding/base64"
"encoding/json"
+ "errors"
"io"
"log/slog"
"net/http"
@@ -15,6 +16,7 @@ import (
"strings"
"testing"
+ "amadan.net/rastrillo/rastrillo"
"amadan.net/rastrillo/rastrillo/db"
fichas "amadan.net/oficina/fichas/internal/fichas"
@@ -249,3 +251,61 @@ func TestSuiteServesACardMadeThroughTheApp(t *testing.T) {
t.Errorf("S2 for an address not admitted: %s", got[0])
}
}
+
+// Every suite response the app serves carries Cache-Control: no-store and
+// Vary: Authorization (doctrine §6.5, revision 11) — a 200, each refusal,
+// the cursor reset, the 401 and the mux's own 404 and 405 — as it leaves
+// the process: through rastrillo.Handler, the assembly Serve uses, around
+// fichas.App exactly as main builds it. server.Handler sets both, and
+// conformance.CheckProducer checks Handler alone; this checks that nothing
+// in front of it — rastrillo's panic recovery and security headers, and
+// app.go's outer mux — drops or rewrites them. Today nothing does:
+// rastrillo's securityHeaders sets only the CSP, nosniff, X-Frame-Options
+// and Referrer-Policy, before the handler runs.
+//
+// The cursor reset is also checked end to end here: a cursor no Fichas log
+// issued is exactly 409 {"code":"CURSOR_RESET"} at the app's edge, which
+// suite.DecodeS1 reads as suite.ErrCursorReset.
+//
+// MUTATION-TESTED 2026-11-02, each reverted: a middleware wrapped round the
+// suite mount in app.go that sets Cache-Control: private, max-age=60 as the
+// status is written → every case; the same middleware deleting Vary →
+// every case; the producer answering an unparseable cursor with a plain
+// error (revision 10's 503) → "the cursor reset", twice.
+func TestEverySuiteResponseIsNoStore(t *testing.T) {
+ served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: suiteApp(t, suiteConsumers()).(*http.ServeMux), ErrorPage: fichas.ErrorPage})
+ if err != nil {
+ t.Fatalf("rastrillo.Handler: %v", err)
+ }
+ t.Cleanup(func() { closeDB() })
+
+ reset := call(served, "GET", suite.RouteS1+"?cursor=never-issued-by-fichas", suiteToken, nil)
+ if _, err := suite.DecodeS1(reset.Code, reset.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) {
+ t.Errorf("the cursor reset: %d %q, want %d %s", reset.Code, reset.Body.String(), suite.CursorResetStatus, suite.CursorResetBody)
+ }
+
+ pair := suite.ItemRevision{ItemID: "1.1", Revision: 1}
+ for _, c := range []struct {
+ name, method, target, tok string
+ body []byte
+ want int
+ }{
+ {"S1", "GET", suite.RouteS1, suiteToken, nil, http.StatusOK},
+ {"the cursor reset", "GET", suite.RouteS1 + "?cursor=never-issued-by-fichas", suiteToken, nil, suite.CursorResetStatus},
+ {"S2", "POST", suite.RouteS2, suiteToken, s2Body(t, TestOwner, pair), http.StatusOK},
+ {"S2, malformed", "POST", suite.RouteS2, suiteToken, []byte("{"), http.StatusBadRequest},
+ {"S3, refused", "GET", suite.RouteS3 + "/1.1?revision=1", suiteToken, nil, http.StatusNotFound},
+ {"no token", "GET", suite.RouteS1, "", nil, http.StatusUnauthorized},
+ {"the mux's 404", "GET", "/suite/s9", suiteToken, nil, http.StatusNotFound},
+ {"the mux's 405", "DELETE", suite.RouteS1, suiteToken, nil, http.StatusMethodNotAllowed},
+ } {
+ rec := call(served, c.method, c.target, c.tok, c.body)
+ if rec.Code != c.want {
+ t.Errorf("%s: %d, want %d", c.name, rec.Code, c.want)
+ }
+ // The harness's own reading of the rule (conformance.storeAudit).
+ if cc, vary := rec.Header().Get("Cache-Control"), rec.Header().Get("Vary"); cc != "no-store" || vary != "Authorization" {
+ t.Errorf("%s: Cache-Control %q, Vary %q; want no-store and Authorization", c.name, cc, vary)
+ }
+ }
+}