oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 crand "crypto/rand"
6 "errors"
7 "io"
8 "strconv"
9 "testing"
10
11 "amadan.net/oficina/suite"
12)
13
14// feedRowsOf is a document's suite_feed rows, oldest first.
15func feedRowsOf(t *testing.T, s *Store, docID int64) []SuiteFeedRow {
16 t.Helper()
17 var rows []SuiteFeedRow
18 if err := s.db.Where("document_id = ?", docID).Order("id").Find(&rows).Error; err != nil {
19 t.Fatal(err)
20 }
21 return rows
22}
23
24// The delegated agent API that landed on main (5039cf6) creates and edits
25// documents through CreateDraft and ApplyUpdate, inside its own writer
26// transaction. So an agent-created document is on the team rung (Paul,
27// 2026-11-01), its revisions are drawn by newRevision from randomSource,
28// each change is announced in suite_feed, and S2 reads an agent edit's
29// predecessor as STALE from the log. The agent's own "body_revision" /
30// "expected_revision" is doc_updates.seq — a different number, untouched.
31//
32// MUTATION-TESTED 2026-11-02, each reverted: CreateDraft creating private →
33// "visibility"; createDocument's revision fixed at 1 instead of drawn → "the
34// scripted draws" (first row at 1); createDocument without its announce →
35// one row short; ApplyUpdate without bumpRevision → "the edit's revision"
36// unchanged, no third row, and S2 [VISIBLE VISIBLE]. (The fixed-revision
37// mutation first failed to compile — an unused variable, red for the wrong
38// reason — and was redone.)
39func TestSuiteAgentCreateAndEditAreTeamRandomAndAnnounced(t *testing.T) {
40 f := newDocAgentFixture(t)
41 t.Cleanup(func() { randomSource = crand.Reader })
42
43 // create: the document's revision, its nonce, the initial content's
44 // revision, its nonce — in that order, all from randomSource.
45 randomSource = draws(101, 102, 103, 104)
46 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
47 randomSource = crand.Reader
48 var doc Document
49 if err := f.a.store.db.Where("sqid = ?", body.ID).First(&doc).Error; err != nil {
50 t.Fatal(err)
51 }
52 if doc.Visibility != VisibilityTeam {
53 t.Errorf("visibility: an agent-created document is %q, want team", doc.Visibility)
54 }
55 rows := feedRowsOf(t, f.a.store, doc.ID)
56 if len(rows) != 2 || rows[0].Revision != 101 || rows[0].Stamp != 102 || rows[1].Revision != 103 || rows[1].Stamp != 104 || doc.Revision != 103 {
57 t.Errorf("the scripted draws / feed rows: document at %d, rows %+v; want revisions 101 then 103 with nonces 102, 104", doc.Revision, rows)
58 }
59 if body.Revision != "1" {
60 t.Errorf("the agent's body_revision is doc_updates.seq, %q; want \"1\" (the two revisions are separate)", body.Revision)
61 }
62
63 edited := f.call(t, "docs_update", editAgentInput(body))
64 if edited.Code != 200 {
65 t.Fatal(edited.Code, edited.Body.String())
66 }
67 before := doc.Revision
68 if err := f.a.store.db.First(&doc, doc.ID).Error; err != nil {
69 t.Fatal(err)
70 }
71 if doc.Revision == before {
72 t.Errorf("the edit's revision: unchanged at %d", before)
73 }
74 rows = feedRowsOf(t, f.a.store, doc.ID)
75 if len(rows) != 3 || rows[2].Revision != doc.Revision || rows[2].Gone {
76 t.Errorf("the edit's feed row: %+v, want a third row at %d", rows, doc.Revision)
77 }
78 got, err := f.app.suite.Rule(context.Background(), suite.Subject{Kind: suite.SubjectAddress, Value: "owner@example.com"},
79 []suite.ItemRevision{{ItemID: doc.Sqid, Revision: before}, {ItemID: doc.Sqid, Revision: doc.Revision}})
80 if err != nil || got[0] != suite.STALE || got[1] != suite.VISIBLE {
81 t.Errorf("S2 around the agent's edit: %v %v, want [STALE VISIBLE]", got, err)
82 }
83 if strconv.FormatInt(doc.Revision, 10) == body.Revision {
84 t.Error("documents.revision and the agent's body_revision coincide")
85 }
86}
87
88// An agent create or edit whose feed row cannot be written commits nothing:
89// no document, receipt or attribution for a create; no update, receipt,
90// attribution or new revision for an edit.
91//
92// MUTATION-TESTED 2026-11-02, reverted: bumpRevision returning nil when
93// announce fails → the agent edit commits. createDocument ignoring
94// announce's error stayed GREEN here, correctly: the agent create's initial
95// content goes through ApplyUpdate in the same transaction, whose own feed
96// row fails on the same trigger and rolls everything back. That swallow is
97// held where creation is alone — TestSuiteAChangeWithoutItsFeedRowDoesNotCommit
98// ("create"), red under it.
99func TestSuiteAgentWritesRollBackWithoutTheirFeedRow(t *testing.T) {
100 f := newDocAgentFixture(t)
101 body := decodeAgentBody(t, f.call(t, "docs_create", initialAgentInput()))
102 var doc Document
103 if err := f.a.store.db.Where("sqid = ?", body.ID).First(&doc).Error; err != nil {
104 t.Fatal(err)
105 }
106 if _, err := f.app.db.Writer().Exec(`CREATE TRIGGER suite_feed_refuses BEFORE INSERT ON suite_feed BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
107 t.Fatal(err)
108 }
109 count := func(model any) int64 {
110 var n int64
111 if err := f.a.store.db.Model(model).Count(&n).Error; err != nil {
112 t.Fatal(err)
113 }
114 return n
115 }
116 docs, receipts, attributions := count(&Document{}), count(&agentReceipt{}), count(&agentAttribution{})
117 if w := f.call(t, "docs_create", initialAgentInput()); w.Code == 200 {
118 t.Error("an agent create committed without its feed row")
119 }
120 if count(&Document{}) != docs || count(&agentReceipt{}) != receipts || count(&agentAttribution{}) != attributions {
121 t.Error("an agent create left rows behind without its feed row")
122 }
123 updates, editReceipts := count(&DocUpdate{}), count(&agentUpdateReceipt{})
124 if w := f.call(t, "docs_update", editAgentInput(body)); w.Code == 200 {
125 t.Error("an agent edit committed without its feed row")
126 }
127 var after Document
128 if err := f.a.store.db.First(&after, doc.ID).Error; err != nil {
129 t.Fatal(err)
130 }
131 if count(&DocUpdate{}) != updates || count(&agentUpdateReceipt{}) != editReceipts || after.Revision != doc.Revision {
132 t.Error("an agent edit left rows behind without its feed row")
133 }
134}
135
136// failingAfter hands out its bytes and then fails, like a source that dies
137// between two draws.
138type failingAfter struct{ r io.Reader }
139
140func (f failingAfter) Read(p []byte) (int, error) {
141 n, err := f.r.Read(p)
142 if err == io.EOF {
143 return n, errors.New("entropy gone")
144 }
145 return n, err
146}
147
148// byteAtATime returns one byte per Read, as a source may.
149type byteAtATime struct{ r io.Reader }
150
151func (b byteAtATime) Read(p []byte) (int, error) {
152 if len(p) == 0 {
153 return 0, nil
154 }
155 return b.r.Read(p[:1])
156}
157
158// Astra's two nonblocking notes on 65acd67. A source that fails after the
159// revision was drawn — when the feed row's nonce is drawn — still stops the
160// change; and a source that answers in pieces is read until eight bytes are
161// in hand, while one that runs out part-way is an error, never a value
162// built from a half-filled buffer.
163//
164// MUTATION-TESTED 2026-11-02, each reverted: announce falling back to a
165// time-based nonce when randomPositive fails → "nonce failure" commits the
166// rename and the create; randomPositive using a single Read in place of
167// io.ReadFull → "one byte at a time" gets 0x0100000000000000 and "runs out
168// part-way" gets a value. (Falling back to a ZERO nonce stayed green: the
169// column's CHECK (stamp > 0) refuses it and the change rolls back anyway — a
170// second guard, so the mutation was redone with a guessable nonzero value.)
171func TestSuiteRandomnessFailsPartWayAndArrivesInPieces(t *testing.T) {
172 t.Cleanup(func() { randomSource = crand.Reader })
173 app, err := NewForTest(t)
174 if err != nil {
175 t.Fatal(err)
176 }
177 ctx := context.Background()
178 alice := app.TestPerson(t, "alice@example.com")
179 doc, err := app.store.Create(ctx, alice, "Kept")
180 if err != nil {
181 t.Fatal(err)
182 }
183 var docs int64
184 app.store.db.Model(&Document{}).Count(&docs)
185 rows := len(feedRowsOf(t, app.store, doc.ID))
186
187 // One draw is there (the revision), the nonce's is not.
188 randomSource = failingAfter{draws(77)}
189 if err := app.store.Rename(ctx, app.TestActorForPerson(t, alice), doc, "Not renamed"); err == nil {
190 t.Error("nonce failure: a rename committed")
191 }
192 randomSource = failingAfter{draws(78)}
193 if _, err := app.store.Create(ctx, alice, "Not made"); err == nil {
194 t.Error("nonce failure: a document was created")
195 }
196 randomSource = crand.Reader
197 var after Document
198 app.store.db.First(&after, doc.ID)
199 var docsAfter int64
200 app.store.db.Model(&Document{}).Count(&docsAfter)
201 if after.Title != "Kept" || after.Revision != doc.Revision || docsAfter != docs || len(feedRowsOf(t, app.store, doc.ID)) != rows {
202 t.Errorf("nonce failure changed something: %+v, documents %d→%d", after, docs, docsAfter)
203 }
204
205 randomSource = byteAtATime{draws(0x0102030405060708)}
206 if n, err := randomPositive(); err != nil || n != 0x0102030405060708 {
207 t.Errorf("one byte at a time: %#x %v", n, err)
208 }
209 randomSource = failingAfter{io.LimitReader(draws(0x0102030405060708).r, 3)}
210 if n, err := randomPositive(); !errors.Is(err, errNoRandomness) {
211 t.Errorf("runs out part-way: %#x %v, want errNoRandomness", n, err)
212 }
213}
214