Skip to content

fix(codex): skip settled-turn finalization capture after sessions_yield - #124176

Closed
masatohoshino wants to merge 1 commit into
openclaw:mainfrom
masatohoshino:codex-yield-finalization-context-warn
Closed

masatohoshino wants to merge 1 commit into
openclaw:mainfrom
masatohoshino:codex-yield-finalization-context-warn

Conversation

@masatohoshino

@masatohoshino masatohoshino commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Closes #122076

What Problem This Solves

Fixes: a Codex app-server turn that intentionally ends with a successful
sessions_yield is treated as an unfinished silent tool turn, so OpenClaw
attempts settled-turn finalization context capture for it and logs
codex settled-turn finalization context is unavailable whenever that capture
cannot replay the branch — for a turn that completed exactly as intended.

User Impact

Operators no longer see a false "settled-turn finalization context is
unavailable" warning after a Codex turn pauses through sessions_yield, so a
healthy intentional pause stops looking like a finalization failure. Ordinary
non-yield silent tool-result turns are unchanged: they still capture
settled-turn finalization context, and they still emit that warning when the
capture genuinely fails.

Why This Change Was Made

shouldCaptureSettledTurnFinalizationContext in
extensions/codex/src/app-server/run-attempt-finalize.ts selects the capture
from "no assistant text, a tool result, and no prompt error (or failure
finalization explicitly allowed)". A successful sessions_yield turn has
exactly that shape, so the finalizer could not tell an intentional pause from an
incomplete turn. This adds a !toolState.yieldDetected conjunct — the same
"a detected yield is already handled" policy the sibling incomplete-turn gates
already apply (shouldSkipNonVisibleTurnRetry and
resolveSettledToolTerminalContinuationInstruction in
src/agents/embedded-agent-runner/run/incomplete-turn-recovery.ts,
resolveSilentToolResultReplyPayload in incomplete-turn-resolution.ts).

The exclusion covers both terminal outcomes deliberately, because every consumer
of settledTurnFinalizationContext already returns early on a detected yield:

  • resolveSettledToolTerminalContinuationInstruction returns null for a yield,
    and it is the only path that reaches runCodexSettledTurnFinalization — the
    sole reader of the context object;
  • countSettledTurnDeliveryPayloads feeds only that resolver,
    shouldTreatEmptyAssistantReplyAsSilent and
    resolveSilentToolResultReplyPayload, all of which short-circuit on a yield.

A yielded turn therefore consumes no captured context whether it succeeds or
fails; capturing it only risks the false warning. Both outcomes are covered by
the regression cases below.

Evidence

Base: befbed6bd6e (upstream/main). Head: 335116fe6dd.

Diff: one production line plus its comment in run-attempt-finalize.ts; two
parametrized regression cases in the file that now owns settled-finalization
coverage (run-attempt.settled-finalization.test-support.ts); one optional
sessionKey argument on the shared attachSqliteSessionTarget test helper,
whose default is unchanged for every existing caller.

Full-path real behavior proof

Each row below is one complete run of the production attempt path
(runCodexAppServerAttempt → finalizeCodexAttempt) against a real
codex app-server child process
and a real model turn, with the real
sessions_yield tool (src/agents/tools/sessions-yield-tool.ts) reached through
the production dynamic-tool bridge and the real attempt-local
toolState.yieldDetected wiring. Nothing about the tool call, the process, the
model turn or the finalizer is mocked. "before" runs the identical harness
against the branch's exact base commit befbed6bd6e.

The two unreplayable history rows are the reported failure mode: the session
carries an ordinary earlier user image turn, which the settled-turn projection
cannot replay, so capture fails closed and the warning is emitted.

Live case before (befbed6bd6e) after (335116fe6dd)
yielded turn capture selected → context captured (source: harness) capture not selected → context undefined
yielded turn, unreplayable history capture selected → source: unavailable + false warning emitted capture not selected → context undefined, no warning
non-yield control (silent shell tool) capture selected → context captured (source: harness) capture selected → context captured (source: harness)
non-yield control, unreplayable history capture selected → source: unavailable + warning emitted capture selected → source: unavailable + warning emitted

All eight runs (four cases, each run before and after) reached
terminal.kind: "ok", and in every run the turn had the exact shape the
predicate reads: assistantTexts all blank and a toolResult present in
messagesSnapshot. The only input that differed between the yielded rows and
the control rows was yieldDetected.

Recorded observations (redacted to methods, types and tool names)

Yielded case, app-server transcript — identical before and after:

NOTE turn/started
NOTE item/started type=userMessage
NOTE item/completed type=userMessage
NOTE item/started type=reasoning
NOTE item/completed type=reasoning
NOTE item/started type=dynamicToolCall
REQ  item/tool/call tool=sessions_yield
NOTE item/completed type=dynamicToolCall
NOTE thread/status/changed
NOTE turn/completed

Yielded turn with unreplayable history, before (befbed6bd6e):

