oficina / docs Public

Docs: random revisions and feed nonces; STALE decided by the log

Astra's second review (54640b4), two P1s on restore, and the coverage gap
that a clock-only revision survived the suite:

- newRevision: every revision (each change, creation, and 0009 for every
  existing document) is a fresh random positive int63 from crypto/rand
  (SQLite random() in the migration), never the current one. A restored
  database cannot reissue one, whatever the clock or when the backup was
  taken.
- Rule: VISIBLE at the current revision; STALE only for a revision this
  document's suite_feed rows hold; UNKNOWN for anything else (never
  issued, another document's, or from before a restore). Person first.
- suite_feed.stamp is a random nonce, backfill rows included; the cursor
  stays "<id>.<stamp>", checked every request, a mismatch an error.
- suiteClock is touched_at's clock only; tests set it back.
- Tests: Astra's sequences — restore on the real clock and on a clock set
  back (10:00 backup, 10:10 confidential, restore onto 10:10), and a
  pre-0009 backup restored and migrated again with Bob's old grant — plus
  STALE from the log. The custody world is seeded with revision − 1 in
  each item's log, so conformance's one-behind is STALE and one-ahead
  UNKNOWN by the log.

Mutations, each reverted and red: sequential revisions; time-based
revisions and nonces (red under the set-back clock only); STALE without the
log; the log lookup not keyed on the document; the nonce check removed;
0009 without its random UPDATE.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev c4cb4cacba318d9bd6e7f126c1febbe47af299c5 parent e55cdbd
6 files changed, +414 −151
  • internal/docs/migrations/0009_suite.sql +22 −20
  • internal/docs/models.go +8 −7
  • internal/docs/store.go +5 −6
  • internal/docs/suite.go +47 −4
  • internal/docs/suite_feed.go +57 −33
  • internal/docs/suite_test.go +275 −81

CI passed — run details

