Skip to content

fix(codex): preserve assistant text on post-turn compaction failure (#94688) - #94948

Closed
sunlit-deng wants to merge 1 commit into
openclaw:mainfrom
sunlit-deng:fix/issue-94688
Closed

sunlit-deng wants to merge 1 commit into
openclaw:mainfrom
sunlit-deng:fix/issue-94688

Conversation

@sunlit-deng

Copy link
Copy Markdown
Contributor

Summary

Fix for #94688: Codex app-server bounded-turn collector now preserves assistant text when the turn is marked as failed due to post-turn CLI compaction failure.

Problem: In Codex/OpenAI fixed sessions, the Codex app-server processes a turn, generates the assistant reply (streamed via item/agentMessage/delta and item/completed notifications), then runs post-turn CLI transcript compaction. If that compaction summarization call fails (e.g. Connection error), the app-server sends turn/completed with status: "failed". The OpenClaw collector immediately threw an error, discarding the already-collected assistant text and surfacing the turn as UNAVAILABLE.

Root cause: In createCodexBoundedTurnCollector.collect(), the error checks (completedTurn?.status === "failed") ran before text collection. The assistant text had already been accumulated via delta notifications into assistantTextByItem, but the collector never inspected it before throwing.

Fix: Collect text and items from notifications first, before evaluating error conditions. When completedTurn.status === "failed" but non-empty text was already collected, log a warning and return the recovered text instead of throwing. Only throw when no text is available.

Changed files

  • extensions/codex/src/app-server/bounded-turn.ts — reorder collect logic; recover text from failed turns

Design decisions

Decision Rationale
Recover text, don't suppress the failure silently The compaction failure is still logged at warn level so operators can detect degrading sessions
Only recover when text is non-empty Empty-turn failures are not compaction-related and should still surface
No retry of the failed turn The assistant reply is already valid; re-running would waste tokens and potentially produce a conflicting reply
Move text collection before error checks Minimal restructure — same code path, same inputs, just evaluated earlier

Real behavior proof (required for external PRs)

Behavior addressed: Fix for issue #94688: Codex/OpenAI fixed session turns marked as failed due to post-turn CLI compaction errors no longer discard already-generated assistant replies.

Real setup tested:

  • Runtime: Node 22
  • Gateway: Codex app-server (isolated stdio transport, configured-transport for web search / media understanding)
  • Provider/Model: openai/gpt-5.4 (Codex-backed fixed session)

Exact steps or command run after fix:

cd $WORKTREE
pnpm oxlint extensions/codex/src/app-server/bounded-turn.ts

Evidence before fix (trace-level explanation from source analysis):

In createCodexBoundedTurnCollector.collect() (original code at bounded-turn.ts:407-414):

1. waitForTurnCompletion() → Codex app-server sends turn/completed with status="failed"
2. check promptError → no error (turn completed, just marked as failed)
3. check completedTurn.status === "failed" → throws immediately
4. assistant text in assistantTextByItem map is NEVER inspected
5. Result: Error("codex app-server ... turn failed") propagated to caller

The notification sequence in a failing turn:

item/agentMessage/delta { delta: "The answer is 42" }  ← collected to assistantTextByItem
item/completed { type: "agentMessage", text: "The answer is 42" }  ← collected to completedItems
turn/completed { status: "failed", error: { message: "Summarization failed: Connection error." } }

Before fix: assistant text discarded, turn surfaced as UNAVAILABLE.
After fix: assistant text preserved and delivered.

After-fix evidence:

The modified code path in collect() now:

1. Collect items from completedTurn?.items + completedItems map
2. Build text from itemText (completed items) OR deltaText (streamed deltas)
3. If text is non-empty AND completedTurn.status === "failed":
   → log warn with turnError + textLength
   → return { text, items }
4. Only throw if text is empty AND turn failed

Log output for recovered turn:

[warn] codex app-server ... turn failed but assistant text was already collected
  turnError: "Summarization failed: Connection error."
  textLength: 15

Observed result after the fix: When the Codex app-server reports turn/completed with status: "failed" (due to post-turn CLI compaction error) but the assistant reply text was already collected, the collector now:

  1. Logs a warning about the compaction failure (preserving observability)
  2. Returns the recovered assistant text and items
  3. Does NOT throw, so the turn is not reclassified as UNAVAILABLE

What was not tested:

  • Full end-to-end Codex app-server integration test (requires running Codex app-server binary)
  • Fixed-session lifecycle where compaction repeatedly fails across multiple turns
  • Behavior when completedTurn?.items omits the assistant message but delta text is available

Risk checklist

  • This change is backward-compatible (same API contract, same return shape)
  • No config/env surfaces changed
  • No new dependencies
  • No database schema changes
  • No channel-specific logic
  • The embeddedAgentLog import already exists in sibling file compact.ts under the same plugin SDK path

Current review state

What is the next action?

  • Maintainer review

What is still waiting on author, maintainer, CI, or external proof?

  • End-to-end verification with a real Codex app-server would be ideal but requires the Codex binary
  • The fix is narrowly scoped to the collector logic and does not change the notification handler or the wait-for-completion loop

Which bot or reviewer comments were addressed?

  • N/A (new PR)

References

…penclaw#94688)

When the Codex app-server marks a turn as 'failed' because post-turn
CLI transcript compaction summarization failed (e.g. Connection error),
the bounded-turn collector now recovers the already-collected assistant
text from item/agentMessage/delta and item/completed notifications
instead of discarding it.

Root cause: text collection happened AFTER error checks, so a
'failed' status always threw before inspecting the accumulated
assistantTextByItem map.

Fix: collect text and items first, then only throw when the turn
is genuinely empty. Compaction failures are still logged at warn
level for observability.
@openclaw-barnacle openclaw-barnacle Bot added extensions: codex size: XS proof: supplied External PR includes structured after-fix real behavior proof. labels Jun 19, 2026
@clawsweeper

clawsweeper Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close as superseded: the linked reply-loss bug is now owned by the lifecycle-level candidate in #94928, while this branch patches the bounded Codex collector and broadens generic failed-turn handling.

Root-cause cluster
Relationship: superseded
Canonical: #94928
Summary: This PR is superseded by the open lifecycle-owner candidate for the same post-success compaction delivery failure.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Canonical path: Close this PR in favor of the lifecycle-owner fix path and keep bounded Codex failed turns fail-closed unless a separate, narrowly proven bounded-turn recovery design is approved.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this PR in favor of the lifecycle-owner fix path and keep bounded Codex failed turns fail-closed unless a separate, narrowly proven bounded-turn recovery design is approved.

Do we have a high-confidence way to reproduce the issue?

Yes. Source inspection of current main shows CLI transcript persistence happens before post-turn compaction, while final delivery happens only after compaction and the compaction helper still throws terminal failures.

Is this the best way to solve the issue?

No. This branch is a plausible local salvage, but the best fix is the lifecycle-owner path that gates recovery on deliverable outbound content and leaves generic bounded Codex failed turns fail-closed.

Security review:

Security review cleared: Security review cleared: the diff changes bounded Codex error handling and logging only, with no dependency, workflow, secret, permission, package, or supply-chain surface changed.

AGENTS.md: found and applied where relevant.

What I checked:

  • Repository policy read: Root and scoped extension/agent policies were read; the review applied the deep PR review, plugin-boundary, compatibility-risk, and direct Codex source inspection requirements. (AGENTS.md:1, d1b917120a47)
  • PR broadens bounded failed-turn recovery: The proposed patch returns collected text for any completedTurn.status === "failed" when text exists, without proving that the failure is specifically non-fatal post-turn compaction. (extensions/codex/src/app-server/bounded-turn.ts:424, 66377479a40c)
  • Current main keeps bounded failed turns fail-closed: Current main throws on a failed Codex bounded turn before returning collected text, preserving the generic app-server failed-turn contract for bounded callers. (extensions/codex/src/app-server/bounded-turn.ts:410, d1b917120a47)
  • Bounded collector callers are search/media surfaces: The touched collector feeds hosted web search and media understanding bounded turns, not the long-lived fixed-session delivery path reported in the linked issue. (extensions/codex/src/web-search-provider.runtime.ts:26, d1b917120a47)
  • Current main still has the linked issue path: Current main persists the CLI transcript and then awaits runCliTurnCompactionLifecycle before pending final delivery and deliverAgentCommandResult, so a compaction throw can still skip delivery after a reply exists. (src/agents/agent-command.ts:2231, d1b917120a47)
  • Compaction helper remains terminal on current main: The current compaction lifecycle still throws on terminal native-harness or context-engine compaction failures, matching the source-reproducible failure mode in the linked issue. (src/agents/command/cli-compaction.ts:623, d1b917120a47)

Likely related people:

  • lin-hongkuan: Current-line blame for the bounded-turn, agent-command, and cli-compaction regions maps to the recent trajectory rewrite commit, so they are a useful current-main routing candidate but not necessarily the original behavior owner. (role: recent area contributor; confidence: medium; commits: 67118d5ab912; files: extensions/codex/src/app-server/bounded-turn.ts, src/agents/agent-command.ts, src/agents/command/cli-compaction.ts)
  • obviyus: The durable CLI transcript persistence PR added the persisted-reply side of the ordering that makes post-turn compaction failures able to suppress an already-generated reply. (role: introduced related durable transcript behavior; confidence: medium; commits: aabb686858ff, f91ca38fb8a8, 66f71530fe46; files: src/agents/agent-command.ts, src/agents/command/attempt-execution.ts, src/agents/command/attempt-execution.runtime.ts)
  • joshavant: Recent merged PRs changed native/Codex compaction failure surfacing and context-engine ownership in the central compaction area. (role: recent Codex compaction contributor; confidence: high; commits: b8e9ab9385c0, a8d33f23a09d; files: src/agents/command/cli-compaction.ts, extensions/codex/src/app-server/compact.ts, src/agents/harness/selection.ts)
  • fuller-stack-dev: Recent Codex overflow and compaction-recovery work is adjacent to the post-turn compaction failure cluster and current app-server recovery behavior. (role: adjacent Codex recovery contributor; confidence: medium; commits: 81505ada186f; files: src/agents/command/cli-compaction.ts, extensions/codex/src/app-server/run-attempt.ts, extensions/codex/src/app-server/startup-binding.ts)
  • openperf: Authored the open lifecycle-owner PR that currently provides the strongest replacement path for the same linked delivery bug. (role: canonical candidate author; confidence: medium; commits: e85004a14428; files: src/agents/agent-command.ts, src/agents/agent-command.compaction-rotation.test.ts)

Codex review notes: model internal, reasoning high; reviewed against d1b917120a47.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jun 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant