Skip to content

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

Go

feat(task): reuse workdir on manual retry, gate session on error class (MUL-4869) (#5525)

Bohan Jiangae68799c6450
diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdx
index 87f05ed1b5..f166ee1f05 100644
--- a/apps/docs/content/docs/tasks.ja.mdx
+++ b/apps/docs/content/docs/tasks.ja.mdx
@@ -81,7 +81,9 @@ multica issue rerun <issue-id>
- 実行ログの特定の行にあるリトライボタンは、その行のタスク ID も一緒に送信するため、再実行は**現在の担当者ではなく、まさにそのタスクを実行したエージェント**を対象とします。これにより、スクワッドワーカー、並列の @-メンションエージェント、または再割り当てによってエージェントが入れ替わった行に対しても、行単位のリトライが意味を持つようになります。
- このイシューに対する対象エージェントのキュー待ちまたは実行中のタスクを**キャンセルします**(ある場合)。同じイシューで他のエージェントが所有するタスク(例: 並列の @-メンション実行)はそのまま残します。
- **まったく新しい**タスクを作成します — オリジナルのタスクが試行回数の上限に達していても、試行回数は 1 にリセットされます。
-- **新しいエージェントセッション**を開始します — 以前のセッション ID は**継承されません**。手動の再実行は、以前の成果物が悪かったと判断したことを意味するため、同じ会話を続けると汚染された状態をそのまま再生してしまいます。(一方、自動リトライはセッションを継承します — そのパスは悪い成果物ではなくインフラ障害のためのものです。)
+- **作業ディレクトリを再利用します。セッションを再開するかどうかは、どこからトリガーしたかによって変わります:**
+ - **実行ログの行単位リトライ**(task ID を伴う): その実行の作業ディレクトリを再利用するため、ディスクに書き込み済みのファイルは保持されます。その実行のセッションも再開します — ただし失敗が会話を汚染した場合(コンテキストオーバーフロー、反復上限、invalid request、Codex セマンティック無活動、エージェントフォールバック)は、再利用した作業ディレクトリの上で新しいセッションを開始します。元のディレクトリが失われている場合(GC 済み、別のランタイム上、または記録される前に失敗)は、新しい作業ディレクトリにフォールバックします。これにより、ネットワークの一時的な不調、provider の 5xx / レート制限、一時的にオフラインになったランタイム、すでに修正した auth/クォータ/設定エラーなどの**一時的な失敗**は、最初からやり直すのではなく中断したところから続行します。
+ - **task ID を伴わない CLI / API 再実行**: 続行すべき特定の実行がないため、**新しいセッション + 新しい作業ディレクトリ**で開始します。
比較:
@@ -91,7 +93,8 @@ multica issue rerun <issue-id>
| 上限 | 2 回の試行 | 制限なし |
| 適用できるソース | イシュー、チャット | エージェント担当者があるイシュー |
| 選択されるエージェント | 失敗したタスクと同じエージェント | ソースタスクのエージェント(UI 行単位リトライ)またはイシューの現在の担当者(CLI / task_id なし) |
-| セッション継承 | あり(以前のセッションを再開) | なし(新しいセッション) |
+| 作業ディレクトリ | 再利用(以前のファイルから続行) | 行単位リトライ: まだ存在すれば再利用; CLI / task_id なし: 新規 |
+| セッション継承 | あり(以前のセッションを再開) | 行単位リトライ: 失敗が会話を汚染しない限り再開; CLI / task_id なし: 新規 |
## 失敗したタスクがイシューのステータスに与える影響
@@ -101,7 +104,7 @@ multica issue rerun <issue-id>
できます — AI コーディングツールがセッション再開をサポートしている限りは。
-Multica はタスク中にセッション ID を**2 回**固定します: 開始時に 1 回(AI ツールが最初のシステムメッセージを返したとき)、終了時に 1 回(完了または失敗時)。1 回目はデーモンが実行の途中でクラッシュしても復旧できるようにし、2 回目は次の**自動リトライ**のために予約され、その ID を渡し返すことでエージェントが以前の会話とファイル状態を引き継げるようにします。**手動の再実行は意図的にこのステップをスキップし**、新しいセッションを開始します — [手動の再実行 vs. 自動リトライ](#manual-rerun-vs-automatic-retry)を参照してください。
+Multica はタスク中にセッション ID を**2 回**固定します: 開始時に 1 回(AI ツールが最初のシステムメッセージを返したとき)、終了時に 1 回(完了または失敗時)。1 回目はデーモンが実行の途中でクラッシュしても復旧できるようにし、2 回目は次の**自動リトライ**と**実行ログの行単位リトライ**で再利用され、その ID を渡し返すことでエージェントが以前の会話とファイル状態を引き継げるようにします — ただし失敗が会話を汚染した場合は、作業ディレクトリのみを再利用して新しいセッションを開始します。**task ID を伴わない CLI / API 再実行**は、新しいセッション + 新しい作業ディレクトリで開始します — [手動の再実行 vs. 自動リトライ](#manual-rerun-vs-automatic-retry)を参照してください。
ただし、**実際にどの AI コーディングツールがこれをサポートするか**は大きく異なります。
diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdx
index 3f1cb72929..388a108295 100644
--- a/apps/docs/content/docs/tasks.ko.mdx
+++ b/apps/docs/content/docs/tasks.ko.mdx
@@ -81,7 +81,9 @@ multica issue rerun <issue-id>
- 실행 로그의 특정 행에 있는 재시도 버튼은 해당 행의 작업 ID를 함께 전송하므로, 재실행은 **현재 담당자가 아니라 바로 그 작업을 실행했던 에이전트**를 대상으로 합니다. 덕분에 스쿼드 워커, 병렬 @-멘션 에이전트, 또는 재할당으로 인해 에이전트가 교체된 행에 대해서도 행 단위 재시도가 의미를 갖게 됩니다.
- 이 이슈에 대한 대상 에이전트의 대기 중이거나 실행 중인 작업을 **취소합니다**(있는 경우). 같은 이슈에서 다른 에이전트가 소유한 작업(예: 병렬 @-멘션 실행)은 그대로 둡니다.
- **완전히 새로운** 작업을 생성합니다 — 원본 작업이 시도 횟수 상한에 도달했더라도 시도 횟수가 1로 재설정됩니다.
-- **새로운 에이전트 세션**을 시작합니다 — 이전 세션 ID는 **상속되지 않습니다**. 수동 재실행은 이전 산출물이 나빴다고 판단했다는 의미이므로, 같은 대화를 이어가면 오염된 상태를 그대로 재생하게 됩니다. (반면 자동 재시도는 세션을 상속합니다 — 그 경로는 잘못된 산출물이 아니라 인프라 장애를 위한 것입니다.)
+- **작업 디렉터리를 재사용하며, 세션 재개 여부는 어디에서 트리거했는지에 따라 달라집니다:**
+ - **실행 로그의 행 단위 재시도**(task ID 포함): 해당 실행의 작업 디렉터리를 재사용하므로 디스크에 이미 기록된 파일이 보존됩니다. 그 실행의 세션도 재개합니다 — 단, 실패가 대화를 오염시킨 경우(컨텍스트 오버플로, 반복 한도, invalid request, Codex 시맨틱 무활동, 에이전트 폴백)에는 재사용한 작업 디렉터리 위에서 새 세션을 시작합니다. 원본 디렉터리가 사라진 경우(GC됨, 다른 런타임에 있음, 또는 기록되기 전에 실패)에는 새 작업 디렉터리로 폴백합니다. 따라서 네트워크 순간 장애, provider의 5xx / 속도 제한, 잠시 오프라인이 된 런타임, 이미 수정한 auth/할당량/설정 오류 같은 **일시적 실패**는 처음부터 다시 시작하지 않고 중단된 지점부터 이어집니다.
+ - **task ID 없는 CLI / API 재실행**: 이어갈 특정 실행이 없으므로 **새 세션 + 새 작업 디렉터리**로 시작합니다.
비교:
@@ -91,7 +93,8 @@ multica issue rerun <issue-id>
| 상한 | 2회 시도 | 제한 없음 |
| 적용 가능한 소스 | 이슈, 채팅 | 에이전트 담당자가 있는 이슈 |
| 선택되는 에이전트 | 실패한 작업과 동일한 에이전트 | 소스 작업의 에이전트(UI 행 단위 재시도) 또는 이슈의 현재 담당자(CLI / task_id 없음) |
-| 세션 상속 | 예(이전 세션 재개) | 아니요(새 세션) |
+| 작업 디렉터리 | 재사용(이전 파일에서 이어감) | 행 단위 재시도: 아직 남아 있으면 재사용; CLI / task_id 없음: 새로 시작 |
+| 세션 상속 | 예(이전 세션 재개) | 행 단위 재시도: 실패가 대화를 오염시키지 않는 한 재개; CLI / task_id 없음: 새로 시작 |
## 실패한 작업이 이슈 상태에 미치는 영향
@@ -101,7 +104,7 @@ multica issue rerun <issue-id>
가능합니다 — AI 코딩 도구가 세션 재개를 지원하는 한 그렇습니다.
-Multica는 작업 중에 세션 ID를 **두 번** 고정합니다: 시작 시 한 번(AI 도구가 첫 번째 시스템 메시지를 반환할 때), 종료 시 한 번(완료 또는 실패 시). 첫 번째는 데몬이 실행 도중 충돌하더라도 복구할 수 있게 해주고, 두 번째는 다음 **자동 재시도**를 위해 예약되어 그 ID를 다시 전달함으로써 에이전트가 이전 대화와 파일 상태를 이어받을 수 있게 합니다. **수동 재실행은 의도적으로 이 단계를 건너뛰고** 새 세션을 시작합니다 — [수동 재실행 vs. 자동 재시도](#manual-rerun-vs-automatic-retry)를 참고하세요.
+Multica는 작업 중에 세션 ID를 **두 번** 고정합니다: 시작 시 한 번(AI 도구가 첫 번째 시스템 메시지를 반환할 때), 종료 시 한 번(완료 또는 실패 시). 첫 번째는 데몬이 실행 도중 충돌하더라도 복구할 수 있게 해주고, 두 번째는 다음 **자동 재시도**와 **실행 로그의 행 단위 재시도**에서 재사용되어, 그 ID를 다시 전달함으로써 에이전트가 이전 대화와 파일 상태를 이어받게 합니다 — 단, 실패가 대화를 오염시킨 경우에는 작업 디렉터리만 재사용하고 새 세션을 시작합니다. **task ID 없는 CLI / API 재실행**은 새 세션 + 새 작업 디렉터리로 시작합니다 — [수동 재실행 vs. 자동 재시도](#manual-rerun-vs-automatic-retry)를 참고하세요.
하지만 **실제로 어떤 AI 코딩 도구가 이를 지원하는지**는 크게 다릅니다:
diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdx
index c791279d20..38dec7d4b5 100644
--- a/apps/docs/content/docs/tasks.mdx
+++ b/apps/docs/content/docs/tasks.mdx
@@ -81,7 +81,9 @@ Behavior:
- The execution-log retry button on a specific row sends that row's task ID alongside, so the rerun targets **the agent that ran that exact task** — not the current assignee. This makes per-row retry meaningful for squad workers, parallel @-mention agents, or rows whose agent has since been displaced by a reassignment.
- **Cancels** the target agent's queued or running task on this issue (if any). Tasks owned by other agents on the same issue (e.g. parallel @-mention runs) are left alone.
- Creates a **brand-new** task — attempt count resets to 1, even if the original task hit the attempt ceiling.
-- Starts a **fresh agent session** — the prior session ID is **not** inherited. A manual rerun means you've judged the previous output bad, so resuming the same conversation would replay the same poisoned state. (Automatic retry, by contrast, does inherit the session — that path is for infrastructure failures, not bad output.)
+- **Reuses the workdir; the session is resumed conditionally — and this depends on how you triggered the rerun:**
+ - **Execution-log per-row retry** (carries a task ID): reuses that exact run's working directory, so files already written to disk are preserved. It resumes that run's agent session too — *unless* the failure poisoned the conversation (context overflow, iteration limit, invalid request, Codex semantic inactivity, agent fallback), in which case it starts a fresh session on top of the reused workdir. If the original directory is gone (garbage-collected, on a different runtime, or never recorded before the failure), it falls back to a fresh workdir. So a transient failure — a network blip, a provider 5xx / rate-limit, a runtime that briefly went offline, or an auth/quota/config error you've since fixed — continues from where it left off instead of starting over.
+ - **CLI / API rerun without a task ID**: there is no specific run to continue, so it starts a **fresh agent session in a fresh workdir**.
Comparison:
@@ -91,7 +93,8 @@ Comparison:
| Ceiling | 2 attempts | No limit |
| Applicable sources | Issues, chat | Issues with an agent assignee |
| Agent picked | Same agent as the failed task | Source task's agent (UI per-row retry) or issue's current assignee (CLI / no task_id) |
-| Session inheritance | Yes (resumes prior session) | No (fresh session) |
+| Workdir | Reused (continues from prior files) | Per-row retry: reused when it still exists; CLI / no task_id: fresh |
+| Session inheritance | Yes (resumes prior session) | Per-row retry: resumes unless the failure poisoned the conversation; CLI / no task_id: fresh |
## How a failed task affects issue status
@@ -101,7 +104,7 @@ If an issue-triggered task fails (and no automatic retry succeeds) because the i
Yes — as long as the AI coding tool supports session resumption.
-Multica pins the session ID **twice** during a task: once at the start (when the AI tool returns its first system message), and once at the end (on completion or failure). The first lets the daemon recover if it crashes mid-run; the second is reserved for the next **automatic retry**, where that ID is passed back so the agent can pick up the previous conversation and file state. **Manual rerun deliberately skips this** and starts a fresh session — see [Manual rerun vs. automatic retry](#manual-rerun-vs-automatic-retry).
+Multica pins the session ID **twice** during a task: once at the start (when the AI tool returns its first system message), and once at the end (on completion or failure). The first lets the daemon recover if it crashes mid-run; the second is passed back to the next **automatic retry** and to an **execution-log per-row retry**, so the agent picks up the previous conversation and file state — unless the failure poisoned the conversation, in which case only the workdir is reused and a fresh session starts. A **CLI / API rerun without a task ID** starts a fresh session in a fresh workdir — see [Manual rerun vs. automatic retry](#manual-rerun-vs-automatic-retry).
But **which AI coding tools actually support this** varies a lot:
diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdx
index bf684cb902..833b099528 100644
--- a/apps/docs/content/docs/tasks.zh.mdx
+++ b/apps/docs/content/docs/tasks.zh.mdx
@@ -83,7 +83,9 @@ multica issue rerun <issue-id>
- 执行日志里某一行的 retry 按钮会把这一行的 task ID 一并发出,rerun 会**针对那一行原本的 agent**,而不是当前分配人。这让 squad worker、并行的 @-mention agent、或者已经被新分配人替代的旧任务行的 retry 按钮都能符合直觉地工作。
- **取消**目标 agent 在这条 issue 上 queued / running 的任务(如果有)。同 issue 上其它 agent 的任务(例如 @-mention 触发的并行任务)不会被一起取消。
- 创建一个**全新**的执行任务——尝试次数重置为 1,即使原任务已达最大尝试。
-- 启动**全新的智能体会话**——**不**继承之前的会话 ID。手动重跑意味着你已经判定上一次的产出不行,再继续之前的对话只会重放被污染的上下文。(自动重试则相反,会继承会话——那条路径处理的是基础设施层面的失败,不是产出不好。)
+- **复用工作目录;是否续接会话取决于你从哪里触发:**
+ - **执行日志里某一行的 retry**(带 task ID):复用那一次执行的工作目录,磁盘上已经写好的文件会被保留;同时也会续接那次执行的会话——**除非**这次失败污染了对话(context 溢出、迭代上限、invalid request、Codex 语义无活动、agent fallback),这种情况下会在复用的工作目录上开一个全新会话。如果原目录已经不在了(被 GC、在另一台 runtime 上、或失败太早还没记录),则回退到全新目录。这样一来,网络抖动、provider 5xx / 限流、runtime 短暂离线、或你已经修好的 auth/额度/配置错误等**临时故障**就能从中断处继续,而不用从头再来。
+ - **不带 task ID 的 CLI / API rerun**:没有具体某一次执行可续,因此**开一个全新会话 + 全新工作目录**。
对比:
@@ -93,7 +95,8 @@ multica issue rerun <issue-id>
| 上限 | 2 次 | 无上限 |
| 适用来源 | issue、聊天 | 有智能体分配人的 issue |
| 跑哪个 agent | 失败任务原本的 agent | UI 单行 retry:那一行任务的 agent;CLI / 不带 task_id:issue 当前的分配人 |
-| 会话继承 | 是(接着上次会话) | 否(全新会话) |
+| 工作目录 | 复用(接着上次的文件继续) | 单行 retry:原目录还在就复用;CLI / 不带 task_id:全新 |
+| 会话继承 | 是(接着上次会话) | 单行 retry:除非失败污染了对话,否则续接;CLI / 不带 task_id:全新 |
## 失败的任务对 issue 状态有什么影响
@@ -103,7 +106,7 @@ multica issue rerun <issue-id>
可以——前提是对应的 AI 编程工具支持会话恢复。
-Multica 在任务过程中**两次**保存会话 ID——任务一开始(AI 工具返回第一条系统消息时)pin 一次,任务结束(完成或失败)时再 pin 一次。前者让守护进程中途崩溃时也能恢复,后者留给下一次**自动重试**——届时把这个 ID 传回去,智能体就能接着上次的对话和文件状态继续。**手动重跑会主动跳过这一步**,永远从全新会话开始——见 [手动重跑和自动重试的区别](#手动重跑和自动重试的区别)。
+Multica 在任务过程中**两次**保存会话 ID——任务一开始(AI 工具返回第一条系统消息时)pin 一次,任务结束(完成或失败)时再 pin 一次。前者让守护进程中途崩溃时也能恢复,后者会被下一次**自动重试**以及**执行日志里的单行 retry**复用——把这个 ID 传回去,智能体就能接着上次的对话和文件状态继续;只有当这次失败污染了对话时,才只复用工作目录、另开全新会话。**不带 task ID 的 CLI / API rerun** 则从全新会话 + 全新工作目录开始——见 [手动重跑和自动重试的区别](#手动重跑和自动重试的区别)。
但**哪些 AI 编程工具真的支持**差别很大:
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index cc8772087c..40b91211be 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1965,24 +1965,49 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
resp.TriggerCommentContent = "The newest triggering comment is no longer available. Address every earlier comment included below."
}
- // Look up the prior session for this (agent, issue) pair so the daemon
- // can resume the Claude Code conversation context.
- //
- // Skip all prior state when the task was flagged as a manual rerun:
- // the user just judged the prior output bad, so the daemon must start a
- // fresh agent session in a fresh workdir instead of resuming anything
- // from the same conversation that produced that output.
- if !task.ForceFreshSession {
+ // Resolve the prior agent session / workdir to resume.
+ if task.RerunOfTaskID.Valid {
+ // Manual retry: resume precisely from the source task the user
+ // clicked, NOT the most-recent (agent, issue) row — a parallel task
+ // on the same issue must never hijack the resume (MUL-4869). The
+ // workdir is ALWAYS reused when it still exists; the session is
+ // resumed only when the source failure did not poison the
+ // conversation AND the source ran on this runtime.
+ //
+ // Resume-safety is computed HERE from the source task, not read off
+ // task.ForceFreshSession: RerunIssue pins that flag to true so an OLD
+ // claim handler mid rolling-deploy degrades to a clean start instead
+ // of resuming a different execution via the (agent, issue) lookup.
+ // service.ResumeUnsafeFailure mirrors GetLastTaskSession, including
+ // its 400/invalid_request_error text defense for legacy /
+ // mis-classified rows that the exact-source path would otherwise miss.
+ //
+ // When the source workdir is gone (GC'd), absent on this runtime, or
+ // was never recorded (failed too early), execenv.Reuse falls back to a
+ // fresh Prepare and gateResumeToReusedWorkdir drops the now-unusable
+ // session — reuse is best-effort, never a silent swap onto a stale
+ // directory. PriorWorkDir is offered regardless of runtime (a shared
+ // mount may still resolve it); only the per-cwd session is
+ // runtime-gated.
+ if src, err := h.Queries.GetAgentTask(r.Context(), task.RerunOfTaskID); err == nil {
+ if src.WorkDir.Valid {
+ resp.PriorWorkDir = src.WorkDir.String
+ }
+ if !service.ResumeUnsafeFailure(src.FailureReason.String, src.Error.String) &&
+ src.SessionID.Valid && src.RuntimeID == task.RuntimeID {
+ resp.PriorSessionID = src.SessionID.String
+ }
+ }
+ } else if !task.ForceFreshSession {
+ // Non-rerun follow-up on the same issue: resume the most recent
+ // (agent, issue) session so the agent keeps the issue's conversation
+ // context across turns. The "Focus on THIS comment" guard in
+ // prompt.go defends against inheriting the prior turn's "Done."
+ // marker, and GetLastTaskSession already excludes poisoned sessions.
if prior, err := h.Queries.GetLastTaskSession(r.Context(), db.GetLastTaskSessionParams{
AgentID: task.AgentID,
IssueID: task.IssueID,
}); err == nil && prior.SessionID.Valid {
- // Resume the prior session when it ran on the same runtime —
- // including comment-triggered follow-ups, so the agent keeps the
- // issue's conversation context across turns. The "Focus on THIS
- // comment" guard in prompt.go defends against inheriting the prior
- // turn's "Done." marker, and GetLastTaskSession already excludes
- // poisoned sessions.
if prior.RuntimeID == task.RuntimeID {
resp.PriorSessionID = prior.SessionID.String
}
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index 2540e6e515..3fd132c47c 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -3485,6 +3485,113 @@ func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {
}
}
+// TestClaimTask_ManualRetryReusesWorkdir is the MUL-4869 claim-layer contract: a
+// manual retry (rerun_of_task_id set) ALWAYS hands back the source task's
+// workdir, and resumes the session only when the source failure did not poison
+// the conversation AND the source ran on the claiming runtime. The rerun row's
+// force_fresh_session is always true (rollback-safe); the session decision is
+// computed here from the source task, including the legacy 400 error-text guard.
+// Contrast with a plain force_fresh task carrying no rerun lineage, which resumes
+// nothing — covered by TestClaimTask_IssuePriorSessionRuntimeGuard.
+func TestClaimTask_ManualRetryReusesWorkdir(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)
+ otherRuntimeID := createRuntimeGuardRuntime(t, ctx, "kimi")
+
+ // insertRerun persists a terminal source task plus a queued rerun that points
+ // at it (rerun_of_task_id) with force_fresh_session=true, mimicking what
+ // RerunIssue writes, then claims and returns the resolved task. Each case uses
+ // a fresh issue so the partial unique index (one pending task per issue+agent)
+ // never trips across cases. The source's runtime, failure_reason, and error
+ // text drive the runtime-match and resume-safety gates.
+ issueNum := 81207
+ insertRerun := func(t *testing.T, sourceRuntimeID, failureReason, errorText, session, workdir string) *claimRuntimeGuardTask {
+ t.Helper()
+ issueNum++
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_id, creator_type, number, position)
+ VALUES ($1, 'manual-retry-reuse fixture', 'in_progress', 'none', $2, 'member', $3, 0)
+ RETURNING id
+ `, testWorkspaceID, testUserID, issueNum).Scan(&issueID); err != nil {
+ t.Fatalf("setup: create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })
+ var sourceID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority,
+ failure_reason, error, session_id, work_dir
+ )
+ VALUES ($1, $2, $3, 'failed', 0, $4, $5, $6, $7)
+ RETURNING id
+ `, agentID, sourceRuntimeID, issueID, failureReason, errorText, session, workdir).Scan(&sourceID); err != nil {
+ t.Fatalf("setup: insert source task: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, sourceID) })
+ // force_fresh_session is always true on a rerun row (rollback-safe); the
+ // new claim handler resumes from the source task regardless.
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, runtime_id, issue_id, status, priority,
+ rerun_of_task_id, force_fresh_session
+ )
+ VALUES ($1, $2, $3, 'queued', 0, $4, TRUE)
+ `, agentID, runtimeID, issueID, sourceID); err != nil {
+ t.Fatalf("setup: insert rerun task: %v", err)
+ }
+ return claimTaskForRuntimeGuard(t, runtimeID, daemonID)
+ }
+
+ t.Run("resume_safe_same_runtime_reuses_both", func(t *testing.T) {
+ task := insertRerun(t, runtimeID, "timeout", "", "safe-session", "/tmp/retry-safe-workdir")
+ if task.PriorWorkDir != "/tmp/retry-safe-workdir" {
+ t.Fatalf("PriorWorkDir = %q, want /tmp/retry-safe-workdir", task.PriorWorkDir)
+ }
+ if task.PriorSessionID != "safe-session" {
+ t.Fatalf("PriorSessionID = %q, want safe-session (transient failure resumes)", task.PriorSessionID)
+ }
+ })
+
+ t.Run("poisoned_reason_same_runtime_reuses_workdir_fresh_session", func(t *testing.T) {
+ task := insertRerun(t, runtimeID, "agent_error.context_overflow", "", "poison-session", "/tmp/retry-poison-workdir")
+ if task.PriorWorkDir != "/tmp/retry-poison-workdir" {
+ t.Fatalf("PriorWorkDir = %q, want /tmp/retry-poison-workdir (workdir reused even when session poisoned)", task.PriorWorkDir)
+ }
+ if task.PriorSessionID != "" {
+ t.Fatalf("PriorSessionID = %q, want empty (poisoned session starts fresh)", task.PriorSessionID)
+ }
+ })
+
+ t.Run("legacy_400_error_text_reuses_workdir_fresh_session", func(t *testing.T) {
+ // failure_reason is a benign generic 'agent_error', but the raw error
+ // carries the Anthropic 400 invalid_request_error marker — the exact
+ // source path must still refuse to resume that session (defense-in-depth
+ // mirrored from GetLastTaskSession).
+ task := insertRerun(t, runtimeID, "agent_error", "API error 400 invalid_request_error: prompt is too long", "legacy400-session", "/tmp/retry-legacy400-workdir")
+ if task.PriorWorkDir != "/tmp/retry-legacy400-workdir" {
+ t.Fatalf("PriorWorkDir = %q, want /tmp/retry-legacy400-workdir", task.PriorWorkDir)
+ }
+ if task.PriorSessionID != "" {
+ t.Fatalf("PriorSessionID = %q, want empty (legacy 400 invalid_request_error must not resume)", task.PriorSessionID)
+ }
+ })
+
+ t.Run("different_runtime_reuses_workdir_drops_session", func(t *testing.T) {
+ task := insertRerun(t, otherRuntimeID, "timeout", "", "cross-session", "/tmp/retry-cross-workdir")
+ if task.PriorWorkDir != "/tmp/retry-cross-workdir" {
+ t.Fatalf("PriorWorkDir = %q, want /tmp/retry-cross-workdir (workdir offered regardless of runtime, best-effort)", task.PriorWorkDir)
+ }
+ if task.PriorSessionID != "" {
+ t.Fatalf("PriorSessionID = %q, want empty (cross-runtime session cannot resolve)", task.PriorSessionID)
+ }
+ })
+}
+
func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
diff --git a/server/internal/service/rerun_workdir_reuse_test.go b/server/internal/service/rerun_workdir_reuse_test.go
new file mode 100644
index 0000000000..d855add990
--- /dev/null
+++ b/server/internal/service/rerun_workdir_reuse_test.go
@@ -0,0 +1,84 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// TestRerunIssuePinsForceFreshSessionForRollbackSafety locks in the rollback-safe
+// half of the MUL-4869 contract: RerunIssue ALWAYS persists
+// force_fresh_session=true on the rerun row, no matter how the source task
+// failed. The session-reuse decision is made later by the (new) claim handler
+// from the source task, so an OLD claim handler picked up mid rolling-deploy —
+// which gates the whole resume lookup on !force_fresh_session — degrades to a
+// clean start instead of resuming a different execution via the
+// (agent, issue) most-recent query. The claim-layer behaviour (workdir always
+// reused, session gated by source failure class) is asserted in
+// TestClaimTask_ManualRetryReusesWorkdir.
+func TestRerunIssuePinsForceFreshSessionForRollbackSafety(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, creatorID, agentID, issueID := seedAttributionFixture(t, pool)
+ _ = workspaceID
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+
+ // agent_task_queue.runtime_id is NOT NULL; reuse the fixture agent's runtime.
+ 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)
+ }
+
+ // The flag must be true across resume-safe, resume-poisoned, and cancelled
+ // source failures alike — the enqueue row never encodes the classification.
+ cases := []struct {
+ name string
+ status string
+ failureReason any // string, or nil for a NULL failure_reason
+ }{
+ {name: "transient_timeout", status: "failed", failureReason: "timeout"},
+ {name: "transient_provider_network", status: "failed", failureReason: "agent_error.provider_network"},
+ {name: "poisoned_context_overflow", status: "failed", failureReason: "agent_error.context_overflow"},
+ {name: "cancelled_no_reason", status: "cancelled", failureReason: nil},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ var sourceID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, failure_reason, session_id, work_dir)
+ VALUES ($1, $2, $3, $4, 0, $5, 'src-session', '/tmp/src-workdir')
+ RETURNING id
+ `, agentID, runtimeID, issueID, tc.status, tc.failureReason).Scan(&sourceID); err != nil {
+ t.Fatalf("insert source task: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, sourceID) })
+
+ task, err := svc.RerunIssue(ctx, util.MustParseUUID(issueID), sourceID, pgtype.UUID{}, util.MustParseUUID(creatorID), nil)
+ if err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+ t.Cleanup(func() { pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, task.ID) })
+
+ var forceFresh bool
+ var rerunOf pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ SELECT force_fresh_session, rerun_of_task_id FROM agent_task_queue WHERE id = $1
+ `, task.ID).Scan(&forceFresh, &rerunOf); err != nil {
+ t.Fatalf("read rerun task: %v", err)
+ }
+ if !forceFresh {
+ t.Errorf("force_fresh_session = false, want true for rollback safety (source failure_reason=%v)", tc.failureReason)
+ }
+ if !rerunOf.Valid || rerunOf.Bytes != sourceID.Bytes {
+ t.Errorf("rerun_of_task_id = %s, want source %s", util.UUIDToString(rerunOf), util.UUIDToString(sourceID))
+ }
+ })
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 377856b185..46f110d190 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -3060,15 +3060,40 @@ var retryableReasons = map[string]bool{
func resumeUnsafeFailureReason(reason string) bool {
switch reason {
- // Keep in sync with GetLastTaskSession / GetLastChatTaskSession and
- // CreateRetryTask's fresh-session CASE WHEN.
- case "iteration_limit", "agent_fallback_message", "api_invalid_request", "codex_semantic_inactivity":
+ // Failures that poison the agent CONVERSATION (not the workdir): resuming
+ // the same session would immediately replay the stuck/oversized state.
+ // Keep in sync with the GetLastTaskSession / GetLastChatTaskSession resume
+ // blacklists. (CreateRetryTask's fresh-session CASE WHEN only needs the
+ // subset of these that is also auto-retryable, currently
+ // codex_semantic_inactivity.)
+ case "iteration_limit", "agent_fallback_message", "api_invalid_request", "codex_semantic_inactivity", "agent_error.context_overflow":
return true
default:
return false
}
}
+// ResumeUnsafeFailure reports whether a failed task's agent session must NOT be
+// resumed on a retry. It combines the failure_reason poison set
+// (resumeUnsafeFailureReason) with the SAME defense-in-depth on raw error text
+// that the GetLastTaskSession / GetLastChatTaskSession resume queries apply: an
+// Anthropic 400 invalid_request_error means the conversation history itself is
+// unprocessable even when failure_reason was mis- or un-classified (legacy
+// 'agent_error' rows written before MUL-1921, or deploy-window rows). Callers
+// that only have a failure_reason (e.g. at fail time) may pass an empty
+// errorText.
+//
+// This is the shared source of truth for the manual-retry claim path, which
+// reads the exact source task instead of GetLastTaskSession and would otherwise
+// bypass the error-text guard.
+func ResumeUnsafeFailure(failureReason, errorText string) bool {
+ if resumeUnsafeFailureReason(failureReason) {
+ return true
+ }
+ lower := strings.ToLower(errorText)
+ return strings.Contains(lower, "400") && strings.Contains(lower, "invalid_request_error")
+}
+
// 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
@@ -3177,13 +3202,22 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
// or squad leader). This preserves the CLI / API contract for callers
// that have an issue ID but no specific task to target.
//
-// The new task is flagged force_fresh_session=true so the daemon starts a
-// clean agent session instead of resuming the prior (agent_id, issue_id)
-// session. A user clicking rerun has just judged the prior output bad —
-// resuming the same conversation would replay the same poisoned state.
-// Auto-retry of an orphaned mid-flight failure (HandleFailedTasks →
-// MaybeRetryFailedTask → CreateRetryTask) does NOT take this path, so
-// MUL-1128's mid-flight resume contract is preserved.
+// A retry ALWAYS reuses the source task's workdir when it still exists on
+// disk (MUL-4869): a transient failure — network, provider 5xx/rate-limit,
+// runtime_offline, timeout, or an auth/quota/config error the user has since
+// fixed — should not throw away the work already done. Only the agent SESSION
+// is conditionally resumed, and that decision is made later by the daemon claim
+// handler from the SOURCE task (via rerun_of_task_id), NOT baked into this row.
+// enqueueRerunTask pins force_fresh_session=true so an old claim handler during
+// a rolling deploy degrades to a clean start rather than resuming a different
+// execution; the new claim handler ignores the flag for reruns and resumes the
+// session only when the source failure did not poison the conversation (see
+// service.ResumeUnsafeFailure) and the source ran on the same runtime. When the
+// dir is objectively unreusable (GC'd, absent on the claiming runtime, or never
+// recorded) the daemon falls back to a fresh workdir. Auto-retry of an orphaned
+// mid-flight failure (HandleFailedTasks → MaybeRetryFailedTask →
+// CreateRetryTask) takes its own path, so MUL-1128's mid-flight resume contract
+// is preserved.
//
// ErrRerunInvokeNotAllowed signals that RerunIssue refused to rerun because the
// current operator may not invoke the resolved target agent. The handler maps it
@@ -3370,8 +3404,16 @@ func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []p
// When the target agent is the issue's single-agent assignee we use the
// assignee-driven path (enqueueIssueTask) so the issue-assignee bookkeeping
// stays in sync; otherwise (squad member, prior assignee that has since been
-// reassigned, mention agent) we use the mention path with the same
-// force_fresh_session=true contract.
+// reassigned, mention agent) we use the mention path.
+//
+// force_fresh_session is pinned to true on every rerun row on purpose. It is
+// the rollback-safe legacy signal: an OLD claim handler (mid rolling deploy)
+// gates the whole resume lookup on !force_fresh_session, so it starts clean
+// instead of resuming via the (agent, issue) most-recent query — which could
+// pick a different execution than the one the user clicked. The NEW claim
+// handler ignores this flag for reruns and instead reads the exact source task
+// (rerun_of_task_id) to reuse its workdir and, when the failure did not poison
+// the conversation, resume its session (MUL-4869).
func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {
if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&
util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {
diff --git a/server/internal/service/task_complete_race_test.go b/server/internal/service/task_complete_race_test.go
index eb2d0ca2ee..14d96089cc 100644
--- a/server/internal/service/task_complete_race_test.go
+++ b/server/internal/service/task_complete_race_test.go
@@ -179,6 +179,7 @@ func TestTaskFailureClassifiers(t *testing.T) {
{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},
+ {reason: "agent_error.context_overflow", wantType: "agent_error", wantResumeOK: false, wantRetry: false},
{reason: "agent_error", wantType: "agent_error", wantResumeOK: true, wantRetry: false},
// Missing terminal result errors classify to agent_error.unknown. Keep
// that deterministic upstream failure outside the auto-retry allowlist.
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index d61bf0c163..7c7f7c4968 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -2606,7 +2606,7 @@ WHERE agent_id = $1 AND issue_id = $2
status = 'completed'
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
)
)
@@ -2636,19 +2636,26 @@ type GetLastTaskSessionRow struct {
// conversation and lose the in-flight context — exactly what MUL-1128's B
// branch is meant to fix.
//
-// Manual rerun (TaskService.RerunIssue) does NOT take this path: it sets
-// force_fresh_session=true on the new task, and the daemon claim handler
-// skips this lookup entirely. The user already judged the prior output bad;
-// resuming the same conversation would replay a poisoned state.
+// Manual rerun (TaskService.RerunIssue) does NOT take this path. The claim
+// handler branches on rerun_of_task_id FIRST and resolves the session/workdir
+// from that exact source task (so a parallel task on the same issue can't be
+// resumed by mistake), reusing the source workdir and resuming its session only
+// when the source failure is resume-safe. The rerun row still carries
+// force_fresh_session=true purely as a rollback-safe signal: an OLD claim
+// handler that predates the rerun_of_task_id branch falls back to this query,
+// and force_fresh_session=true makes it start clean instead of resuming the
+// wrong execution (MUL-4869).
//
// Tasks that ended in a known "poisoned" terminal state are also excluded
// here so even auto-retry does not inherit the bad session. The daemon
// classifies these failures (iteration_limit, agent_fallback_message,
-// api_invalid_request, codex_semantic_inactivity) when it detects either an
-// agent fallback marker in the output, an upstream API 400 that means the
-// conversation history itself is unprocessable (oversized image, malformed
-// base64, etc.), or a Codex semantic inactivity timeout whose recorded
-// session may replay the same stuck state.
+// api_invalid_request, codex_semantic_inactivity, agent_error.context_overflow)
+// when it detects either an agent fallback marker in the output, an upstream
+// API 400 that means the conversation history itself is unprocessable
+// (oversized image, malformed base64, etc.), a Codex semantic inactivity
+// timeout whose recorded session may replay the same stuck state, or a context
+// window overflow that would immediately overflow again on resume. Keep this
+// list in sync with resumeUnsafeFailureReason and GetLastChatTaskSession.
//
// The error-text ILIKE clause is defense-in-depth for the api_invalid_request
// shape: a legacy row tagged 'agent_error' (pre-MUL-1921), a deploy-window
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index dbaf81d44b..4457f05e0d 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -467,7 +467,7 @@ WHERE chat_session_id = $1
status = 'completed'
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
)
)
@@ -488,7 +488,8 @@ type GetLastChatTaskSessionRow struct {
// resume there than start over and lose conversation memory. Used as a
// fallback when chat_session.session_id is NULL. Resume-unsafe failures are
// excluded because replaying those sessions deterministically reproduces the
-// same terminal state.
+// same terminal state. Keep this list in sync with resumeUnsafeFailureReason
+// and GetLastTaskSession.
func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtype.UUID) (GetLastChatTaskSessionRow, error) {
row := q.db.QueryRow(ctx, getLastChatTaskSession, chatSessionID)
var i GetLastChatTaskSessionRow
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index e817ebf8b7..0a07179fe3 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -619,19 +619,26 @@ RETURNING *;
-- conversation and lose the in-flight context — exactly what MUL-1128's B
-- branch is meant to fix.
--
--- Manual rerun (TaskService.RerunIssue) does NOT take this path: it sets
--- force_fresh_session=true on the new task, and the daemon claim handler
--- skips this lookup entirely. The user already judged the prior output bad;
--- resuming the same conversation would replay a poisoned state.
+-- Manual rerun (TaskService.RerunIssue) does NOT take this path. The claim
+-- handler branches on rerun_of_task_id FIRST and resolves the session/workdir
+-- from that exact source task (so a parallel task on the same issue can't be
+-- resumed by mistake), reusing the source workdir and resuming its session only
+-- when the source failure is resume-safe. The rerun row still carries
+-- force_fresh_session=true purely as a rollback-safe signal: an OLD claim
+-- handler that predates the rerun_of_task_id branch falls back to this query,
+-- and force_fresh_session=true makes it start clean instead of resuming the
+-- wrong execution (MUL-4869).
--
-- Tasks that ended in a known "poisoned" terminal state are also excluded
-- here so even auto-retry does not inherit the bad session. The daemon
-- classifies these failures (iteration_limit, agent_fallback_message,
--- api_invalid_request, codex_semantic_inactivity) when it detects either an
--- agent fallback marker in the output, an upstream API 400 that means the
--- conversation history itself is unprocessable (oversized image, malformed
--- base64, etc.), or a Codex semantic inactivity timeout whose recorded
--- session may replay the same stuck state.
+-- api_invalid_request, codex_semantic_inactivity, agent_error.context_overflow)
+-- when it detects either an agent fallback marker in the output, an upstream
+-- API 400 that means the conversation history itself is unprocessable
+-- (oversized image, malformed base64, etc.), a Codex semantic inactivity
+-- timeout whose recorded session may replay the same stuck state, or a context
+-- window overflow that would immediately overflow again on resume. Keep this
+-- list in sync with resumeUnsafeFailureReason and GetLastChatTaskSession.
--
-- The error-text ILIKE clause is defense-in-depth for the api_invalid_request
-- shape: a legacy row tagged 'agent_error' (pre-MUL-1921), a deploy-window
@@ -647,7 +654,7 @@ WHERE agent_id = $1 AND issue_id = $2
status = 'completed'
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
)
)
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index fef86178a8..bb1a7d87be 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -237,14 +237,15 @@ RETURNING *;
-- resume there than start over and lose conversation memory. Used as a
-- fallback when chat_session.session_id is NULL. Resume-unsafe failures are
-- excluded because replaying those sessions deterministically reproduces the
--- same terminal state.
+-- same terminal state. Keep this list in sync with resumeUnsafeFailureReason
+-- and GetLastTaskSession.
SELECT session_id, work_dir, runtime_id FROM agent_task_queue
WHERE chat_session_id = $1
AND (
status = 'completed'
OR (
status = 'failed'
- AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity')
+ AND COALESCE(failure_reason, '') NOT IN ('iteration_limit', 'agent_fallback_message', 'api_invalid_request', 'codex_semantic_inactivity', 'agent_error.context_overflow')
AND NOT (COALESCE(error, '') ILIKE '%400%' AND COALESCE(error, '') ILIKE '%invalid_request_error%')
)
)