diff --git a/internal/docs/migrations/0009_suite.sql b/internal/docs/migrations/0009_suite.sql
index 82d21ce..75b8143 100644
--- a/internal/docs/migrations/0009_suite.sql
+++ b/internal/docs/migrations/0009_suite.sql
@@ -12,18 +12,22 @@
ALTER TABLE documents ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private'
CHECK (visibility IN ('private', 'team'));
--- revision: one counter per document, moved in the same writer transaction
+-- revision: a token per document, replaced in the same writer transaction
-- as every applied update, rename, visibility change and deletion. Not
-- doc_updates.seq, which a rename never touches although a rename changes
--- what S3 serves. Each move sets it to max(revision + 1, now in unix
--- microseconds) (bumpRevision), so a database restored from a backup never
--- issues again a revision it issued before the restore: a consumer's copy
--- from before cannot match the current revision by coincidence (Astra on
--- oficina/docs feat/suite-producer, 2026-11-01). Existing documents start at
--- 1: nothing was ever issued for them, and their first change jumps to the
--- clock.
+-- what S3 serves. Every value is a fresh random positive int63
+-- (newRevision), here and in code, never a count and never a clock: after a
+-- restore from a backup a count or a clock issues again a value issued
+-- before, for different content, and a consumer's copy would be answered as
+-- current (Astra on oficina/docs feat/suite-producer, two rounds,
+-- 2026-11-01 — including a backup taken BEFORE this migration, restored and
+-- migrated again, which a constant here would have given the same revision
+-- it gave the first time). memoria only matches revisions for equality, and
+-- S2 decides STALE from suite_feed, so no order is needed. SQLite's random()
+-- is seeded from the OS; masked to 63 bits and forced odd, so never 0.
ALTER TABLE documents ADD COLUMN revision INTEGER NOT NULL DEFAULT 1
CHECK (revision >= 1);
+UPDATE documents SET revision = (random() & 9223372036854775807) | 1;
-- suite_feed: append-only, one row per bump (creation included), written in
-- the bump's own transaction, so S1 can page by id and a consumer's cursor is
@@ -31,11 +35,12 @@ ALTER TABLE documents ADD COLUMN revision INTEGER NOT NULL DEFAULT 1
-- fields suite S1 carries and a stamp, so the table holds nothing the
-- plaintext gate (spec §12) would have to look at.
--
--- stamp is the row's creation time in unix nanoseconds, written once. The
--- S1 cursor is "<id>.<stamp>" and the stamp is checked on every request:
--- after a restore AUTOINCREMENT hands the same ids out again to different
--- rows, and a bare id would carry on silently from a position that now
--- means something else (the Fichas pattern, fichas main 7bfd4c4).
+-- stamp is a random positive nonce, written once with the row. The S1
+-- cursor is "<id>.<stamp>" and the stamp is checked on every request: after
+-- a restore AUTOINCREMENT hands the same ids out again to different rows,
+-- and a bare id would carry on silently from a position that now means
+-- something else (the Fichas pattern, fichas main 7bfd4c4). Random, not a
+-- time, so a clock set back cannot reproduce one either.
CREATE TABLE IF NOT EXISTS suite_feed (
id INTEGER PRIMARY KEY AUTOINCREMENT,
document_id INTEGER NOT NULL,
@@ -45,16 +50,13 @@ CREATE TABLE IF NOT EXISTS suite_feed (
stamp INTEGER NOT NULL CHECK (stamp > 0)
);
--- Every live document that already exists is announced once, at revision 1,
--- so a consumer's first poll sees the whole library rather than only what
+-- Every live document that already exists is announced once, at its new
+-- random revision, so a consumer's first poll sees the whole library rather than only what
-- changes after this deploy. Live is the producer's definition: not deleted,
-- and not one of 0002_owners.sql's orphans, which nobody can read.
--- Their stamps are the migration's own time (julianday is milliseconds),
--- plus the row's position so no two are equal: a backup taken before this
--- migration and migrated again later gets different ones.
+-- Their stamps are random nonces like every other row's.
INSERT INTO suite_feed (document_id, revision, gone, touched_at, stamp)
- SELECT id, revision, 0, updated_at,
- CAST((julianday('now') - 2440587.5) * 86400000000000 AS INTEGER) + ROW_NUMBER() OVER (ORDER BY updated_at, id)
+ SELECT id, revision, 0, updated_at, (random() & 9223372036854775807) | 1
FROM documents
WHERE deleted_at IS NULL AND owner_id > 0
ORDER BY updated_at, id;
diff --git a/internal/docs/models.go b/internal/docs/models.go
index bf9a5a1..bac4ec5 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -61,10 +61,11 @@ type Document struct {
// (a test inserting a Document directly) is private, as 0009 makes every
// existing row, rather than an empty string the CHECK refuses.
Visibility Visibility `gorm:"column:visibility;not null;default:private"`
- // Revision moves 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 max(previous
- // + 1, now in unix microseconds), so a restore never reissues one.
+ // 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.
Revision int64 `gorm:"column:revision;not null;default:1"`
CreatedAt time.Time `gorm:"column:created_at;not null"`
@@ -96,9 +97,9 @@ type SuiteFeedRow struct {
Revision int64 `gorm:"column:revision;not null"`
Gone bool `gorm:"column:gone;not null"`
TouchedAt time.Time `gorm:"column:touched_at;not null"`
- // Stamp is the row's creation in unix nanoseconds, written once; the S1
- // cursor carries it so a cursor from before a restore is refused rather
- // than read as a position in a log that has since been rewritten.
+ // Stamp is a random nonce written once with the row; the S1 cursor
+ // carries it so a cursor from before a restore is refused rather than
+ // read as a position in a log that has since been rewritten.
Stamp int64 `gorm:"column:stamp;not null"`
}
diff --git a/internal/docs/store.go b/internal/docs/store.go
index 3aa14e3..a306d7b 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -300,9 +300,8 @@ func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token strin
// createDocument is CreateDraft with the rung chosen by the caller: team for
// every document a person makes, private for the sample library (seed.go),
// which is one person's welcome content and would otherwise sit in every
-// member's list. Creation writes its first revision (the clock, in unix
-// microseconds) and its suite_feed row in the same transaction as the
-// document.
+// member's list. Creation writes its first revision (random, newRevision)
+// and its suite_feed row in the same transaction as the document.
func (s *Store) createDocument(ctx context.Context, owner int64, title, token string, visibility Visibility) (*Document, error) {
if !visibility.valid() {
return nil, fmt.Errorf("docs: create document: unknown visibility %q", visibility)
@@ -331,9 +330,9 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st
GUID: guid,
ClientID: clientID,
Visibility: visibility,
- // The clock, as every later revision is (bumpRevision): a
+ // Random, as every later revision is (newRevision): a
// restore never reissues a value.
- Revision: revisionClock(),
+ Revision: newRevision(0),
CreatedAt: now,
UpdatedAt: now,
}
@@ -359,7 +358,7 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st
if err := tx.Create(doc).Error; err != nil {
return err
}
- if err := announce(tx, doc.ID, doc.Revision, false, now); err != nil {
+ if err := announce(tx, doc.ID, doc.Revision, false); err != nil {
return err
}
return s.requireMember(ctx, actor)
diff --git a/internal/docs/suite.go b/internal/docs/suite.go
index b1e84d8..c81900b 100644
--- a/internal/docs/suite.go
+++ b/internal/docs/suite.go
@@ -50,7 +50,7 @@ func liveDocuments(g *gorm.DB) *gorm.DB {
// Feed pages suite_feed by id.
//
-// The cursor is "<feed id>.<that row's stamp>" (unix nanoseconds, written
+// 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
@@ -189,6 +189,11 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
uncertain = standing == roster.Unknown
}
+ issued, err := p.issued(ctx, pairs, canRead)
+ if err != nil {
+ return nil, err
+ }
+
for i, pr := range pairs {
rev, can := canRead[pr.ItemID]
_, live := isLive[pr.ItemID]
@@ -206,17 +211,55 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
out[i] = suite.NOT_VISIBLE
case pr.Revision == rev:
out[i] = suite.VISIBLE
- case pr.Revision >= 1 && pr.Revision < rev:
+ case issued[pr]:
+ // A revision this document had, by Docs' own log: moved on.
out[i] = suite.STALE
default:
- // Ahead of Docs' own revision (a restore from backup, suite
- // §4.3), or below 1: a revision this log does not recognise.
+ // A revision this log never issued for this document — one
+ // from before a restore, or one never issued at all (suite
+ // §4.3): withheld loudly. Revisions are random, so there is no
+ // "ahead" or "behind" to read off the number.
out[i] = suite.UNKNOWN
}
}
return out, nil
}
+// issued is which of the asked (item, revision) pairs this log holds: a
+// revision suite_feed recorded for that document. Asked only for pairs the
+// asker may read at a revision that is not current, since only those turn
+// on it. Revisions are random, so the log is the only thing that can say a
+// revision is behind (doctrine §4.3: compare against your log).
+func (p *suiteProducer) issued(ctx context.Context, pairs []suite.ItemRevision, canRead map[string]int64) (map[suite.ItemRevision]bool, error) {
+ var ids []string
+ var revs []int64
+ for _, pr := range pairs {
+ if rev, can := canRead[pr.ItemID]; can && pr.Revision != rev {
+ ids = append(ids, pr.ItemID)
+ revs = append(revs, pr.Revision)
+ }
+ }
+ out := map[suite.ItemRevision]bool{}
+ if len(ids) == 0 {
+ return out, nil
+ }
+ var rows []struct {
+ Sqid string
+ Revision int64
+ }
+ if err := p.store.db.WithContext(ctx).Table("suite_feed").
+ Select("documents.sqid, suite_feed.revision").
+ Joins("JOIN documents ON documents.id = suite_feed.document_id").
+ Where("documents.sqid IN ? AND suite_feed.revision IN ?", ids, revs).
+ Scan(&rows).Error; err != nil {
+ return nil, err
+ }
+ for _, r := range rows {
+ out[suite.ItemRevision{ItemID: r.Sqid, Revision: r.Revision}] = true
+ }
+ return out, nil
+}
+
// liveRevisions is each live document's current revision, by sqid.
func (p *suiteProducer) liveRevisions(ctx context.Context, ids []string) (map[string]int64, error) {
var rows []struct {
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go
index 134080a..90743f7 100644
--- a/internal/docs/suite_feed.go
+++ b/internal/docs/suite_feed.go
@@ -2,6 +2,8 @@ package docs
import (
"context"
+ crand "crypto/rand"
+ "encoding/binary"
"errors"
"fmt"
"time"
@@ -13,55 +15,77 @@ import (
// the two rungs this column holds.
var errUnknownVisibility = errors.New("docs: unknown visibility")
-// announce appends one row to suite_feed. Called only inside the transaction
-// that made the change it records, so the log and the documents table can
-// never disagree about a committed revision (spec §8.2.2).
-func announce(tx *gorm.DB, docID, revision int64, gone bool, at time.Time) error {
- row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: at, Stamp: time.Now().UnixNano()}
+// suiteClock is the feed's clock, for touched_at only. Nothing the suite
+// contract matches on — a revision, a cursor's nonce — is read from it, so a
+// clock set back across a restore cannot make a value repeat. A variable so
+// a test can set it back and show exactly that.
+var suiteClock = time.Now
+
+// randomPositive is a fresh positive int63 from crypto/rand.
+func randomPositive() int64 {
+ for {
+ var b [8]byte
+ crand.Read(b[:])
+ if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 {
+ return n
+ }
+ }
+}
+
+// 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 0009, 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 random value repeats with probability 2^-63, 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 {
+ for {
+ if r := randomPositive(); r != current {
+ return r
+ }
+ }
+}
+
+// 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
+// committed revision (spec §8.2.2).
+func announce(tx *gorm.DB, docID, revision int64, gone bool) error {
+ row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: suiteClock().UTC(), Stamp: randomPositive()}
if err := tx.Create(row).Error; err != nil {
return fmt.Errorf("docs: announce document %d: %w", docID, err)
}
return nil
}
-// revisionClock is the floor a new revision is raised to: now, in unix
-// microseconds. Below 2^53 until the year 2255, so it survives a JSON
-// number on the wire.
-func revisionClock() int64 { return time.Now().UnixMicro() }
-
-// bumpRevision moves a document to its next revision 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 revision no
-// document has.
-//
-// The next revision is max(revision + 1, now in unix microseconds), never
-// simply revision + 1. After a restore from a backup, +1 would hand out
-// again a revision issued before the restore — for different content — and
-// a consumer holding the old (sqid, revision) would be told it is current
-// (Astra on oficina/docs feat/suite-producer, 2026-11-01: a private draft
-// backed up, renamed to confidential text, restored and shared with the
-// team, answered VISIBLE against the confidential copy). With the clock as
-// the floor every revision issued after the restore is later than any
-// issued before it, so the old copy reads STALE or UNKNOWN, withheld
-// loudly. Still +1 if the clock has not moved, so it is strictly monotonic.
+// bumpRevision moves a document to a new revision (newRevision) 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
+// revision no document has.
func bumpRevision(tx *gorm.DB, docID int64, gone bool) error {
+ var current int64
+ if err := tx.Model(&Document{}).Where("id = ?", docID).Select("revision").Scan(&current).Error; err != nil {
+ return fmt.Errorf("docs: read revision of document %d: %w", docID, err)
+ }
+ revision := newRevision(current)
// UpdateColumn, not Update: GORM's Update also stamps updated_at, and a
// bump is not an edit — the list's recency must not move on a rename of
// the rung or a deletion's bookkeeping.
- res := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", gorm.Expr("MAX(revision + 1, ?)", revisionClock()))
+ res := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", revision)
if res.Error != nil {
return fmt.Errorf("docs: bump revision of document %d: %w", docID, res.Error)
}
if res.RowsAffected != 1 {
return fmt.Errorf("docs: bump revision of document %d: %d rows", docID, res.RowsAffected)
}
- var revision int64
- if err := tx.Model(&Document{}).Where("id = ?", docID).Select("revision").Scan(&revision).Error; err != nil {
- return fmt.Errorf("docs: read revision of document %d: %w", docID, err)
- }
- return announce(tx, docID, revision, gone, time.Now().UTC())
+ return announce(tx, docID, revision, gone)
}
// SetVisibility moves a document between the private and team rungs (spec
diff --git a/internal/docs/suite_test.go b/internal/docs/suite_test.go
index bad8924..69478ee 100644
--- a/internal/docs/suite_test.go
+++ b/internal/docs/suite_test.go
@@ -13,16 +13,22 @@ import (
"strconv"
"strings"
"testing"
+ "testing/fstest"
"time"
"amadan.net/oficina/home/connect"
connectlinks "amadan.net/oficina/home/connect/linkstore"
+ "amadan.net/oficina/home/dashboard"
+ "amadan.net/oficina/home/handoff"
"amadan.net/oficina/home/roster"
"amadan.net/oficina/suite"
"amadan.net/oficina/suite/conformance"
"amadan.net/oficina/suite/server"
"amadan.net/rastrillo/rastrillo"
+ "amadan.net/rastrillo/rastrillo/db"
"amadan.net/rastrillo/rastrillo/migrate"
+ "amadan.net/rastrillo/rastrillo/sessions"
+ "github.com/carlosframework/docs/internal/docs/linkstore"
"gorm.io/gorm"
)
@@ -37,18 +43,26 @@ func suiteVector(t *testing.T, id string) []byte {
return b
}
-// setRevision puts a document at the fixture's revision and announces it,
-// as a bump would. The fixture numbers its revisions 2 to 11, and real bumps
-// jump to the clock (bumpRevision), 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.
+// 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
+// (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) {
t.Helper()
err := s.db.Transaction(func(tx *gorm.DB) error {
- if err := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", revision).Error; err != nil {
- return err
+ for _, r := range []int64{revision - 1, revision} {
+ if err := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", r).Error; err != nil {
+ return err
+ }
+ if err := announce(tx, docID, r, false); err != nil {
+ return err
+ }
}
- return announce(tx, docID, revision, false, time.Now().UTC())
+ return nil
})
if err != nil {
t.Fatal(err)
@@ -136,8 +150,8 @@ func seedCustody(t *testing.T, s *Store, asker, other custodyParty) {
}
}
if c.Rung == suite.RungDeleted {
- // Deleted through the real path; its last revision is the
- // clock's, which nothing asks about: a deleted item is
+ // 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)
if err := s.deleteDocument(ctx, doc.ID); err != nil {
@@ -277,8 +291,8 @@ func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
if err := app.store.db.Where("sqid = ?", strings.TrimPrefix(rec.Header().Get("Location"), "/d/")).First(&doc).Error; err != nil {
t.Fatal(err)
}
- if doc.Visibility != VisibilityTeam || doc.Revision < time.Now().Add(-time.Minute).UnixMicro() {
- t.Errorf("a new document: %q at revision %d, want team at the clock", doc.Visibility, doc.Revision)
+ if doc.Visibility != VisibilityTeam || doc.Revision < 1 {
+ t.Errorf("a new document: %q at revision %d, want team at a positive revision", doc.Visibility, doc.Revision)
}
samples := newSampleDocumentsInternalTestApp(t, "1")
@@ -336,11 +350,17 @@ func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
}
}
exec("0009_suite.sql")
- var private, atOne int
+ var private, distinct, low int
db.QueryRow(`SELECT COUNT(*) FROM documents WHERE visibility = 'private'`).Scan(&private)
- db.QueryRow(`SELECT COUNT(*) FROM documents WHERE revision = 1`).Scan(&atOne)
- if private != 4 || atOne != 4 {
- t.Errorf("an existing document: %d of 4 private, %d of 4 at revision 1", private, atOne)
+ db.QueryRow(`SELECT COUNT(DISTINCT revision) FROM documents`).Scan(&distinct)
+ db.QueryRow(`SELECT COUNT(*) FROM documents WHERE revision < 1000000`).Scan(&low)
+ if private != 4 || distinct != 4 || low != 0 {
+ t.Errorf("an existing document: %d of 4 private, %d distinct revisions, %d small ones; want 4, 4 random, 0", private, distinct, low)
+ }
+ var unmatched int
+ db.QueryRow(`SELECT COUNT(*) FROM suite_feed f JOIN documents d ON d.id = f.document_id WHERE f.revision != d.revision`).Scan(&unmatched)
+ if unmatched != 0 {
+ t.Errorf("%d backfilled rows announce a revision their document does not have", unmatched)
}
rows, err := db.Query(`SELECT document_id, stamp FROM suite_feed ORDER BY id`)
if err != nil {
@@ -352,8 +372,8 @@ func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
var id, stamp int64
rows.Scan(&id, &stamp)
fed = append(fed, id)
- if stamp < time.Now().Add(-time.Minute).UnixNano() || stamps[stamp] {
- t.Errorf("a backfilled stamp that is not the migration's own, distinct time: %d", stamp)
+ if stamp < 1 || stamps[stamp] {
+ t.Errorf("a backfilled stamp that is not a distinct positive nonce: %d", stamp)
}
stamps[stamp] = true
}
@@ -486,8 +506,8 @@ func TestSuiteTeamRungTeamMode(t *testing.T) {
// S1 as Docs serves it: pages in id order, a cursor "<id>.<stamp>", the tip
// returning the cursor given with no rows, any cursor Docs did not issue an
// error, a row per bump (update, rename, visibility change, deletion) at a
-// revision that is the clock's or later and strictly increasing, nothing
-// for a grant or an unchanged rung, gone only on deletion.
+// fresh positive revision, nothing for a grant or an unchanged rung, gone
+// only on deletion.
//
// MUTATION-TESTED 2026-11-01, each reverted: Rename without bumpRevision,
// ApplyUpdate without it, SetVisibility without it, and creation without
@@ -513,7 +533,6 @@ func TestSuiteFeed(t *testing.T) {
alice := app.TestPerson(t, "alice@example.com")
actor := app.TestActorForPerson(t, alice)
- before := revisionClock()
doc, _ := app.store.Create(ctx, alice, "One")
two, _ := app.store.Create(ctx, alice, "Two")
revs := []int64{revisionOf(t, app.store, doc.ID)}
@@ -539,18 +558,13 @@ func TestSuiteFeed(t *testing.T) {
app.TestSoftDelete(t, two.Sqid)
twoGone := revisionOf(t, app.store, two.ID)
- // Every revision is the clock's or later, and strictly increasing: a
- // restore can never hand one out again (bumpRevision).
- if revs[0] < before || twoBefore < before {
- t.Errorf("a first revision below the clock: %v, %d < %d", revs, twoBefore, before)
- }
- for k := 1; k < len(revs); k++ {
- if revs[k] <= revs[k-1] {
- t.Errorf("revisions not strictly increasing: %v", revs)
+ // Every revision is new: no two the same, none below 1 (newRevision).
+ seen := map[int64]bool{}
+ for _, r := range append(revs, twoBefore, twoGone) {
+ if r < 1 || seen[r] {
+ t.Errorf("revisions not fresh and positive: %v, %d, %d", revs, twoBefore, twoGone)
}
- }
- if twoGone <= twoBefore {
- t.Errorf("deletion did not move the revision: %d then %d", twoBefore, twoGone)
+ seen[r] = true
}
type step struct {
@@ -919,58 +933,208 @@ func TestSuiteConsumersMalformedRefusesBoot(t *testing.T) {
}
}
-// Astra's restore sequence (oficina/docs feat/suite-producer, 2026-11-01),
-// with a real SQLite backup: a private draft is backed up; it is renamed to
-// confidential text, and memoria holds that revision and the feed cursor
-// after it; the backup is restored and the harmless draft is shared with the
-// team. With revisions that counted up from the restored value, the team
-// share reissued the held revision, so S2 answered VISIBLE for a teammate
-// against the confidential copy, and S1 answered the held cursor with no
-// rows and the same cursor — silence for ever. Now the revision is later
-// than anything issued before the restore, and the old cursor is an error.
+// Astra's restore sequences (oficina/docs feat/suite-producer, two rounds,
+// 2026-11-01), with a real SQLite backup: a private draft is backed up; it
+// is renamed to confidential text, and memoria holds that revision and the
+// feed cursor after it; the backup is restored and the harmless draft is
+// shared with the team. With revisions counted up from the restored value
+// the share reissued the held revision, so S2 answered VISIBLE for a
+// teammate against the confidential copy, and S1 answered the held cursor
+// with no rows and the same cursor for ever. With revisions and nonces read
+// from a clock, the same happened when the restore landed on a clock set
+// back to the confidential edit's time ("clock set back"). Revisions and
+// nonces are random now, so neither repeats.
//
-// MUTATION-TESTED 2026-11-01, each reverted: bumpRevision as revision + 1
-// with creation at revision 1 → "VISIBLE against the confidential copy";
-// Feed without the stamp check (a bare id) → "the cursor from before the
-// restore".
+// MUTATION-TESTED 2026-11-01, each reverted: sequential revisions
+// (newRevision returning current + 1, creation at 1) → both subtests
+// VISIBLE against the confidential copy; time-based revisions and nonces
+// (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.
func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ // clock is suiteClock at each step, or nil for the real clock.
+ clock map[string]time.Time
+ }{
+ {"real clock", nil},
+ {"clock set back", map[string]time.Time{
+ "backup": time.Date(2026, 11, 1, 10, 0, 0, 0, time.UTC),
+ "confidential": time.Date(2026, 11, 1, 10, 10, 0, 0, time.UTC),
+ // The restore happens at 10:20 on a clock that reads 10:10.
+ "restored": time.Date(2026, 11, 1, 10, 10, 0, 0, time.UTC),
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ at := func(step string) {
+ if when, ok := tc.clock[step]; ok {
+ suiteClock = func() time.Time { return when }
+ }
+ }
+ t.Cleanup(func() { suiteClock = time.Now })
+ at("backup")
+ dir := t.TempDir()
+ path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db")
+ cfg := Config{DBPath: path, Env: "development", AllowedAddresses: "alice@example.com,bob@example.com"}
+ app, err := New(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ alice := app.TestPerson(t, "alice@example.com")
+ app.TestPerson(t, "bob@example.com")
+ doc := app.TestCreatePrivate(t, alice, "Draft")
+ if _, err := app.db.Writer().Exec("VACUUM INTO ?", backup); err != nil {
+ t.Fatal(err)
+ }
+ at("confidential")
+ if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Confidential: the acquisition"); err != nil {
+ t.Fatal(err)
+ }
+ held := revisionOf(t, app.store, doc.ID)
+ if body, err := app.suite.Content(ctx, doc.Sqid, held); err != nil || !strings.Contains(string(body), "Confidential") {
+ t.Fatalf("memoria's copy: %q %v", body, err)
+ }
+ cursor := feedTip(t, app.suite)
+ if err := app.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ restoreFile(t, backup, path)
+ at("restored")
+ restored, err := NewForTestWith(t, cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := restored.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityTeam); err != nil {
+ t.Fatal(err)
+ }
+ got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: doc.Sqid, Revision: held}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got[0] != suite.UNKNOWN {
+ t.Errorf("S2 for a teammate at the confidential copy's revision after the restore: %s, want UNKNOWN (not in the restored log)", got[0])
+ }
+ 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))
+ }
+ })
+ }
+}
+
+// Astra's second-round sequence: a backup taken BEFORE migration 0009. A
+// harmless document is granted to Bob and backed up; Bob is revoked and the
+// document renamed to confidential text; the suite is deployed (0009 runs)
+// and memoria holds the confidential revision; the pre-0009 backup is
+// restored and the new build boots, running 0009 again over the harmless,
+// Bob-granted document. A constant there gave it the same revision as the
+// confidential copy, and S2 answered VISIBLE for Bob. No clock involved.
+//
+// MUTATION-TESTED 2026-11-01, reverted: 0009 without its random UPDATE (every
+// existing document at revision 1, as before) → Bob VISIBLE.
+func TestSuiteRestoreOfAPre0009BackupIssuesNewRevisions(t *testing.T) {
dir := t.TempDir()
path, backup := filepath.Join(dir, "docs.db"), filepath.Join(dir, "backup.db")
+
+ // A database at 0008: the boot schema with Docs' own set cut before 0009.
+ old := fstest.MapFS{}
+ entries, err := fs.ReadDir(migrationFS, "migrations")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range entries {
+ if e.Name() < "0009" {
+ b, _ := fs.ReadFile(migrationFS, "migrations/"+e.Name())
+ old["migrations/"+e.Name()] = &fstest.MapFile{Data: b}
+ }
+ }
+ pre := migrate.Merge(migrate.MustFromFS(dashboard.Migrations, "oficina_dashboard"), sessions.Schema, authSchema, migrate.MustFromFS(old, "docs"), linkstore.Schema, migrate.MustFromFS(handoff.Migrations, "oficina_handoff"), migrate.MustFromFS(connectlinks.Migrations, connectlinks.SchemaNamespace))
+ d, err := db.Open(path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := migrate.Apply(context.Background(), d, pre); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now().UTC()
+ for _, q := range []struct {
+ sql string
+ args []any
+ }{
+ {`INSERT INTO people (id, email, created_at) VALUES (1, 'alice@example.com', ?), (2, 'bob@example.com', ?)`, []any{now, now}},
+ {`INSERT INTO documents (id, sqid, title, guid, client_id, created_at, updated_at, owner_id) VALUES (1, 'harmless01', 'Harmless', 'g', 1, ?, ?, 1)`, []any{now, now}},
+ {`INSERT INTO grants (doc_id, subject, role, created_by, created_at) VALUES (1, 'bob@example.com', 'reader', 1, ?)`, []any{now}},
+ } {
+ if _, err := d.Writer().Exec(q.sql, q.args...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err := d.Writer().Exec("VACUUM INTO ?", backup); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := d.Writer().Exec(`DELETE FROM grants`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := d.Writer().Exec(`UPDATE documents SET title = 'Confidential: the acquisition' WHERE id = 1`); err != nil {
+ t.Fatal(err)
+ }
+ if err := d.Close(); err != nil {
+ t.Fatal(err)
+ }
+
cfg := Config{DBPath: path, Env: "development", AllowedAddresses: "alice@example.com,bob@example.com"}
- app, err := New(cfg)
+ deployed, err := New(cfg)
if err != nil {
t.Fatal(err)
}
ctx := context.Background()
- alice := app.TestPerson(t, "alice@example.com")
- app.TestPerson(t, "bob@example.com")
- doc := app.TestCreatePrivate(t, alice, "Draft")
- if _, err := app.db.Writer().Exec("VACUUM INTO ?", backup); err != nil {
+ held := revisionOf(t, deployed.store, 1)
+ if body, err := deployed.suite.Content(ctx, "harmless01", held); err != nil || !strings.Contains(string(body), "Confidential") {
+ t.Fatalf("memoria's copy: %q %v", body, err)
+ }
+ if err := deployed.Close(); err != nil {
t.Fatal(err)
}
- if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Confidential: the acquisition"); err != nil {
+
+ restoreFile(t, backup, path)
+ restored, err := NewForTestWith(t, cfg)
+ if err != nil {
t.Fatal(err)
}
- held := revisionOf(t, app.store, doc.ID)
- if body, err := app.suite.Content(ctx, doc.Sqid, held); err != nil || !strings.Contains(string(body), "Confidential") {
- t.Fatalf("memoria's copy: %q %v", body, err)
+ got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: "harmless01", Revision: held}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got[0] != suite.UNKNOWN {
+ t.Errorf("S2 for Bob at the confidential copy's revision after restoring a pre-0009 backup: %s, want UNKNOWN", got[0])
}
+}
+
+// feedTip follows the feed to its tip and returns the cursor there.
+func feedTip(t *testing.T, p *suiteProducer) string {
+ t.Helper()
cursor := ""
for {
- f, err := app.suite.Feed(ctx, cursor, 100)
+ f, err := p.Feed(context.Background(), cursor, 100)
if err != nil {
t.Fatal(err)
}
if f.Cursor == cursor {
- break
+ return cursor
}
cursor = f.Cursor
}
- if err := app.Close(); err != nil {
- t.Fatal(err)
- }
+}
- // The restore: the backup over the live file, its journal gone.
+// restoreFile puts a backup over a closed database file, its journal gone,
+// as an operator restoring from a snapshot does.
+func restoreFile(t *testing.T, backup, path string) {
+ t.Helper()
for _, f := range []string{path + "-wal", path + "-shm"} {
os.Remove(f)
}
@@ -981,27 +1145,6 @@ func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) {
if err := os.WriteFile(path, b, 0o600); err != nil {
t.Fatal(err)
}
- restored, err := NewForTestWith(t, cfg)
- if err != nil {
- t.Fatal(err)
- }
- if err := restored.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityTeam); err != nil {
- t.Fatal(err)
- }
-
- got, err := restored.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "bob@example.com"}, []suite.ItemRevision{{ItemID: doc.Sqid, Revision: held}})
- if err != nil {
- t.Fatal(err)
- }
- if got[0] == suite.VISIBLE {
- t.Errorf("S2 for a teammate answered VISIBLE against the confidential copy (revision %d) after the restore", held)
- }
- 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))
- }
}
// A roster lease that runs out during an S2 call (Astra, 2026-11-01): before
@@ -1097,3 +1240,54 @@ func TestSuiteAChangeWithoutItsFeedRowDoesNotCommit(t *testing.T) {
t.Errorf("rows committed without their feed rows: updates %d→%d, documents %d→%d", updates, updatesAfter, docs, docsAfter)
}
}
+
+// STALE is decided by Docs' own log, not by comparing numbers (doctrine
+// §4.3): revisions are random, so a revision from this document's history
+// is STALE, one it never had — never issued, or another document's — is
+// UNKNOWN, whatever its size.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: Rule answering STALE for any
+// non-current revision without consulting the log → both "never issued"
+// cases and "another document's" STALE (and conformance's "one revision
+// ahead" STALE in both shapes); the log lookup not keyed on the document →
+// "another document's" STALE. (A first try at the second dropped the
+// document from the SQL in a way SQLite refused — red for a syntax error,
+// not the rule — and was redone as a valid query.)
+func TestSuiteStaleIsDecidedByTheLog(t *testing.T) {
+ app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ alice := app.TestPerson(t, "alice@example.com")
+ actor := app.TestActorForPerson(t, alice)
+ doc, _ := app.store.Create(ctx, alice, "One")
+ other, _ := app.store.Create(ctx, alice, "Two")
+ 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))
+ }
+ current := history[len(history)-1]
+ ask := []suite.ItemRevision{
+ {ItemID: doc.Sqid, Revision: history[0]},
+ {ItemID: doc.Sqid, Revision: history[1]},
+ {ItemID: doc.Sqid, Revision: current},
+ {ItemID: doc.Sqid, Revision: current - 1},
+ {ItemID: doc.Sqid, Revision: 1},
+ {ItemID: doc.Sqid, Revision: revisionOf(t, app.store, other.ID)},
+ }
+ got, err := app.suite.Rule(ctx, suite.Subject{Kind: suite.SubjectAddress, Value: "alice@example.com"}, ask)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []suite.Authorization{suite.STALE, suite.STALE, suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN}
+ names := []string{"first", "second", "current", "never issued (current - 1)", "never issued (1)", "another document's"}
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("%s: %s, want %s", names[i], got[i], want[i])
+ }
+ }
+}