Skip to content

fix(codex): prevent stale compaction after session rollover - #138767

Merged
vincentkoc merged 1 commit into
mainfrom
fix/codex-fence-current-binding-generation
Sep 5, 2026
Merged

vincentkoc merged 1 commit into
mainfrom
fix/codex-fence-current-binding-generation

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Sep 5, 2026 •

Copy link
Copy Markdown
Member

Related: #138473

What Problem This Solves

Fixes an issue where a queued Codex compaction admitted under one durable session generation could continue after the same session key rolled over to a successor generation. An already-readable native binding bypassed the durable-row generation fence, so stale work could acquire a client or write after ownership had moved.

Why This Change Was Made

Codex binding resolution now captures tri-state authority from the canonical session row: a current durable row composes an exact (sessionId, previousSessionId) host assertion with the caller assertion, no row remains scoped ephemeral, and mismatched or unreadable authority fails closed. Reclaim and ordinary resolution share that prepared capture without persisting authority.

Compaction now resolves the binding once before client selection and narrowly converts only resolver-time cancellation into the existing compaction result. The merged pre-write rejection, ambiguous-write retirement, watcher, cleanup, and finalization paths remain unchanged.

User Impact

Queued Codex compaction can no longer act through a stale native-thread binding after same-key session rollover. The successor generation can adopt the existing native thread without a stale client acquisition or write from its predecessor.

Evidence

Local ClawSweeper completed on exact range 7b1795acc6783273c4218a511011bc1f7f13bd65..f44a3ffaa5831ccaf157f5fb9e751cab34a02298 after using an isolated authenticated reviewer home. It found no code defect, cleared security, judged the shared-owner fix correct, and requested the live final-effect proof recorded above. Hosted ClawSweeper then reviewed the same exact head with no findings and no before-merge actions: #138767 (comment). Hosted CI is green at that SHA. Fresh generic autoreview also completed on exact commit f44a3ffaa5831ccaf157f5fb9e751cab34a02298: scoped clean, no P0/P1 findings, patch correct at 0.93 confidence.

Agent Transcript

Redacted codex session transcript: fix(codex): fence current bindings against host rollover
source: [LOCAL_SESSION]
redaction: local paths, emails, phone-shaped strings, token-shaped strings, auth headers, auth query params
omitted: raw tool outputs, system/developer prompts, local paths, secrets, browser/session/auth details
stats: {"agent":"codex","entries":5,"user":2,"assistant":2,"toolCalls":220,"toolOutputsDropped":219,"web":0,"redactions":1,"omittedUnsafe":0,"rawEntries":37}

[user]
Proceed as sole executor for a new follow-up PR from current main. Preserve both old dirty GWTs untouched. Read `CONTRIBUTING.md`, root/scoped AGENTS, relevant PR templates, `.agents/skills/test-audit/SKILL.md`, `.agents/skills/clawsweeper/SKILL.md`, and `.agents/skills/agent-transcript/SKILL.md` before contribution.

1. Fetch latest `origin/main`; verify squash `c26e46b2f87ad50d2f655e44975eafc8d394527f` is an ancestor. Compare its tree with merg
...[truncated 3150 chars]

[assistant]
hi. i’m re-anchoring on current `origin/main`, contribution policy, and the preserved patch evidence first. then i’ll build this in a fresh GWT and keep both old dirty worktrees untouched.

policy is clear: this is a new bug-fix PR, no changelog edit in a normal PR, and uncommitted autoreview is mandatory. i’m now verifying current main, squash ancestry/tree identity, the exact sibling Codex contract, and duplicate PR state before creating the fresh worktree.

current main is exactly the squash commit and contains it. its full tree is not identical to `f4e1c` because the squash was produced on a much newer main base; the four target files still need a focused comparison. GitHub GraphQL is rate-limited, so duplicate search will use REST/git-backed checks before any PR mutation.

the fresh GWT is clean at `c26e46b2`, with linked dependencies and the generation-finalization test already registered. the four target files are byte-identical between merged `f4e1c` and squash `c26e46b2`; i’m reading the owner and tests now to rebuild the fix with a smaller production shape.

i found the cleaner absorption point: prepare one authority capture, let the private reclaim worker consume it, and keep the host-only callback inside the verify path. that preserves the public boolean/rollback behavior while avoiding the earlier wrapper duplication; compact still needs a small resolver-abort adapter because merging it into the outer catch would broaden cancellation semantics.

the owner refactor is now **+19 production LOC** versus main, down from +26: `session-binding.ts` +14 and `compact.ts` +5. i found one more mechanical reduction in the capture return without changing the authority model; after that the remaining growth is the new durable-row fence plus the deliberately separate resolver-abort boundary.