terminal                          : { kind: "ok" }
yieldDetected                     : true
assistantTexts all blank          : true
messagesSnapshot has toolResult   : true
settledTurnFinalizationContext    : { source: "unavailable" }
warn: codex settled-turn finalization context capture failed { reason: "unsupported_user_image" }
warn: codex settled-turn finalization context is unavailable  { reason: "context_unavailable", ... }

Same case, after (335116fe6dd):

terminal                          : { kind: "ok" }
yieldDetected                     : true
assistantTexts all blank          : true
messagesSnapshot has toolResult   : true
settledTurnFinalizationContext    : undefined   (capture not selected)
settled-turn finalization warnings: none

Non-yield control with the same unreplayable history, after (335116fe6dd)
— the legitimate warning is preserved:

terminal                          : { kind: "ok" }
yieldDetected                     : false
assistantTexts all blank          : true
messagesSnapshot has toolResult   : true
settledTurnFinalizationContext    : { source: "unavailable" }
warn: codex settled-turn finalization context capture failed { reason: "unsupported_user_image" }
warn: codex settled-turn finalization context is unavailable  { reason: "context_unavailable", ... }

Command (the driver is a local-only *.real-binary.live.test.ts harness, not
committed to this branch; it only builds attempt params, starts the real
app-server client and records the finalizer's own outputs and warn calls):

OPENCLAW_LIVE_TEST=1 OPENCLAW_LIVE_CODEX_MODEL=<codex model> \
  node scripts/run-vitest.mjs run --config test/vitest/vitest.live.config.ts \
  extensions/codex/src/app-server/yield-finalization-proof.real-binary.live.test.ts

Focused tests

pnpm test extensions/codex/src/app-server/run-attempt.test.ts — 194 passed,
including the pre-existing non-yield settled-finalization it.each matrix.

Test cost, as the repository policy requires:

  • pnpm test extensions/codex/src/app-server/run-attempt.test.ts --maxWorkers=1
    — 194 passed, 92.8 s wall (Vitest-reported duration 91.08 s).
  • The two cases this PR adds account for 1.76 s of that: 893 ms for the
    completed-yield case and 867 ms for the allowed-failure case. They use the
    suite's existing fake-transport fixture, add no timers, sleeps, polling,
    process boots, serial config or worker pin.
  • CI on this head: the file runs inside the sharded changed-extensions lane.
    All 12 checks-node-changed-extensions-* shards succeeded, between 3 m 48 s
    and 7 m 42 s wall each; the check-run API does not attribute an individual
    file to a shard, so a per-file CI figure is not available.

The two new cases drive runCodexAppServerAttempt with the fake app-server
transport used by every other test in that file, but with the real
sessions_yield tool, the real dynamic-tool bridge and real toolState wiring,
and assert that settledTurnFinalizationContext is undefined and that no
"codex settled-turn finalization context is unavailable" warning was logged —
for a completed yield and for a yield followed by an allowed-failure terminal
outcome. Both fail on the unpatched predicate with
expected CodexSettledTurnContext{…} to be undefined.

Other checks

  • oxfmt --check and oxlint on the three changed files: clean.
  • pnpm tsgo:extensions and pnpm tsgo:extensions:test: clean.
  • git diff --check: clean.
  • pnpm check:changed: "mobile protocol event coverage" and "conflict markers"
    pass. The "line-cap growth ratchet" lane could not run locally — it shells out
    to git cat-file --batch -z, unsupported by the Git 2.34.1 installed here, and
    it fails identically on an unmodified checkout of befbed6bd6e. CI covers it:
    checks-fast-baseline-ratchets succeeded on this head.

What was not tested

createSessionsYieldTool's own requester/session-store side effects beyond the
yield claim (onBeforeYield) are not exercised; they need a real spawned
subagent and are unrelated to this predicate.

@clawsweeper

clawsweeper Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@masatohoshino
masatohoshino marked this pull request as ready for review August 15, 2026 12:59
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 15, 2026
@clawsweeper

clawsweeper Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 21, 2026, 1:32 AM ET / 05:32 UTC (Revision 7).

ClawSweeper review

What this changes

The Codex plugin skips unnecessary finalization-context capture after intentional session yields and adds regression coverage for successful and failed terminal outcomes.

Merge readiness

✅ Ready for maintainer review

This remains a useful, focused fix absent from current main and the latest release. The updated evidence resolves the previous review’s test-cost request, and no blocking correctness or security finding remains.

Priority: P2
Reviewed head: 335116fe6dd50a482872db6e09901f8e6269680e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong relevant runtime observations, meaningful regressions, and the previous evidence follow-up resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Recorded before/after real Codex app-server and model runs exercise the changed production finalizer through the dynamic-tool bridge: intentional yields lose the false warning, while non-yield controls retain capture and genuine warnings.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): Recorded before/after real Codex app-server and model runs exercise the changed production finalizer through the dynamic-tool bridge: intentional yields lose the false warning, while non-yield controls retain capture and genuine warnings.
Evidence reviewed 10 items Verified introduced change: The pinned merge-base-to-head diff adds the yield exclusion, two boundary regression cases, and an optional session key in a test helper. The inspected test-merge commit has the exact pinned base and head parents, and its resulting changes remain confined to these three files.
Current main still needs the fix: The current-main capture predicate checks blank assistant text, a tool result, and eligible terminal status but does not exclude detected yields.
Latest release comparison: The same exclusion is absent at the supplied latest release, v2026.9.5. Local release-blob inspection failed; the GitHub contents API successfully supplied the release source.
Findings None None.
Security None None.

