Skip to content

fix(native-chat): a failed Codex turn keeps its failure and "Worked for" - #23514

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/codex-turn-settles-once
Sep 28, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/codex-turn-settles-once

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​321 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​321
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​43 $\color{#cf222e}{\Huge{\mathbf{−}}}$​58 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15

ELI5

When a Codex turn fails, Codex tells Orca twice: once with an error, then again with a "turn finished: failed" message. Orca ended the turn both times. Usually the second end was thrown away, but if the two arrived close enough together, the second one replaced the first and the chat showed the failed turn as interrupted with no "Worked for" time. Now Orca ends a turn once, and the first ending is final.

What Changed

Before: Codex reports a turn-ending fault as an error, and then always sends a failed turn/completed for the same turn. Orca's Codex translator ended the turn on the error (recorded as failed, with its start time and the message that opened it) and forgot that turn's state. When the completion arrived, it ended the same turn a second time from nothing: interrupted, no start time, no link to the opening message.

When the user saw it: both endings are written under the same settlement id, and the journal skips a settlement id it has already applied, so most of the time the second ending never landed. It did land when the completion arrived while the error's ending was still waiting in the session's write queue behind an earlier write (for example the error's own status row). That queue merges pending lifecycle writes with the same settlement id, so the second ending replaced the first before either was written. The turn was then stored as interrupted without a start time, so the host no longer gave it a "Worked for" duration.

After: both ways a Codex turn ends go through one step, and a turn's first ending is final. A later end for a main-thread turn Orca has already ended publishes nothing (subagent threads have no turn record, so a second end there changes nothing either). That covers an error followed by a completion, a duplicate completion, and a second error. The journal's settlement-id check is still there, but it is no longer what keeps a failed turn's record correct.

Mechanism: complete() and fail() in codex-structured-journal-translation-turn-boundaries.ts each carried a copy of the settle logic, and only fail() skipped a turn that was no longer open. They now share one end(), whose first check is whether the translator's existing window of recently settled turns (CodexJournalRecentTurns) already holds the turn. No new state is added.

Why

Checked in Codex's own source: a turn-ending error is followed by TurnComplete, which the app-server maps to a failed turn/completed for the same turn. So every failed Codex turn produced a second ending; whether it reached the stored record depended only on write timing.

Fixing it where the second ending is produced removes the double write at its source. Relying on the journal's dedupe left it exposed to anything that merges or reorders writes before they reach the journal, which is exactly what the write queue does.

The later completion's only extra field is Codex's own duration, which Orca's timing uses only when both host timestamps are missing; the first ending has both. An echo arriving after the turn ended still updates the record through the existing request-origin revision, and a provider exit settles through the session sweep, so neither path relied on a second ending.

Alternative considered: skipping only "a completion after an error". Rejected, because a duplicate completion would still produce a second write for a finished turn; one rule where a turn ends covers every order.

Alternative considered: stop treating the turn-ending error as an end and let turn/completed alone settle the turn, since current Codex always sends it. Not done here: the error ending was added (#22047) because a failed turn could otherwise read as working forever, and removing it is a separate behaviour change that first needs a capture from the oldest supported Codex showing the completion always follows. With both ends kept, the first one has to be final.

Linked Issue

No issue. Found while reviewing #23059, which fixes the same pattern for a failed Codex /compact in its own new code. This PR fixes the ordinary-turn path that is on main today. The two touch the same file and will be merged together cleanly by whichever lands second.

Visual Proof

N/A: no UI change of its own, and the failure depends on write timing. Live QA on main plus #23552 with a real Codex model failure did not reproduce the relabel (0 of 6 failed turns), because the queue merge needs the two frames to overlap a pending write. With this PR, the same real failure was checked live: one settlement, the turn stays failed, "Worked for" stays, and nothing relabels it after 10 seconds.

With this PR (and current main), a real Codex turn that failed because the account rejects the model. Ten seconds after it ended, the turn still reads failed (red), with its "Worked for":

failed turn 10 seconds after it ended

The same turn expanded, showing the error rows:

failed turn with its error rows

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New codex-structured-journal-turn-settles-once-journal.test.ts drives a real translator, the real session write queue and a real on-disk journal. It sends a turn-ending error (willRetry: false) and the failed turn/completed back to back while the error's status row is still being written, so the two endings meet in the queue. It checks the stored turn stays completed with outcome failure, keeps its start time and error-time end, and still yields a 2-second "Worked for" duration. With main's translator it fails: the turn is stored as interrupted with no start time. With a drain between the two frames, main's translator passes, which confirms the queue merge is the path.

New codex-structured-journal-translation-turn-settles-once.test.ts checks the translator alone:

  • The real frame order (start, the user message echo, content, a turn-ending error, then turn/completed status failed): exactly one terminal write, a record that stays completed with outcome failure and keeps its start time, request time and message link, and one error row.
  • A duplicate turn/completed does not produce a second write for a successful turn.
  • An ordinary turn is unchanged, and the turn after a failed one settles on its own.

Reverting the fix makes the new journal test fail and the first two translator tests fail ("expected 1 terminal write, got 2"). Node typecheck, oxlint and the changed-lines quality gate pass, as do the eight Codex structured-journal translation suites, the new journal test and the event-sink suite (132 tests).

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Author X: @BrennanKB5

Security: none. Cross-platform, SSH and mobile: the translator runs on the execution host; no wire or client change. Backwards compatibility: none affected; it only stops a second write.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Codex follows a turn-ending `error` with a failed `turn/completed` for the
same turn. The error settled the turn and dropped its start and attributed
send; the completion then re-settled it from nothing, so the record lost its
start time and flipped from completed/failure to interrupted/failure. A
failed turn lost its "Worked for" and read as interrupted.

Both ends now go through one settlement that refuses a turn already in the
recent-turns window, so every later end (error then completion, a duplicate
completion) adds nothing and overwrites nothing.
The fixture was labelled and worded as a failed compaction; this change
covers the ordinary-turn path, so its frames now read as one.
@brennanb2025

brennanb2025 commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Review status: ready for review

Head: 225485e81a2, which merges current main. CI: 20 passing, 14 skipped by path, 0 failing. One shard first failed in transcript-watch-liveness.test.ts, which this PR does not touch; it passes locally 7/7 and passed on rerun.

Does it fix the problem? Yes. A failed Codex turn now stays failed and keeps its "Worked for", start time and message link instead of flipping to interrupted. Every turn-ending Codex error is followed by a failed turn/completed for the same turn (checked in Codex's own source), so every failed turn produced a second ending. Main's journal usually throws the second one away, because both endings share one settlement id. The second ending only reached the record when it arrived while the first was still waiting in the write queue, where writes with the same id merge.

Live QA on this laptop, with real Codex and a model the account rejects, which makes Codex send error and then a failed turn/completed for the same turn:

  • With this PR: one settlement, the turn stays failed, "Worked for" is kept, and there is no relabel 10 seconds later. The same holds with main merged in.
  • On main: the relabel did not reproduce in 6 of 6 failed turns, because it needs the two endings to overlap a pending write.

New host-level test: it runs through the real translator, write queue and on-disk journal, and makes the two endings merge in the queue. It is red on main's translator (the turn is stored as interrupted with no start time) and green with this PR. With a drain between the two endings it passes on main, which confirms the queue merge is the only path.

Architecture: both ways a turn ends go through one step, and a turn's first ending is final, using the translator's existing window of recently settled turns (no new state). This removes the double settle rather than guarding one order of it.

Review loop: clean. Checked by reading the code: nothing the skipped second ending used to do is lost:

  • no items or prompts can start after the error;
  • a late message echo still updates the record;
  • the only field lost is the provider duration, which is a fallback only.

Also checked:

  • Recent-turns window: it holds 256 turns / 256 KB, keyed by thread and turn, so an eviction between the error and its completion can't happen.
  • Child threads: unchanged.
  • Restore and rewind: they publish records directly and never call this step.
  • Tests: reverting the fix fails the failure-order and duplicate-completion tests.

Not run: live QA. A real failing Codex turn needs a signed-in Codex, which the isolated review rig doesn't have; the tests replay Codex's real frame order.

Related: #23059 fixes the same pattern for a failed /compact in its new code; the two touch the same file.

Late steps from the full review prompt:

  • The readiness checklist passed at the start (run late, after the earlier review) and at the end, with no P0, P1 or P2 findings.
  • One fresh review loop came back clean: 170 tests across the Codex journal suites pass, and removing only the new check turns 3 tests red.
  • A precedent check found that making the first ending final is the standard way to handle a turn that ends twice.
  • Screenshots of the failed turn after the fix are in the body.

@brennanb2025
brennanb2025 marked this pull request as ready for review September 28, 2026 09:40

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Settle-once turn end: complete() and fail() now share one private end(), whose first check is whether CodexJournalRecentTurns already holds the turn; a turn's first terminal settlement is final. This stops the failed turn/completed Codex always sends after a turn-ending error from overwriting the fail() record with one that has no startedAt (and therefore no "Worked for").
  • CodexJournalRecentTurns.has: new accessor on the bounded recent-turns window, plus a doc comment noting the window now also blocks a second settlement.
  • Translator test (codex-structured-journal-translation-turn-settles-once.test.ts): pins error-then-completion to a single terminal write with the opening message, start time, request time and one error row; a duplicate completion to one write; an ordinary turn unchanged; and the next turn settling on its own.
  • Journal test (codex-structured-journal-turn-settles-once-journal.test.ts): drives the real translator, deferred sink queue and on-disk journal with the two ends overlapping a pending write, and asserts the stored turn stays completed/failure with a 2-second "Worked for".

I verified these are not theatre by reverting the two production files to origin/main: three of the five new tests fail exactly as described (two terminal writes; interrupted with no startedAt), and all five pass with the fix. The full codex-structured-journal-* set (15 suites, 151 tests) passes, as do tc:node, check:code-quality:changed and oxlint on the changed files. The logic reads soundly: fail() only fires for willRetry: false errors and requires an active turn (always start()ed with startedAt), recentTurns is populated only for the primary thread so the guard is inert for subagent threads, and no path relied on the second settlement (late echoes revise via attributeRequest; provider exit settles through the session sweep).

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: a3cf1710-b19d-49d1-ba27-6ec7b8402dd2

📥 Commits

Reviewing files that changed from the base of the PR and between a174a08 and 225485e.

📒 Files selected for processing (4)
  • src/main/codex/codex-structured-journal-translation-turn-boundaries.ts
  • src/main/codex/codex-structured-journal-translation-turn-settles-once.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-state.ts
  • src/main/codex/codex-structured-journal-turn-settles-once-journal.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

complete and fail now pass terminal data to shared settlement logic. The handler skips turns already present in recent-turn state and records accepted terminal turns. Tests cover duplicate and independent settlements, successful completion, and a failed turn written to the on-disk journal.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 22548

No actionable merge-blocking issue was established. The queue-regression test’s coverage remains unconfirmed, but the available evidence does not show a failure that should prevent merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 22548

The change preserves the first accepted turn ending, preventing a later completion message from erasing a recorded failure and elapsed time. No expanded access or privileges were identified. Protection against unusually delayed duplicate events remains bounded.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The identified effect is on lifecycle records for turns in a Codex session. The inspected dispatch path shows no new caller, privilege, or cross-service dependency.

Trust Boundaries and Controls

  • observed — Codex notifications enter the existing translator. The failure path requires an active turn, and journal batches pass through sink admission and a journal-side applied-settlement check.

Resilience and Maintainability Implications

  • inferred — Journal deduplication protects an already applied settlement, but cannot protect a first write that is replaced while still pending in the sink queue. Whether provider events can arrive late enough to exceed the recent-turn window remains unverified.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: preserving failure state and the “Worked for” duration for failed Codex turns.
Description check ✅ Passed The description is detailed and mostly complete. It covers the user-visible behavior, implementation, rationale, alternatives, testing, screenshots, and compatibility considerations. It states that no…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@brennanb2025
brennanb2025 merged commit 2c92e5e into main Sep 28, 2026
93 of 95 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant