Repository navigation
fix(codex): duplicate final reply after a resumed parent waits for a native child - #186128
cassthebandit wants to merge 1 commit into
Conversation
…native child A resumed Codex thread receives no raw item events, so a V2 wait gave OpenClaw no receipt and the completion owner delivered the consumed result again. Hold the current-turn completion envelopes carried by the parent's latest model request and settle them through the existing receipt tracker when native reports that turn completed. A later request replaces them; compaction, a non-Stop hook, a failed or interrupted turn, or owner release before turn completion keeps delivery pending. Related: openclaw#156070
|
🦞👀 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. |
|
Codex review: needs real behavior proof before merge. What this changesThis PR uses parent model-request input to deduplicate native child results after a Codex conversation resumes. Example: After a Gateway restart, a parent waits for a child that returns “The build passed.”
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Partial Merge readiness⛔ Blocked before merge - 3 items remain Keep open: this PR addresses a concrete duplicate-reply bug, but receipt settlement can suppress an unconsumed result, and the added tests trigger a failing CI ratchet. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe Codex plugin observes native child execution and correlates completion receipts with assignments; consumed results suppress detached parent continuations, while unconsumed results remain pending. flowchart LR
A[Native child result] --> B[Parent model request]
B --> C[Inference proxy]
C --> D[Held turn receipts]
E[Native turn completion] --> D
D --> F[Existing receipt tracker]
F --> G[Completion delivery owner]
Technical reviewBest possible solution: Keep receipt matching in its existing owner, but require positive sampling-completion evidence before retiring a result. Do we have a high-confidence way to reproduce the issue? The official-release report supplies duplicate replies and correlated logs, and current native source confirms that resumed listeners omit the raw receipts used by OpenClaw; no target code was executed during this review. Is this the best way to solve the issue? Reusing the existing receipt tracker is appropriately scoped, but native turn completion is weaker than completed sampling and cannot safely serve as its sole acknowledgement. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 2e333671f594. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
PR surfaceSource +111, Tests +164. Total +275 across 9 files. Added test files: 0. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 27, 2026, 12:58 PM ET / 16:58 UTC. |
Original-head live behavior evidence for #186128These are retained terminal results from the original source-build investigation, not new runs and not proof of a later repair commit. The publication follow-up inspected the matching JSON receipts and harness source without executing the harness. Identity and test boundaryBoth passing receipts contain this identity (verbatim field values): {
"head": "d7ca03a8938a66809aa7334a67daa2c273b7c7d7",
"dirty": [],
"binary": "codex-cli 0.164.0",
"binarySha256": "d8990e3ee7acfbc26f91265b12a1a83f0fee40d0e0f8f1f40a37d4ec21f499cf"
}Base sources: The retained harness performs an ordinary warm turn, stops its first Gateway, starts a second Gateway against the same isolated state, then spawns and waits for a child. For the consumed case it later sends an ordinary turn, re-tasks the same child, and waits again. Counts are not merely response-label expectations: After fix: restart → wait_agent → one answer per resultVerbatim retained terminal stdout, {"ok":true,"scenario":"restart-wait","failures":[],"checks":{"unexpectedParentExecutions":0,"finalB":1,"ordinary":1,"finalC":1,"unexpectedAnswers":0,"announceRuns":0,"childTurns":{"b":1,"c":1},"parentRequests":["warm:new:user","spawn-b:cold_resume:user","wait-b:cold_resume:user","final-b:cold_resume:user","ordinary:cold_resume:user","retask-c:cold_resume:user","wait-c:cold_resume:user","final-c:cold_resume:user"],"sameChild":true,"activeRun":false,"notStreamingWakeFailures":0,"injected":0},"labels":["warm","spawn-b","wait-b","child-b","final-b","ordinary","retask-c","wait-c","child-c","final-c"],"cleanup":{"gateways":[{"index":1,"exitCode":0,"signal":null},{"index":2,"exitCode":0,"signal":null}],"providerClosed":true,"distRestored":true}}The matching receipt additionally records Unconsumed-result control: automatic delivery remainsVerbatim retained terminal stdout, {"ok":true,"scenario":"restart-unconsumed","failures":[],"checks":{"unexpectedParentExecutions":0,"finalB":1,"ordinary":1,"finalC":0,"unexpectedAnswers":0,"announceRuns":1,"childTurns":{"b":1,"c":0},"parentRequests":["warm:new:user","spawn-b:cold_resume:user","yield-b:cold_resume:user","final-b:new:user","ordinary:new:user"],"sameChild":true,"activeRun":false,"notStreamingWakeFailures":0,"injected":0},"labels":["warm","spawn-b","yield-b","child-b","final-b","ordinary"],"cleanup":{"gateways":[{"index":1,"exitCode":0,"signal":null},{"index":2,"exitCode":0,"signal":null}],"providerClosed":true,"distRestored":true}}The matching receipt records This control establishes one answer and one automatic continuation for the yielded, unsampled result. It does not exercise same-child reuse; the generic Before fix: duplicate reproducedFor this baseline the checkout's HEAD remained Verbatim retained terminal stdout, {"ok":false,"scenario":"restart-wait","error":"Error: Timeout same child reused","labels":["warm","spawn-b","wait-b","child-b","final-b","unexpected-parent","ordinary","retask-c","wait-c","rewait","rewait"],"cleanup":{"gateways":[{"index":1,"exitCode":0,"signal":null},{"index":2,"exitCode":null,"signal":"SIGKILL"}],"providerClosed":true,"distRestored":true}}The retained provider trace orders This is evidence of the unwanted automatic continuation after the parent answered. The baseline then timed out on reuse, so it has no successful final count summary. Its second owned Gateway required SIGKILL during cleanup. An earlier baseline attempt failed during startup-sidecar availability and is excluded from behavior comparisons. The unconsumed control was run on head only. LimitsNo new live run is claimed. These receipts cover original head No claim of universal no-loss: the PR's unresolved compaction-setup failure edge remains. Preemption/compaction/hook-stop paths were not driven end to end; WebSocket inference, other native versions/provider names, pending-result survival across Gateway replacement, and external channel delivery are not established here. In these scenarios the child is created after the Gateway restart. |
Follow-up: receipt settlement remains blockedThe current head I ran a new, local owner-boundary regression against the submitted production code. It models abandonment of the receipt-bearing sampling followed by a completed turn with no compaction/error notification. The real monitor, receipt tracker and settlement owner suppress detached delivery when the test expects it to remain pending: 28 passed, 1 failed. The test is uncommitted. It simulates that native schedule; it does not execute native preemption or compaction failure. In particular, its synthetic request abort occurs after capture and is not proof that native abandoned a stream. It must not be used alone to certify a repair. A proxy-observed The existing positive boundary is native's handling of The earlier linked end-to-end evidence remains valid only for its stated scenarios. It does not cover this loss path. The test-line CI failure also remains unresolved. This update does not request re-review or claim readiness. |
|
This pull request has been automatically marked as stale after 7 days without qualifying human activity. |
|
Closing due to inactivity. |
Status: draft; submitted settlement rule is unsafe
The submitted head remains
d7ca03a8938a66809aa7334a67daa2c273b7c7d7. The failing owner-boundary regression and correctness block remain applicable. Generic turn completion does not prove that native consumed a particular result. No replacement production code has been pushed; the hosted test-line ratchet remains red.October 29 investigation outcome
9def09af, not built or run. Cold resume and initially-disabled loaded rejoin still cannot enable the raw completion signal.9d4bc16a, stages raw receipts until native sampling completion. Its compaction flag excludes the compaction response itself, but leaves unsampled receipts pending. A later normal response can therefore accept an old receipt after history replacement removed the result. The source-supported schedule is raw result → abandoned sampling → successful mid-turn compaction → successful ordinary sampling without the original result. Native 0.164 permits the abandoned sampling and can exclude FINAL_ANSWER envelopes during remote compaction. This is source analysis, not a new native end-to-end reproduction or a review approval of that PR. Pending unsampled evidence must be invalidated at history replacement, while genuinely sampled and new post-compaction receipts need appropriate controls.The smaller direction to evaluate is correct native-event settlement in the existing receipt owner, native resume-event support, and a small OpenClaw resume opt-in once that API exists. It still needs combined restart/resume/wait and failure/preemption/compaction proof. Neither this PR nor the related PR is declared sufficient or ready on that basis. No native upgrade, live runtime change, merge, or complete fix is claimed.
October 29 runnable maintainer handoff
9d4bc16a, the actual receipt/parser classes fail the stale pre-compaction receipt test; the fresh post-compaction control passes. This is tracker-level proof using synthetic events, not a native preemption/compaction or Gateway end-to-end loss reproduction.Ownership and acceptance boundary
These reports are evidence and acceptance criteria, not approval of either OpenClaw PR or a claim that a fix has shipped.
The original implementation description and historical evidence below are preserved for review, not a merge recommendation. In particular, the earlier advice to settle resumed receipts from generic turn completion, and its composition advice for #149490, are superseded.
Related: #156070
What Problem This Solves
After a Gateway restart, a Codex parent can receive a native child's result through
wait_agentand answer it. A separate automaticannounce:codex-native:…:succeededrun then gives the same answer again.User Impact
On providers that native Codex treats as OpenAI (OpenAI API key and Codex/ChatGPT login), a resumed conversation that waits for a native child and answers it in a turn that completes normally no longer gets a second automatic answer for that result. In the tested yield/unconsumed scenarios, results the parent did not sample are still delivered automatically. No configuration change or migration is needed.
Known correctness limitation: a native compaction-setup failure after a preempted or mailbox-failed request can cause a result to be marked consumed without a completed sampling. The detailed condition is below; this edge has not been reproduced end to end.
Not changed, so an extra reply can still happen (nothing is dropped in these cases):
OpenAI. That covers OpenClaw's subscription-sharing route and custom Responses providers. Routes that do not use the inference proxy are not covered either.response.create, which sends only new input. If the parent makes another model request in the same turn after the one that carried the result, that later request no longer carries it and the result stays pending. The end-to-end runs below used HTTP.Stopruns after the request that carried it, or if the foreground owner is released or yields before native reports the turn completed."Consumed" here means native completed a parent sampling that carried the result. That is neither a durable native acknowledgement nor channel delivery. Recovering a pending child result across Gateway replacement is not tested.
The native contract below was checked against the managed Codex 0.164.0. Older or newer external app-server overrides were not validated.
Why This Change Was Made
Codex streams raw item events only to threads started with
experimentalRawEvents, andthread/resumehas no such option. V2waititems carry no receiver status, and after resume the alternative raw envelope events are also absent, so OpenClaw records no receipt and the completion owner delivers the already-consumed result again.#130503 tried to fix this on the native side by renewing the raw-event opt-in on resume. It was withdrawn to keep completion handling in OpenClaw without a Codex protocol change, and Codex 0.164.0 still has no resume opt-in. This change stays in OpenClaw. #166349 tracks the broader parent-wake and restart semantics; this PR fixes only the duplicate.
The receipt still reaches OpenClaw: native sends the child's
FINAL_ANSWERenvelope as current-turn input in the parent's next model request, which the plugin already authorizes. The parent's receipt tracker holds the receipts carried by the turn's latest ordinary model request, and hands them to the existing tracker when native reports that turncompleted, unless compaction or a non-Stophook ran in between.Settlement rules and native contract
Resumed threads get no per-sampling completion notification (
rawResponse/completedis a raw event).thread/tokenUsage/updatedis also emitted after a context-window error, on rate-limit headers and around compaction, so it does not prove that a sampling succeeded. The change therefore uses this evidence:contextCompactionitems, andhook/startedfor any hook other thanStop, discard what is held for that turn. These are how native can complete a turn without another sampling after a preempted or interrupted stream: a hook that blocks steered input, or a session-start hook after compaction.Stophooks run only after a final sampling completed.completed, the held receipts go to the existing tracker. This happens behind the existing owner gate (bound, not yielded, not settled) and before the turn observer marks the owner's model execution settled.Native's contract, as checked in source: a turn is
completedwhen no turn-affecting error was recorded. Retries rebuild the prompt from the current recorded history. Same-turn preemption can drop a streaming request and continue the turn. Compaction or a token-budget rollover can then removeFINAL_ANSWERitems before the next sampling. A blocking input hook can also end the loop without another sampling. Capture always precedes forwarding, so it is ordered before the turn's completion.One native path is not covered: if setting up a mid-turn compaction fails before the compaction task starts, native reports the turn
completedwith neither acontextCompactionitem nor an error. A result could be marked consumed only if, in the same step, the request carrying it was also preempted or hit a mailbox stream error and a compaction was due. The underlyingcompletedstatus there looks like a native status issue. This remains an unresolved correctness limitation for maintainer consideration, not a demonstrated no-drop guarantee.Held receipts are foreground-only. They are discarded when an owner releases its turn, when the last owner releases, and when a parent retires or the monitor is disposed. Matching, alias, predecessor/successor and custody state stay in the existing tracker. Fresh threads keep their raw-event receipts unchanged.
Checked in openai/codex rust-v0.164.0:
ThreadResumeParamshas no raw-event option. The resumed listener is attached with raw events disabled (app-server/src/request_processors/thread_processor.rs).rawResponseItem/completedandrawResponse/completedare dropped for listeners without the opt-in (app-server/src/request_processors/thread_lifecycle.rs).handle_turn_completereportsFailedonly when a turn-affecting error was recorded, otherwiseCompleted; aborts reportInterrupted(app-server/src/bespoke_event_handling.rs).response.completed. Mid-turn compaction or rollover can run before the next sampling, and a blocking input hook can end the loop (core/src/session/turn.rs). Remote compaction excludesFINAL_ANSWERitems (core/src/compact_remote_v2.rs). Compaction tasks emit acontextCompactionitem (compact.rs,compact_remote_v2*.rs,compact_token_budget.rs).ContextWindowExceeded, on rate-limit events and during compaction (core/src/session/turn.rs,compact*.rs).internal_chat_message_metadata_passthroughcleared before the request is sent (core/src/client.rs,model-provider-info/src/lib.rs).core/src/hook_runtime.rs).Composition with #149490 (open; rewrites the same tracker): #149490 holds raw receipts until a later non-compaction
rawResponse/completed. That is a raw event, so it does not fire on resumed threads. If both land, the input receipts held here should keep settling onturn/completedand should not be routed through #149490's "wait for a later response" gate, which never fires after the turn ends. The two changes touch overlapping lines innative-subagent-delivery-receipts.tsand the monitor wiring, so whichever lands second needs a manual merge.Evidence
Inspectable original-head terminal results and test boundaries, including the restart/wait case, unconsumed-result control and failing baseline. These are retained runs, not proof of a later repair.
The reproduction and test results below come from the prepared source-build investigation. The publication review inspected the retained logs and exact patch, but did not rerun those tests.
Base
ba1828c8fb5554b752e11cdba0306fa2d1d4c634(main), headd7ca03a8938a66809aa7334a67daa2c273b7c7d7; native Codex 0.164.0 from the lockfile. The change was first developed on89bc6de; none of its nine files changed between the two bases, and the commit is patch-identical.Freshness check (2026-10-27). Upstream main had advanced to
5cf6a7fd4ebaebb9f1fee12a1d33f2ab291e3f86; all nine patch-target files have identical Git blob IDs to the tested baseba1828c8. This is a source-drift check, not a rerun of tests on that newer main. #156070 remains open; #149490 remains open and unmerged at9d4bc16a.Real Gateway scenarios (isolated state, real native app-server with V2 multi-agent, scripted loopback Responses provider over HTTP, synthetic credentials, provider named
OpenAI). The steps follow the issue: an ordinary turn, then a real Gateway restart. The parent spawns a child, callswait_agentand answers. After an ordinary turn, a fresh request re-tasks the same child and waits again.wait_agentannounce:codex-native:…:succeededrun answers again (every base run)The first row was rerun on both the base and head above; the second row was rerun on the head only. The other rows ran with the same patch on the earlier base
89bc6de.The preemption, compaction and hook-stop paths could not be driven by a scripted provider alone; they are covered by the owner-boundary tests below.
Tests
native-subagent-monitor.completion-delivery.test.ts(owning monitor boundary, real tracker and delivery owner):Stophook), both reused-child cases, and the release-lifetime case.Stophook after it, and held evidence surviving release.inference-routing.test.ts: only ordinary/responsesturn input is offered for receipt capture. All 49 pass; with the production change reverted, that case fails.pnpm test <file> --maxWorkers=1: 12 s and 11 s wall when warm (46 s and 23 s on a cold transform cache, over 80% transform). Each file runs under 2 s of test time. The 11 new monitor cases total 18 ms, and the 2 routing cases 2 ms.pnpm test:extension codex(438 files): 5,319 passed, 17 skipped, 2 failed. The 2 failures are intransport-startup.test.ts(ProcessInspectionError, from the local sandbox's process-inspection permission) and fail identically on base.pnpm check:changedagainst the base: 31 of 32 lanes pass, including extension and extension-test typecheck, changed-file lint and format, and the line-cap and other ratchets. The dead-export scan is red with 20 entries that are identical on base, none in the changed files.pnpm deadcode:unused-filesreports 14 entries, also identical on base and none in the changed files. The monitor shrinks by 2 lines.agent-tools.prefix-stability.test.tspasses.89bc6de4583cb2b3fd70a6bb52dd1a5e1db202c9, supplied head42a1336656637c2df8829ce3d69ac1af8af665b6. Both returned approve-with-changes, with no P0/P1 findings; required P2 scope disclosures (native version and WebSocket efficacy) are included above. The reviewed patch and final submission have the same stable patch ID,4a7dea7442e030a81a3aaf94f634c156c9c7b1d6. A separate native Codex handoff review inspected the exact final patch (ba1828c8→d7ca03a8) for correctness, ownership and loss paths and found no new actionable P0–P2 production-code finding; a separate evidence review checked retained logs and corrected count/scope wording. Those publishing-lane reviews did not rerun tests. The compaction-setup loss edge remains explicitly unresolved, not waived by these reviews.Not covered: a real-native run of the preemption, compaction or hook-stop paths; WebSocket transport; external app-server versions other than 0.164.0; a pending child result surviving Gateway replacement; channel delivery. The reporter's
queue_message_failed reason=not_streamingwarning did not appear on the testedmainsnapshots, although the duplicateannounce:codex-native:…:succeededrun did.