Keep team budgets and uncertain actions bounded across recovery
14 files changed,
+643
−232
docs/superpowers/plans/2026-11-01-team-service.md+23 −0internal/team/actions.go+27 −68internal/team/actions_test.go+17 −69internal/team/budget.go+7 −3internal/team/evidence.go+10 −3internal/team/fixture_test.go+9 −9internal/team/jobs.go+3 −0internal/team/model.go+31 −19internal/team/recovery.go+47 −14internal/team/review_regression_test.go+336 −0internal/team/scheduler.go+2 −2internal/team/store.go+106 −43internal/team/store_test.go+3 −2internal/teamcontract/authority_test.go+22 −0
diff --git a/docs/superpowers/plans/2026-11-01-team-service.md b/docs/superpowers/plans/2026-11-01-team-service.md| index 90a4b90e0..5097b37ec 100644 |
| --- a/docs/superpowers/plans/2026-11-01-team-service.md |
| +++ b/docs/superpowers/plans/2026-11-01-team-service.md |
| @@ -38,6 +38,29 @@ authenticated runner transport and real integrations remain M2-M4 work. |
| Only records used by the local workflow are implemented in this first slice; |
| the unused conversation/memory contracts land with their M3 consumers. |
| +The implementation review narrowed recovery before live adapters exist. |
| +An admitted action is never automatically dispatched again, even when an |
| +adapter reports an absent effect. Recovery can record a positive receipt; |
| +otherwise the outcome remains unknown and its reservation stays charged. |
| +A conservative audited settlement allows unrelated work to resume without |
| +claiming the uncertain action succeeded. Retrying an undispatched attempt |
| +remains supported. |
| + |
| +Schema 2 adds an external transaction position to detect snapshots restored |
| +within the same process incarnation. Reads also advance this position in the |
| +prototype. Missing or mismatched history stays quarantined across reopens, |
| +even if no outstanding action survives in the snapshot. There is no automatic |
| +restore release or operator override in this slice. A hosted restore needs |
| +an explicit recovery protocol; the local witness is not a host-loss durability |
| +claim. Migration from schema 1 preserves records and quarantines its history. |
| + |
| +Before live adapters, bind evidence to authenticated runners, enforce provider |
| +request ceilings in the adapter, flag measured usage above its reservation, |
| +enforce elapsed job time beyond Claim, and implement supported waiting-state |
| +resolution. The review also records stricter check-count/provenance assertions, |
| +failed rework evidence consistency, numeric payload normalization and further |
| +business-fixture failure cases. These are follow-ups, not implemented claims. |
| + |
| ## M0: contracts and integration fixtures |
| Create `internal/team/model.go`, `policy.go` and fixture-only adapter |
diff --git a/internal/team/actions.go b/internal/team/actions.go| index f5fe6828b..c845c6294 100644 |
| --- a/internal/team/actions.go |
| +++ b/internal/team/actions.go |
| @@ -87,13 +87,13 @@ func hashBytes(b []byte) string { |
| return hex.EncodeToString(sum[:]) |
| } |
| -const actionColumns = `id, job_id, step_id, attempt_id, fence, key, operation, class, payload_hash, payload, state, reservation_id, grant_ref, grant_version, grant_epoch, admitted_at, admission_ends, receipt, last_error, created_at, updated_at` |
| +const actionColumns = `id, job_id, step_id, attempt_id, fence, key, operation, class, payload_hash, payload, state, reservation_id, grant_ref, grant_version, grant_epoch, admitted_at, admission_ends, receipt, last_error, created_at, updated_at, admitted_incarnation` |
| func scanAction(r rowScanner) (Action, error) { |
| var a Action |
| var op, class, state, admitted, ends, receipt, created, updated string |
| if err := r.Scan(&a.ID, &a.Job, &a.Step, &a.Attempt, &a.Fence, &a.Key, &op, &class, &a.PayloadHash, &a.Payload, &state, &a.Reservation, |
| - &a.Grant.Ref, &a.Grant.Version, &a.Grant.Epoch, &admitted, &ends, &receipt, &a.LastError, &created, &updated); err != nil { |
| + &a.Grant.Ref, &a.Grant.Version, &a.Grant.Epoch, &admitted, &ends, &receipt, &a.LastError, &created, &updated, &a.AdmittedIncarnation); err != nil { |
| return a, err |
| } |
| a.Operation, a.Class, a.State = Operation(op), ReplayClass(class), ActionState(state) |
| @@ -167,6 +167,9 @@ func (s *Store) Intend(ctx context.Context, scope Scope, h Handle, in IntentSpec |
| if err != nil { |
| return err |
| } |
| + if !operationAllowed(hd.step.Capability, in.Operation) { |
| + return fail(CodeScope, "capability %s cannot perform %s", hd.step.Capability, in.Operation) |
| + } |
| if in.Operation == OpForgePublish { |
| if err := checkPublication(ctx, tx, hd.job, payload); err != nil { |
| return err |
| @@ -332,8 +335,8 @@ func (s *Store) Admit(ctx context.Context, scope Scope, id ActionID) (Dispatch, |
| if err := checkBudget(ctx, tx, hd.job, Usage{}); err != nil { |
| return err |
| } |
| - _, err = tx.ExecContext(ctx, `UPDATE actions SET state='dispatching', grant_version=?, grant_epoch=?, admitted_at=?, admission_ends=?, updated_at=? WHERE id=? AND state='intent'`, |
| - adm.Version, adm.Epoch, ts(now), ts(adm.ExpiresAt), ts(now), int64(a.ID)) |
| + _, err = tx.ExecContext(ctx, `UPDATE actions SET state='dispatching', grant_version=?, grant_epoch=?, admitted_at=?, admission_ends=?, updated_at=?, admitted_incarnation=? WHERE id=? AND state='intent'`, |
| + adm.Version, adm.Epoch, ts(now), ts(adm.ExpiresAt), ts(now), s.incarnation, int64(a.ID)) |
| if err != nil { |
| return fail(CodeInvalid, "admit: %v", err) |
| } |
| @@ -428,7 +431,7 @@ func (s *Store) Lost(ctx context.Context, scope Scope, id ActionID, detail strin |
| if err != nil { |
| return err |
| } |
| - if a.State != ActionDispatching { |
| + if a.State != ActionDispatching && a.State != ActionUncertain { |
| return fail(CodeState, "action %d is %s", id, a.State) |
| } |
| if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error=?, updated_at=? WHERE id=?`, detail, ts(now), int64(a.ID)); err != nil { |
| @@ -460,23 +463,21 @@ func (s *Store) Dispatch(ctx context.Context, scope Scope, id ActionID) (Receipt |
| } |
| rc, execErr := ad.Execute(ctx, d) |
| if execErr != nil { |
| - if err := s.Lost(ctx, scope, id, execErr.Error()); err != nil { |
| + if err := s.Lost(context.WithoutCancel(ctx), scope, id, execErr.Error()); err != nil { |
| return Receipt{}, err |
| } |
| return Receipt{}, fail(CodeUncertain, "action %d: %v", id, execErr) |
| } |
| - if err := s.Record(ctx, scope, id, rc); err != nil { |
| + if err := s.Record(context.WithoutCancel(ctx), scope, id, rc); err != nil { |
| return Receipt{}, err |
| } |
| return rc, nil |
| } |
| -// Reconcile resolves an uncertain (or, after a restart, dispatching) |
| -// action through its adapter. A receipt is recorded. Definitive absence |
| -// returns the action to intent on its existing reservation, so a replay |
| -// goes through Admit again without a second paid execution. Without a |
| -// definitive answer only read-only and idempotent operations may replay; |
| -// reconcilable and unsafe ones stay uncertain (ErrUncertain). |
| +// Reconcile recovers a receipt for an uncertain action. This prototype never |
| +// automatically redispatches an admitted operation: even a missing effect |
| +// does not prove that no request is still running or that no usage was billed. |
| +// Unknown outcomes retain their reservation until a receipt or audited charge. |
| func (s *Store) Reconcile(ctx context.Context, scope Scope, id ActionID) (Action, error) { |
| var a Action |
| err := s.tx(ctx, func(tx *sql.Tx) error { |
| @@ -485,7 +486,13 @@ func (s *Store) Reconcile(ctx context.Context, scope Scope, id ActionID) (Action |
| return err |
| } |
| a, err = loadAction(ctx, tx, j.ID, id) |
| - return err |
| + if err != nil { |
| + return err |
| + } |
| + if a.State == ActionDispatching && a.AdmittedIncarnation == s.incarnation { |
| + return fail(CodeState, "action %d may still be executing in this incarnation", id) |
| + } |
| + return nil |
| }) |
| if err != nil { |
| return a, err |
| @@ -505,67 +512,19 @@ func (s *Store) Reconcile(ctx context.Context, scope Scope, id ActionID) (Action |
| } |
| return s.GetAction(ctx, scope, id) |
| } |
| - replay := rerr == nil && res.Definitive |
| - if !replay && (a.Class == ReplayReadOnly || a.Class == ReplayIdempotent) { |
| - replay = true |
| - } |
| - detail := "no definitive answer" |
| + detail := "no receipt; automatic redispatch is not supported" |
| if rerr != nil { |
| detail = rerr.Error() |
| } |
| - err = s.tx(ctx, func(tx *sql.Tx) error { |
| - now := s.clock.Now() |
| - j, err := loadJob(ctx, tx, scope) |
| - if err != nil { |
| - return err |
| - } |
| - cur, err := loadAction(ctx, tx, j.ID, id) |
| - if err != nil { |
| - return err |
| - } |
| - if !cur.State.inFlight() { |
| - return fail(CodeState, "action %d is %s", id, cur.State) |
| - } |
| - if !replay { |
| - if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error=?, updated_at=? WHERE id=?`, detail, ts(now), int64(id)); err != nil { |
| - return fail(CodeInvalid, "reconcile: %v", err) |
| - } |
| - if !j.State.Terminal() && !(j.State == JobWaiting && j.Wait == WaitUncertainOutcome) { |
| - if _, err := bumpJob(ctx, tx, j, JobWaiting, WaitUncertainOutcome, j.Outcome, now); err != nil { |
| - return err |
| - } |
| - } |
| - return appendEvent(ctx, tx, scope, "action.uncertain", "broker", map[string]any{"action": id, "key": cur.Key, "detail": detail, "class": cur.Class}, now) |
| - } |
| - if j.State.Terminal() { |
| - // Nothing to replay for: the intent is revoked and its reservation released. |
| - if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='revoked', last_error=?, updated_at=? WHERE id=?`, detail, ts(now), int64(id)); err != nil { |
| - return fail(CodeInvalid, "reconcile: %v", err) |
| - } |
| - if _, err := tx.ExecContext(ctx, `UPDATE reservations SET state='released', settled_at=? WHERE id=? AND state='open'`, ts(now), int64(cur.Reservation)); err != nil { |
| - return fail(CodeInvalid, "release: %v", err) |
| - } |
| - return appendEvent(ctx, tx, scope, "action.revoked", "broker", map[string]any{"action": id, "key": cur.Key, "detail": "absent upstream; job " + string(j.State)}, now) |
| - } |
| - if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='intent', last_error=?, updated_at=? WHERE id=?`, detail, ts(now), int64(id)); err != nil { |
| - return fail(CodeInvalid, "reconcile: %v", err) |
| - } |
| - if err := appendEvent(ctx, tx, scope, "action.replayable", "broker", map[string]any{"action": id, "key": cur.Key, "definitive": rerr == nil && res.Definitive, "class": cur.Class}, now); err != nil { |
| - return err |
| - } |
| - return resumeIfResolved(ctx, tx, j, now) |
| - }) |
| + err = s.Lost(ctx, scope, id, detail) |
| if err != nil { |
| return a, err |
| } |
| - a, gerr := s.GetAction(ctx, scope, id) |
| - if gerr != nil { |
| - return a, gerr |
| - } |
| - if !replay { |
| - return a, fail(CodeUncertain, "action %d: %s", id, detail) |
| + a, err = s.GetAction(ctx, scope, id) |
| + if err != nil { |
| + return a, err |
| } |
| - return a, nil |
| + return a, fail(CodeUncertain, "action %d: %s", id, detail) |
| } |
| // GetAction reads one action. |
diff --git a/internal/team/actions_test.go b/internal/team/actions_test.go| index a32d99622..85a844ce8 100644 |
| --- a/internal/team/actions_test.go |
| +++ b/internal/team/actions_test.go |
| @@ -53,14 +53,15 @@ func TestPublicationIsBoundToTargetAndCandidate(t *testing.T) { |
| e := newEnv(t) |
| _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| w := e.workflow(scope) |
| - _, _, err := w.Reproduce(e.ctx, []byte(FixtureBaseSource)) |
| + repro, _, err := w.Reproduce(e.ctx, []byte(FixtureBaseSource)) |
| must(t, err) |
| cand, err := w.Implement(e.ctx, "implement", "ws-implement-1") |
| must(t, err) |
| - // The publish step depends on verify; use a graph-free check through a |
| - // claim on review (publish capability is not required for Intend's |
| - // binding checks, which run before any role logic). |
| - h := e.claim(scope, "review", "runner-b", "ws-review-1") |
| + _, err = w.ReviewCandidate(e.ctx, "ws-review-1", cand) |
| + must(t, err) |
| + _, err = w.Verify(e.ctx, repro, cand) |
| + must(t, err) |
| + h := e.claim(scope, "publish", "runner-a", "ws-publish-1") |
| try := func(repo, ref, head string) error { |
| _, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: "pub/" + repo + ref + short(head), Operation: OpForgePublish, |
| Payload: mustJSON(publication{Repository: repo, Ref: ref, Head: head})}) |
| @@ -73,7 +74,7 @@ func TestPublicationIsBoundToTargetAndCandidate(t *testing.T) { |
| wantCode(t, err, CodeInvalid) |
| must(t, try("example/shop", "team/fix-sum", cand.Hash)) |
| acts, _ := e.store.Actions(e.ctx, scope) |
| - if len(acts) != 2 { // the implement call and the one accepted publication |
| + if len(acts) != 3 { // implement, review and the accepted publication |
| t.Fatalf("%d actions", len(acts)) |
| } |
| } |
| @@ -127,78 +128,25 @@ func TestLostReplyNeverReplaysBlind(t *testing.T) { |
| } |
| } |
| -func TestReconcileClasses(t *testing.T) { |
| +func TestReconcileWithoutReceiptNeverRedispatches(t *testing.T) { |
| e := newEnv(t) |
| _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| - w := e.workflow(scope) |
| - repro, _, err := w.Reproduce(e.ctx, []byte(FixtureBaseSource)) |
| - must(t, err) |
| - cand, err := w.Implement(e.ctx, "implement", "ws-implement-1") |
| - must(t, err) |
| - _, err = w.ReviewCandidate(e.ctx, "ws-review-1", cand) |
| - must(t, err) |
| - _, err = w.Verify(e.ctx, repro, cand) |
| + h := e.claim(scope, "reproduce", "runner-a", "ws-1") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("lost", Usage{InputTokens: 10, OutputTokens: 10})) |
| must(t, err) |
| - h := e.claim(scope, "publish", "runner-a", "ws-publish-1") |
| - job := e.job(scope) |
| - pub := func(key string) ActionID { |
| - id, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: key, Operation: OpForgePublish, Payload: mustJSON(publication{Repository: job.Target.Repository, Ref: job.Target.Ref, Head: cand.Hash})}) |
| - must(t, err) |
| - return id |
| - } |
| - // Reconcilable, forge cannot answer definitively and holds nothing: wait. |
| - e.forge.SetDefinitive(false) |
| - id := pub("pub/1") |
| _, err = e.store.Admit(e.ctx, scope, id) |
| must(t, err) |
| - must(t, e.store.Lost(e.ctx, scope, id, "timeout before send")) |
| + must(t, e.store.Lost(e.ctx, scope, id, "reply lost")) |
| _, err = e.store.Reconcile(e.ctx, scope, id) |
| wantCode(t, err, CodeUncertain) |
| - a, _ := e.store.GetAction(e.ctx, scope, id) |
| - if a.State != ActionUncertain { |
| - t.Fatalf("action %s", a.State) |
| - } |
| - // Definitive absence: back to intent on the same reservation, replayable. |
| - e.forge.SetDefinitive(true) |
| - a, err = e.store.Reconcile(e.ctx, scope, id) |
| - must(t, err) |
| - if a.State != ActionIntent { |
| - t.Fatalf("action %s", a.State) |
| - } |
| - if j := e.job(scope); j.State != JobRunning { |
| - t.Fatalf("job %s", j.State) |
| - } |
| - res, _ := e.store.Reservations(e.ctx, scope) |
| - open := 0 |
| - for _, r := range res { |
| - if r.State == ReservationOpen { |
| - open++ |
| - } |
| - } |
| - if open != 1 { |
| - t.Fatalf("%d open reservations", open) |
| - } |
| - rc, err := e.store.Dispatch(e.ctx, scope, id) |
| - must(t, err) |
| - if rc.Outcome != OutcomeSuccess { |
| - t.Fatalf("receipt %+v", rc) |
| - } |
| - // Idempotent class (tracker): lost reply replays without a definitive answer. |
| - tid, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: "milestone/1", Operation: OpTrackerPublish, Payload: []byte(`{"event":"review_opened"}`)}) |
| - must(t, err) |
| - _, err = e.store.Admit(e.ctx, scope, tid) |
| + _, err = e.store.Dispatch(e.ctx, scope, id) |
| + wantCode(t, err, CodeState) |
| + _, err = e.store.Cancel(e.ctx, scope, "operator", "stop") |
| must(t, err) |
| - must(t, e.store.Lost(e.ctx, scope, tid, "socket closed")) |
| - a, err = e.store.Reconcile(e.ctx, scope, tid) |
| + rows, err := e.store.Reservations(e.ctx, scope) |
| must(t, err) |
| - if a.State != ActionIntent { |
| - t.Fatalf("tracker action %s", a.State) |
| - } |
| - if _, err := e.store.Dispatch(e.ctx, scope, tid); err != nil { |
| - t.Fatal(err) |
| - } |
| - if e.tracker.Events() != 1 { |
| - t.Fatalf("tracker events %d", e.tracker.Events()) |
| + if len(rows) != 1 || rows[0].State != ReservationOpen { |
| + t.Fatalf("lost usage was released: %+v", rows) |
| } |
| } |
diff --git a/internal/team/budget.go b/internal/team/budget.go| index 167f39031..faad98b47 100644 |
| --- a/internal/team/budget.go |
| +++ b/internal/team/budget.go |
| @@ -95,15 +95,19 @@ func reserve(ctx context.Context, tx *sql.Tx, j jobRow, step StepID, attempt Att |
| if err := want.validate(); err != nil { |
| return 0, want, err |
| } |
| - priced, err := j.Policy.price(op, want) |
| + account, err := accountPolicy(ctx, tx, j.Account) |
| + if err != nil { |
| + return 0, want, err |
| + } |
| + priced, err := account.price(op, want) |
| if err != nil { |
| return 0, want, err |
| } |
| if priced.Calls != 1 { |
| return 0, want, fail(CodeInvalid, "a reservation covers exactly one call") |
| } |
| - if !priced.within(j.Policy.reserveLimits(op)) { |
| - return 0, want, fail(CodeBudget, "reservation %+v exceeds per-call %+v", priced, j.Policy.reserveLimits(op)) |
| + if !priced.within(account.reserveLimits(op)) { |
| + return 0, want, fail(CodeBudget, "reservation %+v exceeds per-call %+v", priced, account.reserveLimits(op)) |
| } |
| if err := checkBudget(ctx, tx, j, priced); err != nil { |
| return 0, want, err |
diff --git a/internal/team/evidence.go b/internal/team/evidence.go| index a70fdbab1..16a836bc8 100644 |
| --- a/internal/team/evidence.go |
| +++ b/internal/team/evidence.go |
| @@ -248,12 +248,19 @@ func (s *Store) Conclude(ctx context.Context, scope Scope, actor string) (Eviden |
| return fail(CodeState, "job %d is %s", j.ID, j.State) |
| } |
| var live int |
| - if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts WHERE job_id=? AND state IN ('active','stopping')`, int64(j.ID)).Scan(&live); err != nil { |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts WHERE job_id=? AND containment='pending'`, int64(j.ID)).Scan(&live); err != nil { |
| return fail(CodeInvalid, "attempts: %v", err) |
| } |
| if live > 0 { |
| return fail(CodeState, "job %d has %d live attempts", j.ID, live) |
| } |
| + var children int |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM jobs WHERE parent=? AND state NOT IN ('succeeded','failed','cancelled')`, int64(j.ID)).Scan(&children); err != nil { |
| + return fail(CodeInvalid, "children: %v", err) |
| + } |
| + if children != 0 { |
| + return fail(CodeState, "job %d has %d unfinished children", j.ID, children) |
| + } |
| switch j.Evidence.Predicate { |
| case PredicateSoftwareFix: |
| rep, err = evaluateSoftwareFix(ctx, tx, j) |
| @@ -274,7 +281,7 @@ func (s *Store) Conclude(ctx context.Context, scope Scope, actor string) (Eviden |
| return err |
| } |
| } else { |
| - if _, err := bumpJob(ctx, tx, j, JobSucceeded, WaitNone, outcome, now); err != nil { |
| + if _, err := terminate(ctx, tx, j, JobSucceeded, actor, outcome, now); err != nil { |
| return err |
| } |
| } |
| @@ -374,7 +381,7 @@ func evaluateSoftwareFix(ctx context.Context, tx *sql.Tx, j jobRow) (EvidenceRep |
| return miss("candidate result is " + string(vr.Outcome) + " with " + itoa(vr.TestsRun) + " run and " + itoa(vr.TestsFailed) + " failed; expected a pass") |
| } |
| rep.CandidateResult = cr.Hash |
| - rows, err := tx.QueryContext(ctx, `SELECT `+actionColumns+` FROM actions WHERE job_id=? AND operation=? AND state='succeeded' ORDER BY id DESC`, int64(j.ID), string(OpForgePublish)) |
| + rows, err := tx.QueryContext(ctx, `SELECT `+actionColumns+` FROM actions WHERE job_id=? AND operation=? AND state='succeeded' AND step_id IN (SELECT id FROM steps WHERE job_id=? AND capability=?) ORDER BY id DESC`, int64(j.ID), string(OpForgePublish), int64(j.ID), string(CapPublish)) |
| if err != nil { |
| return rep, fail(CodeInvalid, "publications: %v", err) |
| } |
diff --git a/internal/team/fixture_test.go b/internal/team/fixture_test.go| index d498d58dd..0faf52915 100644 |
| --- a/internal/team/fixture_test.go |
| +++ b/internal/team/fixture_test.go |
| @@ -274,7 +274,7 @@ func TestFixture(t *testing.T) { |
| t.Logf("clean restart: incarnation %d, job %s", st.Incarnation, e.job(scope).State) |
| }) |
| - t.Run("crash_after_admit_then_recover", func(t *testing.T) { |
| + t.Run("crash_after_publication_before_receipt_recorded", func(t *testing.T) { |
| e := newEnv(t) |
| _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| w := e.workflow(scope) |
| @@ -291,9 +291,11 @@ func TestFixture(t *testing.T) { |
| payload := mustJSON(publication{Repository: job.Target.Repository, Ref: job.Target.Ref, Head: cand.Hash}) |
| id, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: "publish/" + short(cand.Hash), Operation: OpForgePublish, Payload: payload}) |
| must(t, err) |
| - _, err = e.store.Admit(e.ctx, scope, id) |
| + d, err := e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + _, err = e.forge.Execute(e.ctx, d) |
| must(t, err) |
| - // Process dies between admission and the adapter call. |
| + // The forge has the receipt; the store dies before recording it. |
| e.crash() |
| e.openNoResume() |
| w = e.workflow(scope) |
| @@ -312,12 +314,10 @@ func TestFixture(t *testing.T) { |
| } |
| a, err := e.store.GetAction(e.ctx, scope, id) |
| must(t, err) |
| - if a.State != ActionIntent { |
| - t.Fatalf("action after definitive absence: %s", a.State) |
| + if a.State != ActionSucceeded || a.Receipt == nil { |
| + t.Fatalf("action after receipt recovery: %+v", a) |
| } |
| - rc, err := e.store.Dispatch(e.ctx, scope, id) |
| - must(t, err) |
| - must(t, w.FinishPublish(e.ctx, h, cand, rc)) |
| + must(t, w.FinishPublish(e.ctx, h, cand, *a.Receipt)) |
| rep, err := w.Conclude(e.ctx) |
| must(t, err) |
| if !rep.Satisfied { |
| @@ -361,7 +361,7 @@ func TestFixture(t *testing.T) { |
| t.Fatalf("resume %+v job %s", rr, j.State) |
| } |
| _, err = s.Claim(e.ctx, scope, "implement", "runner-a", "ws-implement-2") |
| - wantCode(t, err, CodeState) |
| + wantCode(t, err, CodeAdmissionPaused) |
| }) |
| t.Run("authority_unavailable_fails_closed", func(t *testing.T) { |
diff --git a/internal/team/jobs.go b/internal/team/jobs.go| index fe919aabe..fd6b68c63 100644 |
| --- a/internal/team/jobs.go |
| +++ b/internal/team/jobs.go |
| @@ -130,6 +130,9 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| if err == nil && spec.Policy.Account != account.Account { |
| return fail(CodeConflict, "job cannot change the account budget") |
| } |
| + if err == nil && (spec.Policy.Rates != account.Rates || spec.Policy.PerCall != account.PerCall) { |
| + return fail(CodeConflict, "job cannot change account prices or per-call ceilings") |
| + } |
| depth := 0 |
| if spec.Parent != 0 { |
| parent, err := loadJob(ctx, tx, Scope{Account: spec.Account, Job: spec.Parent}) |
diff --git a/internal/team/model.go b/internal/team/model.go| index 83215dba4..d0b877ba3 100644 |
| --- a/internal/team/model.go |
| +++ b/internal/team/model.go |
| @@ -503,6 +503,17 @@ func (o Operation) external() bool { |
| return o == OpProviderCall || o == OpForgePublish || o == OpTrackerPublish |
| } |
| +func operationAllowed(cap Capability, op Operation) bool { |
| + switch op { |
| + case OpProviderCall: |
| + return cap.Valid() |
| + case OpForgePublish, OpTrackerPublish: |
| + return cap == CapPublish |
| + default: |
| + return false |
| + } |
| +} |
| + |
| // ReplayClass is the adapter's classification of an operation. |
| type ReplayClass string |
| @@ -564,25 +575,26 @@ type IntentSpec struct { |
| // Action is the durable action record. |
| type Action struct { |
| - ID ActionID |
| - Job JobID |
| - Step StepID |
| - Attempt AttemptID |
| - Fence int64 |
| - Key string |
| - Operation Operation |
| - Class ReplayClass |
| - PayloadHash string |
| - Payload []byte |
| - State ActionState |
| - Reservation ReservationID |
| - Grant GrantSnapshot |
| - AdmittedAt time.Time |
| - AdmissionEnds time.Time |
| - Receipt *Receipt |
| - LastError string |
| - CreatedAt time.Time |
| - UpdatedAt time.Time |
| + AdmittedIncarnation int64 |
| + ID ActionID |
| + Job JobID |
| + Step StepID |
| + Attempt AttemptID |
| + Fence int64 |
| + Key string |
| + Operation Operation |
| + Class ReplayClass |
| + PayloadHash string |
| + Payload []byte |
| + State ActionState |
| + Reservation ReservationID |
| + Grant GrantSnapshot |
| + AdmittedAt time.Time |
| + AdmissionEnds time.Time |
| + Receipt *Receipt |
| + LastError string |
| + CreatedAt time.Time |
| + UpdatedAt time.Time |
| } |
| // Dispatch is the admitted, immutable request an adapter executes. |
diff --git a/internal/team/recovery.go b/internal/team/recovery.go| index 2588d769e..b0dde2023 100644 |
| --- a/internal/team/recovery.go |
| +++ b/internal/team/recovery.go |
| @@ -26,11 +26,13 @@ type ResumeReport struct { |
| // (ErrAuthorityUnavailable) with nothing resumed. Every action left |
| // dispatching by the previous incarnation becomes uncertain and is |
| // reconciled through its adapter; what stays uncertain keeps its job |
| -// waiting. Ordinary crash recovery then opens admission. A quarantined |
| -// store (missing or mismatched marker, unclean shutdown) also needs every |
| -// in-flight action resolved before quarantine clears; until then it stays |
| -// paused. |
| +// waiting. After an unclean shutdown, all uncertain actions need receipts |
| +// or conservative audited charges before admission reopens. Missing or |
| +// mismatched external history stays quarantined: this prototype has no |
| +// operator recovery API for a restored snapshot. |
| func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| var rep ResumeReport |
| type jobRef struct { |
| scope Scope |
| @@ -39,6 +41,20 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| } |
| var jobs []jobRef |
| err := s.tx(ctx, func(tx *sql.Tx) error { |
| + var paused, restore int |
| + if err := tx.QueryRowContext(ctx, `SELECT admission_paused, restore_uncertain FROM service WHERE id=1`).Scan(&paused, &restore); err != nil { |
| + return err |
| + } |
| + if paused == 0 { |
| + return fail(CodeState, "recovery requires paused admission") |
| + } |
| + // An old snapshot's intents may have executed after the backup. |
| + // Classify them before revocation can otherwise release their budgets. |
| + if restore != 0 { |
| + if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='restored intent may have executed after snapshot' WHERE state='intent'`); err != nil { |
| + return err |
| + } |
| + } |
| rows, err := tx.QueryContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE state NOT IN ('succeeded','failed','cancelled') ORDER BY id`) |
| if err != nil { |
| return fail(CodeInvalid, "jobs: %v", err) |
| @@ -72,6 +88,9 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| if err != nil { |
| return err |
| } |
| + if j.State.Terminal() { |
| + return nil |
| + } |
| now := s.clock.Now() |
| if _, err := tx.ExecContext(ctx, `UPDATE jobs SET grant_version=?, grant_epoch=?, grant_observed_at=? WHERE id=?`, adm.Version, adm.Epoch, ts(now), int64(j.ID)); err != nil { |
| return fail(CodeInvalid, "snapshot: %v", err) |
| @@ -95,10 +114,10 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| var acts []actRef |
| err = s.tx(ctx, func(tx *sql.Tx) error { |
| now := s.clock.Now() |
| - if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='incarnation ended while dispatching', updated_at=? WHERE state='dispatching'`, ts(now)); err != nil { |
| + if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='incarnation ended while dispatching', updated_at=? WHERE state='dispatching' AND admitted_incarnation<>?`, ts(now), s.incarnation); err != nil { |
| return fail(CodeInvalid, "actions: %v", err) |
| } |
| - rows, err := tx.QueryContext(ctx, `SELECT a.id, j.id, j.account FROM actions a JOIN jobs j ON j.id=a.job_id WHERE a.state='uncertain' ORDER BY a.id`) |
| + rows, err := tx.QueryContext(ctx, `SELECT a.id, j.id, j.account FROM actions a JOIN jobs j ON j.id=a.job_id JOIN reservations r ON r.id=a.reservation_id WHERE a.state='uncertain' AND r.state<>'settled_audited' ORDER BY a.id`) |
| if err != nil { |
| return fail(CodeInvalid, "actions: %v", err) |
| } |
| @@ -128,29 +147,43 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| } |
| err = s.tx(ctx, func(tx *sql.Tx) error { |
| now := s.clock.Now() |
| - rows, err := tx.QueryContext(ctx, `SELECT id FROM attempts WHERE state='active' AND lease_deadline<=?`, ts(now)) |
| + // RFC3339Nano omits trailing fractional zeros; text order is not |
| + // time order. Compare parsed deadlines, including old stored rows. |
| + rows, err := tx.QueryContext(ctx, `SELECT id, lease_deadline FROM attempts WHERE state='active'`) |
| if err != nil { |
| return fail(CodeInvalid, "attempts: %v", err) |
| } |
| for rows.Next() { |
| var id int64 |
| - if err := rows.Scan(&id); err != nil { |
| + var deadline string |
| + if err := rows.Scan(&id, &deadline); err != nil { |
| rows.Close() |
| return fail(CodeInvalid, "attempts: %v", err) |
| } |
| - rep.Expired = append(rep.Expired, AttemptID(id)) |
| + if !parseTS(deadline).After(now) { |
| + rep.Expired = append(rep.Expired, AttemptID(id)) |
| + } |
| + } |
| + if err := rows.Err(); err != nil { |
| + rows.Close() |
| + return err |
| } |
| rows.Close() |
| - if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='expired', updated_at=? WHERE state='active' AND lease_deadline<=?`, ts(now), ts(now)); err != nil { |
| - return fail(CodeInvalid, "expire: %v", err) |
| + for _, id := range rep.Expired { |
| + if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='expired', updated_at=? WHERE id=? AND state='active'`, ts(now), int64(id)); err != nil { |
| + return fail(CodeInvalid, "expire: %v", err) |
| + } |
| } |
| - var quarantine int |
| + var quarantine, restore int |
| var why string |
| - if err := tx.QueryRowContext(ctx, `SELECT quarantine, quarantine_why FROM service WHERE id=1`).Scan(&quarantine, &why); err != nil { |
| + if err := tx.QueryRowContext(ctx, `SELECT quarantine, quarantine_why, restore_uncertain FROM service WHERE id=1`).Scan(&quarantine, &why, &restore); err != nil { |
| return fail(CodeInvalid, "service: %v", err) |
| } |
| - if quarantine != 0 && len(rep.Unresolved) > 0 { |
| + if restore != 0 || (quarantine != 0 && len(rep.Unresolved) > 0) { |
| rep.Quarantine, rep.Why = true, why+"; "+itoa(len(rep.Unresolved))+" actions unresolved" |
| + if restore != 0 { |
| + rep.Why = "restored history requires operator recovery; missing post-snapshot work cannot be inferred" |
| + } |
| _, err := tx.ExecContext(ctx, `UPDATE service SET quarantine_why=? WHERE id=1`, rep.Why) |
| if err != nil { |
| return fail(CodeInvalid, "service: %v", err) |
diff --git a/internal/team/review_regression_test.go b/internal/team/review_regression_test.go| new file mode 100644 |
| index 000000000..9b93aead5 |
| --- /dev/null |
| +++ b/internal/team/review_regression_test.go |
| @@ -0,0 +1,336 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "os" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| +) |
| + |
| +func TestAccountQuotesCannotBeChangedByJobs(t *testing.T) { |
| + e := newEnv(t) |
| + parent, _ := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + for _, child := range []bool{false, true} { |
| + for _, change := range []func(*Policy){ |
| + func(p *Policy) { p.Rates = Rates{Version: 1} }, |
| + func(p *Policy) { p.PerCall.InputTokens++ }, |
| + } { |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + if child { |
| + spec.Parent = parent.ID |
| + } |
| + change(&spec.Policy) |
| + _, err := e.store.CreateJob(e.ctx, spec) |
| + wantCode(t, err, CodeConflict) |
| + } |
| + } |
| +} |
| + |
| +type controlledAdapter struct { |
| + class ReplayClass |
| + execute func(context.Context, Dispatch) (Receipt, error) |
| + reconciles atomic.Int64 |
| +} |
| + |
| +func (a *controlledAdapter) Classify(Operation) (ReplayClass, error) { return a.class, nil } |
| +func (a *controlledAdapter) Execute(ctx context.Context, d Dispatch) (Receipt, error) { |
| + return a.execute(ctx, d) |
| +} |
| +func (a *controlledAdapter) Reconcile(context.Context, Dispatch) (ReconcileResult, error) { |
| + a.reconciles.Add(1) |
| + return ReconcileResult{Definitive: true}, nil |
| +} |
| + |
| +func TestEveryReplayClassRetainsUnknownUsage(t *testing.T) { |
| + for _, class := range []ReplayClass{ReplayReadOnly, ReplayIdempotent, ReplayReconcilable, ReplayUnsafe} { |
| + t.Run(string(class), func(t *testing.T) { |
| + e := newEnv(t) |
| + ad := &controlledAdapter{class: class, execute: func(context.Context, Dispatch) (Receipt, error) { |
| + return Receipt{}, errors.New("lost reply") |
| + }} |
| + e.store.adapters[OpProviderCall] = ad |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "r", "ws") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| + must(t, err) |
| + _, err = e.store.Dispatch(e.ctx, scope, id) |
| + wantCode(t, err, CodeUncertain) |
| + _, err = e.store.Reconcile(e.ctx, scope, id) |
| + wantCode(t, err, CodeUncertain) |
| + _, err = e.store.Dispatch(e.ctx, scope, id) |
| + wantCode(t, err, CodeState) |
| + _, err = e.store.Cancel(e.ctx, scope, "operator", "stop") |
| + must(t, err) |
| + rows, err := e.store.Reservations(e.ctx, scope) |
| + must(t, err) |
| + if len(rows) != 1 || rows[0].State != ReservationOpen { |
| + t.Fatalf("unknown usage released: %+v", rows) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestLiveDispatchCannotBeReconciledOrResumed(t *testing.T) { |
| + e := newEnv(t) |
| + entered, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{}) |
| + var releaseOnce sync.Once |
| + finish := func() { releaseOnce.Do(func() { close(release) }) } |
| + var dispatchErr error |
| + ad := &controlledAdapter{class: ReplayReconcilable, execute: func(context.Context, Dispatch) (Receipt, error) { |
| + close(entered) |
| + <-release |
| + return Receipt{ID: "one-effect", Outcome: OutcomeSuccess, Usage: &Usage{Calls: 1, InputTokens: 1, CostMicros: 1003}}, nil |
| + }} |
| + e.store.adapters[OpProviderCall] = ad |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "r", "ws") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| + must(t, err) |
| + go func() { _, dispatchErr = e.store.Dispatch(e.ctx, scope, id); close(done) }() |
| + t.Cleanup(func() { finish(); <-done }) |
| + <-entered |
| + _, err = e.store.Reconcile(e.ctx, scope, id) |
| + wantCode(t, err, CodeState) |
| + _, err = e.store.Resume(e.ctx) |
| + wantCode(t, err, CodeState) |
| + if ad.reconciles.Load() != 0 { |
| + t.Fatal("queried a potentially live operation") |
| + } |
| + finish() |
| + <-done |
| + must(t, dispatchErr) |
| +} |
| + |
| +func TestCancelledCallerStillRecordsLostOutcome(t *testing.T) { |
| + e := newEnv(t) |
| + ctx, cancel := context.WithCancel(e.ctx) |
| + defer cancel() |
| + e.store.adapters[OpProviderCall] = &controlledAdapter{class: ReplayUnsafe, execute: func(context.Context, Dispatch) (Receipt, error) { |
| + cancel() |
| + return Receipt{}, context.Canceled |
| + }} |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "r", "ws") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| + must(t, err) |
| + _, err = e.store.Dispatch(ctx, scope, id) |
| + wantCode(t, err, CodeUncertain) |
| + a, err := e.store.GetAction(e.ctx, scope, id) |
| + must(t, err) |
| + if a.State != ActionUncertain { |
| + t.Fatalf("action remained %s", a.State) |
| + } |
| +} |
| + |
| +func TestAuditedUnknownUsageDoesNotQuarantineOtherJobs(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "r", "ws") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 10, OutputTokens: 10})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + must(t, e.store.Lost(e.ctx, scope, id, "lost reply")) |
| + e.crash() |
| + e.openNoResume() |
| + rr, err := e.store.Resume(e.ctx) |
| + must(t, err) |
| + if !rr.Quarantine || rr.Resumed { |
| + t.Fatalf("unexpected recovery: %+v", rr) |
| + } |
| + rows, err := e.store.Reservations(e.ctx, scope) |
| + must(t, err) |
| + _, err = e.store.SettleAudited(e.ctx, scope, rows[0].ID, "operator", "charge the full reservation; outcome remains unknown") |
| + must(t, err) |
| + rr, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + if !rr.Resumed { |
| + t.Fatalf("audit did not release unrelated work: %+v", rr) |
| + } |
| + a, _ := e.store.GetAction(e.ctx, scope, id) |
| + if a.State != ActionUncertain { |
| + t.Fatal("audit fabricated a successful result") |
| + } |
| +} |
| + |
| +func TestUncontainedAttemptsKeepTheirConcurrencySlot(t *testing.T) { |
| + for _, expired := range []bool{false, true} { |
| + t.Run(itoa(map[bool]int{false: 0, true: 1}[expired]), func(t *testing.T) { |
| + e := newEnv(t) |
| + spec := softwareSpec([]StepSpec{{Key: "one", Capability: CapReproduce, Version: 1}, {Key: "two", Capability: CapReproduce, Version: 1}}) |
| + spec.Policy.MaxConcurrentAttempts = 1 |
| + _, scope := e.createJob(spec) |
| + h := e.claim(scope, "one", "r1", "ws1") |
| + if expired { |
| + e.clock.Advance(spec.Policy.lease() + 1) |
| + e.crash() |
| + e.openNoResume() |
| + rr, err := e.store.Resume(e.ctx) |
| + must(t, err) |
| + if len(rr.Expired) != 1 || rr.Expired[0] != h.Attempt { |
| + t.Fatalf("expired attempt not recovered: %+v", rr) |
| + } |
| + } else { |
| + must(t, e.store.Complete(e.ctx, scope, h, AttemptResult{Outcome: OutcomeSuccess})) |
| + } |
| + _, err := e.store.Claim(e.ctx, scope, "two", "r2", "ws2") |
| + wantCode(t, err, CodeQuota) |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + _, err = e.store.Claim(e.ctx, scope, "two", "r2", "ws2") |
| + must(t, err) |
| + }) |
| + } |
| +} |
| + |
| +func TestReviewerCannotPublish(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec([]StepSpec{{Key: "review", Capability: CapReview, Version: 1}})) |
| + h := e.claim(scope, "review", "reviewer", "review-workspace") |
| + for _, op := range []Operation{OpForgePublish, OpTrackerPublish} { |
| + _, err := e.store.Intend(e.ctx, scope, h, IntentSpec{Key: string(op), Operation: op, Payload: []byte(`{}`)}) |
| + wantCode(t, err, CodeScope) |
| + } |
| + rows, err := e.store.Reservations(e.ctx, scope) |
| + must(t, err) |
| + if len(rows) != 0 { |
| + t.Fatal("refused publication consumed a reservation") |
| + } |
| +} |
| + |
| +func TestConcludeWaitsForChildren(t *testing.T) { |
| + e := newEnv(t) |
| + parent, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + spec.Parent = parent.ID |
| + e.createJob(spec) |
| + _, err := e.store.Conclude(e.ctx, scope, "operator") |
| + wantCode(t, err, CodeState) |
| + if e.job(scope).State.Terminal() { |
| + t.Fatal("parent concluded with unfinished children") |
| + } |
| +} |
| + |
| +func TestConcludeRevokesUnusedIntents(t *testing.T) { |
| + e := newEnv(t) |
| + steps := append(SoftwareSteps(false), StepSpec{Key: "optional", Capability: CapReproduce, Version: 1}) |
| + spec := softwareSpec(steps) |
| + _, scope := e.createJob(spec) |
| + w := e.workflow(scope) |
| + repro, _, err := w.Reproduce(e.ctx, []byte(FixtureBaseSource)) |
| + must(t, err) |
| + cand, err := w.Implement(e.ctx, "implement", "ws-implement-1") |
| + must(t, err) |
| + _, err = w.ReviewCandidate(e.ctx, "ws-review-1", cand) |
| + must(t, err) |
| + _, err = w.Verify(e.ctx, repro, cand) |
| + must(t, err) |
| + _, _, err = w.Publish(e.ctx, cand) |
| + must(t, err) |
| + h := e.claim(scope, "optional", "runner", "ws-optional") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("unused", Usage{InputTokens: 10, OutputTokens: 10})) |
| + must(t, err) |
| + e.clock.Advance(spec.Policy.lease() + 1) |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + rep, err := w.Conclude(e.ctx) |
| + must(t, err) |
| + if !rep.Satisfied { |
| + t.Fatalf("unexpected evidence: %+v", rep) |
| + } |
| + a, err := e.store.GetAction(e.ctx, scope, id) |
| + must(t, err) |
| + if a.State != ActionRevoked { |
| + t.Fatalf("success left an unused intent: %+v", a) |
| + } |
| + ledger, err := e.store.Ledger(e.ctx, scope) |
| + must(t, err) |
| + if ledger.Reserved != (Usage{}) { |
| + t.Fatalf("success kept an unused reservation: %+v", ledger) |
| + } |
| +} |
| + |
| +func TestSameIncarnationSnapshotCannotRepeatAnIntent(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "r", "ws") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("call", Usage{InputTokens: 100, OutputTokens: 100})) |
| + must(t, err) |
| + backup := e.snapshot() |
| + _, err = e.store.Dispatch(e.ctx, scope, id) |
| + must(t, err) |
| + calls := e.impl.Calls() |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + raw, err := os.ReadFile(backup) |
| + must(t, err) |
| + must(t, os.WriteFile(e.path, raw, 0o600)) // preserve the newer external marker |
| + e.openNoResume() |
| + st, err := e.store.Status(e.ctx) |
| + must(t, err) |
| + if !st.Quarantine { |
| + t.Fatal("older snapshot from same incarnation was accepted") |
| + } |
| + a, err := e.store.GetAction(e.ctx, scope, id) |
| + must(t, err) |
| + if a.State != ActionUncertain { |
| + t.Fatalf("restored intent was trusted as %s", a.State) |
| + } |
| + rr, err := e.store.Resume(e.ctx) |
| + must(t, err) |
| + if rr.Resumed || !rr.Quarantine { |
| + t.Fatalf("restored history resumed: %+v", rr) |
| + } |
| + _, err = e.store.Dispatch(e.ctx, scope, id) |
| + if err == nil || e.impl.Calls() != calls { |
| + t.Fatal("restored intent executed again") |
| + } |
| +} |
| + |
| +func TestRestoreWithoutRecordedActionsStillNeedsOperator(t *testing.T) { |
| + e := newEnv(t) |
| + backup := e.snapshot() |
| + e.createJob(softwareSpec(SoftwareSteps(false))) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + raw, err := os.ReadFile(backup) |
| + must(t, err) |
| + must(t, os.WriteFile(e.path, raw, 0o600)) |
| + e.openNoResume() |
| + rr, err := e.store.Resume(e.ctx) |
| + must(t, err) |
| + if rr.Resumed || !rr.Quarantine { |
| + t.Fatal("missing post-snapshot work was assumed absent") |
| + } |
| + _, err = e.store.CreateJob(e.ctx, softwareSpec(SoftwareSteps(false))) |
| + wantCode(t, err, CodeAdmissionPaused) |
| +} |
| + |
| +func TestVersionOneMigrationPreservesJobsAndQuarantinesHistory(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + db, err := sql.Open("sqlite", e.path) |
| + must(t, err) |
| + for _, q := range []string{ |
| + `ALTER TABLE service DROP COLUMN revision`, |
| + `ALTER TABLE service DROP COLUMN restore_uncertain`, |
| + `ALTER TABLE actions DROP COLUMN admitted_incarnation`, |
| + `UPDATE service SET schema_version=1 WHERE id=1`, |
| + } { |
| + _, err := db.Exec(q) |
| + must(t, err) |
| + } |
| + must(t, db.Close()) |
| + must(t, os.WriteFile(e.path+".incarnation", []byte("incarnation=1\nclean=true\n"), 0o600)) |
| + e.openNoResume() |
| + _, err = e.store.GetJob(e.ctx, scope) |
| + must(t, err) |
| + st, err := e.store.Status(e.ctx) |
| + must(t, err) |
| + if st.SchemaVersion != SchemaVersion || !st.Quarantine { |
| + t.Fatalf("migration status: %+v", st) |
| + } |
| +} |
diff --git a/internal/team/scheduler.go b/internal/team/scheduler.go| index 647edfe9c..a40a55c07 100644 |
| --- a/internal/team/scheduler.go |
| +++ b/internal/team/scheduler.go |
| @@ -151,10 +151,10 @@ func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspa |
| return fail(CodeQuota, "step %q used its %d attempts", st.Key, j.Policy.MaxAttemptsPerStep) |
| } |
| var jobLive, accountLive int |
| - if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts WHERE job_id=? AND state IN ('active','stopping') AND containment='pending'`, int64(j.ID)).Scan(&jobLive); err != nil { |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts WHERE job_id=? AND containment='pending'`, int64(j.ID)).Scan(&jobLive); err != nil { |
| return fail(CodeInvalid, "concurrency: %v", err) |
| } |
| - if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts a JOIN jobs j ON j.id=a.job_id WHERE j.account=? AND a.state IN ('active','stopping') AND a.containment='pending'`, string(j.Account)).Scan(&accountLive); err != nil { |
| + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM attempts a JOIN jobs j ON j.id=a.job_id WHERE j.account=? AND a.containment='pending'`, string(j.Account)).Scan(&accountLive); err != nil { |
| return fail(CodeInvalid, "concurrency: %v", err) |
| } |
| account, err := accountPolicy(ctx, tx, j.Account) |
diff --git a/internal/team/store.go b/internal/team/store.go| index f8d8a7391..11b09a8ed 100644 |
| --- a/internal/team/store.go |
| +++ b/internal/team/store.go |
| @@ -9,6 +9,7 @@ import ( |
| "path/filepath" |
| "strconv" |
| "strings" |
| + "sync" |
| "time" |
| _ "modernc.org/sqlite" |
| @@ -17,7 +18,7 @@ import ( |
| // SchemaVersion is the one schema this binary writes. A database with a |
| // newer version is refused (ErrStaleStore): the binary would not know the |
| // rows it was reading. |
| -const SchemaVersion = 1 |
| +const SchemaVersion = 2 |
| // Adapter executes one operation class against an external system. Execute |
| // runs an admitted dispatch and returns its receipt; an error from Execute |
| @@ -55,6 +56,7 @@ type Store struct { |
| auth Authority |
| adapters map[Operation]Adapter |
| incarnation int64 |
| + recoveryMu sync.Mutex |
| } |
| // Open opens or creates the database at path. Admission is paused on every |
| @@ -93,11 +95,9 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) { |
| // closes the database. |
| func (s *Store) Close() error { |
| ctx := context.Background() |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| - if _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=1 WHERE id=1`); err != nil { |
| - return err |
| - } |
| - return writeMarker(s.marker, s.incarnation, true) |
| + err := s.transact(ctx, true, func(tx *sql.Tx) error { |
| + _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=1 WHERE id=1`) |
| + return err |
| }) |
| if cerr := s.db.Close(); err == nil { |
| err = cerr |
| @@ -124,6 +124,8 @@ CREATE TABLE IF NOT EXISTS service ( |
| id INTEGER PRIMARY KEY CHECK (id = 1), |
| schema_version INTEGER NOT NULL, |
| incarnation INTEGER NOT NULL, |
| + revision INTEGER NOT NULL DEFAULT 0, |
| + restore_uncertain INTEGER NOT NULL DEFAULT 0, |
| admission_paused INTEGER NOT NULL, |
| quarantine INTEGER NOT NULL, |
| quarantine_why TEXT NOT NULL |
| @@ -225,6 +227,7 @@ CREATE TABLE IF NOT EXISTS actions ( |
| last_error TEXT NOT NULL, |
| created_at TEXT NOT NULL, |
| updated_at TEXT NOT NULL, |
| + admitted_incarnation INTEGER NOT NULL DEFAULT 0, |
| UNIQUE(job_id, key) |
| ); |
| CREATE INDEX IF NOT EXISTS actions_state ON actions(state); |
| @@ -271,6 +274,21 @@ func (s *Store) migrate(ctx context.Context) error { |
| return fail(CodeInvalid, "service row: %v", err) |
| case v > SchemaVersion: |
| return fail(CodeStaleStore, "schema %d newer than %d", v, SchemaVersion) |
| + case v == 1: |
| + for _, statement := range []string{ |
| + `ALTER TABLE service ADD COLUMN revision INTEGER NOT NULL DEFAULT 0`, |
| + `ALTER TABLE service ADD COLUMN restore_uncertain INTEGER NOT NULL DEFAULT 0`, |
| + `ALTER TABLE actions ADD COLUMN admitted_incarnation INTEGER NOT NULL DEFAULT 0`, |
| + } { |
| + if _, err := tx.ExecContext(ctx, statement); err != nil { |
| + return fail(CodeInvalid, "migration: %v", err) |
| + } |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE service SET schema_version=? WHERE id=1`, SchemaVersion); err != nil { |
| + return err |
| + } |
| + case v != SchemaVersion: |
| + return fail(CodeStaleStore, "unsupported schema %d", v) |
| } |
| return nil |
| }) |
| @@ -281,35 +299,55 @@ func (s *Store) migrate(ctx context.Context) error { |
| func (s *Store) start(ctx context.Context) error { |
| var next int64 |
| err := s.tx(ctx, func(tx *sql.Tx) error { |
| - var inc int64 |
| - if err := tx.QueryRowContext(ctx, `SELECT incarnation FROM service WHERE id=1`).Scan(&inc); err != nil { |
| - return fail(CodeInvalid, "incarnation: %v", err) |
| + var inc, revision int64 |
| + var previousRestore int |
| + if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision, restore_uncertain FROM service WHERE id=1`).Scan(&inc, &revision, &previousRestore); err != nil { |
| + return err |
| } |
| - why := "" |
| - if inc > 0 { |
| - mInc, clean, err := readMarker(s.marker) |
| + why, restore := "", previousRestore |
| + if inc == 0 { |
| + if _, err := os.Stat(s.marker); err == nil { |
| + return fail(CodeStaleStore, "database is empty but its external witness exists") |
| + } else if !errors.Is(err, os.ErrNotExist) { |
| + return err |
| + } |
| + } else { |
| + mInc, mRevision, clean, err := readMarker(s.marker) |
| switch { |
| case err != nil: |
| - why = "marker missing or unreadable: " + err.Error() |
| - case mInc != inc: |
| - why = fmt.Sprintf("marker incarnation %d, database %d: restored snapshot", mInc, inc) |
| + why, restore = "marker missing or unreadable: "+err.Error(), 1 |
| + case mInc != inc || mRevision != revision: |
| + why, restore = fmt.Sprintf("marker position %d/%d, database %d/%d: restored snapshot", mInc, mRevision, inc, revision), 1 |
| case !clean: |
| why = "unclean shutdown" |
| } |
| } |
| - next = inc + 1 |
| - if err := writeMarker(s.marker, next, false); err != nil { |
| + if restore != 0 && why == "" { |
| + why = "restored history requires operator recovery" |
| + } |
| + var err error |
| + next, err = addChecked(inc, 1) |
| + if err != nil { |
| + return err |
| + } |
| + nextRevision, err := addChecked(revision, 1) |
| + if err != nil { |
| + return err |
| + } |
| + if err := writeMarker(s.marker, next, nextRevision, false); err != nil { |
| return err |
| } |
| q := 0 |
| if why != "" { |
| q = 1 |
| } |
| - _, err := tx.ExecContext(ctx, `UPDATE service SET incarnation=?, admission_paused=1, quarantine=?, quarantine_why=? WHERE id=1`, next, q, why) |
| - if err != nil { |
| - return fail(CodeInvalid, "start: %v", err) |
| + if restore != 0 { |
| + if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='restored intent may have executed after snapshot' WHERE state='intent'`); err != nil { |
| + return err |
| + } |
| } |
| - return nil |
| + _, err = tx.ExecContext(ctx, `UPDATE service SET incarnation=?, revision=?, admission_paused=1, quarantine=?, quarantine_why=?, restore_uncertain=? WHERE id=1`, next, nextRevision, q, why, restore) |
| + return err |
| }) |
| if err == nil { |
| s.incarnation = next |
| @@ -317,38 +355,43 @@ func (s *Store) start(ctx context.Context) error { |
| return err |
| } |
| -func readMarker(path string) (int64, bool, error) { |
| +func readMarker(path string) (int64, int64, bool, error) { |
| raw, err := os.ReadFile(path) |
| if err != nil { |
| - return 0, false, err |
| + return 0, 0, false, err |
| } |
| - var inc int64 |
| + inc, revision := int64(-1), int64(-1) |
| clean := false |
| for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") { |
| - k, v, ok := strings.Cut(line, "=") |
| + key, value, ok := strings.Cut(line, "=") |
| if !ok { |
| - continue |
| + return 0, 0, false, fmt.Errorf("invalid marker line") |
| } |
| - switch k { |
| + switch key { |
| case "incarnation": |
| - inc, err = strconv.ParseInt(v, 10, 64) |
| - if err != nil { |
| - return 0, false, err |
| - } |
| + inc, err = strconv.ParseInt(value, 10, 64) |
| + case "revision": |
| + revision, err = strconv.ParseInt(value, 10, 64) |
| case "clean": |
| - clean = v == "true" |
| + clean, err = strconv.ParseBool(value) |
| } |
| + if err != nil { |
| + return 0, 0, false, err |
| + } |
| + } |
| + if inc < 0 || revision < 0 { |
| + return 0, 0, false, fmt.Errorf("marker has no valid position") |
| } |
| - return inc, clean, nil |
| + return inc, revision, clean, nil |
| } |
| -func writeMarker(path string, inc int64, clean bool) error { |
| +func writeMarker(path string, inc, revision int64, clean bool) error { |
| tmp := path + ".tmp" |
| - body := fmt.Sprintf("incarnation=%d\nclean=%t\n", inc, clean) |
| + body := fmt.Sprintf("incarnation=%d\nclean=%t\nrevision=%d\n", inc, clean, revision) |
| if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| return fail(CodeInvalid, "marker: %v", err) |
| } |
| - if err := os.WriteFile(tmp, []byte(body), 0o644); err != nil { |
| + if err := os.WriteFile(tmp, []byte(body), 0o600); err != nil { |
| return fail(CodeInvalid, "marker: %v", err) |
| } |
| if err := os.Rename(tmp, path); err != nil { |
| @@ -357,29 +400,49 @@ func writeMarker(path string, inc int64, clean bool) error { |
| return nil |
| } |
| -// tx runs fn in one immediate write transaction. Any error rolls back. |
| +// Every transaction advances an external position before committing. A |
| +// rollback or an older database snapshot therefore leaves a detectable |
| +// mismatch, including snapshots taken within the same writer incarnation. |
| +// Reads also advance the position in this bounded prototype; optimizing |
| +// that requires retaining the same witness for every mutation path. |
| func (s *Store) tx(ctx context.Context, fn func(*sql.Tx) error) error { |
| + return s.transact(ctx, false, fn) |
| +} |
| + |
| +func (s *Store) transact(ctx context.Context, clean bool, fn func(*sql.Tx) error) error { |
| tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return fail(CodeInvalid, "begin: %v", err) |
| } |
| - // A replacement Open takes ownership. An older handle must not resume |
| - // admission, record effects or mark that replacement's shutdown clean. |
| + defer tx.Rollback() |
| if s.incarnation != 0 { |
| var current int64 |
| if err := tx.QueryRowContext(ctx, `SELECT incarnation FROM service WHERE id=1`).Scan(¤t); err != nil { |
| - tx.Rollback() |
| - return fail(CodeInvalid, "owner: %v", err) |
| + return err |
| } |
| if current != s.incarnation { |
| - tx.Rollback() |
| return fail(CodeStaleStore, "incarnation %d replaced by %d", s.incarnation, current) |
| } |
| } |
| if err := fn(tx); err != nil { |
| - tx.Rollback() |
| return err |
| } |
| + if s.incarnation != 0 { |
| + var revision int64 |
| + if err := tx.QueryRowContext(ctx, `SELECT revision FROM service WHERE id=1`).Scan(&revision); err != nil { |
| + return err |
| + } |
| + next, err := addChecked(revision, 1) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE service SET revision=? WHERE id=1`, next); err != nil { |
| + return err |
| + } |
| + if err := writeMarker(s.marker, s.incarnation, next, clean); err != nil { |
| + return err |
| + } |
| + } |
| if err := tx.Commit(); err != nil { |
| return fail(CodeInvalid, "commit: %v", err) |
| } |
diff --git a/internal/team/store_test.go b/internal/team/store_test.go| index 20e742c95..c8024c198 100644 |
| --- a/internal/team/store_test.go |
| +++ b/internal/team/store_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "os" |
| "path/filepath" |
| + "strings" |
| "testing" |
| "time" |
| ) |
| @@ -120,13 +121,13 @@ func TestStartupPausedUntilResume(t *testing.T) { |
| } |
| raw, err := os.ReadFile(e.path + ".incarnation") |
| must(t, err) |
| - if string(raw) != "incarnation=2\nclean=false\n" { |
| + if !strings.HasPrefix(string(raw), "incarnation=2\nclean=false\nrevision=") { |
| t.Fatalf("marker %q", raw) |
| } |
| must(t, s.Close()) |
| e.store = nil |
| raw, _ = os.ReadFile(e.path + ".incarnation") |
| - if string(raw) != "incarnation=2\nclean=true\n" { |
| + if !strings.HasPrefix(string(raw), "incarnation=2\nclean=true\nrevision=") { |
| t.Fatalf("marker after close %q", raw) |
| } |
| // A missing marker on a used database is quarantine. |
diff --git a/internal/teamcontract/authority_test.go b/internal/teamcontract/authority_test.go| index a2986a67d..d307f4f02 100644 |
| --- a/internal/teamcontract/authority_test.go |
| +++ b/internal/teamcontract/authority_test.go |
| @@ -68,6 +68,28 @@ func TestChildCannotRaiseParentsDepthLimit(t *testing.T) { |
| } |
| } |
| +func TestNewJobsCannotUnderpriceAccountReservations(t *testing.T) { |
| + s, ctx := contractStore(t) |
| + p := finitePolicy() |
| + parent, err := s.CreateJob(ctx, businessJob(p)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, parentID := range []team.JobID{0, parent.ID} { |
| + proposal := businessJob(p) |
| + proposal.Parent = parentID |
| + proposal.Policy.Rates = team.Rates{Version: 1} |
| + if _, err := s.CreateJob(ctx, proposal); err == nil { |
| + t.Fatalf("job with parent %d replaced the account price table", parentID) |
| + } |
| + proposal.Policy = p |
| + proposal.Policy.PerCall.OutputTokens-- |
| + if _, err := s.CreateJob(ctx, proposal); err == nil { |
| + t.Fatalf("job with parent %d replaced the account call ceiling", parentID) |
| + } |
| + } |
| +} |
| + |
| func TestNewJobCannotRaiseAccountCallLimit(t *testing.T) { |
| s, ctx := contractStore(t) |
| p := finitePolicy() |