oficina / equipo Public

fix: unblock coordinator after reset and settle delivery once

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev f5c5c16f5f3bd829f61050cf121040bc7ecf3228 parent c0fa3d4
11 files changed, +700 −17
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +331 −0
  • internal/equipo/conversation/coordinator.go +8 −1
  • internal/equipo/conversation/coordinator_engine.go +5 −4
  • internal/equipo/conversation/coordinator_events.go +13 −2
  • internal/equipo/conversation/coordinator_execution.go +4 −3
  • internal/equipo/conversation/coordinator_poll.go +27 −4
  • internal/equipo/conversation/store.go +1 −0
  • internal/equipo/conversations.go +1 −1
  • internal/equipo/coordinator.go +7 −1
  • internal/equipo/coordinator_execution.go +1 −1
  • internal/plan3test/coordinator_fixes_test.go +302 −0

CI failed — run details

diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 0fa35cac..469dc71d 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -390,3 +390,334 @@ The first role-revision mutation only caused a compile error and is not behavior
Tasks 6/7 must supply the durable tool-effect delivery validator, richer policy-filtered context, provider journal/runtime wiring and task-wait behavior without holding a lease. The default delivery validator is absent and refuses completion. The initial subscription lane and read-only action inventories do not enable live work. Paul's new live certification is still required, and Task 6's expanded tool inventory will require new hashes again. Historical version-1 standalone account-policy fixtures remain compatible; current runner version-2 jobs require positive configured projects unless their target is conversation.
New copy is individually pending in copy.go and listed with draft text in the full report. README prose was unchanged. No subagents, copy-review server, live sign-in, enrolment, push, merge, deployment or handoff file. Go caches stayed at defaults. No server was started. Task-owned scratch was removed.
+
+
+## Fix round 1
+
+Status: DONE for the six dispatched findings (Important 1/2 and Minor 1/3/5/9). The original live-certification and Task 6/7 integration concerns remain outside this fix. No coordinator tool inventory changed.
+
+### Changes and covering tests
+
+- Important 1: claim and poll now share the turn-blocking query. Uncertainty and message ordering apply within the current generation. Running work and pending containment still block across generations. `TestCoordinatorFixResetNewMessage` resets an in-flight turn, contains it, polls and claims a new message, and checks that the old turn remains uncertain with its full call/token reservation charged. `TestCoordinatorFixUncertainWaitsForRetry` checks that same-generation uncertainty blocks both poll and claim until explicit retry, then verifies a new job and fresh context. `TestCoordinatorFixPollWaitsForContainment` checks that poll cannot offer a turn whose claim is blocked by outstanding containment after delivery.
+- Important 2: delivery reads the existing action receipt. If completion already settled it, delivery requires a successful action, matching outcome and exactly matching usage, including whether usage is unknown. It keeps the first receipt and does not call Record again. Delivery without prior completion still records its receipt. `TestCoordinatorFixCompletedThenDelivery` uses distinct process/delivery receipt IDs, checks duplicate delivery, and rejects mismatched usage, unknown usage and outcome. The existing delivery-atomicity test remains green.
+- Minor 1: delivery compares its session ID with the bound provider session before invoking the validator or writing. `TestCoordinatorFixDeliverySession` checks rejection without effects, preservation of the original session, and successful delivery with the matching session.
+- Minor 3: selection distinguishes observed missing/ineligible connections from query failures through a specific waiting-connection error. Poll persists waiting only for that observation. Other failures return an error and roll back the transaction, including any turns queued earlier in that poll. `TestCoordinatorFixPollUnknownConnection` injects a missing-table failure. `TestCoordinatorFixPollMissingConnection` covers missing and stale connections, authority revision mismatch, and atomic/idempotent waiting-state audits.
+- Minor 5: newly queued turns and poll requeues append `coordinator.queue` in the same transaction, with actor `coordinator:<binding ID>` and the delegating person recorded separately. Poll waiting-state changes also append an audit. `TestCoordinatorFixQueueAudit` injects audit failures for explicit queue, first poll and reset requeue; it checks rollback and one correctly attributed audit per new turn, including replay.
+- Minor 9: retry turns save the canonical hash of the same input used for retry replay. `TestCoordinatorFixRetryInputHash` checks the exact hash and replay identity.
+
+### Red evidence
+
+Tests were written before the implementation changes. Command:
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFix' -count=1
+```
+
+Exit 1. Failure output (opaque generated IDs omitted):
+
+```text
+TestCoordinatorFixResetNewMessage: new generation claim blocked by old uncertainty: This record changed. Reload the page and try again.
+TestCoordinatorFixPollWaitsForContainment: poll offered a turn claim refuses while containment is pending
+TestCoordinatorFixCompletedThenDelivery/none: completed then delivery with distinct receipts failed: team: receipt_conflict: action 1 already holds receipt "process-receipt"
+TestCoordinatorFixDeliverySession: delivery overwrote the bound provider session
+TestCoordinatorFixPollUnknownConnection: unknown connection lookup became a definite waiting state [] <nil>
+TestCoordinatorFixPollMissingConnection/revision: authority mismatch became connection absence
+TestCoordinatorFixQueueAudit/queue: queue succeeded without its audit
+TestCoordinatorFixQueueAudit/poll: queue succeeded without its audit
+TestCoordinatorFixQueueAudit/requeue: queue succeeded without its audit
+TestCoordinatorFixRetryInputHash: retry input hash = "", want "126c55b9a785ac6bd5e816cf5fc281b57c99517e2eb9746db38f2669cf63f8f3"
+FAIL
+rastrillo-budget/v1 ran 5.033s
+FAIL amadan.net/oficina/equipo/internal/plan3test 5.276s
+FAIL
+```
+
+The first implementation rerun exited 1 (4.515s) on the test's charge assertion. The fixture assertion incorrectly expected a reservation state named `unknown`. Existing core accounting uses `state='settled', settled_by='unknown'`. The test was corrected to check that representation for the old job, with settled calls/input/output equal to the full reservation. No accounting implementation changed. The next combined coordinator run passed. Additional waiting-audit rollback assertions were then added and passed; their mutation below independently proves they detect a missing audit.
+
+### Green commands and output
+
+After all ten mutations were restored:
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFix' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/plan3test 4.959s
+```
+
+The same covering command also passed before mutation testing (5.219s). The broader targeted coordinator checks passed after the behavioral fixes:
+
+```sh
+CGO_ENABLED=0 go test ./internal/equipo/team ./internal/plan3test -run '^TestCoordinator' -count=1
+```
+
+Exit 0:
+
+```text
+ok amadan.net/oficina/equipo/internal/equipo/team 0.708s
+ok amadan.net/oficina/equipo/internal/plan3test 6.875s
+```
+
+```sh
+CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/conversation ./internal/plan3test
+gofmt -l internal/equipo internal/plan3test
+git diff --check
+```
+
+Each exited 0 with no output, including the final checks after restoration.
+
+```sh
+CGO_ENABLED=0 make budget
+```
+
+Exit 0:
+
+```text
+go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
+budget size: 29 directories within budget
+```
+
+```sh
+CGO_ENABLED=0 make migration-check
+```
+
+Exit 0:
+
+```text
+CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1
+ok amadan.net/oficina/equipo/internal/equipo 0.123s
+```
+
+### Guard mutations
+
+Each guard was broken separately and restored in a `finally` block before the next mutation. Every run compiled and failed the intended assertion. The final covering command above passed after restoration.
+
+#### generation
+
+Made the generation condition always true, so older uncertainty blocks new work.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixResetNewMessage$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixResetNewMessage (0.69s)
+ coordinator_fixes_test.go:36: poll must offer only the new prompt: []
+FAIL
+rastrillo-budget/v1 ran 686ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.741s
+FAIL
+```
+
+#### current-uncertainty
+
+Removed current uncertainty from the uncertainty and earlier-message checks.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixUncertainWaitsForRetry$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixUncertainWaitsForRetry (0.84s)
+ coordinator_fixes_test.go:69: claim ignored current uncertainty
+FAIL
+rastrillo-budget/v1 ran 844ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.898s
+FAIL
+```
+
+#### containment
+
+Removed pending containment from the shared blocking query.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixPollWaitsForContainment$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixPollWaitsForContainment (0.64s)
+ coordinator_fixes_test.go:95: poll offered a turn claim refuses while containment is pending [{7VRIZHP5WZVLZPZURGWMEIVKL2 TYB4MI3FOFDTSX6FRY2ZJIZ2AF next 1 1 queued}]
+FAIL
+rastrillo-budget/v1 ran 635ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.691s
+FAIL
+```
+
+#### second-receipt
+
+Recorded the delivery receipt even when completion already settled the action.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixCompletedThenDelivery/none$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixCompletedThenDelivery (0.65s)
+ --- FAIL: TestCoordinatorFixCompletedThenDelivery/none (0.65s)
+ coordinator_fixes_test.go:142: completed then delivery with distinct receipts failed: team: receipt_conflict: action 1 already holds receipt "process-receipt"
+FAIL
+rastrillo-budget/v1 ran 650ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.703s
+FAIL
+```
+
+#### receipt-consistency
+
+Disabled the comparison with the settled receipt.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixCompletedThenDelivery$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixCompletedThenDelivery (1.53s)
+ --- FAIL: TestCoordinatorFixCompletedThenDelivery/usage (0.30s)
+ coordinator_fixes_test.go:134: delivery accepted inconsistent receipt
+ --- FAIL: TestCoordinatorFixCompletedThenDelivery/unknown (0.29s)
+ coordinator_fixes_test.go:134: delivery accepted inconsistent receipt
+ --- FAIL: TestCoordinatorFixCompletedThenDelivery/outcome (0.30s)
+ coordinator_fixes_test.go:134: delivery accepted inconsistent receipt
+FAIL
+rastrillo-budget/v1 ran 1.53s
+FAIL amadan.net/oficina/equipo/internal/plan3test 1.584s
+FAIL
+```
+
+#### session-binding
+
+Removed delivery session comparison.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixDeliverySession$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixDeliverySession (0.60s)
+ coordinator_fixes_test.go:171: delivery overwrote the bound provider session
+FAIL
+rastrillo-budget/v1 ran 603ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.657s
+FAIL
+```
+
+#### unknown-connection
+
+Mapped generic unavailable errors to persisted waiting.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixPollUnknownConnection$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixPollUnknownConnection (0.59s)
+ coordinator_fixes_test.go:189: unknown connection lookup became a definite waiting state [] <nil>
+FAIL
+rastrillo-budget/v1 ran 592ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.645s
+FAIL
+```
+
+#### queue-audit
+
+Removed the audit from new queued-turn insertion.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixQueueAudit$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixQueueAudit (1.10s)
+ --- FAIL: TestCoordinatorFixQueueAudit/queue (0.57s)
+ coordinator_fixes_test.go:262: queue succeeded without its audit
+ --- FAIL: TestCoordinatorFixQueueAudit/poll (0.26s)
+ coordinator_fixes_test.go:262: queue succeeded without its audit
+ --- FAIL: TestCoordinatorFixQueueAudit/requeue (0.27s)
+ coordinator_fixes_test.go:262: queue succeeded without its audit
+FAIL
+rastrillo-budget/v1 ran 1.103s
+FAIL amadan.net/oficina/equipo/internal/plan3test 1.156s
+FAIL
+```
+
+#### retry-hash
+
+Blanked the new retry row input hash before insertion.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixRetryInputHash$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixRetryInputHash (0.61s)
+ coordinator_fixes_test.go:295: retry input hash = "", want "2de7ffb67f2ed5bc5ed6545a7ce8762eb5ca3f90fffa165491661a18feb69cf8"
+FAIL
+rastrillo-budget/v1 ran 606ms
+FAIL amadan.net/oficina/equipo/internal/plan3test 0.659s
+FAIL
+```
+
+#### waiting-audit
+
+Removed the audit from waiting-state transitions.
+
+```sh
+CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFixPollMissingConnection$' -count=1
+```
+
+Exit 1. Restored.
+
+```text
+--- FAIL: TestCoordinatorFixPollMissingConnection (1.13s)
+ --- FAIL: TestCoordinatorFixPollMissingConnection/missing (0.60s)
+ coordinator_fixes_test.go:212: waiting state succeeded without its audit
+ --- FAIL: TestCoordinatorFixPollMissingConnection/stale (0.27s)
+ coordinator_fixes_test.go:212: waiting state succeeded without its audit
+FAIL
+rastrillo-budget/v1 ran 1.127s
+FAIL amadan.net/oficina/equipo/internal/plan3test 1.185s
+FAIL
+```
+
+### Files, copy and self-review
+
+Implementation files changed:
+
+- `internal/equipo/conversation/coordinator.go`
+- `internal/equipo/conversation/coordinator_engine.go`
+- `internal/equipo/conversation/coordinator_events.go`
+- `internal/equipo/conversation/coordinator_execution.go`
+- `internal/equipo/conversation/coordinator_poll.go`
+- `internal/equipo/conversation/store.go`
+- `internal/equipo/conversations.go`
+- `internal/equipo/coordinator.go`
+- `internal/equipo/coordinator_execution.go`
+- `internal/plan3test/coordinator_fixes_test.go`
+
+Both this controller report and `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-5-report.md` received this fix-round section. The task report stays in the existing ignored controller directory; the repository controller report is committed with the code.
+
+New user-facing string keys/text: none. The specific connection error reuses the existing pending entry `coordinator.waiting_connection`: `Waiting for your connection`. No copy or README text changed.
+
+Self-review checked that old uncertainty is neither requeued nor refunded, containment remains required across generations, receipt settlement occurs once, query failures roll back all poll writes, and audit failures roll back their turn changes. Delivery validators must still be local and bounded. A disagreement about known versus unknown usage is rejected without changing the settled receipt. Other review findings not dispatched for this round remain outside scope; Task 6 owns the Claude tool inventory.
+
+No full suite, make ci, provider calls, sign-ins, enrolment, agents, servers, handoff file, push, merge or deployment. Go caches stayed at their defaults. Mutation scratch was created under `$TMPDIR` and removed after its output was copied into these reports. Commit subject: `fix: unblock coordinator after reset and settle delivery once`; author: `codex <codex~paul@keymail.dev>`.
diff --git a/internal/equipo/conversation/coordinator.go b/internal/equipo/conversation/coordinator.go
index d637fe7f..9c9187cd 100644
--- a/internal/equipo/conversation/coordinator.go
+++ b/internal/equipo/conversation/coordinator.go
@@ -126,6 +126,9 @@ func (s *Store) QueueCoordinator(actor kernel.Actor, messageID string, project i
if err = s.tx.Create(&row).Error; err != nil {
return out, err
}
+ if err = s.deps.CoordinatorAudit(s.tx, b, "coordinator.queue", row.ID); err != nil {
+ return out, err
+ }
return row.CoordinatorTurn, s.SaveCoordinatorResult(actor, "coordinator.queue", actor.Address, m, input, row.CoordinatorTurn)
}
func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutation) (CoordinatorTurn, error) {
@@ -161,7 +164,11 @@ func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutatio
if err = s.tx.Model(&TurnRecord{}).Where("id=?", id).Select("state", "revision").Updates(map[string]any{"state": "superseded", "revision": old.Revision + 1}).Error; err != nil {
return out, err
}
- row := TurnRecord{CoordinatorTurn: CoordinatorTurn{ID: rand.Text(), MessageID: old.MessageID, RequestID: m.RequestID, Generation: b.Generation, Revision: 1, State: "queued"}, TeamID: b.TeamID, Person: actor.Address, BindingID: b.ID, ConversationID: old.ConversationID, Sequence: old.Sequence, ProjectID: old.ProjectID, MemberRevision: b.MemberRevision, ConnectionRevision: b.ConnectionRevision}
+ hash, err := kernel.InputHash(input)
+ if err != nil {
+ return out, err
+ }
+ row := TurnRecord{CoordinatorTurn: CoordinatorTurn{ID: rand.Text(), MessageID: old.MessageID, RequestID: m.RequestID, Generation: b.Generation, Revision: 1, State: "queued"}, TeamID: b.TeamID, Person: actor.Address, BindingID: b.ID, ConversationID: old.ConversationID, Sequence: old.Sequence, ProjectID: old.ProjectID, MemberRevision: b.MemberRevision, ConnectionRevision: b.ConnectionRevision, InputHash: hash}
if err = s.tx.Create(&row).Error; err != nil {
return out, err
}
diff --git a/internal/equipo/conversation/coordinator_engine.go b/internal/equipo/conversation/coordinator_engine.go
index c54a8c31..5c3ffa1e 100644
--- a/internal/equipo/conversation/coordinator_engine.go
+++ b/internal/equipo/conversation/coordinator_engine.go
@@ -13,10 +13,11 @@ type RunnerPrincipal = runnerproto.RunnerPrincipal
type Assignment = runnerproto.Assignment
type RunnerRequest = runnerproto.RunnerRequest
type Engine struct {
- Selection func(*gorm.DB, BindingRecord) (runnerproto.Selection, error)
- CheckProject func(*gorm.DB, string, int64, runnerproto.Selection) (int64, error)
- StoreError func(error) error
- NotFound error
+ Selection func(*gorm.DB, BindingRecord) (runnerproto.Selection, error)
+ CheckProject func(*gorm.DB, string, int64, runnerproto.Selection) (int64, error)
+ StoreError func(error) error
+ WaitingConnection error
+ NotFound error
Core *team.Store
Atomic func(context.Context, func(context.Context, *gorm.DB) error) error
diff --git a/internal/equipo/conversation/coordinator_events.go b/internal/equipo/conversation/coordinator_events.go
index 86667f80..1d35aa4a 100644
--- a/internal/equipo/conversation/coordinator_events.go
+++ b/internal/equipo/conversation/coordinator_events.go
@@ -27,6 +27,9 @@ func (e *Engine) CompleteCoordinator(ctx context.Context, p RunnerPrincipal, c C
if event.Scope != c.Scope || event.Handle != c.Handle || event.AssignmentID != row.ID || event.TaskID != row.ID || event.TurnID != row.ID || event.ActionID != c.Admission.Dispatch.Action {
return e.Forbidden
}
+ if row.ProviderSessionID != "" && row.ProviderSessionID != event.SessionID {
+ return e.Conflict
+ }
hash := event.ContentHash()
if row.State == "delivered" {
if row.DeliveryHash != hash {
@@ -47,10 +50,18 @@ func (e *Engine) CompleteCoordinator(ctx context.Context, p RunnerPrincipal, c C
if receipt.Outcome != team.OutcomeSuccess {
return team.ErrEvidence
}
- if err = e.Conversation(tx).DeliverCoordinator(row, body); err != nil {
+ action, err := e.Core.GetAction(ctx, c.Scope, event.ActionID)
+ if err != nil {
return err
}
- if err = e.Core.Record(ctx, c.Scope, event.ActionID, receipt); err != nil {
+ if saved := action.Receipt; saved != nil {
+ if action.State != team.ActionSucceeded || saved.Outcome != receipt.Outcome || (saved.Usage == nil) != (receipt.Usage == nil) || (saved.Usage != nil && *saved.Usage != *receipt.Usage) {
+ return team.ErrReceiptConflict
+ }
+ } else if err = e.Core.Record(ctx, c.Scope, event.ActionID, receipt); err != nil {
+ return err
+ }
+ if err = e.Conversation(tx).DeliverCoordinator(row, body); err != nil {
return err
}
if err = e.Core.DeliverCoordinator(ctx, c.Scope, c.Handle, b.ID, hash); err != nil {
diff --git a/internal/equipo/conversation/coordinator_execution.go b/internal/equipo/conversation/coordinator_execution.go
index 0c615e7c..45d893c1 100644
--- a/internal/equipo/conversation/coordinator_execution.go
+++ b/internal/equipo/conversation/coordinator_execution.go
@@ -41,14 +41,15 @@ func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID
if row.State != "queued" && row.State != "waiting_connection" && row.State != "waiting_task" && row.State != "budget_needed" {
return e.Conflict
}
- var n int64
- if err = tx.Model(&TurnRecord{}).Where("team_id=? AND person=? AND id<>? AND (state IN ('running','uncertain') OR (sequence<? AND state NOT IN ('delivered','superseded')) OR attempt_id IN (SELECT id FROM attempts WHERE containment='pending'))", row.TeamID, row.Person, row.ID, row.Sequence).Count(&n).Error; err != nil {
+ blocked, err := coordinatorBlocked(tx, row)
+ if err != nil {
return err
}
- if n > 0 {
+ if blocked {
return e.Conflict
}
// A shared credential home remains unavailable while specialist work holds it.
+ var n int64
if err = tx.Table("runner_assignments").Where("person=? AND state IN ('claimed','reconcile','fenced') AND attempt_id IN (SELECT id FROM attempts WHERE containment='pending') AND json_extract(selection,'$.ConnectionID')=?", p.Person, b.ConnectionID).Count(&n).Error; err != nil {
return err
}
diff --git a/internal/equipo/conversation/coordinator_poll.go b/internal/equipo/conversation/coordinator_poll.go
index a8ea6adc..57f1aac2 100644
--- a/internal/equipo/conversation/coordinator_poll.go
+++ b/internal/equipo/conversation/coordinator_poll.go
@@ -42,10 +42,17 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor
if row.State == "running" || row.State == "uncertain" {
continue
}
+ blocked, err := coordinatorBlocked(tx, row)
+ if err != nil {
+ return err
+ }
+ if blocked {
+ continue
+ }
_, _, _, err = e.Current(ctx, tx, p, row.ID)
if err != nil {
- if errors.Is(err, e.Forbidden) || errors.Is(err, e.Unavailable) || errors.Is(err, e.NotFound) {
- return tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": "waiting_connection"}).Error
+ if errors.Is(err, e.WaitingConnection) {
+ return e.waitCoordinator(tx, b, row, "waiting_connection")
}
return err
}
@@ -54,11 +61,11 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor
return err
}
if busy > 0 {
- return tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": "waiting_task"}).Error
+ return e.waitCoordinator(tx, b, row, "waiting_task")
}
if err = e.Core.CoordinatorAvailable(ctx, team.AccountID(b.TeamID), p.Person); err != nil {
if errors.Is(err, team.ErrBudget) {
- return tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": "budget_needed"}).Error
+ return e.waitCoordinator(tx, b, row, "budget_needed")
}
return err
}
@@ -68,3 +75,19 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor
})
return out, err
}
+
+func coordinatorBlocked(tx *gorm.DB, row TurnRecord) (bool, error) {
+ var n int64
+ err := tx.Model(&TurnRecord{}).Where("team_id=? AND person=? AND id<>? AND (state='running' OR (generation=? AND (state='uncertain' OR (sequence<? AND state NOT IN ('delivered','superseded')))) OR attempt_id IN (SELECT id FROM attempts WHERE containment='pending'))", row.TeamID, row.Person, row.ID, row.Generation, row.Sequence).Count(&n).Error
+ return n > 0, err
+}
+
+func (e *Engine) waitCoordinator(tx *gorm.DB, b BindingRecord, row TurnRecord, state string) error {
+ if row.State == state {
+ return nil
+ }
+ if err := tx.Model(&TurnRecord{}).Where("id=?", row.ID).Select("state").Updates(map[string]any{"state": state}).Error; err != nil {
+ return err
+ }
+ return e.Audit(tx, b, "coordinator."+state, row.ID)
+}
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go
index fb01d7be..512e8512 100644
--- a/internal/equipo/conversation/store.go
+++ b/internal/equipo/conversation/store.go
@@ -17,6 +17,7 @@ type TaskAccess struct {
Revision int64
}
type Dependencies struct {
+ CoordinatorAudit func(*gorm.DB, BindingRecord, string, string) error
Authorize func(*gorm.DB, kernel.Actor) (string, error)
Task func(*gorm.DB, kernel.Actor, string) (TaskAccess, error)
Audit func(*gorm.DB, kernel.Actor, string, string) error
diff --git a/internal/equipo/conversations.go b/internal/equipo/conversations.go
index 48025706..1e1416db 100644
--- a/internal/equipo/conversations.go
+++ b/internal/equipo/conversations.go
@@ -29,7 +29,7 @@ func conversationAuthority(tx *gorm.DB, actor Actor) (string, error) {
}
func conversationAt(tx *gorm.DB) *conversation.Store {
return conversation.New(tx, conversation.Dependencies{
- Authorize: conversationAuthority,
+ Authorize: conversationAuthority, CoordinatorAudit: coordinatorAudit,
Task: func(tx *gorm.DB, actor Actor, id string) (conversation.TaskAccess, error) {
teamID, err := conversationAuthority(tx, actor)
if err != nil {
diff --git a/internal/equipo/coordinator.go b/internal/equipo/coordinator.go
index 3cdd8ee7..da91bc05 100644
--- a/internal/equipo/coordinator.go
+++ b/internal/equipo/coordinator.go
@@ -5,6 +5,7 @@ import (
"amadan.net/oficina/equipo/internal/equipo/team"
"amadan.net/oficina/equipo/internal/runnerproto"
"context"
+ "errors"
"gorm.io/gorm"
"time"
)
@@ -18,6 +19,8 @@ func CoordinatorGrantRef(person string) string {
return team.CoordinatorGrantRef(normalizeAddress(person))
}
+var errCoordinatorWaitingConnection = &refusal{copyText("coordinator.waiting_connection"), ErrUnavailable}
+
func (s *Store) coordinatorSelection(tx *gorm.DB, b conversation.BindingRecord) (Selection, error) {
m, err := currentRunnerMember(tx, b.Person)
if err != nil {
@@ -28,6 +31,9 @@ func (s *Store) coordinatorSelection(tx *gorm.DB, b conversation.BindingRecord)
}
var c connectionRecord
if err = tx.First(&c, "id=?", b.ConnectionID).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return Selection{}, errCoordinatorWaitingConnection
+ }
return Selection{}, storeError(err)
}
if c.Person != b.Person || c.RunnerID != b.RunnerID || c.Revision != b.ConnectionRevision {
@@ -54,7 +60,7 @@ func (s *Store) coordinatorSelection(tx *gorm.DB, b conversation.BindingRecord)
}
return Selection{ConnectionID: c.ID, RunnerID: c.RunnerID, Person: c.Person, Provider: r.Provider, Family: r.Family, Model: r.Model, AccountID: r.Routing.AccountID, AccountLabel: r.AccountLabel, Revision: c.Revision, Isolation: iso}, nil
}
- return Selection{}, ErrUnavailable
+ return Selection{}, errCoordinatorWaitingConnection
}
func (s *Store) coordinatorApplication() *conversation.Application {
var core *team.Store
diff --git a/internal/equipo/coordinator_execution.go b/internal/equipo/coordinator_execution.go
index 7b19cd11..02c51afe 100644
--- a/internal/equipo/coordinator_execution.go
+++ b/internal/equipo/coordinator_execution.go
@@ -16,7 +16,7 @@ func (e *Execution) coordinatorEngine() *conversation.Engine {
return &conversation.Engine{Core: e.Core, Atomic: e.atomic, Selection: e.store.coordinatorSelection, StoreError: storeError, NotFound: ErrNotFound, CheckProject: func(tx *gorm.DB, p string, id int64, sel Selection) (int64, error) {
project, err := e.store.coordinatorProject(tx, p, id, sel)
return project.Revision, err
- }, Conversation: conversationAt, Now: func() time.Time { return e.store.runnerClock.Now().UTC() }, Audit: coordinatorAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, Events: e.validators.Events, Receipt: e.validators.Receipt, Containment: e.validators.Containment, Delivery: e.validators.CoordinatorDelivery, Redact: func(raw []byte) []byte { return runner.RedactJSON(raw, nil) },
+ }, Conversation: conversationAt, Now: func() time.Time { return e.store.runnerClock.Now().UTC() }, Audit: coordinatorAudit, Invalid: ErrInvalid, Conflict: ErrConflict, Forbidden: ErrForbidden, Unavailable: ErrUnavailable, WaitingConnection: errCoordinatorWaitingConnection, Events: e.validators.Events, Receipt: e.validators.Receipt, Containment: e.validators.Containment, Delivery: e.validators.CoordinatorDelivery, Redact: func(raw []byte) []byte { return runner.RedactJSON(raw, nil) },
RunnerCurrent: func(tx *gorm.DB, p RunnerPrincipal) error {
_, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC())
return err
diff --git a/internal/plan3test/coordinator_fixes_test.go b/internal/plan3test/coordinator_fixes_test.go
new file mode 100644
index 00000000..7846f56d
--- /dev/null
+++ b/internal/plan3test/coordinator_fixes_test.go
@@ -0,0 +1,302 @@
+package plan3test
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/equipo"
+ "amadan.net/oficina/equipo/internal/equipo/kernel"
+ "amadan.net/oficina/equipo/internal/equipo/team"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+)
+
+func coordinatorEvent(c equipo.CoordinatorClaim, kind string) runnerproto.Event {
+ return runnerproto.Event{Version: 2, ID: kind, TaskID: c.Turn.ID, AssignmentID: c.Turn.ID, ServerID: "fixture", AgentID: "fixture", SessionID: "session", TurnID: c.Turn.ID, Kind: kind, Scope: c.Scope, Handle: c.Handle, ActionID: c.Admission.Dispatch.Action, Payload: json.RawMessage(`{}`), SourceTime: time.Now().UTC()}
+}
+
+func TestCoordinatorFixResetNewMessage(t *testing.T) {
+ f, x, p, b := coordinatorFixture(t)
+ old := queueCoordinator(t, f, "uncertain prompt", "old")
+ c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision)
+ must(t, err)
+ x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ if _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}); err == nil {
+ t.Fatal("reset skipped containment")
+ }
+ must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle}))
+ b2, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision})
+ must(t, err)
+ msg, err := f.Store.SendMessage(ctx, owner, "", "new prompt", equipo.Mutation{RequestID: "new"})
+ must(t, err)
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 1 || turns[0].MessageID != msg.ID || turns[0].Generation != b2.Generation {
+ t.Fatalf("poll must offer only the new prompt: %+v", turns)
+ }
+ next, err := x.ClaimCoordinator(ctx, p, turns[0].ID, turns[0].Revision)
+ if err != nil {
+ t.Fatalf("new generation claim blocked by old uncertainty: %v", err)
+ }
+ if next.Scope.Job == c.Scope.Job || len(next.Context.Messages) != 1 || next.Context.Messages[0].ID != msg.ID {
+ t.Fatal("new message reused the old admission or prompt")
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='uncertain' AND generation=?", old.ID, b.Generation) != 1 {
+ t.Fatal("old uncertain turn changed")
+ }
+ if f.count(t, "SELECT count(*) FROM reservations WHERE job_id=? AND state='settled' AND settled_by='unknown' AND s_calls=r_calls AND s_calls=1 AND s_input=r_input AND s_output=r_output", c.Scope.Job) != 1 || f.count(t, "SELECT count(*) FROM admission_tickets") != 2 {
+ t.Fatal("old uncertainty lost its charge or new message was not admitted")
+ }
+}
+
+func TestCoordinatorFixUncertainWaitsForRetry(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ old := queueCoordinator(t, f, "uncertain prompt", "old")
+ c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision)
+ must(t, err)
+ x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "session.bound")))
+ must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "turn.uncertain")))
+ must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle}))
+ next := queueCoordinator(t, f, "later prompt", "next")
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 0 {
+ t.Fatal("poll offered work behind current uncertainty", turns)
+ }
+ if _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision); err == nil {
+ t.Fatal("claim ignored current uncertainty")
+ }
+ // The next claim must rebuild context from current instance data.
+ f.exec(t, "UPDATE conversation_messages SET body='current context' WHERE id=?", old.MessageID)
+ retry, err := f.Store.RetryCoordinatorTurn(ctx, owner, old.ID, equipo.Mutation{RequestID: "retry", Revision: 2})
+ must(t, err)
+ again, err := x.ClaimCoordinator(ctx, p, retry.ID, retry.Revision)
+ must(t, err)
+ if again.Scope.Job == c.Scope.Job || again.Context.Messages[0].Body != "current context" || again.Turn.ContextHash == c.Turn.ContextHash {
+ t.Fatal("explicit retry reused admission or context")
+ }
+}
+
+func TestCoordinatorFixPollWaitsForContainment(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ old := queueCoordinator(t, f, "first", "first")
+ c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision)
+ must(t, err)
+ x.SetRunnerValidators(equipo.RunnerValidators{CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) {
+ return "answer", team.Receipt{ID: "delivered", Outcome: team.OutcomeSuccess}, nil
+ }})
+ must(t, x.CompleteCoordinator(ctx, p, c, coordinatorEvent(c, "coordinator.delivery")))
+ next := queueCoordinator(t, f, "next", "next")
+ turns, err := x.PollCoordinator(ctx, p)
+ must(t, err)
+ if len(turns) != 0 {
+ t.Fatal("poll offered a turn claim refuses while containment is pending", turns)
+ }
+ if _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision); err == nil {
+ t.Fatal("claim bypassed containment")
+ }
+}
+
+func TestCoordinatorFixCompletedThenDelivery(t *testing.T) {
+ for _, mismatch := range []string{"none", "usage", "unknown", "outcome"} {
+ t.Run(mismatch, func(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ turn := queueCoordinator(t, f, "hello", "turn")
+ c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision)
+ must(t, err)
+ usage := team.Usage{Calls: 1, InputTokens: 12, OutputTokens: 4}
+ completed := team.Receipt{ID: "process-receipt", Outcome: team.OutcomeSuccess, Usage: &usage}
+ delivered := completed
+ delivered.ID = "delivery-receipt"
+ switch mismatch {
+ case "usage":
+ different := usage
+ different.InputTokens++
+ delivered.Usage = &different
+ case "unknown":
+ delivered.Usage = nil
+ case "outcome":
+ completed.Outcome = team.OutcomeFailure
+ }
+ x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) {
+ return completed, nil
+ }, CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) {
+ return "answer", delivered, nil
+ }})
+ must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "session.bound")))
+ must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "turn.completed")))
+ event := coordinatorEvent(c, "coordinator.delivery")
+ err = x.CompleteCoordinator(ctx, p, c, event)
+ if mismatch != "none" {
+ if err == nil {
+ t.Fatal("delivery accepted inconsistent receipt")
+ }
+ if f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 0 {
+ t.Fatal("rejected delivery wrote an answer")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("completed then delivery with distinct receipts failed: %v", err)
+ }
+ must(t, x.CompleteCoordinator(ctx, p, c, event))
+ action, err := x.Core.GetAction(ctx, c.Scope, event.ActionID)
+ must(t, err)
+ if action.Receipt == nil || action.Receipt.ID != completed.ID || action.Receipt.Usage == nil || *action.Receipt.Usage != usage {
+ t.Fatal("delivery replaced the settled receipt", action.Receipt)
+ }
+ if f.count(t, "SELECT count(*) FROM reservations WHERE state='settled'") != 1 || f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 1 || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.delivered'") != 1 || f.count(t, "SELECT count(*) FROM jobs WHERE state='succeeded'") != 1 {
+ t.Fatal("delivery was not settled exactly once")
+ }
+ })
+ }
+}
+
+func TestCoordinatorFixDeliverySession(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ turn := queueCoordinator(t, f, "hello", "turn")
+ c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision)
+ must(t, err)
+ validations := 0
+ x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, CoordinatorDelivery: func(context.Context, equipo.CoordinatorClaim, runnerproto.Event) (string, team.Receipt, error) {
+ validations++
+ return "answer", team.Receipt{ID: "receipt", Outcome: team.OutcomeSuccess}, nil
+ }})
+ must(t, x.CoordinatorEvent(ctx, p, c, coordinatorEvent(c, "session.bound")))
+ event := coordinatorEvent(c, "coordinator.delivery")
+ event.SessionID = "other-session"
+ if err = x.CompleteCoordinator(ctx, p, c, event); err == nil {
+ t.Fatal("delivery overwrote the bound provider session")
+ }
+ if validations != 0 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND provider_session_id='session' AND state='running'", turn.ID) != 1 || f.count(t, "SELECT count(*) FROM conversation_messages WHERE author_kind='coordinator'") != 0 {
+ t.Fatal("mismatched session had effects")
+ }
+ event.SessionID = "session"
+ must(t, x.CompleteCoordinator(ctx, p, c, event))
+}
+
+func TestCoordinatorFixPollUnknownConnection(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ turn := queueCoordinator(t, f, "hello", "turn")
+ _, err := f.Store.SendMessage(ctx, owner, "", "not queued yet", equipo.Mutation{RequestID: "new"})
+ must(t, err)
+ before := f.count(t, "SELECT count(*) FROM audit_events")
+ f.exec(t, "ALTER TABLE connections RENAME TO missing_connections")
+ turns, err := x.PollCoordinator(ctx, p)
+ if err == nil || len(turns) != 0 {
+ t.Fatal("unknown connection lookup became a definite waiting state", turns, err)
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='queued'", turn.ID) != 1 || f.count(t, "SELECT count(*) FROM coordinator_turns") != 1 || f.count(t, "SELECT count(*) FROM audit_events") != before {
+ t.Fatal("failed poll persisted changes")
+ }
+}
+
+func TestCoordinatorFixPollMissingConnection(t *testing.T) {
+ for _, change := range []string{"missing", "stale", "revision"} {
+ t.Run(change, func(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ turn := queueCoordinator(t, f, "hello", "turn")
+ switch change {
+ case "missing":
+ f.exec(t, "DELETE FROM connections WHERE id='claude'")
+ case "stale":
+ f.exec(t, "UPDATE connections SET last_seen=? WHERE id='claude'", time.Now().Add(-time.Hour).UTC())
+ case "revision":
+ f.exec(t, "UPDATE connections SET revision=revision+1 WHERE id='claude'")
+ }
+ if change != "revision" {
+ f.exec(t, "CREATE TRIGGER waiting_audit_failure BEFORE INSERT ON audit_events WHEN NEW.kind='coordinator.waiting_connection' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END")
+ if _, err := x.PollCoordinator(ctx, p); err == nil {
+ t.Fatal("waiting state succeeded without its audit")
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='queued'", turn.ID) != 1 {
+ t.Fatal("audit failure persisted waiting state")
+ }
+ f.exec(t, "DROP TRIGGER waiting_audit_failure")
+ }
+ turns, err := x.PollCoordinator(ctx, p)
+ if change == "revision" {
+ if err == nil || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='queued'", turn.ID) != 1 {
+ t.Fatal("authority mismatch became connection absence")
+ }
+ return
+ }
+ must(t, err)
+ if len(turns) != 0 || f.count(t, "SELECT count(*) FROM coordinator_turns WHERE id=? AND state='waiting_connection'", turn.ID) != 1 {
+ t.Fatal("known missing connection did not persist waiting")
+ }
+ _, err = x.PollCoordinator(ctx, p)
+ must(t, err)
+ if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.waiting_connection' AND record_id=?", turn.ID) != 1 {
+ t.Fatal("waiting state audit missing or duplicated")
+ }
+ })
+ }
+}
+
+func TestCoordinatorFixQueueAudit(t *testing.T) {
+ for _, via := range []string{"queue", "poll", "requeue"} {
+ t.Run(via, func(t *testing.T) {
+ f, x, p, b := coordinatorFixture(t)
+ msg, err := f.Store.SendMessage(ctx, owner, "", "hello", equipo.Mutation{RequestID: "message"})
+ must(t, err)
+ if via == "requeue" {
+ _, err = f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: "initial"})
+ must(t, err)
+ _, err = f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision})
+ must(t, err)
+ }
+ before := f.count(t, "SELECT count(*) FROM coordinator_turns")
+ f.exec(t, "CREATE TRIGGER queue_audit_failure BEFORE INSERT ON audit_events WHEN NEW.kind='coordinator.queue' BEGIN SELECT RAISE(ABORT,'fixture audit failure'); END")
+ queue := func() error {
+ if via == "queue" {
+ _, err := f.Store.QueueCoordinatorTurn(ctx, owner, msg.ID, 0, equipo.Mutation{RequestID: "queue"})
+ return err
+ }
+ _, err := x.PollCoordinator(ctx, p)
+ return err
+ }
+ if err = queue(); err == nil {
+ t.Fatal("queue succeeded without its audit")
+ }
+ if f.count(t, "SELECT count(*) FROM coordinator_turns") != before {
+ t.Fatal("failed audit did not roll back queued turn")
+ }
+ f.exec(t, "DROP TRIGGER queue_audit_failure")
+ must(t, queue())
+ must(t, queue())
+ expected := before + 1
+ if f.count(t, "SELECT count(*) FROM coordinator_turns") != expected || f.count(t, "SELECT count(*) FROM audit_events WHERE kind='coordinator.queue' AND actor=? AND delegating_person=?", "coordinator:"+b.ID, owner.Address) != expected {
+ t.Fatal("queue audit missing, duplicated or misattributed")
+ }
+ })
+ }
+}
+
+func TestCoordinatorFixRetryInputHash(t *testing.T) {
+ f, x, p, _ := coordinatorFixture(t)
+ old := queueCoordinator(t, f, "hello", "old")
+ c, err := x.ClaimCoordinator(ctx, p, old.ID, old.Revision)
+ must(t, err)
+ x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }})
+ must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle}))
+ retry, err := f.Store.RetryCoordinatorTurn(ctx, owner, old.ID, equipo.Mutation{RequestID: "retry", Revision: 2})
+ must(t, err)
+ expected, err := kernel.InputHash(struct {
+ ID string
+ Revision int64
+ }{old.ID, 2})
+ must(t, err)
+ var hash string
+ must(t, f.DB.Writer().QueryRow("SELECT input_hash FROM coordinator_turns WHERE id=?", retry.ID).Scan(&hash))
+ if hash != expected {
+ t.Fatalf("retry input hash = %q, want %q", hash, expected)
+ }
+ replay, err := f.Store.RetryCoordinatorTurn(ctx, owner, old.ID, equipo.Mutation{RequestID: "retry", Revision: 2})
+ must(t, err)
+ if replay.ID != retry.ID {
+ t.Fatal("retry replay duplicated turn")
+ }
+}