Suite producer adopts contract revision 11: CURSOR_RESET, revisions fresh against the whole log, CheckProducer
Fable 5.1 APPROVE at d0c7761; its L1 test gap closed in b60c194. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/suite-r11 into main.
9 files changed,
+591
−127
docs/superpowers/specs/2026-09-19-fichas-design.md+113 −43go.mod+1 −1go.sum+2 −4internal/fichas/store.go+43 −2internal/fichas/suite.go+30 −18internal/fichas/suite_conformance_test.go+76 −39internal/fichas/suite_revision_test.go+145 −2internal/fichas/suite_test.go+121 −18internal/fichastest/suite_test.go+60 −0
CI passed — run details
diff --git a/docs/superpowers/specs/2026-09-19-fichas-design.md b/docs/superpowers/specs/2026-09-19-fichas-design.md| index bd02e05..d66e99b 100644 |
| --- a/docs/superpowers/specs/2026-09-19-fichas-design.md |
| +++ b/docs/superpowers/specs/2026-09-19-fichas-design.md |
| @@ -345,6 +345,23 @@ follows is only what is particular to Fichas. Built on branch |
| `feat/suite-producer`, which sits on `feat/contract-demo` — the build that |
| is live — and not on `main`, which has no code. |
| +**Amended 2026-11-02 (this session, adopting revision 11).** Fichas now |
| +builds against suite doctrine **revision 11**, pinned at |
| +`amadan.net/oficina/suite` commit **`91affa1`** (suite `main`; Fable 5.1 |
| +APPROVE on 640d058, squashed to 91affa1): its status block, §6's S1 row, |
| +§6.5 (the producer half, `Handler` the only mount, |
| +`conformance.RunProducer`/`CheckProducer`, no-store on every response), |
| +§6.6 (revisions and cursors survive a restore; `CURSOR_RESET`), and §11 |
| +gates 3 and 5. Cited, not restated. What changed in Fichas for it: an |
| +unrecognised cursor is `server.ErrCursorReset`, not a 503 (§6.2); a new |
| +revision is redrawn against every revision the card's log holds, not only |
| +the current one (§6.2); the conformance test drives the producer through |
| +`server.Handler` via `CheckProducer` and asks at the fixture's named |
| +revisions (§6.6, §6.7). Gate 5 (a removed member) is Fichas' admission |
| +list: a removed address is `NOT_VISIBLE` on the next S2 call |
| +(`TestSuiteRuleIsNeverCached`); Fichas has no grants or ownership for it to |
| +keep, so §14's open question has nothing to act on here. |
| + |
| **S9 (reach) depends on an unresolved ruling — see §10.** |
| ### 6.1 Paul's ruling, and why it costs Fichas nothing new |
| @@ -398,8 +415,20 @@ else: |
| lower id. |
| - **Every request checks the cursor's nonce.** The event at the cursor's |
| id must still exist, be a card event, and carry that nonce. 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. |
| + the feed returns `server.ErrCursorReset`, which the package answers |
| + `409 {"code":"CURSOR_RESET"}` (doctrine §6.6, revision 11) — never a |
| + page, and since revision 11 never a 503 either, which stalled the |
| + consumer for ever. A cursor that is not in the canonical form, names an |
| + event ahead of the log, or one another log issued is reset the same way. |
| + Fichas expires and compacts nothing (the log is append-only, §5), so an |
| + expired cursor cannot arise; were events ever pruned, a cursor naming a |
| + pruned one would find no event and be reset. A failed *read* of the |
| + cursor's event stays an error, a 503 the consumer retries: a database |
| + that did not answer has not said the cursor is wrong. |
| +- **The stamp is the per-event nonce**, drawn at random for each event and |
| + written with it — the first of the two shapes doctrine §6.6 makes |
| + normative — so a restored log holds only the stamps of the events it |
| + has. |
| **item_id is `"<card id>.<card nonce>"`** — both parts canonical positive |
| decimals, so one card has exactly one id on the wire (`"042.…"`, `"+42.…"` |
| @@ -425,7 +454,8 @@ with `created_at`; on a clock that is frozen, or set back to where it |
| stood at the backup, a recreated card gets that too. A random nonce it |
| gets again only with negligible probability (2^-63 per draw): the old |
| item id is `NOT_VISIBLE` in S2 and refused in S3, and the event at the old |
| -cursor carries another nonce (or is gone), so S1 is a 503. |
| +cursor carries another nonce (or is gone), so S1 answers the reset |
| +(revision 11; a 503 under revision 10). |
| **Revisions are random, and their order is the log's (amended 2026-11-01, |
| this session, as Docs did).** The nonces leave one case: a card that |
| @@ -437,8 +467,14 @@ clock does too: frozen, or behind by less than the backup's age, and |
| `max(previous + 1, now)` is a counter again; and a backup from before a |
| clock scheme still holds the counter's small values. So **every revision |
| Fichas issues — creation and every change — is a fresh random positive |
| -int63** from crypto/rand (store.go `nextRevision`), redrawn in the |
| -vanishing case that it equals the card's current one (and when it is 0). |
| +int63** from crypto/rand (store.go `nextRevision`), redrawn when it is 0 |
| +and, for a change to an existing card, while it equals **any revision the |
| +card's log holds** — the current one or any before it (store.go |
| +`freshRevision`, doctrine §6.6's L4, revision 11; revision 10's Fichas |
| +checked only the current one). The check reads the card's own card-kind |
| +events inside the write's transaction; a failed read fails the write, and |
| +a source that yields nothing fresh in eight draws fails it loudly rather |
| +than spinning. A new card has no log to collide with. |
| A reissue has negligible probability — 2^-63 per draw — so memoria's held |
| revision after a restore is `UNKNOWN` (the restored log never issued it) |
| and S3 refuses it: not `VISIBLE` for different text, whatever the clock |
| @@ -476,11 +512,13 @@ equality. |
| 0005 only fills nonces that were 0, and its triggers refuse any later |
| change. |
| -**The reset is kept.** A restore still rewrites the feed, so S1 still |
| -answers the consumer's cursor with a 503 (the cursor's nonce). On that |
| -503: **reset the consumer** — discard every item it holds from this |
| -instance and its cursor, and re-read from `""` — so held copies that S2 |
| -now answers `UNKNOWN` are replaced rather than withheld for ever. |
| +**The reset is the contract's now (revision 11).** A restore still |
| +rewrites the feed, so S1 answers the consumer's old cursor with the reset: |
| +`409 {"code":"CURSOR_RESET"}`. What the consumer then does — hide every |
| +item it holds from this instance, re-read from `""`, retire what the |
| +re-read does not list, at most one reset per re-read — is doctrine §6.6's |
| +consumer half, binding on memoria, and replaces the manual reset revision |
| +10's 503 needed. |
| ### 6.3 S2 — admission, keyed on the address |
| @@ -544,6 +582,16 @@ FICHAS_SUITE_CONSUMERS=[{"consumer_id":"memoria","tokens":[{"epoch":1,"sha256":" |
| Unset or empty: no consumers, and **the routes do not exist** — `/suite/` |
| falls through to the app like any unknown path. Malformed: boot is refused. |
| +**Every suite response is `Cache-Control: no-store`, `Vary: Authorization`** |
| +(doctrine §6.5, revision 11) — set by `server.Handler` on each 200, each |
| +refusal, the reset, the 401 and the mux's own 404 and 405. What sits in |
| +front of `Handler` in production is rastrillo's panic recovery and its |
| +`securityHeaders` (CSP, nosniff, X-Frame-Options, Referrer-Policy, set |
| +before the handler runs; nothing about caching), then `App`'s outer |
| +`ServeMux`; no Fichas middleware wraps `/suite/`. The harness covers |
| +`Handler` only, so `fichastest.TestEverySuiteResponseIsNoStore` checks the |
| +two headers through `rastrillo.Handler` around `App` as `main` builds it. |
| + |
| `server.Handler` is mounted on the outer `ServeMux` at `/suite/`: outside |
| the session group, and outside the chi router whose app-wide |
| `csrf.Protect(cfg.Origin)` would refuse memoria's `POST /suite/s2`, which |
| @@ -554,27 +602,36 @@ every other route keeps the check. |
| ### 6.6 Gates |
| -- **Conformance.** `conformance.CheckAs(h, suite.SubjectAddress)` — the |
| - harness's entry point for an address-keyed app — runs in `make ci` |
| - 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` (the deleted case deleted). Random revisions cannot be edited |
| - into the fixture's small numbers, so each card's two events and its row |
| - are then set directly: its current revision R, and a history event at |
| - R − 1, so "one behind" is in its log (`STALE`) and "one ahead" is not |
| - (`UNKNOWN`). |
| - `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 |
| - `UNKNOWN`, follows S1 to its tip, and asks S3 one revision either side. |
| - The adapter renames ids; it decides nothing. |
| +- **Conformance.** `conformance.CheckProducer(p, suite.SubjectAddress)` — |
| + revision 11's entry point for an app on `suite/server`, which mounts the |
| + producer through `server.Handler` behind a token it mints and requires |
| + the 401 without it — runs in `make ci` 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` (the deleted case deleted). |
| + Random revisions cannot be edited into the fixture's numbers, so each |
| + card's two events and its row are then set directly: the first event at |
| + the case's `prior_revision`, the last and the row at its `revision` — the |
| + fixture's names, never computed — so the prior revision is in its log |
| + (`STALE`) and the case's `unknown_revision` is not (`UNKNOWN`). |
| + `CheckProducer` 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 |
| + `UNKNOWN`; asks S2 about an id Fichas does not know (`NOT_VISIBLE`); |
| + follows S1 to its tip and asks it from a cursor no log issued (the |
| + reset); refuses S3 at the other two revisions, with no, a malformed or a |
| + zero revision, and on POST; and holds every response to no-store and |
| + `Vary: Authorization`. The adapter renames ids; it decides nothing. No |
| + test calls the deprecated `server.Routes`. |
| The test asserts the failures are **exactly** the twelve listed in §6.7 |
| - — no more, no fewer — so a fixture change on the suite branch fails |
| + — no more, no fewer — in the harness's own words at `91affa1`, and pins |
| + the fixture's nine case ids, so a fixture change on the suite side fails |
| loudly here rather than being absorbed. |
| - **Fichas-native tests** (`suite_test.go`, `fichastest/suite_test.go`): |
| S1 paging, tip, `gone` on delete, the revision bump on update and on an |
| - entry, malformed and future cursors; every S2 branch above; S3 |
| + entry, malformed, future and restored cursors reset (and a failed cursor |
| + read a 503, not a reset); a new revision fresh against the card's whole |
| + log; every S2 branch above; S3 |
| current-only and the text shape; the CSRF exemption is exactly |
| `/suite/`; no consumers, no routes; a configured consumer and no token is |
| a 401; a malformed `FICHAS_SUITE_CONSUMERS` refuses boot. Every guard |
| @@ -585,8 +642,8 @@ every other route keeps the check. |
| Evidence for the suite, where its AGENTS.md says fixtures are corrected by |
| the second implementation. Not changed there from here. |
| -The fixture (`fixtures/custody.json` at `c38e3ad` (suite main; the reviewed branch tip 983114a plus polish)) describes a world with |
| -a sharing ladder. Fichas has none: |
| +The fixture (`fixtures/custody.json` at `91affa1`, revision 11: nine |
| +cases) describes a world with a sharing ladder. Fichas has none: |
| | Case | Fixture state | Fichas | Result | |
| |---|---|---|---| |
| @@ -594,22 +651,32 @@ a sharing ladder. Fichas has none: |
| | `doc-deleted` | deleted | a gone card | passes | |
| | `doc-private` | private, the asker owns it | no private state; every member sees it | passes, **by coincidence**: VISIBLE because every member sees every card, not because of ownership | |
| | `doc-granted` | granted to the asker | no grants | passes, **by coincidence**, as above | |
| -| `doc-guest` | granted to a guest only | no guests, no grants | **fails** S2 for the asker at the current revision (VISIBLE), one behind (STALE) and one ahead (UNKNOWN); the fixture wants NOT_VISIBLE at all three | |
| +| `doc-guest` | granted to a guest only | no guests, no grants | **fails** S2 for the asker at the current revision (VISIBLE), at the case's prior revision (STALE) and at its never-issued revision (UNKNOWN); the fixture wants NOT_VISIBLE at all three | |
| | `doc-link` | private to someone else, link-shared | no private state, no links | **fails**, as above | |
| | `doc-was-team` | moved from team to private | no private state | **fails**, as above | |
| | `doc-link-added-late` | private, link added later | no private state, no links | **fails**, as above | |
| +Revision 11 proposed a tenth case, `doc-owner-left` (private, owned by a |
| +member who has lost team standing, `NOT_VISIBLE` to everybody); it was |
| +withdrawn at `91affa1` pending Paul's ruling (doctrine §14). Were it |
| +restored, Fichas could not express it either — a card's owner is |
| +provenance, and every admitted person reads every card — and the test's |
| +pinned case list would fail first. |
| + |
| One more gap, not a failure because the test's adapter bridges it (a |
| second, the fixture's suite-shape-only askers, was closed upstream at |
| -`c38e3ad` (suite main; the reviewed branch tip 983114a plus polish) by `CheckAs`): |
| +`c38e3ad` by `CheckAs`, which `CheckProducer` runs): |
| - **Item ids are names, not an app's ids.** `doc-team` is not a card id; |
| an app whose ids it allocates itself cannot seed them as given. |
| -S3 (current and superseded revisions) and S1 (every live item at its |
| -current revision, the deleted one gone, paged to the tip) pass in full, as |
| -do every stranger question and every `person_ref` question. The twelve failures — four cases, three revisions each |
| -— are not bugs to fix in Fichas: |
| +S3 (current, prior and never-issued revisions, and the malformed-revision |
| +and POST refusals), S1 (every live item at its current revision, the |
| +deleted one gone, paged to the tip; the never-issued cursor reset), the |
| +unknown-id questions, the 401 and the no-store headers pass in full, as do |
| +every stranger question and every `person_ref` question. The twelve |
| +failures — four cases, three revisions each — are not bugs to fix in |
| +Fichas: |
| bending the producer to refuse cards that every member can open in the app |
| would make memoria hide what Fichas shows. |
| @@ -747,14 +814,14 @@ sealed or sealed+print only. |
| for consistent whole-database restores and forward-only migrations |
| (§6.2): a card recreated after a restore passes as one memoria holds |
| only with negligible probability (the item id's random nonce); a feed |
| - position rewritten by a restore is a 503, not a silent continuation (the |
| - cursor's nonce); and a card edited after the restore reissues a |
| - revision memoria holds only with probability 2^-63 per draw (random |
| - revisions, ordered by the log). The reset is |
| - manual today: on a Fichas S1 503 after a restore, discard everything |
| - memoria holds from this instance plus its cursor, and re-read from `""`. |
| - Open for Paul: whether memoria should do that by itself on a persistent |
| - S1 503. |
| + position rewritten by a restore is reset, not a silent continuation (the |
| + cursor's nonce); and a card edited after the restore cannot reissue a |
| + revision its restored log holds, and reissues one memoria holds only |
| + with probability 2^-63 per draw (random revisions, ordered by the log). |
| + *Amended 2026-11-02:* the reset is no longer manual. Revision 11 answered |
| + the question this item left open for Paul: S1 answers the cursor |
| + `409 {"code":"CURSOR_RESET"}` and the consumer starts over by itself |
| + (doctrine §6.6). |
| - **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 |
| @@ -788,6 +855,9 @@ In order, and small: |
| from the events table, S2 as admission, S3 as the card's text, mounted |
| only when `FICHAS_SUITE_CONSUMERS` is set. Conformance runs in CI with |
| the inexpressible cases asserted (§6.7). Not deployed, not merged. |
| + **Moved to revision 11 at `91affa1` on 2026-11-02** (branch |
| + `feat/suite-r11`, from `main`): the cursor reset, the log-wide revision |
| + redraw, `CheckProducer` (§6 intro). |
| 5. The derived summary, with citations (§7). |
| References and reach (§9) wait on §10's ruling. **Reshaping by sentence is |
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..6e0d7d9 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,74 @@ 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()) |
| + } |
| +} |
| + |
| +// The same for the page read that follows a recognised cursor: a failure |
| +// there is a 503, never the reset. Only the second events query fails, so |
| +// the cursor lookup succeeds and the page read is the one that breaks |
| +// (Fable's review of d0c7761, L1: failing every events query tripped the |
| +// lookup first and left this path untested). |
| +// |
| +// MUTATION-TESTED 2026-11-02, reverted: the page read's error mapped to |
| +// server.ErrCursorReset → "a failed page read" and "through the server". |
| +func TestSuiteFeedPageReadFailureIsNotAReset(t *testing.T) { |
| + g, a, p := suiteWorld(t) |
| + mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + _, tip := readFeed(t, p, "", 10) |
| + mustCard(t, g, a, map[string]string{FieldName: "Sliabh Teoranta"}) |
| + failing, seen := false, 0 |
| + if err := g.Callback().Query().Before("gorm:query").Register("test:fail_page", func(tx *gorm.DB) { |
| + if failing && tx.Statement.Table == "events" { |
| + seen++ |
| + if seen == 2 { |
| + 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 page read: %+v, %v; want an error that is not the reset", f, err) |
| + } |
| + if seen < 2 { |
| + t.Fatalf("only %d events queries ran, so the page read was never reached", seen) |
| + } |
| + seen = 0 |
| + 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 +553,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 +710,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 +754,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 +793,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) |
| + } |
| + } |
| +} |