oficina / docs Public

Docs: fix Astra's review of the suite producer (two P1s, a P2, a coverage gap)

1. Restore (P1). bumpRevision sets max(revision + 1, now in unix
   microseconds) and creation starts at the clock, so a database restored
   from a backup never reissues a revision; memoria's pre-restore copy
   reads STALE or UNKNOWN. suite_feed gains a write-once stamp (unix
   nanos); the S1 cursor is "<id>.<stamp>", checked every request, and a
   cursor that does not match, or that Docs did not issue, is an error
   (503) — never a page. 0009 is edited in place (unmerged, undeployed);
   its backfill stamps are the migration's time plus row number.
   TestSuiteRestoreNeverReissuesARevisionOrACursor is Astra's sequence with
   a real SQLite backup (VACUUM INTO, close, copy back, reopen).
2. Lease expiry (P1). Rule asks the latched team standing again after its
   reads; if it is no longer Member the readable set is read again without
   the membership clauses, so the team rung and ownership answer UNKNOWN
   and an address grant stays VISIBLE. A test-only step hook expires the
   lease before and after the reads (TestSuiteRuleLeaseRunsOutMidCall).
3. Guest 403 (P2). The lone-shape member guard honours item=true: share,
   revoke, publish and the team rung answer a guest 404, as team mode
   always has; create stays 403. TestAGuestCannotCreateOrShare now expects
   404 and adds a guest who owns a document, so the guard stays visible.
4. Coverage. TestSuiteAChangeWithoutItsFeedRowDoesNotCommit forces the
   feed insert to fail (a trigger) and checks rename, update, visibility,
   deletion and creation all roll back.

Fixture-world revisions are set directly (setRevision), since real bumps
now jump to the clock; tests that named revisions 1-4 read them instead.
Every new guard mutated and seen red; recorded in each test's comment.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 54640b4825094eb5d6b0b0cb68168824b609667e parent 750997a
8 files changed, +534 −140
  • internal/docs/guest_test.go +29 −7
  • internal/docs/migrations/0009_suite.sql +24 −7
  • internal/docs/models.go +8 −3
  • internal/docs/store.go +8 −5
  • internal/docs/suite.go +149 −55
  • internal/docs/suite_feed.go +18 −2
  • internal/docs/suite_test.go +289 −60
  • internal/docs/team_access.go +9 −1

CI passed — run details