local package links are incomplete, so i’m taking the allowed route: one fresh task-owned Hetzner lease. the first remote proof will apply only the four regression tests to exact `c26e46b2` and confirm the expected 3 failures before running the candidate.

one local tooling probe added `@pnpm/exe` metadata to the lockfile. that is outside scope and entirely task-created, so i’m removing it now; the branch remains four-file only.

fresh Hetzner lease acquired: `[LEASE_ID]` (`golden-crab`, `ccx33`). i’m using it for both exact-main pre-fix reproduction and candidate validation, then it will be released before handoff.

the remote checkout is still syncing/installing; no test output yet. the candidate remains four-file only at +19 production LOC, and the exact-main regression harness is staged to require precisely 3 failures and 123 passes.

exact-main pre-fix is proven on `[RUN_ID]`: **3 intended failures, 123 passes**. the failures are exactly current-binding rotation, stale readable binding admission, and queued compaction after row rotation; the no-row ephemeral case passes.

post-fix focused proof is clean: `[RUN_ID]`, **126/126**, plus scoped oxlint. next is the 716-test surface, registered attempt-extra project, its topology/config owner, both tsgo lanes, and the changed classifier on the same lease.

continuing from the active Hetzner validation. implementation is complete at four files; i’m waiting on the broad post-fix run, then i’ll handle review, signing, and the draft PR if it stays clean.

the broad surface is still green and working through the large lifecycle suite. no blocker yet; the pre-fix proof remains 3 deterministic failures, while the focused candidate proof is 126/126.

the exact reviewed 11-file surface is now confirmed at 716/716. attempt-extra is running next; after that come topology, type/lint/classifier, then the two independent reviews.

attempt-extra has one known unrelated failure at `run-attempt.native-hook-relay.test.ts:466`; the exact touched 716 surface and topology owner both pass. i’ll reproduce that assertion on untouched `c26` before classifying it, while the type/classifier lanes finish.

the remote validation is complete: 716/716, topology 24/24, both tsgo lanes, and `check:changed` all pass. attempt-extra is 281/282 with the same native-hook assertion outside this patch; i’m now proving that exact failure on untouched `c26` before treating it as baseline.

the attempt-extra miss is confirmed unchanged on untouched `c26`, so it is baseline, not branch-owned. i’m freezing edits now and running the required independent autoreview against the exact four-file diff.

autoreview itself failed before producing a verdict, not on a code finding. i’m checking the engine error and will rerun with an independent local reviewer rather than treating infrastructure failure as review evidence.

the first reviewer process failed, and Claude’s local auth is expired. i’m making one bounded retry with the configured Codex access fallback model; if that infrastructure also fails, i’ll record autoreview as unavailable rather than laundering it into a clean verdict.

autoreview is unavailable because both local reviewer credentials are expired/unauthorized; no verdict was produced. i’m recording that as a remaining draft gate, doing the final hands-on diff audit, and rechecking `origin/main` before I create the signed candidate for ClawSweeper.

`origin/main` advanced from `c26e46b2` to `7b1795acc6` during validation. i’m checking whether those commits touch the invariant; if they do not conflict, i’ll rebase the fresh dirty GWT onto the new main and rerun the affected proof before committing.

the main advance is non-conflicting: none of the four target files changed, though adjacent Codex app-server files did. i’m rebasing the fresh worktree onto `7b1795acc6`, then I’ll rerun the focused surface against that actual base.

the new-main rerun hit only a stale remote dependency tree after the package update (`tsx/esm` missing). this is the task-owned Hetzner box, so I’m reconciling dependencies there, then rerunning the same proof unchanged.

the rebased candidate is now on `7b1795acc6`; dependency refresh completed on the owned box. the duplicate scan found only unrelated Codex runtime and reply-execution PRs, so there is no exact open duplicate so far.

new-main validation remains green through the 716-test surface; attempt-extra is progressing normally. the production delta is still +19, down from +26: +14 centralizes one canonical durable-row fence shared by resolution/reclaim, and +5 isolates resolver-time abort normalization without widening the existing operation catch.

the rebased 716 surface still passes. two remaining failures are environmental/baseline: the same native-hook assertion, plus the fresh remote checkout lacks generated `ui/config/*.ts` files needed by topology and extension-test typecheck. i’m locating the repo-native generator and will rerun only those failed lanes.

the topology/type failure is a sparse-checkout omission, not generated code: `ui/config/*.ts` is tracked on main but excluded by this GWT’s sparse patterns. i’m adding that tracked directory to the fresh worktree’s sparse set, then rerunning only topology and the failed classifier lane.

