oficina / docs Public

Docs: S2 checks standing after its last read; a random source seam with redraws tested

Astra round 3 on c4cb4ca:

- P1: the log (history) read ran after Rule's final standing check, so a
  lease that ran out during it answered VISIBLE for the team rung and
  ownership. The check now follows every read, with the grant-only reread
  kept; a "history" step hook and a third TestSuiteRuleLeaseRunsOutMidCall
  case (Astra's probe: want [UNKNOWN UNKNOWN VISIBLE STALE]).
- Coverage: randomSource (crypto/rand by default) feeds revisions and feed
  nonces; randomPositive and newRevision return an error when it cannot be
  read, and the change does not commit — no fallback. Tests force a zero
  draw (and a sign-bit-only one) then 7, and the current revision then the
  next, and a broken source.
- The focused history test now asks two documents in one batch at each
  other's old revisions, so mixing histories fails there.
- 0009's comment gives 62 bits for migrated values.

Mutations, each reverted and red: the standing check back before the
history read; no zero redraw; no current redraw; a time-based fallback for
a failed read; the log lookup keyed on revision alone.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 65acd671a6fa9614d66dc162105727a73aa3dfba parent e1ae695
5 files changed, +178 −40
  • internal/docs/migrations/0009_suite.sql +2 −1
  • internal/docs/store.go +6 −1
  • internal/docs/suite.go +14 −6
  • internal/docs/suite_feed.go +40 −13
  • internal/docs/suite_test.go +116 −19

CI passed — run details

diff --git a/internal/docs/migrations/0009_suite.sql b/internal/docs/migrations/0009_suite.sql
index 75b8143..60500ef 100644
--- a/internal/docs/migrations/0009_suite.sql
+++ b/internal/docs/migrations/0009_suite.sql
@@ -24,7 +24,8 @@ ALTER TABLE documents ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private'
-- 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.
+-- is ChaCha20 seeded from the OS; masked to 63 bits and forced odd, so never
+-- 0 and 62 random bits (spec §8.2.2 has the probabilities).
ALTER TABLE documents ADD COLUMN revision INTEGER NOT NULL DEFAULT 1
CHECK (revision >= 1);
UPDATE documents SET revision = (random() & 9223372036854775807) | 1;
diff --git a/internal/docs/store.go b/internal/docs/store.go
index a306d7b..08e899c 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -317,6 +317,11 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st
clientID := uint64(mrand.Int64())
now := time.Now().UTC()
+ revision, err := newRevision(0)
+ if err != nil {
+ return nil, err
+ }
+
var lastErr error
for attempt := 0; attempt < maxSqidAttempts; attempt++ {
sqid, err := newSqid()
@@ -332,7 +337,7 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st
Visibility: visibility,
// Random, as every later revision is (newRevision): a
// restore never reissues a value.
- Revision: newRevision(0),
+ Revision: revision,
CreatedAt: now,
UpdatedAt: now,
}
diff --git a/internal/docs/suite.go b/internal/docs/suite.go
index c81900b..d503e59 100644
--- a/internal/docs/suite.go
+++ b/internal/docs/suite.go
@@ -33,7 +33,8 @@ type suiteProducer struct {
// Bridge a signed-in request resolves through. nil outside team mode.
subjects homeSubjects
// step, when set, is called at named points: "asked" after the asker is
- // mapped, "read" after Rule's reads, "replayed" between Content's replay
+ // mapped, "read" after Rule's readable read, "history" after its log
+ // read (the last before standing is checked), "replayed" between Content's replay
// and its second read of the revision. Tests only: it is how a lease
// running out or a change landing mid-request is made to happen on
// demand, which nothing else can arrange.
@@ -178,6 +179,18 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
return nil, err
}
p.at("read")
+ issued, err := p.issued(ctx, pairs, canRead)
+ if err != nil {
+ return nil, err
+ }
+ p.at("history")
+ // Standing is asked here, after the LAST database read (Astra, round
+ // 3: asked before the history read, a lease that ran out during it
+ // answered VISIBLE from a membership that had lapsed). Still Member:
+ // every read above ran under a valid lease. Not Member: the readable
+ // set is read again, now without the membership clauses (Unknown is
+ // latched), and only what an address grant opens stays readable. The
+ // history read needs no repeat: it was asked for a superset.
uncertain := false
if access != nil {
standing := access.state()
@@ -189,11 +202,6 @@ 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]
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go
index 90743f7..387cf61 100644
--- a/internal/docs/suite_feed.go
+++ b/internal/docs/suite_feed.go
@@ -6,6 +6,7 @@ import (
"encoding/binary"
"errors"
"fmt"
+ "io"
"time"
"gorm.io/gorm"
@@ -21,13 +22,27 @@ var errUnknownVisibility = errors.New("docs: unknown visibility")
// 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 {
+// randomSource is where revisions and feed nonces come from: crypto/rand.
+// A variable so a test can force particular draws; a source that fails is
+// an error, and the change that wanted the value does not commit. Nothing
+// falls back to a clock, a counter or math/rand, which a restore or an
+// attacker could reproduce.
+var randomSource io.Reader = crand.Reader
+
+// errNoRandomness is a randomSource that could not be read.
+var errNoRandomness = errors.New("docs: no randomness for a revision or a feed nonce")
+
+// randomPositive is a fresh positive int63 from randomSource: eight bytes,
+// the sign bit cleared, and a zero drawn again (0 is memoria's "not a
+// sibling" value and below the column's CHECK).
+func randomPositive() (int64, error) {
for {
var b [8]byte
- crand.Read(b[:])
+ if _, err := io.ReadFull(randomSource, b[:]); err != nil {
+ return 0, errNoRandomness
+ }
if n := int64(binary.BigEndian.Uint64(b[:]) & (1<<63 - 1)); n != 0 {
- return n
+ return n, nil
}
}
}
@@ -39,14 +54,19 @@ func randomPositive() int64 {
// 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 {
+// 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) {
for {
- if r := randomPositive(); r != current {
- return r
+ r, err := randomPositive()
+ if err != nil {
+ return 0, err
+ }
+ if r != current {
+ return r, nil
}
}
}
@@ -56,7 +76,11 @@ func newRevision(current int64) int64 {
// 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()}
+ nonce, err := randomPositive()
+ if err != nil {
+ return err
+ }
+ row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: suiteClock().UTC(), Stamp: nonce}
if err := tx.Create(row).Error; err != nil {
return fmt.Errorf("docs: announce document %d: %w", docID, err)
}
@@ -74,7 +98,10 @@ func bumpRevision(tx *gorm.DB, docID int64, gone bool) error {
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)
+ revision, err := newRevision(current)
+ if err != nil {
+ return err
+ }
// 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.
diff --git a/internal/docs/suite_test.go b/internal/docs/suite_test.go
index 69478ee..976822d 100644
--- a/internal/docs/suite_test.go
+++ b/internal/docs/suite_test.go
@@ -3,6 +3,8 @@ package docs
import (
"bytes"
"context"
+ crand "crypto/rand"
+ "encoding/binary"
"errors"
"io/fs"
"net/http"
@@ -1147,17 +1149,21 @@ func restoreFile(t *testing.T, backup, path string) {
}
}
-// A roster lease that runs out during an S2 call (Astra, 2026-11-01): before
-// the reads, and after them. Either way what only membership opens — the
-// team rung, and ownership in team mode — is UNKNOWN, and an independent
-// address grant is still VISIBLE.
+// A roster lease that runs out during an S2 call (Astra, 2026-11-01, and
+// round 3 for the history read): before the reads, after the readable read,
+// and after the log read. Each way what only membership opens — the team
+// rung, and ownership in team mode — is UNKNOWN, and an independent address
+// grant still answers, VISIBLE at its current revision and STALE at one
+// from its log.
//
// MUTATION-TESTED 2026-11-01, each reverted: standing taken once in
// askerActor, before the reads (the old code) → "asked": doc-team and
// doc-private NOT_VISIBLE, and "read": both VISIBLE; the second read
-// skipped when standing has lapsed → "read": both VISIBLE.
+// skipped when standing has lapsed → "read": both VISIBLE; the standing
+// check moved back before the history read (round 2's order) → "history":
+// both VISIBLE, Astra's probe exactly.
func TestSuiteRuleLeaseRunsOutMidCall(t *testing.T) {
- for _, stage := range []string{"asked", "read"} {
+ for _, stage := range []string{"asked", "read", "history"} {
t.Run(stage, func(t *testing.T) {
_, p, clock, _, _ := teamCustodyStore(t)
p.step = func(at string) {
@@ -1166,12 +1172,12 @@ func TestSuiteRuleLeaseRunsOutMidCall(t *testing.T) {
}
}
got, err := p.Rule(context.Background(), suite.Subject{Kind: suite.SubjectPersonRef, Value: anaSubject}, []suite.ItemRevision{
- {ItemID: "doc-team", Revision: 7}, {ItemID: "doc-private", Revision: 4}, {ItemID: "doc-granted", Revision: 9},
+ {ItemID: "doc-team", Revision: 7}, {ItemID: "doc-private", Revision: 4}, {ItemID: "doc-granted", Revision: 9}, {ItemID: "doc-granted", Revision: 8},
})
if err != nil {
t.Fatal(err)
}
- want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE}
+ want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.STALE}
for i := range want {
if got[i] != want[i] {
t.Errorf("pair %d: %s, want %s", i, got[i], want[i])
@@ -1248,9 +1254,10 @@ func TestSuiteAChangeWithoutItsFeedRowDoesNotCommit(t *testing.T) {
//
// 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
+// cases and the cross-document ones STALE (and conformance's "one revision
+// ahead" STALE in both shapes); the log lookup not keyed on the document
+// (any history row with the asked revision counts) → the three
+// cross-document cases 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) {
@@ -1263,31 +1270,121 @@ func TestSuiteStaleIsDecidedByTheLog(t *testing.T) {
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)
+ historyOf := func(d *Document, titles ...string) []int64 {
+ h := []int64{revisionOf(t, app.store, d.ID)}
+ for _, title := range titles {
+ if err := app.store.Rename(ctx, actor, d, title); err != nil {
+ t.Fatal(err)
+ }
+ h = append(h, revisionOf(t, app.store, d.ID))
}
- history = append(history, revisionOf(t, app.store, doc.ID))
+ return h
}
+ history := historyOf(doc, "One, again", "One, once more")
+ otherHistory := historyOf(other, "Two, again")
current := history[len(history)-1]
+ // One batch, both documents, each asked at the other's old revisions:
+ // a log read that mixes the two documents' histories answers those
+ // STALE here, not only in conformance.
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)},
+ {ItemID: doc.Sqid, Revision: otherHistory[1]},
+ {ItemID: doc.Sqid, Revision: otherHistory[0]},
+ {ItemID: other.Sqid, Revision: history[0]},
+ {ItemID: other.Sqid, Revision: otherHistory[0]},
}
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"}
+ want := []suite.Authorization{suite.STALE, suite.STALE, suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.UNKNOWN, suite.STALE}
+ names := []string{"first", "second", "current", "never issued (current - 1)", "never issued (1)", "another document's current", "another document's old", "this one's old, asked of the other", "the other's own old"}
for i := range want {
if got[i] != want[i] {
t.Errorf("%s: %s, want %s", names[i], got[i], want[i])
}
}
}
+
+// scriptedRandom is a randomSource that hands out the bytes it was given, and
+// then fails.
+type scriptedRandom struct{ r *bytes.Reader }
+
+func (s scriptedRandom) Read(p []byte) (int, error) { return s.r.Read(p) }
+
+func draws(values ...uint64) scriptedRandom {
+ var b []byte
+ for _, v := range values {
+ b = binary.BigEndian.AppendUint64(b, v)
+ }
+ return scriptedRandom{bytes.NewReader(b)}
+}
+
+type brokenRandom struct{}
+
+func (brokenRandom) Read([]byte) (int, error) { return 0, errors.New("no entropy") }
+
+// The two redraws, forced (Astra, round 3: both survived the suite): a draw
+// of zero — directly, or a value that is zero once its sign bit is cleared —
+// is drawn again, and a draw equal to the document's current revision is
+// drawn again. And a source that fails is an error that stops the change:
+// nothing falls back to a value a restore or anybody else could reproduce.
+//
+// MUTATION-TESTED 2026-11-01, each reverted: randomPositive returning its
+// first draw whatever it is → "zero, then 7" gets 0 and "the sign bit" gets
+// 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.
+func TestSuiteRevisionsRedrawAndNeverFallBack(t *testing.T) {
+ t.Cleanup(func() { randomSource = crand.Reader })
+
+ randomSource = draws(0, 7)
+ if n, err := randomPositive(); err != nil || n != 7 {
+ t.Errorf("zero, then 7: %d %v", n, err)
+ }
+ randomSource = draws(1<<63, 11)
+ if n, err := randomPositive(); err != nil || n != 11 {
+ t.Errorf("the sign bit alone (zero once cleared), then 11: %d %v", n, err)
+ }
+ randomSource = draws(5, 9)
+ if n, err := newRevision(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)
+ }
+
+ app, err := NewForTest(t)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx := context.Background()
+ randomSource = crand.Reader
+ alice := app.TestPerson(t, "alice@example.com")
+ doc, err := app.store.Create(ctx, alice, "Kept")
+ if err != nil {
+ t.Fatal(err)
+ }
+ randomSource = brokenRandom{}
+ if _, err := randomPositive(); !errors.Is(err, errNoRandomness) {
+ t.Errorf("a broken source: %v, want errNoRandomness", err)
+ }
+ var before int64
+ app.store.db.Model(&Document{}).Count(&before)
+ if _, err := app.store.Create(ctx, alice, "Not made"); err == nil {
+ t.Error("a broken source: a document was created")
+ }
+ if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Not renamed"); err == nil {
+ t.Error("a broken source: a rename committed")
+ }
+ var after int64
+ app.store.db.Model(&Document{}).Count(&after)
+ if after != before || revisionOf(t, app.store, doc.ID) != doc.Revision {
+ t.Errorf("a broken source changed something: documents %d→%d, revision %d→%d", before, after, doc.Revision, revisionOf(t, app.store, doc.ID))
+ }
+}