Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6016: feat(task): retry exact Codex capacity failures (#6747)

sample_project_js8fda4f22d542
diff --git a/.env.example b/.env.example
index 4bbf6719f3..4aa003a3ca 100644
--- a/.env.example
+++ b/.env.example
@@ -23,6 +23,12 @@ DATABASE_URL=postgres://multica:multica@localhost:5432/multica?sslmode=disable
# "production" by default. Local dev can leave it unset.
# See SELF_HOSTING.md for the full login setup.
APP_ENV=
+# Additional immediate retries only when the persisted raw Codex error is
+# exactly "Selected model is at capacity. Please try a different model."
+# Set to 0 to disable this dedicated retry policy. Maximum 20; a negative,
+# malformed or larger value stops the server at startup rather than falling
+# back to the default, because each retry launches another runtime.
+MULTICA_CODEX_CAPACITY_RETRY_COUNT=6
# Optional local/testing shortcut. Empty by default, so there is no fixed
# verification code. Without RESEND_API_KEY, generated codes print to stdout.
# If you need deterministic local automation, set a 6-digit value such as
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index b473389f90..6b4254f084 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -46,6 +46,12 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
Kubernetes で shutdown hold を設定する場合、`terminationGracePeriodSeconds` は hold と実際のシャットダウンにかかる時間の合計より大きくしてください。
+### タスクのリトライ
+
+| 変数 | デフォルト | 説明 |
+|---|---|---|
+| `MULTICA_CODEX_CAPACITY_RETRY_COUNT` | `6` | タスクに保存された Codex の生エラーが `Selected model is at capacity. Please try a different model.` と完全に一致する場合の、追加の即時リトライ回数。デフォルトでは合計 7 回まで実行します。`0` にするとこの専用ポリシーは無効になります。上限は `20` です。負数・不正な値・上限を超える値を指定した場合は、デフォルトへフォールバックせず起動時にサーバーを停止します。リトライのたびにタスク行の書き込み、ランタイムの起動、プロバイダーへの再呼び出しが発生するためです。その他の容量不足やレート制限のエラーは、このポリシーではリトライされません。 |
+
## 公開アドレスとブラウザアクセス
| 変数 | デフォルト | 説明 |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index b44323a49f..e5143d880f 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -46,6 +46,12 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
Kubernetes에서 shutdown hold를 설정하면 `terminationGracePeriodSeconds`가 hold와 실제 종료에 필요한 시간의 합보다 커야 합니다.
+### 작업 재시도
+
+| 변수 | 기본값 | 설명 |
+|---|---|---|
+| `MULTICA_CODEX_CAPACITY_RETRY_COUNT` | `6` | 작업에 저장된 Codex 원본 오류가 `Selected model is at capacity. Please try a different model.`와 정확히 일치할 때 추가로 즉시 재시도하는 횟수입니다. 기본값은 총 7회 실행을 허용하며, `0`은 이 전용 정책을 비활성화합니다. 최댓값은 `20`이며, 음수·잘못된 형식·최댓값을 초과하는 값은 기본값으로 되돌리지 않고 서버 시작을 중단시킵니다. 재시도마다 작업 행을 기록하고 런타임을 실행하며 공급자를 다시 호출하기 때문입니다. 그 밖의 용량 또는 속도 제한 오류는 이 정책으로 재시도하지 않습니다. |
+
## 공개 주소와 브라우저 접근
| 변수 | 기본값 | 설명 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index bedc63dcd8..7f2fb20c2d 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -46,6 +46,12 @@ You also need to pick an email service, otherwise verification codes and invitat
When setting a shutdown hold on Kubernetes, `terminationGracePeriodSeconds` must exceed the hold plus the time the actual shutdown needs.
+### Task retries
+
+| Variable | Default | Description |
+|---|---|---|
+| `MULTICA_CODEX_CAPACITY_RETRY_COUNT` | `6` | Additional immediate retries when a task's persisted raw Codex error is exactly `Selected model is at capacity. Please try a different model.` The default allows seven total executions; `0` disables this dedicated policy. Maximum `20` — a negative, malformed or larger value stops the server at startup instead of falling back to the default, because every retry writes a task row, launches a runtime and calls the provider again. Other capacity or rate-limit errors are not retried by this policy. |
+
## Public URLs and browser access
| Variable | Default | Description |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 8fc8992f6d..3e496bb80b 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -46,6 +46,12 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
在 Kubernetes 中设置 shutdown hold 时,`terminationGracePeriodSeconds` 要大于 hold 与实际退出所需时间之和。
+### 任务重试
+
+| 变量 | 默认值 | 说明 |
+|---|---|---|
+| `MULTICA_CODEX_CAPACITY_RETRY_COUNT` | `6` | 当任务持久化的 Codex 原始错误与 `Selected model is at capacity. Please try a different model.` 完全一致时,立即追加的重试次数。默认值允许总计执行 7 次;`0` 关闭此专用策略。上限为 `20`:负数、格式错误或超过上限的值会让服务在启动时直接失败,而不是回退到默认值,因为每次重试都会写入一条任务记录、拉起一个运行时并再次调用模型提供方。其他容量或限流错误不会被此策略重试。 |
+
## 对外地址与浏览器访问
| 变量 | 默认值 | 说明 |
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index 34124fd6bb..a01d512e52 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -11,6 +11,7 @@ data:
MULTICA_DATABASE_CONNECT_TIMEOUT: {{ .Values.backend.config.databaseConnectTimeout | quote }}
APP_ENV: {{ .Values.backend.config.appEnv | quote }}
MULTICA_APP_URL: {{ .Values.backend.config.appUrl | quote }}
+ MULTICA_CODEX_CAPACITY_RETRY_COUNT: {{ .Values.backend.config.codexCapacityRetryCount | quote }}
FRONTEND_ORIGIN: {{ .Values.backend.config.frontendOrigin | quote }}
CORS_ALLOWED_ORIGINS: {{ .Values.backend.config.corsAllowedOrigins | quote }}
COOKIE_DOMAIN: {{ .Values.backend.config.cookieDomain | quote }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index 2b643111b3..15cede9e23 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -123,6 +123,7 @@ backend:
databaseConnectTimeout: 5s
appEnv: production
appUrl: http://multica.dev.lan
+ codexCapacityRetryCount: 6
frontendOrigin: http://multica.dev.lan
corsAllowedOrigins: ""
cookieDomain: ""
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 0a4d06ab7e..367566cb70 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -94,6 +94,7 @@ services:
CLOUDFRONT_PRIVATE_KEY: ${CLOUDFRONT_PRIVATE_KEY:-}
COOKIE_DOMAIN: ${COOKIE_DOMAIN:-}
APP_ENV: ${APP_ENV:-production}
+ MULTICA_CODEX_CAPACITY_RETRY_COUNT: ${MULTICA_CODEX_CAPACITY_RETRY_COUNT:-6}
MULTICA_DEV_VERIFICATION_CODE: ${MULTICA_DEV_VERIFICATION_CODE:-}
MULTICA_APP_URL: ${MULTICA_APP_URL:-http://localhost:3000}
MULTICA_DATABASE_STARTUP_TIMEOUT: ${MULTICA_DATABASE_STARTUP_TIMEOUT:-3m}
diff --git a/docs/superpowers/plans/2026-08-11-codex-capacity-auto-retry.md b/docs/superpowers/plans/2026-08-11-codex-capacity-auto-retry.md
new file mode 100644
index 0000000000..2e17cc91d6
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-11-codex-capacity-auto-retry.md
@@ -0,0 +1,410 @@
+# Codex Capacity Auto-Retry Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Automatically and immediately retry only the exact Codex selected-model capacity error, with six additional retries by default and deployment-level configuration.
+
+**Architecture:** Keep classification and retry eligibility separate. `pkg/taskfailure` recognizes and normalizes the exact raw error for reporting, while `TaskService` owns a dedicated raw-error retry policy that reuses the atomic `FailTask -> CreateRetryTask` flow and persists `retry_count + 1` as the child ceiling. The API composition boundary parses `MULTICA_CODEX_CAPACITY_RETRY_COUNT` and injects it into the service; deployment manifests only expose the value.
+
+**Tech Stack:** Go 1.26, pgx/sqlc task persistence, Go testing, Docker Compose, Helm, Fumadocs MDX.
+
+---
+
+## File Map
+
+- `server/pkg/taskfailure/classify.go`: exact Codex capacity witness and legacy-daemon normalization.
+- `server/pkg/taskfailure/classify_test.go`: strict equality and normalization regression tests.
+- `server/internal/service/task.go`: capacity retry budget, eligibility, immediate scheduling, and sweeper parity.
+- `server/internal/service/task_complete_race_test.go`: pure retry-policy matrix and generic-policy non-regression.
+- `server/internal/service/retry_deferred_test.go`: database-backed `FailTask` child creation assertions.
+- `server/internal/handler/handler.go`: handler config field and `TaskService` injection.
+- `server/cmd/server/router.go`: deployment environment parsing and handler configuration.
+- `server/cmd/server/codex_capacity_retry_test.go`: environment parser tests.
+- `.env.example`: operator-facing default.
+- `docker-compose.selfhost.yml`: backend environment forwarding.
+- `deploy/helm/multica/values.yaml`: Helm backend configuration default.
+- `deploy/helm/multica/templates/configmap.yaml`: Helm environment rendering.
+- `apps/docs/content/docs/environment-variables{,.zh,.ja,.ko}.mdx`: localized API-server configuration reference.
+
+### Task 1: Make The Capacity Witness Strict
+
+**Files:**
+- Modify: `server/pkg/taskfailure/classify_test.go`
+- Modify: `server/pkg/taskfailure/classify.go`
+
+- [ ] **Step 1: Add failing strict-match tests**
+
+Extend the classifier and normalization tables with exact and near-match cases:
+
+```go
+const codexCapacityError = "Selected model is at capacity. Please try a different model."
+
+{"codex selected model at capacity", codexCapacityError, ReasonAgentProviderCapacityOrRateLimit},
+{"codex capacity uppercase stays model unavailable", strings.ToUpper(codexCapacityError), ReasonAgentModelNotFoundOrUnavailable},
+{"codex capacity padded stays model unavailable", " " + codexCapacityError, ReasonAgentModelNotFoundOrUnavailable},
+{"codex capacity suffix stays model unavailable", codexCapacityError + " Contact support.", ReasonAgentModelNotFoundOrUnavailable},
+```
+
+For `NormalizeDaemonReason`, assert that only the exact raw error upgrades legacy
+`model_not_found_or_unavailable`, `unknown`, and coarse `agent_error` labels.
+
+- [ ] **Step 2: Run the focused tests and confirm RED**
+
+```powershell
+Set-Location server
+go test ./pkg/taskfailure -run 'Test(ClassifyRules|NormalizeDaemonReason)$' -count=1
+```
+
+Expected: FAIL because the current predicate trims and folds case.
+
+- [ ] **Step 3: Implement exact recognition**
+
+```go
+const codexSelectedModelCapacityError = "Selected model is at capacity. Please try a different model."
+
+func IsCodexSelectedModelCapacityError(rawError string) bool {
+ return rawError == codexSelectedModelCapacityError
+}
+```
+
+Call this predicate from `Classify(rawError)` before the broader selected-model
+rule and from `NormalizeDaemonReason`. Do not compare lowercased or trimmed input
+for this witness.
+
+- [ ] **Step 4: Run the focused tests and confirm GREEN**
+
+Run the command from Step 2. Expected: PASS.
+
+- [ ] **Step 5: Commit the classifier increment**
+
+```powershell
+git commit --only -m "fix(taskfailure): recognize exact Codex capacity error" -- server/pkg/taskfailure/classify.go server/pkg/taskfailure/classify_test.go
+```
+
+### Task 2: Add The Dedicated Capacity Retry Policy
+
+**Files:**
+- Modify: `server/internal/service/task_complete_race_test.go`
+- Modify: `server/internal/service/retry_deferred_test.go`
+- Modify: `server/internal/service/task.go`
+
+- [ ] **Step 1: Rewrite pure policy tests to the approved budget semantics**
+
+Pass an explicit capacity count into the retry helpers. Cover attempts 1 through
+7, generic `max_attempts=1`, count zero, strict near-matches, generic rate
+limits, autopilot exclusion, and missing issue/chat links. Core assertions:
+
+```go
+const capacityErr = "Selected model is at capacity. Please try a different model."
+const capacityRetryCount int32 = 6
+
+if !retryEligible(reason, capacityErr, mkTask(1, 1), capacityRetryCount) {
+ t.Fatal("capacity policy must override generic max_attempts")
+}
+if retryEligible(reason, capacityErr, mkTask(7, 1), capacityRetryCount) {
+ t.Fatal("attempt 7 must exhaust six additional retries")
+}
+if retryEligible(reason, capacityErr, mkTask(1, 2), 0) {
+ t.Fatal("zero capacity retries must disable the special policy")
+}
+if got := retryAttemptCeiling(reason, capacityErr, 1, capacityRetryCount); got != 7 {
+ t.Fatalf("ceiling = %d, want 7", got)
+}
+if got := retryDelayForAttempt(reason, capacityErr, 6); got != 0 {
+ t.Fatalf("capacity delay = %s, want immediate", got)
+}
+```
+
+Update every generic retry test to pass empty raw error and zero capacity count
+so provider-network and timeout behavior remain independently covered.
+
+- [ ] **Step 2: Add a database-backed failing `FailTask` test**
+
+Add `TestFailTaskCodexCapacityBudget` beside the provider-network test. Create a
+running parent with `attempt=1/max_attempts=1`, configure the service with count
+six, call `FailTask` with the exact raw error and a legacy model-unavailable
+reason, and assert one child with:
+
+```go
+wantAttempt := int32(2)
+wantMaxAttempts := int32(7)
+wantStatus := "queued"
+wantFireAtValid := false
+wantForceFreshSession := false
+```
+
+Table cases also assert no child for count zero, attempt seven, and a generic
+429 error.
+
+- [ ] **Step 3: Run focused service tests and confirm RED**
+
+```powershell
+Set-Location server
+go test ./internal/service -run 'Test(ProviderNetworkRetrySchedule|TaskFailureClassifiers|CodexCapacityFailureRetries|FailTaskCodexCapacityBudget)$' -count=1
+```
+
+Expected: compile failure from the helper signatures or assertion failures
+because capacity still uses the generic budget.
+
+- [ ] **Step 4: Implement the minimal service policy**
+
+```go
+const DefaultCodexCapacityRetryCount int32 = 6
+
+// Add to TaskService.
+CodexCapacityRetryCount int32
+
+func retryCandidate(reason, rawError string, capacityRetryCount int32) bool {
+ if taskfailure.IsCodexSelectedModelCapacityError(rawError) {
+ return capacityRetryCount > 0
+ }
+ return retryableReasons[reason]
+}
+
+func retryAttemptCeiling(reason, rawError string, taskMaxAttempts, capacityRetryCount int32) int32 {
+ if taskfailure.IsCodexSelectedModelCapacityError(rawError) && capacityRetryCount > 0 {
+ return capacityRetryCount + 1
+ }
+ if taskMaxAttempts <= 1 {
+ return taskMaxAttempts
+ }
+ if reason == string(taskfailure.ReasonAgentProviderNetwork) && taskMaxAttempts < providerNetworkMaxAttempts {
+ return providerNetworkMaxAttempts
+ }
+ return taskMaxAttempts
+}
+
+func retryDelayForAttempt(reason, rawError string, failedAttempt int32) time.Duration {
+ if taskfailure.IsCodexSelectedModelCapacityError(rawError) {
+ return 0
+ }
+ if reason == string(taskfailure.ReasonAgentProviderNetwork) &&
+ failedAttempt >= providerNetworkMaxAttempts-1 {
+ return providerNetworkFinalRetryWait
+ }
+ return 0
+}
+
+func retryEligible(reason, rawError string, task db.AgentTaskQueue, capacityRetryCount int32) bool {
+ return retryCandidate(reason, rawError, capacityRetryCount) &&
+ task.Attempt < retryAttemptCeiling(reason, rawError, task.MaxAttempts, capacityRetryCount) &&
+ !task.AutopilotRunID.Valid &&
+ (task.IssueID.Valid || task.ChatSessionID.Valid)
+}
+```
+
+In `FailTask`, use `errMsg` and the injected setting for candidate, eligibility,
+ceiling, and delay decisions. In
+`MaybeRetryFailedTask`, use `parent.Error.String` and the same setting. Leave
+capacity out of `retryableReasons`.
+
+- [ ] **Step 5: Format and run focused tests GREEN**
+
+```powershell
+gofmt -w server/internal/service/task.go server/internal/service/task_complete_race_test.go server/internal/service/retry_deferred_test.go
+Set-Location server
+go test ./internal/service -run 'Test(ProviderNetworkRetrySchedule|TaskFailureClassifiers|CodexCapacityFailureRetries|FailTaskProviderNetworkBudget|FailTaskCodexCapacityBudget)$' -count=1
+```
+
+Expected: PASS.
+
+- [ ] **Step 6: Commit the retry-policy increment**
+
+```powershell
+git commit --only -m "feat(task): retry exact Codex capacity failures" -- server/internal/service/task.go server/internal/service/task_complete_race_test.go server/internal/service/retry_deferred_test.go
+```
+
+### Task 3: Parse And Inject The Deployment Setting
+
+**Files:**
+- Create: `server/cmd/server/codex_capacity_retry_test.go`
+- Modify: `server/cmd/server/router.go`
+- Modify: `server/internal/handler/handler.go`
+
+- [ ] **Step 1: Write failing environment parser tests**
+
+```go
+func TestCodexCapacityRetryCountFromEnv(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ want int32
+ }{
+ {"unset uses default", "", 6},
+ {"zero disables", "0", 0},
+ {"positive count", "3", 3},
+ {"surrounding whitespace", " 3 ", 3},
+ {"negative uses default", "-1", 6},
+ {"malformed uses default", "six", 6},
+ {"maximum accepted", "2147483646", 2147483646},
+ {"overflowing total uses default", "2147483647", 6},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("MULTICA_CODEX_CAPACITY_RETRY_COUNT", tc.raw)
+ if got := codexCapacityRetryCountFromEnv(); got != tc.want {
+ t.Fatalf("codexCapacityRetryCountFromEnv() = %d, want %d", got, tc.want)
+ }
+ })
+ }
+}
+```
+
+- [ ] **Step 2: Run the parser test and confirm RED**
+
+```powershell
+Set-Location server
+go test ./cmd/server -run TestCodexCapacityRetryCountFromEnv -count=1
+```
+
+Expected: compile failure because the parser does not exist.
+
+- [ ] **Step 3: Implement parsing and injection**
+
+Add a domain-specific parser in `router.go` that trims the value, uses
+`strconv.ParseInt(raw, 10, 32)`, accepts `0..2147483646`, and logs a warning
+before returning `service.DefaultCodexCapacityRetryCount` for invalid input.
+
+Add to `handler.Config`:
+
+```go
+CodexCapacityRetryCount int32
+```
+
+Populate it in `NewRouterWithOptions` and inject it in `handler.New`:
+
+```go
+CodexCapacityRetryCount: codexCapacityRetryCountFromEnv(),
+taskSvc.CodexCapacityRetryCount = cfg.CodexCapacityRetryCount
+```
+
+- [ ] **Step 4: Format and run parser plus service tests GREEN**
+
+```powershell
+gofmt -w server/cmd/server/router.go server/cmd/server/codex_capacity_retry_test.go server/internal/handler/handler.go
+Set-Location server
+go test ./cmd/server -run TestCodexCapacityRetryCountFromEnv -count=1
+go test ./internal/service -run 'Test(CodexCapacityFailureRetries|FailTaskCodexCapacityBudget)$' -count=1
+```
+
+Expected: PASS.
+
+- [ ] **Step 5: Commit the configuration increment**
+
+```powershell
+git commit --only -m "feat(server): configure Codex capacity retries" -- server/cmd/server/router.go server/cmd/server/codex_capacity_retry_test.go server/internal/handler/handler.go
+```
+
+### Task 4: Expose The Deployment Configuration
+
+**Files:**
+- Modify: `.env.example`
+- Modify: `docker-compose.selfhost.yml`
+- Modify: `deploy/helm/multica/values.yaml`
+- Modify: `deploy/helm/multica/templates/configmap.yaml`
+- Modify: `apps/docs/content/docs/environment-variables.mdx`
+- Modify: `apps/docs/content/docs/environment-variables.zh.mdx`
+- Modify: `apps/docs/content/docs/environment-variables.ja.mdx`
+- Modify: `apps/docs/content/docs/environment-variables.ko.mdx`
+
+- [ ] **Step 1: Run manifest assertions before editing**
+
+```powershell
+docker compose -f docker-compose.selfhost.yml config | Select-String 'MULTICA_CODEX_CAPACITY_RETRY_COUNT: "6"'
+helm template multica deploy/helm/multica | Select-String 'MULTICA_CODEX_CAPACITY_RETRY_COUNT: "6"'
+```
+
+Expected: no match.
+
+- [ ] **Step 2: Wire defaults through deployment surfaces**
+
+```dotenv
+MULTICA_CODEX_CAPACITY_RETRY_COUNT=6
+```
+
+```yaml
+MULTICA_CODEX_CAPACITY_RETRY_COUNT: ${MULTICA_CODEX_CAPACITY_RETRY_COUNT:-6}
+```
+
+```yaml
+backend:
+ config:
+ codexCapacityRetryCount: 6
+```
+
+```yaml
+MULTICA_CODEX_CAPACITY_RETRY_COUNT: {{ .Values.backend.config.codexCapacityRetryCount | quote }}
+```
+
+- [ ] **Step 3: Document server-side semantics in every locale**
+
+Add the variable to an API-server task retry section, not the daemon table. Each
+description states that the default is six additional immediate retries, zero
+disables the exact-error policy, and other capacity/rate-limit errors are not
+retried.
+
+- [ ] **Step 4: Render and validate manifests GREEN**
+
+```powershell
+docker compose -f docker-compose.selfhost.yml config | Select-String 'MULTICA_CODEX_CAPACITY_RETRY_COUNT: "6"'
+helm template multica deploy/helm/multica | Select-String 'MULTICA_CODEX_CAPACITY_RETRY_COUNT: "6"'
+git diff --check
+```
+
+Expected: both render checks match and `git diff --check` reports no errors.
+
+- [ ] **Step 5: Commit deployment and documentation**
+
+```powershell
+git commit --only -m "docs: expose Codex capacity retry setting" -- .env.example docker-compose.selfhost.yml deploy/helm/multica/values.yaml deploy/helm/multica/templates/configmap.yaml apps/docs/content/docs/environment-variables.mdx apps/docs/content/docs/environment-variables.zh.mdx apps/docs/content/docs/environment-variables.ja.mdx apps/docs/content/docs/environment-variables.ko.mdx
+```
+
+### Task 5: Final Verification And Scope Review
+
+**Files:**
+- Verify all files listed above.
+
+- [ ] **Step 1: Run focused backend suites**
+
+```powershell
+Set-Location server
+go test ./pkg/taskfailure -count=1
+go test ./cmd/server -count=1
+go test ./internal/service -count=1
+```
+
+Expected: PASS for every package.
+
+- [ ] **Step 2: Run broader Go verification**
+
+```powershell
+Set-Location server
+go test ./... -count=1
+```
+
+Expected: PASS. If the repository-wide suite exceeds the execution window,
+record the timeout separately from focused passing evidence.
+
+- [ ] **Step 3: Review diff and generated configuration**
+
+```powershell
+git diff --check
+git status --short
+docker compose -f docker-compose.selfhost.yml config
+helm template multica deploy/helm/multica
+```
+
+Expected: no whitespace errors, the environment variable appears in both
+deployment outputs, and unrelated pre-existing worktree changes remain intact.
+
+- [ ] **Step 4: Run GitNexus change detection**
+
+Run `detect_changes({scope: "compare", base_ref: "main"})`, review every changed
+symbol and affected process, and investigate any HIGH or CRITICAL result before
+completion.
+
+- [ ] **Step 5: Report completed behavior**
+
+Report the strict matching rule, default/configured budget, immediate retry
+behavior, COM-44 evidence, deployment surfaces, exact test results, and any
+residual verification timeout.
diff --git a/docs/superpowers/specs/2026-08-11-codex-capacity-auto-retry-design.md b/docs/superpowers/specs/2026-08-11-codex-capacity-auto-retry-design.md
new file mode 100644
index 0000000000..1d53789d3d
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-11-codex-capacity-auto-retry-design.md
@@ -0,0 +1,168 @@
+# Codex Capacity Auto-Retry Design
+
+Date: 2026-08-11
+
+## Goal
+
+Automatically retry a Multica Codex task when, and only when, its raw error is
+exactly:
+
+```text
+Selected model is at capacity. Please try a different model.
+```
+
+This removes the manual retry step for transient Codex model-capacity failures
+while leaving all other failure behavior unchanged.
+
+## Production Evidence
+
+COM-44 on `multica.fabu.ai` currently demonstrates the gap. Its 43 recorded
+runs include 15 failures with the exact raw error above. The latest inspected
+failure (`b0b4a98c-01e6-45a7-90ab-d7da6fa800bd`, completed
+2026-08-11T01:31:18Z) persisted the legacy reason
+`agent_error.model_not_found_or_unavailable` with `attempt=1` and
+`max_attempts=2`. Subsequent executions were manual reruns rather than automatic
+capacity retries.
+
+## Configuration
+
+The API server reads the deployment-level environment variable
+`MULTICA_CODEX_CAPACITY_RETRY_COUNT` at startup.
+
+- The default is `6`.
+- The number means additional retries, so `6` permits seven total executions.
+- `0` disables only this Codex capacity policy.
+- The value must be a base-10 integer from `0` through `2147483646`, leaving
+ room for the initial execution in the signed 32-bit task attempt columns.
+- An unset variable uses the default. An invalid or negative value logs a
+ startup warning and uses the default.
+- This setting is authoritative for the special policy. A task's generic
+ `max_attempts` value does not reduce or disable it.
+
+Each retry child persists `max_attempts = configured retry count + 1`. This
+keeps the execution record self-describing and avoids rows such as
+`attempt=3/max_attempts=2`.
+
+## Matching Rules
+
+Capacity retry eligibility is determined from the raw error, not from the
+shared failure-reason bucket. The comparison is byte-for-byte equality with the
+complete string above.
+
+The policy deliberately does not:
+
+- trim leading or trailing whitespace;
+- fold letter case;
+- accept prefixes, suffixes, or embedded matches;
+- retry other capacity, overload, 429, or rate-limit failures; or
+- add the shared `agent_error.provider_capacity_or_rate_limit` reason to the
+ generic `retryableReasons` allowlist.
+
+The task-failure classifier may assign the shared capacity reason to this exact
+Codex error for reporting. Server-side normalization also upgrades the known
+labels emitted by older daemons, including
+`agent_error.model_not_found_or_unavailable`, when the raw error is exact. The
+raw-error predicate remains the retry gate, so classification cannot broaden
+the policy to unrelated failures.
+
+## Architecture And Flow
+
+The implementation reuses the existing server-side
+`FailTask -> CreateRetryTask` transaction path.
+
+1. The daemon reports a failed task and its raw error to `FailTask`.
+2. `FailTask` classifies and normalizes the reason for persistence.
+3. The retry gate evaluates generic retry policy and the dedicated Codex
+ capacity policy separately.
+4. For an exact capacity match with remaining configured budget, `FailTask`
+ creates the retry child in the same transaction that marks the parent
+ failed. This error is resume-safe, so the child inherits the existing
+ session and work directory when they are available.
+5. The child is created without `fire_at`; it is queued and claimable
+ immediately. No delay, exponential backoff, or maximum-backoff calculation
+ applies.
+6. The existing wakeup path notifies the runtime that work is available.
+
+The orphan-recovery path, `MaybeRetryFailedTask`, applies the same predicate to
+the parent's persisted raw error and the same configured ceiling. This keeps
+normal failure handling and sweeper recovery consistent.
+
+Existing safety boundaries remain in place: automatic retry requires an issue
+or chat-session link, and autopilot tasks remain owned by the autopilot
+scheduler rather than the task retry loop.
+
+## Service Boundaries
+
+Environment parsing stays at the API composition boundary. The parsed count is
+passed through handler configuration and stored on `TaskService`; service code
+does not call `os.Getenv`.
+
+The task service owns three small decisions:
+
+- exact raw-error recognition;
+- the capacity-specific total-attempt ceiling; and
+- selection of immediate retry without `fire_at`.
+
+Generic failure reasons retain their existing allowlist, ceilings, and delays.
+In particular, the provider-network three-attempt schedule and its final
+five-second delay do not change.
+
+## Failure Reporting
+
+An attempt that successfully creates a retry child remains silent through the
+existing retry-pending behavior: it does not emit the user-visible terminal
+failure or quick-create failure notification. The retry child reports its own
+outcome.
+
+When the configured capacity budget is exhausted, or retry-child creation
+fails, the task follows the existing terminal failure path and the error is
+shown normally. There is no fallback to another model.
+
+## Deployment And Documentation
+
+The variable is exposed wherever non-secret backend deployment configuration
+is declared:
+
+- `.env.example`, with default `6`;
+- self-hosted Docker Compose backend environment, forwarding the deployment
+ value with default `6`;
+- Helm `backend.config` values and backend ConfigMap; and
+- the environment-variable documentation, explicitly listed as API-server
+ configuration rather than daemon configuration.
+
+No secret handling is required.
+
+## Tests
+
+Focused tests cover:
+
+- exact classification and normalization for current and legacy daemon labels;
+- rejection of case changes, surrounding whitespace, prefixes, suffixes, and
+ unrelated 429/rate-limit errors;
+- environment parsing for unset, positive, zero, negative, malformed, and
+ out-of-range values;
+- `6` producing six retry children and a total ceiling of seven attempts;
+- `0` disabling the special policy;
+- generic `max_attempts=1` not disabling an enabled capacity policy;
+- capacity retries creating no delay or `fire_at` value;
+- generic retry policies retaining their existing budgets and backoff; and
+- final exhaustion becoming a normal visible failure while intermediate
+ retrying failures remain silent.
+
+The implementation starts with failing focused tests, then runs the affected Go
+package tests and the repository's broader verification appropriate to the
+changed backend and deployment files.
+
+## Data And Migration Impact
+
+No schema or data migration is needed. Existing `attempt`, `max_attempts`, raw
+error, failure reason, parent-task linkage, and `fire_at` fields already express
+the required behavior.
+
+## Non-Goals
+
+- Generic provider-capacity or rate-limit retries.
+- Model fallback or model selection changes.
+- Delayed or exponential retry scheduling.
+- Per-agent, per-workspace, or UI configuration.
+- Retrying already-terminal historical COM-44 runs.
diff --git a/server/cmd/server/codex_capacity_retry_test.go b/server/cmd/server/codex_capacity_retry_test.go
new file mode 100644
index 0000000000..c39b21307c
--- /dev/null
+++ b/server/cmd/server/codex_capacity_retry_test.go
@@ -0,0 +1,98 @@
+package main
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/service"
+)
+
+// TestCodexCapacityRetryCountBounds pins the two constants the boundary cases
+// below are written against. They are spelled as literals in those cases on
+// purpose — the ceiling is a product decision, so moving it should be a
+// deliberate edit that updates the expectations, not a silent re-derivation.
+func TestCodexCapacityRetryCountBounds(t *testing.T) {
+ if service.DefaultCodexCapacityRetryCount != 6 {
+ t.Fatalf("DefaultCodexCapacityRetryCount = %d, want 6", service.DefaultCodexCapacityRetryCount)
+ }
+ if service.MaxCodexCapacityRetryCount != 20 {
+ t.Fatalf("MaxCodexCapacityRetryCount = %d, want 20", service.MaxCodexCapacityRetryCount)
+ }
+}
+
+func TestParseCodexCapacityRetryCountAccepts(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ want int32
+ }{
+ {"empty uses default", "", 6},
+ {"blank uses default", " ", 6},
+ {"zero disables the policy", "0", 0},
+ {"positive count", "3", 3},
+ {"surrounding whitespace", " 3 ", 3},
+ {"default is inside the ceiling", "6", 6},
+ {"one below maximum", "19", 19},
+ {"maximum accepted", "20", 20},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := parseCodexCapacityRetryCount(tc.raw)
+ if err != nil {
+ t.Fatalf("parseCodexCapacityRetryCount(%q) returned error: %v", tc.raw, err)
+ }
+ if got != tc.want {
+ t.Fatalf("parseCodexCapacityRetryCount(%q) = %d, want %d", tc.raw, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestParseCodexCapacityRetryCountRejects covers the blocker this ceiling
+// exists for: capacity retries fire with zero delay and each one writes a task
+// row, launches a runtime and calls the provider, so a value past the maximum
+// must stop the boot rather than fall back to the default and look configured.
+// The three int32-scale cases are the values the pre-ceiling parser accepted.
+func TestParseCodexCapacityRetryCountRejects(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ }{
+ {"negative", "-1"},
+ {"malformed", "six"},
+ {"trailing garbage", "3x"},
+ {"one past maximum", "21"},
+ {"former int32 ceiling", "2147483646"},
+ {"overflowing total", "2147483647"},
+ {"int32 overflow", "2147483648"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := parseCodexCapacityRetryCount(tc.raw)
+ if err == nil {
+ t.Fatalf("parseCodexCapacityRetryCount(%q) = %d, want error", tc.raw, got)
+ }
+ if got != 0 {
+ t.Fatalf("parseCodexCapacityRetryCount(%q) = %d alongside an error, want 0", tc.raw, got)
+ }
+ })
+ }
+}
+
+// TestCodexCapacityRetryCountFallsBackWhenUnset pins the nil-versus-zero
+// distinction RouterOptions carries: tests and NewRouter leave the pointer nil
+// and must get the default, while an explicit zero disables the policy.
+func TestCodexCapacityRetryCountFallsBackWhenUnset(t *testing.T) {
+ if got := codexCapacityRetryCount(RouterOptions{}); got != service.DefaultCodexCapacityRetryCount {
+ t.Fatalf("unset = %d, want %d", got, service.DefaultCodexCapacityRetryCount)
+ }
+ disabled := int32(0)
+ if got := codexCapacityRetryCount(RouterOptions{CodexCapacityRetryCount: &disabled}); got != 0 {
+ t.Fatalf("explicit zero = %d, want 0", got)
+ }
+ configured := int32(11)
+ if got := codexCapacityRetryCount(RouterOptions{CodexCapacityRetryCount: &configured}); got != 11 {
+ t.Fatalf("explicit value = %d, want 11", got)
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index f298a04ed9..e74c6d5e58 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -581,6 +581,15 @@ func main() {
os.Exit(1)
}
+ // Same posture for the Codex capacity retry budget: a value above the
+ // ceiling would let one capacity failure spawn an unbounded task chain, so
+ // the boot stops rather than quietly restoring the default.
+ codexCapacityRetries, err := parseCodexCapacityRetryCount(os.Getenv("MULTICA_CODEX_CAPACITY_RETRY_COUNT"))
+ if err != nil {
+ slog.Error("invalid MULTICA_CODEX_CAPACITY_RETRY_COUNT", "error", err)
+ os.Exit(1)
+ }
+
r, h := NewRouterWithOptions(pool, hub, bus, analyticsClient, storeRedis, RouterOptions{
HTTPMetrics: httpMetrics,
BusinessMetrics: businessMetrics,
@@ -593,6 +602,8 @@ func main() {
FeatureFlags: flags,
HeartbeatScheduler: heartbeatScheduler,
LLMMaxRetries: llmMaxRetries,
+
+ CodexCapacityRetryCount: &codexCapacityRetries,
})
srv := &http.Server{
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 4635c8df5d..a7f7bc8ac0 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/netip"
"os"
+ "strconv"
"strings"
"time"
@@ -186,6 +187,48 @@ func parseTrustedProxies(raw string) []netip.Prefix {
return out
}
+// codexCapacityRetryCount resolves the capacity retry budget the Handler runs
+// with. main() injects the validated value; NewRouter and tests leave it nil
+// and get the service default.
+func codexCapacityRetryCount(opts RouterOptions) int32 {
+ if opts.CodexCapacityRetryCount != nil {
+ return *opts.CodexCapacityRetryCount
+ }
+ return service.DefaultCodexCapacityRetryCount
+}
+
+// parseCodexCapacityRetryCount turns the raw MULTICA_CODEX_CAPACITY_RETRY_COUNT
+// value into the deployment-wide number of additional retries for Codex's exact
+// selected-model capacity error. An empty value yields the service default.
+//
+// Like parseLLMMaxRetries (MUL-6364) this returns an error instead of warning
+// and falling back to the default. The reason is stronger here: capacity
+// retries fire with zero delay, and each attempt writes a task row, launches a
+// runtime and calls the provider again, so an unnoticed value is not merely
+// "not what the operator asked for" — above the ceiling it is an effectively
+// unbounded task chain. Failing the boot makes a typo'd knob visible instead of
+// leaving a server that looks configured and is not.
+func parseCodexCapacityRetryCount(raw string) (int32, error) {
+ raw = strings.TrimSpace(raw)
+ if raw == "" {
+ return service.DefaultCodexCapacityRetryCount, nil
+ }
+ // Parsed at 64 bits so an out-of-int32 value reports the ceiling error
+ // rather than a shape error: "must be at most 20" tells the operator what
+ // to do, "must be an integer" does not.
+ value, err := strconv.ParseInt(raw, 10, 64)
+ if err != nil {
+ return 0, fmt.Errorf("must be an integer, got %q", raw)
+ }
+ if value < 0 {
+ return 0, fmt.Errorf("must not be negative, got %d", value)
+ }
+ if value > int64(service.MaxCodexCapacityRetryCount) {
+ return 0, fmt.Errorf("must be at most %d, got %d", service.MaxCodexCapacityRetryCount, value)
+ }
+ return int32(value), nil
+}
+
// normalizeServerVersion maps the unstamped "dev" default (main.go's
// `version` var, unchanged when the binary wasn't built with
// -X main.version=<tag>) to an empty string. handler.Config.ServerVersion
@@ -238,6 +281,14 @@ type RouterOptions struct {
// any test that happened to have the variable set. nil means unset, which
// is what tests and NewRouter get.
LLMMaxRetries *llm.RetryOverride
+ // CodexCapacityRetryCount carries the parsed
+ // MULTICA_CODEX_CAPACITY_RETRY_COUNT budget, injected for the same reason as
+ // LLMMaxRetries above: a value over service.MaxCodexCapacityRetryCount must
+ // fail the boot, and only main() can exit. nil means unset, which is what
+ // tests and NewRouter get — they fall back to
+ // service.DefaultCodexCapacityRetryCount. A non-nil zero is meaningful and
+ // distinct from unset: it disables the dedicated capacity policy.
+ CodexCapacityRetryCount *int32
}
func buildChannelSupervisor(
@@ -409,6 +460,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
LLMBaseURL: strings.TrimSpace(os.Getenv("MULTICA_LLM_BASE_URL")),
LLMDefaultModel: strings.TrimSpace(os.Getenv("MULTICA_LLM_DEFAULT_MODEL")),
LLMMaxRetries: opts.LLMMaxRetries,
+ CodexCapacityRetryCount: codexCapacityRetryCount(opts),
ServerVersion: normalizeServerVersion(version),
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 4cf31b692c..abbb449c5b 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -143,6 +143,13 @@ type Config struct {
// and cmd/server additionally fails the boot on an out-of-range value before
// one reaches this struct. See llm.Config.MaxRetries for the full semantics.
LLMMaxRetries *llm.RetryOverride
+ // CodexCapacityRetryCount is the deployment-wide number of additional
+ // immediate retries for Codex's exact selected-model capacity error. Zero
+ // disables only that dedicated policy. cmd/server enforces
+ // service.MaxCodexCapacityRetryCount as a hard maximum, failing the boot on
+ // an out-of-range value rather than correcting it, so the value reaching
+ // this struct is already validated.
+ CodexCapacityRetryCount int32
// ServerVersion is the build version of the running API binary (the same
// value main.go stamps via -X main.version and reports on /metrics).
// Surfaced through /api/config so self-hosted operators can confirm which
@@ -441,6 +448,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)
taskSvc.Analytics = analyticsClient
taskSvc.SourceContextStorage = store
+ taskSvc.CodexCapacityRetryCount = cfg.CodexCapacityRetryCount
// Chat follow-up suggestions run through the same internal LLM layer that
// backs auto-titling. A deployment with no MULTICA_LLM_* configuration gets
// a disabled client, which turns the feature off rather than failing.
diff --git a/server/internal/service/retry_deferred_test.go b/server/internal/service/retry_deferred_test.go
index f07c9df421..41309a1ea9 100644
--- a/server/internal/service/retry_deferred_test.go
+++ b/server/internal/service/retry_deferred_test.go
@@ -349,3 +349,141 @@ func TestFailTaskProviderNetworkBudget(t *testing.T) {
})
}
}
+
+// TestFailTaskCodexCapacityBudget locks the exact COM-44 error to its dedicated
+// deployment budget. It exercises the real fail transaction so the persisted
+// child ceiling, immediate queue state, and resume fields cannot drift away
+// from the pure retry-policy helpers.
+func TestFailTaskCodexCapacityBudget(t *testing.T) {
+ const capacityErr = "Selected model is at capacity. Please try a different model."
+
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ _, _, agentID, issueID := seedAttributionFixture(t, pool)
+
+ var runtimeID string
+ if err := pool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&runtimeID); err != nil {
+ t.Fatalf("read agent runtime: %v", err)
+ }
+
+ cases := []struct {
+ name string
+ rawError string
+ reason string
+ attempt int32
+ maxAttempts int32
+ capacityRetries int32
+ wantChild bool
+ }{
+ {
+ name: "enabled policy overrides generic retry disable",
+ rawError: capacityErr,
+ reason: "agent_error.model_not_found_or_unavailable",
+ attempt: 1,
+ maxAttempts: 1,
+ capacityRetries: 6,
+ wantChild: true,
+ },
+ {
+ name: "zero disables capacity policy",
+ rawError: capacityErr,
+ reason: "agent_error.model_not_found_or_unavailable",
+ attempt: 1,
+ maxAttempts: 2,
+ capacityRetries: 0,
+ wantChild: false,
+ },
+ {
+ name: "seventh execution exhausts six retries",
+ rawError: capacityErr,
+ reason: "agent_error.provider_capacity_or_rate_limit",
+ attempt: 7,
+ maxAttempts: 7,
+ capacityRetries: 6,
+ wantChild: false,
+ },
+ {
+ name: "generic rate limit is terminal",
+ rawError: "API Error: 429 Too Many Requests",
+ reason: "agent_error.provider_capacity_or_rate_limit",
+ attempt: 1,
+ maxAttempts: 2,
+ capacityRetries: 6,
+ wantChild: false,
+ },
+ {
+ name: "padded capacity error is terminal",
+ rawError: " Selected model is at capacity. Please try a different model. ",
+ reason: "agent_error.model_not_found_or_unavailable",
+ attempt: 1,
+ maxAttempts: 2,
+ capacityRetries: 6,
+ wantChild: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var parentID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, attempt, max_attempts, session_id, work_dir)
+ VALUES ($1, $2, $3, 'running', 0, $4, $5, 'capacity-session', '/tmp/capacity-workdir')
+ RETURNING id
+ `, agentID, runtimeID, issueID, tc.attempt, tc.maxAttempts).Scan(&parentID); err != nil {
+ t.Fatalf("insert parent task: %v", err)
+ }
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE parent_task_id = $1 OR id = $1`, parentID)
+ })
+
+ svc := &TaskService{
+ Queries: q,
+ TxStarter: pool,
+ Bus: events.New(),
+ CodexCapacityRetryCount: tc.capacityRetries,
+ }
+ if _, err := svc.FailTask(ctx, parentID, tc.rawError, "capacity-session", "/tmp/capacity-workdir", "", tc.reason, false, "", ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+
+ var childCount int
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE parent_task_id = $1`, parentID).Scan(&childCount); err != nil {
+ t.Fatalf("count retry children: %v", err)
+ }
+ if !tc.wantChild {
+ if childCount != 0 {
+ t.Fatalf("retry child count = %d, want 0", childCount)
+ }
+ return
+ }
+ if childCount != 1 {
+ t.Fatalf("retry child count = %d, want 1", childCount)
+ }
+
+ var (
+ attempt, maxAttempts int32
+ status, sessionID string
+ workDir string
+ fireAtValid bool
+ forceFreshSession bool
+ )
+ if err := pool.QueryRow(ctx, `
+ SELECT attempt, max_attempts, status, fire_at IS NOT NULL,
+ force_fresh_session, COALESCE(session_id, ''), COALESCE(work_dir, '')
+ FROM agent_task_queue WHERE parent_task_id = $1
+ `, parentID).Scan(&attempt, &maxAttempts, &status, &fireAtValid, &forceFreshSession, &sessionID, &workDir); err != nil {
+ t.Fatalf("read retry child: %v", err)
+ }
+ if attempt != 2 || maxAttempts != 7 {
+ t.Errorf("child attempt/max_attempts = %d/%d, want 2/7", attempt, maxAttempts)
+ }
+ if status != "queued" || fireAtValid {
+ t.Errorf("child status/fire_at = %q/%v, want queued/false", status, fireAtValid)
+ }
+ if forceFreshSession || sessionID != "capacity-session" || workDir != "/tmp/capacity-workdir" {
+ t.Errorf("child resume state = fresh:%v session:%q workdir:%q", forceFreshSession, sessionID, workDir)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 408ad0aea4..c451b134e9 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -49,6 +49,12 @@ type TaskService struct {
// FeatureFlags is the server-side toggle router. Nil is valid and returns
// each call site's default.
FeatureFlags *featureflag.Service
+ // CodexCapacityRetryCount is the number of additional immediate attempts
+ // allowed only for Codex's exact selected-model capacity error. Zero
+ // disables that dedicated policy. The API composition boundary supplies
+ // the deployment default; direct test/service construction may leave it
+ // zero intentionally.
+ CodexCapacityRetryCount int32
// EmptyClaim caches "this runtime has no queued task" so the daemon
// poll path can skip a Postgres scan on the steady-state empty case.
// Optional — a nil cache disables the fast path and every claim
@@ -4612,20 +4618,20 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
retryFireAt pgtype.Timestamptz
retryMaxAttempts pgtype.Int4
)
- if retryableReasons[failureReason] {
+ if retryCandidate(failureReason, errMsg, s.CodexCapacityRetryCount) {
if parent, perr := s.Queries.GetAgentTask(ctx, taskID); perr != nil {
slog.Warn("fail task auto-retry: load parent failed",
"task_id", util.UUIDToString(taskID), "error", perr)
- } else if retryEligible(failureReason, parent) {
+ } else if retryEligible(failureReason, errMsg, parent, s.CodexCapacityRetryCount) {
wantRetry = true
// Persist the reason-aware effective budget into the child so the
// retry chain self-describes (e.g. provider_network → max_attempts=3),
// rather than leaking a contradictory attempt=N/max_attempts=2 row.
- retryMaxAttempts = pgtype.Int4{Int32: retryAttemptCeiling(failureReason, parent.MaxAttempts), Valid: true}
+ retryMaxAttempts = pgtype.Int4{Int32: retryAttemptCeiling(failureReason, errMsg, parent.MaxAttempts, s.CodexCapacityRetryCount), Valid: true}
// Defer this attempt when the reason's schedule calls for a backoff
// (provider_network's final attempt waits ~5s); a zero delay leaves
// fire_at NULL so the child is created immediately-claimable.
- if delay := retryDelayForAttempt(failureReason, parent.Attempt); delay > 0 {
+ if delay := retryDelayForAttempt(failureReason, errMsg, parent.Attempt); delay > 0 {
retryFireAt = pgtype.Timestamptz{Time: time.Now().Add(delay), Valid: true}
}
if agent, aerr := s.Queries.GetAgent(ctx, parent.AgentID); aerr != nil {
@@ -4977,6 +4983,25 @@ var retryableReasons = map[string]bool{
string(taskfailure.ReasonSkillBundleUnavailable): true,
}
+// DefaultCodexCapacityRetryCount is the number of additional executions the
+// API server allows for Codex's exact selected-model capacity error when the
+// deployment does not override MULTICA_CODEX_CAPACITY_RETRY_COUNT.
+const DefaultCodexCapacityRetryCount int32 = 6
+
+// MaxCodexCapacityRetryCount is the hard ceiling on
+// MULTICA_CODEX_CAPACITY_RETRY_COUNT. Unlike the generic retry budgets this one
+// is a work-amplification bound, not a latency one: capacity retries fire with
+// zero delay, and each attempt writes a task row, launches a runtime and calls
+// the provider again. A mistyped value must not be able to turn one failure
+// into an effectively unbounded task chain, so the knob is capped rather than
+// accepted up to MaxInt32.
+//
+// 20 is ~3x the default of 6, which leaves an operator room to widen the budget
+// during a prolonged capacity incident while bounding the worst case to 21
+// total attempts. Past that the condition is an outage to route around, not a
+// blip to retry through.
+const MaxCodexCapacityRetryCount int32 = 20
+
// runtime_offline retries start deferred, not queued: their positive fire_at
// routes them through health-gated promotion after a fresh runtime heartbeat
// returns. The queue sweeper also exempts this retry lineage, covering the race
@@ -4996,17 +5021,20 @@ const (
)
// retryAttemptCeiling reports how many attempts the auto-retry path allows for
-// a failure reason. It only ever WIDENS the task's generic max_attempts, and
-// only for reasons with a bespoke schedule; everything else keeps the column's
-// value (default 2 = first run + one retry).
+// a failure reason. Generic failures honor the task's max_attempts value
+// (default 2 = first run + one retry), including max_attempts <= 1 disabling
+// retries. The dedicated Codex capacity policy is an explicit exception: when
+// enabled, its configured ceiling overrides the inherited max_attempts value.
+// Other bespoke schedules may only widen an enabled generic retry budget.
//
-// max_attempts <= 1 explicitly disables auto-retry (055_task_lease_and_retry.up
-// .sql: "1 disables retry"), so it is never overridden — a disabled task must
-// not be revived by a raised ceiling. Callers persist this value into the retry
-// child (CreateRetryTask's max_attempts) so the row stays self-consistent:
-// provider_network's chain records attempt=3, max_attempts=3, not a
+// Callers persist this reason-aware value into the retry child
+// (CreateRetryTask's max_attempts) so the row stays self-consistent: for
+// example, provider_network's chain records attempt=3, max_attempts=3, not a
// contradictory attempt=3, max_attempts=2 (MUL-4910).
-func retryAttemptCeiling(reason string, taskMaxAttempts int32) int32 {
+func retryAttemptCeiling(reason, rawError string, taskMaxAttempts, capacityRetryCount int32) int32 {
+ if taskfailure.IsCodexSelectedModelCapacityError(rawError) && capacityRetryCount > 0 {
+ return capacityRetryCount + 1
+ }
if taskMaxAttempts <= 1 {
return taskMaxAttempts
}
@@ -5017,12 +5045,18 @@ func retryAttemptCeiling(reason string, taskMaxAttempts int32) int32 {
}
// retryDelayForAttempt reports how long to defer the NEXT attempt after a
-// failure at failedAttempt. runtime_offline always gets a positive fire_at so
-// it waits for the health-gated promotion path. provider_network's final
-// attempt is deferred ~5s; every other retry remains immediate (zero delay →
-// the child is created 'queued', claimable at once). Callers pass the returned
-// delay to CreateRetryTask via fire_at.
-func retryDelayForAttempt(reason string, failedAttempt int32) time.Duration {
+// failure at failedAttempt. The Codex capacity policy is always immediate — it
+// exists to re-roll a momentary capacity rejection, so a delay would defeat it,
+// and that takes precedence over the reason-based schedules below.
+// runtime_offline always gets a positive fire_at so it waits for the
+// health-gated promotion path. provider_network's final attempt is deferred
+// ~5s; every other retry remains immediate (zero delay → the child is created
+// 'queued', claimable at once). Callers pass the returned delay to
+// CreateRetryTask via fire_at.
+func retryDelayForAttempt(reason, rawError string, failedAttempt int32) time.Duration {
+ if taskfailure.IsCodexSelectedModelCapacityError(rawError) {
+ return 0
+ }
if reason == string(taskfailure.ReasonRuntimeOffline) {
return runtimeOfflineRetryDeferral
}
@@ -5094,14 +5128,26 @@ func ResumeUnsafeFailure(failureReason, errorText string) bool {
return taskfailure.UnresumableHistory(errorText)
}
+// retryCandidate keeps the exact Codex capacity policy separate from the
+// generic failure-reason allowlist. An exact raw error always takes this branch,
+// so a configured zero disables it even if a stale daemon supplied an unrelated
+// generic-retry reason.
+func retryCandidate(failureReason, rawError string, capacityRetryCount int32) bool {
+ if taskfailure.IsCodexSelectedModelCapacityError(rawError) {
+ return capacityRetryCount > 0
+ }
+ return retryableReasons[failureReason]
+}
+
// retryEligible reports whether a failed task qualifies for an automatic retry
-// attempt: an infrastructure-shaped failure_reason, remaining attempt budget,
-// not an autopilot run, and linked to an issue or chat session. Shared by
-// FailTask's in-transaction retry and the orphan sweeper's MaybeRetryFailedTask
-// so both agree on which failures re-run.
-func retryEligible(failureReason string, t db.AgentTaskQueue) bool {
- return retryableReasons[failureReason] &&
- t.Attempt < retryAttemptCeiling(failureReason, t.MaxAttempts) &&
+// attempt: either a generic infrastructure-shaped reason or the exact Codex
+// capacity error, remaining policy-specific attempt budget, not an autopilot
+// run, and linked to an issue or chat session. Shared by FailTask's
+// in-transaction retry and the orphan sweeper's MaybeRetryFailedTask so both
+// agree on which failures re-run.
+func retryEligible(failureReason, rawError string, t db.AgentTaskQueue, capacityRetryCount int32) bool {
+ return retryCandidate(failureReason, rawError, capacityRetryCount) &&
+ t.Attempt < retryAttemptCeiling(failureReason, rawError, t.MaxAttempts, capacityRetryCount) &&
!t.AutopilotRunID.Valid &&
(t.IssueID.Valid || t.ChatSessionID.Valid || isSourceContextQuickCreateTask(t))
}
@@ -5159,7 +5205,11 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
if parent.FailureReason.Valid {
reason = parent.FailureReason.String
}
- if !retryableReasons[reason] {
+ rawError := ""
+ if parent.Error.Valid {
+ rawError = parent.Error.String
+ }
+ if !retryCandidate(reason, rawError, s.CodexCapacityRetryCount) {
return nil, nil
}
// Use the reason-aware ceiling, not the raw max_attempts column, so an
@@ -5167,19 +5217,20 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
// allowed its deferred 3rd attempt (retryAttemptCeiling raises the ceiling
// to 3). Kept in sync with retryEligible below, which applies the same
// ceiling to the primary FailTask path.
- if parent.Attempt >= retryAttemptCeiling(reason, parent.MaxAttempts) {
+ ceiling := retryAttemptCeiling(reason, rawError, parent.MaxAttempts, s.CodexCapacityRetryCount)
+ if parent.Attempt >= ceiling {
slog.Info("task auto-retry skipped: budget exhausted",
"task_id", util.UUIDToString(parent.ID),
"attempt", parent.Attempt,
"max_attempts", parent.MaxAttempts,
- "ceiling", retryAttemptCeiling(reason, parent.MaxAttempts),
+ "ceiling", ceiling,
)
return nil, nil
}
// Autopilot has its own retry semantics (don't double-trigger) and a task
// with no issue/chat link has nowhere to report its retry — retryEligible
// covers both, keeping this sweeper path in sync with FailTask's in-tx retry.
- if !retryEligible(reason, parent) {
+ if !retryEligible(reason, rawError, parent, s.CodexCapacityRetryCount) {
return nil, nil
}
@@ -5202,7 +5253,7 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
// NULL for an immediate child), and write the reason-aware ceiling into the
// child's max_attempts so the retry chain stays self-consistent.
var retryFireAt pgtype.Timestamptz
- if delay := retryDelayForAttempt(reason, parent.Attempt); delay > 0 {
+ if delay := retryDelayForAttempt(reason, rawError, parent.Attempt); delay > 0 {
retryFireAt = pgtype.Timestamptz{Time: time.Now().Add(delay), Valid: true}
}
// Same advisory slot check as FailTask's path, for the same reason: skip the
@@ -5232,7 +5283,7 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
NewTaskID: dbid.NewV7(),
ID: parent.ID,
FireAt: retryFireAt,
- MaxAttempts: pgtype.Int4{Int32: retryAttemptCeiling(reason, parent.MaxAttempts), Valid: true},
+ MaxAttempts: pgtype.Int4{Int32: ceiling, Valid: true},
RuntimeMcpOverlay: runtimeMCPOverlay.Overlay,
RuntimeConnectedApps: runtimeMCPOverlay.ConnectedApps,
})
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index 91879e9577..acfb0cb0a8 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -191,7 +191,7 @@ func TestProviderNetworkRetrySchedule(t *testing.T) {
{"timeout", 1, 1}, // unrelated + disabled → untouched
}
for _, tc := range ceilingCases {
- if got := retryAttemptCeiling(tc.reason, tc.max); got != tc.want {
+ if got := retryAttemptCeiling(tc.reason, "", tc.max, 0); got != tc.want {
t.Errorf("ceiling(%q, %d) = %d, want %d", tc.reason, tc.max, got, tc.want)
}
}
@@ -209,7 +209,7 @@ func TestProviderNetworkRetrySchedule(t *testing.T) {
{"timeout", 2, 0}, // unrelated reason → never deferred
}
for _, tc := range delayCases {
- if got := retryDelayForAttempt(tc.reason, tc.failedAttempt); got != tc.want {
+ if got := retryDelayForAttempt(tc.reason, "", tc.failedAttempt); got != tc.want {
t.Errorf("retryDelayForAttempt(%q, %d) = %s, want %s", tc.reason, tc.failedAttempt, got, tc.want)
}
}
@@ -239,7 +239,7 @@ func TestProviderNetworkRetrySchedule(t *testing.T) {
{"non-retryable reason never retries", "agent_error.unknown", 1, 2, false},
}
for _, tc := range eligCases {
- if got := retryEligible(tc.reason, mkTask(tc.attempt, tc.max)); got != tc.want {
+ if got := retryEligible(tc.reason, "", mkTask(tc.attempt, tc.max), 0); got != tc.want {
t.Errorf("%s: retryEligible(%q, attempt=%d/max=%d) = %v, want %v", tc.name, tc.reason, tc.attempt, tc.max, got, tc.want)
}
}
@@ -247,16 +247,36 @@ func TestProviderNetworkRetrySchedule(t *testing.T) {
func TestTaskFailureClassifiers(t *testing.T) {
cases := []struct {
- reason string
- wantType string
- wantResumeOK bool
- wantRetry bool
+ reason string
+ rawError string
+ capacityRetries int32
+ wantType string
+ wantResumeOK bool
+ wantRetry bool
}{
{reason: "timeout", wantType: "timeout", wantResumeOK: true, wantRetry: true},
{reason: "codex_semantic_inactivity", wantType: "timeout", wantResumeOK: false, wantRetry: true},
// Transient mid-stream provider disconnect (MUL-4910): retryable, and
// resume-safe so the retry continues the truncated conversation.
{reason: "agent_error.provider_network", wantType: "agent_error", wantResumeOK: true, wantRetry: true},
+ // COM-44: this exact capacity failure is transient and resume-safe. Its
+ // dedicated deployment budget keeps the retry bounded.
+ {
+ reason: "agent_error.provider_capacity_or_rate_limit",
+ rawError: "Selected model is at capacity. Please try a different model.",
+ capacityRetries: 6,
+ wantType: "agent_error",
+ wantResumeOK: true,
+ wantRetry: true,
+ },
+ {
+ reason: "agent_error.provider_capacity_or_rate_limit",
+ rawError: "API Error: 429 Too Many Requests",
+ capacityRetries: 6,
+ wantType: "agent_error",
+ wantResumeOK: true,
+ wantRetry: false,
+ },
{reason: "runtime_recovery", wantType: "runtime", wantResumeOK: true, wantRetry: true},
{reason: "iteration_limit", wantType: "agent_output", wantResumeOK: false, wantRetry: false},
{reason: "api_invalid_request", wantType: "agent_error", wantResumeOK: false, wantRetry: false},
@@ -275,13 +295,111 @@ func TestTaskFailureClassifiers(t *testing.T) {
if got := !resumeUnsafeFailureReason(tc.reason); got != tc.wantResumeOK {
t.Fatalf("resume-safe(%q) = %v, want %v", tc.reason, got, tc.wantResumeOK)
}
- if got := retryableReasons[tc.reason]; got != tc.wantRetry {
- t.Fatalf("retryableReasons[%q] = %v, want %v", tc.reason, got, tc.wantRetry)
+ task := db.AgentTaskQueue{
+ Attempt: 1,
+ MaxAttempts: 2,
+ IssueID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},
+ }
+ if got := retryEligible(tc.reason, tc.rawError, task, tc.capacityRetries); got != tc.wantRetry {
+ t.Fatalf("retryEligible(%q, %q) = %v, want %v", tc.reason, tc.rawError, got, tc.wantRetry)
}
})
}
}
+// TestCodexCapacityFailureRetries walks COM-44's exact error through both
+// current- and old-daemon wire shapes into the retry gate. The shared capacity
+// reason is deliberately insufficient on its own: unrelated 429/rate-limit
+// failures retain their prior terminal behavior.
+func TestCodexCapacityFailureRetries(t *testing.T) {
+ const capacityErr = "Selected model is at capacity. Please try a different model."
+ const capacityRetries int32 = 6
+
+ mkTask := func(attempt, max int32) db.AgentTaskQueue {
+ return db.AgentTaskQueue{
+ Attempt: attempt,
+ MaxAttempts: max,
+ IssueID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true},
+ }
+ }
+ resolveFailureReason := func(reported string) string {
+ if reported == "" {
+ reported = taskfailure.Classify(capacityErr).String()
+ }
+ return taskfailure.NormalizeDaemonReason(reported, capacityErr).String()
+ }
+
+ daemonReasons := []struct {
+ name string
+ reported string
+ }{
+ {"current daemon", ""},
+ {"old daemon model-unavailable label", taskfailure.ReasonAgentModelNotFoundOrUnavailable.String()},
+ {"old daemon catchall", taskfailure.ReasonAgentUnknown.String()},
+ {"pre-MUL-1949 daemon", "agent_error"},
+ }
+ for _, daemon := range daemonReasons {
+ t.Run(daemon.name, func(t *testing.T) {
+ reason := resolveFailureReason(daemon.reported)
+ if reason != taskfailure.ReasonAgentProviderCapacityOrRateLimit.String() {
+ t.Fatalf("resolved reason = %q, want %q", reason, taskfailure.ReasonAgentProviderCapacityOrRateLimit)
+ }
+ if resumeUnsafeFailureReason(reason) {
+ t.Fatal("capacity retry must preserve the existing session")
+ }
+ if got := retryAttemptCeiling(reason, capacityErr, 1, capacityRetries); got != 7 {
+ t.Fatalf("capacity ceiling = %d, want 7 total attempts", got)
+ }
+ for attempt := int32(1); attempt <= capacityRetries; attempt++ {
+ if !retryEligible(reason, capacityErr, mkTask(attempt, 1), capacityRetries) {
+ t.Fatalf("attempt %d must retry despite generic max_attempts=1", attempt)
+ }
+ }
+ if retryEligible(reason, capacityErr, mkTask(7, 7), capacityRetries) {
+ t.Fatal("attempt 7 must exhaust six additional retries")
+ }
+ if retryEligible(reason, capacityErr, mkTask(1, 2), 0) {
+ t.Fatal("capacity retry count zero must disable the special policy")
+ }
+ if delay := retryDelayForAttempt(reason, capacityErr, 6); delay != 0 {
+ t.Fatalf("capacity retry delay = %s, want immediate", delay)
+ }
+ })
+ }
+
+ nearMatches := []string{
+ "SELECTED MODEL IS AT CAPACITY. PLEASE TRY A DIFFERENT MODEL.",
+ " Selected model is at capacity. Please try a different model.",
+ "Selected model is at capacity. Please try a different model. ",
+ "Selected model is at capacity. Please try a different model. Contact support.",
+ }
+ for _, rawError := range nearMatches {
+ if retryEligible(taskfailure.ReasonAgentModelNotFoundOrUnavailable.String(), rawError, mkTask(1, 2), capacityRetries) {
+ t.Errorf("near-match %q must not retry", rawError)
+ }
+ }
+
+ autopilotTask := mkTask(1, 2)
+ autopilotTask.AutopilotRunID = pgtype.UUID{Bytes: [16]byte{2}, Valid: true}
+ if retryEligible(taskfailure.ReasonAgentProviderCapacityOrRateLimit.String(), capacityErr, autopilotTask, capacityRetries) {
+ t.Fatal("autopilot tasks must remain owned by the autopilot scheduler")
+ }
+ unlinkedTask := mkTask(1, 2)
+ unlinkedTask.IssueID = pgtype.UUID{}
+ if retryEligible(taskfailure.ReasonAgentProviderCapacityOrRateLimit.String(), capacityErr, unlinkedTask, capacityRetries) {
+ t.Fatal("tasks without an issue or chat link must not retry")
+ }
+
+ const genericRateLimit = "API Error: 429 Too Many Requests"
+ rateLimitReason := taskfailure.Classify(genericRateLimit).String()
+ if rateLimitReason != taskfailure.ReasonAgentProviderCapacityOrRateLimit.String() {
+ t.Fatalf("rate-limit precondition classified as %q", rateLimitReason)
+ }
+ if retryEligible(rateLimitReason, genericRateLimit, mkTask(1, 2), capacityRetries) {
+ t.Fatal("the shared capacity reason must not make unrelated rate limits retryable")
+ }
+}
+
// TestRuntimeCLITimeoutIsNotAutoRetried pins the retry posture for #7112. A
// local runtime CLI that missed its preparation deadline is not transient: the
// same host runs the same CLI on the next attempt and takes the same 8-11s to
@@ -377,12 +495,12 @@ func TestOpencodeStreamEndedFailureRetries(t *testing.T) {
t.Errorf("resumeUnsafeFailureReason(%q) = true, want false", reason)
}
// With an attempt left, the failure produces a retry task.
- if !retryEligible(reason, mkTask(1, 2)) {
+ if !retryEligible(reason, tc.errMsg, mkTask(1, 2), 0) {
t.Errorf("retryEligible(%q, attempt=1/max=2) = false, want true", reason)
}
// And still terminates once the ceiling is reached, so a
// deterministically broken provider cannot loop forever.
- if retryEligible(reason, mkTask(providerNetworkMaxAttempts, 2)) {
+ if retryEligible(reason, tc.errMsg, mkTask(providerNetworkMaxAttempts, 2), 0) {
t.Errorf("retryEligible(%q, attempt=%d/max=2) = true, want false at the ceiling",
reason, providerNetworkMaxAttempts)
}
@@ -425,7 +543,7 @@ func TestSkillBundleFailureFromLegacyDaemonRetries(t *testing.T) {
// What an old daemon puts on the wire, and what FailTask does with it.
legacyReason := taskfailure.ReasonAgentUnknown.String()
- if retryEligible(legacyReason, task) {
+ if retryEligible(legacyReason, legacyErr, task, 0) {
t.Fatal("precondition: the raw catchall must not be retryable, or this test proves nothing")
}
@@ -433,7 +551,7 @@ func TestSkillBundleFailureFromLegacyDaemonRetries(t *testing.T) {
if normalized != taskfailure.ReasonSkillBundleUnavailable.String() {
t.Fatalf("normalized reason = %q, want %q", normalized, taskfailure.ReasonSkillBundleUnavailable)
}
- if !retryEligible(normalized, task) {
+ if !retryEligible(normalized, legacyErr, task, 0) {
t.Errorf("a skill-bundle failure reported by an old daemon must still be retried; got reason %q", normalized)
}
@@ -443,7 +561,7 @@ func TestSkillBundleFailureFromLegacyDaemonRetries(t *testing.T) {
taskfailure.ReasonSkillBundleUnavailable.String(),
`skill bundle unavailable: skill "x" (id=1, 10 bytes) after 30s: context deadline exceeded`,
).String()
- if !retryEligible(current, task) {
+ if !retryEligible(current, `skill bundle unavailable: skill "x" (id=1, 10 bytes) after 30s: context deadline exceeded`, task, 0) {
t.Errorf("a skill-bundle failure reported by a current daemon must be retried; got reason %q", current)
}
}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 17e541cf83..8211697dde 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -3078,8 +3078,9 @@ type CreateRetryTaskParams struct {
// p.max_attempts unchanged). Callers persist the reason-aware effective ceiling
// here so the row stays self-consistent — e.g. provider_network's chain records
// attempt=3, max_attempts=3 rather than leaking attempt=3, max_attempts=2 to the
-// task API (MUL-4910). The Go retryAttemptCeiling already refuses to raise a
-// disabled (max_attempts<=1) task, so this only ever widens, never revives.
+// task API (MUL-4910). Generic failures keep max_attempts<=1 disabled, while an
+// enabled dedicated Codex capacity policy intentionally overrides that inherited
+// limit; this query persists whichever effective ceiling the caller computed.
func (q *Queries) CreateRetryTask(ctx context.Context, arg CreateRetryTaskParams) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, createRetryTask,
arg.ID,
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 560ce97fc7..1df629400b 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -580,8 +580,9 @@ WHERE id = $1 AND issue_id IS NULL
-- p.max_attempts unchanged). Callers persist the reason-aware effective ceiling
-- here so the row stays self-consistent — e.g. provider_network's chain records
-- attempt=3, max_attempts=3 rather than leaking attempt=3, max_attempts=2 to the
--- task API (MUL-4910). The Go retryAttemptCeiling already refuses to raise a
--- disabled (max_attempts<=1) task, so this only ever widens, never revives.
+-- task API (MUL-4910). Generic failures keep max_attempts<=1 disabled, while an
+-- enabled dedicated Codex capacity policy intentionally overrides that inherited
+-- limit; this query persists whichever effective ceiling the caller computed.
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, chat_session_id, autopilot_run_id,
status, priority, trigger_comment_id, coalesced_comment_ids, trigger_summary, context,
diff --git a/server/pkg/taskfailure/classify.go b/server/pkg/taskfailure/classify.go
index eec226c42f..be49207dcb 100644
--- a/server/pkg/taskfailure/classify.go
+++ b/server/pkg/taskfailure/classify.go
@@ -138,13 +138,16 @@ func Classify(rawError string) Reason {
):
return ReasonAgentProviderQuotaLimit
- // 5. Capacity / rate limit. 429 / 529 / overloaded / rate limit.
+ // 5. Capacity / rate limit. 429 / 529 / overloaded / rate limit / Codex
+ // selected-model capacity. This precedes rule 8 because Codex's wording
+ // also contains the broader "selected model" witness.
case httpCapacityCodeRe.MatchString(lower),
containsAny(lower,
"rate limit",
"overloaded",
"no capacity available",
- ):
+ ),
+ IsCodexSelectedModelCapacityError(rawError):
return ReasonAgentProviderCapacityOrRateLimit
// 6. Provider 5xx / server error. The 5xx regex is checked here
@@ -345,6 +348,20 @@ var contextWindowExceededWitnesses = []string{
TerminalReasonPromptTooLong,
}
+// codexSelectedModelCapacityError is Codex's complete transient model-capacity
+// error. It must be checked before the broader "selected model"
+// model-unavailable rule.
+const codexSelectedModelCapacityError = "Selected model is at capacity. Please try a different model."
+
+// IsCodexSelectedModelCapacityError reports whether rawError is exactly the
+// complete Codex capacity error. The retry gate uses the same byte-for-byte
+// predicate as classification and mixed-version normalization so the shared
+// capacity/rate-limit reason does not broaden COM-44 to unrelated provider
+// failures.
+func IsCodexSelectedModelCapacityError(rawError string) bool {
+ return rawError == codexSelectedModelCapacityError
+}
+
// legacySkillBundlePrefix is the exact wrapper a pre-MUL-5370 daemon put on a
// failed skill-bundle download. It is an unambiguous witness: no other code
// path ever produced it, and a current daemon writes "skill bundle
@@ -379,6 +396,17 @@ var legacyContextOverflowReasons = map[string]bool{
"agent_error": true,
}
+// legacyCodexCapacityReasons are the labels an older daemon can report for
+// Codex's exact capacity wording. Its broad "selected model" rule chooses
+// model_not_found_or_unavailable; still older classifiers report unknown or
+// the pre-MUL-1949 coarse reason. The exact witness makes upgrading these
+// labels safe while preserving unrelated refined reasons.
+var legacyCodexCapacityReasons = map[string]bool{
+ string(ReasonAgentModelNotFoundOrUnavailable): true,
+ string(ReasonAgentUnknown): true,
+ "agent_error": true,
+}
+
// legacyOpenclawCLITimeoutWitnesses identify an OpenClaw config-discovery
// timeout in the wire text of a daemon that predates the sentinel
// (execenv.ErrOpenclawCLITimeout). Both halves must appear: the prep-stage
@@ -459,6 +487,13 @@ func NormalizeDaemonReason(reason, rawError string) Reason {
strings.HasPrefix(strings.TrimSpace(rawError), legacySkillBundlePrefix) {
return ReasonSkillBundleUnavailable
}
+ // COM-44: installed daemons classify this exact error as model unavailable
+ // before the dedicated capacity witness reaches them. Upgrade their stale
+ // non-empty reason server-side so the bounded retry applies immediately.
+ if legacyCodexCapacityReasons[reason] &&
+ IsCodexSelectedModelCapacityError(rawError) {
+ return ReasonAgentProviderCapacityOrRateLimit
+ }
// GH #6360: the same mixed-version gap, on a failure where waiting for
// every host to update is more expensive. A daemon whose rule 1 predates
// contextWindowExceededWitnesses reports the catchall, and the catchall is
diff --git a/server/pkg/taskfailure/classify_test.go b/server/pkg/taskfailure/classify_test.go
index 0e6e6cbe40..30d2845222 100644
--- a/server/pkg/taskfailure/classify_test.go
+++ b/server/pkg/taskfailure/classify_test.go
@@ -84,6 +84,11 @@ func TestClassifyRules(t *testing.T) {
{"rate limit", "rate limit exceeded for tier 3", ReasonAgentProviderCapacityOrRateLimit},
{"overloaded", "overloaded_error: please retry", ReasonAgentProviderCapacityOrRateLimit},
{"no capacity available", "no capacity available; try again later", ReasonAgentProviderCapacityOrRateLimit},
+ {"codex selected model at capacity", "Selected model is at capacity. Please try a different model.", ReasonAgentProviderCapacityOrRateLimit},
+ {"codex capacity uppercase stays model unavailable", "SELECTED MODEL IS AT CAPACITY. PLEASE TRY A DIFFERENT MODEL.", ReasonAgentModelNotFoundOrUnavailable},
+ {"codex capacity leading whitespace stays model unavailable", " Selected model is at capacity. Please try a different model.", ReasonAgentModelNotFoundOrUnavailable},
+ {"codex capacity trailing whitespace stays model unavailable", "Selected model is at capacity. Please try a different model. ", ReasonAgentModelNotFoundOrUnavailable},
+ {"codex capacity near-match stays model unavailable", "Selected model is at capacity. Please try a different model. Contact support if this persists.", ReasonAgentModelNotFoundOrUnavailable},
// 6. Provider 5xx / server error.
{"server had an error", "the server had an error processing your request", ReasonAgentProviderServerError},
@@ -382,6 +387,53 @@ func TestNormalizeDaemonReason(t *testing.T) {
want: Reason(""),
},
+ // --- COM-54: Codex model-capacity failures. Daemons whose
+ // classifier predates the dedicated capacity witness report the exact
+ // message as model_not_found_or_unavailable because it contains
+ // "selected model". Upgrade that stale non-empty label server-side.
+ {
+ name: "old daemon model-unavailable guess on codex capacity is upgraded",
+ reason: string(ReasonAgentModelNotFoundOrUnavailable),
+ raw: "Selected model is at capacity. Please try a different model.",
+ want: ReasonAgentProviderCapacityOrRateLimit,
+ },
+ {
+ name: "old daemon catchall on codex capacity is upgraded",
+ reason: string(ReasonAgentUnknown),
+ raw: "Selected model is at capacity. Please try a different model.",
+ want: ReasonAgentProviderCapacityOrRateLimit,
+ },
+ {
+ name: "pre-MUL-1949 coarse reason on codex capacity is upgraded",
+ reason: "agent_error",
+ raw: "Selected model is at capacity. Please try a different model.",
+ want: ReasonAgentProviderCapacityOrRateLimit,
+ },
+ {
+ name: "codex capacity uppercase is not upgraded",
+ reason: string(ReasonAgentModelNotFoundOrUnavailable),
+ raw: "SELECTED MODEL IS AT CAPACITY. PLEASE TRY A DIFFERENT MODEL.",
+ want: ReasonAgentModelNotFoundOrUnavailable,
+ },
+ {
+ name: "codex capacity with surrounding whitespace is not upgraded",
+ reason: string(ReasonAgentModelNotFoundOrUnavailable),
+ raw: " Selected model is at capacity. Please try a different model. ",
+ want: ReasonAgentModelNotFoundOrUnavailable,
+ },
+ {
+ name: "unrelated refined reason with codex capacity text is left alone",
+ reason: string(ReasonAgentProviderAuthOrAccess),
+ raw: "401 Unauthorized: Selected model is at capacity.",
+ want: ReasonAgentProviderAuthOrAccess,
+ },
+ {
+ name: "capacity near-match is not upgraded",
+ reason: string(ReasonAgentModelNotFoundOrUnavailable),
+ raw: "Selected model is at capacity. Please try a different model. Contact support if this persists.",
+ want: ReasonAgentModelNotFoundOrUnavailable,
+ },
+
// --- GH #6360: response-side context overflow. An un-upgraded daemon
// classifies the wordings below as the catchall, which is on no resume
// blacklist — so without this the over-full session stays pinned and