[user]
The task-owned remote process has exited. Please report the exact validation statuses now, then finish the reviewed scope: reduce/justify production +19, run local ClawSweeper/autoreview as required, signed semantic commit, push, open draft PR with scrubbed temp-file body + ghx no-cache readback, release only your lease, and return exact head/signature/PR URL. Do not chase unrelated main movement or broaden scope.

[assistant]
status now: 716/716 passed on `7b1795acc6`; attempt-extra is 281/282 with the exact same base failure at `run-attempt.native-hook-relay.test.ts:466`; topology is 24/24 after restoring tracked sparse files. `check:changed` is in its final lanes now; no branch-owned failure or blocker.

validation is closed: `check:changed` passed after sparse restoration, including both tsgo lanes and oxlint. the +19 production lines are the compressed owner-level fix; further reduction would either duplicate authority policy, weaken the exact pair fence, or broaden abort handling, so I’m keeping it and creating the single signed candidate now.

the signed candidate is `f44a3ffaa5831ccaf157f5fb9e751cab34a02298` with a verified good SSH signature. local ClawSweeper completed; i’m reading its report now and will only amend if it found an actionable issue in this invariant.

both local review tools reached the exact committed range but failed before verdict on the same expired/unauthorized reviewer credentials; neither produced a finding. i’m keeping that explicit in the draft as a remaining gate, then pushing the signed commit and opening the draft with the completed runtime evidence.

status: pre-fix regression was 123/126 with the three intended failures; candidate is 716/716, topology 24/24, `check:changed` green, and attempt-extra is 281/282 with the same proven base failure. Production is +19 after reduction; I’m finishing transcript scrub, live-state checks, push, draft PR, then releasing only `[LEASE_ID]`.

the transcript helper picked an unrelated older session, so I’m discarding that artifact. `origin/main` moved after the commit; per your instruction I’m only checking whether the four owned files changed, not rebasing or chasing unrelated movement.

[tool summary]
46 read, 4 write, 170 execute; raw tool outputs dropped: 219

@clawsweeper

clawsweeper Bot commented Sep 5, 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.

@vincentkoc vincentkoc self-assigned this Sep 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 4, 2026, 9:58 PM ET / September 5, 2026, 01:58 UTC.

ClawSweeper review

What this changes

Makes Codex session-to-thread lookups retain generation checks, preventing queued compaction from acting after session rollover while preserving cancellation results and adding regression coverage.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still contains the readable-binding bypass, and the merged predecessor-recovery work does not cover this admission case. No blocking correctness defect was found in the proposed patch.

Priority: P2
Reviewed head: f44a3ffaa5831ccaf157f5fb9e751cab34a02298

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused shared-owner repair with useful regression coverage and no blocking finding; reported remote execution remains distinguished from independently inspected source.
Proof confidence 🌊 off-meta tidepool Not applicable: This MEMBER-authored internal lifecycle repair is exempt from the external-contributor proof gate, and no unresolved introduced authority violation was identified. Inspected regressions cover stale admission, queue rejection, and successor adoption; no new native-runtime run is independently claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored internal lifecycle repair is exempt from the external-contributor proof gate, and no unresolved introduced authority violation was identified. Inspected regressions cover stale admission, queue rejection, and successor adoption; no new native-runtime run is independently claimed.
Evidence reviewed 15 items Pinned introduction and merge ownership: The reviewed checkout is the original PR head. Its raw parent matches the supplied merge base, and the verified test merge has the pinned base followed by this exact head. Comparing that merge against its base changes only the four supplied files; unrelated endpoint drift was excluded.
Current main still needs the repair: Fetched main returns a no-op assertion for an already-readable compaction binding. Its shared resolver captures host-generation authority only during missing-binding recovery. Both production files have identical blobs on fetched main and the PR merge base.
Canonical authority owner: The new capture composes caller authority with the canonical row's exact sessionId/previousSessionId pair. Missing rows retain ephemeral behavior; mismatched or unreadable durable authority rejects. Resolution and reclaim consume the same capture rather than maintaining separate policies.
Findings None None.
Security None None.

How this fits together

The Codex plugin maps OpenClaw sessions to saved Codex conversations. Compaction and related operations resolve that mapping, wait for thread ownership, and send requests to Codex app-server.

flowchart TD
  A[Session action] --> D[Resolve generation and thread]
  B[Canonical session row] --> D
  C[Saved native binding] --> D
  D --> E[Wait for thread ownership]
  E --> F{Generation still current?}
  F -->|Yes| G[Codex request and guarded writes]
  F -->|No| H[Reject without changing successor]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +19, Tests +173. Total +192 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 116 97 +19
