← Back to Pull requests

fix(turn-driver): pin UTF-8 on the Codex session evidence I/O #6709

Closed
unknown closed this pull request without merging on Oct 17, 2026 12:02 UTC
View on GitHub
unknown unknown commented on Oct 17, 2026 04:13 UTC
Author

Goal And Delivered Outcome



  • Outcome basis / optional anchor: issue #6708 (self-contained reproduced defect). No roadmap card or RFC id is claimed.

  • Goal/source and gap: the managed Codex session observed the CLI exec JSONL through Path.open() with no codec, and two durable attempt records were written through os.fdopen() with no codec while their own reader re-reads them as UTF-8 bytes (json.loads(path.read_bytes())). On any host whose default encoding is not UTF-8, the read raises before the native identity is observed, and the Turn then fails closed with Codex did not confirm the expected session identity — a state the class contract deliberately does not repair with a fresh conversation. The shipped UTF-8 file gate could not see either site, because it inspects read_text() / write_text() / builtin open() only.

  • Observable before → after, with the validation row that proves it: on a host whose default codec is cp936, observe() on an ordinary UTF-8 event stream containing non-ASCII model text raises UnicodeDecodeError: 'gbk' codec can't decode byte 0x90 ... before the change and returns the observed identity after it (regression_parity and unit rows below).

  • Reach, checked by searching the tree rather than assumed: CodexAgentSession.observe() has no caller under loopx/. The production callers are benchmark/runtime/worker.py:510, benchmark/runtime/checkpoint_wake.py:214, and benchmark/runtime/checkpoint_session_refresh.py:80 — the only production caller of prepare_checkpoint_refresh. The ordinary Turn path streams events over a pipe (codex_cli.py) and never performs this file read, so the capability this repairs today is the benchmark wake / checkpoint-refresh harness on a non-UTF-8 host. It is worth repairing here because the failing class is shared control-plane code on the host class this repository ships for (windows-powershell, cp936), the failure is post-spend and non-retryable under the class contract, and the gate rule closes the API-class hole for every future caller.

  • Issue/task and intended base: Fixes #6708, base main (110893bca, rebased).


  • Author Declaration



  • Written by: model_agent — DeepSeek family, through the DeepSeek Harness agent runtime.


  • Implemented against



  • Specification and revision: the reproduced defect in issue #6708; the shipped UTF-8 file-gate contract in tests/test_loopx_text_io_utf8.py (revision 110893bca); the class contract documented in loopx/control_plane/turn_driver/codex_agent_session.py (CodexAgentSession docstring: "A native ID must be observed even on timeout; neither missing history nor a failed resume permits a fresh fork").

  • Criteria:


  • | Criterion (spec clause) | Disposition | Symbol / path | Test or command |
    | --- | --- | --- | --- |
    | Shipped text file I/O pins UTF-8 explicitly (tests/test_loopx_text_io_utf8.py) | implemented | tests/test_loopx_text_io_utf8.py (_text_io_calls_without_utf8_encoding) | the extended gate reports no Codex site; its self-check covers os.fdopen missing/binary/keyword/positional codec shapes |
    | The observed Codex event stream is decoded as the UTF-8 JSONL the CLI writes (CodexAgentSession.observe) | implemented | loopx/control_plane/turn_driver/codex_agent_session.py | pytest tests/control_plane/test_codex_session_utf8_evidence.py |
    | A durable attempt record is written with the codec its own reader assumes (prepare_checkpoint_refresh, _fork_native_checkpoint) | implemented | loopx/control_plane/turn_driver/codex_agent_session.py, loopx/hosts/codex_checkpoint.py | protected by the gate rule: reverting both pins leaves this suite green and makes tests/test_loopx_text_io_utf8.py report codex_agent_session.py:173 and codex_checkpoint.py:415. The write is latent rather than reproduced — json.dump escapes non-ASCII by default, so the record bytes are ASCII even under cp936. |

  • Self-check before submission: read the complete diff and both call sites, re-ran the gate's self-check, the focused session/checkpoint suites and ruff, and confirmed with the fix reverted that the new suite fails and the two unrelated failures below reproduce at the base. Deliberately left out: the trajectory-assessment offenders owned by #6691, the packages/ scope the file gate does not scan, and the Path.open() receiver-shape gap the gate cannot decide statically (named under Coverage and gaps).


  • Scope And Continuation



  • Completed scope and remaining work: complete within this scope. Three codec pins, one gate rule, one focused regression suite.

  • Slice boundary / successor: N/A. The remaining Path.open() receiver-shape gap is documented in the test suite rather than deferred to a new task; the wide packages/ inventory is a separate, larger piece of work and is not claimed here.


  • Validation



  • Tested revision: e1da32c1cb9409ece520e5b8d8265a10338dace9

  • Run state: finished

  • Input classes: synthetic, public_fixture


  • | Check kind | Result | Public-safe evidence / limitation |
    | --- | --- | --- |
    | regression_parity | passed | Baseline (same source, fix reverted): UnicodeDecodeError: 'gbk' codec can't decode byte 0x90 in position 50: illegal multibyte sequence, raised from codex_agent_session.observe at loopx/control_plane/turn_driver/codex_agent_session.py:96. Head: pytest tests/control_plane/test_codex_session_utf8_evidence.py → 2 passed. The non-UTF-8 default codec is the reproduced condition; the downstream RuntimeError: Codex did not confirm the expected session identity is quoted from the class contract in codex_agent_session.py, not independently reproduced on this host. |
    | unit | passed | pytest tests/control_plane/test_codex_session_utf8_evidence.py -q → 2 passed. Both cases drive the shipped owners in a child interpreter with -X utf8=0, LC_ALL=C, PYTHONCOERCECLOCALE=0; the child asserts its own default codec is not UTF-8 and then decodes the exact bytes it writes, so the case cannot pass vacuously. On a host whose codec accepts those bytes (latin-1, cp1251) the child reports it and the case skips with the resolved codec named instead of claiming coverage; the probe was checked against cp936, ascii, cp1252, cp1250, cp1257, latin-1, cp1251 and utf-8. |
    | integration | passed | pytest tests/control_plane/test_codex_checkpoint_context_refresh.py tests/test_loopx_turn_driver.py tests/control_plane/test_codex_session_utf8_evidence.py -q → 126 passed, 2 failed. Both failures reproduce with the diff reverted: test_redirected_original_output_cannot_recover_an_identity needs symlink privilege on this host, and test_default_agent_session_reuses_planning_across_completed_todos reads the fake Codex executable as text (Path.read_text() on a binary) before any changed code runs. |
    | static | passed | ruff check on the four changed paths → All checks passed!; the gate's own self-check case (test_guard_reports_missing_and_non_utf8_codecs) passes with the new os.fdopen shapes. |
    | integration | passed | pytest tests/test_loopx_text_io_utf8.py -q -> 2 passed at this head. The 12 pre-existing trajectory-assessment offenders this PR disclosed at cd148933b were fixed by #6691 (560fc66b9, merged before this head) and the rebased base 110893bca carries them, so the gate is green here with nothing deselected; stripping the pins from the two shipped files in a scratch copy still makes it report codex_agent_session.py:173 and codex_checkpoint.py:415. pytest tests/control_plane/test_codex_checkpoint_context_refresh.py tests/test_loopx_turn_driver.py tests/control_plane/test_codex_session_utf8_evidence.py -q -> 126 passed, 2 failed; both failures reproduce with the diff reverted: test_redirected_original_output_cannot_recover_an_identity needs symlink privilege on this host, and test_default_agent_session_reuses_planning_across_completed_todos reads the fake Codex executable as text (Path.read_text() on a binary) before any changed code runs. |

    | unit | passed | Review-follow-up head e1da32c1c (rebased on main 110893bca): the same two cases on Linux Python 3.12 (python:3.12-slim, repository mounted at /src) -> 2 passed; with only path.open(encoding="utf-8") reverted in a scratch copy -> 2 failed with UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 36 from the observe read. The earlier heads a786ed7cb and 400d7a1cb failed both cases on that host before importing loopx (Unable to decode the command from the command line), because -c text is decoded with the ASCII filesystem encoding; the child program now travels on stdin (CPython decodes stdin source as UTF-8) and the fixture's workspace is the filesystem-safe tmp_path, while the non-ASCII payload stays in the CLI's UTF-8 event bytes. Windows cp936, focused suite + gate: 4 passed. |

  • Coverage and gaps: the changed behavior is covered end to end — the same child process exercises the observe read and the attempt-record read path, and the gate rule is mutation-checked by the guard's self-check. Not covered: hosts whose default codec decodes the sample (the case names the codec and skips rather than passing for the wrong reason), the two os.fdopen write pins (latent, as above, and guarded only by the gate rule), the packages/ tree the file gate does not scan, and Path.open() receivers whose type cannot be decided statically — the gate still cannot reject that API shape, which is why the regression suite exists next to it. Same-class sites outside this PR's scope, left for their existing owners: trajectory_assessment.py:190/191 (fixed by #6691, 560fc66b9), benchmark/runtime/worker.py:487 and :524 (outside the gate's loopx/ scan root), and the test-side tests/test_loopx_turn_driver.py:1032.


  • Frontend / Visual Evidence



  • UI impact: none

  • Before: N/A

  • After: N/A

  • States and viewports shown: N/A

  • Source data: none

  • Attention review: N/A — no user-visible surface changed.

  • Craft review: N/A — no user-visible surface changed.


  • Type of Change



  • Bug fix

  • Test update


  • LoopX Area



  • Control plane (goals, todos, quota, scheduler, registry, runtime)

  • Host or runtime integration


  • Technical Direction



  • Direction / acceptance reference, when applicable: core control-plane hardening of an existing owner; no RFC or roadmap id is claimed.


  • Shared-authority RFC fixture impact



  • Production-scale fixture schema: N/A

  • Semantic dimensions changed, or reviewed no-impact rationale: N/A — no state, protocol or vocabulary change.

  • Provider conformance arms run: N/A

  • Read-only legacy/file/PostgreSQL three-arm rehearsal (required for promotion, runtime-routing, or compatibility-projection changes): N/A


  • Boundary Checklist



  • Neither the diff nor this PR body/comments/attachments disclose private state, credentials, raw traces or verifier output, internal links, or local machine paths (including .loopx/, .codex/goals/, and live ACTIVE_GOAL_STATE.md).

  • I did not duplicate maintainer-owned benchmark work unless a maintainer split out a public issue for it.

  • I kept the change scoped to the linked issue/task.

  • Existing English/Chinese RFC pairs (including ledger entries) both have a diff, and the local premerge check python3 scripts/check_rfc_bilingual.py --base origin/main --head HEAD passes, or no paired RFC changed.

  • I completed the visual evidence section for UI changes, or marked UI impact none.

  • Every commit includes a DCO Signed-off-by trailer (git commit -s).


  • AI disclosure: this change was drafted with AI assistance at my request, under my direction and review.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: JasonBuildAI Review duration: 469m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #6709"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%