Skip to content

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

Go

MUL-6737: fix(timeouts): close the two gaps the 2h inactivity budget left open (#7699)

Bohan Jiang64ec7f54163d
diff --git a/.env.example b/.env.example
index 67d62c134e..1aa488b979 100644
--- a/.env.example
+++ b/.env.example
@@ -88,12 +88,6 @@ MULTICA_SHUTDOWN_HOLD_DURATION=
# Accepts a positive Go duration. The default is 3h; values below 150s are
# clamped to the runtime heartbeat freshness window.
MULTICA_RUNTIME_RECONNECT_GRACE=3h
-# How long a task may sit in 'queued' without being claimed before failing
-# with 'queued_expired'. Accepts a positive Go duration; empty, unset, or
-# invalid values keep the default of 2h. Raise this when a runtime has low
-# task concurrency and tasks can legitimately wait behind long-running work
-# — with a concurrency-1 runtime a backlog can exceed the default 2h.
-MULTICA_TASK_QUEUED_TTL=2h
# Comma-separated CIDR list of reverse proxies whose X-Forwarded-For /
# X-Real-IP headers the per-IP webhook rate limiter is allowed to trust.
# Empty (the default) means "trust no headers" — the limiter uses
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 62c83d8bfe..d177b1b8d3 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -250,7 +250,7 @@ Daemon behavior is configured via flags or environment variables:
| Agent timeout | `--agent-timeout` | `MULTICA_AGENT_TIMEOUT` | `0` (no cap; bounded by the watchdogs) |
| Agent idle watchdog | — | `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` (`0` disables the whole watchdog suite) |
| Agent tool watchdog | — | `MULTICA_AGENT_TOOL_WATCHDOG` | same as the idle watchdog (`0` = never force-stop during a tool call) |
-| Codex semantic inactivity timeout | `--codex-semantic-inactivity-timeout` | `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `10m` |
+| Codex semantic inactivity timeout | `--codex-semantic-inactivity-timeout` | `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as the idle watchdog (Codex's timer is not tool-aware, so it tracks the larger of the idle / tool budgets) |
| Codex first-turn no-progress timeout | — | `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` (keeps the built-in `60s` ceiling) |
| Codex handshake timeout | `--codex-handshake-timeout` | `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` |
| OpenCode idle watchdog | — | `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` (`0` falls back to the generic idle watchdog; cannot extend it) |
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index 841eccbda4..04c8fd4f87 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -60,7 +60,7 @@ multica daemon start
ランタイムがオフラインのとき:
-- キュー済みのタスクは、デフォルトで最長 2 時間、ランタイムの復帰を待ちます(`MULTICA_TASK_QUEUED_TTL` で変更可能、[環境変数](/environment-variables))。
+- キュー済みのタスクはランタイムの復帰を待ちます。失敗するのは、そのランタイムが再接続猶予を超えてハートビートを停止し、**かつ**タスク自身も同じ時間キューで待った場合のみです。したがって単に取り込み中のランタイムは滞留分を保持し続け、すでにオフラインのランタイムに割り当てられた作業にも猶予がまるまる 1 回分残ります。
- 実行中だったタスクは失敗します。条件を満たすイシューまたはチャットのタスクは自動リトライできます。
- デーモンが再起動すると、ランタイムを再登録し、前回正常に終了しなかったタスクを回収します。
- 7 日を超えてオフラインで、(アーカイブ済みを含め)どのエージェントにも紐づいていないランタイムは、自動的にクリーンアップされます。
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index 058743ce0b..d8220a147f 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -60,7 +60,7 @@ multica daemon start
런타임이 오프라인일 때는 다음과 같이 처리됩니다.
-- 이미 큐에 들어간 태스크는 런타임이 복구될 때까지 기본값으로 최대 2시간 기다립니다(`MULTICA_TASK_QUEUED_TTL`로 조정 가능, [환경 변수](/environment-variables)).
+- 이미 큐에 들어간 태스크는 런타임이 복구될 때까지 기다립니다. 해당 런타임이 재연결 유예를 넘겨 하트비트를 멈추고 **동시에** 태스크도 그만큼 기다린 뒤에만 실패하므로, 단지 바쁜 런타임은 밀린 작업을 그대로 유지하고 이미 오프라인인 런타임에 배정된 작업도 온전한 유예를 한 번 갖습니다.
- 실행 중인 태스크는 실패합니다. 조건을 만족하는 이슈 또는 대화 태스크는 자동으로 재시도될 수 있습니다.
- 데몬이 다시 시작되면 런타임을 재등록하고 이전에 정상적으로 끝나지 않은 태스크를 회수합니다.
- 7일 넘게 오프라인이고 연결된 에이전트가 하나도 없는 런타임은 보관된 에이전트까지 확인한 뒤 자동으로 정리됩니다.
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index b5550dcc9c..113617ebec 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -60,7 +60,7 @@ The daemon sends a heartbeat every 15 seconds. The server combines heartbeats an
When a runtime is offline:
-- Tasks already queued wait for the runtime to recover, for up to 2 hours by default (adjustable via `MULTICA_TASK_QUEUED_TTL`, see [Environment variables](/environment-variables)).
+- Tasks already queued wait for the runtime to recover. They fail only once it has stopped heartbeating for longer than the reconnect grace **and** the task has itself been queued that long, so a runtime that is merely busy keeps its backlog, and work assigned to an already-offline runtime still gets a full grace to wait.
- Tasks that were running fail; eligible issue or chat tasks can retry automatically.
- When the daemon starts again, it re-registers its runtimes and reclaims tasks that did not end cleanly last time.
- A runtime offline for more than 7 days with no agents bound to it (including archived ones) is cleaned up automatically.
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index 12c2827c06..6cb982c7bb 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -60,7 +60,7 @@ multica daemon start
运行时离线时:
-- 已经排队的 task 会等待运行时恢复,默认最多保留 2 小时(可用 `MULTICA_TASK_QUEUED_TTL` 调整,见[环境变量](/environment-variables))。
+- 已经排队的 task 会等待运行时恢复,只有当它心跳缺席超过重连宽限期**且**该 task 自己也已排队满这么久时才会失败;所以运行时只是忙的话积压会一直保留,指派给已离线运行时的工作也仍然有完整一个宽限期可以等待。
- 正在执行的 task 会失败;符合条件的 issue 或对话 task 可以自动重试。
- 守护进程重新启动后,会重新注册运行时,并回收上一次没有正常结束的 task。
- 离线超过 7 天且没有任何智能体(包括已归档的)绑定的运行时,会被自动清理。
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index ecaec84fd8..545cca3de1 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -42,7 +42,6 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `LOG_LEVEL` | アプリのデフォルト | ログレベル |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 終了シグナル受信後、グレースフルシャットダウンを開始するまでの待機時間 |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | オフラインのランタイムが処理中の作業を失敗させずに再接続できる猶予時間。`150s` 未満は `150s` に補正されます |
-| `MULTICA_TASK_QUEUED_TTL` | `2h` | タスクがキュー内でクレームされずに置かれることのできる最長時間。超過すると `queued_expired` で失敗します。低並行度のランタイムが長時間実行中の作業の後ろに正当に待機しうる場合は大きくしてください |
Kubernetes で shutdown hold を設定する場合、`terminationGracePeriodSeconds` は hold と実際のシャットダウンにかかる時間の合計より大きくしてください。
@@ -230,7 +229,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に
| `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | 出力もツール実行もない状態の静穏上限。`0` で watchdog 全体を無効化 |
| `MULTICA_AGENT_TOOL_WATCHDOG` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | 単一のツール呼び出しが静穏なままでいられる上限。モデルより長い余裕をツールに与えたい場合のみ設定し、`0` はツール実行中に強制停止しません |
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 専用の静穏しきい値 |
-| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `10m` | Codex のセマンティック静穏しきい値 |
+| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | Codex のセマンティック静穏しきい値。Codex 自身のタイマーはツール実行中かどうかを判別できないため、独自の短い上限を持たず idle / tool 予算の大きい方に追従します |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 初回ターンの無進捗上限を明示的に上書き;`0` はデフォルトを維持。実効の初回ターン待機は依然として `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` と全体の実行タイムアウトに制限される——`MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` をこの値より厳密に大きく(余裕を持たせて)設定すること。さもないと待機はその値で打ち切られ、モデルカタログの起動リトライがスキップされる。同値では不十分:セマンティックタイマーが先に起動するため、同値の場合でもリトライが失われることがある |
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 起動ハンドシェイクの上限 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud は `true`、セルフホストは `false` | CLI の更新を自動でチェックして適用するか |
@@ -272,7 +271,7 @@ multica config show
| `poll_interval` | `30s` | タスクのポーリング間隔 |
| `heartbeat_interval` | `15s` | ハートビート間隔 |
| `agent_timeout` | 無制限 | 1 回の実行の絶対時間上限 |
-| `codex_semantic_inactivity_timeout` | `10m` | Codex のセマンティック静穏しきい値 |
+| `codex_semantic_inactivity_timeout` | 派生値 | Codex のセマンティック静穏しきい値。未設定なら idle と tool の watchdog 予算のうち大きい方を採用し、tool 予算が `0` の場合は idle 予算に回帰します。Codex 自身の `10m` が残るのは watchdog 一式を無効化したときだけです |
| `codex_handshake_timeout` | `30s` | Codex app-server ハンドシェイクの上限 |
| `disable_auto_update` | 環境に従う | `true` で自動更新を無効化。`false` はローカルの上書きをクリアし、環境変数またはデフォルトに戻します |
| `auto_update_check_interval` | `6h` | 更新チェックの間隔 |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index a58dac8a17..4144cb0715 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -42,7 +42,6 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `LOG_LEVEL` | 앱 기본값 | 로그 수준 |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 종료 신호를 받은 뒤 graceful shutdown을 시작하기 전 대기 시간 |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | 오프라인 런타임이 진행 중인 작업을 실패시키지 않고 재연결할 수 있는 유예 시간. `150s` 미만은 `150s`로 조정됨 |
-| `MULTICA_TASK_QUEUED_TTL` | `2h` | 태스크가 대기열에 점유되지 않고 머물 수 있는 최대 시간. 초과 시 `queued_expired`로 실패. 저 동시성 런타임이 긴 작업 뒤에 합리적으로 대기할 수 있으므로 이 경우 값을 키워야 함 |
Kubernetes에서 shutdown hold를 설정하면 `terminationGracePeriodSeconds`가 hold와 실제 종료에 필요한 시간의 합보다 커야 합니다.
@@ -230,7 +229,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스
| `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | 출력과 도구 실행이 모두 없을 때의 무응답 상한. `0`이면 watchdog 전체가 비활성화됩니다 |
| `MULTICA_AGENT_TOOL_WATCHDOG` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | 단일 도구 호출이 계속 무응답인 시간 상한. 모델보다 도구에 더 여유를 주고 싶을 때만 따로 설정하며, `0`이면 도구 실행 중에는 강제 종료하지 않습니다 |
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 전용 무응답 기준값 |
-| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `10m` | Codex 의미 활동 없음 기준값 |
+| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | Codex 의미 활동 없음 기준값. Codex 자체 타이머는 도구 실행 중인지 알 수 없으므로 별도의 짧은 상한 대신 idle / tool 예산 중 큰 값을 따릅니다 |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 첫 턴 무진행 상한의 명시적 재정의; `0` 은 기본값 유지. 실제 첫 턴 대기는 여전히 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 및 전체 실행 타임아웃으로 제한됨 — `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 을 이 값보다 엄격히 크게(여유를 두고) 설정해야 하며, 그렇지 않으면 대기가 그 값으로 잘리고 모델 카탈로그 시작 재시도가 건너뛰어짐. 값이 같으면 충분하지 않음: 의미 타이머가 먼저 시작되므로 값이 같을 때도 재시도가 손실될 수 있음 |
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 시작 handshake 상한 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`, 자체 호스팅 `false` | CLI 자동 확인 및 업데이트 여부 |
@@ -272,7 +271,7 @@ multica config show
| `poll_interval` | `30s` | 실행 태스크 polling 간격 |
| `heartbeat_interval` | `15s` | heartbeat 간격 |
| `agent_timeout` | 제한 없음 | 단일 실행의 절대 시간 제한 |
-| `codex_semantic_inactivity_timeout` | `10m` | Codex 의미 활동 없음 기준값 |
+| `codex_semantic_inactivity_timeout` | 파생 | Codex 의미 활동 없음 기준값. 설정하지 않으면 idle과 tool watchdog 예산 중 큰 값을 따르고, tool 예산이 `0`이면 idle 예산으로 되돌아갑니다. Codex 자체의 `10m`은 watchdog 전체를 비활성화했을 때만 유지됩니다 |
| `codex_handshake_timeout` | `30s` | Codex app-server handshake 상한 |
| `disable_auto_update` | 환경을 따름 | `true`는 자동 업데이트를 끔. `false`는 로컬 덮어쓰기를 지우고 환경 변수 또는 기본값으로 복귀 |
| `auto_update_check_interval` | `6h` | 업데이트 확인 간격 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 1eac3a4831..59d65253aa 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -42,7 +42,6 @@ You also need to pick an email service, otherwise verification codes and invitat
| `LOG_LEVEL` | application default | Log level |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | How long to wait after a termination signal before graceful shutdown begins |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | How long an offline runtime may reconnect before its in-flight tasks fail; values below `150s` are clamped |
-| `MULTICA_TASK_QUEUED_TTL` | `2h` | How long a task may sit in the queue unclaimed before failing with `queued_expired`; raise it when low-concurrency runtimes can legitimately wait behind long-running work |
When setting a shutdown hold on Kubernetes, `terminationGracePeriodSeconds` must exceed the hold plus the time the actual shutdown needs.
@@ -230,7 +229,7 @@ The variables below are read on the computer that runs your agents, not in the A
| `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | Silence ceiling with no output and no tool execution; `0` disables the watchdog entirely |
| `MULTICA_AGENT_TOOL_WATCHDOG` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Silence ceiling for a single tool call; set it only to give tools more room than the model gets, `0` never force-stops a tool call |
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode-specific silence threshold |
-| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `10m` | Codex semantic-silence threshold |
+| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Codex semantic-silence threshold. Codex's own timer cannot see that a tool is running, so it tracks the larger of the idle / tool budgets instead of holding a separate, shorter ceiling |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Explicit override for the Codex first-turn no-progress ceiling; `0` keeps the default. The effective first-turn wait stays bounded by `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` and the overall execution timeout — set `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` strictly above this value (with some margin), or the wait is truncated to it and the model-catalog startup retry is skipped. Equal values are not enough: the semantic timer is armed first, so at equal durations the retry can still be lost |
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server startup handshake ceiling |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`; self-hosted `false` | Whether to check for and apply CLI updates automatically |
@@ -272,7 +271,7 @@ Supported keys:
| `poll_interval` | `30s` | Task polling interval |
| `heartbeat_interval` | `15s` | Heartbeat interval |
| `agent_timeout` | unlimited | Absolute time limit per run |
-| `codex_semantic_inactivity_timeout` | `10m` | Codex semantic-silence threshold |
+| `codex_semantic_inactivity_timeout` | derived | Codex semantic-silence threshold. With nothing set it takes the larger of the idle and tool watchdog budgets; a tool budget of `0` falls back to the idle budget, and only when the whole watchdog suite is disabled does Codex keep its own `10m` |
| `codex_handshake_timeout` | `30s` | Codex app-server handshake ceiling |
| `disable_auto_update` | follows environment | `true` turns auto-update off; `false` clears the local override and returns to the env var or default |
| `auto_update_check_interval` | `6h` | Update check interval |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index f5cf16a758..63cb85a613 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -42,7 +42,6 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `LOG_LEVEL` | 应用默认 | 日志级别 |
| `MULTICA_SHUTDOWN_HOLD_DURATION` | `0` | 收到终止信号后,开始优雅退出前等待多久 |
| `MULTICA_RUNTIME_RECONNECT_GRACE` | `3h` | 运行时离线后可重新连接且不终止在途 task 的宽限时间;低于 `150s` 时按 `150s` 处理 |
-| `MULTICA_TASK_QUEUED_TTL` | `2h` | task 在队列中无人认领的最长时长,超过后以 `queued_expired` 失败;低并发运行时可能合理地排在长任务之后,此时应调大 |
在 Kubernetes 中设置 shutdown hold 时,`terminationGracePeriodSeconds` 要大于 hold 与实际退出所需时间之和。
@@ -230,7 +229,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游
| `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` | 没有输出且没有工具执行时的静默上限;`0` 表示整套 watchdog 关闭 |
| `MULTICA_AGENT_TOOL_WATCHDOG` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | 单个工具调用持续静默的上限;只有希望工具比模型有更多余量时才单独设置,`0` 表示工具执行期间永不强制停止 |
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 专用静默阈值 |
-| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `10m` | Codex 语义静默阈值 |
+| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | Codex 语义静默阈值。Codex 自己的计时器看不到工具是否在执行,因此跟随 idle / tool 预算中较大的那个,而不再单独保留一个更短的上限 |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | 显式覆盖 Codex 首轮无进展上限;`0` 保持默认值。实际首轮等待仍受 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 和总执行超时限制——需将 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 设为严格大于此值(并留出余量),否则等待会被截断至该值,且会跳过模型目录启动重试。设为相等还不够:语义计时器先启动,两者相等时仍可能丢失该重试 |
| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 启动握手上限 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`;自托管 `false` | 是否自动检查并更新 CLI |
@@ -272,7 +271,7 @@ multica config show
| `poll_interval` | `30s` | 执行任务轮询间隔 |
| `heartbeat_interval` | `15s` | 心跳间隔 |
| `agent_timeout` | 不限制 | 单次执行的绝对时限 |
-| `codex_semantic_inactivity_timeout` | `10m` | Codex 语义静默阈值 |
+| `codex_semantic_inactivity_timeout` | 派生 | Codex 语义静默阈值。未设置时取 idle 与 tool watchdog 预算中较大的那个;tool 预算为 `0` 时回落到 idle 预算;只有整套 watchdog 关闭时才保留 Codex 自己的 `10m` |
| `codex_handshake_timeout` | `30s` | Codex app-server 握手上限 |
| `disable_auto_update` | 跟随环境 | `true` 关闭自动更新;`false` 清除本地覆盖,回到环境变量或默认 |
| `auto_update_check_interval` | `6h` | 检查更新的间隔 |
diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdx
index 445267f022..156148eee5 100644
--- a/apps/docs/content/docs/tasks.ja.mdx
+++ b/apps/docs/content/docs/tasks.ja.mdx
@@ -45,7 +45,7 @@ import { Callout } from "fumadocs-ui/components/callout";
| `failed` | 実行がエラーになったか中断された |
| `cancelled` | 実行が手動で停止された |
-ランタイムがオンラインなら、新しいタスクは通常すぐに始まります。キューに入ったあとでランタイムがオフラインになった場合、タスクは復帰までキューで待機します。2 時間(デフォルト)を超えて取得されないタスクは失敗として終了します。上限は `MULTICA_TASK_QUEUED_TTL` で変更できます([環境変数](/environment-variables))。
+ランタイムがオンラインなら、新しいタスクは通常すぐに始まります。キューに入ったあとでランタイムがオフラインになった場合、タスクは復帰までキューで待機します。待ち時間の長さ自体では失効しません。ハートビートを送り続けているランタイムは「いなくなった」のではなく「取り込み中」なので、その滞留分は必要なだけ待てます。キュー内のタスクが失敗するのは、担当ランタイムが再接続猶予を超えて沈黙し、**かつ**そのタスク自身も同じ時間だけキューで待った場合だけです。2 つ目の条件は「すでに休止中のマシンに割り当てたとき」のためのもので、その場合もタスクは即座に失敗せず、マシンを復帰させるための猶予をまるまる 1 回分確保します。
<Callout type="info">
トリガーの前の時点で対象ランタイムのオフラインが分かっている場合、一部の即時操作は、誰も取得できないタスクを作成する代わりに、いまは実行できない旨をその場で表示します。
@@ -94,7 +94,7 @@ import { Callout } from "fumadocs-ui/components/callout";
| 原因 | 意味 | 対処 |
| --- | --- | --- |
| `runtime_offline` | 実行中にランタイムがオフラインになった | ランタイムを復旧してからリトライ。[デーモンとランタイム](/daemon-runtimes)を参照 |
-| `queued_expired` | ランタイムに取得されないまま未取得上限(デフォルト 2 時間、`MULTICA_TASK_QUEUED_TTL` で変更可能)を超えてキューで待機した | ランタイムがオンラインであることを確認してからリトライ |
+| `queued_expired` | ランタイムが再接続猶予を超えてハートビートを停止し、かつそのタスクも同じ時間キューで待っていた | ランタイムがオンラインであることを確認してからリトライ |
| `runtime_recovery` | デーモンが再起動後、中断された実行を回収した | そのままリトライ |
| `cancelled` | 手動で停止されたか、アーカイブ・削除に伴ってキャンセルされた | 対処不要 |
| `timeout` | デーモンに設定された実行時間の上限を超えた | イシューの範囲を狭めるか、デーモンの `agent_timeout` を調整する |
@@ -149,7 +149,7 @@ multica issue rerun <issue-id>
| 状態 | 意味 | タイムアウトと結果 |
| --- | --- | --- |
| `deferred` | 後で発火するようスケジュール済み | 予定時刻になると `queued` に入り、以降は下のルールに従う |
-| `queued` | ランタイムによる取得待ち | **2 時間(デフォルト)**取得されないと失敗として終了し(`MULTICA_TASK_QUEUED_TTL` で上限を変更可)、自動リトライされない |
+| `queued` | ランタイムによる取得待ち | ランタイムがハートビートを送り続けている限り待機し、さらにどの場合でもキュー投入から最低 1 回分の再接続猶予は確保される。両方の期間が過ぎたときにのみ失敗し、自動リトライはされない |
| `dispatched` | ランタイムが取得し、ツールを起動中 | **5 分**を超えてこの状態に留まると失敗として扱われる |
| `waiting_local_directory` | ローカルディレクトリロックの解放待ち | 独自のタイムアウトはなし。ディレクトリが解放されると起動フローに戻る |
| `running` | AI コーディングツールが実行中 | 固定の時間上限はなし。生存はランタイムのハートビート(15 秒ごと)で判定し、ハートビートを失ったランタイムは遅くとも約 3 分でオフラインと判定され、その上のタスクも失敗する |
diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdx
index 6280101aff..6fa1103819 100644
--- a/apps/docs/content/docs/tasks.ko.mdx
+++ b/apps/docs/content/docs/tasks.ko.mdx
@@ -45,7 +45,7 @@ import { Callout } from "fumadocs-ui/components/callout";
| `failed` | 실행 중 오류가 발생했거나 중단되었습니다. |
| `cancelled` | 실행을 수동으로 중지했습니다. |
-런타임이 온라인이면 새 태스크가 보통 빠르게 시작됩니다. 태스크가 큐에 들어간 뒤 런타임이 오프라인이 되면 복구될 때까지 큐에서 기다립니다. 기본값인 2시간이 넘게 수령되지 않으면 태스크가 실패로 끝납니다. 상한은 `MULTICA_TASK_QUEUED_TTL`로 조정할 수 있습니다([환경 변수](/environment-variables)).
+런타임이 온라인이면 새 태스크가 보통 빠르게 시작됩니다. 태스크가 큐에 들어간 뒤 런타임이 오프라인이 되면 복구될 때까지 큐에서 기다립니다. 오래 기다렸다는 이유만으로 만료되지는 않습니다. 하트비트를 계속 보내는 런타임은 사라진 것이 아니라 바쁜 것이므로, 밀린 작업은 필요한 만큼 기다릴 수 있습니다. 큐의 태스크는 담당 런타임이 재연결 유예를 넘겨 조용해지고 **동시에** 그 태스크 자신도 그만큼 큐에서 기다린 경우에만 실패합니다. 두 번째 조건은 이미 잠들어 있는 기기에 작업을 배정한 경우를 위한 것으로, 이때도 태스크는 곧바로 실패하지 않고 기기를 깨울 수 있도록 유예를 온전히 한 번 확보합니다.
<Callout type="info">
트리거하기 전에 대상 런타임이 오프라인임을 시스템이 이미 아는 경우 일부 즉시 실행 작업은 수령할 수 없는 태스크를 만들지 않고 현재 실행할 수 없다고 바로 알립니다.
@@ -94,7 +94,7 @@ heartbeat가 정상인 런타임은 장시간 태스크도 실행할 수 있으
| 원인 | 의미 | 처리 방법 |
| --- | --- | --- |
| `runtime_offline` | 실행 중 런타임이 오프라인이 됨 | 런타임을 복구한 뒤 재시도합니다. [데몬과 런타임](/daemon-runtimes) 참고 |
-| `queued_expired` | 수령 상한(기본 2시간, `MULTICA_TASK_QUEUED_TTL`로 조정 가능)을 넘겨서 런타임이 가져가지 않음 | 런타임이 온라인인지 확인한 뒤 재시도 |
+| `queued_expired` | 런타임이 재연결 유예를 넘겨 하트비트를 멈췄고, 태스크도 그만큼 큐에서 기다림 | 런타임이 온라인인지 확인한 뒤 재시도 |
| `runtime_recovery` | 데몬 재시작 후 중단된 실행을 회수함 | 바로 재시도 |
| `cancelled` | 수동으로 중지되었거나 보관 또는 삭제와 함께 취소됨 | 별도 처리 불필요 |
| `timeout` | 데몬에 설정된 실행 시간 상한을 초과함 | 이슈 범위를 줄이거나 데몬의 `agent_timeout` 조정 |
@@ -149,7 +149,7 @@ multica issue rerun <issue-id>
| 상태 | 의미 | timeout과 결과 |
| --- | --- | --- |
| `deferred` | 나중에 트리거되도록 예약됨 | 예정 시간이 되면 `queued`로 들어가고 이후 아래 규칙에 따라 시간을 계산합니다. |
-| `queued` | 런타임이 가져가기를 기다림 | **2시간(기본값)** 넘게 수령되지 않으면 실패로 끝나며(`MULTICA_TASK_QUEUED_TTL`로 상한 조정 가능) 자동 재시도하지 않습니다. |
+| `queued` | 런타임이 가져가기를 기다림 | 런타임이 하트비트를 보내는 동안에는 계속 기다리고, 어떤 경우에도 큐에 들어간 뒤 최소 한 번의 재연결 유예는 확보합니다. 두 기간이 모두 지난 뒤에만 실패하며 자동 재시도하지 않습니다. |
| `dispatched` | 런타임이 가져갔고 도구를 시작 중 | **5분** 넘게 머물면 실패로 처리합니다. |
| `waiting_local_directory` | 로컬 디렉터리 잠금 해제를 기다림 | 별도 timeout이 없으며 디렉터리가 해제되면 시작 과정으로 돌아갑니다. |
| `running` | AI 코딩 도구 실행 중 | 고정 시간 상한이 없습니다. 런타임 heartbeat로 생존을 판단하며 15초마다 heartbeat를 보냅니다. heartbeat를 잃은 런타임은 늦어도 약 3분 뒤 오프라인으로 판단되고 그 위의 태스크도 실패합니다. |
diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdx
index ff2dbb815f..b7667f9e24 100644
--- a/apps/docs/content/docs/tasks.mdx
+++ b/apps/docs/content/docs/tasks.mdx
@@ -45,7 +45,7 @@ A task typically moves through these states:
| `failed` | The run errored or was interrupted |
| `cancelled` | The run was stopped manually |
-When the runtime is online, a new task usually starts quickly; if the runtime goes offline after the task enters the queue, the task stays queued until it recovers. A task left unclaimed for more than 2 hours by default ends as failed; the limit is adjustable via `MULTICA_TASK_QUEUED_TTL` ([Environment variables](/environment-variables)).
+When the runtime is online, a new task usually starts quickly; if the runtime goes offline after the task enters the queue, the task stays queued until it recovers. Queued work is not expired for waiting too long — a runtime that keeps heartbeating is busy, not gone, so its backlog is allowed to drain however long that takes. A queued task fails only when **both** are true: its runtime has been silent past the reconnect grace, **and** the task itself has been queued that long. The second condition matters when you assign work to a machine that is already asleep — the task still gets a full grace for you to bring it back, rather than failing straight away.
<Callout type="info">
If the system already knows the target runtime is offline before triggering, some immediate actions report that the run cannot start right now instead of creating a task nothing can claim.
@@ -94,7 +94,7 @@ The failure reasons shown in the execution log and usage stats fall into two gro
| Reason | Meaning | What to do |
| --- | --- | --- |
| `runtime_offline` | The runtime went offline during the run | Restore the runtime and retry; see [Daemon and runtimes](/daemon-runtimes) |
-| `queued_expired` | Queued past the unclaimed limit (2 hours by default, adjustable via `MULTICA_TASK_QUEUED_TTL`) with no runtime claiming it | Confirm the runtime is online, then retry |
+| `queued_expired` | The runtime stopped heartbeating for longer than the reconnect grace, and the task had also been queued that long | Confirm the runtime is online, then retry |
| `runtime_recovery` | The daemon reclaimed an interrupted run after restarting | Retry directly |
| `cancelled` | Stopped manually, or cancelled along with an archive or delete | Nothing to do |
| `timeout` | Exceeded the daemon's configured execution time limit | Narrow the issue scope, or adjust the daemon's `agent_timeout` |
@@ -149,7 +149,7 @@ The numbers below reflect the server's default configuration, for quick cross-ch
| State | Meaning | Timeout and consequence |
| --- | --- | --- |
| `deferred` | Scheduled to fire later | Enters `queued` at the scheduled time, then the rules below apply |
-| `queued` | Waiting for a runtime to claim it | Fails after **2 hours by default** unclaimed (limit settable via `MULTICA_TASK_QUEUED_TTL`); not retried automatically |
+| `queued` | Waiting for a runtime to claim it | Waits as long as its runtime keeps heartbeating, and in every case for at least one reconnect grace after being queued; fails only when both windows have passed, and is not retried automatically |
| `dispatched` | Claimed; the tool is starting | Treated as failed after more than **5 minutes** in this state |
| `waiting_local_directory` | Waiting for the local directory lock to release | No timeout of its own; returns to the startup flow once the directory is released |
| `running` | The AI coding tool is executing | No fixed duration cap; liveness follows the runtime heartbeat — one every 15 seconds; a runtime that loses its heartbeat is marked offline within about 3 minutes at the latest, and its tasks fail with it |
diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdx
index c9c44f13ed..3cf2d08730 100644
--- a/apps/docs/content/docs/tasks.zh.mdx
+++ b/apps/docs/content/docs/tasks.zh.mdx
@@ -45,7 +45,7 @@ Issue 保存一项工作的目标、讨论、负责人和最终状态;执行
| `failed` | 执行出错或中断 |
| `cancelled` | 执行被手动停止 |
-运行时在线时,新 task 通常会很快开始;如果 task 入队后运行时离线,它会留在队列中等待恢复。排队超过 2 小时(默认值)仍未被领取时,task 会以失败结束;该上限可通过 `MULTICA_TASK_QUEUED_TTL` 调整(见[环境变量](/environment-variables))。
+运行时在线时,新 task 通常会很快开始;如果 task 入队后运行时离线,它会留在队列中等待恢复。排队本身不会导致过期——运行时只要还在心跳就说明它是忙,不是没了,它的积压可以排多久就排多久。只有**同时**满足两个条件,排队中的 task 才会失败:绑定的运行时心跳缺席超过重连宽限期,**并且**该 task 自己也已经排队满这么久。第二个条件针对的是「指派给一台已经休眠的机器」——这种情况下 task 仍然会获得完整的一个宽限期供你把机器唤醒,而不是立刻失败。
<Callout type="info">
如果系统在触发前已经知道目标运行时离线,部分即时操作会直接提示当前无法运行,而不是继续创建一条无法领取的 task。
@@ -94,7 +94,7 @@ issue 产生的所有 task 都列在 issue 右侧栏的 **执行日志**里,
| 原因 | 含义 | 处理 |
| --- | --- | --- |
| `runtime_offline` | 执行期间运行时离线 | 恢复运行时后重试,见[守护进程与运行时](/daemon-runtimes) |
-| `queued_expired` | 排队超过领取上限(默认 2 小时,可用 `MULTICA_TASK_QUEUED_TTL` 调整)无运行时领取 | 确认运行时在线后重试 |
+| `queued_expired` | 运行时心跳缺席超过重连宽限期,且该 task 也已排队满这么久 | 确认运行时在线后重试 |
| `runtime_recovery` | 守护进程重启后回收了中断的执行 | 直接重试 |
| `cancelled` | 被手动停止,或随归档、删除一并取消 | 无需处理 |
| `timeout` | 超过守护进程配置的执行时长上限 | 缩小 issue 范围,或调整守护进程的 `agent_timeout` |
@@ -149,7 +149,7 @@ Issue 是否完成,以实际工作进展和它的状态为准。
| 状态 | 含义 | 超时与后果 |
| --- | --- | --- |
| `deferred` | 已安排稍后触发 | 到达预定时间后进入 `queued`,再按下面的规则计时 |
-| `queued` | 等待运行时领取 | 超过 **2 小时(默认值)**未被领取即以失败结束(可用 `MULTICA_TASK_QUEUED_TTL` 调整),不会自动重试 |
+| `queued` | 等待运行时领取 | 只要运行时还在心跳就一直等待,并且无论如何都会在入队后至少保留一个重连宽限期;两个窗口都过去才会失败,且不会自动重试 |
| `dispatched` | 运行时已领取,正在启动工具 | 停留超过 **5 分钟**按失败处理 |
| `waiting_local_directory` | 等待本地目录锁释放 | 没有独立超时;目录释放后回到启动流程 |
| `running` | AI 编程工具正在执行 | 不设固定时长上限;以运行时心跳判定存活,心跳每 15 秒一次,失去心跳的运行时最迟约 3 分钟被判为离线,其上的 task 随之失败 |
diff --git a/apps/docs/content/docs/troubleshooting.ja.mdx b/apps/docs/content/docs/troubleshooting.ja.mdx
index 14fa7e703c..ba2d22ca7a 100644
--- a/apps/docs/content/docs/troubleshooting.ja.mdx
+++ b/apps/docs/content/docs/troubleshooting.ja.mdx
@@ -67,7 +67,7 @@ multica config show
3. エージェントに利用可能な同時実行枠が残っているか。
4. デーモンに全体の実行キャパシティが残っているか。
-エージェントはデフォルトで最大 6 件、1 つのデーモンはデフォルトで最大 20 件のタスクを同時に実行します。上限に達すると、新しいタスクは実行中のものが終わるまでキューに残ります。ランタイムがオフラインの間もタスクはキューに残り続け、2 時間(デフォルト)を超えて引き受けられなかった場合にのみ失敗します(上限は `MULTICA_TASK_QUEUED_TTL` で変更可能、[環境変数](/environment-variables))。
+エージェントはデフォルトで最大 6 件、1 つのデーモンはデフォルトで最大 20 件のタスクを同時に実行します。上限に達すると、新しいタスクは実行中のものが終わるまでキューに残ります。ランタイムがオフラインの間もタスクはキューに残り続け、そのランタイムが再接続猶予を超えてハートビートを停止し、かつタスク自身も同じ時間待った場合にのみ失敗します。取り込み中のランタイムの後ろに長い待ち行列ができても待ち時間を理由に失効することはなく、すでにオフラインのマシンに割り当てた場合も復帰させるための猶予がまるまる 1 回分残ります。
```bash
multica daemon status --output json
diff --git a/apps/docs/content/docs/troubleshooting.ko.mdx b/apps/docs/content/docs/troubleshooting.ko.mdx
index 8eb69f5208..21471aa9cb 100644
--- a/apps/docs/content/docs/troubleshooting.ko.mdx
+++ b/apps/docs/content/docs/troubleshooting.ko.mdx
@@ -67,7 +67,7 @@ multica config show
3. 에이전트에 사용 가능한 동시 실행 용량이 남아 있는지
4. 데몬에 전체 실행 용량이 남아 있는지
-에이전트 한 명은 기본적으로 실행 태스크를 최대 6개까지 동시에 실행하고 데몬 하나는 최대 20개까지 실행합니다. 상한에 도달하면 새 실행 태스크는 큐에 남아 기존 실행이 끝난 뒤 시작됩니다. 런타임이 오프라인이어도 실행 태스크는 계속 대기하며 기본값인 2시간 넘게 수령되지 않을 때만 실패합니다(상한은 `MULTICA_TASK_QUEUED_TTL`로 조정 가능, [환경 변수](/environment-variables)).
+에이전트 한 명은 기본적으로 실행 태스크를 최대 6개까지 동시에 실행하고 데몬 하나는 최대 20개까지 실행합니다. 상한에 도달하면 새 실행 태스크는 큐에 남아 기존 실행이 끝난 뒤 시작됩니다. 런타임이 오프라인이어도 실행 태스크는 계속 대기하며, 해당 런타임이 재연결 유예를 넘겨 하트비트를 멈추고 태스크도 그만큼 기다린 뒤에만 실패합니다. 바쁜 런타임 뒤의 긴 대기열이 기다렸다는 이유로 만료되지 않으며, 이미 오프라인인 기기에 배정한 경우에도 깨울 수 있는 유예가 온전히 한 번 남습니다.
```bash
multica daemon status --output json
diff --git a/apps/docs/content/docs/troubleshooting.mdx b/apps/docs/content/docs/troubleshooting.mdx
index 5b0f646df4..863d5ea632 100644
--- a/apps/docs/content/docs/troubleshooting.mdx
+++ b/apps/docs/content/docs/troubleshooting.mdx
@@ -67,7 +67,7 @@ Open the issue's **execution log** and check the task's current status and what
3. Does the agent still have concurrency headroom?
4. Does the daemon still have global execution capacity?
-An agent runs at most 6 tasks concurrently by default; a single daemon runs at most 20. At the limit, new tasks stay in the queue until a running one finishes. Tasks also keep queueing while the runtime is offline; they only fail after going unclaimed for more than 2 hours by default (raise the limit with `MULTICA_TASK_QUEUED_TTL`, see [Environment variables](/environment-variables)).
+An agent runs at most 6 tasks concurrently by default; a single daemon runs at most 20. At the limit, new tasks stay in the queue until a running one finishes. Tasks also keep queueing while the runtime is offline; they only fail once that runtime has stopped heartbeating for longer than the reconnect grace and the task has itself waited that long, so a long queue behind a busy runtime is never expired for waiting, and assigning work to a machine that is already offline still leaves a full grace to bring it back.
```bash
multica daemon status --output json
diff --git a/apps/docs/content/docs/troubleshooting.zh.mdx b/apps/docs/content/docs/troubleshooting.zh.mdx
index 01c0113d06..6cea00762e 100644
--- a/apps/docs/content/docs/troubleshooting.zh.mdx
+++ b/apps/docs/content/docs/troubleshooting.zh.mdx
@@ -67,7 +67,7 @@ multica config show
3. 智能体是否还有可用并发额度;
4. 守护进程是否还有全局执行容量。
-智能体默认最多同时执行 6 条执行任务;单个守护进程默认最多同时执行 20 条。达到上限时,新执行任务会留在队列中,等已有执行结束后再开始。运行时离线时,执行任务也会继续排队;超过 2 小时(默认值)仍未领取才会失败(上限可用 `MULTICA_TASK_QUEUED_TTL` 调整,见[环境变量](/environment-variables))。
+智能体默认最多同时执行 6 条执行任务;单个守护进程默认最多同时执行 20 条。达到上限时,新执行任务会留在队列中,等已有执行结束后再开始。运行时离线时,执行任务也会继续排队;只有该运行时心跳缺席超过重连宽限期、且该执行任务自己也已等满这么久时才会失败;所以排在忙碌运行时后面的长队列不会因为等太久而被判失败,指派给已经离线的机器时也仍然留有完整一个宽限期把它唤醒。
```bash
multica daemon status --output json
diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yaml
index 2cc7be3c07..17156a13ca 100644
--- a/deploy/helm/multica/templates/configmap.yaml
+++ b/deploy/helm/multica/templates/configmap.yaml
@@ -28,7 +28,6 @@ data:
CLOUDFRONT_DOMAIN: {{ .Values.backend.config.cloudfrontDomain | quote }}
CLOUDFRONT_KEY_PAIR_ID: {{ .Values.backend.config.cloudfrontKeyPairId | quote }}
LOCAL_UPLOAD_BASE_URL: {{ .Values.backend.config.localUploadBaseUrl | quote }}
- MULTICA_TASK_QUEUED_TTL: {{ .Values.backend.config.taskQueuedTTL | quote }}
{{- if not .Values.postgres.external.enabled }}
# --- PostgreSQL (consumed by the backend to build DATABASE_URL) ---
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index a2d4fe4470..e0e5550626 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -146,11 +146,6 @@ backend:
cloudfrontDomain: ""
cloudfrontKeyPairId: ""
localUploadBaseUrl: http://api.multica.dev.lan
- # How long a task may sit in the queue unclaimed before failing with
- # `queued_expired`; raise it when a runtime's low task concurrency lets
- # tasks legitimately wait behind long-running work.
- # Accepts a positive duration and empty/unset falls back to the server default of 2h.
- taskQueuedTTL: 2h
resources:
requests:
cpu: 100m
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 374f8b8c69..5bfe06c579 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -100,7 +100,6 @@ services:
MULTICA_DATABASE_CONNECT_TIMEOUT: ${MULTICA_DATABASE_CONNECT_TIMEOUT:-5s}
MULTICA_SHUTDOWN_HOLD_DURATION: ${MULTICA_SHUTDOWN_HOLD_DURATION:-}
MULTICA_RUNTIME_RECONNECT_GRACE: ${MULTICA_RUNTIME_RECONNECT_GRACE:-}
- MULTICA_TASK_QUEUED_TTL: ${MULTICA_TASK_QUEUED_TTL:-}
ALLOW_SIGNUP: ${ALLOW_SIGNUP:-true}
ALLOWED_EMAILS: ${ALLOWED_EMAILS:-}
ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index 4df9c96640..88c9697af7 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -34,17 +34,9 @@ default_config="$(
)"
require_rendered_value "$default_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "true"'
require_rendered_value "$default_config" 'MULTICA_CLOUD_URL: ""'
-require_rendered_value "$default_config" 'MULTICA_TASK_QUEUED_TTL: "2h"'
require_rendered_value "$default_config" 'MULTICA_DATABASE_STARTUP_TIMEOUT: "3m"'
require_rendered_value "$default_config" 'MULTICA_DATABASE_CONNECT_TIMEOUT: "5s"'
-queued_ttl_config="$(
- helm template multica "$CHART_DIR" \
- --show-only templates/configmap.yaml \
- --set-string backend.config.taskQueuedTTL=12h
-)"
-require_rendered_value "$queued_ttl_config" 'MULTICA_TASK_QUEUED_TTL: "12h"'
-
default_backend="$(
helm template multica "$CHART_DIR" \
--show-only templates/backend.yaml
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index a292b4b030..b40c3ce517 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -600,12 +600,10 @@ func main() {
)
runtimeReconnectGrace = minimumRuntimeReconnectGrace
}
- // MULTICA_TASK_QUEUED_TTL lets self-hosted deployments that legitimately
- // hold queued work behind long-running tasks — e.g. a runtime with low
- // task concurrency — raise the built-in 2h queued expiry without losing
- // work to queued_expired failures.
- go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus, runtimeReconnectGrace,
- envDuration("MULTICA_TASK_QUEUED_TTL", defaultTaskQueuedTTL))
+ // Queued work now expires on the same runtime-liveness signal as in-flight
+ // work, so there is no separate queue TTL to tune: a busy runtime keeps its
+ // backlog, and a departed one retires everything it owned at once.
+ go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus, runtimeReconnectGrace)
// Seven-day runtime retention does not share the 30-second liveness tick:
// its bounded transactions run independently once per hour, so a slow GC
// round cannot delay offline detection or task recovery.
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 74f699bd60..b718cb946c 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -85,22 +85,6 @@ const (
// liveness + DB stale + FailTasksForOfflineRuntimes), which typically
// reclaims orphaned tasks within ~180s.
runningTimeoutSeconds = 9000.0
- // defaultTaskQueuedTTL expires tasks that have been sitting in 'queued'
- // for longer than this without ever being claimed. This is the cleanup
- // arm of the MUL-1899 backlog fix: even with the dispatch-time
- // admission gate that blocks new enqueues against offline runtimes,
- // tasks already on the queue when a runtime drops off (or that lost
- // the race against a runtime that went offline mid-tick) need a
- // time-bounded exit. The 2h default was chosen under the historical
- // assumption that it sits conservatively above any reasonable "queued
- // behind a long-running task" window for an online runtime, so the sweep
- // drains the historical 87k autopilot backlog within ~24h without
- // expiring legitimately-pending work. That assumption breaks down for
- // self-hosted deployments whose runtimes have low task concurrency: a
- // single slow task can hold the rest of the queue for longer than 2
- // hours; raise it via MULTICA_TASK_QUEUED_TTL in that case to avoid
- // queued_expired failures.
- defaultTaskQueuedTTL = 2 * time.Hour
// queuedExpireBatchSize caps how many queued rows a single sweeper tick
// transitions to failed. Keeps the sweep transaction short even when
// the historical backlog is large (~89k at MUL-1899 baseline). At 30s
@@ -173,7 +157,7 @@ func runPeriodicSweep(ctx context.Context, interval time.Duration, sweep func())
// hot heartbeat path; the DB is allowed to lag up to runtimeHeartbeatDBFlushInterval).
// When liveness is unavailable or errors, we fall back to trusting the DB
// stale window — that is the original behavior.
-func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration, queuedTTL time.Duration) {
+func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration) {
runPeriodicSweep(ctx, sweepInterval, func() {
// These stages retain the existing cadence and ordering in PR1 so the
// rollout changes no business predicate or recovery semantics. Runtime
@@ -183,7 +167,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handle
sweepOfflineRuntimeTasks(ctx, queries, taskSvc, reconnectGrace)
sweepExpiredRuntimeReconnectRetries(ctx, queries, taskSvc, reconnectGrace)
sweepStaleTasks(ctx, queries, taskSvc, bus, reconnectGrace)
- sweepExpiredQueuedTasks(ctx, queries, taskSvc, queuedTTL)
+ sweepExpiredQueuedTasks(ctx, queries, taskSvc, reconnectGrace)
sweepPendingDelegatedFailureRecoveries(ctx, taskSvc)
sweepDeferredChatFinalizations(ctx, queries, taskSvc)
})
@@ -675,21 +659,22 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.
return
}
-// sweepExpiredQueuedTasks fails tasks that have been sitting in 'queued' for
-// longer than the TTL. Companion to the dispatch-time admission gate added
-// in MUL-1899: that gate prevents new doomed enqueues; this gate drains the
-// historical backlog and catches the race where a runtime goes offline AFTER
-// a task is already queued. Capped to queuedExpireBatchSize per tick so a
-// big backlog can't monopolise the DB.
-func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, queuedTTL time.Duration) (stats runtimeSweepStageStats) {
+// sweepExpiredQueuedTasks fails queued tasks whose runtime has stopped proving
+// it is alive. Companion to the dispatch-time admission gate added in MUL-1899:
+// that gate prevents new doomed enqueues; this one retires work already queued
+// against a runtime that then went away. It deliberately does NOT expire on
+// queue age — a heartbeating runtime is busy, not dead, and MUL-6558 showed a
+// wall clock killing healthy work behind a slow queue. Capped to
+// queuedExpireBatchSize per tick so a big backlog can't monopolise the DB.
+func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) (stats runtimeSweepStageStats) {
startedAt := time.Now()
defer func() {
observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageQueuedExpiry, startedAt, stats)
}()
failedTasks, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
- TtlSecs: queuedTTL.Seconds(),
- MaxPerTick: queuedExpireBatchSize,
+ ReconnectGraceSecs: reconnectGrace.Seconds(),
+ MaxPerTick: queuedExpireBatchSize,
})
if err != nil {
slog.Warn("task sweeper: failed to expire stale queued tasks", "error", err)
diff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.go
index e40d5af949..f512bfd421 100644
--- a/server/cmd/server/runtime_sweeper_test.go
+++ b/server/cmd/server/runtime_sweeper_test.go
@@ -1035,10 +1035,16 @@ func TestSweepDoesNotResetIssueAlreadyInReview(t *testing.T) {
}
}
-// TestExpireStaleQueuedTasks verifies the MUL-1899 queued-TTL sweeper:
-// tasks that have been sitting in 'queued' beyond the TTL are transitioned
-// to 'failed' with failure_reason='queued_expired', while fresh queued tasks
-// are left alone and the per-tick batch limit is respected.
+// TestExpireStaleQueuedTasks pins the queued sweep to runtime liveness rather
+// than queue age (MUL-6558). The same ancient queued task must survive while
+// its runtime is heartbeating — a busy runtime is not a dead one — and only
+// become expirable once that runtime has been silent past the reconnect grace.
+// A third phase covers the other direction: liveness alone is not enough
+// either, because enqueue binds a task to its agent's runtime without checking
+// that the runtime is up. A task assigned to an already-dead runtime must still
+// get its own full grace to wait, or assigning an issue to a laptop that is
+// closed overnight fails inside one sweep tick.
+// A runtime_offline retry stays exempt throughout; FailExpiredRuntimeReconnectRetries owns its exit.
func TestExpireStaleQueuedTasks(t *testing.T) {
if testPool == nil {
t.Skip("no database connection")
@@ -1116,21 +1122,63 @@ func TestExpireStaleQueuedTasks(t *testing.T) {
}
queries := db.New(testPool)
+ const graceSecs = 3600.0
+
+ // Assertions are scoped to this test's own rows: the sweep is now keyed on
+ // the runtime rather than on each row's age, so it legitimately also picks
+ // up queued rows other tests left on the same shared fixture runtime.
+ expiredIDs := func(rows []db.AgentTaskQueue) map[[16]byte]bool {
+ out := map[[16]byte]bool{}
+ for _, row := range rows {
+ out[row.ID.Bytes] = true
+ }
+ return out
+ }
+
+ // Phase 1 — the regression guard. The runtime is heartbeating (the
+ // integration fixture inserts last_seen_at=now()), so none of these rows may
+ // expire, including the 5h-old one. Under the old wall clock it died here.
+ survivors, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
+ ReconnectGraceSecs: graceSecs,
+ MaxPerTick: 100,
+ })
+ if err != nil {
+ t.Fatalf("ExpireStaleQueuedTasks (live runtime) failed: %v", err)
+ }
+ live := expiredIDs(survivors)
+ if live[parseUUIDBytes(oldTaskID)] {
+ t.Fatal("live runtime: the 5h-old queued task was expired — queue age must not expire work behind a heartbeating runtime (MUL-6558)")
+ }
+ if live[parseUUIDBytes(freshTaskID)] {
+ t.Fatal("live runtime: the fresh queued task was expired")
+ }
+
+ // Phase 2 — the runtime goes silent past the grace. Now the queued work it
+ // owned is unreachable and must be retired, except the runtime_offline retry.
+ ageOutAgentRuntime(t, agentID, 5*time.Hour)
failed, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
- TtlSecs: 3600.0, // 1h TTL — old task is 5h, fresh task is 0s
- MaxPerTick: 100,
+ ReconnectGraceSecs: graceSecs,
+ MaxPerTick: 100,
})
if err != nil {
- t.Fatalf("ExpireStaleQueuedTasks failed: %v", err)
+ t.Fatalf("ExpireStaleQueuedTasks (dead runtime) failed: %v", err)
}
- if len(failed) != 1 {
- t.Fatalf("expected exactly 1 expired task, got %d", len(failed))
+ expired := expiredIDs(failed)
+ if !expired[parseUUIDBytes(oldTaskID)] {
+ t.Fatal("dead runtime: the 5h-old queued task should expire once its runtime is gone")
}
- if failed[0].ID.Bytes != parseUUIDBytes(oldTaskID) {
- t.Fatalf("expired the wrong task: got %x", failed[0].ID.Bytes)
+ // The fresh row is the same case as phase 3 seen from the other side: its
+ // runtime is dead, but it has not waited a grace of its own yet, so both
+ // conditions are required and it survives this sweep.
+ if expired[parseUUIDBytes(freshTaskID)] {
+ t.Fatal("dead runtime: a task queued moments ago must still get its own full grace before failing")
+ }
+ if expired[parseUUIDBytes(recoveryTaskID)] {
+ t.Fatal("runtime_offline retry must stay exempt from the queued sweep")
}
- // DB assertions: old → failed/queued_expired, fresh → still queued.
+ // DB assertions: the aged row failed as queued_expired; the fresh row is
+ // still queued because only one of the two conditions holds for it.
var oldStatus, oldReason, oldErr string
if err := testPool.QueryRow(ctx, `
SELECT status, COALESCE(failure_reason, ''), COALESCE(error, '')
@@ -1144,8 +1192,8 @@ func TestExpireStaleQueuedTasks(t *testing.T) {
if oldReason != "queued_expired" {
t.Fatalf("old task: expected failure_reason=queued_expired, got %q", oldReason)
}
- if !strings.Contains(oldErr, "expired in queue") {
- t.Fatalf("old task: expected error to mention expiry, got %q", oldErr)
+ if !strings.Contains(oldErr, "runtime unavailable") {
+ t.Fatalf("old task: expected error to name the runtime as the cause, got %q", oldErr)
}
var freshStatus string
@@ -1155,7 +1203,7 @@ func TestExpireStaleQueuedTasks(t *testing.T) {
t.Fatalf("failed to read fresh task: %v", err)
}
if freshStatus != "queued" {
- t.Fatalf("fresh task: expected status=queued, got %q", freshStatus)
+ t.Fatalf("fresh task: expected status=queued (it has not waited a full grace yet), got %q", freshStatus)
}
var recoveryStatus string
@@ -1165,10 +1213,57 @@ func TestExpireStaleQueuedTasks(t *testing.T) {
if recoveryStatus != "queued" {
t.Fatalf("runtime recovery retry: expected status=queued, got %q", recoveryStatus)
}
+
+ // Phase 3 — a task enqueued AFTER the runtime went dark. The runtime has
+ // been silent for hours, so the liveness clause is already satisfied the
+ // moment this row is created; only the row's own age keeps it alive. It
+ // must survive until it has waited a full grace of its own, otherwise
+ // assigning an issue to a machine that is merely asleep fails in ~30s.
+ lateIssueID := mkIssue("Queued TTL test (enqueued after runtime died)")
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE issue_id = $1`, lateIssueID)
+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, lateIssueID)
+ })
+ var lateTaskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, created_at)
+ VALUES ($1, $2, $3, 'queued', 0, now())
+ RETURNING id
+ `, agentID, runtimeID, lateIssueID).Scan(&lateTaskID); err != nil {
+ t.Fatalf("failed to insert late queued task: %v", err)
+ }
+
+ lateSweep, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
+ ReconnectGraceSecs: graceSecs,
+ MaxPerTick: 100,
+ })
+ if err != nil {
+ t.Fatalf("ExpireStaleQueuedTasks (late enqueue) failed: %v", err)
+ }
+ if expiredIDs(lateSweep)[parseUUIDBytes(lateTaskID)] {
+ t.Fatal("a task enqueued against an already-offline runtime was failed immediately; it must get a full reconnect grace of its own to wait")
+ }
+
+ // Once it HAS waited a full grace, it expires like any other.
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue SET created_at = now() - make_interval(secs => $1) WHERE id = $2
+ `, graceSecs+60, lateTaskID); err != nil {
+ t.Fatalf("failed to age the late task: %v", err)
+ }
+ agedSweep, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
+ ReconnectGraceSecs: graceSecs,
+ MaxPerTick: 100,
+ })
+ if err != nil {
+ t.Fatalf("ExpireStaleQueuedTasks (aged late enqueue) failed: %v", err)
+ }
+ if !expiredIDs(agedSweep)[parseUUIDBytes(lateTaskID)] {
+ t.Fatal("a task that waited a full grace against a dead runtime should expire")
+ }
}
// TestExpireStaleQueuedTasksRespectsBatchLimit verifies the per-tick cap so
-// that a large historical backlog cannot monopolise a single sweep.
+// that a large backlog behind a departed runtime cannot monopolise a sweep.
func TestExpireStaleQueuedTasksRespectsBatchLimit(t *testing.T) {
if testPool == nil {
t.Skip("no database connection")
@@ -1219,10 +1314,14 @@ func TestExpireStaleQueuedTasksRespectsBatchLimit(t *testing.T) {
}
}
+ // Nothing is expirable while the runtime heartbeats, so the batch cap can
+ // only be observed once that runtime has been silent past the grace.
+ ageOutAgentRuntime(t, agentID, 5*time.Hour)
+
queries := db.New(testPool)
failed, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
- TtlSecs: 3600.0,
- MaxPerTick: 2, // cap below the backlog
+ ReconnectGraceSecs: 3600.0,
+ MaxPerTick: 2, // cap below the backlog
})
if err != nil {
t.Fatalf("ExpireStaleQueuedTasks failed: %v", err)
diff --git a/server/cmd/server/sweeper_task_timeouts_test.go b/server/cmd/server/sweeper_task_timeouts_test.go
deleted file mode 100644
index 7fbfb40658..0000000000
--- a/server/cmd/server/sweeper_task_timeouts_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package main
-
-import (
- "testing"
- "time"
-)
-
-// TestQueuedTTLFromEnv pins the env parsing for the queued TTL (the same
-// helper and default main passes into runRuntimeSweeper): unset,
-// unparseable, or non-positive values fall back to the documented default
-// so existing deployments behave identically. A zero TTL must stay invalid:
-// it would expire every queued task immediately.
-func TestQueuedTTLFromEnv(t *testing.T) {
- tests := []struct {
- name string
- value string
- want time.Duration
- }{
- {name: "unset keeps the built-in default", value: "", want: 2 * time.Hour},
- {name: "positive duration overrides the default", value: "12h", want: 12 * time.Hour},
- {name: "unparseable value falls back to the default", value: "not-a-duration", want: 2 * time.Hour},
- {name: "non-positive value falls back to the default", value: "0s", want: 2 * time.Hour},
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- t.Setenv("MULTICA_TASK_QUEUED_TTL", tc.value)
-
- got := envDuration("MULTICA_TASK_QUEUED_TTL", defaultTaskQueuedTTL)
- if got != tc.want {
- t.Errorf("MULTICA_TASK_QUEUED_TTL=%q -> %s, want %s", tc.value, got, tc.want)
- }
- })
- }
-}
-
-// TestDefaultTaskQueuedTTL pins the built-in default so the documented 2h
-// window and the code cannot drift apart.
-func TestDefaultTaskQueuedTTL(t *testing.T) {
- if defaultTaskQueuedTTL != 2*time.Hour {
- t.Errorf("defaultTaskQueuedTTL = %s, want 2h", defaultTaskQueuedTTL)
- }
-}
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 82afc6f67b..fba0c88e3f 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -304,7 +304,71 @@ func LoadConfig(overrides Overrides) (Config, error) {
agentTimeout = *overrides.AgentTimeout
}
- codexSemanticInactivityTimeout, err := durationFromEnv("MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT", DefaultCodexSemanticInactivityTimeout)
+ // MULTICA_AGENT_IDLE_WATCHDOG=0 disables the per-task idle watchdog. We
+ // route 0 through durationFromEnv so the operator can opt out without
+ // patching the binary; any positive duration overrides DefaultAgentIdleWatchdog.
+ agentIdleWatchdog, err := durationFromEnv("MULTICA_AGENT_IDLE_WATCHDOG", DefaultAgentIdleWatchdog)
+ if err != nil {
+ return Config{}, err
+ }
+ // MULTICA_OPENCODE_IDLE_WATCHDOG narrows the no-message window for
+ // OpenCode's streamed model responses. Zero removes the provider-specific
+ // override and falls back to MULTICA_AGENT_IDLE_WATCHDOG; positive values
+ // cannot extend the global bound, and the global zero still disables the
+ // whole mechanism.
+ openCodeIdleWatchdog, err := durationFromEnv("MULTICA_OPENCODE_IDLE_WATCHDOG", DefaultOpenCodeIdleWatchdog)
+ if err != nil {
+ return Config{}, err
+ }
+
+ // The in-flight-tool budget defaults to the idle budget: the tool window
+ // only ever existed because 30 min was too short for a real build/install/
+ // test, and now that the idle budget is sized for the longest legitimate
+ // silent step it already covers those.
+ //
+ // The derivation tracks in BOTH directions, which is the point of collapsing
+ // this to one number. Raising MULTICA_AGENT_IDLE_WATCHDOG no longer leaves
+ // tool calls silently pinned to the old ceiling — and lowering it now also
+ // lowers the tool budget, where previously a shortened idle window left
+ // tools at a separate, larger 2h. That second direction is a real behaviour
+ // change for anyone who had deliberately shortened the idle window; the
+ // override below is how they keep the two apart.
+ //
+ // MULTICA_AGENT_TOOL_WATCHDOG still overrides for the deliberate "tools may
+ // run longer than the model may think" case, and 0 keeps its meaning: never
+ // force-stop while a tool is in flight.
+ agentToolWatchdog, err := durationFromEnv("MULTICA_AGENT_TOOL_WATCHDOG", agentIdleWatchdog)
+ if err != nil {
+ return Config{}, err
+ }
+
+ // Codex runs a semantic-inactivity timer of its own inside the app-server
+ // protocol, and unlike the daemon's watchdog it is NOT tool-aware: a
+ // commandExecution that emits nothing for the whole window trips it even
+ // though a tool is plainly in flight. That one timer therefore stands in
+ // for BOTH daemon watchdogs on a Codex run, so it has to be sized like the
+ // larger of them — otherwise a quiet test suite or an output-buffering
+ // `docker build` dies at the Codex ceiling long before the daemon budget
+ // that was supposed to protect it, and "we raised the budget to 2h" is
+ // simply false for Codex users.
+ //
+ // A tool budget of 0 means "never force-stop while a tool is in flight",
+ // which this timer cannot express — it has no way to see the tool. It falls
+ // back to the idle budget rather than running unbounded, which is the
+ // conservative reading.
+ //
+ // When the whole watchdog suite is disabled (idle = 0), Codex keeps its own
+ // built-in default. Disabling the daemon's watchdogs has never disabled this
+ // timer, and quietly turning it into "unbounded" here would be a much larger
+ // change than this one.
+ codexSemanticDefault := agentIdleWatchdog
+ if agentToolWatchdog > codexSemanticDefault {
+ codexSemanticDefault = agentToolWatchdog
+ }
+ if codexSemanticDefault <= 0 {
+ codexSemanticDefault = DefaultCodexSemanticInactivityTimeout
+ }
+ codexSemanticInactivityTimeout, err := durationFromEnv("MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT", codexSemanticDefault)
if err != nil {
return Config{}, err
}
@@ -353,44 +417,6 @@ func LoadConfig(overrides Overrides) (Config, error) {
codexHandshakeTimeout = overrides.CodexHandshakeTimeout
}
- // MULTICA_AGENT_IDLE_WATCHDOG=0 disables the per-task idle watchdog. We
- // route 0 through durationFromEnv so the operator can opt out without
- // patching the binary; any positive duration overrides DefaultAgentIdleWatchdog.
- agentIdleWatchdog, err := durationFromEnv("MULTICA_AGENT_IDLE_WATCHDOG", DefaultAgentIdleWatchdog)
- if err != nil {
- return Config{}, err
- }
- // MULTICA_OPENCODE_IDLE_WATCHDOG narrows the no-message window for
- // OpenCode's streamed model responses. Zero removes the provider-specific
- // override and falls back to MULTICA_AGENT_IDLE_WATCHDOG; positive values
- // cannot extend the global bound, and the global zero still disables the
- // whole mechanism.
- openCodeIdleWatchdog, err := durationFromEnv("MULTICA_OPENCODE_IDLE_WATCHDOG", DefaultOpenCodeIdleWatchdog)
- if err != nil {
- return Config{}, err
- }
-
- // The in-flight-tool budget defaults to the idle budget: the tool window
- // only ever existed because 30 min was too short for a real build/install/
- // test, and now that the idle budget is sized for the longest legitimate
- // silent step it already covers those.
- //
- // The derivation tracks in BOTH directions, which is the point of collapsing
- // this to one number. Raising MULTICA_AGENT_IDLE_WATCHDOG no longer leaves
- // tool calls silently pinned to the old ceiling — and lowering it now also
- // lowers the tool budget, where previously a shortened idle window left
- // tools at a separate, larger 2h. That second direction is a real behaviour
- // change for anyone who had deliberately shortened the idle window; the
- // override below is how they keep the two apart.
- //
- // MULTICA_AGENT_TOOL_WATCHDOG still overrides for the deliberate "tools may
- // run longer than the model may think" case, and 0 keeps its meaning: never
- // force-stop while a tool is in flight.
- agentToolWatchdog, err := durationFromEnv("MULTICA_AGENT_TOOL_WATCHDOG", agentIdleWatchdog)
- if err != nil {
- return Config{}, err
- }
-
maxConcurrentTasks, err := intFromEnv("MULTICA_DAEMON_MAX_CONCURRENT_TASKS", DefaultMaxConcurrentTasks)
if err != nil {
return Config{}, err
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 12ad5a4125..7068c452be 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -824,6 +824,76 @@ func TestLoadConfig_ToolWatchdogDefaultsToIdleWatchdog(t *testing.T) {
}
}
+// TestLoadConfig_CodexSemanticInactivityDerivesFromWatchdog pins the fix for
+// the gap the 2h change left behind: Codex's own semantic-inactivity timer is
+// not tool-aware, so if it keeps a 10m ceiling it kills a quiet build long
+// before the daemon budget that was supposed to protect it, and the raised
+// budget is a lie for Codex users.
+func TestLoadConfig_CodexSemanticInactivityDerivesFromWatchdog(t *testing.T) {
+ stageFakeAgent(t)
+ for _, key := range []string{
+ "MULTICA_AGENT_IDLE_WATCHDOG",
+ "MULTICA_AGENT_TOOL_WATCHDOG",
+ "MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT",
+ } {
+ t.Setenv(key, "")
+ }
+
+ load := func(t *testing.T) Config {
+ t.Helper()
+ cfg, err := LoadConfig(Overrides{
+ ServerURL: "http://localhost:8080",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig: %v", err)
+ }
+ return cfg
+ }
+
+ cfg := load(t)
+ if cfg.CodexSemanticInactivityTimeout != DefaultAgentIdleWatchdog {
+ t.Fatalf("CodexSemanticInactivityTimeout = %s, want the idle budget %s", cfg.CodexSemanticInactivityTimeout, DefaultAgentIdleWatchdog)
+ }
+
+ // Raising the idle budget carries Codex with it.
+ t.Setenv("MULTICA_AGENT_IDLE_WATCHDOG", "6h")
+ if got := load(t).CodexSemanticInactivityTimeout; got != 6*time.Hour {
+ t.Fatalf("CodexSemanticInactivityTimeout = %s, want 6h", got)
+ }
+
+ // A wider tool budget wins: this timer cannot see that a tool is in flight,
+ // so it has to be sized like the larger of the two or it re-creates the very
+ // bug being fixed, one tier up.
+ t.Setenv("MULTICA_AGENT_TOOL_WATCHDOG", "9h")
+ if got := load(t).CodexSemanticInactivityTimeout; got != 9*time.Hour {
+ t.Fatalf("CodexSemanticInactivityTimeout = %s, want the wider tool budget 9h", got)
+ }
+
+ // A tool budget of 0 means "never force-stop during a tool", which this
+ // timer cannot express; it falls back to the idle budget rather than
+ // silently running unbounded.
+ t.Setenv("MULTICA_AGENT_TOOL_WATCHDOG", "0")
+ if got := load(t).CodexSemanticInactivityTimeout; got != 6*time.Hour {
+ t.Fatalf("CodexSemanticInactivityTimeout = %s, want the idle budget 6h when the tool budget is unbounded", got)
+ }
+
+ // The explicit env still wins over the derivation.
+ t.Setenv("MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT", "20m")
+ if got := load(t).CodexSemanticInactivityTimeout; got != 20*time.Minute {
+ t.Fatalf("CodexSemanticInactivityTimeout = %s, want 20m from env", got)
+ }
+
+ // Disabling the watchdog suite has never disabled this timer; Codex keeps
+ // its own built-in default rather than becoming unbounded.
+ t.Setenv("MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT", "")
+ t.Setenv("MULTICA_AGENT_IDLE_WATCHDOG", "0")
+ t.Setenv("MULTICA_AGENT_TOOL_WATCHDOG", "")
+ if got := load(t).CodexSemanticInactivityTimeout; got != DefaultCodexSemanticInactivityTimeout {
+ t.Fatalf("CodexSemanticInactivityTimeout = %s, want the codex built-in %s when watchdogs are off", got, DefaultCodexSemanticInactivityTimeout)
+ }
+}
+
func TestLoadConfig_OpenCodeIdleWatchdog(t *testing.T) {
stageFakeAgent(t)
t.Setenv("MULTICA_OPENCODE_IDLE_WATCHDOG", "")
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index f37a3fbeac..3881e8aaaf 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -1977,6 +1977,10 @@ func (d *Daemon) Run(ctx context.Context) error {
// without it an operator cannot read the tool budget actually in effect.
"tool_watchdog", d.cfg.AgentToolWatchdog,
"opencode_idle_watchdog", d.cfg.OpenCodeIdleWatchdog,
+ // Derived from the watchdog budget too (Codex's own timer is not
+ // tool-aware), so it needs the same treatment as tool_watchdog: without
+ // it the effective Codex budget is invisible until a timeout fires.
+ "codex_semantic_inactivity", d.cfg.CodexSemanticInactivityTimeout,
"max_concurrent_tasks", d.cfg.MaxConcurrentTasks,
"gc_enabled", d.cfg.GCEnabled,
"auto_update", d.cfg.AutoUpdateEnabled,
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 2e4d9e68bf..bb7aada94f 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -3299,6 +3299,18 @@ WITH victims AS (
SELECT id FROM agent_task_queue
WHERE status = 'queued'
AND created_at < now() - make_interval(secs => $1::double precision)
+ AND (
+ runtime_id IS NULL
+ OR NOT EXISTS (
+ SELECT 1 FROM agent_runtime r WHERE r.id = agent_task_queue.runtime_id
+ )
+ OR EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = agent_task_queue.runtime_id
+ AND COALESCE(r.last_seen_at, r.updated_at) <
+ now() - make_interval(secs => $1::double precision)
+ )
+ )
AND NOT EXISTS (
SELECT 1 FROM agent_task_queue retry_parent
WHERE retry_parent.id = agent_task_queue.parent_task_id
@@ -3311,13 +3323,23 @@ WITH victims AS (
UPDATE agent_task_queue t
SET status = 'failed',
completed_at = now(),
- error = 'task expired in queue',
+ error = 'runtime unavailable while task was queued',
failure_reason = 'queued_expired',
prepare_lease_expires_at = NULL
FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
AND t.created_at < now() - make_interval(secs => $1::double precision)
+ AND (
+ t.runtime_id IS NULL
+ OR NOT EXISTS (SELECT 1 FROM agent_runtime r WHERE r.id = t.runtime_id)
+ OR EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = t.runtime_id
+ AND COALESCE(r.last_seen_at, r.updated_at) <
+ now() - make_interval(secs => $1::double precision)
+ )
+ )
AND NOT EXISTS (
SELECT 1 FROM agent_task_queue retry_parent
WHERE retry_parent.id = t.parent_task_id
@@ -3327,19 +3349,56 @@ RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t
`
type ExpireStaleQueuedTasksParams struct {
- TtlSecs float64 `json:"ttl_secs"`
- MaxPerTick int32 `json:"max_per_tick"`
+ ReconnectGraceSecs float64 `json:"reconnect_grace_secs"`
+ MaxPerTick int32 `json:"max_per_tick"`
}
-// Fails tasks that have been sitting in 'queued' for longer than the TTL.
-// This is the cleanup arm of the MUL-1899 "queued backlog" fix: even with the
-// new dispatch-time admission gate that refuses to enqueue when the runtime
-// is offline, we still need to drain the historical 87k+ doomed rows and
-// handle edge cases where a runtime goes offline AFTER a task is already
-// queued (the admission check protects new enqueues, not in-flight queue
-// depth). A retry created by runtime_offline is exempt: it deliberately waits
-// for that runtime to reconnect, so time spent in this recovery state must not
-// consume the generic queue TTL.
+// Fails queued tasks whose runtime can no longer prove it is alive.
+//
+// This used to be a pure wall clock: queued for longer than a TTL (default 2h)
+// meant failed. That conflated "nobody is coming for this task" with "the
+// queue ahead of it is long", and the second one is not a failure. MUL-6558
+// was exactly that — a self-hosted runtime with low task concurrency held its
+// own queue past 2h and healthy work died as queued_expired. The TTL knob
+// added then (MULTICA_TASK_QUEUED_TTL) only moved the cliff; it did not stop
+// a busy runtime from eventually crossing it.
+//
+// So the question is not "how long has this waited" but "is anything still
+// able to pick it up". A runtime that keeps heartbeating is busy, not dead,
+// and its backlog must be allowed to drain however long that takes. The
+// liveness signal is the same one FailTasksForOfflineRuntimes uses for
+// dispatched/running rows, so a daemon going down now retires its queued and
+// its in-flight work on one clock instead of two.
+//
+// The row must ALSO have been queued for a full grace of its own. Enqueue binds
+// a task to agent.runtime_id without checking that the runtime is up, so
+// runtime liveness alone would fail a task the instant it is assigned to a
+// runtime that has been offline a while — a laptop closed overnight would turn
+// "assign this issue" into a failure inside one 30s sweep tick instead of
+// waiting for the machine to come back. Requiring the task's own age keeps the
+// promise the name makes: a queued task gets one full reconnect grace before it
+// is given up on, counted from when it started waiting. It also bounds the
+// scan, which would otherwise re-evaluate the runtime subquery against every
+// queued row on every tick.
+//
+// Heartbeat age is read directly rather than gated on runtime.status='online',
+// so a row stuck at 'online' with a long-dead heartbeat still releases its
+// queue.
+//
+// The runtime_id IS NULL / missing-runtime arms are fail-closed defence, not
+// live paths: the schema already excludes both. runtime_id was NOT NULL from
+// migration 004 until 251 replaced it with CHECK (runtime_id IS NOT NULL OR
+// completed_at IS NOT NULL), which every insert and update is checked against
+// (NOT VALID only skips the backfill scan), so no queued row can be unbound.
+// A dangling reference is impossible because agent_task_queue_runtime_id_fkey
+// (migration 004) is ON DELETE CASCADE: deleting a runtime removes the rows
+// referencing it rather than orphaning them, and the normal delete path
+// (migration 251, MUL-5559) explicitly unbinds history tasks first in the same
+// transaction. They are kept so a future schema change cannot silently strand
+// rows that have no liveness signal at all.
+//
+// A retry created by runtime_offline is exempt: it deliberately waits for that
+// runtime to reconnect, and FailExpiredRuntimeReconnectRetries owns its exit.
//
// Concurrency safety: the daemon's claim path may race with this sweeper to
// transition the same row out of 'queued'. We protect against that two
@@ -3347,7 +3406,7 @@ type ExpireStaleQueuedTasksParams struct {
// 1. The CTE selects victims with FOR UPDATE SKIP LOCKED so a row that is
// currently being claimed (or otherwise locked) is skipped — no lock
// contention with the dispatch path, and we won't queue up behind it.
-// 2. The outer UPDATE re-checks status='queued' AND the TTL predicate at
+// 2. The outer UPDATE re-checks status='queued' AND the liveness predicate at
// apply time. If a daemon claimed the row between selection and update
// (e.g. lock released after the claim transaction commits), the row is
// already 'dispatched'/'running' and the WHERE clause filters it out
@@ -3357,7 +3416,7 @@ type ExpireStaleQueuedTasksParams struct {
// the DB when the backlog is large — the sweeper drains the rest on
// subsequent ticks.
func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQueuedTasksParams) ([]AgentTaskQueue, error) {
- rows, err := q.db.Query(ctx, expireStaleQueuedTasks, arg.TtlSecs, arg.MaxPerTick)
+ rows, err := q.db.Query(ctx, expireStaleQueuedTasks, arg.ReconnectGraceSecs, arg.MaxPerTick)
if err != nil {
return nil, err
}
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 5b6befe35a..d4e80a55f7 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -1394,15 +1394,52 @@ WHERE (
RETURNING *;
-- name: ExpireStaleQueuedTasks :many
--- Fails tasks that have been sitting in 'queued' for longer than the TTL.
--- This is the cleanup arm of the MUL-1899 "queued backlog" fix: even with the
--- new dispatch-time admission gate that refuses to enqueue when the runtime
--- is offline, we still need to drain the historical 87k+ doomed rows and
--- handle edge cases where a runtime goes offline AFTER a task is already
--- queued (the admission check protects new enqueues, not in-flight queue
--- depth). A retry created by runtime_offline is exempt: it deliberately waits
--- for that runtime to reconnect, so time spent in this recovery state must not
--- consume the generic queue TTL.
+-- Fails queued tasks whose runtime can no longer prove it is alive.
+--
+-- This used to be a pure wall clock: queued for longer than a TTL (default 2h)
+-- meant failed. That conflated "nobody is coming for this task" with "the
+-- queue ahead of it is long", and the second one is not a failure. MUL-6558
+-- was exactly that — a self-hosted runtime with low task concurrency held its
+-- own queue past 2h and healthy work died as queued_expired. The TTL knob
+-- added then (MULTICA_TASK_QUEUED_TTL) only moved the cliff; it did not stop
+-- a busy runtime from eventually crossing it.
+--
+-- So the question is not "how long has this waited" but "is anything still
+-- able to pick it up". A runtime that keeps heartbeating is busy, not dead,
+-- and its backlog must be allowed to drain however long that takes. The
+-- liveness signal is the same one FailTasksForOfflineRuntimes uses for
+-- dispatched/running rows, so a daemon going down now retires its queued and
+-- its in-flight work on one clock instead of two.
+--
+-- The row must ALSO have been queued for a full grace of its own. Enqueue binds
+-- a task to agent.runtime_id without checking that the runtime is up, so
+-- runtime liveness alone would fail a task the instant it is assigned to a
+-- runtime that has been offline a while — a laptop closed overnight would turn
+-- "assign this issue" into a failure inside one 30s sweep tick instead of
+-- waiting for the machine to come back. Requiring the task's own age keeps the
+-- promise the name makes: a queued task gets one full reconnect grace before it
+-- is given up on, counted from when it started waiting. It also bounds the
+-- scan, which would otherwise re-evaluate the runtime subquery against every
+-- queued row on every tick.
+--
+-- Heartbeat age is read directly rather than gated on runtime.status='online',
+-- so a row stuck at 'online' with a long-dead heartbeat still releases its
+-- queue.
+--
+-- The runtime_id IS NULL / missing-runtime arms are fail-closed defence, not
+-- live paths: the schema already excludes both. runtime_id was NOT NULL from
+-- migration 004 until 251 replaced it with CHECK (runtime_id IS NOT NULL OR
+-- completed_at IS NOT NULL), which every insert and update is checked against
+-- (NOT VALID only skips the backfill scan), so no queued row can be unbound.
+-- A dangling reference is impossible because agent_task_queue_runtime_id_fkey
+-- (migration 004) is ON DELETE CASCADE: deleting a runtime removes the rows
+-- referencing it rather than orphaning them, and the normal delete path
+-- (migration 251, MUL-5559) explicitly unbinds history tasks first in the same
+-- transaction. They are kept so a future schema change cannot silently strand
+-- rows that have no liveness signal at all.
+--
+-- A retry created by runtime_offline is exempt: it deliberately waits for that
+-- runtime to reconnect, and FailExpiredRuntimeReconnectRetries owns its exit.
--
-- Concurrency safety: the daemon's claim path may race with this sweeper to
-- transition the same row out of 'queued'. We protect against that two
@@ -1410,7 +1447,7 @@ RETURNING *;
-- 1. The CTE selects victims with FOR UPDATE SKIP LOCKED so a row that is
-- currently being claimed (or otherwise locked) is skipped — no lock
-- contention with the dispatch path, and we won't queue up behind it.
--- 2. The outer UPDATE re-checks status='queued' AND the TTL predicate at
+-- 2. The outer UPDATE re-checks status='queued' AND the liveness predicate at
-- apply time. If a daemon claimed the row between selection and update
-- (e.g. lock released after the claim transaction commits), the row is
-- already 'dispatched'/'running' and the WHERE clause filters it out
@@ -1421,7 +1458,19 @@ RETURNING *;
WITH victims AS (
SELECT id FROM agent_task_queue
WHERE status = 'queued'
- AND created_at < now() - make_interval(secs => @ttl_secs::double precision)
+ AND created_at < now() - make_interval(secs => @reconnect_grace_secs::double precision)
+ AND (
+ runtime_id IS NULL
+ OR NOT EXISTS (
+ SELECT 1 FROM agent_runtime r WHERE r.id = agent_task_queue.runtime_id
+ )
+ OR EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = agent_task_queue.runtime_id
+ AND COALESCE(r.last_seen_at, r.updated_at) <
+ now() - make_interval(secs => @reconnect_grace_secs::double precision)
+ )
+ )
AND NOT EXISTS (
SELECT 1 FROM agent_task_queue retry_parent
WHERE retry_parent.id = agent_task_queue.parent_task_id
@@ -1434,13 +1483,23 @@ WITH victims AS (
UPDATE agent_task_queue t
SET status = 'failed',
completed_at = now(),
- error = 'task expired in queue',
+ error = 'runtime unavailable while task was queued',
failure_reason = 'queued_expired',
prepare_lease_expires_at = NULL
FROM victims v
WHERE t.id = v.id
AND t.status = 'queued'
- AND t.created_at < now() - make_interval(secs => @ttl_secs::double precision)
+ AND t.created_at < now() - make_interval(secs => @reconnect_grace_secs::double precision)
+ AND (
+ t.runtime_id IS NULL
+ OR NOT EXISTS (SELECT 1 FROM agent_runtime r WHERE r.id = t.runtime_id)
+ OR EXISTS (
+ SELECT 1 FROM agent_runtime r
+ WHERE r.id = t.runtime_id
+ AND COALESCE(r.last_seen_at, r.updated_at) <
+ now() - make_interval(secs => @reconnect_grace_secs::double precision)
+ )
+ )
AND NOT EXISTS (
SELECT 1 FROM agent_task_queue retry_parent
WHERE retry_parent.id = t.parent_task_id