How this fits together

The Codex plugin receives model and tool events from Codex app-server and turns them into OpenClaw attempt results. Its finalizer captures context for unfinished silent tool turns so the agent runner can produce a final answer; intentional yields already bypass that recovery.

flowchart TD
  A[Codex model turn] --> B[Dynamic tool bridge]
  B --> C[Recorded yield state]
  A --> D[Turn completion]
  C --> E[Finalization capture decision]
  D --> E
  E -->|Intentional yield| F[Return paused attempt]
  E -->|Eligible silent tool turn| G[Capture recovery context]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +5, Tests +68. Total +73 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 6 1 +5
Tests 2 69 1 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 75 2 +73

Review metrics

Metric Value Why it matters
Reported regression cost 2 added cases: 1.76 s; focused suite: 92.8 s wall The added cases reuse the existing attempt fixture, and the updated timing evidence resolves the previous review’s required follow-up.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #122076
Summary: This PR is the candidate fix for the reported yield-capture warning; the related instrumentation and truncated-stream changes address distinct behavior.

Members:

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

Technical review

Best possible solution:

Keep intentional yields outside finalization-context capture while retaining ordinary silent-tool recovery and its legitimate diagnostics.

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

Yes: current-main source admits silent yielded tool turns into context capture, and the supplied before/after traces exercise that path with unreplayable image history. This review inspected source and recorded evidence without executing the reproduction.

Is this the best way to solve the issue?

Yes: excluding the existing yield signal at the capture owner matches downstream recovery gates and avoids adding another policy or configuration surface.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 00caa84ce72c.

Labels

Label justifications:

  • P2: This fixes a deterministic misleading warning in intentional Codex yields, with limited operational impact and no demonstrated outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (logs): Recorded before/after real Codex app-server and model runs exercise the changed production finalizer through the dynamic-tool bridge: intentional yields lose the false warning, while non-yield controls retain capture and genuine warnings.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded before/after real Codex app-server and model runs exercise the changed production finalizer through the dynamic-tool bridge: intentional yields lose the false warning, while non-yield controls retain capture and genuine warnings.

Evidence

What I checked:

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • VACInc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-08-15T13:05:24.371Z sha 597659fd678d5bff33ee7e59678aa567c995a2e8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-15T14:46:02.370Z sha 597659fd678d5bff33ee7e59678aa567c995a2e8 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-22T00:35:39.705Z sha 597659fd678d5bff33ee7e59678aa567c995a2e8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-28T02:06:51.767Z sha 597659fd678d5bff33ee7e59678aa567c995a2e8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-03T04:33:50.443Z sha 597659fd678d5bff33ee7e59678aa567c995a2e8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-21T05:20:49.154Z sha 335116f :: needs changes before merge. :: none

@masatohoshino

Copy link
Copy Markdown
Contributor Author

The PR body's "Real behavior proof" section now includes a source citation
answering the question above about verifying the pinned Codex app-server
ordering: the app-server's turn-execution task awaits every in-flight
tool-call future (including the dynamic-tool handler blocking on the
client's response) via a blocking drain_in_flight call before that task
can return, and TurnComplete is constructed only after the task returns
— so turn/completed cannot be emitted while this fix's sessions_yield
tool call is still outstanding
(openai/codex @ a7edf37cb46b,
core/src/session/turn.rs:2715
,
tool response → task return → TurnComplete construction
(core/src/tasks/mod.rs:384-410) → turn/completed emission).

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 15, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Aug 22, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 3, 2026
@VACInc

VACInc commented Sep 6, 2026

Copy link
Copy Markdown
Member

Related merge: #140367 landed in main on September 6, 2026 (04081aa). It changes incomplete-completions classification and the embedded runner's commentary-aware recovery gates.

It does not modify the Codex app-server context-capture predicate in extensions/codex/src/app-server/run-attempt-finalize.ts or add the successful-sessions_yield exclusion proposed here. #122076 is not resolved by this merge. Leaving this PR open.

shouldCaptureSettledTurnFinalizationContext treated a successful
sessions_yield turn (no assistant text, a toolResult, no prompt error) the
same as a genuinely incomplete turn, triggering a doomed context-capture
attempt and a false "codex settled-turn finalization context is unavailable"
warning. Add !toolState.yieldDetected to the predicate, mirroring the
existing yieldDetected gate in incomplete-turn-recovery.ts.

Fixes openclaw#122076
@masatohoshino
masatohoshino force-pushed the codex-yield-finalization-context-warn branch from 597659f to 335116f Compare September 21, 2026 05:07
@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Codex sessions_yield logs a settled-turn finalization context failure

2 participants