Tests 2 173 0 +173
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 289 97 +192

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +19 net; tests +173 net The production growth is justified by shared generation capture and cancellation-boundary preservation, rather than a parallel recovery implementation.

Technical review

Best possible solution:

Keep generation validation in the shared binding owner rather than adding a compaction-only guard or setting; the small production increase supplies the missing authority capture and preserves the narrow cancellation boundary.

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

Yes, from source: hold the native-thread queue, admit compaction with a readable binding, rotate the canonical session row, then release the queue. Current main retains a no-op generation assertion; the added regression exercises this sequence, but this reviewer did not execute it.

Is this the best way to solve the issue?

Yes—the canonical session row already records the required lineage, and composing its exact generation pair with caller authority repairs shared resolver consumers without another store, public API, or option.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: Repairs a source-proven Codex lifecycle race across session rollover; a broad outage or release-blocking impact is not established.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This MEMBER-authored internal lifecycle repair is exempt from the external-contributor proof gate, and no unresolved introduced authority violation was identified. Inspected regressions cover stale admission, queue rejection, and successor adoption; no new native-runtime run is independently claimed.

Label justifications:

  • P2: Repairs a source-proven Codex lifecycle race across session rollover; a broad outage or release-blocking impact is not established.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This MEMBER-authored internal lifecycle repair is exempt from the external-contributor proof gate, and no unresolved introduced authority violation was identified. Inspected regressions cover stale admission, queue rejection, and successor adoption; no new native-runtime run is independently claimed.

Evidence

What I checked:

  • Pinned introduction and merge ownership: The reviewed checkout is the original PR head. Its raw parent matches the supplied merge base, and the verified test merge has the pinned base followed by this exact head. Comparing that merge against its base changes only the four supplied files; unrelated endpoint drift was excluded. (f44a3ffaa583)
  • Current main still needs the repair: Fetched main returns a no-op assertion for an already-readable compaction binding. Its shared resolver captures host-generation authority only during missing-binding recovery. Both production files have identical blobs on fetched main and the PR merge base. (extensions/codex/src/app-server/compact.ts:465, cfc6534da8c3)
  • Canonical authority owner: The new capture composes caller authority with the canonical row's exact sessionId/previousSessionId pair. Missing rows retain ephemeral behavior; mismatched or unreadable durable authority rejects. Resolution and reclaim consume the same capture rather than maintaining separate policies. (extensions/codex/src/app-server/session-binding.ts:95, f44a3ffaa583)
  • Host lineage and storage boundary: The existing host producer records predecessor lineage when a same-key session rolls over. The binding reader requests the canonical session entry, and binding mutations invoke supplied assertions before synchronous updates. This patch adds no schema or serialized-record change. (src/config/sessions/session-entry-lineage.ts:11, f44a3ffaa583)
  • Queue and final-write enforcement: Compaction checks the retained assertion before acquiring a client and carries it into resume, projection mutation, native compaction, and completion handling. The actual client invokes its assertion immediately before each physical write, including overload retries. (extensions/codex/src/app-server/compact.ts:574, f44a3ffaa583)
  • Physical transport assertion: The request owner calls assertCurrent without an intervening await before writeMessage. The new generation assertion therefore reaches the final native-request boundary rather than serving only as an admission check. (extensions/codex/src/app-server/client.ts:691, f44a3ffaa583)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: 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.

@vincentkoc
vincentkoc marked this pull request as ready for review September 5, 2026 02:25
@vincentkoc
vincentkoc merged commit 116c6c3 into main Sep 5, 2026
179 checks passed
@vincentkoc
vincentkoc deleted the fix/codex-fence-current-binding-generation branch September 5, 2026 02:34
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
…8767)

Fix stale Codex compaction after durable same-key session rollover by carrying
canonical session-generation authority through binding resolution and final
transport writes.

- share the exact `(sessionId, previousSessionId)` fence across readable-binding
  resolution and generation reclaim
- preserve caller-owned ephemeral authority, successor adoption, and narrow
  resolver-cancellation behavior
- prove the stale generation makes zero Codex protocol calls while the successor
  resumes and compacts the same real native thread

Validation: focused 126/126, reviewed owner/sibling surface 716/716,
`check:changed`, exact-head hosted CI, local and hosted ClawSweeper, scoped-clean
autoreview, and live Codex rollover proof `run_84742ba57fbd`.

Related: openclaw#138473
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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.

1 participant