diff --git a/internal/docs/guest_test.go b/internal/docs/guest_test.go
index 7524cb3..573050d 100644
--- a/internal/docs/guest_test.go
+++ b/internal/docs/guest_test.go
@@ -59,13 +59,35 @@ func TestAGuestCannotCreateOrShare(t *testing.T) {
// produces for Bob on Alice's document — so deleting the member guard
// from sharePost left it green. The re-review caught that by mutation:
// three of the four guarded routes had never been exercised at all.
- for _, c := range []struct{ what, path, body string }{
- {"share", "/d/" + sqid + "/share", "address=mallory@example.com&role=writer"},
- {"revoke", "/d/" + sqid + "/share/revoke", "address=alice@example.com"},
- {"publish", "/d/" + sqid + "/share/link", "on=1"},
- } {
- if rec := post(t, app, bob, c.path, c.body); rec.Code != http.StatusForbidden {
- t.Errorf("guest %s: status %d, want 403 from the member guard", c.what, rec.Code)
+ //
+ // 404 since 2026-11-01 (Astra): a route about one document answers a
+ // guest as one about a document they cannot reach, never 403, as team
+ // mode always has. The owner check answers Bob 404 on Alice's document
+ // too, so the guard is only visible on a document the guest OWNS: Carol
+ // below owns one (made before she lost her place on the list, say) and
+ // is admitted only by a grant. Without the guard her share would 303.
+ //
+ // MUTATION-TESTED 2026-11-01, each reverted: shareTeam without the
+ // member guard → "carol on her own, team rung" 303; the lone-shape guard
+ // answering 403 whatever item says (the old code) → every case 403.
+ carolsID := app.TestPerson(t, "carol@example.com")
+ carols := app.TestCreatePrivate(t, carolsID, "Carol's own").Sqid
+ post(t, app, alice, "/d/"+sqid+"/share", "address=carol@example.com&role=reader")
+ carol := signInCookies(t, app, "carol@example.com")
+ for _, who := range []struct {
+ name string
+ cookies []*http.Cookie
+ sqid string
+ }{{"bob on alice's", bob, sqid}, {"carol on her own", carol, carols}, {"bob on none", bob, "zzzzzzzzzz"}} {
+ for _, c := range []struct{ what, path, body string }{
+ {"share", "/share", "address=mallory@example.com&role=writer"},
+ {"revoke", "/share/revoke", "address=alice@example.com"},
+ {"publish", "/share/link", "on=1"},
+ {"team rung", "/share/team", "visibility=team"},
+ } {
+ if rec := post(t, app, who.cookies, "/d/"+who.sqid+c.path, c.body); rec.Code != http.StatusNotFound {
+ t.Errorf("guest %s, %s: status %d, want 404", who.name, c.what, rec.Code)
+ }
}
}
}
diff --git a/internal/docs/migrations/0009_suite.sql b/internal/docs/migrations/0009_suite.sql
index 0e3f8e0..82d21ce 100644
--- a/internal/docs/migrations/0009_suite.sql
+++ b/internal/docs/migrations/0009_suite.sql
@@ -12,32 +12,49 @@
ALTER TABLE documents ADD COLUMN visibility TEXT NOT NULL DEFAULT 'private'
CHECK (visibility IN ('private', 'team'));
--- revision: one counter per document, bumped in the same writer transaction
+-- revision: one counter per document, moved 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. Existing documents start at 1, which is also what a new
--- document is created at.
+-- 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.
ALTER TABLE documents ADD COLUMN revision INTEGER NOT NULL DEFAULT 1
CHECK (revision >= 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
-- a position in this table. No title, no content, no visibility: the four
--- fields suite S1 carries and nothing else, so the table holds nothing the
+-- 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).
CREATE TABLE IF NOT EXISTS suite_feed (
id INTEGER PRIMARY KEY AUTOINCREMENT,
document_id INTEGER NOT NULL,
revision INTEGER NOT NULL,
gone INTEGER NOT NULL CHECK (gone IN (0, 1)),
- touched_at DATETIME NOT NULL
+ touched_at DATETIME NOT NULL,
+ 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
-- 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.
-INSERT INTO suite_feed (document_id, revision, gone, touched_at)
- SELECT id, revision, 0, updated_at FROM documents
+-- 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.
+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)
+ 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 b3b336d..bf9a5a1 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -61,9 +61,10 @@ 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 counts the changes a suite consumer must re-read: every
- // applied update, rename, visibility change and deletion, bumped in the
- // same transaction (bumpRevision, suite.go). Starts at 1.
+ // 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 int64 `gorm:"column:revision;not null;default:1"`
CreatedAt time.Time `gorm:"column:created_at;not null"`
@@ -95,6 +96,10 @@ 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 int64 `gorm:"column:stamp;not null"`
}
// TableName pins the table rather than leaving it to GORM's pluralising.
diff --git a/internal/docs/store.go b/internal/docs/store.go
index 8d9c6e3..3aa14e3 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -300,8 +300,9 @@ 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 revision 1 and its suite_feed row in the
-// same transaction as the document.
+// 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.
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)
@@ -330,9 +331,11 @@ func (s *Store) createDocument(ctx context.Context, owner int64, title, token st
GUID: guid,
ClientID: clientID,
Visibility: visibility,
- Revision: 1,
- CreatedAt: now,
- UpdatedAt: now,
+ // The clock, as every later revision is (bumpRevision): a
+ // restore never reissues a value.
+ Revision: revisionClock(),
+ CreatedAt: now,
+ UpdatedAt: now,
}
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := s.requireMember(ctx, actor); err != nil {
diff --git a/internal/docs/suite.go b/internal/docs/suite.go
index 4fbb71a..b1e84d8 100644
--- a/internal/docs/suite.go
+++ b/internal/docs/suite.go
@@ -32,10 +32,12 @@ type suiteProducer struct {
// subjects resolves a Home subject in team mode, the same connect
// Bridge a signed-in request resolves through. nil outside team mode.
subjects homeSubjects
- // replayed, when set, runs between Content's replay and its second read
- // of the revision. Tests only: it is how a change landing mid-read is
- // made to happen on demand, which nothing else can arrange.
- replayed func()
+ // step, when set, is called at named points: "asked" after the asker is
+ // mapped, "read" after Rule's reads, "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.
+ step func(stage string)
}
var _ server.Producer = (*suiteProducer)(nil)
@@ -46,16 +48,32 @@ func liveDocuments(g *gorm.DB) *gorm.DB {
return g.Where("documents.deleted_at IS NULL AND documents.owner_id > 0")
}
-// Feed pages suite_feed by id. The cursor is the last id served, in decimal;
-// "" is the beginning, and a cursor that does not parse is answered from the
-// beginning too (a re-announce is always safe; a refusal would stall the
-// consumer on its own stored cursor). At the tip the cursor given comes back
-// unchanged with no rows, which is what ends a consumer's poll.
+// Feed pages suite_feed by id.
+//
+// The cursor is "<feed id>.<that row's stamp>" (unix nanoseconds, 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.
func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (suite.Feed, error) {
- after, err := strconv.ParseInt(cursor, 10, 64)
- valid := err == nil && after >= 0
- if !valid {
- after = 0
+ after, stamp, err := parseFeedCursor(cursor)
+ if err != nil {
+ return suite.Feed{}, err
+ }
+ db := p.store.db.WithContext(ctx)
+ if after > 0 {
+ var at []SuiteFeedRow
+ if err := db.Model(&SuiteFeedRow{}).Select("id", "stamp").Where("id = ?", after).Find(&at).Error; err != nil {
+ 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")
+ }
}
var rows []struct {
ID int64
@@ -63,9 +81,10 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui
Revision int64
Gone bool
TouchedAt time.Time
+ Stamp int64
}
- err = p.store.db.WithContext(ctx).Table("suite_feed").
- Select("suite_feed.id, documents.sqid, suite_feed.revision, suite_feed.gone, suite_feed.touched_at").
+ 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).
Order("suite_feed.id").
@@ -75,10 +94,10 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui
return suite.Feed{}, err
}
if len(rows) == 0 {
- // The tip: the cursor given, unchanged, so the consumer stops. A
- // cursor that did not parse ("" included) gets a real position to
- // come back with instead, never "" (outside the contract).
- if !valid {
+ // The tip: the cursor given, unchanged, so the consumer stops. ""
+ // becomes "0", the beginning, because the contract refuses an empty
+ // cursor.
+ if cursor == "" {
cursor = "0"
}
return suite.Feed{Cursor: cursor, Rows: []suite.FeedRow{}}, nil
@@ -87,16 +106,52 @@ func (p *suiteProducer) Feed(ctx context.Context, cursor string, limit int) (sui
for _, r := range rows {
feed.Rows = append(feed.Rows, suite.FeedRow{ItemID: r.Sqid, Revision: r.Revision, Gone: r.Gone, TouchedAt: r.TouchedAt.UTC()})
}
- feed.Cursor = strconv.FormatInt(rows[len(rows)-1].ID, 10)
+ last := rows[len(rows)-1]
+ feed.Cursor = strconv.FormatInt(last.ID, 10) + "." + strconv.FormatInt(last.Stamp, 10)
return feed, nil
}
+// 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) {
+ if c == "" || c == "0" {
+ return 0, 0, nil
+ }
+ 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 after, stamp, nil
+}
+
+func canonicalPositive(s string) (int64, bool) {
+ n, err := strconv.ParseInt(s, 10, 64)
+ if err != nil || n < 1 || strconv.FormatInt(n, 10) != s {
+ return 0, false
+ }
+ return n, true
+}
+
// Rule answers, per pair, whether the named asker may open the document now
// in Docs: the read predicate (permissionScope — ownership, a live grant,
// the team rung for a member; never a link) for the actor the asker maps to.
+//
+// In team mode standing is asked again AFTER the reads, from the request's
+// latched Access (Astra, 2026-11-01). A lease that ran out before the read
+// would otherwise answer NOT_VISIBLE for what membership opens, and one that
+// ran out after it would answer VISIBLE from a membership that has lapsed.
+// If standing is still Member the reads ran under a valid lease. If not, the
+// readable set is read again — now without the membership clauses, Unknown
+// being latched — so only what an address grant opens stays readable, and
+// what only membership would open is UNKNOWN (standing Unknown) or
+// NOT_VISIBLE (NotMember).
func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []suite.ItemRevision) ([]suite.Authorization, error) {
out := make([]suite.Authorization, len(pairs))
- actor, ctx, uncertain, keyed, err := p.askerActor(ctx, asker)
+ actor, ctx, access, keyed, err := p.askerActor(ctx, asker)
if err != nil {
return nil, err
}
@@ -109,39 +164,36 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
}
return out, nil
}
+ p.at("asked")
ids := make([]string, 0, len(pairs))
for _, pr := range pairs {
ids = append(ids, pr.ItemID)
}
- db := p.store.db.WithContext(ctx)
-
- type current struct {
- Sqid string
- Revision int64
- }
- var live, readable []current
- if err := liveDocuments(db.Model(&Document{})).Where("documents.sqid IN ?", ids).
- Select("documents.sqid, documents.revision").Scan(&live).Error; err != nil {
+ isLive, err := p.liveRevisions(ctx, ids)
+ if err != nil {
return nil, err
}
- if err := p.store.permissionScope(ctx, db.Model(&Document{}), actor, permissionRead).
- Where("documents.sqid IN ? AND documents.deleted_at IS NULL", ids).
- Select("documents.sqid, documents.revision").Scan(&readable).Error; err != nil {
+ canRead, err := p.readable(ctx, actor, ids)
+ if err != nil {
return nil, err
}
- isLive := make(map[string]bool, len(live))
- for _, d := range live {
- isLive[d.Sqid] = true
- }
- canRead := make(map[string]int64, len(readable))
- for _, d := range readable {
- canRead[d.Sqid] = d.Revision
+ p.at("read")
+ uncertain := false
+ if access != nil {
+ standing := access.state()
+ if standing != roster.Member {
+ if canRead, err = p.readable(ctx, actor, ids); err != nil {
+ return nil, err
+ }
+ }
+ uncertain = standing == roster.Unknown
}
for i, pr := range pairs {
rev, can := canRead[pr.ItemID]
+ _, live := isLive[pr.ItemID]
switch {
- case !isLive[pr.ItemID]:
+ case !live:
// Deleted, or never existed.
out[i] = suite.NOT_VISIBLE
case !can && uncertain:
@@ -165,9 +217,53 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
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 {
+ Sqid string
+ Revision int64
+ }
+ if err := liveDocuments(p.store.db.WithContext(ctx).Model(&Document{})).Where("documents.sqid IN ?", ids).
+ Select("documents.sqid, documents.revision").Scan(&rows).Error; err != nil {
+ return nil, err
+ }
+ out := make(map[string]int64, len(rows))
+ for _, r := range rows {
+ out[r.Sqid] = r.Revision
+ }
+ return out, nil
+}
+
+// readable is the documents among ids the actor may read now, with their
+// revisions: permissionScope, under ctx's standing.
+func (p *suiteProducer) readable(ctx context.Context, actor Actor, ids []string) (map[string]int64, error) {
+ var rows []struct {
+ Sqid string
+ Revision int64
+ }
+ if err := p.store.permissionScope(ctx, p.store.db.WithContext(ctx).Model(&Document{}), actor, permissionRead).
+ Where("documents.sqid IN ? AND documents.deleted_at IS NULL", ids).
+ Select("documents.sqid, documents.revision").Scan(&rows).Error; err != nil {
+ return nil, err
+ }
+ out := make(map[string]int64, len(rows))
+ for _, r := range rows {
+ out[r.Sqid] = r.Revision
+ }
+ return out, nil
+}
+
+// at runs the test-only step hook, if one is set.
+func (p *suiteProducer) at(stage string) {
+ if p.step != nil {
+ p.step(stage)
+ }
+}
+
// askerActor maps the asker to the actor Docs keys on in its current shape,
// and returns the context permissionScope must read it under. keyed is false
-// for an asker of the other kind. uncertain is team standing Unknown.
+// for an asker of the other kind. access is the request's latched team
+// standing, nil in lone shape.
//
// Lone shape keys on an address: the front door first (a configured member,
// or a holder of a live grant, as requireAdmission asks on every request),
@@ -180,41 +276,41 @@ func (p *suiteProducer) Rule(ctx context.Context, asker suite.Subject, pairs []s
// (identityResolver.resolve), and the roster standing for that subject. A
// subject with no Docs principal yet is an actor with no person, which reads
// the team rung by standing alone and nothing else.
-func (p *suiteProducer) askerActor(ctx context.Context, asker suite.Subject) (actor Actor, out context.Context, uncertain, keyed bool, err error) {
+func (p *suiteProducer) askerActor(ctx context.Context, asker suite.Subject) (actor Actor, out context.Context, access *requestAccess, keyed bool, err error) {
s := p.store
if s.team == nil {
if asker.Kind != suite.SubjectAddress {
- return Actor{}, ctx, false, false, nil
+ return Actor{}, ctx, nil, false, nil
}
address := subjectOf(asker.Value)
admitted, err := p.list.allows(address)
if err != nil {
- return Actor{}, ctx, false, true, err
+ return Actor{}, ctx, nil, true, err
}
if !admitted {
- return Actor{}, ctx, false, true, nil
+ return Actor{}, ctx, nil, true, nil
}
var person Person
err = s.db.WithContext(ctx).Where("email = ?", address).First(&person).Error
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
- return Actor{VerifiedAddress: &address}, ctx, false, true, nil
+ return Actor{VerifiedAddress: &address}, ctx, nil, true, nil
case err != nil:
- return Actor{}, ctx, false, true, err
+ return Actor{}, ctx, nil, true, err
}
- return localActor(person.ID, address), ctx, false, true, nil
+ return localActor(person.ID, address), ctx, nil, true, nil
}
if asker.Kind != suite.SubjectPersonRef {
- return Actor{}, ctx, false, false, nil
+ return Actor{}, ctx, nil, false, nil
}
subject := asker.Value
actor, err = p.homeActor(ctx, subject)
if err != nil {
- return Actor{}, ctx, false, true, err
+ return Actor{}, ctx, nil, true, err
}
a := s.team.resolveAccess(ctx, requestIdentity{Actor: actor, HomeSubject: subject})
- return actor, withAccess(ctx, a), a.state() == roster.Unknown, true, nil
+ return actor, withAccess(ctx, a), a, true, nil
}
// homeActor is a Home subject's actor in team mode, or the empty actor when
@@ -260,9 +356,7 @@ func (p *suiteProducer) Content(ctx context.Context, itemID string, revision int
if err != nil {
return nil, err
}
- if p.replayed != nil {
- p.replayed()
- }
+ p.at("replayed")
again, err := p.liveDocument(ctx, itemID)
if err != nil {
return nil, err
diff --git a/internal/docs/suite_feed.go b/internal/docs/suite_feed.go
index 04aa5df..134080a 100644
--- a/internal/docs/suite_feed.go
+++ b/internal/docs/suite_feed.go
@@ -17,24 +17,40 @@ var errUnknownVisibility = errors.New("docs: unknown visibility")
// 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}
+ row := &SuiteFeedRow{DocumentID: docID, Revision: revision, Gone: gone, TouchedAt: at, Stamp: time.Now().UnixNano()}
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.
func bumpRevision(tx *gorm.DB, docID int64, gone bool) error {
// 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("revision + 1"))
+ res := tx.Model(&Document{}).Where("id = ?", docID).UpdateColumn("revision", gorm.Expr("MAX(revision + 1, ?)", revisionClock()))
if res.Error != nil {
return fmt.Errorf("docs: bump revision of document %d: %w", docID, res.Error)
}
diff --git a/internal/docs/suite_test.go b/internal/docs/suite_test.go
index ae40c8b..bad8924 100644
--- a/internal/docs/suite_test.go
+++ b/internal/docs/suite_test.go
@@ -37,25 +37,32 @@ func suiteVector(t *testing.T, id string) []byte {
return b
}
-// bumpTo moves a document's revision up to target through bumpRevision, the
-// path every real change takes, so the feed carries a row per step.
-func bumpTo(t *testing.T, s *Store, docID, target int64) {
+// 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.
+func setRevision(t *testing.T, s *Store, docID, revision int64) {
t.Helper()
- for {
- var d Document
- if err := s.db.First(&d, docID).Error; err != nil {
- t.Fatal(err)
- }
- if d.Revision == target {
- return
- }
- if d.Revision > target {
- t.Fatalf("document %d is at revision %d, past %d", docID, d.Revision, target)
- }
- if err := s.db.Transaction(func(tx *gorm.DB) error { return bumpRevision(tx, docID, false) }); err != nil {
- t.Fatal(err)
+ 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
}
+ return announce(tx, docID, revision, false, time.Now().UTC())
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+// revisionOf is a document's current revision.
+func revisionOf(t *testing.T, s *Store, docID int64) int64 {
+ t.Helper()
+ var d Document
+ if err := s.db.First(&d, docID).Error; err != nil {
+ t.Fatal(err)
}
+ return d.Revision
}
// custodyParty is somebody in the custody fixture's world: the person id and
@@ -68,7 +75,7 @@ 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 reached by real bumps. The fixture's ids are not
+// and the case's revision (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
@@ -129,16 +136,15 @@ func seedCustody(t *testing.T, s *Store, asker, other custodyParty) {
}
}
if c.Rung == suite.RungDeleted {
- bumpTo(t, s, doc.ID, c.Revision-1)
+ // Deleted through the real path; its last revision is the
+ // clock's, 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 {
t.Fatal(err)
}
} else {
- bumpTo(t, s, doc.ID, c.Revision)
- }
- var got Document
- if err := s.db.First(&got, doc.ID).Error; err != nil || got.Revision != c.Revision {
- t.Fatalf("%s: seeded at revision %d, want %d (%v)", c.ItemID, got.Revision, c.Revision, err)
+ setRevision(t, s, doc.ID, c.Revision)
}
}
}
@@ -271,8 +277,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 != 1 {
- t.Errorf("a new document: %q at revision %d, want team at 1", doc.Visibility, doc.Revision)
+ 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)
}
samples := newSampleDocumentsInternalTestApp(t, "1")
@@ -336,15 +342,20 @@ func TestSuiteNewDocumentsAreTeamAndExistingArePrivate(t *testing.T) {
if private != 4 || atOne != 4 {
t.Errorf("an existing document: %d of 4 private, %d of 4 at revision 1", private, atOne)
}
- rows, err := db.Query(`SELECT document_id FROM suite_feed ORDER BY id`)
+ rows, err := db.Query(`SELECT document_id, stamp FROM suite_feed ORDER BY id`)
if err != nil {
t.Fatal(err)
}
var fed []int64
+ stamps := map[int64]bool{}
for rows.Next() {
- var id int64
- rows.Scan(&id)
+ 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)
+ }
+ stamps[stamp] = true
}
rows.Close()
if len(fed) != 2 || fed[0] != 1 || fed[1] != 4 {
@@ -472,17 +483,19 @@ func TestSuiteTeamRungTeamMode(t *testing.T) {
}
}
-// S1 as Docs serves it: pages in id order, a cursor that is the last id, the
-// tip returning the cursor given with no rows, a malformed cursor answered
-// from the beginning, a row per bump (update, rename, visibility change,
-// deletion), nothing for a grant or an unchanged rung, gone only on deletion.
+// 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.
//
// MUTATION-TESTED 2026-11-01, each reverted: Rename without bumpRevision,
// ApplyUpdate without it, SetVisibility without it, and creation without
// its announce → each a missing row in the feed comparison; SetVisibility
// bumping when nothing changed → an extra row; deleteDocument announcing
// gone=false → "(gone)"; Feed returning "" at an empty tip → "empty tip";
-// Feed ignoring the cursor → "the cursor came back unchanged with rows".
+// Feed ignoring the cursor → "the cursor came back unchanged with rows";
+// Feed not checking the stamp → cursor "2.1" answered a page.
func TestSuiteFeed(t *testing.T) {
app, err := NewForTest(t)
if err != nil {
@@ -500,32 +513,54 @@ 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)}
if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil {
t.Fatal(err)
}
+ revs = append(revs, revisionOf(t, app.store, doc.ID))
if err := app.store.Rename(ctx, actor, doc, "One, renamed"); err != nil {
t.Fatal(err)
}
+ revs = append(revs, revisionOf(t, app.store, doc.ID))
if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil {
t.Fatal(err)
}
+ revs = append(revs, revisionOf(t, app.store, doc.ID))
if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err != nil {
t.Fatal(err)
}
if err := app.store.Grant(ctx, alice, doc.Sqid, "bob@example.com", RoleReader); err != nil {
t.Fatal(err)
}
+ twoBefore := revisionOf(t, app.store, two.ID)
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)
+ }
+ }
+ if twoGone <= twoBefore {
+ t.Errorf("deletion did not move the revision: %d then %d", twoBefore, twoGone)
+ }
type step struct {
sqid string
rev int64
gone bool
}
- want := []step{{doc.Sqid, 1, false}, {two.Sqid, 1, false}, {doc.Sqid, 2, false}, {doc.Sqid, 3, false}, {doc.Sqid, 4, false}, {two.Sqid, 2, true}}
+ want := []step{{doc.Sqid, revs[0], false}, {two.Sqid, twoBefore, false}, {doc.Sqid, revs[1], false}, {doc.Sqid, revs[2], false}, {doc.Sqid, revs[3], false}, {two.Sqid, twoGone, true}}
var got []step
+ var cursors []string
cursor := ""
for page := 0; page < 10; page++ {
f, err := p.Feed(ctx, cursor, 2)
@@ -548,25 +583,30 @@ func TestSuiteFeed(t *testing.T) {
got = append(got, step{r.ItemID, r.Revision, r.Gone})
}
cursor = f.Cursor
+ cursors = append(cursors, cursor)
}
if len(got) != len(want) {
t.Fatalf("feed %+v, want %+v (rename, unchanged rung, grant)", got, want)
}
- for i := range want {
- if got[i] != want[i] {
- t.Errorf("row %d: %+v, want %+v (gone)", i, got[i], want[i])
+ for k := range want {
+ if got[k] != want[k] {
+ t.Errorf("row %d: %+v, want %+v (gone)", k, got[k], want[k])
}
}
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)
}
- if bad, _ := p.Feed(ctx, "not-a-cursor", 100); len(bad.Rows) != len(want) {
- t.Errorf("a malformed cursor: %d rows, want the whole feed again", len(bad.Rows))
+ // 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.
+ 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))
+ }
}
- var current Document
- app.store.db.First(&current, doc.ID)
- if current.Revision != 4 {
- t.Errorf("document revision %d, want 4", current.Revision)
+ if f, err := p.Feed(ctx, cursors[0], 100); err != nil || len(f.Rows) != len(want)-2 {
+ t.Errorf("a cursor Docs issued: %d rows, %v", len(f.Rows), err)
}
}
@@ -623,26 +663,29 @@ func TestSuiteRuleLoneShape(t *testing.T) {
}
}
- expect("wrong kind", ask(suite.SubjectPersonRef, "alice@example.com", pr(own, 1), pr(private, 1)), suite.UNKNOWN, suite.UNKNOWN)
+ rev := func(d *Document) int64 { return revisionOf(t, app.store, d.ID) }
+ first := rev(own)
+ expect("wrong kind", ask(suite.SubjectPersonRef, "alice@example.com", pr(own, first), pr(private, rev(private))), suite.UNKNOWN, suite.UNKNOWN)
expect("the owner", ask(suite.SubjectAddress, "Alice@Example.com",
- pr(own, 1), pr(own, 0), pr(own, 2), pr(private, 1), suite.ItemRevision{ItemID: "no-such-sqid", Revision: 1}, pr(gone, 2)),
+ pr(own, first), pr(own, 0), pr(own, first+1), pr(private, rev(private)), suite.ItemRevision{ItemID: "no-such-sqid", Revision: 1}, pr(gone, rev(gone))),
suite.VISIBLE, suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE)
if _, err := app.store.ApplyUpdate(ctx, own, app.TestActorForPerson(t, alice), ReadFragmentFixture(t, "hello")); err != nil {
t.Fatal(err)
}
- expect("behind", ask(suite.SubjectAddress, "alice@example.com", pr(own, 1), pr(own, 2)), suite.STALE, suite.VISIBLE)
- expect("a member who never signed in", ask(suite.SubjectAddress, "newcomer@example.com", pr(own, 2), pr(private, 1), pr(linked, 1)),
+ now := rev(own)
+ expect("behind", ask(suite.SubjectAddress, "alice@example.com", pr(own, first), pr(own, now)), suite.STALE, suite.VISIBLE)
+ expect("a member who never signed in", ask(suite.SubjectAddress, "newcomer@example.com", pr(own, now), pr(private, rev(private)), pr(linked, rev(linked))),
suite.VISIBLE, suite.NOT_VISIBLE, suite.NOT_VISIBLE)
- expect("a grantee who never signed in", ask(suite.SubjectAddress, "invitee@example.com", pr(granted, 1), pr(own, 2)),
+ expect("a grantee who never signed in", ask(suite.SubjectAddress, "invitee@example.com", pr(granted, rev(granted)), pr(own, now)),
suite.VISIBLE, suite.NOT_VISIBLE)
- expect("a refused address", ask(suite.SubjectAddress, "stranger@example.com", pr(own, 2), pr(linked, 1)),
+ expect("a refused address", ask(suite.SubjectAddress, "stranger@example.com", pr(own, now), pr(linked, rev(linked))),
suite.NOT_VISIBLE, suite.NOT_VISIBLE)
// Somebody taken off the allowlist who still owns a document: the front
// door refuses them on every request (requireAdmission), so S2 must too,
// although ownership alone would otherwise open it.
former := app.TestPerson(t, "former@example.com")
theirs := app.TestCreatePrivate(t, former, "Theirs")
- expect("a refused address that owns a document", ask(suite.SubjectAddress, "former@example.com", pr(theirs, 1)), suite.NOT_VISIBLE)
+ expect("a refused address that owns a document", ask(suite.SubjectAddress, "former@example.com", pr(theirs, rev(theirs))), suite.NOT_VISIBLE)
var n int64
app.store.db.Model(&Person{}).Where("email IN ?", []string{"newcomer@example.com", "invitee@example.com", "stranger@example.com"}).Count(&n)
if n != 0 {
@@ -729,42 +772,49 @@ func TestSuiteContent(t *testing.T) {
alice := app.TestPerson(t, "alice@example.com")
actor := app.TestActorForPerson(t, alice)
doc, _ := app.store.Create(ctx, alice, "Minutes")
+ created := revisionOf(t, app.store, doc.ID)
if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err != nil {
t.Fatal(err)
}
- body, err := app.suite.Content(ctx, doc.Sqid, 2)
+ current := revisionOf(t, app.store, doc.ID)
+ body, err := app.suite.Content(ctx, doc.Sqid, current)
if err != nil || string(body) != "Minutes\n\nhello world" {
t.Errorf("titled: %q %v", body, err)
}
- if _, err := app.suite.Content(ctx, doc.Sqid, 1); !errors.Is(err, suite.ErrNotAvailable) {
+ if _, err := app.suite.Content(ctx, doc.Sqid, created); !errors.Is(err, suite.ErrNotAvailable) {
t.Errorf("an old revision: %v", err)
}
- if _, err := app.suite.Content(ctx, doc.Sqid, 3); !errors.Is(err, suite.ErrNotAvailable) {
+ if _, err := app.suite.Content(ctx, doc.Sqid, current+1); !errors.Is(err, suite.ErrNotAvailable) {
t.Errorf("a future revision: %v", err)
}
untitled, _ := app.store.Create(ctx, alice, "")
if _, err := app.store.ApplyUpdate(ctx, untitled, actor, ReadFragmentFixture(t, "hello")); err != nil {
t.Fatal(err)
}
- if body, err := app.suite.Content(ctx, untitled.Sqid, 2); err != nil || string(body) != "hello world" {
+ if body, err := app.suite.Content(ctx, untitled.Sqid, revisionOf(t, app.store, untitled.ID)); err != nil || string(body) != "hello world" {
t.Errorf("untitled: %q %v", body, err)
}
// A rename that lands while the text is being replayed: the body read
- // is the old title's, so it must not go out labelled revision 2.
- app.suite.replayed = func() {
- app.suite.replayed = nil
+ // is the old title's, so it must not go out labelled with the revision
+ // it was asked at.
+ app.suite.step = func(stage string) {
+ if stage != "replayed" {
+ return
+ }
+ app.suite.step = nil
if err := app.store.Rename(ctx, actor, doc, "Minutes, renamed"); err != nil {
t.Fatal(err)
}
}
- if body, err := app.suite.Content(ctx, doc.Sqid, 2); !errors.Is(err, suite.ErrNotAvailable) {
+ if body, err := app.suite.Content(ctx, doc.Sqid, current); !errors.Is(err, suite.ErrNotAvailable) {
t.Errorf("a change during the read: %q %v, want not available", body, err)
}
- if body, err := app.suite.Content(ctx, doc.Sqid, 3); err != nil || string(body) != "Minutes, renamed\n\nhello world" {
+ renamed := revisionOf(t, app.store, doc.ID)
+ if body, err := app.suite.Content(ctx, doc.Sqid, renamed); err != nil || string(body) != "Minutes, renamed\n\nhello world" {
t.Errorf("after the rename: %q %v", body, err)
}
app.TestSoftDelete(t, doc.Sqid)
- if _, err := app.suite.Content(ctx, doc.Sqid, 4); !errors.Is(err, suite.ErrNotAvailable) {
+ if _, err := app.suite.Content(ctx, doc.Sqid, revisionOf(t, app.store, doc.ID)); !errors.Is(err, suite.ErrNotAvailable) {
t.Errorf("deleted: %v", err)
}
}
@@ -868,3 +918,182 @@ 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.
+//
+// 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".
+func TestSuiteRestoreNeverReissuesARevisionOrACursor(t *testing.T) {
+ 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)
+ }
+ 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 := ""
+ for {
+ f, err := app.suite.Feed(ctx, cursor, 100)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if f.Cursor == cursor {
+ break
+ }
+ cursor = f.Cursor
+ }
+ if err := app.Close(); err != nil {
+ t.Fatal(err)
+ }
+
+ // The restore: the backup over the live file, its journal gone.
+ for _, f := range []string{path + "-wal", path + "-shm"} {
+ os.Remove(f)
+ }
+ b, err := os.ReadFile(backup)
+ if err != nil {
+ t.Fatal(err)
+ }
+ 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
+// 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.
+//
+// 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.
+func TestSuiteRuleLeaseRunsOutMidCall(t *testing.T) {
+ for _, stage := range []string{"asked", "read"} {
+ t.Run(stage, func(t *testing.T) {
+ _, p, clock, _, _ := teamCustodyStore(t)
+ p.step = func(at string) {
+ if at == stage {
+ clock.step(61 * time.Second)
+ }
+ }
+ 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},
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := []suite.Authorization{suite.UNKNOWN, suite.UNKNOWN, suite.VISIBLE}
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("pair %d: %s, want %s", i, got[i], want[i])
+ }
+ }
+ })
+ }
+}
+
+// Every change and its feed row are one transaction: when the feed row
+// cannot be written, the change does not commit either. A rename committed
+// without its row would leave a consumer holding a title the feed never
+// told it had changed (Astra, 2026-11-01: swallowing the insert's error
+// survived the suite).
+//
+// MUTATION-TESTED 2026-11-01, each reverted: bumpRevision returning nil
+// when announce fails → rename, update, visibility and deletion all commit;
+// createDocument ignoring announce's error → "create".
+func TestSuiteAChangeWithoutItsFeedRowDoesNotCommit(t *testing.T) {
+ 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, "Before")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := app.db.Writer().Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
+ t.Fatal(err)
+ }
+ var updates, docs int64
+ app.store.db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Count(&updates)
+ app.store.db.Model(&Document{}).Count(&docs)
+ rev := revisionOf(t, app.store, doc.ID)
+
+ if err := app.store.Rename(ctx, actor, doc, "After"); err == nil {
+ t.Error("rename: succeeded without its feed row")
+ }
+ if _, err := app.store.ApplyUpdate(ctx, doc, actor, ReadFragmentFixture(t, "hello")); err == nil {
+ t.Error("update: succeeded without its feed row")
+ }
+ if err := app.store.SetVisibility(ctx, alice, doc.Sqid, VisibilityPrivate); err == nil {
+ t.Error("visibility: succeeded without its feed row")
+ }
+ if err := app.store.deleteDocument(ctx, doc.ID); err == nil {
+ t.Error("deletion: succeeded without its feed row")
+ }
+ if _, err := app.store.Create(ctx, alice, "New"); err == nil {
+ t.Error("create: succeeded without its feed row")
+ }
+
+ var after Document
+ if err := app.store.db.First(&after, doc.ID).Error; err != nil {
+ t.Fatal(err)
+ }
+ if after.Title != "Before" || after.Visibility != VisibilityTeam || after.DeletedAt != nil || after.Revision != rev {
+ t.Errorf("a change committed without its feed row: %+v", after)
+ }
+ var updatesAfter, docsAfter int64
+ app.store.db.Model(&DocUpdate{}).Where("doc_id = ?", doc.ID).Count(&updatesAfter)
+ app.store.db.Model(&Document{}).Count(&docsAfter)
+ if updatesAfter != updates || docsAfter != docs {
+ t.Errorf("rows committed without their feed rows: updates %d→%d, documents %d→%d", updates, updatesAfter, docs, docsAfter)
+ }
+}
diff --git a/internal/docs/team_access.go b/internal/docs/team_access.go
index d5ef804..645cc74 100644
--- a/internal/docs/team_access.go
+++ b/internal/docs/team_access.go
@@ -236,7 +236,15 @@ func (h *handlers) requireMemberRequest(w http.ResponseWriter, r *http.Request,
if h.member(r) {
return true
}
- h.fail(w, r, http.StatusForbidden, failStatus)
+ // A route about one document answers a guest as one about a
+ // document they cannot reach: 404, never 403, as team mode below
+ // always has (Astra, 2026-11-01). Create, which names no document,
+ // stays 403.
+ if item {
+ h.fail(w, r, http.StatusNotFound, failDocument)
+ } else {
+ h.fail(w, r, http.StatusForbidden, failStatus)
+ }
return false
}
actor, e := h.actor(r)