oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "amadan.net/oficina/equipo/internal/equipo/mergegate"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "log/slog"
11 "os"
12 "path/filepath"
13 "reflect"
14 "sync"
15 "testing"
16 "time"
17
18 "gorm.io/gorm"
19
20 "amadan.net/oficina/equipo/internal/equipo/housekeeping"
21 "amadan.net/oficina/equipo/internal/wire"
22 "amadan.net/rastrillo/rastrillo/db"
23)
24
25// The store-level housekeeping tests: the principal's checks inside the
26// shared store functions, the ledger's state machine, reservations and
27// stand-down, on the chat tables with a two-person roster. The contract
28// tests in internal/thintest drive the same through the person API.
29
30const (
31 hkOwner = "owner@example.com"
32 hkMember = "member@example.com"
33)
34
35type hkRig struct {
36 t *testing.T
37 s *Store
38 ctx context.Context
39 now time.Time
40}
41
42// hkTemplate is the migrated database every rig copies: migrating once
43// keeps the package inside its time budget.
44var hkTemplate struct {
45 once sync.Once
46 dir string
47 err error
48}
49
50func hkTemplatePath() (string, error) {
51 hkTemplate.once.Do(func() {
52 dir, err := os.MkdirTemp("", "chat-hk-")
53 if err != nil {
54 hkTemplate.err = err
55 return
56 }
57 hkTemplate.dir = dir
58 d, err := db.Open(filepath.Join(dir, "template.db"), slog.New(slog.NewTextHandler(io.Discard, nil)))
59 if err != nil {
60 hkTemplate.err = err
61 return
62 }
63 defer d.Close()
64 if err := d.G.AutoMigrate(Models...); err != nil {
65 hkTemplate.err = err
66 return
67 }
68 for _, q := range []string{
69 "CREATE TABLE members (address text PRIMARY KEY, active integer, role text)",
70 "CREATE TABLE teams (id text PRIMARY KEY)",
71 "INSERT INTO teams(id) VALUES ('TEAM1')",
72 "INSERT INTO members(address, active, role) VALUES ('owner@example.com', 1, 'owner'), ('member@example.com', 1, 'owner')",
73 "PRAGMA wal_checkpoint(TRUNCATE)",
74 } {
75 if _, err := d.Writer().Exec(q); err != nil {
76 hkTemplate.err = err
77 return
78 }
79 }
80 })
81 return filepath.Join(hkTemplate.dir, "template.db"), hkTemplate.err
82}
83
84func newHKRig(t *testing.T) *hkRig {
85 t.Helper()
86 src, err := hkTemplatePath()
87 if err != nil {
88 t.Fatal(err)
89 }
90 raw, err := os.ReadFile(src)
91 if err != nil {
92 t.Fatal(err)
93 }
94 path := filepath.Join(t.TempDir(), "hk.db")
95 if err := os.WriteFile(path, raw, 0o600); err != nil {
96 t.Fatal(err)
97 }
98 d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
99 if err != nil {
100 t.Fatal(err)
101 }
102 t.Cleanup(func() { _ = d.Close() })
103 r := &hkRig{t: t, ctx: context.Background(), now: time.Date(2026, 11, 8, 12, 0, 0, 0, time.UTC)}
104 r.s = NewStore(d, Authority{
105 CurrentPerson: func(context.Context, *gorm.DB) error { return nil },
106 Audit: func(*gorm.DB, string, string, string) error { return nil },
107 Me: func(*gorm.DB, string) (wire.Me, error) { return wire.Me{Role: "owner"}, nil },
108 PrimaryRunner: func(*gorm.DB, string) (string, error) { return "RUNNER1", nil },
109 Copy: func(k string) string { return k },
110 }, nil)
111 r.s.now = func() time.Time { return r.now }
112 return r
113}
114
115func (r *hkRig) tx(fn func(*txn) error) error { return r.s.tx(r.ctx, fn) }
116
117func (r *hkRig) must(err error) {
118 r.t.Helper()
119 if err != nil {
120 r.t.Fatal(err)
121 }
122}
123
124// task records an open task in project p1.
125func (r *hkRig) task(id, title, creator string) taskRecord {
126 r.t.Helper()
127 k := taskRecord{ID: id, ProjectID: "p1", Title: title, Stage: wire.StageNoted, Creator: creator, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now, Branch: "equipo/" + id}
128 r.must(r.tx(func(t *txn) error {
129 var n int64
130 if err := t.db.Model(&projectRecord{}).Where("id = ?", "p1").Count(&n).Error; err != nil {
131 return err
132 }
133 if n == 0 {
134 if err := t.db.Create(&projectRecord{ID: "p1", Repo: "amadan.net/oficina/sample", State: wire.ProjectActive, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error; err != nil {
135 return err
136 }
137 }
138 return t.db.Create(&k).Error
139 }))
140 r.now = r.now.Add(time.Second)
141 return k
142}
143
144func (r *hkRig) load(id string) taskRecord {
145 r.t.Helper()
146 var k taskRecord
147 r.must(r.s.db.G.Where("id = ?", id).First(&k).Error)
148 return k
149}
150
151func (r *hkRig) row(person, detector, key string) (hkRecord, bool) {
152 r.t.Helper()
153 var rows []hkRecord
154 r.must(r.s.db.G.Where("person = ? AND detector = ? AND finding_key = ?", person, detector, key).Find(&rows).Error)
155 if len(rows) == 0 {
156 return hkRecord{}, false
157 }
158 return rows[0], true
159}
160
161func (r *hkRig) count(q string, args ...any) int64 {
162 r.t.Helper()
163 var n int64
164 r.must(r.s.db.G.Raw(q, args...).Scan(&n).Error)
165 return n
166}
167
168// run claims and acts on one finding in its own transaction.
169func (r *hkRig) run(d housekeeping.Detector, f housekeeping.Finding) bool {
170 r.t.Helper()
171 var did bool
172 r.must(r.tx(func(t *txn) error {
173 var err error
174 did, err = t.hkRun(d, f)
175 return err
176 }))
177 return did
178}
179
180func combineFinding(k, into taskRecord, owner string) housekeeping.Finding {
181 return housekeeping.Finding{Detector: housekeeping.DuplicateSameCreatorID, Subject: housekeeping.Subject{Kind: housekeeping.SubjectTask, ID: k.ID}, Owner: owner, SubjectRevision: k.Revision,
182 Key: "duplicate:" + min(k.ID, into.ID) + ":" + max(k.ID, into.ID), Proposal: housekeeping.Proposal{Action: housekeeping.ActionCombine, Task: k.ID, Into: into.ID}}
183}
184
185func sameCreator() housekeeping.Detector { return housekeeping.DuplicateSameCreator() }
186
187// TestHousekeepingPrincipal: the principal's checks run inside the store
188// functions, so a finding no detector should produce is still refused:
189// a fold whose destination is another person's task, a fold for a person
190// removed from the roster since, a link written on another person's task.
191// Each is refused, recorded, and nothing it tried survives.
192func TestHousekeepingPrincipal(t *testing.T) {
193 r := newHKRig(t)
194 mine := r.task("tkmine", "Swipe back from the edge doesn't work", hkOwner)
195 theirs := r.task("tktheirs", "Swipe back from the pane edge doesn't work", hkMember)
196 before := []taskRecord{r.load(mine.ID), r.load(theirs.ID)}
197
198 // A fold into another person's task.
199 if r.run(sameCreator(), combineFinding(mine, theirs, hkOwner)) {
200 t.Fatal("folded into another person's task")
201 }
202 row, ok := r.row(hkOwner, housekeeping.DuplicateSameCreatorID, combineFinding(mine, theirs, hkOwner).Key)
203 if !ok || row.State != wire.ActionRefused || row.Reason != wire.ReasonHousekeepingForbidden {
204 t.Fatalf("row: %+v", row)
205 }
206 // The same fold claimed for the other person: their own task goes into
207 // the owner's.
208 if r.run(sameCreator(), combineFinding(theirs, mine, hkMember)) {
209 t.Fatal("folded another person's task into the owner's")
210 }
211 for i, k := range []taskRecord{r.load(mine.ID), r.load(theirs.ID)} {
212 if !reflect.DeepEqual(k, before[i]) {
213 t.Fatalf("a refused fold changed %s:\n%+v\n%+v", k.ID, k, before[i])
214 }
215 }
216 if n := r.count("SELECT COUNT(*) FROM chat_task_entries"); n != 0 {
217 t.Fatalf("a refused fold copied %d entries", n)
218 }
219 if n := r.count("SELECT COUNT(*) FROM chat_cards"); n != 0 {
220 t.Fatalf("a refused fold left %d cards", n)
221 }
222
223 // The owner's own pair, but the owner left the team since the finding.
224 again := r.task("tkagain", "Swipe back from the edge doesn't work again", hkOwner)
225 r.must(r.tx(func(t *txn) error { return t.db.Exec("UPDATE members SET active = 0 WHERE address = ?", hkOwner).Error }))
226 if r.run(sameCreator(), combineFinding(again, mine, hkOwner)) {
227 t.Fatal("folded for a person no longer on the team")
228 }
229 if row, _ := r.row(hkOwner, housekeeping.DuplicateSameCreatorID, combineFinding(again, mine, hkOwner).Key); row.State != wire.ActionRefused {
230 t.Fatalf("departed person's fold: %+v", row)
231 }
232 if k := r.load(again.ID); k.FoldedInto != "" || k.Stage != wire.StageNoted {
233 t.Fatalf("departed person's task changed: %+v", k)
234 }
235 r.must(r.tx(func(t *txn) error { return t.db.Exec("UPDATE members SET active = 1 WHERE address = ?", hkOwner).Error }))
236
237 // A link claimed by the owner but written on the other person's task.
238 link := housekeeping.Finding{Detector: housekeeping.DuplicatePossibleID, Subject: housekeeping.Subject{Kind: housekeeping.SubjectTask, ID: theirs.ID}, Owner: hkOwner, Key: "possible:x", Proposal: housekeeping.Proposal{Action: housekeeping.ActionLink, Task: theirs.ID, Into: mine.ID}}
239 r.run(housekeeping.DuplicatePossible(), link)
240 if row, _ := r.row(hkOwner, housekeeping.DuplicatePossibleID, "possible:x"); row.State != wire.ActionRefused {
241 t.Fatalf("link on another's task: %+v", row)
242 }
243 if k := r.load(theirs.ID); k.DuplicateOf != "" {
244 t.Fatal("a refused link was written")
245 }
246
247 // The owner's own pair, on the team: combined, with its receipt.
248 fresh := r.task("tkfresh", "Swipe back from the edge doesn't work at all", hkOwner)
249 if !r.run(sameCreator(), combineFinding(fresh, mine, hkOwner)) {
250 t.Fatal("the owner's own pair was not combined")
251 }
252 if k := r.load(fresh.ID); k.FoldedInto != mine.ID {
253 t.Fatalf("own pair: %+v", k)
254 }
255}
256
257// TestHousekeepingNever: under the principal, the shared store functions
258// refuse what housekeeping may never do, whatever code asks; through the
259// ledger the attempt is a refused row and nothing it wrote survives.
260func TestHousekeepingNever(t *testing.T) {
261 r := newHKRig(t)
262 k := r.task("tkone", "Crash on launch", hkOwner)
263 r.must(r.tx(func(t *txn) error {
264 return t.db.Create(&stepRecord{ID: "s1", TaskID: k.ID, Idx: 0, Specialist: wire.SpecialistEngineering, Person: hkOwner, State: wire.StepFailed, Attempt: 1, Terminated: true, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error
265 }))
266 p := &Principal{Team: "TEAM1", Person: hkOwner, Detector: "test", FindingID: "hk_test"}
267 m := r.task("tkm", "Theirs", hkMember)
268 r.must(r.tx(func(t *txn) error {
269 return t.db.Create(&cardRecord{ID: "cmerge", Person: hkOwner, Kind: wire.CardMerge, State: wire.CardOpen, TaskID: k.ID, Options: "[]", Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error
270 }))
271 never := map[string]func(t *txn) error{
272 "delete a project": func(t *txn) error { _, err := t.removeProject(hkOwner, "p1"); return err },
273 "cancel a task": func(t *txn) error { _, err := t.cancelTask(hkOwner, k.ID); return err },
274 "end a task": func(t *txn) error {
275 k := r.load(k.ID)
276 k.Stage = wire.StageDone
277 return t.saveTask(&k)
278 },
279 "merge eligibility": func(t *txn) error {
280 k := r.load(k.ID)
281 k.MergeEligible = "abc"
282 return t.saveTask(&k)
283 },
284 "ready to merge": func(t *txn) error {
285 k := r.load(k.ID)
286 k.ReadySHA = "abc"
287 return t.saveTask(&k)
288 },
289 "merge": func(t *txn) error {
290 k := r.load(k.ID)
291 return t.startMerge(&k, progress{}, nil, false, decidedPolicy)
292 },
293 "a merge policy": func(t *txn) error {
294 pr, err := t.mergePolicy(k.ProjectID)
295 if err != nil {
296 return err
297 }
298 return t.savePolicy(&pr, hkOwner)
299 },
300 "a merge card": func(t *txn) error {
301 k := r.load(k.ID)
302 return t.askMerge(&k, progress{}, mergegate.Decision{Class: mergegate.ClassAsk})
303 },
304 "a setting": func(t *txn) error { _, err := t.setSetting("project_home", "x", hkOwner); return err },
305 "another's notebook": func(t *txn) error { return t.saveNotebook(hkMember, nil) },
306 "another's task": func(t *txn) error { return t.saveTask(&m) },
307 // Astra round 1, finding 1: the caller's copy claims the
308 // principal's person; the stored task is another's.
309 "a forged creator": func(t *txn) error {
310 forged := m
311 forged.Creator, forged.DuplicateOf = hkOwner, "tkone"
312 return t.saveTask(&forged)
313 },
314 // Finding 2: clearing or replacing the person's own notes.
315 "clear own notes": func(t *txn) error { return t.saveNotebook(hkOwner, nil) },
316 "replace own notes": func(t *txn) error { return t.saveNotebook(hkOwner, []wire.NotebookEntry{{Text: "x"}}) },
317 // Finding 2: resolving or withdrawing an open card.
318 "withdraw a merge card": func(t *txn) error { return t.withdrawMergeCards(r.load(k.ID)) },
319 "resolve a card": func(t *txn) error {
320 var c cardRecord
321 if err := t.db.Where("id = ?", "cmerge").First(&c).Error; err != nil {
322 return err
323 }
324 c.State = wire.CardResolved
325 return t.saveCard(&c)
326 },
327 "dispatch, no reserve": func(t *txn) error {
328 var s stepRecord
329 t.db.First(&s)
330 kk := r.load(k.ID)
331 return t.dispatchStep(&kk, &s)
332 },
333 "a turn, no reserve": func(t *txn) error { return t.dispatch(&turnRecord{ID: "t1", Person: hkOwner}) },
334 }
335 for name, fn := range never {
336 err := r.tx(func(t *txn) error {
337 t.hk = p
338 return fn(t)
339 })
340 if !errors.Is(err, ErrHousekeepingForbidden) {
341 t.Errorf("%s: %v", name, err)
342 }
343 }
344 if k2 := r.load(k.ID); k2.Stage != wire.StageNoted || k2.MergeEligible != "" || k2.ReadySHA != "" {
345 t.Fatalf("task changed: %+v", k2)
346 }
347 if m2 := r.load(m.ID); m2.Creator != hkMember || m2.DuplicateOf != "" || m2.Revision != m.Revision {
348 t.Fatalf("the forged write reached another's task: %+v", m2)
349 }
350 if n := r.count("SELECT COUNT(*) FROM chat_cards WHERE id = 'cmerge' AND state = ?", wire.CardOpen); n != 1 {
351 t.Fatal("the merge card was withdrawn")
352 }
353
354 // Dispatch with a reservation: on a limited connection, refused; on
355 // the selected connection, healthy, reported and fresh, the gate opens.
356 r.connection("cn1", "local1", wire.ConnLimited, 0.1, r.now)
357 reserved := &Principal{Team: "TEAM1", Person: hkOwner, Detector: "test", FindingID: "hk_test", Reserved: housekeeping.AutoRetry}
358 dispatch := func() error {
359 return r.tx(func(t *txn) error {
360 t.hk = reserved
361 var s stepRecord
362 t.db.First(&s)
363 kk := r.load(k.ID)
364 return t.dispatchStep(&kk, &s)
365 })
366 }
367 if err := dispatch(); !errors.Is(err, ErrHousekeepingForbidden) {
368 t.Fatalf("dispatch on a limited connection: %v", err)
369 }
370 // Finding 3: slice 1 has no judgement turns or retries, so even a
371 // reservation on a healthy, reported, fresh connection dispatches
372 // nothing.
373 r.connection("cn1", "local1", wire.ConnHealthy, 0.5, r.now)
374 if err := dispatch(); !errors.Is(err, ErrHousekeepingForbidden) {
375 t.Fatalf("dispatch within a reservation in slice 1: %v", err)
376 }
377 if err := r.tx(func(t *txn) error {
378 t.hk = reserved
379 return t.dispatch(&turnRecord{ID: "t2", Person: hkOwner, Kind: wire.TurnHousekeeping})
380 }); !errors.Is(err, ErrHousekeepingForbidden) {
381 t.Fatalf("a housekeeping turn in slice 1: %v", err)
382 }
383
384 // Through the ledger: a proposal whose action reaches a forbidden store
385 // function is a refused row, and the transaction's other writes stay.
386 for name, act := range map[string]func(*txn, *hkRecord, housekeeping.Finding) (hkResult, error){
387 "merge": func(t *txn, _ *hkRecord, _ housekeeping.Finding) (hkResult, error) {
388 k := r.load(k.ID)
389 return hkResult{}, t.startMerge(&k, progress{}, nil, false, decidedPolicy)
390 },
391 "delete": func(t *txn, _ *hkRecord, _ housekeeping.Finding) (hkResult, error) {
392 _, err := t.removeProject(hkOwner, "p1")
393 return hkResult{}, err
394 },
395 "cancel": func(t *txn, _ *hkRecord, _ housekeeping.Finding) (hkResult, error) {
396 _, err := t.cancelTask(hkOwner, k.ID)
397 return hkResult{}, err
398 },
399 } {
400 hkActions[name] = act
401 hkClassActions[housekeeping.ClassAct][name] = true
402 t.Cleanup(func() { delete(hkActions, name); delete(hkClassActions[housekeeping.ClassAct], name) })
403 f := housekeeping.Finding{Detector: "never", Subject: housekeeping.Subject{Kind: housekeeping.SubjectTask, ID: k.ID}, Owner: hkOwner, Key: "never:" + name, Proposal: housekeeping.Proposal{Action: name, Task: k.ID}}
404 d := housekeeping.Detector{ID: "never", Subject: housekeeping.SubjectTask, Class: housekeeping.ClassAct, Triggers: []string{housekeeping.TriggerSweep}, Judgement: housekeeping.JudgementNone}
405 if r.run(d, f) {
406 t.Fatalf("%s acted", name)
407 }
408 if row, _ := r.row(hkOwner, "never", "never:"+name); row.State != wire.ActionRefused || row.Reason != wire.ReasonHousekeepingForbidden {
409 t.Fatalf("%s: %+v", name, row)
410 }
411 }
412 var proj projectRecord
413 r.must(r.s.db.G.Where("id = ?", "p1").First(&proj).Error)
414 if proj.State != wire.ProjectActive || r.load(k.ID).Stage != wire.StageNoted || r.load(k.ID).CancelRequested {
415 t.Fatal("a refused action survived")
416 }
417}
418
419// connection records a connection that answered the person's last turn.
420func (r *hkRig) connection(id, local, state string, utilization float64, checked time.Time) {
421 r.t.Helper()
422 raw, _ := json.Marshal(wire.Headroom{Utilization: &utilization, Windows: []wire.Window{}})
423 r.must(r.tx(func(t *txn) error {
424 if err := t.db.Exec("DELETE FROM chat_connections WHERE id = ?", id).Error; err != nil {
425 return err
426 }
427 if err := t.db.Create(&connectionRecord{ID: id, Person: hkOwner, LocalID: local, Provider: "claude", State: state, Headroom: string(raw), Revision: 1, CreatedAt: checked, UpdatedAt: checked}).Error; err != nil {
428 return err
429 }
430 var n int64
431 t.db.Model(&turnRecord{}).Where("id = ?", "tlast").Count(&n)
432 if n == 0 {
433 return t.db.Create(&turnRecord{ID: "tlast", Person: hkOwner, State: wire.TurnReplied, Attempt: 1, Connection: local, CreatedAt: r.now, UpdatedAt: r.now}).Error
434 }
435 return t.db.Model(&turnRecord{}).Where("id = ?", "tlast").Update("connection", local).Error
436 }))
437}
438
439// judge is a test detector that spends: a judgement turn's reservation.
440func judge(cost housekeeping.Cost) housekeeping.Detector {
441 return housekeeping.Detector{ID: "judge", Subject: housekeeping.SubjectTask, Class: housekeeping.ClassPropose, Triggers: []string{housekeeping.TriggerSweep}, Judgement: housekeeping.JudgementModel, Cost: cost}
442}
443
444func judgeFinding(n int) housekeeping.Finding {
445 return housekeeping.Finding{Detector: "judge", Subject: housekeeping.Subject{Kind: housekeeping.SubjectTask, ID: "tkone"}, Owner: hkOwner, SubjectRevision: 1, Key: fmt.Sprintf("judge:%d", n)}
446}
447
448func (r *hkRig) state(key string) hkRecord {
449 r.t.Helper()
450 row, ok := r.row(hkOwner, "judge", key)
451 if !ok {
452 r.t.Fatalf("no row %s", key)
453 }
454 return row
455}
456
457// TestHousekeepingReservation: Paul's budget, four turns, 150,000 tokens
458// and three retries a day per person, is reserved in the claim's
459// transaction: exhaustion holds, two claims racing the last room cannot
460// both pass, and a reservation counts in full until its attempt's
461// termination and charge are in (unknown usage charges it all). A
462// judgement turn reserves its share, 37,500, so all four fit exactly.
463func TestHousekeepingReservation(t *testing.T) {
464 r := newHKRig(t)
465 r.task("tkone", "Crash on launch", hkOwner)
466 r.connection("cn1", "local1", wire.ConnHealthy, 0.2, r.now)
467 d := judge(housekeeping.JudgementTurn)
468 for i := range 3 {
469 r.run(d, judgeFinding(i))
470 if s := r.state(judgeFinding(i).Key); s.State != wire.ActionClaimed || s.ReservedTurns != 1 || s.ReservedTokens != 37500 {
471 t.Fatalf("claim %d: %+v", i, s)
472 }
473 }
474 // Two claims race the fourth, the last that fits: exactly one wins.
475 var wg sync.WaitGroup
476 for _, n := range []int{10, 11} {
477 wg.Add(1)
478 go func() {
479 defer wg.Done()
480 r.run(d, judgeFinding(n))
481 }()
482 }
483 wg.Wait()
484 a, b := r.state("judge:10"), r.state("judge:11")
485 if (a.State == wire.ActionClaimed) == (b.State == wire.ActionClaimed) {
486 t.Fatalf("racing claims: %s and %s", a.State, b.State)
487 }
488 held := a
489 if a.State == wire.ActionClaimed {
490 held = b
491 }
492 if held.State != wire.ActionHeld || held.Reason != wire.ReasonHeldBudget {
493 t.Fatalf("the loser: %+v", held)
494 }
495 // Exhausted: a fifth is held, and the view shows the day reserved.
496 r.run(d, judgeFinding(5))
497 if s := r.state("judge:5"); s.State != wire.ActionHeld || s.Reason != wire.ReasonHeldBudget {
498 t.Fatalf("after the last: %+v", s)
499 }
500 var view wire.Housekeeping
501 r.must(r.tx(func(t *txn) error { var e error; view, e = t.housekeepingView(hkOwner); return e }))
502 if view.Budget.Turns != (wire.BudgetMeter{Reserved: 4, Limit: 4}) || view.Budget.Tokens != (wire.BudgetMeter{Reserved: 150000, Limit: 150000}) {
503 t.Fatalf("budget: %+v", view.Budget)
504 }
505 // Turns bind too: with small turns, a fifth is held on turns alone.
506 small := judge(housekeeping.Cost{Turns: 1, Tokens: 1})
507 r3 := newHKRig(t)
508 r3.task("tkone", "Crash on launch", hkOwner)
509 r3.connection("cn1", "local1", wire.ConnHealthy, 0.2, r3.now)
510 for i := range 5 {
511 r3.run(small, judgeFinding(i))
512 }
513 if s := r3.state("judge:3"); s.State != wire.ActionClaimed {
514 t.Fatalf("fourth turn: %+v", s)
515 }
516 if s := r3.state("judge:4"); s.State != wire.ActionHeld || s.Reason != wire.ReasonHeldBudget {
517 t.Fatalf("fifth turn: %+v", s)
518 }
519
520 // Settling: the row stays releasing until termination; no figure
521 // charges the whole reservation; a complete figure charges itself.
522 first := r.state("judge:0")
523 r.must(r.tx(func(t *txn) error { return t.hkSettle(&first, nil, false, false) }))
524 if s := r.state("judge:0"); !s.Releasing || s.ChargedTokens != 37500 || s.ChargedComplete {
525 t.Fatalf("unknown usage: %+v", s)
526 }
527 second := r.state("judge:1")
528 r.must(r.tx(func(t *txn) error {
529 return t.hkSettle(&second, &housekeeping.Cost{Turns: 1, Tokens: 12000}, true, true)
530 }))
531 var used, charged housekeeping.Cost
532 r.must(r.tx(func(t *txn) error {
533 var e error
534 used, charged, e = t.hkUsed(hkOwner, housekeeping.DayStart(r.now, time.UTC))
535 return e
536 }))
537 // judge:1 is charged 12,000 but its row is still claimed, so it counts
538 // its full reservation until it moves on.
539 if charged.Tokens != 49500 || used.Turns != 4 {
540 t.Fatalf("used %+v charged %+v", used, charged)
541 }
542
543 // Tokens: an automatic retry reserves 100,000; a second does not fit.
544 r2 := newHKRig(t)
545 r2.task("tkone", "Crash on launch", hkOwner)
546 r2.connection("cn1", "local1", wire.ConnHealthy, 0.2, r2.now)
547 retry := judge(housekeeping.AutoRetry)
548 r2.run(retry, judgeFinding(1))
549 r2.run(retry, judgeFinding(2))
550 if a, b := r2.state("judge:1"), r2.state("judge:2"); a.State != wire.ActionClaimed || b.State != wire.ActionHeld || b.Reason != wire.ReasonHeldBudget {
551 t.Fatalf("tokens: %s, %s %s", a.State, b.State, b.Reason)
552 }
553 // Tomorrow the budget is fresh.
554 r2.now = r2.now.Add(24 * time.Hour)
555 r2.connection("cn1", "local1", wire.ConnHealthy, 0.2, r2.now)
556 r2.run(retry, judgeFinding(2))
557 if b := r2.state("judge:2"); b.State != wire.ActionClaimed {
558 t.Fatalf("next day: %+v", b)
559 }
560
561 // Pause: a claim that never left goes back to held; one dispatched
562 // keeps releasing until its charge is in.
563 dispatched := r2.state("judge:1")
564 r2.must(r2.tx(func(t *txn) error {
565 return t.db.Model(&hkRecord{}).Where("id = ?", dispatched.ID).Update("attempt", "s1:2").Error
566 }))
567 if _, err := r2.s.SetHousekeeping(r2.ctx, hkOwner, wire.SetHousekeeping{Paused: true}); err != nil {
568 t.Fatal(err)
569 }
570 if a, b := r2.state("judge:1"), r2.state("judge:2"); !a.Releasing || a.State != wire.ActionClaimed || b.State != wire.ActionHeld || b.ReservedTokens != 0 {
571 t.Fatalf("pause: %+v / %+v", a, b)
572 }
573}
574
575// TestHousekeepingStandsDown: what spends stands down unless the
576// connection the choice selected reports headroom, checked in the last
577// fifteen minutes, below 0.8; unknown is stand down; no other connection
578// is tried in its place. A combine, which spends nothing, still acts.
579func TestHousekeepingStandsDown(t *testing.T) {
580 d := judge(housekeeping.JudgementTurn)
581 for name, set := range map[string]func(r *hkRig){
582 "unknown headroom": func(r *hkRig) {
583 r.must(r.tx(func(t *txn) error {
584 return t.db.Create(&connectionRecord{ID: "cn1", Person: hkOwner, LocalID: "local1", State: wire.ConnHealthy, Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error
585 }))
586 r.must(r.tx(func(t *txn) error {
587 return t.db.Create(&turnRecord{ID: "tlast", Person: hkOwner, State: wire.TurnReplied, Connection: "local1", CreatedAt: r.now, UpdatedAt: r.now}).Error
588 }))
589 },
590 "at 0.8": func(r *hkRig) { r.connection("cn1", "local1", wire.ConnHealthy, 0.8, r.now) },
591 "checked 16 min": func(r *hkRig) { r.connection("cn1", "local1", wire.ConnHealthy, 0.1, r.now.Add(-16*time.Minute)) },
592 "limited": func(r *hkRig) { r.connection("cn1", "local1", wire.ConnLimited, 0.1, r.now) },
593 // Two connections and neither answered last: the choice is not
594 // known here, so unknown.
595 "none selected": func(r *hkRig) {
596 u := 0.1
597 raw, _ := json.Marshal(wire.Headroom{Utilization: &u})
598 r.must(r.tx(func(t *txn) error {
599 return t.db.Create(&connectionRecord{ID: "cn3", Person: hkOwner, LocalID: "local3", State: wire.ConnHealthy, Headroom: string(raw), Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error
600 }))
601 },
602 } {
603 r := newHKRig(t)
604 r.task("tkone", "Crash on launch", hkOwner)
605 set(r)
606 // Another healthy connection with room is never tried instead.
607 r.must(r.tx(func(t *txn) error {
608 u := 0.1
609 raw, _ := json.Marshal(wire.Headroom{Utilization: &u})
610 return t.db.Create(&connectionRecord{ID: "cn2", Person: hkOwner, LocalID: "local2", State: wire.ConnHealthy, Headroom: string(raw), Revision: 1, CreatedAt: r.now, UpdatedAt: r.now}).Error
611 }))
612 r.run(d, judgeFinding(1))
613 if s := r.state("judge:1"); s.State != wire.ActionHeld || s.Reason != wire.ReasonHeldStandDown {
614 t.Errorf("%s: %s %s", name, s.State, s.Reason)
615 }
616 // The combine carries on.
617 a := r.task("tka", "Swipe back from the edge doesn't work", hkOwner)
618 b := r.task("tkb", "Swipe back from the edge doesn't work again", hkOwner)
619 if !r.run(sameCreator(), combineFinding(b, a, hkOwner)) {
620 t.Errorf("%s: the combine stood down", name)
621 }
622 }
623}
624
625// TestHousekeepingLedger: the state machine. A replayed event is a no-op;
626// a deterministic action claims and acts in one transaction; a crash
627// after a claim with nothing dispatched releases it to held at restart,
628// one dispatched waits for sync, one whose subject moved expires and is
629// released; held is claimed when there is room; a veto recurs once; a
630// team-scoped key raised by two people is one row; held rows are capped.
631func TestHousekeepingLedger(t *testing.T) {
632 r := newHKRig(t)
633 a := r.task("tka", "Swipe back from the edge doesn't work", hkOwner)
634 b := r.task("tkb", "Swipe back from the edge doesn't work again", hkOwner)
635
636 // One transaction: if the caller's transaction fails, neither the row
637 // nor the fold exists.
638 boom := errors.New("caller failed")
639 err := r.tx(func(t *txn) error {
640 if _, err := t.hkRun(sameCreator(), combineFinding(b, a, hkOwner)); err != nil {
641 return err
642 }
643 return boom
644 })
645 if !errors.Is(err, boom) {
646 t.Fatal(err)
647 }
648 if _, ok := r.row(hkOwner, housekeeping.DuplicateSameCreatorID, combineFinding(b, a, hkOwner).Key); ok || r.load(b.ID).FoldedInto != "" {
649 t.Fatal("claim or fold survived the caller's rollback")
650 }
651 // The pass over the project, twice: one combine, the replay a no-op.
652 var n1, n2 int
653 r.must(r.tx(func(t *txn) error {
654 var e error
655 n1, e = t.housekeepingPass(housekeeping.TriggerRecordTask, "p1")
656 return e
657 }))
658 r.must(r.tx(func(t *txn) error {
659 var e error
660 n2, e = t.housekeepingPass(housekeeping.TriggerRecordTask, "p1")
661 return e
662 }))
663 if n1 != 1 || n2 != 0 || r.count("SELECT COUNT(*) FROM chat_housekeeping WHERE detector = ?", housekeeping.DuplicateSameCreatorID) != 1 {
664 t.Fatalf("passes: %d then %d", n1, n2)
665 }
666
667 // Crash after a claim: insert claimed rows as a spending claim leaves
668 // them, then recover as at start-up.
669 c := r.task("tkc", "Timeline jumps", hkOwner)
670 claimed := func(id, key string, rev int64, attempt string) {
671 at := r.now
672 r.must(r.tx(func(t *txn) error {
673 return t.db.Create(&hkRecord{ID: id, Team: "TEAM1", Person: hkOwner, Detector: "judge", SubjectKind: housekeeping.SubjectTask, SubjectID: c.ID, SubjectRevision: rev, FindingKey: key, Class: housekeeping.ClassPropose, State: wire.ActionClaimed, ClaimedAt: &at, Attempt: attempt, ReservedTurns: 1, ReservedTokens: 40000, At: at, Revision: 1}).Error
674 }))
675 }
676 claimed("hk_same", "judge:same", c.Revision, "")
677 claimed("hk_moved", "judge:moved", c.Revision-1, "")
678 claimed("hk_sent", "judge:sent", c.Revision, "t_1:1")
679 released, expired, err := r.s.RecoverHousekeeping(r.ctx, false)
680 r.must(err)
681 if released != 1 || expired != 1 {
682 t.Fatalf("recovered: %d released, %d expired", released, expired)
683 }
684 if s := r.state("judge:same"); s.State != wire.ActionHeld || s.ReservedTokens != 0 {
685 t.Fatalf("unchanged, nothing dispatched: %+v", s)
686 }
687 if s := r.state("judge:moved"); s.State != wire.ActionExpired || s.Reason != wire.ReasonSubjectMoved || s.Releasing || s.ChargedTokens != 0 {
688 t.Fatalf("subject moved: %+v", s)
689 }
690 if s := r.state("judge:sent"); s.State != wire.ActionClaimed {
691 t.Fatalf("dispatched: %+v", s)
692 }
693
694 // Held, then claimed when there is room: ten actions today fill the
695 // ceiling; tomorrow the held finding acts.
696 for i := range housekeeping.ActionsPerDay {
697 at := r.now
698 r.must(r.tx(func(t *txn) error {
699 return t.db.Create(&hkRecord{ID: fmt.Sprintf("hk_f%d", i), Team: "TEAM1", Person: hkOwner, Detector: housekeeping.DuplicateSameCreatorID, FindingKey: fmt.Sprintf("filler:%d", i), Class: housekeeping.ClassAct, State: wire.ActionDone, ClaimedAt: &at, At: at, Revision: 1}).Error
700 }))
701 }
702 x := r.task("tkx", "Compose sheet keyboard covers the send button", hkOwner)
703 y := r.task("tky", "Compose sheet keyboard covers the send button too", hkOwner)
704 r.run(sameCreator(), combineFinding(y, x, hkOwner))
705 if row, _ := r.row(hkOwner, housekeeping.DuplicateSameCreatorID, combineFinding(y, x, hkOwner).Key); row.State != wire.ActionHeld || row.Reason != wire.ReasonHeldCeiling {
706 t.Fatalf("eleventh action: %+v", row)
707 }
708 if r.load(y.ID).FoldedInto != "" {
709 t.Fatal("the eleventh action acted")
710 }
711 r.now = r.now.Add(24 * time.Hour)
712 r.run(sameCreator(), combineFinding(y, x, hkOwner))
713 if row, _ := r.row(hkOwner, housekeeping.DuplicateSameCreatorID, combineFinding(y, x, hkOwner).Key); row.State != wire.ActionDone || r.load(y.ID).FoldedInto != x.ID {
714 t.Fatalf("held then claimed: %+v", row)
715 }
716
717 // A veto: quiet for 30 days, then one recurrence, then never.
718 at := r.now.Add(-31 * 24 * time.Hour)
719 r.must(r.tx(func(t *txn) error {
720 return t.db.Create(&hkRecord{ID: "hk_veto", Team: "TEAM1", Person: hkOwner, Detector: "judge", FindingKey: "judge:veto", Class: housekeeping.ClassPropose, State: wire.ActionVetoed, UndoneAt: &at, At: at, Revision: 1}).Error
721 }))
722 r.connection("cn1", "local1", wire.ConnHealthy, 0.1, r.now)
723 veto := judgeFinding(0)
724 veto.Key = "judge:veto"
725 r.run(judge(housekeeping.JudgementTurn), veto)
726 if s := r.state("judge:veto"); s.State != wire.ActionClaimed || s.Recurrences != 1 {
727 t.Fatalf("recurrence: %+v", s)
728 }
729 r.must(r.tx(func(t *txn) error {
730 return t.db.Model(&hkRecord{}).Where("id = ?", "hk_veto").Updates(map[string]any{"state": wire.ActionVetoed, "undone_at": at}).Error
731 }))
732 r.run(judge(housekeeping.JudgementTurn), veto)
733 if s := r.state("judge:veto"); s.State != wire.ActionVetoed {
734 t.Fatalf("second recurrence: %+v", s)
735 }
736
737 // A team subject's key raised by two people: one row.
738 team := housekeeping.Detector{ID: "team", Subject: housekeeping.SubjectProject, Class: housekeeping.ClassPropose, Triggers: []string{housekeeping.TriggerSweep}, Judgement: housekeeping.JudgementNone}
739 hkActions["note"] = func(*txn, *hkRecord, housekeeping.Finding) (hkResult, error) { return hkResult{Action: "note"}, nil }
740 hkClassActions[housekeeping.ClassPropose]["note"] = true
741 t.Cleanup(func() { delete(hkActions, "note"); delete(hkClassActions[housekeeping.ClassPropose], "note") })
742 for range 2 {
743 r.run(team, housekeeping.Finding{Detector: "team", Subject: housekeeping.Subject{Kind: housekeeping.SubjectProject, ID: "p1"}, Key: "stale:p1", Proposal: housekeeping.Proposal{Action: "note"}})
744 }
745 if n := r.count("SELECT COUNT(*) FROM chat_housekeeping WHERE finding_key = 'stale:p1'"); n != 1 {
746 t.Fatalf("team key rows: %d", n)
747 }
748
749 // Held rows are capped: the oldest beyond twenty expire.
750 full := judge(housekeeping.Cost{Turns: 5})
751 for i := range housekeeping.HeldPerPerson + 2 {
752 r.now = r.now.Add(time.Second)
753 f := judgeFinding(100 + i)
754 r.run(full, f)
755 }
756 if n := r.count("SELECT COUNT(*) FROM chat_housekeeping WHERE state = 'held' AND person = ?", hkOwner); n != housekeeping.HeldPerPerson {
757 t.Fatalf("held rows: %d", n)
758 }
759 if s := r.state("judge:100"); s.State != wire.ActionExpired || s.Reason != wire.ReasonHeldOverflow {
760 t.Fatalf("oldest held: %+v", s)
761 }
762}
763
764// TestHousekeepingAutoDisable: a detector switches itself off for the
765// person after two failures within seven days, of mixed kinds; the
766// failure rows survive the action's rollback; re-enabling clears the
767// count and nothing re-enables on its own.
768func TestHousekeepingAutoDisable(t *testing.T) {
769 r := newHKRig(t)
770 r.task("tkone", "Crash on launch", hkOwner)
771 hkActions["explode"] = func(*txn, *hkRecord, housekeeping.Finding) (hkResult, error) {
772 return hkResult{}, errors.New("disk on fire")
773 }
774 hkClassActions[housekeeping.ClassAct]["explode"] = true
775 t.Cleanup(func() { delete(hkActions, "explode"); delete(hkClassActions[housekeeping.ClassAct], "explode") })
776 d := housekeeping.Detector{ID: housekeeping.DuplicateSameCreatorID, Subject: housekeeping.SubjectTask, Class: housekeeping.ClassAct, Triggers: []string{housekeeping.TriggerSweep}, Judgement: housekeeping.JudgementNone}
777 f := housekeeping.Finding{Subject: housekeeping.Subject{Kind: housekeeping.SubjectTask, ID: "tkone"}, Owner: hkOwner, Key: "boom:1", Proposal: housekeeping.Proposal{Action: "explode"}}
778 // The action fails inside a caller's transaction that then rolls back:
779 // the row goes with it, the failure count does not.
780 err := r.tx(func(t *txn) error {
781 if _, err := t.hkRun(d, f); err != nil {
782 return err
783 }
784 return errors.New("caller failed")
785 })
786 if err == nil {
787 t.Fatal("caller error lost")
788 }
789 if n := r.count("SELECT COUNT(*) FROM chat_housekeeping_failures WHERE kind = 'failed'"); n != 1 {
790 t.Fatalf("failure rows after the rollback: %d", n)
791 }
792 off := func() bool {
793 var s hkSettings
794 r.must(r.tx(func(t *txn) error { var e error; s, e = t.hkSettings(hkOwner); return e }))
795 return s.disabledFor(d.ID)
796 }
797 if off() {
798 t.Fatal("disabled after one failure")
799 }
800 // An Undo of another action is the second, of another kind.
801 r.must(r.tx(func(t *txn) error {
802 row := hkRecord{ID: "hk_u", Team: "TEAM1", Person: hkOwner, Detector: d.ID, FindingKey: "u:1", Class: housekeeping.ClassAct, State: wire.ActionDone, At: r.now, Revision: 1}
803 if err := t.db.Create(&row).Error; err != nil {
804 return err
805 }
806 return t.hkUndone(&row)
807 }))
808 if !off() {
809 t.Fatal("not disabled after two failures within seven days")
810 }
811 // Off: its findings are not claimed.
812 f2 := f
813 f2.Key, f2.Proposal.Action = "boom:2", housekeeping.ActionLink
814 r.run(d, f2)
815 if _, ok := r.row(hkOwner, d.ID, "boom:2"); ok {
816 t.Fatal("a disabled detector claimed a finding")
817 }
818 // Nothing re-enables on its own, a week on.
819 r.now = r.now.Add(8 * 24 * time.Hour)
820 if !off() {
821 t.Fatal("re-enabled on its own")
822 }
823 var set hkSettings
824 r.must(r.tx(func(t *txn) error { var e error; set, e = t.hkSettings(hkOwner); return e }))
825 if _, err := r.s.SetDetector(r.ctx, hkOwner, d.ID, wire.SetDetector{Enabled: true, Revision: set.Revision}); err != nil {
826 t.Fatal(err)
827 }
828 if off() {
829 t.Fatal("re-enable did not take")
830 }
831 // Re-enabling cleared the count: one more failure does not disable.
832 r.must(r.tx(func(t *txn) error {
833 return t.hkFailure(hkFailureRecord{Person: hkOwner, Detector: d.ID, Kind: failureFailed, At: r.now})
834 }))
835 if off() {
836 t.Fatal("the count was not cleared")
837 }
838}
839
840// TestHousekeepingPreempts: person turns come first in the queue, then
841// move-in and explore, then housekeeping; housekeeping never dispatches
842// beside a person's turn.
843func TestHousekeepingPreempts(t *testing.T) {
844 r := newHKRig(t)
845 for i, kind := range []string{wire.TurnHousekeeping, wire.TurnMoveIn, wire.TurnPerson} {
846 at := r.now.Add(time.Duration(i) * time.Second)
847 r.must(r.tx(func(t *txn) error {
848 return t.db.Create(&turnRecord{ID: "t" + kind, Person: hkOwner, State: wire.TurnQueued, Attempt: 1, Kind: kind, CreatedAt: at, UpdatedAt: at}).Error
849 }))
850 if kind == wire.TurnPerson {
851 r.must(r.tx(func(t *txn) error {
852 return t.db.Create(&messageRecord{ID: "m1", Person: hkOwner, IdempotencyKey: "k1", Role: wire.RolePerson, Text: "hi", TurnID: "t", Revision: 1, CreatedAt: at}).Error
853 }))
854 }
855 }
856 var order []string
857 for range 3 {
858 r.must(r.tx(func(t *txn) error { return t.dispatchNext(hkOwner, wire.LaneCoordinator) }))
859 var next turnRecord
860 r.must(r.s.db.G.Where("dispatched = ? AND state = ?", true, wire.TurnQueued).First(&next).Error)
861 order = append(order, next.Kind)
862 r.must(r.tx(func(t *txn) error {
863 return t.db.Model(&turnRecord{}).Where("id = ?", next.ID).Update("state", wire.TurnReplied).Error
864 }))
865 }
866 if !reflect.DeepEqual(order, []string{wire.TurnPerson, wire.TurnMoveIn, wire.TurnHousekeeping}) {
867 t.Fatalf("order: %q", order)
868 }
869}
870
871// TestHousekeepingClassActions (Astra round 1, finding 4): the executor
872// checks the detector's class against the proposal before anything runs.
873// A link or propose detector can never combine; an act detector can never
874// merely link through the combine's budget. Each mismatch is refused and
875// changes nothing.
876func TestHousekeepingClassActions(t *testing.T) {
877 r := newHKRig(t)
878 a := r.task("tka", "Swipe back from the edge doesn't work", hkOwner)
879 b := r.task("tkb", "Swipe back from the edge doesn't work again", hkOwner)
880 for _, c := range []struct {
881 class, action string
882 }{{housekeeping.ClassLink, housekeeping.ActionCombine}, {housekeeping.ClassPropose, housekeeping.ActionCombine}, {housekeeping.ClassAsk, housekeeping.ActionCombine}, {housekeeping.ClassAct, housekeeping.ActionLink}} {
883 d := housekeeping.Detector{ID: "x_" + c.class, Subject: housekeeping.SubjectTask, Class: c.class, Triggers: []string{housekeeping.TriggerSweep}, Judgement: housekeeping.JudgementNone}
884 f := combineFinding(b, a, hkOwner)
885 f.Detector, f.Proposal.Action = d.ID, c.action
886 if r.run(d, f) {
887 t.Errorf("%s detector ran %s", c.class, c.action)
888 }
889 if row, _ := r.row(hkOwner, d.ID, f.Key); row.State != wire.ActionRefused || row.Reason != wire.ReasonHousekeepingForbidden {
890 t.Errorf("%s with %s: %+v", c.class, c.action, row)
891 }
892 }
893 if k := r.load(b.ID); k.FoldedInto != "" || k.DuplicateOf != "" || k.Revision != b.Revision {
894 t.Fatalf("a mismatched proposal changed the task: %+v", k)
895 }
896 if n := r.count("SELECT COUNT(*) FROM chat_cards"); n != 0 {
897 t.Fatalf("a mismatched proposal left %d cards", n)
898 }
899}
900