Suite producer adopts contract revision 11: CURSOR_RESET, revisions unique against the whole log (UNIQUE index), RunProducer
Fable 5.1 whole-branch review APPROVE (discussion #104); its Low finding answered in 460d8d7 and 609fe76. Hub CI passed on 609fe76. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/suite-r11 into main.
9 files changed,
+500
−98
docs/superpowers/specs/2026-08-30-docs-design.md+96 −20go.mod+1 −1go.sum+2 −6internal/docs/migrations/0012_suite_feed_revisions.sql+13 −0internal/docs/models.go+3 −2internal/docs/store.go+1 −1internal/docs/suite.go+42 −24internal/docs/suite_feed.go+49 −16internal/docs/suite_test.go+293 −28
CI passed — run details
diff --git a/docs/superpowers/specs/2026-08-30-docs-design.md b/docs/superpowers/specs/2026-08-30-docs-design.md| index 86a68ca..4472337 100644 |
| --- a/docs/superpowers/specs/2026-08-30-docs-design.md |
| +++ b/docs/superpowers/specs/2026-08-30-docs-design.md |
| @@ -654,14 +654,17 @@ ruling. |
| The native apps get `visibility` in the share JSON and the same route; |
| their UI for it is not built yet. |
| -### 8.2.2 Serving the suite contract (suite revision 10) |
| +### 8.2.2 Serving the suite contract (suite revision 11) |
| Docs implements `server.Producer` from `amadan.net/oficina/suite/server` |
| -(suite §6.5, read at commit `c38e3ad`) and mounts `server.Handler`. The |
| -package owns the bearer check, the wire shapes, the S2 decode and cap and |
| -S3's one refusal; what follows is only the part Docs owes. Custody is every |
| -live document, per revision 10's §4.2 and §4.3 notes, which are cited and |
| -not restated. |
| +(suite §6.5 and §6.6, **revision 11, read at commit `91affa1`**, suite |
| +`main` on 2026-11-02; built against revision 10 at `c38e3ad` and moved to |
| +revision 11 on branch `feat/suite-r11`) and mounts `server.Handler`. The |
| +package owns the bearer check, the wire shapes, the strict S2 decode and |
| +cap, `Cache-Control: no-store` and `Vary: Authorization` on every response, |
| +the cursor reset's fixed 409 and S3's one refusal; what follows is only the |
| +part Docs owes. Custody is every live document, per revision 10's §4.2 and |
| +§4.3 notes, which are cited and not restated. |
| **The revision counter.** `documents.revision` moves, in the same writer |
| transaction as the change, on creation and on every applied update |
| @@ -670,10 +673,17 @@ alone misses renames, and a rename changes S3's bytes. A grant, a revoke or |
| a link changes who may read, which S2 asks live, so none of them moves it. |
| Each new value — on every change, on creation, and in migration 0011 for |
| every document that existed before it — is **a fresh random positive |
| -value**, never the current one. In code it is 63 random bits from Go's |
| -`crypto/rand` (a zero, or the current value, is drawn again; a source that |
| -cannot be read is an error and the change does not commit — nothing falls |
| -back to a clock or a counter). In migration 0011 it is SQLite's `random()` |
| +value**, never the current one and never any revision this document's |
| +`suite_feed` rows hold. In code it is 63 random bits from Go's |
| +`crypto/rand` (a zero, the current value, or any value in the document's |
| +log is drawn again — `logRevisionTaken`, one probe of the |
| +`suite_feed_document_revision` index that migration `0012` adds, since every |
| +applied update bumps and the log only grows; a source or a log that cannot |
| +be read is an error and the change does not commit — nothing falls back to |
| +a clock or a counter). Revision 11 (suite §6.6) makes the whole-log rule |
| +normative: a draw equal to a *prior* revision would give an old name to new |
| +bytes, and a consumer still holding that prior copy would be answered |
| +`VISIBLE` over it. Revision 10's code redrew only on the current value. In migration 0011 it is SQLite's `random()` |
| masked to 63 bits and forced odd, so **62 random bits**; SQLite's PRNG is |
| ChaCha20 (verified in modernc.org/sqlite v1.55.0), seeded from the OS |
| (`/dev/urandom`), and falls back to the time and the process id if that |
| @@ -697,10 +707,21 @@ library. *Live* is `deleted_at IS NULL AND owner_id > 0`: the orphans |
| **S1.** Pages the log by `id`, 256 rows (`server.FeedPageLimit`). The cursor |
| is `"<id>.<stamp>"` of the last row served, in canonical decimals; `""` and |
| `"0"` are the beginning. The stamp is checked against the row on every |
| -request, and a cursor whose row is gone or carries another stamp — or any |
| -cursor Docs did not issue — is an error, which the suite package answers |
| -503: never a page, never a guess at a position. At the tip Docs returns the |
| -cursor it was given and no rows. Every |
| +request. A cursor the log does not recognise — one whose row is gone or |
| +carries another stamp, or any cursor Docs did not issue or that does not |
| +parse — is `server.ErrCursorReset`, which the suite package answers with |
| +suite §6.6's one fixed `409 {"code":"CURSOR_RESET"}`: never a page, never a |
| +guess at a position, and (since revision 11) never the 503 revision 10's |
| +Docs gave it. Docs never expires or compacts `suite_feed`, so no cursor it |
| +issued goes stale any other way. **A log that cannot be read is not a |
| +reset**: the read's error is returned as it is and the package answers 503, |
| +because a reset makes the consumer set aside everything it holds from Docs |
| +and a database that is briefly unreadable has lost nothing. `""` and `"0"` |
| +are never reset. The stamp is drawn at random **per event and written with |
| +that event's row**, the first of the two shapes suite §6.6 makes normative, |
| +so a restored log holds only the stamps of the rows it actually has; Docs |
| +keeps no generation id. At the tip Docs returns the cursor it was given and |
| +no rows. Every |
| row is emitted, so a document edited ten times since the last poll appears |
| ten times; the earlier rows name revisions that are no longer current, S3 |
| answers them 404, and the consumer counts them missing until the last row |
| @@ -733,6 +754,29 @@ revision. A Home subject with no Docs principal yet still reads the |
| team rung by standing alone, since its first sign-in would. Nothing is |
| cached: every call reads the roster lease and the database afresh. |
| +*A person removed from the team* is answered by the same read check as |
| +everything else, and revision 11 changes nothing in `Rule`. What that |
| +check does today, observed 2026-11-02 on `feat/suite-r11` (team mode, the |
| +custody fixture's world with the asker off the roster): a document they |
| +were **individually granted** stays `VISIBLE` (the address grant does not |
| +key on standing), and the team rung goes; so does **ownership** — their own |
| +private document answers `NOT_VISIBLE`, because `permissionScope` opens |
| +ownership only to a `Member` (above). In lone shape an address taken off |
| +`$DOCS_ALLOWED_ADDRESSES` and holding no live grant fails the front door |
| +and reaches nothing; one still holding a grant passes it and keeps its own |
| +documents too (read from the code, not run). Suite gate 5's reading, which binds |
| +until Paul rules on suite §14's question, is that losing team standing |
| +does not *by itself* revoke what a person owns or was individually granted |
| +(the module's `server.Producer` doc says the same). Docs therefore keeps |
| +grants as gate 5 reads, and drops ownership, which is closer to revision |
| +11's withdrawn proposal than to gate 5. **This is recorded, not changed**: |
| +the brief for this branch was to leave `Rule` alone until Paul rules, and |
| +the ownership rule is the app's own read check, which S2 must not diverge |
| +from. Revision 11's case `doc-owner-left` was withdrawn at `91affa1`, so no |
| +binding fixture asks; Docs' custody seeding refuses any case whose owner is |
| +not `asker` or `other`, so a reinstated case is seen rather than seeded as |
| +somebody else's. |
| + |
| **S3.** The current revision only; anything else is |
| `suite.ErrNotAvailable`, as is a deleted or unknown id. The body is plain |
| UTF-8: the title, a blank line, then `Store.Text`. An untitled document is |
| @@ -769,11 +813,30 @@ most N·M·2^-62 (a million each side: about 2×10^-7). A cursor fails to be |
| refused only if the row now at its id drew the same nonce, 2^-63 or 2^-62 |
| per cursor. Barring that, a pre-restore copy is `UNKNOWN` (its revision is |
| not in the restored log), withheld loudly, and a pre-restore cursor is a |
| -503. The migration's fallback seed (time and pid, when `/dev/urandom` |
| -cannot be opened) would weaken only migration-issued values, once. Kept as defence in depth: that persistent S1 error is the |
| -signal, not something to retry past — **after a restore memoria must drop |
| -everything it holds from Docs and its Docs cursor, and re-read from |
| -`""`.** |
| +`409 CURSOR_RESET` (revision 10's Docs answered it 503, and left the |
| +reset to a person). The migration's fallback seed (time and pid, when |
| +`/dev/urandom` cannot be opened) would weaken only migration-issued values, |
| +once. The reset is the signal: on it memoria soft-drops everything it holds |
| +from Docs, re-reads from `""` and retires what the re-read does not name |
| +(suite §6.6's consumer half, which is memoria's and is cited, not |
| +restated). |
| + |
| +**Headers, and what sits in front of `Handler`.** `server.Handler` sets |
| +`Cache-Control: no-store` and `Vary: Authorization` on every suite |
| +response, refusals and the 401 included. `mountSuite` puts it on the outer |
| +mux beside the router, outside the session, admission and `homeCSRF` |
| +layers; the only thing in front of it in the binary is rastrillo's |
| +production stack (`rastrillo.Handler(ServeOptions(...))`: locale, security |
| +headers, panic recovery), which adds its own security headers and leaves |
| +those two alone. `TestSuiteS1ResetIsNotAFailure` holds both through that |
| +stack; what a proxy in front of the box does is outside this repo. |
| + |
| +**Conformance.** `conformance.RunProducer` (revision 11), in lone shape |
| +(address askers) and team mode (person refs), drives the producer through |
| +`server.Handler` with a token the harness mints, so what is tested is what |
| +is served. It replaced `conformance.RunAs`/`Run` over `server.Routes`, the |
| +unauthenticated routes the module has deprecated. The seeding reads each |
| +case's `prior_revision` from the fixture rather than computing one. |
| **The delegated agent API (main `5039cf6`) and this section.** Its |
| `docs_create` and `docs_update` write through `CreateDraft` and |
| @@ -1366,6 +1429,19 @@ Docs does **not** restate any of them. Where this spec previously did — the |
| five-call contract in §9.1, the instance boundary in §8.2, the egress reason |
| in §11.2 — the restatement has been replaced by a citation. |
| +**Suite revision 11, commit `91affa1` (2026-11-02), consumed for the producer |
| +half; §8.2.2 cites it.** It makes a restore safe and S2/S3 fail closed: a |
| +revision is unique per item against every revision the log holds (§6.6); a |
| +cursor the log does not recognise is answered `409 {"code":"CURSOR_RESET"}`, |
| +never a 503 (§6, S1 row; §6.6); the cursor stamp is drawn per event (§6.6); |
| +every response carries `Cache-Control: no-store` and `Vary: Authorization` |
| +(§6.5); and producers test through `conformance.RunProducer` (§6.5, gate |
| +3). Its one question for Paul — whether a person removed from the team keeps |
| +what they own or were granted — is unruled, so gate 5's reading binds; Docs' |
| +`Rule` is unchanged, and where it differs from that reading (ownership, in |
| +team mode) §8.2.2 says so. `91affa1` is suite `main` after Fable 5.1's review |
| +(APPROVE on 640d058). |
| + |
| **Suite revision 10, commit `c38e3ad` (2026-11-01), consumed for the producer |
| half.** Paul's ruling that day, **"Hold private too, check per person"**, |
| widens custody to every live item; the revision's notes at §4.2 and §4.3 and |
| @@ -1378,7 +1454,7 @@ rounds); §8.2.2 was built against it, conformance included. |
| **Docs imports the contract module under its old path.** Suite §10 says Docs |
| moves from `github.com/carlosframework/docs` to `amadan.net/oficina/docs` |
| before it imports the contract. Importing works without the move — `go get |
| -amadan.net/oficina/suite@c38e3ad` resolves through the hub — so the move |
| +amadan.net/oficina/suite@91affa1` resolves through the hub — so the move |
| stays a follow-up of its own rather than riding this change. |
| **Not yet consumed**, because they need work this spec has not specified: |
diff --git a/go.mod b/go.mod| index 85516d6..cfd48d5 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -10,7 +10,7 @@ require ( |
| amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489 |
| amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af |
| amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af |
| - amadan.net/oficina/suite v0.0.0-20261101215835-c38e3ad85990 |
| + amadan.net/oficina/suite v0.0.0-20261102002704-91affa14eae4 |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3 |
| amadan.net/rastrillo/rastrillo v0.29.1-0.20261027164201-054787952dd2 |
| github.com/carlosframework/rastrillo v0.23.0 |
diff --git a/go.sum b/go.sum| index e530b99..66b5e02 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -1,9 +1,5 @@ |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000 h1:L07nc+dmLI7c1PBkSkbnrjOK5f8p6OBbA/yTxznxCAw= |
| amadan.net/oficina/agent-access.git v0.0.0-20261024232549-8ed8ba826000/go.mod h1:Ph9PIa3VE1IEaUzZiQH6D+IQ6HThWWGfVr0ecMMgrFA= |
| -amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796 h1:yj3d1pKgMbZ3e+7zTf+SWdGYux4E0hhnCOr4YJxH9VE= |
| -amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| -amadan.net/oficina/estilo.git v0.0.0-20261030224824-b8cad3fddfdb h1:hKhThGbsGfIiFLlFv7PeycDip0wy1J/9izkc0rC8ICM= |
| -amadan.net/oficina/estilo.git v0.0.0-20261030224824-b8cad3fddfdb/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407 h1:lpD4zWYtPc77ZNpYXk54+AqQ66i5kLIP2XGa40r1Nmw= |
| amadan.net/oficina/estilo.git v0.0.0-20261030224852-1348c4b3b407/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw= |
| amadan.net/oficina/home/connect v0.0.0-20261030223040-6d99b0ccc542 h1:b2JT0B0Y+5sTsCmVhX6cywCRdGd9s3lRP8wpqOytlbM= |
| @@ -16,8 +12,8 @@ amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af h1:YtDEq1YUm87 |
| amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg= |
| amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af h1:QsC+WKvYxiKipS3+J4D9YWRmKQ+cJJTevlH6kP8UVhA= |
| amadan.net/oficina/home/teammode v0.0.0-20261030153823-602f5136f9af/go.mod h1:dXBZeB2ic33SIZiGUCzafmviUT8TYWgzSYZvo2rM6zA= |
| -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/native/server v0.0.0-20260923173546-2a5d07b2c8d3 h1:5EFx7BLJj/+G/rt8bTmeyMWVfF5s5Sns7ajTvX4w/I8= |
| amadan.net/rastrillo/native/server v0.0.0-20260923173546-2a5d07b2c8d3/go.mod h1:ZaaxeE278dJltdrLwmwpxUjQ5wuKzqDAVSNRet+WupY= |
| amadan.net/rastrillo/rastrillo v0.29.1-0.20261027164201-054787952dd2 h1:ybFov1+wRduFtkxTn44QnzCKTDhyjfFWxWsW+cKaAyk= |
diff --git a/internal/docs/migrations/0012_suite_feed_revisions.sql b/internal/docs/migrations/0012_suite_feed_revisions.sql| new file mode 100644 |
| index 0000000..69223f4 |
| --- /dev/null |
| +++ b/internal/docs/migrations/0012_suite_feed_revisions.sql |
| @@ -0,0 +1,13 @@ |
| +-- One index for the question every bump now asks of suite_feed: does this |
| +-- document's log already hold the revision just drawn? Suite revision 11 |
| +-- (§6.6, suite main 91affa1) makes a revision unique per item against every |
| +-- revision the log holds for it, not only the current one, so bumpRevision |
| +-- redraws on any match (logRevisionTaken). Every applied update bumps and |
| +-- the log is append-only, so without this the probe is a scan of a table |
| +-- that only grows. It serves Rule's history read (issued) too, which asks |
| +-- the same (document, revision) pairs. |
| +-- |
| +-- UNIQUE (Fable's review of db4a14c): the invariant is then the schema's |
| +-- and not only bumpRevision's, so a future path that announces without |
| +-- bumping fails loudly instead of reissuing a revision. |
| +CREATE UNIQUE INDEX IF NOT EXISTS suite_feed_document_revision ON suite_feed (document_id, revision); |
diff --git a/internal/docs/models.go b/internal/docs/models.go| index d3b4380..42e7e17 100644 |
| --- a/internal/docs/models.go |
| +++ b/internal/docs/models.go |
| @@ -64,8 +64,9 @@ type Document struct { |
| // Revision is replaced on every change a suite consumer must re-read: |
| // every applied update, rename, visibility change and deletion, in the |
| // same transaction (bumpRevision, suite_feed.go). Each value is a fresh |
| - // random positive int63, so a restore never reissues one; it has no |
| - // order, and S2 reads STALE from suite_feed. |
| + // random positive int63, never one the document's suite_feed already |
| + // holds (suite revision 11 §6.6), so a restore never reissues one; it |
| + // has no order, and S2 reads STALE from suite_feed. |
| Revision int64 `gorm:"column:revision;not null;default:1"` |
| CreatedAt time.Time `gorm:"column:created_at;not null"` |
diff --git a/internal/docs/store.go b/internal/docs/store.go| index eb31ce7..eca2322 100644 |
| --- a/internal/docs/store.go |
| +++ b/internal/docs/store.go |
| @@ -317,7 +317,7 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st |
| clientID := uint64(mrand.Uint32N(math.MaxUint32)) + 1 |
| now := time.Now().UTC() |
| - revision, err := newRevision(0) |
| + revision, err := newRevision(noRevisionTaken) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/docs/suite.go b/internal/docs/suite.go| index d503e59..747cd85 100644 |
| --- a/internal/docs/suite.go |
| +++ b/internal/docs/suite.go |
| @@ -17,9 +17,10 @@ import ( |
| ) |
| // suiteProducer is Docs' half of the suite contract (spec §8.2.2; suite |
| -// revision 10 and §6.5, commit c38e3ad): the feed of every live document, |
| -// Docs' own per-person read check, and a document's text. The suite |
| -// package owns the bearer check, the wire shapes and S3's one refusal. |
| +// revision 11, §6.5 and §6.6, commit 91affa1): the feed of every live |
| +// document, Docs' own per-person read check, and a document's text. The |
| +// suite package owns the bearer check, the wire shapes, the cache headers, |
| +// the cursor reset's 409 and S3's one refusal. |
| // |
| // Nothing here caches. Every Rule reads the roster lease, the allowlist and |
| // the database afresh, because an authorization answer held past its request |
| @@ -51,20 +52,35 @@ func liveDocuments(g *gorm.DB) *gorm.DB { |
| // Feed pages suite_feed by id. |
| // |
| -// The cursor is "<feed id>.<that row's stamp>" (a random nonce, written |
| -// once), and the stamp is checked on every request. After a restore from an |
| -// older backup AUTOINCREMENT hands the same ids out again to different rows; |
| -// a bare id would carry on silently from a position that now means |
| -// something else, and a consumer at the restored tip would get no rows and |
| -// its own cursor back for ever (Astra, 2026-11-01). A stamp that no longer |
| -// matches, and any cursor Docs did not issue, is an error, which the suite |
| -// package answers 503: loud, never a page. "" and "0" are the beginning. At |
| -// the tip the cursor given comes back unchanged with no rows, which is what |
| -// ends a consumer's poll. |
| +// The cursor is "<feed id>.<that row's stamp>", and the stamp is checked on |
| +// every request. The stamp is a random nonce drawn per event and written |
| +// once with that event's row (announce), which is the first of the two |
| +// shapes suite revision 11 §6.6 makes normative: a restored log holds only |
| +// the stamps of the rows it actually has. (A generation id kept in this same |
| +// database would not do: a restore brings the old one back with the old |
| +// rows.) After a restore from an older backup AUTOINCREMENT hands the same |
| +// ids out again to different rows; a bare id would carry on silently from a |
| +// position that now means something else, and a consumer at the restored |
| +// tip would get no rows and its own cursor back for ever (Astra, |
| +// 2026-11-01). |
| +// |
| +// A cursor this log does not recognise — one that does not parse, names a |
| +// row the log does not hold, or carries another stamp than that row's — is |
| +// server.ErrCursorReset, which the suite package answers with §6.6's one |
| +// fixed 409 {"code":"CURSOR_RESET"}: the consumer sets aside what it holds |
| +// from Docs and reads again from "". Suite revision 10 had Docs answer it |
| +// 503 and leave the reset to a person; revision 11 (suite main 91affa1) |
| +// makes the reset the contract. Docs never expires or compacts suite_feed, |
| +// so no cursor it issued goes stale any other way. A failed read is NOT a |
| +// reset: it is the error it is, which the package answers 503, because a |
| +// reset destroys a consumer's whole copy and a database that is briefly |
| +// unreadable has lost nothing. "" and "0" are the beginning and are never |
| +// reset. At the tip the cursor given comes back unchanged with no rows, |
| +// which is what ends a consumer's poll. |
| func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) { |
| - after, stamp, err := parseFeedCursor(cursor) |
| - if err != nil { |
| - return suite.Feed{}, err |
| + after, stamp, ok := parseFeedCursor(cursor) |
| + if !ok { |
| + return suite.Feed{}, server.ErrCursorReset |
| } |
| db := p.store.db.WithContext(ctx) |
| if after > 0 { |
| @@ -73,7 +89,9 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui |
| return suite.Feed{}, err |
| } |
| if len(at) != 1 || at[0].Stamp != stamp { |
| - return suite.Feed{}, errors.New("docs: suite feed cursor names a row this log does not hold; the database was restored, so the consumer must drop what it holds from Docs and start again") |
| + // A row this log does not hold, or another row at that id: |
| + // the database was restored, or another log issued it. |
| + return suite.Feed{}, server.ErrCursorReset |
| } |
| } |
| var rows []struct { |
| @@ -84,7 +102,7 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui |
| TouchedAt time.Time |
| Stamp int64 |
| } |
| - err = db.Table("suite_feed"). |
| + err := db.Table("suite_feed"). |
| Select("suite_feed.id, documents.sqid, suite_feed.revision, suite_feed.gone, suite_feed.touched_at, suite_feed.stamp"). |
| Joins("JOIN documents ON documents.id = suite_feed.document_id"). |
| Where("suite_feed.id > ? AND documents.owner_id > 0", after). |
| @@ -114,19 +132,19 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui |
| // parseFeedCursor reads a cursor Docs issued: "" or "0" is the beginning, |
| // anything else "<id>.<stamp>" in canonical positive decimals, so a value has |
| -// one spelling. Anything else was not issued here, and is an error rather |
| -// than a guess at a position. |
| -func parseFeedCursor(c string) (after, stamp int64, err error) { |
| +// one spelling. Anything else was not issued here: ok is false, and Feed |
| +// answers it with the cursor reset rather than a guess at a position. |
| +func parseFeedCursor(c string) (after, stamp int64, ok bool) { |
| if c == "" || c == "0" { |
| - return 0, 0, nil |
| + return 0, 0, true |
| } |
| head, tail, found := strings.Cut(c, ".") |
| after, ok1 := canonicalPositive(head) |
| stamp, ok2 := canonicalPositive(tail) |
| if !found || !ok1 || !ok2 { |
| - return 0, 0, errors.New("docs: suite feed cursor was not issued by Docs") |
| + return 0, 0, false |
| } |
| - return after, stamp, nil |
| + return after, stamp, true |
| } |
| func canonicalPositive(s string) (int64, bool) { |
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go| index 277cbcf..fd6b5e6 100644 |
| --- a/internal/docs/suite_feed.go |
| +++ b/internal/docs/suite_feed.go |
| @@ -48,29 +48,62 @@ func randomPositive() (int64, error) { |
| } |
| // newRevision is the revision a change is given: a fresh random positive |
| -// int63, never the document's current one. Revisions are not counted up and |
| -// not read from a clock (Astra on oficina/docs feat/suite-producer, two |
| -// rounds, 2026-11-01): after a restore from a backup — including one taken |
| -// before migration 0011, and one restored onto a clock set back — a counter |
| -// or a clock issues again a revision it issued before, for different |
| -// content, and S2 answers VISIBLE against a copy the asker may no longer |
| -// read. A draw matches any one earlier value with probability 2^-63 |
| -// (spec §8.2.2 has the cumulative figure), whatever the clock, the |
| -// migration's timing or the backup. Order is not needed: memoria only ever |
| -// matches revisions for equality (memoria models.go, SiblingRevision), and |
| -// S2's STALE is decided from this log (Rule), not by comparing numbers. |
| -func newRevision(current int64) (int64, error) { |
| +// int63 that taken does not report. Revisions are not counted up and not |
| +// read from a clock (Astra on oficina/docs feat/suite-producer, two rounds, |
| +// 2026-11-01): after a restore from a backup — including one taken before |
| +// migration 0011, and one restored onto a clock set back — a counter or a |
| +// clock issues again a revision it issued before, for different content, |
| +// and S2 answers VISIBLE against a copy the asker may no longer read. A draw |
| +// matches any one earlier value with probability 2^-63 (spec §8.2.2 has the |
| +// cumulative figure), whatever the clock, the migration's timing or the |
| +// backup. Order is not needed: memoria only ever matches revisions for |
| +// equality (memoria models.go, SiblingRevision), and S2's STALE is decided |
| +// from this log (Rule), not by comparing numbers. |
| +// |
| +// taken is asked about every draw, and a draw it reports is drawn again. |
| +// For a document that exists it is logRevisionTaken: the current revision |
| +// and every revision suite_feed holds for that document, because suite |
| +// revision 11 §6.6 (91affa1) makes a revision unique per item against the |
| +// whole log — a draw equal to a prior revision gives an old name to new |
| +// bytes, and a consumer still holding that prior copy would be told VISIBLE |
| +// over it. A new document has no log, and nothing is taken. |
| +func newRevision(taken func(int64) (bool, error)) (int64, error) { |
| for { |
| r, err := randomPositive() |
| if err != nil { |
| return 0, err |
| } |
| - if r != current { |
| + used, err := taken(r) |
| + if err != nil { |
| + return 0, err |
| + } |
| + if !used { |
| return r, nil |
| } |
| } |
| } |
| +// noRevisionTaken is newRevision's taken for a document being created: it |
| +// has no current revision and no log yet. |
| +func noRevisionTaken(int64) (bool, error) { return false, nil } |
| + |
| +// logRevisionTaken reports a draw that is the document's current revision |
| +// or any revision its suite_feed rows hold, read in the caller's |
| +// transaction. suite_feed_document_revision (0012) keeps it one index probe, |
| +// since every applied update bumps and the log only grows. |
| +func logRevisionTaken(tx *gorm.DB, docID, current int64) func(int64) (bool, error) { |
| + return func(r int64) (bool, error) { |
| + if r == current { |
| + return true, nil |
| + } |
| + var held []int64 |
| + if err := tx.Model(&SuiteFeedRow{}).Where("document_id = ? AND revision = ?", docID, r).Limit(1).Pluck("revision", &held).Error; err != nil { |
| + return false, fmt.Errorf("docs: read the log of document %d: %w", docID, err) |
| + } |
| + return len(held) > 0, nil |
| + } |
| +} |
| + |
| // announce appends one row to suite_feed, with a fresh random nonce for the |
| // S1 cursor. Called only inside the transaction that made the change it |
| // records, so the log and the documents table can never disagree about a |
| @@ -87,8 +120,8 @@ func announce(tx *gorm.DB, docID, revision int64, gone bool) error { |
| return nil |
| } |
| -// bumpRevision moves a document to a new revision (newRevision) and |
| -// announces it, in the caller's transaction. Every change a suite consumer |
| +// bumpRevision moves a document to a new revision (newRevision, never one |
| +// its log holds) and announces it, in the caller's transaction. Every change a suite consumer |
| // must re-read goes through here: an applied update, a rename, a visibility |
| // change and a deletion (gone). A row that is not there is an error rather |
| // than a silent no-op, because a bump that touched nothing would announce a |
| @@ -98,7 +131,7 @@ func bumpRevision(tx *gorm.DB, docID int64, gone bool) error { |
| if err := tx.Model(&Document{}).Where("id = ?", docID).Select("revision").Scan(¤t).Error; err != nil { |
| return fmt.Errorf("docs: read revision of document %d: %w", docID, err) |
| } |
| - revision, err := newRevision(current) |
| + revision, err := newRevision(logRevisionTaken(tx, docID, current)) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/docs/suite_test.go b/internal/docs/suite_test.go| index ee09879..b1903b1 100644 |
| --- a/internal/docs/suite_test.go |
| +++ b/internal/docs/suite_test.go |
| @@ -9,6 +9,7 @@ import ( |
| "io/fs" |
| "net/http" |
| "net/http/httptest" |
| + "net/url" |
| "os" |
| "path/filepath" |
| "sort" |
| @@ -45,18 +46,21 @@ func suiteVector(t *testing.T, id string) []byte { |
| return b |
| } |
| -// setRevision puts a document at the fixture's revision, with the revision |
| -// before it in its history: both are announced, as two bumps would be. The |
| -// fixture numbers its revisions 2 to 11 and real bumps are random |
| +// setRevision puts a document at the fixture's revision, with the case's |
| +// prior revision before it in its history: both are announced, as two bumps |
| +// would be. The fixture names its revisions and real bumps are random |
| // (newRevision), so the world is seeded at the fixture's numbers directly; |
| // the producer reads documents.revision and suite_feed and does not care how |
| -// they got there. revision - 1 being in the log is what makes the harness's |
| -// "one behind" STALE (Docs decides STALE from its log), and revision + 1 |
| -// never being announced is what makes "one ahead" UNKNOWN. |
| -func setRevision(t *testing.T, s *Store, docID, revision int64) { |
| +// they got there. prior being in the log is what makes the harness's |
| +// prior_revision STALE (Docs decides STALE from its log), and the case's |
| +// unknown_revision never being announced is what makes it UNKNOWN. Suite |
| +// revision 11 (91affa1) names prior_revision in the fixture rather than |
| +// letting the harness compute "one behind"; it is revision - 1 in every case |
| +// today, and is read from the fixture here all the same. |
| +func setRevision(t *testing.T, s *Store, docID, prior, revision int64) { |
| t.Helper() |
| err := s.db.Transaction(func(tx *gorm.DB) error { |
| - for _, r := range []int64{revision - 1, revision} { |
| + for _, r := range []int64{prior, revision} { |
| if err := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", r).Error; err != nil { |
| return err |
| } |
| @@ -91,11 +95,20 @@ type custodyParty struct { |
| // seedCustody builds the custody fixture's world in a Docs store, through |
| // Docs' own store paths: each case's rung, its owner (the asker or the other |
| // party), a grant to the asker or to a guest, a published link, a deletion, |
| -// and the case's revision (setRevision). The fixture's ids are not |
| +// and the case's revisions (setRevision). The fixture's ids are not |
| // sqids; each document's sqid is set to the fixture id straight after it is |
| // created (the column is a plain unique TEXT), so the producer under test is |
| // the real one with no id-mapping in between. Documents are untitled, so S3's |
| // body is the text alone and equals the fixture's s3_body exactly. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each reverted: the "other" owner arm renamed |
| +// so the switch no longer knows it → both conformance tests fatal on |
| +// "custody case doc-team: owner "other" is not one this seeding knows"; |
| +// setRevision seeding revision + 1000 in place of the fixture's |
| +// prior_revision → both conformance tests "at a prior revision the log |
| +// holds: got UNKNOWN, want STALE" for the four cases the asker may open. |
| +// (A first try seeded revision - 2 and went red on the column's CHECK, not |
| +// on the rule, so it proved nothing and was redone.) |
| func seedCustody(t *testing.T, s *Store, asker, other custodyParty) { |
| t.Helper() |
| ctx := context.Background() |
| @@ -104,9 +117,20 @@ func seedCustody(t *testing.T, s *Store, asker, other custodyParty) { |
| t.Fatal(err) |
| } |
| for _, c := range f.Cases { |
| - owner := other |
| - if c.Owner == "asker" { |
| + // "asker" and "other" are the only owners a binding case names. |
| + // Revision 11 briefly added "stranger" (doc-owner-left: an owner |
| + // who has lost team standing), withdrawn at 91affa1 until Paul rules |
| + // (suite §14); Docs' Rule keeps gate 5's reading meanwhile. A case |
| + // naming any other owner is refused here rather than seeded as |
| + // owned by "other", which would pass it for the wrong reason. |
| + var owner custodyParty |
| + switch c.Owner { |
| + case "asker": |
| owner = asker |
| + case "other": |
| + owner = other |
| + default: |
| + t.Fatalf("custody case %s: owner %q is not one this seeding knows (asker, other)", c.ItemID, c.Owner) |
| } |
| vis := VisibilityPrivate |
| if c.Rung == suite.RungTeam || c.ItemID == "doc-was-team" { |
| @@ -155,12 +179,12 @@ func seedCustody(t *testing.T, s *Store, asker, other custodyParty) { |
| // Deleted through the real path; its last revision is a |
| // random one, which nothing asks about: a deleted item is |
| // NOT_VISIBLE and refused at every revision. |
| - setRevision(t, s, doc.ID, c.Revision-1) |
| + setRevision(t, s, doc.ID, c.PriorRevision, c.Revision) |
| if err := s.deleteDocument(ctx, doc.ID); err != nil { |
| t.Fatal(err) |
| } |
| } else { |
| - setRevision(t, s, doc.ID, c.Revision) |
| + setRevision(t, s, doc.ID, c.PriorRevision, c.Revision) |
| } |
| } |
| } |
| @@ -193,6 +217,20 @@ func loneCustodyApp(t *testing.T) *App { |
| // addresses here, and the harness also asks under person_ref, which must be |
| // UNKNOWN for every pair. |
| // |
| +// Run through conformance.RunProducer (suite revision 11, 91affa1): the |
| +// harness mounts the producer behind server.Handler with a token it mints, |
| +// requires the 401 without it, and audits Cache-Control: no-store and Vary: |
| +// Authorization on every response. It replaces conformance.RunAs over |
| +// server.Routes, the unauthenticated routes the module has deprecated. It |
| +// covers Handler and the producer only; what Docs mounts in front of |
| +// Handler is TestSuiteS1ResetIsNotAFailure's and |
| +// TestSuiteRoutesAreMountedExactlyOutsideCSRF's. |
| +// |
| +// MUTATION-TESTED 2026-11-02, reverted: Feed answering an unparseable |
| +// cursor with a plain error (revision 10's 503) → "S1 with a cursor the log |
| +// never issued: 503, want 409 {"code":"CURSOR_RESET"}" here and in team |
| +// mode. |
| +// |
| // MUTATION-TESTED 2026-11-01, each reverted: the link table read as a grant |
| // in permissionScope (an EXISTS on links) → doc-link, doc-link-added-late |
| // VISIBLE; teamReader returning true → the stranger VISIBLE on doc-team; |
| @@ -207,7 +245,7 @@ func loneCustodyApp(t *testing.T) *App { |
| // the test blind, and was replaced by the one above.) |
| func TestSuiteConformanceLoneShape(t *testing.T) { |
| app := loneCustodyApp(t) |
| - conformance.RunAs(t, server.Routes(app.suite, nil), suite.SubjectAddress) |
| + conformance.RunProducer(t, app.suite, suite.SubjectAddress) |
| } |
| // renamedAskers maps the fixture's person refs onto roster-shaped subjects |
| @@ -269,8 +307,7 @@ func teamCustodyStore(t *testing.T, members ...string) (*App, *suiteProducer, *t |
| // stranger answer UNKNOWN (a 503 for the whole call). |
| func TestSuiteConformanceTeamMode(t *testing.T) { |
| _, p, _, _, _ := teamCustodyStore(t) |
| - h := server.Routes(renamedAskers{Producer: p, names: map[string]string{"pers_ana": anaSubject, "pers_bo": strangerSubject}}, nil) |
| - conformance.Run(t, h) |
| + conformance.RunProducer(t, renamedAskers{Producer: p, names: map[string]string{"pers_ana": anaSubject, "pers_bo": strangerSubject}}, suite.SubjectPersonRef) |
| } |
| // The two halves of Paul's 2026-11-01 ruling, "New docs Team, old private": |
| @@ -519,6 +556,13 @@ func TestSuiteTeamRungTeamMode(t *testing.T) { |
| // gone=false → "(gone)"; Feed returning "" at an empty tip → "empty tip"; |
| // Feed ignoring the cursor → "the cursor came back unchanged with rows"; |
| // Feed not checking the stamp → cursor "2.1" answered a page. |
| +// |
| +// MUTATION-TESTED 2026-11-02 (suite revision 11, the cursor reset), each |
| +// reverted: Feed answering a stamp mismatch or a missing row with a plain |
| +// error (revision 10's 503) → "2.1", "999.<stamp>" and the conformance |
| +// fixture's never-issued cursor "want server.ErrCursorReset"; Feed |
| +// answering an unparseable cursor with a plain error → "not-a-cursor", "-1" |
| +// and the four respellings, same message. |
| func TestSuiteFeed(t *testing.T) { |
| app, err := NewForTest(t) |
| if err != nil { |
| @@ -613,13 +657,14 @@ func TestSuiteFeed(t *testing.T) { |
| if tip, _ := p.Feed(ctx, cursor, 2); tip.Cursor != cursor || len(tip.Rows) != 0 { |
| t.Errorf("tip: %+v, want cursor %q and no rows", tip, cursor) |
| } |
| - // A cursor Docs did not issue is an error (the suite package's 503), |
| - // never a page: not a bare id, not a stamp that does not match the row, |
| - // not another spelling of a real one. |
| + // A cursor Docs did not issue is the cursor reset (suite revision 11 |
| + // §6.6; the suite package's 409 CURSOR_RESET), never a page and never |
| + // another error: not a bare id, not a stamp that does not match the |
| + // row, not another spelling of a real one, not a row past the log's end. |
| id, stamp, _ := strings.Cut(cursors[0], ".") |
| - for _, bad := range []string{"not-a-cursor", id, id + ".1", "0" + cursors[0], id + "." + stamp + "0", "-1", "+" + cursors[0]} { |
| - if f, err := p.Feed(ctx, bad, 100); err == nil { |
| - t.Errorf("cursor %q: a page of %d rows, want an error", bad, len(f.Rows)) |
| + for _, bad := range []string{"not-a-cursor", id, id + ".1", "0" + cursors[0], id + "." + stamp + "0", "-1", "+" + cursors[0], "999." + stamp, suite.NeverIssuedCursor} { |
| + if f, err := p.Feed(ctx, bad, 100); !errors.Is(err, server.ErrCursorReset) { |
| + t.Errorf("cursor %q: %d rows, error %v; want server.ErrCursorReset", bad, len(f.Rows), err) |
| } |
| } |
| if f, err := p.Feed(ctx, cursors[0], 100); err != nil || len(f.Rows) != len(want)-2 { |
| @@ -919,6 +964,116 @@ func TestSuiteRoutesAreMountedExactlyOutsideCSRF(t *testing.T) { |
| } |
| } |
| +// S1 over the wire as memoria meets it — the app's own mux and rastrillo's |
| +// production stack in front of it, as cmd/docs serves — for the two answers |
| +// suite revision 11 (§6.6, 91affa1) keeps apart. A cursor this log does not |
| +// recognise is the fixed 409 {"code":"CURSOR_RESET"}, the one way a |
| +// consumer is told to set aside what it holds from Docs and read from "". |
| +// A log that cannot be read is a 503, because it has lost nothing and a |
| +// reset would destroy the consumer's whole copy. Both carry Cache-Control: |
| +// no-store and Vary: Authorization through every layer Docs puts in front |
| +// of server.Handler (conformance.RunProducer drives Handler alone and cannot |
| +// see those layers, doctrine §6.5). |
| +// |
| +// MUTATION-TESTED 2026-11-02, each reverted: Feed answering a failed stamp |
| +// read with server.ErrCursorReset (a database failure read as a reset) → |
| +// "a log that cannot be read, from a cursor it issued: 409, want 503"; |
| +// Feed answering a stamp mismatch with a plain error (revision 10) → "a |
| +// stamp this log never wrote: 503"; Feed answering an unparseable cursor |
| +// with a plain error → "a cursor that does not parse: 503"; mountSuite |
| +// wrapping Handler in a layer whose ResponseWriter sets Cache-Control: |
| +// private at WriteHeader → every "Cache-Control" line, on both layers. (A |
| +// first try set the header before calling Handler and stayed green: |
| +// Handler sets no-store over it, so that layer was harmless, not the test |
| +// blind.) |
| +func TestSuiteS1ResetIsNotAFailure(t *testing.T) { |
| + app, err := NewForTestWith(t, Config{SuiteConsumers: suiteConsumersJSON()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + if _, err := app.store.Create(ctx, alice, "One"); err != nil { |
| + t.Fatal(err) |
| + } |
| + served, done, err := rastrillo.Handler(ServeOptions(rastrillo.Options{}, app)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if done != nil { |
| + defer done() |
| + } |
| + layers := map[string]http.Handler{"the app's mux": app.Handler(), "rastrillo's production stack": served} |
| + s1 := func(h http.Handler, cursor string) *httptest.ResponseRecorder { |
| + return httptestServe(h, suiteRequest("GET", suite.RouteS1+"?cursor="+url.QueryEscape(cursor), suiteTestToken, nil)) |
| + } |
| + headers := func(t *testing.T, what string, rec *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if got := rec.Header().Get("Cache-Control"); got != "no-store" { |
| + t.Errorf("%s: Cache-Control %q, want no-store", what, got) |
| + } |
| + if got := rec.Header().Values("Vary"); len(got) != 1 || got[0] != "Authorization" { |
| + t.Errorf("%s: Vary %q, want Authorization", what, got) |
| + } |
| + } |
| + first := s1(app.Handler(), "") |
| + feed, err := suite.DecodeS1(first.Code, first.Body.Bytes()) |
| + if err != nil || len(feed.Rows) == 0 { |
| + t.Fatalf("S1 from the beginning: %d %v", first.Code, err) |
| + } |
| + issued := feed.Cursor |
| + id, stamp, _ := strings.Cut(issued, ".") |
| + wrongStamp := "1" |
| + if stamp == wrongStamp { |
| + wrongStamp = "2" |
| + } |
| + |
| + for name, h := range layers { |
| + t.Run(name, func(t *testing.T) { |
| + for what, cursor := range map[string]string{ |
| + "a stamp this log never wrote": id + "." + wrongStamp, |
| + "a row this log does not hold": "999999." + stamp, |
| + "a cursor that does not parse": "not-a-cursor", |
| + "the fixture's never-issued one": suite.NeverIssuedCursor, |
| + } { |
| + rec := s1(h, cursor) |
| + if rec.Code != suite.CursorResetStatus || rec.Body.String() != suite.CursorResetBody { |
| + t.Errorf("%s: %d %q, want %d %s", what, rec.Code, rec.Body.String(), suite.CursorResetStatus, suite.CursorResetBody) |
| + } |
| + if _, err := suite.DecodeS1(rec.Code, rec.Body.Bytes()); !errors.Is(err, suite.ErrCursorReset) { |
| + t.Errorf("%s: memoria's decoder reads %v, want suite.ErrCursorReset", what, err) |
| + } |
| + headers(t, what, rec) |
| + } |
| + if rec := s1(h, issued); rec.Code != http.StatusOK { |
| + t.Errorf("a cursor Docs issued: %d, want 200", rec.Code) |
| + } else { |
| + headers(t, "a cursor Docs issued", rec) |
| + } |
| + }) |
| + } |
| + |
| + // The log cannot be read. The table is moved aside, not dropped, so |
| + // nothing about the log's content changes: only whether it can be read. |
| + if err := app.store.db.Exec("ALTER TABLE suite_feed RENAME TO suite_feed_away").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + for name, h := range layers { |
| + t.Run(name+", log unreadable", func(t *testing.T) { |
| + for what, cursor := range map[string]string{ |
| + "a log that cannot be read, from a cursor it issued": issued, |
| + "a log that cannot be read, from the beginning": "", |
| + } { |
| + rec := s1(h, cursor) |
| + if rec.Code != http.StatusServiceUnavailable { |
| + t.Errorf("%s: %d %q, want 503", what, rec.Code, rec.Body.String()) |
| + } |
| + headers(t, what, rec) |
| + } |
| + }) |
| + } |
| +} |
| + |
| func httptestServe(h http.Handler, r *http.Request) *httptest.ResponseRecorder { |
| rec := httptest.NewRecorder() |
| h.ServeHTTP(rec, r) |
| @@ -954,7 +1109,10 @@ func TestSuiteConsumersMalformedRefusesBoot(t *testing.T) { |
| // (newRevision and randomPositive reading suiteClock) → "clock set back" |
| // VISIBLE and its old cursor answered a page, while "real clock" stayed |
| // green, which is why both subtests exist; Feed without the nonce check → |
| -// both subtests' old cursor answered a page. |
| +// both subtests' old cursor answered a page. MUTATION-TESTED 2026-11-02 |
| +// (suite revision 11 §6.6), reverted: Feed answering the stamp mismatch with |
| +// a plain error, revision 10's 503 → both subtests "want |
| +// server.ErrCursorReset". |
| func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) { |
| for _, tc := range []struct { |
| name string |
| @@ -1023,8 +1181,8 @@ func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) { |
| if current := revisionOf(t, restored.store, doc.ID); current == held { |
| t.Errorf("the restore reissued revision %d", held) |
| } |
| - if f, err := restored.suite.Feed(ctx, cursor, 100); err == nil { |
| - t.Errorf("the cursor from before the restore (%q) answered a page: cursor %q, %d rows; want an error", cursor, f.Cursor, len(f.Rows)) |
| + if f, err := restored.suite.Feed(ctx, cursor, 100); !errors.Is(err, server.ErrCursorReset) { |
| + t.Errorf("the cursor from before the restore (%q): cursor %q, %d rows, error %v; want server.ErrCursorReset (suite revision 11 §6.6)", cursor, f.Cursor, len(f.Rows), err) |
| } |
| }) |
| } |
| @@ -1340,6 +1498,12 @@ func (brokenRandom) Read([]byte) (int, error) { return 0, errors.New("no entropy |
| // 0; newRevision returning its first draw → "current, then the next" gets |
| // 5; randomPositive answering a failed read with a time-based value instead |
| // of an error → "a broken source" commits a document. |
| +// |
| +// newRevision now takes what is taken rather than the current revision |
| +// (suite revision 11 §6.6, 91affa1: unique against the whole log; the log |
| +// half is TestSuiteARevisionIsNeverOneTheLogHolds). MUTATION-TESTED |
| +// 2026-11-02, reverted: newRevision ignoring taken's error → "a log that |
| +// cannot be read: a revision was drawn anyway". |
| func TestSuiteRevisionsRedrawAndNeverFallBack(t *testing.T) { |
| t.Cleanup(func() { randomSource = crand.Reader }) |
| @@ -1351,13 +1515,27 @@ func TestSuiteRevisionsRedrawAndNeverFallBack(t *testing.T) { |
| if n, err := randomPositive(); err != nil || n != 11 { |
| t.Errorf("the sign bit alone (zero once cleared), then 11: %d %v", n, err) |
| } |
| + only := func(held ...int64) func(int64) (bool, error) { |
| + return func(r int64) (bool, error) { |
| + for _, h := range held { |
| + if r == h { |
| + return true, nil |
| + } |
| + } |
| + return false, nil |
| + } |
| + } |
| randomSource = draws(5, 9) |
| - if n, err := newRevision(5); err != nil || n != 9 { |
| + if n, err := newRevision(only(5)); err != nil || n != 9 { |
| t.Errorf("current, then the next: %d %v", n, err) |
| } |
| randomSource = draws(5) |
| - if n, err := newRevision(4); err != nil || n != 5 { |
| - t.Errorf("a draw that is not current is kept: %d %v", n, err) |
| + if n, err := newRevision(only(4)); err != nil || n != 5 { |
| + t.Errorf("a draw that is not taken is kept: %d %v", n, err) |
| + } |
| + randomSource = draws(5) |
| + if _, err := newRevision(func(int64) (bool, error) { return false, errors.New("log unreadable") }); err == nil { |
| + t.Error("a log that cannot be read: a revision was drawn anyway") |
| } |
| app, err := NewForTest(t) |
| @@ -1390,6 +1568,93 @@ func TestSuiteRevisionsRedrawAndNeverFallBack(t *testing.T) { |
| } |
| } |
| +// A revision is never one the document's log holds (suite revision 11 §6.6, |
| +// 91affa1, answering Fable's review of 0a59e7d, L4): a draw equal to ANY |
| +// earlier revision of the document is drawn again, not only a draw equal to |
| +// the current one. A draw equal to a prior revision would give an old name |
| +// to new bytes, and a consumer still holding the old copy would be answered |
| +// VISIBLE over text the document no longer has. The draws are forced: the |
| +// document's first revision, its second, its current one, then a fresh |
| +// value, which is the one the rename must take. |
| +// |
| +// MUTATION-TESTED 2026-11-02, each reverted: logRevisionTaken checking only |
| +// the current revision (the revision-10 rule) → "the rename took revision |
| +// <first>, one the log already held"; 0012 deleted → "the log probe's plan |
| +// is [{Detail:SCAN suite_feed}]"; 0012's UNIQUE dropped → "suite_feed |
| +// took a second row"; logRevisionTaken returning false, |
| +// nil on a failed read → "a log that cannot be read: taken false and no |
| +// error". |
| +func TestSuiteARevisionIsNeverOneTheLogHolds(t *testing.T) { |
| + t.Cleanup(func() { randomSource = crand.Reader }) |
| + app, err := NewForTest(t) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx := context.Background() |
| + alice := app.TestPerson(t, "alice@example.com") |
| + actor := app.TestActorForPerson(t, alice) |
| + doc, err := app.store.Create(ctx, alice, "One") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + history := []int64{revisionOf(t, app.store, doc.ID)} |
| + for _, title := range []string{"One, again", "One, once more"} { |
| + if err := app.store.Rename(ctx, actor, doc, title); err != nil { |
| + t.Fatal(err) |
| + } |
| + history = append(history, revisionOf(t, app.store, doc.ID)) |
| + } |
| + const fresh, nonce = 42, 4242 |
| + for _, h := range history { |
| + if h == fresh { |
| + t.Skip("a random revision happened to be the fresh value") |
| + } |
| + } |
| + // Bump: history[0], history[1], history[2] (current), then fresh; then |
| + // announce's nonce. |
| + randomSource = draws(uint64(history[0]), uint64(history[1]), uint64(history[2]), fresh, nonce) |
| + if err := app.store.Rename(ctx, actor, doc, "Different text"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := revisionOf(t, app.store, doc.ID); got != fresh { |
| + t.Errorf("the rename took revision %d, one the log already held (history %v); want the fresh draw %d", got, history, fresh) |
| + } |
| + |
| + // The probe is one index lookup (0012), not a scan of a log that grows |
| + // with every applied update. |
| + var plan []struct{ Detail string } |
| + if err := app.store.db.Raw("EXPLAIN QUERY PLAN SELECT revision FROM suite_feed WHERE document_id = ? AND revision = ? LIMIT 1", doc.ID, fresh).Scan(&plan).Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(plan) != 1 || !strings.Contains(plan[0].Detail, "suite_feed_document_revision") { |
| + t.Errorf("the log probe's plan is %+v, want a search on suite_feed_document_revision", plan) |
| + } |
| + |
| + // The schema holds the rule too: a second row for a revision the log |
| + // already holds is refused, whatever path writes it. The forced draws |
| + // are spent, so the real source goes back first — announce draws a |
| + // nonce, and a failed draw would pass this for the wrong reason (it |
| + // did, the first time). The presence half: a revision the log does not |
| + // hold is taken. |
| + randomSource = crand.Reader |
| + if err := announce(app.store.db, doc.ID, fresh+1, false); err != nil { |
| + t.Fatalf("suite_feed refused a revision it did not hold: %v", err) |
| + } |
| + if err := announce(app.store.db, doc.ID, fresh, false); err == nil { |
| + t.Errorf("suite_feed took a second row at revision %d for one document", fresh) |
| + } |
| + |
| + // A log that cannot be read is an error, never "not taken". Asked of |
| + // the probe directly: through a bump, announce's insert into the same |
| + // missing table would fail anyway and hide whether the probe did. |
| + if err := app.store.db.Exec("ALTER TABLE suite_feed RENAME TO suite_feed_away").Error; err != nil { |
| + t.Fatal(err) |
| + } |
| + if taken, err := logRevisionTaken(app.store.db, doc.ID, fresh)(7); err == nil { |
| + t.Errorf("a log that cannot be read: taken %v and no error", taken) |
| + } |
| +} |
| + |
| // An orphan — a document 0002_owners.sql left at owner_id 0, readable by |
| // nobody — is not live, even if a feed row names it. Nothing in Docs writes |
| // one (announce runs only for documents with an owner), so the row is made |