Restore-proof without the clock: random revisions ordered by the log, random nonces
Replaces e9a665b (clock revisions), which Astra showed still reissues on Docs: a frozen clock or one behind by less than the backup's age makes max(prev + 1, now) a counter again, and a backup from before a clock scheme still holds the counter's small values. - Every card revision Fichas issues, at creation and on every change, is a fresh random positive int63 from crypto/rand (store.go nextRevision), redrawn if it equals the current one. Never reissued, so after a restore memoria's held revision is UNKNOWN and S3 refuses it, whatever the clock did. Existing cards keep their values until their next change. memoria compares revisions only for equality (memoria models.go SiblingRevision), recorded in spec §6.2. - S2: asked == current is VISIBLE; asked in this card's own event log is STALE; anything else UNKNOWN, whatever its size. Person first. - Item id "<card id>.<card nonce>", cursor "<event id>.<event nonce>": random write-once nonces (cards.nonce, events.nonce; migration 0004 generated, 0005 by hand: a random backfill for existing rows, which changes existing item ids once before any consumer connects, and triggers refusing a zero nonce on insert and any change after). - Contract release still compares the revision for equality; Docs decodes it as an int64, so values above 2^53 are exact. Tests: restore sequences on a frozen clock (backup, edit, restore, edit; from a pre-change counted backup; a card recreated with the same id, revision, event position and created_at); STALE by the log, with a revision below current that the log never issued; the nonce schema rules; the backfill; conformance seeds R and a history event at R - 1. 22 mutations: 20 red; the zero and equal-to-current redraws are equivalent (2^-63 draws). Spec §6.2, §6.3, §6.6, §10.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+747
−167
docs/superpowers/specs/2026-09-19-fichas-design.md+98 −65internal/fichas/migrations/0004_alter_cards.sql+4 −0internal/fichas/migrations/0005_suite_nonces.sql+48 −0internal/fichas/migrations/schema.sql+2 −2internal/fichas/models.go+24 −4internal/fichas/models_test.go+1 −0internal/fichas/store.go+45 −2internal/fichas/store_test.go+29 −12internal/fichas/suite.go+66 −27internal/fichas/suite_conformance_test.go+26 −24internal/fichas/suite_revision_test.go+335 −0internal/fichas/suite_test.go+55 −27internal/fichastest/suite_test.go+14 −4
CI passed — run details
diff --git a/docs/superpowers/specs/2026-09-19-fichas-design.md b/docs/superpowers/specs/2026-09-19-fichas-design.md| index f7ef8e8..b0bb341 100644 |
| --- a/docs/superpowers/specs/2026-09-19-fichas-design.md |
| +++ b/docs/superpowers/specs/2026-09-19-fichas-design.md |
| @@ -388,54 +388,82 @@ else: |
| a value, an owner or an actor. |
| - **History is replayed, not collapsed.** A card edited three times since |
| the cursor yields three rows; the consumer keeps the last. |
| -- **The cursor** is `"<event id>.<that event's created_at, unix |
| - nanoseconds>"` for the last row returned. `""` and `"0"` are the |
| - beginning. At the tip the page is `rows: []` and the same cursor — |
| - except that `""` answers `"0"`, because the contract refuses an empty |
| - cursor, and the next poll gets `"0"` back. Within one database history, |
| - `events.id` is `AUTOINCREMENT` and SQLite has one writer, so ids are |
| - committed in order: a cursor can never step past a row that commits |
| - later with a lower id. |
| -- **Every request checks the cursor's stamp.** The event at the cursor's |
| - id must still exist, be a card event, and carry that `created_at`. |
| - Otherwise the feed fails, which §6.5 turns into a 503 — loud, never a |
| - page. A cursor that is not in the canonical form fails the same way. |
| - |
| -**item_id is `"<card id>.<card created_at, unix nanoseconds>"`** — e.g. |
| -`"42.1793571162737001000"` — both parts canonical positive decimals, so one |
| -card has exactly one id on the wire (`"042.…"`, `"+42.…"` and a bare |
| -`"42"` are not it). Both parts are structural and already plaintext (§4.1 |
| -case 2, §4.2), never content. `created_at` is written once, by the insert, |
| -and never updated (`bumpRevision` moves only `revision`, `updated_at` and |
| -`gone`); stored as text, it round-trips to the nanosecond the clock |
| -supplied. It tells the consumer when each card was made, which the feed's |
| -first row for it already says. |
| - |
| -**Why the stamps (Astra review, 2026-11-01).** "An id is never reused" is |
| -true only within one database history. Restore an older backup and |
| -`AUTOINCREMENT` starts again from the backup's counters: a card created |
| -afterwards can get exactly the id, revision 1 and event position of a card |
| -memoria already holds, with different text. With bare ids, S1 would then |
| -answer an unchanged empty page, S2 would answer `VISIBLE` for memoria's old |
| -copy, and S3 would serve the new card's text under the old identity. The |
| -stamps make that impossible: the new card's `created_at` differs, so the |
| -old item id is `NOT_VISIBLE` in S2 and refused in S3, and the event at the |
| -old cursor carries a different stamp (or is gone), so S1 is a 503. |
| - |
| -**What the stamps do not protect, and the reset.** A card that predates the |
| -restore point keeps its id and stamp — correctly, it is the same card. If |
| -memoria held a revision of it written *after* the restore point, and the |
| -card is edited again after the restore up to that same revision number, |
| -the same `(item id, revision)` names different text. S2 cannot tell them |
| -apart, so until memoria is reset it answers `VISIBLE` for the abandoned |
| -copy. S1 does go loud in exactly that case: memoria's cursor is at or past |
| -the event that wrote the abandoned revision, and the restore dropped it. |
| -So **a Fichas 503 on S1 after a restore means: reset the consumer** — |
| -discard every item it holds from this instance and its cursor, and |
| -re-read from `""`. Resetting the cursor alone is not enough. Closing the |
| -gap in S2 itself would need revisions that a restore cannot reproduce |
| -(e.g. event timestamps rather than a per-card counter), which the custody |
| -fixture's fixed revision numbers cannot express; §10. |
| +- **The cursor** is `"<event id>.<that event's nonce>"` for the last row |
| + returned. `""` and `"0"` are the beginning. At the tip the page is |
| + `rows: []` and the same cursor — except that `""` answers `"0"`, |
| + because the contract refuses an empty cursor, and the next poll gets |
| + `"0"` back. Within one database history, `events.id` is |
| + `AUTOINCREMENT` and SQLite has one writer, so ids are committed in |
| + order: a cursor can never step past a row that commits later with a |
| + lower id. |
| +- **Every request checks the cursor's 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. |
| + |
| +**item_id is `"<card id>.<card nonce>"`** — both parts canonical positive |
| +decimals, so one card has exactly one id on the wire (`"042.…"`, `"+42.…"` |
| +and a bare `"42"` are not it). |
| + |
| +**The nonces** (`cards.nonce`, `events.nonce`; migrations 0004 and 0005) |
| +are random positive int63s from crypto/rand, written once with the row. |
| +Plaintext under §4.1 case 1 — they exist only for the suite contract — |
| +and never content: they say nothing about the card. The schema refuses a |
| +row inserted without one and any later change to one (0005's triggers); |
| +0005 gave every row that existed before it a random value from SQLite's |
| +`random()`, which changed existing cards' item ids once, before any |
| +consumer had connected. |
| + |
| +**Why nonces, and not created_at (Astra, 2026-11-01, on Docs).** "An id is |
| +never reused" is true only within one database history. Restore an older |
| +backup and `AUTOINCREMENT` starts again from the backup's counters: a |
| +card created afterwards can get exactly the id and event position of a |
| +card memoria already holds, with different text. With bare ids, S1 would |
| +answer an unchanged empty page, S2 `VISIBLE` for memoria's old copy, and |
| +S3 the new card's text under the old identity. The first fix stamped ids |
| +with `created_at`; on a clock that is frozen, or set back to where it |
| +stood at the backup, a recreated card gets that too. A random nonce it |
| +cannot get: the old item id is `NOT_VISIBLE` in S2 and refused in S3, and |
| +the event at the old cursor carries another nonce (or is gone), so S1 is |
| +a 503. |
| + |
| +**Revisions are random, and their order is the log's (amended 2026-11-01, |
| +this session, as Docs did).** The nonces leave one case: a card that |
| +predates the restore point keeps its id and nonce — correctly, it is the |
| +same card — so a revision issued *after* the backup must never be issued |
| +again after the restore, or one `(item id, revision)` names two texts and |
| +S2 says `VISIBLE` for the abandoned one. A counter reissues exactly. A |
| +clock does too: frozen, or behind by less than the backup's age, and |
| +`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. It is never |
| +reissued, so memoria's held revision after a restore is `UNKNOWN` (the |
| +restored log never issued it) and S3 refuses it — never `VISIBLE` for |
| +different text, whatever the clock did. Cards from before keep their |
| +small counted revisions until their next change; those were issued |
| +before and are in the log, and the risk was only ever reissuing, so they |
| +need no backfill. |
| + |
| +**This rests on memoria comparing revisions only for equality**, which it |
| +does: memoria `internal/memoria/models.go`, `SiblingRevision` — "Never |
| +compared, only matched for equality … STALE and AHEAD are the sibling's |
| +verdict on its own log, not memoria's arithmetic on two numbers" — and its |
| +store treats 0 as "no revision", which a random positive value never is. |
| +So the order of a card's revisions lives in its event log alone: S2's |
| +`STALE` means "this card's log once issued that revision" (§6.3), never |
| +"that number is smaller". A random int63 is under 2^63 and may exceed |
| +2^53, so a consumer must carry it as an integer, as the contract's int64 |
| +does; it is only compared for equality. The contract-release page shows |
| +it as "Source revision", a long number, likewise compared only for |
| +equality. |
| + |
| +**The reset is kept.** A restore still rewrites the feed, so S1 still |
| +answers the consumer's cursor with a 503 (the cursor's 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. |
| ### 6.3 S2 — admission, keyed on the address |
| @@ -448,12 +476,15 @@ pair, in order: |
| |---|---| |
| | kind `person_ref` — a kind Fichas does not key on | `UNKNOWN`, every pair | |
| | `address`, not admitted (`Admit`: the `FICHAS_OWNERS` list, the one predicate sign-in and every session already run) | `NOT_VISIBLE`, every pair | |
| -| admitted; card gone, unknown, an id not in the canonical `<card id>.<stamp>` form, or a stamp that is not this card's `created_at` (a different card under a reused id) | `NOT_VISIBLE` | |
| +| admitted; card gone, unknown, an id not in the canonical `<card id>.<nonce>` form, or a nonce that is not this card's (a different card under a reused id) | `NOT_VISIBLE` | |
| | admitted; asked revision = current | `VISIBLE` | |
| -| admitted; 1 ≤ asked revision < current | `STALE` | |
| -| admitted; asked revision > current, or < 1 — zero or negative (a revision the log never issued) | `UNKNOWN` | |
| +| admitted; asked revision is not current but is in this card's own event log (it was this card's, and the card has moved on) | `STALE` | |
| +| admitted; any other revision — one this card's log never issued, whatever its size, including zero and negatives | `UNKNOWN` | |
| -Nothing is cached: admission and every card's revision are read per call. |
| +Revisions are random, so `STALE` is read off the card's event log in one |
| +query, never off the numbers (§6.2). The person is checked before any |
| +revision. Nothing is cached: admission, every card's revision and its log |
| +are read per call. |
| ### 6.4 S3 — the card as plain text |
| @@ -511,7 +542,11 @@ every other route keeps the check. |
| against `server.Routes` over the real producer and a real database, |
| through a test-only naming adapter: the fixture's item ids map to the |
| card ids seeded for them (and feed rows map back) (one Customer card per case, its name the case's |
| - `s3_body`, edited up to the case's revision; the deleted case deleted). |
| + `s3_body` (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 |
| @@ -691,18 +726,16 @@ sealed or sealed+print only. |
| (`memoria/ZDR-TREAT-AS-LOCAL.md` §6). Not a blocker at one user; a |
| blocker at the second team. |
| - **S1 after a restore from backup** (§6.2; revised after Astra's review, |
| - 2026-11-01). What is protected: a card recreated after a restore cannot |
| - pass as one memoria holds (the item id's stamp), and a feed position |
| - rewritten by a restore is a 503 rather than a silent continuation (the |
| - cursor's stamp). What is not: a card that predates the restore point and |
| - is edited back up to a revision memoria already holds names different |
| - text under the same `(item id, revision)`, and S2 says `VISIBLE` for |
| - the abandoned copy until memoria is reset. The reset is manual today: |
| - on a Fichas S1 503 after a restore, discard everything memoria holds |
| - from this instance plus its cursor, and re-read from `""`. Open for |
| - Paul: whether memoria should do that by itself on a persistent S1 503, |
| - and whether Fichas revisions should become restore-proof (event |
| - timestamps), at the cost of the fixture's fixed revision numbers. |
| + and closed 2026-11-01). Protected, with no assumption about the clock: |
| + a card recreated after a restore cannot pass as one memoria holds (the |
| + item id's nonce); a feed position rewritten by a restore is a 503, not a |
| + silent continuation (the cursor's nonce); and a card edited after the |
| + restore cannot be issued a revision memoria already holds (random |
| + 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. |
| - **A field rename and memoria's copy** (§6.4). Renaming a field moves no |
| card's revision, so memoria keeps the old label in its copy of each card |
| until that card next changes. Bumping every card of the type on a rename |
diff --git a/internal/fichas/migrations/0004_alter_cards.sql b/internal/fichas/migrations/0004_alter_cards.sql| new file mode 100644 |
| index 0000000..eb659cd |
| --- /dev/null |
| +++ b/internal/fichas/migrations/0004_alter_cards.sql |
| @@ -0,0 +1,4 @@ |
| +ALTER TABLE `cards` ADD `nonce` integer NOT NULL DEFAULT 0; |
| + |
| +ALTER TABLE `events` ADD `nonce` integer NOT NULL DEFAULT 0; |
| + |
diff --git a/internal/fichas/migrations/0005_suite_nonces.sql b/internal/fichas/migrations/0005_suite_nonces.sql| new file mode 100644 |
| index 0000000..44bfaab |
| --- /dev/null |
| +++ b/internal/fichas/migrations/0005_suite_nonces.sql |
| @@ -0,0 +1,48 @@ |
| +-- suite_nonces |
| +-- |
| +-- The suite contract's restore protection (spec §6.2). 0004 added |
| +-- cards.nonce and events.nonce at 0; this gives every existing row a |
| +-- random positive value, and makes both columns write-once and never zero. |
| +-- |
| +-- Written by hand: `rastrillo migration generate` knows nothing about |
| +-- backfills or triggers, as 0002 records. |
| +-- |
| +-- random() is SQLite's, seeded from the operating system. The mask keeps |
| +-- 62 bits and the + 1 keeps it positive, so no row is left at 0, which is |
| +-- what "not yet set" means below. Existing cards' suite item ids change |
| +-- with this, once — before any consumer has connected. |
| +UPDATE cards SET nonce = (random() & 4611686018427387903) + 1 WHERE nonce = 0; |
| +UPDATE events SET nonce = (random() & 4611686018427387903) + 1 WHERE nonce = 0; |
| + |
| +-- Never zero on insert: the code always sets one (store.go CreateCard and |
| +-- logEvent), and a row without one would carry an item id or a cursor that |
| +-- names nothing. |
| +CREATE TRIGGER cards_nonce_is_set |
| +BEFORE INSERT ON cards |
| +WHEN NEW.nonce IS NULL OR NEW.nonce <= 0 |
| +BEGIN |
| + SELECT RAISE(ABORT, 'a card needs a nonce: it is half of its suite item id'); |
| +END; |
| + |
| +CREATE TRIGGER events_nonce_is_set |
| +BEFORE INSERT ON events |
| +WHEN NEW.nonce IS NULL OR NEW.nonce <= 0 |
| +BEGIN |
| + SELECT RAISE(ABORT, 'an event needs a nonce: it is half of a suite feed cursor'); |
| +END; |
| + |
| +-- Write-once: a nonce that moved would turn a consumer's held item id or |
| +-- cursor into one that names nothing — or, worse, something else. |
| +CREATE TRIGGER cards_nonce_is_write_once |
| +BEFORE UPDATE OF nonce ON cards |
| +WHEN NEW.nonce IS NOT OLD.nonce |
| +BEGIN |
| + SELECT RAISE(ABORT, 'a card nonce is written once'); |
| +END; |
| + |
| +CREATE TRIGGER events_nonce_is_write_once |
| +BEFORE UPDATE OF nonce ON events |
| +WHEN NEW.nonce IS NOT OLD.nonce |
| +BEGIN |
| + SELECT RAISE(ABORT, 'an event nonce is written once'); |
| +END; |
diff --git a/internal/fichas/migrations/schema.sql b/internal/fichas/migrations/schema.sql| index 6578887..a33be9f 100644 |
| --- a/internal/fichas/migrations/schema.sql |
| +++ b/internal/fichas/migrations/schema.sql |
| @@ -30,13 +30,13 @@ CREATE TABLE `card_types` (`id` integer PRIMARY KEY AUTOINCREMENT,`key` text,`sc |
| CREATE TABLE `card_values` (`card_id` integer,`field_def_id` integer,`sealed_value` blob,`print` text,PRIMARY KEY (`card_id`,`field_def_id`),CONSTRAINT `fk_cards_values` FOREIGN KEY (`card_id`) REFERENCES `cards`(`id`) ON DELETE CASCADE); |
| -CREATE TABLE `cards` (`id` integer PRIMARY KEY AUTOINCREMENT,`card_type_id` integer NOT NULL,`revision` integer NOT NULL DEFAULT 1,`gone` numeric NOT NULL DEFAULT false,`offered` numeric NOT NULL DEFAULT false,`owner_id` integer,`created_at` datetime,`updated_at` datetime,CONSTRAINT `fk_cards_owner` FOREIGN KEY (`owner_id`) REFERENCES `members`(`id`) ON DELETE RESTRICT); |
| +CREATE TABLE `cards` (`id` integer PRIMARY KEY AUTOINCREMENT,`card_type_id` integer NOT NULL,`revision` integer NOT NULL DEFAULT 1,`gone` numeric NOT NULL DEFAULT false,`offered` numeric NOT NULL DEFAULT false,`owner_id` integer,`created_at` datetime,`updated_at` datetime, `nonce` integer NOT NULL DEFAULT 0,CONSTRAINT `fk_cards_owner` FOREIGN KEY (`owner_id`) REFERENCES `members`(`id`) ON DELETE RESTRICT); |
| CREATE TABLE `entries` (`id` integer PRIMARY KEY AUTOINCREMENT,`card_id` integer NOT NULL,`kind` text NOT NULL,`source` text,`actor_id` integer,`type_id` integer NOT NULL,`created_at` datetime,CONSTRAINT `fk_entries_actor` FOREIGN KEY (`actor_id`) REFERENCES `members`(`id`) ON DELETE RESTRICT,CONSTRAINT `fk_cards_entries` FOREIGN KEY (`card_id`) REFERENCES `cards`(`id`) ON DELETE CASCADE); |
| CREATE TABLE `entry_values` (`entry_id` integer,`field_def_id` integer,`sealed_value` blob,`print` text,PRIMARY KEY (`entry_id`,`field_def_id`),CONSTRAINT `fk_entries_values` FOREIGN KEY (`entry_id`) REFERENCES `entries`(`id`) ON DELETE CASCADE); |
| -CREATE TABLE `events` (`id` integer PRIMARY KEY AUTOINCREMENT,`kind` text NOT NULL,`object_kind` text NOT NULL,`object_id` integer,`actor_id` integer,`actor_reason` text,`child_id` integer,`revision` integer,`changed_fields` text,`payload_sealed` blob,`payload_erased_at` datetime,`trigger_id` integer,`created_at` datetime); |
| +CREATE TABLE `events` (`id` integer PRIMARY KEY AUTOINCREMENT,`kind` text NOT NULL,`object_kind` text NOT NULL,`object_id` integer,`actor_id` integer,`actor_reason` text,`child_id` integer,`revision` integer,`changed_fields` text,`payload_sealed` blob,`payload_erased_at` datetime,`trigger_id` integer,`created_at` datetime, `nonce` integer NOT NULL DEFAULT 0); |
| CREATE TABLE `field_defs` (`id` integer PRIMARY KEY AUTOINCREMENT,`card_type_id` integer NOT NULL,`key` text,`sealed_label` blob,`sealed_options` blob,`kind` text,`tier` text,`ordinal` integer,`created_at` datetime,`updated_at` datetime,CONSTRAINT `fk_card_types_fields` FOREIGN KEY (`card_type_id`) REFERENCES `card_types`(`id`) ON DELETE RESTRICT); |
diff --git a/internal/fichas/models.go b/internal/fichas/models.go| index b7b4925..f5788c1 100644 |
| --- a/internal/fichas/models.go |
| +++ b/internal/fichas/models.go |
| @@ -168,7 +168,19 @@ type Card struct { |
| // feed can be served without unsealing and passes the plaintext-grep |
| // gate unaided. memoria §3.2 already concedes update timestamps as a |
| // known leak; this is the same trade, made deliberately. |
| + // |
| + // A revision is a random positive int63 (store.go nextRevision), not a |
| + // counter, so a database restored from an older backup can never hand |
| + // one out again (spec §6.2). Only equality means anything: the order |
| + // of a card's revisions is its event log's. Cards from before keep |
| + // their small counted values until their next change. |
| Revision int64 `gorm:"not null;default:1"` |
| + // Nonce is the card's half of its suite item id, "<id>.<nonce>": a |
| + // random positive int63 written once at creation. After a restore a |
| + // new card can be given an old card's id; it cannot be given its |
| + // nonce. Plaintext under §4.1 case 1. Write-once and never zero, |
| + // enforced by triggers (migrations/0005). |
| + Nonce int64 `gorm:"not null;default:0"` |
| // not null with a default, because a nullable bool does not behave: |
| // with a NULL row, `gone = 0`, `gone != 1` and `NOT gone` all miss |
| // it — and suite/s1.go refuses a feed row whose gone is absent. |
| @@ -324,11 +336,19 @@ type Event struct { |
| // CARD revision, which left the card's own revision chain with gaps |
| // that a contiguity check reads as broken. |
| ChildID int64 |
| - // Revision is the object's revision AFTER this event. Restore needs |
| - // it to check the diff chain is contiguous, and it is what lets the |
| - // log answer "at what revision" for S1 rather than reading the |
| - // current card row. |
| + // Revision is the object's revision AFTER this event. Card revisions |
| + // are random (store.go nextRevision), so the chain is ordered by event |
| + // id, not by revision value; it is unbroken when every card revision |
| + // has its event, which every write path guarantees by logging in the |
| + // same transaction. It is what lets the log answer "at what revision" |
| + // for S1, and "was this ever this card's revision" for S2's STALE. |
| Revision int64 |
| + // Nonce is a random positive int63 written once with the event: the |
| + // suite feed cursor is "<event id>.<nonce>", so a cursor names one |
| + // event in one history even after a restore reissues the id. |
| + // Plaintext under §4.1 case 1; write-once and never zero, enforced by |
| + // triggers (migrations/0005). |
| + Nonce int64 `gorm:"not null;default:0"` |
| // ChangedFields lists the FieldDef ids this event touched, as a JSON |
| // array of integers. **Plaintext, and it must be**: §5 keeps "which |
| // fields changed" permanently, and the only other place to put it is |
diff --git a/internal/fichas/models_test.go b/internal/fichas/models_test.go| index ed66d5b..59ca2b6 100644 |
| --- a/internal/fichas/models_test.go |
| +++ b/internal/fichas/models_test.go |
| @@ -64,6 +64,7 @@ var nonStringPlaintext = map[string]string{ |
| "FieldDef.CreatedAt": "row timestamp", "FieldDef.UpdatedAt": "row timestamp", |
| "Card.ID": "row id", "Card.CardTypeID": "foreign key", "Card.OwnerID": "foreign key to members", |
| "Card.Revision": "S1 feed row", "Card.Gone": "S1 feed row", "Card.Offered": "the reach mark", |
| + "Card.Nonce": "half of the suite item id (§6.2)", "Event.Nonce": "half of the suite feed cursor (§6.2)", |
| "Card.CreatedAt": "row timestamp", "Card.UpdatedAt": "S1 feed row (touched_at)", |
| "CardValue.CardID": "foreign key", "CardValue.FieldDefID": "foreign key", |
| "Entry.ID": "row id", "Entry.CardID": "foreign key", "Entry.TypeID": "foreign key", |
diff --git a/internal/fichas/store.go b/internal/fichas/store.go| index 481c657..85e0a79 100644 |
| --- a/internal/fichas/store.go |
| +++ b/internal/fichas/store.go |
| @@ -2,6 +2,8 @@ package fichas |
| import ( |
| "context" |
| + "crypto/rand" |
| + "encoding/binary" |
| "encoding/json" |
| "fmt" |
| "sort" |
| @@ -152,6 +154,7 @@ func logEvent(tx *gorm.DB, s *seal.Sealer, kind, objectKind string, objectID, ch |
| ChangedFields: string(ids), |
| PayloadSealed: payload, |
| TriggerID: actor.trigger, |
| + Nonce: randomPositive(), |
| } |
| if err := tx.Create(&e).Error; err != nil { |
| return fmt.Errorf("fichas: writing the event: %w", err) |
| @@ -252,6 +255,46 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel |
| return changed, detail, nil |
| } |
| +// randomPositive is a random positive int63 from crypto/rand: a card's |
| +// revisions and the nonces in its item id and the feed's cursor (spec |
| +// §6.2). Zero, which the triggers in migrations/0005 refuse and which |
| +// memoria reads as "no revision", is redrawn. |
| +func randomPositive() int64 { |
| + var b [8]byte |
| + for { |
| + rand.Read(b[:]) // never fails: crypto/rand aborts the process rather than return short |
| + if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 { |
| + return n |
| + } |
| + } |
| +} |
| + |
| +// newRevision issues a card revision. A variable so the suite tests can |
| +// pin it to a readable count; nothing else sets it. |
| +var newRevision = randomRevision |
| + |
| +// randomRevision is a fresh random positive int63 that differs from the |
| +// card's current revision. |
| +// |
| +// Why not a counter, or the clock (spec §6.2): memoria holds (item, |
| +// revision) and asks S2 whether that revision is current. Restore an |
| +// older backup and a counter hands the same numbers out again for |
| +// different text — S2 then says VISIBLE for the abandoned copy. A clock |
| +// does the same if it is frozen, or behind by less than the backup's age. |
| +// A random revision is never reissued; memoria compares revisions only |
| +// for equality, and the ORDER of a card's revisions is its event log's, |
| +// which S2 reads for STALE. |
| +func randomRevision(current int64) int64 { |
| + for { |
| + if r := randomPositive(); r != current { |
| + return r |
| + } |
| + } |
| +} |
| + |
| +// nextRevision is the revision a change to a card at current moves it to. |
| +func nextRevision(current int64) int64 { return newRevision(current) } |
| + |
| // bumpRevision moves a card's revision, guarded on the revision it read. |
| // |
| // The guard makes the invariant LOCAL. Concurrent updates are safe today |
| @@ -260,7 +303,7 @@ func writeValues(tx *gorm.DB, s *seal.Sealer, cardID int64, defs map[string]Fiel |
| // the log would stop being a truthful account of what happened. Costs one |
| // clause. |
| func bumpRevision(tx *gorm.DB, card *Card, extra map[string]any) error { |
| - next := card.Revision + 1 |
| + next := nextRevision(card.Revision) |
| set := map[string]any{"revision": next, "updated_at": time.Now()} |
| for k, v := range extra { |
| set[k] = v |
| @@ -291,7 +334,7 @@ func CreateCard(ctx context.Context, db *gorm.DB, s *seal.Sealer, typeKey string |
| return err |
| } |
| - card = Card{CardTypeID: ct.ID, OwnerID: actor.memberID, Revision: 1} |
| + card = Card{CardTypeID: ct.ID, OwnerID: actor.memberID, Revision: nextRevision(0), Nonce: randomPositive()} |
| if err := tx.Create(&card).Error; err != nil { |
| return fmt.Errorf("fichas: creating the card: %w", err) |
| } |
diff --git a/internal/fichas/store_test.go b/internal/fichas/store_test.go| index db6591d..81f7908 100644 |
| --- a/internal/fichas/store_test.go |
| +++ b/internal/fichas/store_test.go |
| @@ -51,7 +51,9 @@ func TestCreateCardSealsAndLogs(t *testing.T) { |
| if err != nil { |
| t.Fatalf("CreateCard: %v", err) |
| } |
| - if card.ID == 0 || card.Revision != 1 || card.OwnerID == nil || *card.OwnerID != 7 { |
| + // A new card's revision is random and positive, and so is its nonce |
| + // (store.go nextRevision, randomPositive). |
| + if card.ID == 0 || card.Revision < 1 || card.Nonce < 1 || card.OwnerID == nil || *card.OwnerID != 7 { |
| t.Fatalf("card is %+v", card) |
| } |
| @@ -74,7 +76,7 @@ func TestCreateCardSealsAndLogs(t *testing.T) { |
| } |
| ev := events(t, g, ObjectCard, card.ID) |
| - if len(ev) != 1 || ev[0].Kind != EventCreated || ev[0].ActorID == nil || *ev[0].ActorID != 7 || ev[0].Revision != 1 { |
| + if len(ev) != 1 || ev[0].Kind != EventCreated || ev[0].ActorID == nil || *ev[0].ActorID != 7 || ev[0].Revision != card.Revision { |
| t.Fatalf("events are %+v", ev) |
| } |
| var changed []int64 |
| @@ -136,8 +138,11 @@ func TestUpdateCardLogsBeforeAndAfter(t *testing.T) { |
| t.Fatalf("%d events after one update, want 2", len(ev)) |
| } |
| last := ev[1] |
| - if last.Kind != EventUpdated || last.ActorID == nil || *last.ActorID != 2 || last.Revision != 2 { |
| - t.Fatalf("update event is %+v", last) |
| + var reread Card |
| + g.First(&reread, card.ID) |
| + if last.Kind != EventUpdated || last.ActorID == nil || *last.ActorID != 2 || |
| + last.Revision == card.Revision || last.Revision < 1 || last.Revision != reread.Revision { |
| + t.Fatalf("update event is %+v (card created at %d, now at %d)", last, card.Revision, reread.Revision) |
| } |
| raw, err := s.Open(seal.PurposeEventPayload, last.PayloadSealed) |
| if err != nil { |
| @@ -166,8 +171,8 @@ func TestUpdateCardWithNoChangeWritesNoEvent(t *testing.T) { |
| } |
| var reread Card |
| g.First(&reread, card.ID) |
| - if reread.Revision != 1 { |
| - t.Fatalf("a no-op update bumped the revision to %d", reread.Revision) |
| + if reread.Revision != card.Revision { |
| + t.Fatalf("a no-op update moved the revision from %d to %d", card.Revision, reread.Revision) |
| } |
| } |
| @@ -218,8 +223,8 @@ func TestAddEntryLogsAndMovesTheCardRevision(t *testing.T) { |
| var reread Card |
| g.First(&reread, card.ID) |
| - if reread.Revision != 2 { |
| - t.Fatalf("card revision is %d after an entry landed, want 2", reread.Revision) |
| + if reread.Revision == card.Revision { |
| + t.Fatalf("card revision is still %d after an entry landed", reread.Revision) |
| } |
| if n := len(events(t, g, ObjectEntry, entry.ID)); n != 1 { |
| t.Fatalf("%d events for the entry, want 1", n) |
| @@ -288,8 +293,10 @@ func TestAnActorIsAPersonOrADeclaredAppAction(t *testing.T) { |
| // Finding 9: an entry landing used to consume a CARD revision while being |
| // logged under object_kind=entry, which left the card's own chain with |
| -// gaps that a contiguity check reads as broken. |
| -func TestTheCardsRevisionChainIsContiguous(t *testing.T) { |
| +// gaps. Revisions are random now (nextRevision), so the chain is ordered by |
| +// event id and does not count 1, 2, 3: it is unbroken when every card event |
| +// carries a revision of its own, none repeated, and the last is the card's. |
| +func TestTheCardsRevisionChainIsUnbroken(t *testing.T) { |
| g, s := seeded(t) |
| card, _ := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "Cnoc Teoranta"}) |
| if _, err := AddEntry(ctx(), g, s, card.ID, Person(1), TypeCallLog, "manual", map[string]string{FieldBody: "called"}); err != nil { |
| @@ -300,10 +307,20 @@ func TestTheCardsRevisionChainIsContiguous(t *testing.T) { |
| } |
| ev := events(t, g, ObjectCard, card.ID) |
| + if len(ev) != 3 { |
| + t.Fatalf("%d card events, want 3 (created, entry, update)", len(ev)) |
| + } |
| + seen := map[int64]bool{} |
| for i, e := range ev { |
| - if e.Revision != int64(i+1) { |
| - t.Fatalf("card event %d is at revision %d; the chain has a gap", i, e.Revision) |
| + if e.Revision < 1 || seen[e.Revision] { |
| + t.Fatalf("card event %d is at revision %d: zero, negative or repeated", i, e.Revision) |
| } |
| + seen[e.Revision] = true |
| + } |
| + var reread Card |
| + g.First(&reread, card.ID) |
| + if ev[len(ev)-1].Revision != reread.Revision { |
| + t.Fatalf("the chain ends at %d and the card is at %d", ev[len(ev)-1].Revision, reread.Revision) |
| } |
| if ev[1].Kind != EventEntryAdded || ev[1].ChildID == 0 { |
| t.Fatalf("the entry landing is not named on the card's chain: %+v", ev[1]) |
diff --git a/internal/fichas/suite.go b/internal/fichas/suite.go| index 4f5a625..ff7c476 100644 |
| --- a/internal/fichas/suite.go |
| +++ b/internal/fichas/suite.go |
| @@ -37,11 +37,11 @@ var _ server.Producer = (*suiteProducer)(nil) |
| // Feed pages the events table (spec §6.2): card events after the cursor, |
| // in id order, one row each. |
| // |
| -// The cursor is "<event id>.<that event's created_at, unix nanoseconds>", |
| -// and the stamp is checked on every request. After a restore from an older |
| +// The cursor is "<event id>.<that event's nonce>", and the nonce is |
| +// checked on every request. After a restore from an older |
| // backup, AUTOINCREMENT hands the same event ids out again to different |
| // events; a bare id would then continue silently from a position that now |
| -// means something else. A stamp that no longer matches is an error — a 503, |
| +// means something else. A nonce that no longer matches is an error — a 503, |
| // loud — never a page. |
| func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| after, stamp, err := parseCursor(cursor) |
| @@ -51,11 +51,11 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui |
| g := p.g.WithContext(ctx) |
| if after > 0 { |
| var at []Event |
| - if err := g.Model(&Event{}).Select("id", "created_at"). |
| + if err := g.Model(&Event{}).Select("id", "nonce"). |
| Where("id = ? AND object_kind = ?", after, ObjectCard).Find(&at).Error; err != nil { |
| return suite.Feed{}, fmt.Errorf("fichas: reading the feed cursor's event: %w", err) |
| } |
| - if len(at) != 1 || at[0].CreatedAt.UnixNano() != stamp { |
| + 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) |
| } |
| } |
| @@ -63,7 +63,7 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui |
| // Only plaintext columns: nothing sealed is read, so nothing sealed can |
| // reach a row. |
| if err := g.Model(&Event{}). |
| - Select("id", "kind", "object_id", "revision", "created_at"). |
| + Select("id", "kind", "object_id", "revision", "created_at", "nonce"). |
| Where("id > ? AND object_kind = ?", after, ObjectCard). |
| Order("id").Limit(limit).Find(&evs).Error; err != nil { |
| return suite.Feed{}, fmt.Errorf("fichas: reading the feed: %w", err) |
| @@ -76,53 +76,54 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui |
| } |
| return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil |
| } |
| - stamps, err := p.cardStamps(ctx, evs) |
| + nonces, err := p.cardNonces(ctx, evs) |
| if err != nil { |
| return suite.Feed{}, err |
| } |
| rows := make([]suite.FeedRow, len(evs)) |
| for i, e := range evs { |
| - created, ok := stamps[e.ObjectID] |
| + nonce, ok := nonces[e.ObjectID] |
| if !ok { |
| // Card rows are never deleted, so an event for a card with no |
| // row is a log this code did not write. Loud, not skipped. |
| return suite.Feed{}, fmt.Errorf("fichas: event %d names card %d, which has no row", e.ID, e.ObjectID) |
| } |
| rows[i] = suite.FeedRow{ |
| - ItemID: itemID(e.ObjectID, created), |
| + ItemID: itemID(e.ObjectID, nonce), |
| Revision: e.Revision, |
| Gone: e.Kind == EventDeleted, |
| TouchedAt: e.CreatedAt, |
| } |
| } |
| last := evs[len(evs)-1] |
| - return suite.Feed{Cursor: stampedID(last.ID, last.CreatedAt.UnixNano()), Rows: rows}, nil |
| + return suite.Feed{Cursor: stampedID(last.ID, last.Nonce), Rows: rows}, nil |
| } |
| -// cardStamps is each card's creation stamp, for the cards a page names. |
| -func (p *suiteProducer) cardStamps(ctx context.Context, evs []Event) (map[int64]int64, error) { |
| +// cardNonces is each card's nonce, for the cards a page names. |
| +func (p *suiteProducer) cardNonces(ctx context.Context, evs []Event) (map[int64]int64, error) { |
| ids := make([]int64, 0, len(evs)) |
| for _, e := range evs { |
| ids = append(ids, e.ObjectID) |
| } |
| var cards []Card |
| - if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "created_at"). |
| + if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "nonce"). |
| Where("id IN ?", ids).Find(&cards).Error; err != nil { |
| - return nil, fmt.Errorf("fichas: reading card stamps: %w", err) |
| + return nil, fmt.Errorf("fichas: reading card nonces: %w", err) |
| } |
| out := make(map[int64]int64, len(cards)) |
| for _, c := range cards { |
| - out[c.ID] = c.CreatedAt.UnixNano() |
| + out[c.ID] = c.Nonce |
| } |
| return out, nil |
| } |
| -// itemID is a card's id on the wire: "<card id>.<card created_at, unix |
| -// nanoseconds>". The id alone is not enough: after a restore from an older |
| -// backup, a card created afterwards can be given the id, revision and event |
| -// position of one the consumer already holds. created_at is written once, |
| -// at insert, and never updated, so the pair names one card in one history. |
| -func itemID(cardID, created int64) string { return stampedID(cardID, created) } |
| +// itemID is a card's id on the wire: "<card id>.<card nonce>". The id alone |
| +// is not enough: after a restore from an older backup, a card created |
| +// afterwards can be given the id and event position of one the consumer |
| +// already holds. The nonce is random and written once (migrations/0005), |
| +// so the pair names one card in one history. Not created_at: with a clock |
| +// frozen or set back, a recreated card can get that too. |
| +func itemID(cardID, nonce int64) string { return stampedID(cardID, nonce) } |
| func stampedID(id, stamp int64) string { |
| return strconv.FormatInt(id, 10) + "." + strconv.FormatInt(stamp, 10) |
| @@ -190,7 +191,7 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s |
| live := map[int64]Card{} // live cards only |
| if len(ids) > 0 { |
| var cards []Card |
| - if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision", "created_at"). |
| + if err := p.g.WithContext(ctx).Model(&Card{}).Select("id", "revision", "nonce"). |
| Where("id IN ? AND gone = ?", ids, false).Find(&cards).Error; err != nil { |
| return nil, fmt.Errorf("fichas: reading revisions: %w", err) |
| } |
| @@ -199,26 +200,64 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s |
| } |
| } |
| + past, err := p.pastRevisions(ctx, pairs, live) |
| + if err != nil { |
| + return nil, err |
| + } |
| + |
| for i, pr := range pairs { |
| id, stamp, ok := parseStamped(pr.ItemID) |
| c, found := live[id] |
| switch { |
| - case !ok || !found || c.CreatedAt.UnixNano() != stamp: |
| + case !ok || !found || c.Nonce != stamp: |
| // Gone, unknown, or a different card under a reused id. |
| out[i] = suite.NOT_VISIBLE |
| case pr.Revision == c.Revision: |
| out[i] = suite.VISIBLE |
| - case pr.Revision >= 1 && pr.Revision < c.Revision: |
| + case past[cardRevision{id, pr.Revision}]: |
| + // A revision this card had and has moved on from — read off |
| + // its own log, never off the numbers, which are random. |
| out[i] = suite.STALE |
| default: |
| - // Ahead of the log (a restore), or below 1, which it never |
| - // issued: a revision Fichas cannot vouch for. |
| + // A revision this card's log never issued: ahead of a restore, |
| + // or anything else Fichas cannot vouch for. |
| out[i] = suite.UNKNOWN |
| } |
| } |
| return out, nil |
| } |
| +type cardRevision struct{ card, revision int64 } |
| + |
| +// pastRevisions is which asked (card, revision) pairs appear in a live |
| +// card's own event log, in one query. Revisions are random (store.go |
| +// nextRevision), so "older than current" is not a comparison of numbers: |
| +// it is "this card's log once issued it" (spec §6.3). |
| +func (p *suiteProducer) pastRevisions(ctx context.Context, pairs []suite.ItemRevision, live map[int64]Card) (map[cardRevision]bool, error) { |
| + var ids, revs []int64 |
| + for _, pr := range pairs { |
| + id, _, ok := parseStamped(pr.ItemID) |
| + if c, found := live[id]; ok && found && pr.Revision != c.Revision { |
| + ids = append(ids, id) |
| + revs = append(revs, pr.Revision) |
| + } |
| + } |
| + out := map[cardRevision]bool{} |
| + if len(ids) == 0 { |
| + return out, nil |
| + } |
| + var evs []Event |
| + if err := p.g.WithContext(ctx).Model(&Event{}).Select("object_id", "revision"). |
| + Where("object_kind = ? AND object_id IN ? AND revision IN ?", ObjectCard, ids, revs). |
| + Find(&evs).Error; err != nil { |
| + return nil, fmt.Errorf("fichas: reading revision history: %w", err) |
| + } |
| + for _, e := range evs { |
| + out[cardRevision{e.ObjectID, e.Revision}] = true |
| + } |
| + return out, nil |
| +} |
| + |
| // Content is S3 (spec §6.4): the card's text at its current revision, and |
| // suite.ErrNotAvailable for anything else. |
| func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int64) ([]byte, error) { |
| @@ -239,7 +278,7 @@ func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int |
| // check pins where the read STARTED: without it, an edit landing |
| // mid-read that produces the asked revision passes the second check |
| // with the old row's values under the new number. |
| - if cv.Card.CreatedAt.UnixNano() != stamp || cv.Card.Revision != revision { |
| + if cv.Card.Nonce != stamp || cv.Card.Revision != revision { |
| // A different card under a reused id (a restore), or another |
| // revision. |
| return nil, suite.ErrNotAvailable |
diff --git a/internal/fichas/suite_conformance_test.go b/internal/fichas/suite_conformance_test.go| index 0d00331..8c6978a 100644 |
| --- a/internal/fichas/suite_conformance_test.go |
| +++ b/internal/fichas/suite_conformance_test.go |
| @@ -62,8 +62,9 @@ func (n fixtureNames) name(id string) string { |
| // (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), edited |
| -// up to the case's revision, and the deleted case deleted. The harness also |
| +// 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. |
| // |
| @@ -97,36 +98,37 @@ func TestSuiteConformanceFailsOnlyWhereFichasCannotExpress(t *testing.T) { |
| t.Fatal(err) |
| } |
| g, a, p := suiteWorld(t) |
| + // The real, random revisions (suiteWorld pins a count for readability). |
| + pinRevisions(t, randomRevision) |
| ids := map[string]string{} |
| for _, c := range f.Cases { |
| gone := c.Rung == suite.RungDeleted |
| - // A deleted card's last live revision is one below the fixture's, |
| - // because the delete itself is a revision. |
| - lastLive := c.Revision |
| + // 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). |
| + card := mustCard(t, g, a, map[string]string{FieldName: "draft"}) |
| if gone { |
| - lastLive-- |
| - } |
| - name := c.S3Body |
| - if gone { |
| - name = "a card about to be deleted" |
| - } |
| - first := name |
| - if lastLive > 1 { |
| - first = "draft 1" |
| - } |
| - card := mustCard(t, g, a, map[string]string{FieldName: first}) |
| - for r := int64(2); r <= lastLive; r++ { |
| - v := fmt.Sprintf("draft %d", r) |
| - if r == lastLive { |
| - v = name |
| - } |
| - if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldName: v}); err != nil { |
| + if err := DeleteCard(ctx(), g, a.sealer, card.ID, Person(1)); err != nil { |
| t.Fatal(err) |
| } |
| + } else if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldName: c.S3Body}); err != nil { |
| + t.Fatal(err) |
| } |
| - if gone { |
| - if err := DeleteCard(ctx(), g, a.sealer, card.ID, Person(1)); err != nil { |
| + evs := events(t, g, ObjectCard, card.ID) |
| + if len(evs) != 2 { |
| + t.Fatalf("seeding %s: %d card events, want 2", c.ItemID, len(evs)) |
| + } |
| + for _, set := range []struct { |
| + table string |
| + id int64 |
| + rev int64 |
| + }{{"events", evs[0].ID, c.Revision - 1}, {"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) |
| } |
| } |
diff --git a/internal/fichas/suite_revision_test.go b/internal/fichas/suite_revision_test.go| new file mode 100644 |
| index 0000000..db2ddd4 |
| --- /dev/null |
| +++ b/internal/fichas/suite_revision_test.go |
| @@ -0,0 +1,335 @@ |
| +package fichas |
| + |
| +import ( |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| + "testing/fstest" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "amadan.net/rastrillo/rastrillo/sessions" |
| + "gorm.io/gorm" |
| + |
| + "amadan.net/oficina/suite" |
| +) |
| + |
| +// Card revisions and nonces are random positive int63s (spec §6.2, |
| +// store.go nextRevision and randomPositive): never zero, never repeated |
| +// between two cards made one after the other, never the current value. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: revisions as a count |
| +// (current + 1) → "two new cards"; as the clock under a frozen clock |
| +// (max(current + 1, a fixed instant)) → "two new cards"; as the real clock |
| +// (max(current + 1, now in microseconds)) → "repeated" (draws inside one |
| +// microsecond); randomPositive without its sign mask → negative nonces, |
| +// which the insert triggers refuse, so "creating" (and most of the |
| +// package); a card's or an event's nonce left unset → likewise. Two |
| +// mutants survive and are equivalent: randomPositive's zero redraw and |
| +// randomRevision's equal-to-current redraw removed — each guards a 2^-63 |
| +// draw no test can force. |
| +func TestRevisionsAndNoncesAreRandom(t *testing.T) { |
| + g, s := seeded(t) |
| + a, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "A"}) |
| + if err != nil { |
| + t.Fatalf("creating: %v", err) |
| + } |
| + b, err := CreateCard(ctx(), g, s, TypeCustomer, Person(1), map[string]string{FieldName: "B"}) |
| + if err != nil { |
| + t.Fatalf("creating: %v", err) |
| + } |
| + if a.Revision == b.Revision || a.Nonce == b.Nonce { |
| + t.Errorf("two new cards share a revision (%d, %d) or a nonce (%d, %d)", a.Revision, b.Revision, a.Nonce, b.Nonce) |
| + } |
| + seen := map[int64]bool{} |
| + for i := 0; i < 2000; i++ { |
| + r := nextRevision(int64(i)) |
| + if r < 1 { |
| + t.Fatalf("not positive: %d", r) |
| + } |
| + if r == int64(i) || seen[r] { |
| + t.Fatalf("draw %d repeated %d", i, r) |
| + } |
| + seen[r] = true |
| + } |
| + var evs []Event |
| + g.Find(&evs) |
| + for _, e := range evs { |
| + if e.Nonce < 1 { |
| + t.Fatalf("event %d has nonce %d", e.ID, e.Nonce) |
| + } |
| + } |
| +} |
| + |
| +// The nonce columns are write-once and never zero, in the schema itself |
| +// (migrations/0005), not only by convention. |
| +func TestNoncesAreWriteOnceInTheSchema(t *testing.T) { |
| + g, a, _ := suiteWorld(t) |
| + c := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + for name, stmt := range map[string]string{ |
| + "a card's nonce moved": "UPDATE cards SET nonce = nonce + 1 WHERE id = ?", |
| + "an event's nonce moved": "UPDATE events SET nonce = nonce + 1 WHERE object_kind = 'card' AND object_id = ?", |
| + "a card without one": "INSERT INTO cards (card_type_id, revision, nonce) SELECT card_type_id, 1, 0 FROM cards WHERE id = ?", |
| + "an event without one": "INSERT INTO events (kind, object_kind, object_id, nonce) VALUES ('updated', 'card', ?, 0)", |
| + } { |
| + if err := g.Exec(stmt, c.ID).Error; err == nil { |
| + t.Errorf("%s: the schema allowed it", name) |
| + } |
| + } |
| +} |
| + |
| +// frozen pins a database's clock — what stamps created_at — to one |
| +// instant: a clock that stopped, or was set back to where it was when the |
| +// backup was taken. |
| +var frozen = time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC) |
| + |
| +// restorable is a producer over a database file, so it can be backed up |
| +// and a backup opened in its place, with that database's clock frozen. |
| +func restorable(t *testing.T, path string) (*gorm.DB, *app, *suiteProducer) { |
| + t.Helper() |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(path, logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + d.G.Config.NowFunc = func() time.Time { return frozen } |
| + if _, err := migrate.Apply(ctx(), d, BootSchema); err != nil { |
| + t.Fatal(err) |
| + } |
| + s := testSealer(t) |
| + if err := Seed(d.G, s); err != nil { |
| + t.Fatal(err) |
| + } |
| + var n int64 |
| + d.G.Model(&Member{}).Count(&n) |
| + if n == 0 { |
| + pr, _ := s.Print("f_member", []byte("person-1@example.com")) |
| + if err := d.G.Create(&Member{AddressPrint: pr}).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + a := &app{sealer: s, owners: ParseOwners(admittedAsker)} |
| + return d.G, a, producerFor(d.G, a) |
| +} |
| + |
| +func backUp(t *testing.T, g *gorm.DB, to string) { |
| + t.Helper() |
| + if err := g.Exec("VACUUM INTO ?", to).Error; err != nil { |
| + t.Fatalf("backing up: %v", err) |
| + } |
| +} |
| + |
| +func revisionOf(t *testing.T, g *gorm.DB, id int64) int64 { |
| + t.Helper() |
| + var c Card |
| + if err := g.First(&c, id).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + return c.Revision |
| +} |
| + |
| +func askHeld(t *testing.T, p *suiteProducer, held suite.ItemRevision) suite.Authorization { |
| + t.Helper() |
| + got, err := p.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{held}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return got[0] |
| +} |
| + |
| +// The gap the item id's nonce cannot close (spec §6.2): a card that |
| +// predates the restore point keeps its id and nonce, so a revision issued |
| +// after the backup must never be issued again after the restore. Back up, |
| +// edit (memoria holds that revision), restore, edit again — on a frozen |
| +// clock, which is what made clock revisions reissue. The held revision is |
| +// not in the restored log, so it is UNKNOWN before the edit and after it, |
| +// never VISIBLE, and S3 refuses it. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: revisions as a count |
| +// (current + 1) → "reissued", "after the edit" (VISIBLE for the abandoned |
| +// copy), "S3"; as a frozen clock (max(current + 1, a fixed instant)) → the |
| +// same three; every non-current revision STALE → "before the edit". (STALE |
| +// read off the numbers is caught here only when the random held value |
| +// happens to be the lower; TestSuiteRuleEveryBranch catches it every time.) |
| +func TestSuiteRestoreCannotReissueAHeldRevision(t *testing.T) { |
| + dir := t.TempDir() |
| + live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db") |
| + |
| + g, a, p := restorable(t, live) |
| + card := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + backUp(t, g, backup) |
| + if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldNotes: "the text memoria holds"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + held := suite.ItemRevision{ItemID: id(card), Revision: revisionOf(t, g, card.ID)} |
| + if got := askHeld(t, p, held); got != suite.VISIBLE { |
| + t.Fatalf("before the restore, the held revision: %s", got) |
| + } |
| + |
| + g2, a2, p2 := restorable(t, backup) // the restore |
| + if got := askHeld(t, p2, held); got != suite.UNKNOWN { |
| + t.Errorf("before the edit: the restored card never had the held revision, got %s, want UNKNOWN", got) |
| + } |
| + if err := UpdateCard(ctx(), g2, a2.sealer, card.ID, Person(1), map[string]string{FieldNotes: "different text"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now := revisionOf(t, g2, card.ID); now == held.Revision { |
| + t.Errorf("reissued: revision %d names the abandoned text and the new", now) |
| + } |
| + if got := askHeld(t, p2, held); got != suite.UNKNOWN { |
| + t.Errorf("after the edit, the held revision: %s, want UNKNOWN (never VISIBLE)", got) |
| + } |
| + if body, err := p2.Content(ctx(), held.ItemID, held.Revision); !errors.Is(err, suite.ErrNotAvailable) { |
| + t.Errorf("S3 for the held revision after the restore: served %q, %v", body, err) |
| + } |
| +} |
| + |
| +// The same, from a backup taken before this change shipped: the card's |
| +// revisions there are the old small counts, and memoria holds the count |
| +// the old code issued next. One edit after the restore must not land on |
| +// it — a counter would, exactly — and the old history still reads STALE |
| +// from the log. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: revisions as a count → |
| +// "reissued" and "after the edit" (VISIBLE); every non-current revision |
| +// STALE → "before the edit". |
| +func TestSuiteRestoreFromBeforeRandomRevisions(t *testing.T) { |
| + dir := t.TempDir() |
| + live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db") |
| + |
| + g, a, p := restorable(t, live) |
| + // The old code: counted revisions, 1 then 2. |
| + pinRevisions(t, func(current int64) int64 { return current + 1 }) |
| + card := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| + if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldStage: "Lead"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + backUp(t, g, backup) // the card at 2 |
| + if err := UpdateCard(ctx(), g, a.sealer, card.ID, Person(1), map[string]string{FieldNotes: "the text memoria holds"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + held := suite.ItemRevision{ItemID: id(card), Revision: revisionOf(t, g, card.ID)} |
| + if held.Revision != 3 || askHeld(t, p, held) != suite.VISIBLE { |
| + t.Fatalf("the old code's held revision is %d", held.Revision) |
| + } |
| + |
| + // The restore, onto this change. |
| + pinRevisions(t, randomRevision) |
| + g2, a2, p2 := restorable(t, backup) |
| + if got := askHeld(t, p2, held); got != suite.UNKNOWN { |
| + t.Errorf("before the edit: %s, want UNKNOWN", got) |
| + } |
| + if got := askHeld(t, p2, suite.ItemRevision{ItemID: held.ItemID, Revision: 1}); got != suite.STALE { |
| + t.Errorf("an older count, in the restored log: %s, want STALE", got) |
| + } |
| + if err := UpdateCard(ctx(), g2, a2.sealer, card.ID, Person(1), map[string]string{FieldNotes: "different text"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if now := revisionOf(t, g2, card.ID); now == held.Revision { |
| + t.Errorf("reissued: revision %d", now) |
| + } |
| + if got := askHeld(t, p2, held); got == suite.VISIBLE { |
| + t.Errorf("after the edit, the held revision is VISIBLE for different text") |
| + } |
| +} |
| + |
| +// A card created after a restore, on a frozen clock, gets the old card's |
| +// id, revision, event position AND created_at — which is why neither the |
| +// item id nor the cursor is built from created_at. The nonces differ, so |
| +// S2, S3 and S1 all refuse the held identity. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the item id built from |
| +// created_at (in the feed, Rule and Content) → "S2", "S3"; the cursor |
| +// built from the event's created_at → "S1". |
| +func TestSuiteRestoreOnAFrozenClockCannotPassOffANewCard(t *testing.T) { |
| + dir := t.TempDir() |
| + live, backup := filepath.Join(dir, "live.db"), filepath.Join(dir, "backup.db") |
| + |
| + g, a, p := restorable(t, live) |
| + pinRevisions(t, func(current int64) int64 { return current + 1 }) // a collision on revision too |
| + backUp(t, g, backup) // before the card |
| + original := mustCard(t, g, a, map[string]string{FieldName: "The original, which memoria holds"}) |
| + _, heldCursor := readFeed(t, p, "", 10) |
| + |
| + g2, a2, p2 := restorable(t, backup) |
| + recreated := mustCard(t, g2, a2, map[string]string{FieldName: "A different card"}) |
| + var origEv, newEv []Event |
| + g.Where("object_kind = ?", ObjectCard).Find(&origEv) |
| + g2.Where("object_kind = ?", ObjectCard).Find(&newEv) |
| + if recreated.ID != original.ID || recreated.Revision != original.Revision || |
| + !recreated.CreatedAt.Equal(original.CreatedAt) || len(origEv) != 1 || len(newEv) != 1 || |
| + origEv[0].ID != newEv[0].ID || !origEv[0].CreatedAt.Equal(newEv[0].CreatedAt) { |
| + t.Fatalf("the collision did not happen, so this proves nothing: %+v / %+v", original, recreated) |
| + } |
| + |
| + held := suite.ItemRevision{ItemID: id(original), Revision: original.Revision} |
| + if got := askHeld(t, p2, held); got != suite.NOT_VISIBLE { |
| + t.Errorf("S2 for the held item: %s, want NOT_VISIBLE", got) |
| + } |
| + 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) |
| + } |
| +} |
| + |
| +// Migration 0005 gives every row that existed before it a nonce: a card or |
| +// event left at 0 would carry an item id or a cursor that names nothing. |
| +// Built by applying the migrations up to 0004, planting rows at 0, then |
| +// applying the rest. |
| +// |
| +// MUTATION-TESTED 2026-11-01, each reverted: the cards backfill made a |
| +// no-op → "card"; the events backfill made a no-op → "event". |
| +func TestTheNonceBackfillCoversExistingRows(t *testing.T) { |
| + before := fstest.MapFS{} |
| + for _, name := range []string{"0001_init.sql", "0002_immutable_entries.sql", "0003_alter_card_types.sql", "0004_alter_cards.sql"} { |
| + body, err := migrationFS.ReadFile("migrations/" + name) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + before["migrations/"+name] = &fstest.MapFile{Data: body} |
| + } |
| + old, err := migrate.FromFS(before, "fichas") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(filepath.Join(t.TempDir(), "old.db"), logger) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + if _, err := migrate.Apply(ctx(), d, migrate.Merge(sessions.Schema, auth.Schema, old)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := d.G.Exec("INSERT INTO card_types (key, scope) VALUES ('t_old', 'card')").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, stmt := range []string{ |
| + "INSERT INTO cards (card_type_id, revision) SELECT id, 1 FROM card_types WHERE key = 't_old'", |
| + "INSERT INTO events (kind, object_kind, object_id, revision) VALUES ('created', 'card', 1, 1)", |
| + } { |
| + if err := d.G.Exec(stmt).Error; err != nil { |
| + t.Fatalf("%s: %v", stmt, err) |
| + } |
| + } |
| + |
| + if _, err := migrate.Apply(ctx(), d, BootSchema); err != nil { |
| + t.Fatalf("applying 0005: %v", err) |
| + } |
| + var zeroCards, zeroEvents int64 |
| + d.G.Model(&Card{}).Where("nonce < 1").Count(&zeroCards) |
| + d.G.Model(&Event{}).Where("nonce < 1").Count(&zeroEvents) |
| + if zeroCards != 0 { |
| + t.Errorf("card: %d existing cards have no nonce after the backfill", zeroCards) |
| + } |
| + if zeroEvents != 0 { |
| + t.Errorf("event: %d existing events have no nonce after the backfill", zeroEvents) |
| + } |
| +} |
diff --git a/internal/fichas/suite_test.go b/internal/fichas/suite_test.go| index 08b0a72..fcb49c4 100644 |
| --- a/internal/fichas/suite_test.go |
| +++ b/internal/fichas/suite_test.go |
| @@ -28,20 +28,36 @@ func producerFor(g *gorm.DB, a *app) *suiteProducer { |
| return &suiteProducer{g: g, sealer: a.sealer, admit: a.Admit} |
| } |
| +// suiteWorld pins card revisions to a per-card count, 1, 2, 3, in place of |
| +// the random ones Fichas issues. These tests are about what S1, S2 and S3 |
| +// answer for a revision, and readable numbers keep them so; STALE still |
| +// comes from the event log either way. Random revisions, and what a |
| +// counter would get wrong, have their own tests (suite_revision_test.go) |
| +// on the real source. |
| func suiteWorld(t *testing.T) (*gorm.DB, *app, *suiteProducer) { |
| t.Helper() |
| + pinRevisions(t, func(current int64) int64 { return current + 1 }) |
| g, s := seeded(t) |
| a := &app{sealer: s, owners: ParseOwners(admittedAsker)} |
| return g, a, producerFor(g, a) |
| } |
| +// pinRevisions sets how card revisions are issued for one test, and puts |
| +// the random source back after. |
| +func pinRevisions(t testing.TB, next func(current int64) int64) { |
| + t.Helper() |
| + old := newRevision |
| + newRevision = next |
| + t.Cleanup(func() { newRevision = old }) |
| +} |
| + |
| func mustCard(t *testing.T, g *gorm.DB, a *app, values map[string]string) Card { |
| t.Helper() |
| return mustCardBy(t, g, a, Person(1), values) |
| } |
| // mustCardBy creates a card as actor and returns it as the database holds |
| -// it, so its created_at — half of its item id — is the stored value. |
| +// it, so its nonce — half of its item id — is the stored value. |
| func mustCardBy(t *testing.T, g *gorm.DB, a *app, actor Actor, values map[string]string) Card { |
| t.Helper() |
| c, err := CreateCard(ctx(), g, a.sealer, TypeCustomer, actor, values) |
| @@ -55,8 +71,8 @@ func mustCardBy(t *testing.T, g *gorm.DB, a *app, actor Actor, values map[string |
| return stored |
| } |
| -// id is a card's item id: "<card id>.<created_at unix nanos>". |
| -func id(c Card) string { return itemID(c.ID, c.CreatedAt.UnixNano()) } |
| +// id is a card's item id: "<card id>.<nonce>". |
| +func id(c Card) string { return itemID(c.ID, c.Nonce) } |
| // bare is the card id alone, which is not an item id. |
| func bare(c Card) string { return strconv.FormatInt(c.ID, 10) } |
| @@ -242,7 +258,7 @@ func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) { |
| // 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. |
| - other := Event{Kind: EventUpdated, ObjectKind: ObjectType, ObjectID: 1, Revision: 1, CreatedAt: time.Now().UTC()} |
| + other := Event{Kind: EventUpdated, ObjectKind: ObjectType, ObjectID: 1, Revision: 1, CreatedAt: time.Now().UTC(), Nonce: randomPositive()} |
| if err := g.Create(&other).Error; err != nil { |
| t.Fatalf("seeding a catalogue event: %v", err) |
| } |
| @@ -250,7 +266,7 @@ func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) { |
| if err := g.First(&stored, other.ID).Error; err != nil { |
| t.Fatal(err) |
| } |
| - c := stampedID(stored.ID, stored.CreatedAt.UnixNano()) |
| + 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) |
| } |
| @@ -258,24 +274,31 @@ func TestSuiteFeedRefusesACursorItNeverIssued(t *testing.T) { |
| // S2, every branch of spec §6.3's table. |
| // |
| +// Revisions are issued 10 apart here (10, 20, 30), so the table can ask |
| +// about a revision below the current one that the card's log never issued |
| +// — the case where reading STALE off the numbers and reading it off the |
| +// log disagree. |
| +// |
| // MUTATION-TESTED 2026-11-01, each reverted: the person_ref branch removed |
| // (a person_ref falls to admission and answers NOT_VISIBLE) → "person_ref"; |
| // admission skipped → "not admitted"; the gone filter dropped from the |
| -// revision query → "gone"; STALE's lower bound removed (0 and negatives |
| -// are STALE) → "revision 0"/"negative revision"; the lower bound loosened |
| -// to >= 0 → "revision 0"; the > current case answering STALE → "ahead"; |
| +// revision query → "gone"; STALE read off the numbers (1 <= asked < |
| +// current) instead of the log → "never issued, below current"; the history |
| +// query not restricted to this card → "another card's revision"; every |
| +// non-current revision STALE → "ahead", "revision 0", "negative revision"; |
| // == current answering STALE → "current"; the canonical check removed → |
| -// "not canonical"; the stamp comparison removed → "wrong stamp"; the |
| -// query restricted to owner_id = 1 → "owned by another member". |
| +// "not canonical"; the nonce comparison removed → "wrong stamp"; the query |
| +// restricted to owner_id = 1 → "owned by another member". |
| func TestSuiteRuleEveryBranch(t *testing.T) { |
| g, a, p := suiteWorld(t) |
| + pinRevisions(t, func(current int64) int64 { return current + 10 }) |
| live := mustCard(t, g, a, map[string]string{FieldName: "Cnoc Teoranta"}) |
| for _, stage := range []string{"Lead", "Won"} { |
| if err := UpdateCard(ctx(), g, a.sealer, live.ID, Person(1), map[string]string{FieldStage: stage}); err != nil { |
| t.Fatal(err) |
| } |
| } |
| - // live is at revision 3. |
| + // live has been at 10, 20 and is at 30. |
| gone := mustCard(t, g, a, map[string]string{FieldName: "Harbour Timber"}) |
| if err := DeleteCard(ctx(), g, a.sealer, gone.ID, Person(1)); err != nil { |
| t.Fatal(err) |
| @@ -283,24 +306,28 @@ func TestSuiteRuleEveryBranch(t *testing.T) { |
| // Owner is provenance, not authority: a card another member made is |
| // every admitted person's. |
| theirs := mustCardBy(t, g, a, Person(2), map[string]string{FieldName: "Their card"}) |
| - wrongStamp := itemID(live.ID, live.CreatedAt.UnixNano()+1) |
| + wrongStamp := itemID(live.ID, live.Nonce+1) |
| pairs := []suite.ItemRevision{ |
| - {ItemID: id(live), Revision: 3}, // current |
| - {ItemID: id(live), Revision: 2}, // behind |
| - {ItemID: id(live), Revision: 4}, // ahead |
| - {ItemID: id(live), Revision: 0}, // revision 0 |
| - {ItemID: id(live), Revision: -1}, // negative revision |
| - {ItemID: id(gone), Revision: 2}, // gone, at its last revision |
| - {ItemID: "999999.1", Revision: 1}, // unknown |
| - {ItemID: "doc-team", Revision: 1}, // not a card id |
| - {ItemID: "0" + id(live), Revision: 3}, // not canonical |
| - {ItemID: bare(live), Revision: 3}, // no stamp |
| - {ItemID: wrongStamp, Revision: 3}, // wrong stamp |
| - {ItemID: id(theirs), Revision: 1}, // owned by another member |
| + {ItemID: id(live), Revision: 30}, // current |
| + {ItemID: id(live), Revision: 20}, // behind |
| + {ItemID: id(live), Revision: 40}, // ahead |
| + {ItemID: id(live), Revision: 0}, // revision 0 |
| + {ItemID: id(live), Revision: -1}, // negative revision |
| + {ItemID: id(gone), Revision: 20}, // gone, at its last revision |
| + {ItemID: "999999.1", Revision: 1}, // unknown |
| + {ItemID: "doc-team", Revision: 1}, // not a card id |
| + {ItemID: "0" + id(live), Revision: 30}, // not canonical |
| + {ItemID: bare(live), Revision: 30}, // no stamp |
| + {ItemID: wrongStamp, Revision: 30}, // wrong stamp |
| + {ItemID: id(theirs), Revision: 10}, // owned by another member |
| + {ItemID: id(live), Revision: 25}, // never issued, below current |
| + {ItemID: id(live), Revision: 10}, // its first revision |
| + {ItemID: id(theirs), Revision: 20}, // another card's revision |
| } |
| names := []string{"current", "behind", "ahead", "revision 0", "negative revision", "gone", "unknown", |
| - "not a card id", "not canonical", "no stamp", "wrong stamp", "owned by another member"} |
| + "not a card id", "not canonical", "no stamp", "wrong stamp", "owned by another member", |
| + "never issued, below current", "its first revision", "another card's revision"} |
| check := func(what string, asker suite.Subject, want []suite.Authorization) { |
| t.Helper() |
| @@ -329,6 +356,7 @@ func TestSuiteRuleEveryBranch(t *testing.T) { |
| suite.VISIBLE, suite.STALE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, |
| suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE, |
| suite.NOT_VISIBLE, suite.NOT_VISIBLE, suite.VISIBLE, |
| + suite.UNKNOWN, suite.STALE, suite.UNKNOWN, |
| }) |
| // A kind Fichas does not key on is UNKNOWN — loud — even when its value |
| // happens to be an admitted address. |
| @@ -434,7 +462,7 @@ func TestSuiteContent(t *testing.T) { |
| "not a card id": {"doc-team", 1}, |
| "not canonical": {"0" + id(c), 3}, |
| "no stamp": {bare(c), 3}, |
| - "wrong stamp": {itemID(c.ID, c.CreatedAt.UnixNano()+1), 3}, |
| + "wrong stamp": {itemID(c.ID, c.Nonce+1), 3}, |
| } { |
| if body, err := p.Content(ctx(), q.item, q.rev); !errors.Is(err, suite.ErrNotAvailable) || body != nil { |
| t.Errorf("%s: %q, %v; want ErrNotAvailable and no body", name, body, err) |
| @@ -521,7 +549,7 @@ func TestSuiteRestoreCannotPassOffANewCardAsAnOldOne(t *testing.T) { |
| original.ID, recreated.ID, original.Revision, recreated.Revision, origEv, newEv) |
| } |
| if id(recreated) == held { |
| - t.Fatal("the recreated card has the held item id: the clock did not move") |
| + t.Fatal("the recreated card has the held item id: the nonce repeated") |
| } |
| got, err := pBefore.Rule(ctx(), address(admittedAsker), []suite.ItemRevision{{ItemID: held, Revision: 1}}) |
diff --git a/internal/fichastest/suite_test.go b/internal/fichastest/suite_test.go| index 727e841..465edb3 100644 |
| --- a/internal/fichastest/suite_test.go |
| +++ b/internal/fichastest/suite_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "net/url" |
| "path/filepath" |
| "regexp" |
| + "strconv" |
| "strings" |
| "testing" |
| @@ -212,24 +213,33 @@ func TestSuiteServesACardMadeThroughTheApp(t *testing.T) { |
| t.Fatalf("creating a card: %d", rec.Code) |
| } |
| + if rec := post(t, h, "/cards", url.Values{"f_name": {"Second card"}}); rec.Code != http.StatusSeeOther { |
| + t.Fatalf("creating a second card: %d", rec.Code) |
| + } |
| rec := call(h, "GET", suite.RouteS1, suiteToken, nil) |
| feed, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()) |
| - if err != nil || len(feed.Rows) != 1 || feed.Rows[0].Revision != 1 || feed.Rows[0].Gone { |
| + if err != nil || len(feed.Rows) != 2 || feed.Rows[0].Gone { |
| t.Fatalf("S1: %+v, %v", feed, err) |
| } |
| - item := feed.Rows[0].ItemID |
| + // Revisions are random through the whole app (spec §6.2): two new |
| + // cards, which a count would both put at 1, do not share one. |
| + if feed.Rows[0].Revision < 1 || feed.Rows[1].Revision < 1 || feed.Rows[0].Revision == feed.Rows[1].Revision { |
| + t.Errorf("S1 revisions %d and %d: not two distinct random revisions", feed.Rows[0].Revision, feed.Rows[1].Revision) |
| + } |
| + item, rev := feed.Rows[0].ItemID, feed.Rows[0].Revision |
| + revision := strconv.FormatInt(rev, 10) |
| // "<card id>.<created_at unix nanos>" (spec §6.2). |
| if !regexp.MustCompile(`^[1-9][0-9]*\.[1-9][0-9]*$`).MatchString(item) { |
| t.Errorf("item_id %q is not <card id>.<stamp>", item) |
| } |
| - rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision=1", suiteToken, nil) |
| + rec = call(h, "GET", suite.RouteS3+"/"+item+"?revision="+revision, suiteToken, nil) |
| if rec.Code != http.StatusOK || rec.Body.String() != "Cnoc Teoranta\nEmail: orders@cnoc.example" || |
| !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") { |
| t.Errorf("S3: %d %q %q", rec.Code, rec.Body.String(), rec.Header().Get("Content-Type")) |
| } |
| - pairs := []suite.ItemRevision{{ItemID: item, Revision: 1}} |
| + pairs := []suite.ItemRevision{{ItemID: item, Revision: rev}} |
| rec = call(h, "POST", suite.RouteS2, suiteToken, s2Body(t, strings.ToUpper(TestOwner), pairs...)) |
| if got := suite.DecodeS2(pairs, rec.Code, rec.Body.Bytes()); got[0] != suite.VISIBLE { |
| t.Errorf("S2 for the admitted owner (sent in upper case): %s", got[0]) |