Repository navigation
fix(codex): preserve native threads after interrupted compaction - #138473
Conversation
Recognize the host's recorded predecessor before native ownership selection and binding admission. Reuse the existing conditional generation adoption, recheck host lineage after queued waits, and remove the best-effort post-compaction adopter. Preserve native catalog and supervision fences. Fixes #137914. Reported by Vincent Koc; related draft #138184. Co-authored-by: Vincent Koc <[email protected]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
@clawsweeper re-review The earlier review-start lease expired without a completed review. Exact-head CI, independent branch review, and the Crabbox check/build/authenticated restart proof are complete at 99fb041; the PR body contains the evidence and remaining proof limitation. |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
Codex review: needs changes before merge. Reviewed September 4, 2026, 7:05 PM ET / 23:05 UTC. ClawSweeper reviewWhat this changesPreserves saved Codex conversations after interrupted compaction by recovering the recorded predecessor binding before subsequent actions and retaining generation checks through waits and cleanup. Merge readiness⛔ Needs changes before merge - 3 items remain The repair remains necessary, but both previously reported regression-test defects remain on the unchanged reviewed head. The earlier production-fencing corrections are present; the related merged work does not resolve this continuity failure. Priority: P1 Review scores
Verification
How this fits togetherThe Codex plugin connects OpenClaw sessions to native Codex conversation threads. When compaction changes an OpenClaw session generation, its binding owner must preserve the native thread while rejecting work from superseded generations. flowchart TD
A[Compaction commits successor session] --> B[Recorded predecessor lineage]
C[Next turn or control action] --> D[Codex binding recovery]
B --> D
D --> E{Exact current generation?}
E -->|Yes| F[Resume existing native thread]
E -->|No| G[Reject stale work]
F --> H[Guard requests and cleanup]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +245, Tests +928, Docs +6. Total +1179 across 48 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Retain the single binding-owner recovery flow and its cross-wait fences, with regression fixtures that exercise predecessor adoption and reliably drain retained operations rather than introducing another transition store. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the host-commit-before-observer interruption path and both remaining test defects. This read-only review did not execute tests or claim a fresh runtime reproduction. Is this the best way to solve the issue? Yes for the recovery design: existing durable lineage and conditional adoption avoid a second storage protocol, and the added checks preserve that decision across waits. The submitted regression fixtures still need correction before their validation is trustworthy. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 48bbd95b4263. LabelsLabel justifications:
EvidenceAcceptance criteria:
What I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (6 earlier review cycles)
|
… checks Forward the admitted host store to side-question and command binding reads. Reconcile the recorded predecessor before same-thread resume ownership checks, then revalidate the generation fence after the native queue and binding lease. Add failing-before side-question, same-thread resume, and target-store controls, plus a queued-generation rejection regression. Follow-up to #137914.
|
Addressed both Rank-up moves from the review: side-question admission now forwards its admitted storePath, and a regression uses the real host SQLite successor/predecessor pair with a different configured default store. It fails before the fix and passes afterward; the side-question, binding, and core BTW suites pass 214 tests. The same consumer audit found command binding reads dropping the canonical target store and Final-head CI and Crabbox proof are being refreshed, including real Codex ordinary resume, BTW-first, and same-thread command-first scenarios after the host-commit interruption. The PR body will carry their completed results. Existing command auth/model/permission store-routing observations outside the generation admission owner are recorded as a named follow-up with their validation limits. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
Carry the verified host lineage assertion from binding recovery through native queue admission and the existing scoped control RPC checks. A later host-only rollover must reject the earlier command even while the binding still records that earlier generation. Cover host-only and paired-store queue changes plus a host rollover during RPC. Format the command test with the repository-pinned formatter.
Carry the verified host predecessor pair alongside recovered bindings through native queues, leases, client startup, requests, and startup binding writes. Keep each caller's existing abort normalization and cleanup behavior. Settle known compaction rejection before guarded restoration so a failed restoration cannot leak the completion watcher. Cover host-only rollover, startup revocation, and restoration failure with failing-before regressions.
|
The post-adoption host-only rollover finding and its Rank-up moves are addressed in f1b0cf4. Recovery now carries its verified host-generation check through ordinary lifecycle, early connection preparation, BTW, compaction, and command queue/RPC waits; physical requests and binding writes use that same check. Deterministic P→S→T regressions fail before the repair. Existing cancellation and reconnect behavior remains covered. Connected startup-clear and rejected-compaction watcher cleanup cases were also reproduced and repaired. All 958 selected owner tests now have passing evidence, and the full staged review is clean. Fresh exact-head CI, committed-branch review, and Crabbox proof are running; the PR body will record their final results before merge. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Carry recovered generation checks through private attempt context while retaining the original host capability object and its core-owned private registrations. Preserve audio projection and native relay authority, and remove duplicate startup cleanup.
|
The final correction preserves the exact host-capability object while carrying recovered-generation checks in private Codex attempt context. Core keys private audio/question/scheduled capabilities by that object identity; the previous head's clone caused two existing media-lifetime CI failures. Both now pass, alongside all 1,127 tests across 23 complete affected owners. The final duplicate-cleanup simplification also passes all 53 startup/retry/cleanup tests. Lint and staged independent review are clean. The earlier host-only rollover finding and all Rank-up moves remain addressed: explicit admitted-store routing, exact predecessor recovery, and retained P→S→T checks across queue/lease/RPC waits. The original host authority and existing approval/closure policies remain unchanged. Production +444/-216=+228 is the documented missing-recovery exception; tests +1071/-372=+699, docs +6. Exact-head CI, committed-branch review, and Crabbox proof are being refreshed for 5fe3e7a before landing. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
@clawsweeper re-review The prior exact |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Fence unconfirmed compaction retirement and completed-turn coverage after host generation rollover. Settle known pre-write compaction rejections without waiting for a nonexistent native turn, and remove the single-use coverage wrapper. Preserve the original host assertion in the canonical integration fixture.
|
I’m integrating Vincent’s four commits with the cleanup fixes prepared concurrently, preserving his commit history. The combined candidate keeps the retirement guard and adds verified pre-write compaction settlement and post-agent_end coverage fences. The exact-head CI failures on 5a8cda5 are accounted for: retirement needs matching terminal evidence before releasing its watcher; displaced-release coverage needs a recovered P→S admission before S→T; real control fixtures need the committed command context; and the absent plugin-config argument is legitimately undefined. The combined retirement test covers both ambiguous start and acknowledged-start timeout. Auth-store and displaced-release regressions fail against pre-fix production as expected. Fresh review, complete affected suites, exact-head CI, and Crabbox real-runtime proof will run on the integrated head before landing. |
Preserve contributor commits for explicit-store auth and guarded displaced subscription release. Exercise recovered P-to-S-to-T authority in rollback coverage and retain native terminal fencing in both compaction retirement paths. Supply committed admission in real-control deadline and cleanup fixtures. Validation: 311 owner tests and three finalization cases pass; five incoming regressions fail against pre-fix production. Scoped lint and independent review are clean. Exact-head CI and remote runtime proof follow before landing. Co-authored-by: Vincent Koc <[email protected]>
|
The integrated head is d982366, preserving Vincent’s four commits. Both latest findings and Rank-up fixture corrections are addressed: retirement asserts the retained queue and drains matching terminal events, and displaced release uses canonical P→S→T lineage. All 311 tests across complete compact/commands/RPC/request suites pass, alongside all three finalization generation tests. All five added auth/release/acknowledged-retirement regressions fail against pre-fix production. Scoped lint and final staged review are clean. This head also closes the independently reproduced pre-write retry watcher leak and post-agent_end coverage/cleanup rollover holes, preserving the original host capability identity and existing terminal fences. The body records the missing-recovery LOC exception and proof limits. Exact-head CI, committed branch review, and fresh Crabbox owner/check/build/mock/authenticated real-runtime proof are being refreshed before landing; prior runtime evidence is explicitly historical. @clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
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: #138473
…nclaw#138473) Recover the same Codex native thread when compaction commits a host successor but interruption leaves the binding at its recorded predecessor. The host already persists previousSessionId atomically; synchronous native ownership and asynchronous admission now use that fact and the existing conditional binding update. Forward the admitted store and retain the verified host-generation check through ordinary attempts, lifecycle, side questions, native compaction, and manual-resume queue/lease/RPC waits. Carry the recovered generation assertion in private Codex attempt context while preserving the original host-capability object and its core-owned private registrations. Adoption rewrites only the generation fence. Preserve native ownership, catalog refusal, cancellation/reconnect behavior, and unrelated-generation policy. Use the admitted store for manual-resume auth and preserve displaced native ownership across awaited release. Remove the after-compaction adopter and duplicate recovery. Guard startup binding clears after filesystem waits and settle known compaction rejection before restoration, so revoked authority cannot clear a binding and failed restoration cannot leak its completion watcher. Fence unconfirmed remote retirement and post-agent_end coverage/cleanup against a later host generation. Settle known pre-write rejections without waiting for a nonexistent compaction turn. Inline the single-use coverage wrapper so successor messages stay visible on the next saved-thread resume. Failing-before regressions cover interruption, cold saved-ID resume, other generations/owners, and post-adoption host-only rotation. Fixes openclaw#137914. Thanks to @vincentkoc for the report and the draft in openclaw#138184. Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: Vincent Koc <[email protected]>
…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
Closes #137914. Related: #138184. Thanks to @vincentkoc for reporting the failure, authoring that draft, and contributing the manual-resume auth and subscription-release repairs to this PR. His draft PR is unchanged.
What Problem This Solves
Resolves a problem where continuing a Codex chat lost its saved native thread after compaction committed a successor session generation but cancellation or a Gateway restart prevented the post-compaction observer from running. Ordinary sessions could start a replacement thread; native-owned sessions could refuse the next turn.
Why This Change Was Made
The host already records
previousSessionIdatomically withsessionId. Codex's separate binding store keys rows by agent and session key; itssessionIdis a generation fence. The binding owner now adopts exactly that recorded predecessor through its existing conditional update. Read-only native ownership recognizes the same continuity before asynchronous admission. The obsolete after-compaction adopter and duplicate late recovery are removed.Ordinary attempts, lifecycle, side questions, compaction, and manual resume use the same recovery before selecting queues, catalogs, connections, or ownership. Explicit admitted store paths reach both the binding owner and manual-resume auth preparation. Subscription-producing control calls verify the same host row that command ingress already committed before selecting auth. Displaced native subscriptions retain the recovered guard while releasing the old owner, so a later generation restores the old callback and cleans only the replacement. The recovered admission retains its verified host-generation check across subsequent queue, lease, client, and RPC waits, so a later host-only rollover cannot reuse it. This check stays in private Codex attempt context: the original host-capability object remains intact because core keys private audio, question, and scheduled authority by its identity. Existing cancellation, reconnect, and closure authority remain with their owners. Connected cleanup fixes guard startup clears after filesystem waits and dispose a compaction watcher when restoration following a known RPC rejection fails. Unconfirmed remote compaction retirement retains the same generation check before detaching its binding. A rejection before a physical write settles the watcher immediately; it cannot wait for a native turn that never started. Completed-turn coverage and its storage-failure cleanup also retain that check after
agent_end, so a successor message cannot be marked as already seen or lose its saved binding; their single-use wrapper is removed.No durable record, schema/config/env option, dependency override, protocol bump, or cross-database transaction is added. Adoption only rewrites the generation fence. The public hook's
previousSessionIdremains because it shipped in v2026.9.1.User Impact
The next action after an interrupted compaction resumes the same native thread and history. Two-step predecessors and different keys/agents are not adopted. Dynamic-tool changes retain the existing native refusal policy. Admission superseded while waiting rejects before acting on the old generation.
Evidence
Exact-head CI run 33930744598 completed successfully for
f4e1c96807f704cbe8de4276144b52001cbf4183: all 125 jobs completed (109 successful, 16 intentionally skipped). The required watcher exited green; the completed run and every job were checked directly. The final committed-branch review completed all three passes with no actionable P0–P2 findings. Local integrated compact/commands/command-RPC/request suites passed 311 tests; finalization passed all 3 cases; the complete shard-configuration suite passed 24 tests after reproducing and correcting the missing registration.Direct source evidence: host producer
src/config/sessions/session-entry-lineage.ts:11andsession-accessor.sqlite-entry.ts:541; stable-key contractextensions/codex/src/app-server/session-binding-record.ts:305; recovery ownersession-binding.ts:379. The queued-successor regression asserts predecessor lineage is already durable in the commit observer. Current main retains the lineage writer and exact-read behavior, with exact reads extracted intosession-accessor.sqlite-exact-read.ts; merged-source CI covers intervening main changes.Personally inspected pinned Codex
rust-v0.153.0(41e22fee981a63b3698df7ed36bad393cda24715):codex-rs/app-server-protocol/src/protocol/v2/thread.rs:335–410accepts saved thread ID without replacing dynamic tools;codex-rs/app-server/src/request_processors/thread_processor.rs:3657–3677loads persisted history,:3831–3837resumes it, and:3888–3899attaches the listener. Fork contracts were checked atthread.rs:510–600andthread_processor.rs:4723–4729,4790–4810,4987–4999,5123–5127.Final proof passed on configured Blacksmith Testbox lease
tbx_01m1qd4z8cwcwjesqtpfe6rpgq, run 33930824814. The source receiver verified candidatef4e1c96807f704cbe8de4276144b52001cbf4183, treee04a202d063ece5c9dbee3c9ec7e28c8f800f47e, carrier534e9a7296e911ebb6a3cc263783554a804b84dc. Its frozen-lockfile install, ten complete owner files (680 Codex tests plus canonical-descendant integration; two shards),node scripts/check-changed.mjs --base origin/main --head HEAD,pnpm build, tracked-source cleanliness check, and both isolated Gateway proof modes all succeeded. The candidate predates #138612's Testbox transport/runtime fix, so the task launcher restores the verified checkout after login-shell startup and installs its own pinned dependencies.Observed live transcript (synthetic scenario verdicts):
{"scenario":"abort","ok":true,"hostPredecessor":"5a5623bf-4c88-4f80-af4a-2651aa7e8685","hostSuccessor":"5bca28db-01d4-4e31-a44c-e7ed8e409b4a","nativeThreadPreserved":true,"reply":"PREDECESSOR_PROOF_OK native_turn=2","threadStarts":0,"threadResumes":1} {"scenario":"kill","ok":true,"hostPredecessor":"65da1d30-9936-4dcc-8da7-9db5863adc2f","hostSuccessor":"38ff8f21-c109-4d75-8be0-6d8a61422dd4","nativeThreadPreserved":true,"reply":"PREDECESSOR_PROOF_OK native_turn=2","threadStarts":0,"threadResumes":1} {"scenario":"two-steps","ok":true,"hostPredecessor":"36306fd5-6e01-4825-8ef8-2d13c7650209","hostSuccessor":"c102537f-38a8-4692-8f7e-bcc80241328f","nativeThreadPreserved":false,"reply":"PREDECESSOR_PROOF_OK native_turn=1","threadStarts":1,"threadResumes":0} {"scenario":"authenticated-kill-restart-recall","ok":true,"pinnedCodexVersion":"0.153.0","model":"openai/gpt-5.6-luna","hostPredecessor":"7b8287a6-d5d1-470a-bffb-942ce2f608e6","hostSuccessor":"9ad89630-8a6b-4eec-9137-d57b3559591e","nativeThreadId":"01a06ef2-0535-7a41-addb-d0376c5a8791","nativeThreadPreserved":true,"nativeClientChanged":true,"recordedLifecycleAction":"resumed","syntheticRecallMatched":true} {"scenario":"authenticated-kill-restart-btw-first","ok":true,"pinnedCodexVersion":"0.153.0","model":"openai/gpt-5.6-luna","hostPredecessor":"44b36da3-e5fd-47ce-aa4f-2f132de9ac97","hostSuccessor":"b0e08342-a6f0-44b1-ab9a-3309447e34d1","nativeParentThreadId":"01a06ef2-4601-7c32-b1bb-b66388af4747","firstPostRestartUserAction":"/btw","sideResultEvent":"chat.side_result","sideRecallMatched":true,"parentBindingPreservedAfterSide":true,"sideQuestionAndAnswerAbsentFromHistory":true,"parentFollowupAction":"resumed","nativeForkEvidence":"real Codex BTW owner plus exact pinned thread/fork source contract","alternateAdmittedStoreCoverage":"owner regression; public chat.send has no per-request storePath"} {"scenario":"authenticated-kill-restart-resume-command-first","ok":true,"pinnedCodexVersion":"0.153.0","model":"openai/gpt-5.6-luna","hostPredecessor":"fd3bea35-6eed-44c4-ad07-66828a75e7bd","hostSuccessor":"711a2955-f38d-40ee-aafa-15c3f238702b","nativeParentThreadId":"01a06ef2-8efb-79a3-944c-4b5c9c87d0c1","firstPostRestartUserAction":"/codex resume <same saved thread>","commandTerminalEvent":{"event":"chat","state":"final","runId":"7104e041-47c6-431d-aa41-d3f4c46483cb"},"attachmentText":"Attached this OpenClaw session to Codex thread 01a06ef2-8efb-79a3-944c-4b5c9c87d0c1.","nativeParentPreserved":true,"nativeClientChanged":true,"knownNativeMetadataPreserved":true,"pendingResumeConfiguration":false,"parentFollowupAction":"resumed","syntheticRecallMatched":true}The remote command finished with
exitCode: 0,runStatus: succeededin 1752.2 seconds. The task lease was stopped and reportedcompleted.The live scenarios inject a synthetic successful context-engine result to interrupt immediately after the actual host COMMIT; summarization is not tested. BTW uses the real owner and model; its fork mechanism is source-audited rather than independently wire-captured. Alternate admitted-store routing has real host-SQLite regression coverage, but public
chat.sendexposes no per-request store path, so alternate-store auth end to end is not claimed. Synthetic data only; credentials were not printed.git diff --numstatagainst the branch base:The production increase is the explicitly allowed missing-recovery exception: synchronous ownership and asynchronous admission both need exact predecessor recovery, and reproduced post-wait rollover races require retaining its host fence through native requests and writes. The private context carries that check without replacing opaque host authority. Observer, duplicate recovery/cleanup, and single-use coverage wrapper removal pay for part of the change. Removing the remaining checks reopens reproduced races or erases a caller's refusal/cancellation contract. Test totals include parameterization and reindentation.
The latest ClawSweeper fixture findings are addressed: the retirement test first verifies the retained queue and binding, then emits matching terminal events; the displaced-release test now seeds a real P→S predecessor before S→T. All 311 compact/commands/command-RPC/request tests pass. The new generation-finalization suite is registered in the full-suite shard, with all 24 shard-configuration checks passing after reproducing the missing-entry failure. Earlier ClawSweeper Rank-up moves are addressed: explicit side-question store routing with failing-before host-SQLite proof, and retained host-lineage checks with deterministic P→S→T lifecycle/BTW/compaction cases. Manual-resume auth tests fail before the fix by selecting the configured store instead of the admitted pin and accepting missing/mismatched rows; displaced-release proof fails before the guard by unsubscribing the successor’s original native owner. Command queue/RPC races, early connection propagation, startup byte/token clears, watcher cleanup, and unconfirmed remote retirement also fail before their fixes. Actual-client tests additionally reproduce generation rejection and deadline expiry after a single ingress-overload response, proving that known pre-write failure must preserve the binding and release the queue. Two post-
agent_endcases reproduce stale coverage advancement and binding loss while the unchanged same-generation storage-failure control passes; the repaired cases additionally resume the same thread and check the successor message reaches its next prompt. CI additionally caught capability-object cloning dropping accepted audio; preserving the original object fixes both existing failing cases, with an identity assertion and broad sibling-owner coverage. The canonical-descendant integration fixture now supplies the original assertion when constructing a private connection; production has no fixture fallback.Named follow-ups: command model/permission operations still derive their store from configuration outside generation admission; these are source-audited observations, not separately reproduced here.
startup-binding.tsretains legacy session-file metadata reading, a migration/refactor follow-up outside this storage-preserving repair. The unrelated cold-import voice-timeout CI repair landed separately in #138611.NO-FOLLOW-UP: observer and duplicate recovery/cleanup removal already provide the useful refactor; another independent extraction of this repaired owner adds indirection.