fix: retry transient coordinator refusals and finalise only fenced ones
20 files changed,
+912
−45
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+141 −0internal/equipo/conversation/coordinator.go+1 −1internal/equipo/conversation/coordinator_events.go+2 −2internal/equipo/conversation/coordinator_execution.go+1 −1internal/equipo/conversation/coordinator_poll.go+2 −2internal/equipo/conversation/coordinator_recovery.go+14 −2internal/equipo/conversation/coordinator_refusal.go+83 −0internal/plan3test/coordinator_refusal3_test.go+167 −0internal/runner/coordinator_fix_test.go+3 −3internal/runner/coordinator_http_retry_test.go+31 −0internal/runner/coordinator_recovery.go+51 −21internal/runner/coordinator_refusal_test.go+1 −1internal/runner/coordinator_retry.go+71 −0internal/runner/coordinator_retry_test.go+296 −0internal/runner/coordinator_service.go+27 −3internal/runner/http.go+1 −1internal/runner/service.go+2 −5internal/runnerproto/coordinator_handler.go+6 −0internal/runnerproto/retry.go+11 −2
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 1752ef91..e7c4bf50 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -21,7 +21,7 @@ time internal/runner 330s Final corrected package rerun measured 152.897s; revie |
| perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen. |
| perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory. |
| -size internal/runner 9300 8200 Task 7 fix round 1 retains shared-journal refusal recovery, independent polling, containment retry and lease-cadence regression tests beside the runner hooks. Measured 9129 source and 8037 test lines; targeted coordinator runner tests measured 27.384s. Pure context rules remain in runnerproto/coordinator; the 330s time ceiling is unchanged. |
| +size internal/runner 9300 8600 Task 7 fix round 3 keeps journal, service, HTTP classification and restart/refusal matrix tests beside the runner. Measured 9296 source and 8517 test lines; targeted coordinator runner tests measured 63.504s. The source and 330s time ceilings are unchanged. |
| time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner. |
| time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.659s (prior attempt 11.464s) for schema, native approval and fsynced capture fixtures; 15s gives 29 percent headroom under shared-runner load. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index a4003d36..b221c491 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -2748,3 +2748,144 @@ Refused containment reporting does not invent remote acceptance or settle an unk |
| - `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-7-report.md` (ignored report destination) |
| No README, schema, default branch or release changes. No agents or `.claude/HANDOFF.md`. Go caches stayed at their defaults. Task scratch is under `$TMPDIR/equipo-task7-fix2` and is removed after copying the evidence into both reports. All test commands finished; fixture processes and endpoints close through test cleanup. No task server or watcher remains. |
| + |
| + |
| +## Fix round 3 |
| + |
| +Status: DONE. The dispatched refusal/retry finding is fixed. This section supersedes the round 1 and 2 descriptions that treat uncoded HTTP refusals as final. Required commit subject: `fix: retry transient coordinator refusals and finalise only fenced ones` (71 characters). Author: `codex <codex~paul@keymail.dev>`. No push, merge or deployment. |
| + |
| +### Behavior |
| + |
| +Coordinator calls now distinguish explicit fence codes from transient failures. Only a 4xx response carrying `coordinator.fenced`, `coordinator.reset`, `coordinator.superseded` or `coordinator.revoked` permits final refusal retirement. The production instance emits `coordinator.fenced`. Unknown codes, uncoded 401/403/409/422, other uncoded 4xx, network failures, malformed responses and 5xx remain transient. The coordinator boundary converts those remote failures to the retry sentinel; specialist HTTP classification is unchanged. The coordinator HTTP path preserves explicit codes for every 4xx status. |
| + |
| +The instance rechecks the runner and person inside its fence transaction. It requires an already superseded/uncertain turn or an obsolete binding generation. An admitted turn must have an existing attempt whose containment is positively `contained`; pending or unknown containment cannot produce the definitive code. The transaction marks the turn `fenced`, increments its revision and the conversation revision, and records the audit before the coded response is returned. A failed write or lookup cannot become a definitive response. Delivered records retain their state. Polling and the earlier-turn blocker exclude fenced turns. Explicit retry also accepts a fenced turn. This releases later turns without discarding a pending process-containment requirement. |
| + |
| +Transient claim failures retain the durable claim intent. Poll never dispatches an unresolved intent. Recovery either obtains the original claim for cleanup or learns that no claim exists, removes the intent, and lets the next poll claim the queued turn. Definitive claim/recover responses save their code, operation and status before local retirement. A partial retirement resumes from that saved record without another refused call. |
| + |
| +Report retries have per-turn exponential delays of 1, 2, 4, 8 and at most 15 seconds, checked on the existing service poll/lease cadence. Recovery visits pending turns on each service cycle and skips those not yet due. A remote refusal cannot stop specialist work or other offered coordinators. Local journal or containment failures retain their existing blocking behavior. Retry delay is in memory; report/claim work remains durable, so restart retries immediately. Legacy journal entries finalised by rounds 1 or 2 without a definitive code reopen their report work. Only an unclaimed legacy entry can return to polling; a saved claim never returns to provider dispatch. |
| + |
| +Local containment proof is saved before any remote report. While delivery authority remains within its recorded deadlines, a transient delivery failure retries delivery before reporting containment, because the existing containment endpoint makes undelivered work uncertain. After a deadline expires, containment reporting proceeds even if delivery is still refused, then delivery is retried until the instance confirms its fence. Containment failures always retain retry work. A definitive delivery refusal is saved while its containment report is pending. No recovery path sends a provider prompt. |
| + |
| +### Tests and test-first evidence |
| + |
| +`TestCoordinatorRefusalMatrix` covers 11 refusal kinds x four calls x three lifecycle states (132 cases): network, 5xx, uncoded 401/403/409/422, an unknown code and the four definitive codes; claim, recover, containment and delivery; queued, claimed and completed-unreported. Each reachable call checks finality, fatality, retry after journal reopening and prompt count. Impossible lifecycle combinations assert that no call occurs: for example a queued turn has no delivery report, and a saved claim cannot be claimed again. A lost claim response can hide any server state and is reconciled without launching a provider. |
| + |
| +Additional tests cover continued specialist/other-coordinator service, the bounded retry clock, unresolved claim barriers, legacy journal recovery, expiry followed by containment, HTTP classification, durable retirement interrupted by a SQLite trigger, and failure to contain locally. Existing final-refusal tests now supply an explicit fence code. |
| + |
| +Instance tests cover all four operations and three states after reset, real recorded provider completion without coordinator delivery, same-generation queue release, authentication failure, pending and unavailable containment, a failed fence transaction, and the exact code through the HTTP handler. The recorded Claude/Codex continuity fixtures remain offline. |
| + |
| +Tests were written before implementation. Initial runner command (exit 1): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner -run '^TestCoordinator(RefusalMatrix|TransientRefusalKeepsServing)$' -count=1 |
| +``` |
| + |
| +It reproduced `finalised=true want=false` for uncoded recover, containment and delivery refusals, and `remote refusal was fatal` for claim refusals. The first instance command also exited 1: |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(DefinitiveRefusalReleasesQueue|RefusalDoesNotFenceTransientOrPending)$' -count=1 |
| +``` |
| + |
| +Queued cases failed with `missing definitive code` for all four operations. The first claimed-case fixture omitted the containment validator and failed setup; that fixture was corrected before interpreting its results. The runner's other-coordinator fixture also needed a distinct admission action ID. These setup corrections did not replace the reproduced refusal failures. The completed-unreported instance cases were later strengthened to record the provider receipt explicitly. |
| + |
| +### Guard mutations |
| + |
| +Each final mutation below exited 1 on a test assertion and was restored immediately. The final tests ran with all mutations restored. Two first mutation probes passed because another guard protected their chosen path: returning the raw remote error was still caught by `refusedCall`, and a not-yet-due retry did not reach the claim-intent barrier. The HTTP-boundary assertion and a due unresolved-intent test then demonstrated those guards directly. |
| + |
| +- `uncoded-final`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRefusalMatrix/401/recover/queued$ -count=1`. Exit 1; restored. Assertion: `coordinator_retry_test.go:105: finalised=true want=false states=1`. |
| +- `remote-fatal`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorHTTPRefusalClassification$ -count=1`. Exit 1; restored. Assertion: `coordinator_http_retry_test.go:27: status=401 code=form.forbidden final=false error=form.forbidden`. |
| +- `retry-cadence`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRetryCadence$ -count=1`. Exit 1; restored. Assertion: `coordinator_retry_test.go:218: retry churn 4`. |
| +- `pending-claim-barrier`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorPendingClaimPollNeverDispatches$ -count=1`. Exit 1; restored. Assertion: `coordinator_retry_test.go:294: unrecovered claim intent redispatched`. |
| +- `delivery-before-expiry`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorExpiredDeliveryStillReportsContainment$ -count=1`. Exit 1; restored. Assertion: `coordinator_retry_test.go:266: transient delivery lost authority before expiry`. |
| +- `expired-containment`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorExpiredDeliveryStillReportsContainment$ -count=1`. Exit 1; restored. Assertion: `coordinator_retry_test.go:276: expired delivery lost containment retry 0`. |
| +- `legacy-refusal`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorLegacyRefusalRetries/recover$ -count=1`. Exit 1; restored. Assertion: `coordinator_retry_test.go:243: legacy refusal not retried 0`. |
| +- `pending-containment`: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorRefusalDoesNotFenceTransientOrPending$ -count=1`. Exit 1; restored. Assertion: `coordinator_refusal3_test.go:77: pending containment made definitive coordinator.fenced`. |
| +- `durable-fence`: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorDefinitiveRefusalReleasesQueue/claim/queued$ -count=1`. Exit 1; restored. Assertion: `coordinator_refusal3_test.go:53: definitive refusal without durable fence superseded`. |
| +- `fenced-queue`: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestCoordinatorDefinitiveFenceSameGeneration$ -count=1`. Exit 1; restored. Assertion: `coordinator_refusal3_test.go:102: fenced turn still blocks next offer [{ZIDXEFHQRYHOE3XELN5APWOXNL TBJXGHOSHG6R2TZYUYGXE3V222 first e843a8f18b706362834dfd4b42088eea09ce6a62010e5e53420895b695ee2dd6 1 3 fenced}]`. |
| +- `wire-code`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorHTTPRefusalClassification$ -count=1`. Exit 1; restored. Assertion: `coordinator_http_retry_test.go:27: status=401 code=coordinator.fenced final=false error=runner_transient`. |
| +- `durable-refusal`: `CGO_ENABLED=0 go test ./internal/runner -run ^TestCoordinatorRefusalInterruptedRetirement$ -count=1`. Exit 1; restored. Assertion: `coordinator_refusal_test.go:133: interrupted retirement repeated refused call 2`. |
| + |
| +### Final verification |
| + |
| +The broader targeted coordinator regression passed (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/coordinator ./internal/equipo/conversation ./internal/runner ./internal/runnerproto ./internal/runner/provider/... ./internal/plan3test -run '^TestCoordinator' -count=1 |
| +``` |
| + |
| +```text |
| +ok amadan.net/oficina/equipo/internal/coordinator 0.036s |
| +ok amadan.net/oficina/equipo/internal/equipo/conversation 0.004s [no tests to run] |
| +ok amadan.net/oficina/equipo/internal/runner 63.504s |
| +ok amadan.net/oficina/equipo/internal/runnerproto 0.002s [no tests to run] |
| +ok amadan.net/oficina/equipo/internal/runner/provider 0.004s |
| +ok amadan.net/oficina/equipo/internal/runner/provider/claude 5.395s |
| +ok amadan.net/oficina/equipo/internal/runner/provider/codex 7.350s |
| +ok amadan.net/oficina/equipo/internal/plan3test 27.940s |
| +``` |
| + |
| +After the final service guard, expiry and legacy changes, the focused runner/instance regression passed (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/runner ./internal/runnerproto ./internal/plan3test -run '^TestCoordinator(RefusalMatrix|TransientRefusalKeepsServing|RetryCadence|LegacyRefusalRetries|ExpiredDeliveryStillReportsContainment|HTTPRefusalClassification|PendingClaimPollNeverDispatches|Definitive|RefusalDoesNotFenceTransientOrPending|RefusalInterruptedRetirement|RefusalRequiresLocalContainment|RecoveryCallRefusalKeepsServing|RefusalContainmentRetry|SessionService|CrashNeverRedispatches|StopContains)$' -count=1 |
| +``` |
| + |
| +```text |
| +ok amadan.net/oficina/equipo/internal/runner 40.164s |
| +ok amadan.net/oficina/equipo/internal/runnerproto 0.002s [no tests to run] |
| +ok amadan.net/oficina/equipo/internal/plan3test 0.475s |
| +``` |
| + |
| +The definitive instance tests use a separate prefix expression; all final supplementary commands passed (exit 0): |
| + |
| +```sh |
| +CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinator(Definitive.*|RefusalDoesNotFenceTransientOrPending)$' -count=1 |
| +CGO_ENABLED=0 go test ./internal/plan3test -run '^TestCoordinatorFenceUnknownContainmentDenied$' -count=1 |
| +CGO_ENABLED=0 go test ./internal/runner -run '^Test(CoordinatorHTTPRefusalClassification|BudgetRefusalStopsRetry)$' -count=1 |
| +CGO_ENABLED=0 go vet ./internal/equipo/conversation ./internal/runner ./internal/runnerproto ./internal/plan3test |
| +CGO_ENABLED=0 make budget |
| +gofmt -l internal/equipo/conversation internal/runner internal/runnerproto internal/plan3test |
| +git diff --check |
| +``` |
| + |
| +Instance tests took 4.151s and 0.423s; HTTP tests took 0.171s. Vet, formatting and diff checks produced no errors. The size gate reports 30 directories within budget. Its first run correctly failed at 8,508 runner test lines against 8,200; the completed tests measure 8,517. The runner test ceiling is now 8,600. Its source ceiling remains 9,300 and its time ceiling remains 330s. No full test suite or `make ci` ran. There is no SQL/schema change, so no migration check was needed. |
| + |
| +| Directory | Source lines | Test lines | |
| +| --- | ---: | ---: | |
| +| `internal/equipo` | 10798 | 437 | |
| +| `internal/equipo/conversation` | 2540 | 9 | |
| +| `internal/runner` | 9296 | 8517 | |
| +| `internal/runnerproto` | 2234 | 60 | |
| +| `internal/plan3test` | 442 | 3245 | |
| + |
| +### Copy, self-review and limits |
| + |
| +No new or changed user-facing prose or UI copy keys. Existing pending copy remains pending. The protocol accepts four machine codes (`coordinator.fenced`, `coordinator.reset`, `coordinator.superseded`, `coordinator.revoked`); only `coordinator.fenced` is emitted by this instance and used as an audit action. These are protocol identifiers, not new copy entries. No copy-review server or additional agent was started. Reports use plain-writing and humane-docs guidance under the dispatch's explicit report/copy workflow. |
| + |
| +Self-review checked the distinction between remote and local failures, report ordering before/after expiry, positive containment proof before a definitive response, current transaction authority, no queue starvation, durable finality before ACK, old journal reopening, restart retry, and unchanged specialist refusal behavior. Earlier irreversible retirement can already have pruned old tool rows; reopening an old entry can report containment and preserve uncertainty, but cannot reconstruct evidence deleted by the previous implementation. It never fabricates delivery or resends that prompt. A provider result that outlives its delivery authority remains uncertain and needs an explicit person retry. Authentication outages remain retryable until current credentials work again; the runner does not bypass authentication. |
| + |
| +The wider Plan 2b live-release blockers and existing pending copy are outside this fix. No live provider, sign-in, enrolment or release certification ran. No README, vendored static, migration, default branch or deployment changed. No `.claude/HANDOFF.md` was created. Go caches stayed at their defaults. Test fixtures close their processes and endpoints; scratch under `$TMPDIR/equipo-task7-fix3` is removed after the report and commit checks. |
| + |
| +### Files changed |
| + |
| +- `.rastrillo/budgets.txt` |
| +- `internal/equipo/conversation/coordinator.go` |
| +- `internal/equipo/conversation/coordinator_execution.go` |
| +- `internal/equipo/conversation/coordinator_events.go` |
| +- `internal/equipo/conversation/coordinator_poll.go` |
| +- `internal/equipo/conversation/coordinator_recovery.go` |
| +- `internal/equipo/conversation/coordinator_refusal.go` |
| +- `internal/plan3test/coordinator_refusal3_test.go` |
| +- `internal/runner/coordinator_service.go` |
| +- `internal/runner/coordinator_recovery.go` |
| +- `internal/runner/coordinator_retry.go` |
| +- `internal/runner/coordinator_retry_test.go` |
| +- `internal/runner/coordinator_http_retry_test.go` |
| +- `internal/runner/coordinator_refusal_test.go` |
| +- `internal/runner/coordinator_fix_test.go` |
| +- `internal/runner/http.go` |
| +- `internal/runner/service.go` |
| +- `internal/runnerproto/coordinator_handler.go` |
| +- `internal/runnerproto/retry.go` |
| +- `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md` |
| +- `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-7-report.md` (ignored report destination) |
diff --git a/internal/equipo/conversation/coordinator.go b/internal/equipo/conversation/coordinator.go| index 55a19c7f..d993efdc 100644 |
| --- a/internal/equipo/conversation/coordinator.go |
| +++ b/internal/equipo/conversation/coordinator.go |
| @@ -163,7 +163,7 @@ func (s *Store) RetryCoordinator(actor kernel.Actor, id string, m kernel.Mutatio |
| if old.Revision != m.Revision { |
| return out, s.deps.Conflict |
| } |
| - if old.State != "context_limit" && old.State != "context_unavailable" { |
| + if old.State != "context_limit" && old.State != "context_unavailable" && old.State != "fenced" { |
| if old.State != "uncertain" || old.AttemptID == 0 { |
| return out, s.deps.Conflict |
| } |
diff --git a/internal/equipo/conversation/coordinator_events.go b/internal/equipo/conversation/coordinator_events.go| index 8ce4d55a..7b341405 100644 |
| --- a/internal/equipo/conversation/coordinator_events.go |
| +++ b/internal/equipo/conversation/coordinator_events.go |
| @@ -82,7 +82,7 @@ func (e *Engine) CompleteCoordinator(ctx context.Context, p RunnerPrincipal, c C |
| return e.Audit(tx, b, "coordinator.delivered", row.ID) |
| }) |
| } |
| -func (e *Engine) CoordinatorEvent(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| +func (e *Engine) coordinatorEvent(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| if event.Kind == "coordinator.delivery" { |
| return e.CompleteCoordinator(ctx, p, c, event) |
| } |
| @@ -172,7 +172,7 @@ func (e *Engine) CoordinatorEvent(ctx context.Context, p RunnerPrincipal, c Coor |
| return e.Audit(tx, b, "coordinator.event", event.ID) |
| }) |
| } |
| -func (e *Engine) ContainCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, proof runnerproto.ContainmentProof) error { |
| +func (e *Engine) containCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, proof runnerproto.ContainmentProof) error { |
| return e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| // Cleanup authenticates the runner but deliberately permits an old generation. |
| if err := e.RunnerCurrent(tx, p); err != nil { |
diff --git a/internal/equipo/conversation/coordinator_execution.go b/internal/equipo/conversation/coordinator_execution.go| index 58443a6a..1384f865 100644 |
| --- a/internal/equipo/conversation/coordinator_execution.go |
| +++ b/internal/equipo/conversation/coordinator_execution.go |
| @@ -11,7 +11,7 @@ import ( |
| ) |
| func decodeCoordinator(raw string, v any) error { return json.Unmarshal([]byte(raw), v) } |
| -func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, turnID string, revision int64) (CoordinatorClaim, error) { |
| +func (e *Engine) claimCoordinator(ctx context.Context, p RunnerPrincipal, turnID string, revision int64) (CoordinatorClaim, error) { |
| var result CoordinatorClaim |
| var parked error |
| if revision <= 0 || turnID == "" { |
diff --git a/internal/equipo/conversation/coordinator_poll.go b/internal/equipo/conversation/coordinator_poll.go| index 7e875dbc..88f23ea3 100644 |
| --- a/internal/equipo/conversation/coordinator_poll.go |
| +++ b/internal/equipo/conversation/coordinator_poll.go |
| @@ -39,7 +39,7 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| } |
| } |
| var rows []TurnRecord |
| - if err = tx.Where("binding_id=? AND generation=? AND state NOT IN ('delivered','superseded')", b.ID, b.Generation).Order("sequence").Limit(1).Find(&rows).Error; err != nil { |
| + if err = tx.Where("binding_id=? AND generation=? AND state NOT IN ('delivered','superseded','fenced')", b.ID, b.Generation).Order("sequence").Limit(1).Find(&rows).Error; err != nil { |
| return err |
| } |
| for _, row := range rows { |
| @@ -85,7 +85,7 @@ func (e *Engine) PollCoordinator(ctx context.Context, p RunnerPrincipal) ([]Coor |
| 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 |
| + 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','fenced')))) 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 |
| } |
diff --git a/internal/equipo/conversation/coordinator_recovery.go b/internal/equipo/conversation/coordinator_recovery.go| index 39c6b41d..17f127aa 100644 |
| --- a/internal/equipo/conversation/coordinator_recovery.go |
| +++ b/internal/equipo/conversation/coordinator_recovery.go |
| @@ -11,7 +11,7 @@ import ( |
| // RecoverCoordinator returns only the original claim for reconciliation. It |
| // neither renews admission nor grants permission to start a provider process. |
| -func (e *Engine) RecoverCoordinator(ctx context.Context, p RunnerPrincipal, id string, revision int64) (CoordinatorClaim, error) { |
| +func (e *Engine) recoverCoordinator(ctx context.Context, p RunnerPrincipal, id string, revision int64) (CoordinatorClaim, error) { |
| var out CoordinatorClaim |
| err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| if err := e.RunnerCurrent(tx, p); err != nil { |
| @@ -21,6 +21,18 @@ func (e *Engine) RecoverCoordinator(ctx context.Context, p RunnerPrincipal, id s |
| if err := tx.Where("id=? AND person=?", id, p.Person).First(&row).Error; err != nil { |
| return err |
| } |
| + if row.State == "fenced" || row.State == "superseded" { |
| + return e.Conflict |
| + } |
| + if row.State == "uncertain" && row.AttemptID != 0 { |
| + var containment string |
| + if err := tx.Table("attempts").Select("containment").Where("id=?", row.AttemptID).Take(&containment).Error; err != nil { |
| + return err |
| + } |
| + if containment == "contained" { |
| + return e.Conflict |
| + } |
| + } |
| if row.Claim == "" { |
| return nil |
| } |
| @@ -34,7 +46,7 @@ func (e *Engine) RecoverCoordinator(ctx context.Context, p RunnerPrincipal, id s |
| }) |
| return out, err |
| } |
| -func (e *Engine) CoordinatorToolResult(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, call CoordinatorToolCall) (CoordinatorToolResult, error) { |
| +func (e *Engine) coordinatorToolResult(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, call CoordinatorToolCall) (CoordinatorToolResult, error) { |
| var out CoordinatorToolResult |
| canonical, err := coordinator.Canonical(call) |
| if err != nil { |
diff --git a/internal/equipo/conversation/coordinator_refusal.go b/internal/equipo/conversation/coordinator_refusal.go| new file mode 100644 |
| index 00000000..09d91b31 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/coordinator_refusal.go |
| @@ -0,0 +1,83 @@ |
| +package conversation |
| + |
| +import ( |
| + "context" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// A definitive response is a committed fence, with no unresolved containment. |
| +// Authentication failures and failed lookups never establish that fact. |
| +func (e *Engine) coordinatorRefusal(ctx context.Context, p RunnerPrincipal, id string, cause error) error { |
| + if cause == nil { |
| + return nil |
| + } |
| + fenced := false |
| + err := e.Atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + if err := e.RunnerCurrent(tx, p); err != nil { |
| + return err |
| + } |
| + var row TurnRecord |
| + if err := tx.Where("id=? AND person=?", id, p.Person).First(&row).Error; err != nil { |
| + return err |
| + } |
| + var b BindingRecord |
| + if err := tx.First(&b, "id=? AND person=?", row.BindingID, p.Person).Error; err != nil { |
| + return err |
| + } |
| + if row.State == "delivered" { |
| + return nil |
| + } |
| + if row.State != "uncertain" && row.State != "superseded" && row.State != "fenced" && b.Generation == row.Generation { |
| + return nil |
| + } |
| + if row.AttemptID != 0 { |
| + var containment string |
| + if err := tx.Table("attempts").Select("containment").Where("id=?", row.AttemptID).Take(&containment).Error; err != nil { |
| + return err |
| + } |
| + if containment != "contained" { |
| + return nil |
| + } |
| + } |
| + if row.State != "fenced" { |
| + if err := tx.Model(&TurnRecord{}).Where("id=?", id).Select("state", "revision").Updates(map[string]any{"state": "fenced", "revision": gorm.Expr("revision+1")}).Error; err != nil { |
| + return err |
| + } |
| + if err := tx.Model(&Main{}).Where("id=?", row.ConversationID).UpdateColumn("revision", gorm.Expr("revision+1")).Error; err != nil { |
| + return err |
| + } |
| + if err := e.Audit(tx, b, "coordinator.fenced", id); err != nil { |
| + return err |
| + } |
| + } |
| + fenced = true |
| + return nil |
| + }) |
| + if err != nil { |
| + return err |
| + } |
| + if fenced { |
| + return &runnerproto.RefusalError{Status: 409, Reason: "coordinator.fenced"} |
| + } |
| + return cause |
| +} |
| +func (e *Engine) ClaimCoordinator(ctx context.Context, p RunnerPrincipal, id string, revision int64) (CoordinatorClaim, error) { |
| + c, err := e.claimCoordinator(ctx, p, id, revision) |
| + return c, e.coordinatorRefusal(ctx, p, id, err) |
| +} |
| +func (e *Engine) RecoverCoordinator(ctx context.Context, p RunnerPrincipal, id string, revision int64) (CoordinatorClaim, error) { |
| + c, err := e.recoverCoordinator(ctx, p, id, revision) |
| + return c, e.coordinatorRefusal(ctx, p, id, err) |
| +} |
| +func (e *Engine) ContainCoordinator(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, proof runnerproto.ContainmentProof) error { |
| + return e.coordinatorRefusal(ctx, p, c.Turn.ID, e.containCoordinator(ctx, p, c, proof)) |
| +} |
| +func (e *Engine) CoordinatorEvent(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, event runnerproto.Event) error { |
| + return e.coordinatorRefusal(ctx, p, c.Turn.ID, e.coordinatorEvent(ctx, p, c, event)) |
| +} |
| +func (e *Engine) CoordinatorToolResult(ctx context.Context, p RunnerPrincipal, c CoordinatorClaim, call CoordinatorToolCall) (CoordinatorToolResult, error) { |
| + out, err := e.coordinatorToolResult(ctx, p, c, call) |
| + return out, e.coordinatorRefusal(ctx, p, c.Turn.ID, err) |
| +} |
diff --git a/internal/plan3test/coordinator_refusal3_test.go b/internal/plan3test/coordinator_refusal3_test.go| new file mode 100644 |
| index 00000000..25391c70 |
| --- /dev/null |
| +++ b/internal/plan3test/coordinator_refusal3_test.go |
| @@ -0,0 +1,167 @@ |
| +package plan3test |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/http" |
| + "net/http/httptest" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func TestCoordinatorDefinitiveRefusalReleasesQueue(t *testing.T) { |
| + for _, op := range []string{"claim", "recover", "containment", "delivery"} { |
| + for _, phase := range []string{"queued", "claimed", "completed-unreported"} { |
| + t.Run(op+"/"+phase, func(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + turn := queueCoordinator(t, f, "first", "first") |
| + c := equipo.CoordinatorClaim{Turn: turn} |
| + if phase != "queued" { |
| + var err error |
| + c, err = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + } |
| + if phase == "completed-unreported" { |
| + must(t, x.Core.Record(ctx, c.Scope, c.Admission.Dispatch.Action, team.Receipt{ID: "completed", Outcome: team.OutcomeSuccess})) |
| + } |
| + if phase != "queued" { |
| + proof := runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle} |
| + must(t, x.ContainCoordinator(ctx, p, c, proof)) |
| + } |
| + _, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + var refusal error |
| + switch op { |
| + case "claim": |
| + _, refusal = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + case "recover": |
| + _, refusal = x.RecoverCoordinator(ctx, p, turn.ID, turn.Revision) |
| + case "containment": |
| + refusal = x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{}) |
| + case "delivery": |
| + refusal = x.CoordinatorEvent(ctx, p, c, runnerproto.Event{Kind: "coordinator.delivery"}) |
| + } |
| + var definitive *runnerproto.RefusalError |
| + if !errors.As(refusal, &definitive) || definitive.Reason != "coordinator.fenced" { |
| + t.Fatal("missing definitive code", refusal) |
| + } |
| + var state string |
| + must(t, f.DB.Writer().QueryRow("SELECT state FROM coordinator_turns WHERE id=?", turn.ID).Scan(&state)) |
| + if state != "fenced" { |
| + t.Fatal("definitive refusal without durable fence", state) |
| + } |
| + next := queueCoordinator(t, f, "later", "later") |
| + _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| + must(t, err) |
| + }) |
| + } |
| + } |
| +} |
| +func TestCoordinatorRefusalDoesNotFenceTransientOrPending(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "first", "first") |
| + bad := p |
| + bad.CredentialID = "stale" |
| + _, err := x.RecoverCoordinator(ctx, bad, turn.ID, turn.Revision) |
| + var coded *runnerproto.RefusalError |
| + if err == nil || errors.As(err, &coded) { |
| + t.Fatal("authentication error made definitive", err) |
| + } |
| + c, err := x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + must(t, err) |
| + f.exec(t, "UPDATE coordinator_turns SET state='uncertain' WHERE id=?", turn.ID) |
| + _, err = x.ClaimCoordinator(ctx, p, turn.ID, turn.Revision) |
| + if errors.As(err, &coded) { |
| + t.Fatal("pending containment made definitive", err) |
| + } |
| + var state string |
| + must(t, f.DB.Writer().QueryRow("SELECT containment FROM attempts WHERE id=?", c.Handle.Attempt).Scan(&state)) |
| + if state != "pending" { |
| + t.Fatal("refusal invented containment", state) |
| + } |
| +} |
| + |
| +func TestCoordinatorDefinitiveFenceSameGeneration(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + first := queueCoordinator(t, f, "first", "first") |
| + c, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| + must(t, err) |
| + must(t, x.ContainCoordinator(ctx, p, c, runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle})) |
| + next := queueCoordinator(t, f, "next", "next") |
| + _, err = x.RecoverCoordinator(ctx, p, first.ID, first.Revision) |
| + var refusal *runnerproto.RefusalError |
| + if !errors.As(err, &refusal) || !refusal.CoordinatorDefinitive() { |
| + t.Fatal("missing definitive refusal", err) |
| + } |
| + offers, err := x.PollCoordinator(ctx, p) |
| + must(t, err) |
| + if len(offers) != 1 || offers[0].ID != next.ID { |
| + t.Fatal("fenced turn still blocks next offer", offers) |
| + } |
| + _, err = x.ClaimCoordinator(ctx, p, next.ID, next.Revision) |
| + must(t, err) |
| +} |
| + |
| +func TestCoordinatorDefinitiveFenceAtomic(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + first := queueCoordinator(t, f, "first", "first") |
| + _, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + f.exec(t, `CREATE TRIGGER reject_fence BEFORE UPDATE ON coordinator_turns WHEN NEW.state='fenced' BEGIN SELECT RAISE(ABORT,'fence write failed'); END`) |
| + _, err = x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| + var refusal *runnerproto.RefusalError |
| + if err == nil || errors.As(err, &refusal) { |
| + t.Fatal("definitive response escaped failed commit", err) |
| + } |
| + f.exec(t, "DROP TRIGGER reject_fence") |
| + _, err = x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| + if !errors.As(err, &refusal) { |
| + t.Fatal("restored fence not definitive", err) |
| + } |
| +} |
| + |
| +func TestCoordinatorDefinitiveFenceHTTP(t *testing.T) { |
| + f, x, p, b := coordinatorFixture(t) |
| + turn := queueCoordinator(t, f, "first", "first") |
| + _, err := f.Store.ResetCoordinator(ctx, owner, equipo.Mutation{RequestID: "reset", Revision: b.Revision}) |
| + must(t, err) |
| + h := runnerproto.Handler{Execution: func() runnerproto.ExecutionAPI { return x }, AuthenticateRunner: func(context.Context, string) (runnerproto.RunnerPrincipal, error) { return p, nil }, JSON: func(w http.ResponseWriter, status int, v any) { |
| + w.WriteHeader(status) |
| + _ = json.NewEncoder(w).Encode(v) |
| + }, Failure: func(w http.ResponseWriter, err error) { t.Errorf("lost coded refusal: %v", err); w.WriteHeader(500) }} |
| + for _, op := range []string{"claim", "recover"} { |
| + raw, err := json.Marshal(runnerproto.CoordinatorRequest{Version: 2, Capabilities: []string{runnerproto.CoordinatorCapability}, TurnID: turn.ID, Revision: turn.Revision}) |
| + must(t, err) |
| + request := httptest.NewRequest("POST", "/coordinator/"+op, bytes.NewReader(raw)) |
| + request.Header.Set("Authorization", "Bearer fixture") |
| + request.Header.Set("Content-Type", "application/json") |
| + response := httptest.NewRecorder() |
| + h.Router().ServeHTTP(response, request) |
| + var body runnerproto.ErrorResponse |
| + must(t, json.Unmarshal(response.Body.Bytes(), &body)) |
| + if response.Code != 409 || body.Error != "coordinator.fenced" { |
| + t.Fatal("fence code lost on wire", response.Code, body) |
| + } |
| + } |
| +} |
| + |
| +func TestCoordinatorFenceUnknownContainmentDenied(t *testing.T) { |
| + f, x, p, _ := coordinatorFixture(t) |
| + first := queueCoordinator(t, f, "first", "first") |
| + _, err := x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| + must(t, err) |
| + f.exec(t, "UPDATE coordinator_turns SET state='uncertain' WHERE id=?", first.ID) |
| + f.exec(t, "ALTER TABLE attempts RENAME TO unavailable_attempts") |
| + _, err = x.ClaimCoordinator(ctx, p, first.ID, first.Revision) |
| + var refusal *runnerproto.RefusalError |
| + if err == nil || errors.As(err, &refusal) { |
| + t.Fatal("unknown containment became definitive", err) |
| + } |
| +} |
diff --git a/internal/runner/coordinator_fix_test.go b/internal/runner/coordinator_fix_test.go| index 06a4062e..1f5cd077 100644 |
| --- a/internal/runner/coordinator_fix_test.go |
| +++ b/internal/runner/coordinator_fix_test.go |
| @@ -49,7 +49,7 @@ func TestCoordinatorRecoveryRefusedKeepsServing(t *testing.T) { |
| mustJournal(t, s.Journal.consumeTurn(ctx, session.AttemptKey, session.ID, turn.Prompt)) |
| pump := EventPump{Journal: s.Journal, Contain: func(context.Context) error { return nil }} |
| mustJournal(t, pump.AppendDirect(ctx, session, provider.Event{SessionID: session.ID, TurnID: turn.ID, Kind: "turn.completed", Payload: json.RawMessage(`{}`)}, s.template(r))) |
| - refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Status: status}} |
| + refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Reason: "coordinator.fenced", Status: status}} |
| s.API = refused |
| for restart := 0; restart < 2; restart++ { |
| path := s.Journal.path |
| @@ -94,7 +94,7 @@ func TestCoordinatorPollErrorKeepsServing(t *testing.T) { |
| } |
| func TestCoordinatorCleanupRefusalReportsContainment(t *testing.T) { |
| s, api, _, c := coordinatorServiceFixture(t) |
| - refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Status: 403}} |
| + refused := &refusingCoordinatorAPI{coordinatorAPIStub: api, refusal: &RefusalError{Reason: "coordinator.fenced", Status: 403}} |
| s.API = refused |
| _ = s.RunTurn(context.Background(), c) |
| if refused.contained != 1 { |
| @@ -181,7 +181,7 @@ func TestCoordinatorRefusalContainmentRetry(t *testing.T) { |
| s.API = api |
| state := coordinatorState{Claim: c} |
| proof := runnerproto.ContainmentProof{Scope: c.Scope, Handle: c.Handle} |
| - refusal := &RefusalError{Status: 403} |
| + refusal := &RefusalError{Reason: "coordinator.fenced", Status: 403} |
| err := s.finishContained(context.Background(), &state, proof, refusal) |
| if !errors.Is(err, ErrTransient) || fatalServiceError(err) || state.Finished { |
| t.Fatal("delivery refusal made transient containment failure fatal", err) |
diff --git a/internal/runner/coordinator_http_retry_test.go b/internal/runner/coordinator_http_retry_test.go| new file mode 100644 |
| index 00000000..581ebb8e |
| --- /dev/null |
| +++ b/internal/runner/coordinator_http_retry_test.go |
| @@ -0,0 +1,31 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func TestCoordinatorHTTPRefusalClassification(t *testing.T) { |
| + for _, status := range []int{401, 403, 404, 409, 422, 429, 500, 503} { |
| + for _, code := range []string{"coordinator.fenced", "coordinator.reset", "coordinator.superseded", "coordinator.revoked", "form.forbidden", "unknown"} { |
| + c := &HTTPInstance{origin: "https://equipo.example", bearer: runnerproto.RunnerCredential{Token: "fixture", ExpiresAt: time.Now().Add(time.Hour)}, client: &http.Client{Transport: transportFunc(func(*http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(`{"version":2,"error":"` + code + `"}`))}, nil |
| + })}} |
| + s := CoordinatorService{API: c} |
| + err := s.call(context.Background(), "recover", runnerproto.CoordinatorRequest{}, nil) |
| + var refusal *RefusalError |
| + final := errors.As(err, &refusal) && refusal.CoordinatorDefinitive() |
| + want := (status >= 400 && status < 500) && strings.HasPrefix(code, "coordinator.") |
| + if final != want || !final && !errors.Is(err, ErrTransient) { |
| + t.Fatalf("status=%d code=%s final=%v error=%v", status, code, final, err) |
| + } |
| + } |
| + } |
| +} |
diff --git a/internal/runner/coordinator_recovery.go b/internal/runner/coordinator_recovery.go| index 0e20ffad..144d1949 100644 |
| --- a/internal/runner/coordinator_recovery.go |
| +++ b/internal/runner/coordinator_recovery.go |
| @@ -13,11 +13,17 @@ import ( |
| ) |
| func (s *CoordinatorService) Recover(ctx context.Context) error { |
| + if err := s.reopenUncodedRefusals(ctx); err != nil { |
| + return err |
| + } |
| var pending []runnerproto.CoordinatorRequest |
| if err := s.Journal.readStates(ctx, "coordinator-claim", &pending); err != nil { |
| return err |
| } |
| for _, q := range pending { |
| + if !s.retryDue(q.TurnID) { |
| + continue |
| + } |
| var n int |
| if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", q.TurnID).Scan(&n); err != nil { |
| return err |
| @@ -27,14 +33,8 @@ func (s *CoordinatorService) Recover(ctx context.Context) error { |
| } |
| var c runnerproto.CoordinatorClaim |
| if err := s.call(ctx, "recover", q, &c); err != nil { |
| - var refusal *RefusalError |
| - if !errors.As(err, &refusal) { |
| - return err |
| - } |
| - // RunTurn saves its claim before creating a namespace. With no saved |
| - // claim there can be no local process, even if the server admitted it. |
| r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: runnerproto.CoordinatorTurn{ID: q.TurnID, Revision: q.Revision}}} |
| - if err = s.recordRefusal(ctx, &r, "recover", refusal); err != nil { |
| + if err = s.refusedCall(ctx, &r, "recover", err); err != nil { |
| return err |
| } |
| continue |
| @@ -54,6 +54,9 @@ func (s *CoordinatorService) Recover(ctx context.Context) error { |
| return err |
| } |
| for _, r := range states { |
| + if !s.retryDue(r.Claim.Turn.ID) { |
| + continue |
| + } |
| if r.Finished { |
| continue |
| } |
| @@ -86,43 +89,66 @@ func (s *CoordinatorService) Recover(ctx context.Context) error { |
| return err |
| } |
| var deliveryErr error |
| - if status == "completed" { |
| + if r.DeliveryRefusal != nil { |
| + deliveryErr = r.DeliveryRefusal |
| + } else if status == "completed" { |
| deliveryErr = s.reconcileTools(ctx, r) |
| if deliveryErr == nil { |
| deliveryErr = s.finishDelivery(ctx, r) |
| } |
| } |
| if err = s.finishContained(ctx, &r, proof, deliveryErr); err != nil { |
| + if errors.Is(err, ErrTransient) { |
| + s.deferRetry(r.Claim.Turn.ID) |
| + continue |
| + } |
| return err |
| } |
| } |
| return nil |
| } |
| -// Report local containment even when delivery authority has expired. |
| +// Keep delivery authority until its report is accepted or explicitly fenced. |
| func (s *CoordinatorService) finishContained(ctx context.Context, r *coordinatorState, proof runnerproto.ContainmentProof, deliveryErr error) error { |
| + r.Containment = &proof |
| + var refusal *RefusalError |
| + if errors.As(deliveryErr, &refusal) && refusal.CoordinatorDefinitive() { |
| + r.DeliveryRefusal = refusal |
| + } |
| + if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { |
| + return err |
| + } |
| + if deliveryErr != nil && !errors.Is(deliveryErr, ErrTransient) && !errors.Is(deliveryErr, provider.ErrUncertain) && r.DeliveryRefusal == nil { |
| + return deliveryErr |
| + } |
| + pendingDelivery := deliveryErr != nil && !errors.Is(deliveryErr, provider.ErrUncertain) && r.DeliveryRefusal == nil |
| + // Once admission expires, containment must still reach the instance. Its |
| + // next delivery response can then confirm the durable fence explicitly. |
| + if pendingDelivery && s.clock().Before(r.Claim.LeaseDeadline) && s.clock().Before(r.Claim.AttemptDeadline) { |
| + return ErrTransient |
| + } |
| q := coordinatorRequest(r.Claim) |
| q.Proof = &proof |
| if err := s.call(ctx, "containment", q, nil); err != nil { |
| - var refusal *RefusalError |
| - if !errors.As(err, &refusal) { |
| - return err |
| + if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| + return s.recordRefusal(ctx, r, "containment", refusal) |
| } |
| - r.Containment = &proof |
| - return s.recordRefusal(ctx, r, "containment", refusal) |
| + return ErrTransient |
| } |
| - var refusal *RefusalError |
| - if deliveryErr != nil && !errors.Is(deliveryErr, provider.ErrUncertain) && !errors.As(deliveryErr, &refusal) { |
| - return deliveryErr |
| + if pendingDelivery { |
| + return ErrTransient |
| } |
| - if refusal != nil { |
| - return s.recordRefusal(ctx, r, "delivery", refusal) |
| + if r.DeliveryRefusal != nil { |
| + return s.recordRefusal(ctx, r, "delivery", r.DeliveryRefusal) |
| } |
| return s.retireCoordinator(ctx, r) |
| } |
| func (s *CoordinatorService) recordRefusal(ctx context.Context, r *coordinatorState, operation string, refusal *RefusalError) error { |
| - r.Refused, r.RefusalOperation, r.RefusalStatus = true, operation, refusal.Status |
| + if !refusal.CoordinatorDefinitive() { |
| + return ErrTransient |
| + } |
| + r.Refused, r.RefusalOperation, r.RefusalStatus, r.RefusalCode = true, operation, refusal.Status, refusal.Reason |
| // Save the refusal before acknowledging events, so interrupted retirement |
| // resumes locally without repeating a refused call or sending a prompt. |
| if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { |
| @@ -136,7 +162,11 @@ func (s *CoordinatorService) retireCoordinator(ctx context.Context, r *coordinat |
| return err |
| } |
| r.Finished = true |
| - return s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r) |
| + if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { |
| + return err |
| + } |
| + delete(s.retry, r.Claim.Turn.ID) |
| + return nil |
| } |
| // Contained uncertain observations stay in the local audit journal but cannot |
diff --git a/internal/runner/coordinator_refusal_test.go b/internal/runner/coordinator_refusal_test.go| index 18e019b4..1dfa0cd7 100644 |
| --- a/internal/runner/coordinator_refusal_test.go |
| +++ b/internal/runner/coordinator_refusal_test.go |
| @@ -26,7 +26,7 @@ func (a *recoveryRefusalAPI) CoordinatorCall(ctx context.Context, op string, q r |
| } |
| if op == a.operation && id == a.refusedID { |
| a.refusals++ |
| - return &RefusalError{Status: a.status} |
| + return &RefusalError{Reason: "coordinator.fenced", Status: a.status} |
| } |
| if op == "poll" { |
| *out.(*[]runnerproto.CoordinatorTurn) = a.offers |
diff --git a/internal/runner/coordinator_retry.go b/internal/runner/coordinator_retry.go| new file mode 100644 |
| index 00000000..4b663fb5 |
| --- /dev/null |
| +++ b/internal/runner/coordinator_retry.go |
| @@ -0,0 +1,71 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "errors" |
| + "time" |
| +) |
| + |
| +type coordinatorRetry struct { |
| + failures int |
| + after time.Time |
| +} |
| + |
| +func (s *CoordinatorService) clock() time.Time { |
| + if s.now != nil { |
| + return s.now() |
| + } |
| + return time.Now() |
| +} |
| +func (s *CoordinatorService) retryDue(id string) bool { return !s.clock().Before(s.retry[id].after) } |
| +func (s *CoordinatorService) deferRetry(id string) { |
| + if s.retry == nil { |
| + s.retry = map[string]coordinatorRetry{} |
| + } |
| + r := s.retry[id] |
| + r.failures = min(r.failures+1, 6) |
| + r.after = s.clock().Add(min(leaseRenewInterval, time.Second*time.Duration(1<<(r.failures-1)))) |
| + s.retry[id] = r |
| +} |
| +func (s *CoordinatorService) refusedCall(ctx context.Context, r *coordinatorState, op string, err error) error { |
| + var refusal *RefusalError |
| + if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| + return s.recordRefusal(ctx, r, op, refusal) |
| + } |
| + if ctx.Err() != nil { |
| + return ctx.Err() |
| + } |
| + s.deferRetry(r.Claim.Turn.ID) |
| + return nil |
| +} |
| + |
| +// Older journals treated uncoded refusals as final. Restore their report work; |
| +// no record with a saved claim can return to provider dispatch. |
| +func (s *CoordinatorService) reopenUncodedRefusals(ctx context.Context) error { |
| + var states []coordinatorState |
| + if err := s.Journal.readStates(ctx, "coordinator", &states); err != nil { |
| + return err |
| + } |
| + for _, r := range states { |
| + if !r.Refused || (&RefusalError{Status: r.RefusalStatus, Reason: r.RefusalCode}).CoordinatorDefinitive() { |
| + continue |
| + } |
| + id := r.Claim.Turn.ID |
| + if r.Claim.Handle.Attempt == 0 { |
| + q := runnerproto.CoordinatorRequest{TurnID: id, Revision: r.Claim.Turn.Revision} |
| + if err := s.Journal.saveState(ctx, "coordinator-claim", id, q); err != nil { |
| + return err |
| + } |
| + if _, err := s.Journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", id); err != nil { |
| + return err |
| + } |
| + } else { |
| + r.Finished, r.Refused = false, false |
| + if err := s.Journal.saveState(ctx, "coordinator", id, r); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/coordinator_retry_test.go b/internal/runner/coordinator_retry_test.go| new file mode 100644 |
| index 00000000..1f6905ae |
| --- /dev/null |
| +++ b/internal/runner/coordinator_retry_test.go |
| @@ -0,0 +1,296 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type coordinatorRetryAPI struct { |
| + contained int |
| + *coordinatorAPIStub |
| + operation string |
| + failure error |
| + calls int |
| + queued bool |
| +} |
| + |
| +func (a *coordinatorRetryAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| + if op == "containment" { |
| + a.contained++ |
| + } |
| + match := op == a.operation || a.operation == "delivery" && op == "event" && q.Event.Kind == "coordinator.delivery" |
| + if match { |
| + a.calls++ |
| + if a.failure != nil { |
| + return a.failure |
| + } |
| + } |
| + if op == "recover" && a.queued { |
| + return nil |
| + } |
| + return a.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) |
| +} |
| +func reopenCoordinator(t *testing.T, s *CoordinatorService, l *coordinatorFixtureLauncher) { |
| + t.Helper() |
| + path := s.Journal.path |
| + mustJournal(t, s.Journal.Close()) |
| + j, err := OpenJournal(context.Background(), path) |
| + mustJournal(t, err) |
| + t.Cleanup(func() { j.Close() }) |
| + s.Journal, l.j = j, j |
| +} |
| +func TestCoordinatorRefusalMatrix(t *testing.T) { |
| + kinds := []struct { |
| + name string |
| + err error |
| + final bool |
| + }{ |
| + {"network", ErrTransient, false}, {"5xx", &RefusalError{Status: 503}, false}, |
| + {"401", &RefusalError{Status: 401}, false}, {"403", &RefusalError{Status: 403}, false}, |
| + {"409", &RefusalError{Status: 409}, false}, {"422", &RefusalError{Status: 422}, false}, |
| + {"unknown_code", &RefusalError{Status: 403, Reason: "unknown"}, false}, |
| + {"fenced", &RefusalError{Status: 409, Reason: "coordinator.fenced"}, true}, |
| + {"reset", &RefusalError{Status: 403, Reason: "coordinator.reset"}, true}, |
| + {"superseded", &RefusalError{Status: 422, Reason: "coordinator.superseded"}, true}, |
| + {"revoked", &RefusalError{Status: 401, Reason: "coordinator.revoked"}, true}, |
| + } |
| + for _, k := range kinds { |
| + for _, op := range []string{"claim", "recover", "containment", "delivery"} { |
| + for _, phase := range []string{"queued", "claimed", "completed-unreported"} { |
| + t.Run(k.name+"/"+op+"/"+phase, func(t *testing.T) { |
| + ctx := context.Background() |
| + s, base, l, c := coordinatorServiceFixture(t) |
| + api := &coordinatorRetryAPI{coordinatorAPIStub: base, operation: op, failure: k.err, queued: phase == "queued"} |
| + s.API = api |
| + // A lost claim response can hide any server state. Saved local claims must |
| + // never return to claim/recover, and queued work has no report to send. |
| + reachable := op == "recover" || op == "claim" && phase == "queued" || (op == "containment" && phase != "queued") || op == "delivery" && phase == "completed-unreported" |
| + if phase == "completed-unreported" && op != "recover" { |
| + setup := &coordinatorRetryAPI{coordinatorAPIStub: base, operation: "delivery", failure: ErrTransient} |
| + s.API = setup |
| + _ = s.RunTurn(ctx, c) |
| + s.API = api |
| + } else if phase == "claimed" && op != "recover" { |
| + mustJournal(t, s.Journal.saveState(ctx, "coordinator", c.Turn.ID, coordinatorState{Claim: c})) |
| + } |
| + if op == "recover" { |
| + mustJournal(t, s.Journal.saveState(ctx, "coordinator-claim", c.Turn.ID, runnerproto.CoordinatorRequest{TurnID: c.Turn.ID, Revision: c.Turn.Revision})) |
| + } |
| + starts := l.starts |
| + var err error |
| + if op == "claim" { |
| + err = s.Poll(ctx) |
| + } else { |
| + err = s.Recover(ctx) |
| + } |
| + if fatalServiceError(err) { |
| + t.Fatal("remote refusal was fatal", err) |
| + } |
| + var states []coordinatorState |
| + mustJournal(t, s.Journal.readStates(ctx, "coordinator", &states)) |
| + if reachable && api.calls != 1 { |
| + t.Fatalf("refusal not exercised: calls=%d", api.calls) |
| + } |
| + if !reachable && api.calls != 0 { |
| + t.Fatal("invalid lifecycle call", api.calls) |
| + } |
| + if reachable { |
| + final := len(states) == 1 && states[0].Finished && states[0].Refused |
| + if final != k.final { |
| + t.Fatalf("finalised=%v want=%v states=%d", final, k.final, len(states)) |
| + } |
| + } |
| + if l.starts != starts { |
| + t.Fatal("report retry resent prompt") |
| + } |
| + if !reachable { |
| + return |
| + } |
| + // A new service with the reopened journal must retry only transient calls. |
| + reopenCoordinator(t, s, l) |
| + restarted := *s |
| + s = &restarted |
| + s.retry = nil |
| + api.failure = nil |
| + before := api.calls |
| + if op == "claim" { |
| + api.queued = true |
| + } |
| + mustJournal(t, s.Recover(ctx)) |
| + if op == "claim" && !k.final { |
| + base.polled = false |
| + mustJournal(t, s.Poll(ctx)) |
| + } |
| + if k.final && api.calls != before { |
| + t.Fatal("definitive refusal repeated") |
| + } |
| + if !k.final && api.calls != before+1 { |
| + t.Fatal("transient refusal lost retry", api.calls, before) |
| + } |
| + if op != "claim" && l.starts != starts { |
| + t.Fatal("restart resent provider prompt") |
| + } |
| + }) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestCoordinatorTransientRefusalKeepsServing(t *testing.T) { |
| + for _, op := range []string{"recover", "containment", "delivery"} { |
| + t.Run(op, func(t *testing.T) { |
| + s, base, l, c := coordinatorServiceFixture(t) |
| + api := &coordinatorRetryAPI{coordinatorAPIStub: base, operation: op, failure: &RefusalError{Status: 403}} |
| + if op == "recover" { |
| + mustJournal(t, s.Journal.saveState(context.Background(), "coordinator-claim", c.Turn.ID, runnerproto.CoordinatorRequest{TurnID: c.Turn.ID, Revision: c.Turn.Revision})) |
| + } else if op == "containment" { |
| + mustJournal(t, s.Journal.saveState(context.Background(), "coordinator", c.Turn.ID, coordinatorState{Claim: c})) |
| + } else { |
| + s.API = api |
| + _ = s.RunTurn(context.Background(), c) |
| + } |
| + s.API = api |
| + before := l.starts |
| + runSpecialistAfterCoordinator(t, s) |
| + if l.starts != before { |
| + t.Fatal("transient recovery restarted provider") |
| + } |
| + // Other offers must progress while the original report remains retryable. |
| + next := c |
| + next.Turn.ID = "other" |
| + next.Scope.Job++ |
| + next.Handle.Attempt++ |
| + next.Admission.Dispatch.Action++ |
| + next.Admission.Scope = next.Scope |
| + next.Admission.Handle = next.Handle |
| + base.c = next |
| + base.polled = false |
| + // Fail only the original report; the other coordinator can complete. |
| + s.API = &selectiveCoordinatorRetryAPI{api: api, id: c.Turn.ID} |
| + if err := s.Poll(context.Background()); err != nil && !errors.Is(err, ErrTransient) { |
| + t.Fatal(err) |
| + } |
| + if l.starts != before+1 { |
| + t.Fatal("transient refusal blocked other coordinator", fmt.Sprint(l.starts)) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type selectiveCoordinatorRetryAPI struct { |
| + api *coordinatorRetryAPI |
| + id string |
| +} |
| + |
| +func (a *selectiveCoordinatorRetryAPI) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| + if q.TurnID == a.id || q.Claim != nil && q.Claim.Turn.ID == a.id { |
| + return a.api.CoordinatorCall(ctx, op, q, out) |
| + } |
| + return a.api.coordinatorAPIStub.CoordinatorCall(ctx, op, q, out) |
| +} |
| + |
| +func TestCoordinatorRetryCadence(t *testing.T) { |
| + s, base, _, c := coordinatorServiceFixture(t) |
| + api := &coordinatorRetryAPI{coordinatorAPIStub: base, operation: "recover", failure: &RefusalError{Status: 401}, queued: true} |
| + s.API = api |
| + now := time.Now() |
| + s.now = func() time.Time { return now } |
| + mustJournal(t, s.Journal.saveState(context.Background(), "coordinator-claim", c.Turn.ID, runnerproto.CoordinatorRequest{TurnID: c.Turn.ID, Revision: c.Turn.Revision})) |
| + for attempt := 1; attempt <= 8; attempt++ { |
| + mustJournal(t, s.Recover(context.Background())) |
| + if api.calls != attempt { |
| + t.Fatal("retry missing", api.calls, attempt) |
| + } |
| + delay := s.retry[c.Turn.ID].after.Sub(now) |
| + if delay < time.Second || delay > leaseRenewInterval { |
| + t.Fatal("unbounded retry delay", delay) |
| + } |
| + for poll := 0; poll < 3; poll++ { |
| + mustJournal(t, s.Recover(context.Background())) |
| + mustJournal(t, s.Poll(context.Background())) |
| + } |
| + if api.calls != attempt || base.polled && base.delivery { |
| + t.Fatal("retry churn", api.calls) |
| + } |
| + now = now.Add(delay) |
| + } |
| + reopenCoordinator(t, s, &coordinatorFixtureLauncher{}) |
| + s.retry = nil |
| + mustJournal(t, s.Recover(context.Background())) |
| + if api.calls != 9 { |
| + t.Fatal("restart did not retry") |
| + } |
| +} |
| +func TestCoordinatorLegacyRefusalRetries(t *testing.T) { |
| + for _, op := range []string{"recover", "containment", "delivery"} { |
| + t.Run(op, func(t *testing.T) { |
| + s, base, l, c := coordinatorServiceFixture(t) |
| + state := coordinatorState{Claim: c, Finished: true, Refused: true, RefusalOperation: op, RefusalStatus: 403} |
| + if op == "recover" { |
| + state.Claim = runnerproto.CoordinatorClaim{Turn: c.Turn} |
| + } |
| + api := &coordinatorRetryAPI{coordinatorAPIStub: base, operation: op, queued: true} |
| + s.API = api |
| + mustJournal(t, s.Journal.saveState(context.Background(), "coordinator", c.Turn.ID, state)) |
| + reopenCoordinator(t, s, l) |
| + mustJournal(t, s.Recover(context.Background())) |
| + if op != "delivery" && api.calls != 1 { |
| + t.Fatal("legacy refusal not retried", api.calls) |
| + } |
| + if l.starts != 0 { |
| + t.Fatal("legacy refusal resent prompt") |
| + } |
| + if op == "recover" { |
| + base.polled = false |
| + mustJournal(t, s.Poll(context.Background())) |
| + if l.starts != 1 { |
| + t.Fatal("queued legacy refusal wedged claim") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| +func TestCoordinatorExpiredDeliveryStillReportsContainment(t *testing.T) { |
| + s, base, _, c := coordinatorServiceFixture(t) |
| + api := &coordinatorRetryAPI{coordinatorAPIStub: base, operation: "delivery", failure: &RefusalError{Status: 403}} |
| + s.API = api |
| + if err := s.RunTurn(context.Background(), c); !errors.Is(err, ErrTransient) { |
| + t.Fatal(err) |
| + } |
| + if api.contained != 0 { |
| + t.Fatal("transient delivery lost authority before expiry") |
| + } |
| + s.now = func() time.Time { return c.AttemptDeadline.Add(time.Second) } |
| + mustJournal(t, s.Recover(context.Background())) |
| + var states []coordinatorState |
| + mustJournal(t, s.Journal.readStates(context.Background(), "coordinator", &states)) |
| + if states[0].Finished { |
| + t.Fatal("transient delivery finalised at expiry") |
| + } |
| + if states[0].Containment == nil || api.contained != 1 { |
| + t.Fatal("expired delivery lost containment retry", api.contained) |
| + } |
| + // The instance can now respond with a committed fence; only that permits retirement. |
| + api.failure = &RefusalError{Status: 409, Reason: "coordinator.fenced"} |
| + s.retry = nil |
| + mustJournal(t, s.Recover(context.Background())) |
| + states = nil |
| + mustJournal(t, s.Journal.readStates(context.Background(), "coordinator", &states)) |
| + if !states[0].Finished || !states[0].Refused { |
| + t.Fatal("fenced delivery not finalised") |
| + } |
| +} |
| + |
| +func TestCoordinatorPendingClaimPollNeverDispatches(t *testing.T) { |
| + s, _, l, c := coordinatorServiceFixture(t) |
| + mustJournal(t, s.Journal.saveState(context.Background(), "coordinator-claim", c.Turn.ID, runnerproto.CoordinatorRequest{TurnID: c.Turn.ID, Revision: c.Turn.Revision})) |
| + mustJournal(t, s.Poll(context.Background())) |
| + if l.starts != 0 { |
| + t.Fatal("unrecovered claim intent redispatched") |
| + } |
| +} |
diff --git a/internal/runner/coordinator_service.go b/internal/runner/coordinator_service.go| index 97bd0200..72514b0e 100644 |
| --- a/internal/runner/coordinator_service.go |
| +++ b/internal/runner/coordinator_service.go |
| @@ -19,6 +19,8 @@ type CoordinatorAPI interface { |
| } |
| type CoordinatorService struct { |
| release func() error |
| + retry map[string]coordinatorRetry |
| + now func() time.Time |
| RecoverFiles func(context.Context, runnerproto.CoordinatorClaim) error |
| Journal *Journal |
| API CoordinatorAPI |
| @@ -34,6 +36,8 @@ type coordinatorState struct { |
| Refused bool |
| RefusalOperation string |
| RefusalStatus int |
| + RefusalCode string |
| + DeliveryRefusal *RefusalError |
| Containment *runnerproto.ContainmentProof |
| } |
| @@ -43,7 +47,16 @@ func coordinatorRequest(c runnerproto.CoordinatorClaim) runnerproto.CoordinatorR |
| func (s *CoordinatorService) call(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| q.Version = 2 |
| q.Capabilities = []string{runnerproto.CoordinatorCapability} |
| - return s.API.CoordinatorCall(ctx, op, q, out) |
| + err := s.API.CoordinatorCall(ctx, op, q, out) |
| + if err == nil || ctx.Err() != nil { |
| + return err |
| + } |
| + var refusal *RefusalError |
| + if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| + return refusal |
| + } |
| + // Remote contract/authentication failures cannot kill unrelated runner work. |
| + return ErrTransient |
| } |
| func (s *CoordinatorService) Poll(ctx context.Context) error { |
| if s.Journal == nil || s.API == nil || s.OpenLaunch == nil || s.Contain == nil { |
| @@ -57,8 +70,11 @@ func (s *CoordinatorService) Poll(ctx context.Context) error { |
| return err |
| } |
| for _, turn := range turns { |
| + if !s.retryDue(turn.ID) { |
| + continue |
| + } |
| var saved int |
| - if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", turn.ID).Scan(&saved); err != nil { |
| + if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind IN ('coordinator','coordinator-claim') AND state_key=?", turn.ID).Scan(&saved); err != nil { |
| return err |
| } |
| if saved != 0 { |
| @@ -70,9 +86,17 @@ func (s *CoordinatorService) Poll(ctx context.Context) error { |
| } |
| var c runnerproto.CoordinatorClaim |
| if err := s.call(ctx, "claim", q, &c); err != nil { |
| - return err |
| + r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: turn}} |
| + if err = s.refusedCall(ctx, &r, "claim", err); err != nil { |
| + return err |
| + } |
| + continue |
| } |
| if err := s.RunTurn(ctx, c); err != nil { |
| + if errors.Is(err, ErrTransient) { |
| + s.deferRetry(c.Turn.ID) |
| + continue |
| + } |
| return err |
| } |
| } |
diff --git a/internal/runner/http.go b/internal/runner/http.go| index 6f2b890a..1aa91e71 100644 |
| --- a/internal/runner/http.go |
| +++ b/internal/runner/http.go |
| @@ -49,7 +49,7 @@ func (c *HTTPInstance) post(ctx context.Context, op string, body any, token stri |
| } |
| defer response.Body.Close() |
| if response.StatusCode != http.StatusOK { |
| - if response.StatusCode == 403 || response.StatusCode == 401 || response.StatusCode == 409 || response.StatusCode == 422 { |
| + if response.StatusCode == 403 || response.StatusCode == 401 || response.StatusCode == 409 || response.StatusCode == 422 || strings.HasPrefix(op, "coordinator/") && response.StatusCode >= 400 && response.StatusCode < 500 { |
| var body runnerproto.ErrorResponse |
| _ = runnerproto.DecodeLimit(io.LimitReader(response.Body, 4096), &body, 4096) |
| return &RefusalError{Reason: refusalReason(body.Error), Status: response.StatusCode, Claim: op == "claim"} |
diff --git a/internal/runner/service.go b/internal/runner/service.go| index efbc062a..28cee5d2 100644 |
| --- a/internal/runner/service.go |
| +++ b/internal/runner/service.go |
| @@ -29,7 +29,6 @@ func (s *Service) Run(ctx context.Context) error { |
| return provider.ErrContract |
| } |
| needsRecovery := true |
| - coordinatorRecovery := true |
| claimRefusals := 0 |
| for { |
| if ctx.Err() != nil { |
| @@ -51,9 +50,8 @@ func (s *Service) Run(ctx context.Context) error { |
| needsRecovery = false |
| } |
| var coordinatorErr error |
| - if s.Coordinator != nil && coordinatorRecovery { |
| + if s.Coordinator != nil { |
| coordinatorErr = s.Coordinator.Recover(ctx) |
| - coordinatorRecovery = coordinatorErr != nil |
| if fatalServiceError(coordinatorErr) || errors.Is(coordinatorErr, context.Canceled) { |
| return coordinatorErr |
| } |
| @@ -70,10 +68,9 @@ func (s *Service) Run(ctx context.Context) error { |
| assignments = nil |
| } |
| pollErr := err |
| - if s.Coordinator != nil && !coordinatorRecovery { |
| + if s.Coordinator != nil && coordinatorErr == nil { |
| coordinatorErr = s.Coordinator.Poll(ctx) |
| if coordinatorErr != nil { |
| - coordinatorRecovery = true |
| s.report("runner.poll_retry") |
| } |
| } |
diff --git a/internal/runnerproto/coordinator_handler.go b/internal/runnerproto/coordinator_handler.go| index ebe2a932..98229834 100644 |
| --- a/internal/runnerproto/coordinator_handler.go |
| +++ b/internal/runnerproto/coordinator_handler.go |
| @@ -1,6 +1,7 @@ |
| package runnerproto |
| import ( |
| + "errors" |
| "net/http" |
| "slices" |
| ) |
| @@ -63,6 +64,11 @@ func (s *Handler) coordinatorRunnerOperation(op string) http.HandlerFunc { |
| } |
| } |
| if err != nil { |
| + var refusal *RefusalError |
| + if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| + s.JSON(w, refusal.Status, ErrorResponse{Version: 2, Error: refusal.Reason}) |
| + return |
| + } |
| s.Failure(w, err) |
| return |
| } |
diff --git a/internal/runnerproto/retry.go b/internal/runnerproto/retry.go| index b7292bf1..8cf0c75e 100644 |
| --- a/internal/runnerproto/retry.go |
| +++ b/internal/runnerproto/retry.go |
| @@ -43,13 +43,22 @@ func RemoteError(err error) error { |
| return err |
| } |
| -// RefusalError is a final instance decision, safe to persist without response text. |
| +// RefusalError preserves a coded instance response without response prose. |
| type RefusalError struct { |
| Reason string |
| Status int |
| Claim bool |
| } |
| +// CoordinatorDefinitive requires an explicit fence code, never just a status. |
| +func (e *RefusalError) CoordinatorDefinitive() bool { |
| + switch e.Reason { |
| + case "coordinator.fenced", "coordinator.reset", "coordinator.superseded", "coordinator.revoked": |
| + return e.Status >= 400 && e.Status < 500 |
| + } |
| + return false |
| +} |
| + |
| func (e *RefusalError) Error() string { return e.Reason } |
| func (e *RefusalError) Unwrap() error { |
| if e.Status == 401 || e.Status == 403 { |
| @@ -62,7 +71,7 @@ func (e *RefusalError) Unwrap() error { |
| } |
| func RefusalReason(key string) string { |
| switch key { |
| - case "runner.budget", "runner.quota", "runner.evidence", "runner.containment", "runner.replay", "runner.uncertain", "form.invalid", "form.conflict", "form.forbidden": |
| + case "coordinator.fenced", "coordinator.reset", "coordinator.superseded", "coordinator.revoked", "runner.budget", "runner.quota", "runner.evidence", "runner.containment", "runner.replay", "runner.uncertain", "form.invalid", "form.conflict", "form.forbidden": |
| return key |
| default: |
| return "form.invalid" |