Skip to content

fix(codex): duplicate final reply after a resumed parent waits for a native child - #186128

Closed
cassthebandit wants to merge 1 commit into
openclaw:mainfrom
cassthebandit:fix/codex-resumed-wait-duplicate-reply
Closed

cassthebandit wants to merge 1 commit into
openclaw:mainfrom
cassthebandit:fix/codex-resumed-wait-duplicate-reply

Conversation

@cassthebandit

@cassthebandit cassthebandit commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Native dependency confirmed and reported: seven real-app-server scenario results and current-source evidence are posted on the existing Codex issue, with an explicit request to reopen the same-thread-ID case. The tested binary was Codex 0.164.0 with a mocked HTTP provider, not a production model. Current source was separately checked at 9def09af, not built or run. Cold resume and initially-disabled loaded rejoin still cannot enable the raw completion signal.
  • Local replacement prototype rejected before publication: correlating provider response IDs with native completion fixed the modeled owner loss case, but globally removing raw-receipt settlement newly duplicates fresh-thread results on metadata-stripped providers, including subscription sharing, and on proxy-bypassing routes. Independent review also identified a real-stream cancellation/backpressure failure in the proposed HTTP observer. Passing focused owner/relay tests did not establish whole-route compatibility. That prototype is not a proposed ready repair; its code has not been committed or pushed.
  • Related work is not an already-proven substitute: #149490, inspected at unchanged head 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

Ownership and acceptance boundary

  • Codex: expose the existing raw completion notifications for identity-preserving cold resume and initially-disabled loaded rejoin. Preserve experimental gating and existing default-false/enable-only behavior. Controls: fresh enabled; enabled rejoin; disabled-to-enabled rejoin; process restart + same-ID resume; omitted/false on both disabled and already-enabled loaded threads; failed and interrupted sampling must not emit a successful completion acknowledgment.
  • OpenClaw: request the supported resume opt-in when available, and invalidate unacknowledged receipt evidence when history is replaced. Do not infer consumption from raw-item arrival, provider transport completion, or generic turn completion. Controls: stale pre-compaction evidence remains unaccepted; fresh post-compaction receipts can be accepted; already-consumed results are not spuriously redelivered. Preserve wrong-thread/wrong-turn/stale-response rejection and the V1 matching-tool-output eligibility gate.
  • Combined integration: real isolated Gateway restart -> same-parent resume -> native-child wait -> one answer; reuse the same child; yielded, unconsumed, failed, interrupted and preempted/compacted results retain delivery eligibility. Include a metadata-stripped provider route and disclose HTTP/WebSocket coverage. This combined corrected-path proof remains outstanding.

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_agent and answer it. A separate automatic announce:codex-native:…:succeeded run 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):

  • Other provider names. Native removes the per-item metadata this fix reads unless the provider is named exactly OpenAI. That covers OpenClaw's subscription-sharing route and custom Responses providers. Routes that do not use the inference proxy are not covered either.
  • WebSocket incremental requests. On the covered routes native can use WebSocket 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.
  • Uncertain samplings. The result stays pending if the parent's turn fails or is interrupted, or if a later model request in the turn no longer carries the result. It also stays pending if context compaction or a hook other than Stop runs 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, and thread/resume has no such option. V2 wait items 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_ANSWER envelope 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 turn completed, unless compaction or a non-Stop hook ran in between.

Settlement rules and native contract

Resumed threads get no per-sampling completion notification (rawResponse/completed is a raw event). thread/tokenUsage/updated is 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:

  1. The parent's receipt tracker holds only the receipts carried by the parent turn's latest model request. Each later request replaces them. A request that is not an ordinary sampling, such as compaction or review, carries none.
  2. Native contextCompaction items, and hook/started for any hook other than Stop, 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. Stop hooks run only after a final sampling completed.
  3. When native reports that same turn 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 completed when 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 remove FINAL_ANSWER items 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 completed with neither a contextCompaction item 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 underlying completed status 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:

  • ThreadResumeParams has no raw-event option. The resumed listener is attached with raw events disabled (app-server/src/request_processors/thread_processor.rs). rawResponseItem/completed and rawResponse/completed are dropped for listeners without the opt-in (app-server/src/request_processors/thread_lifecycle.rs).
  • handle_turn_complete reports Failed only when a turn-affecting error was recorded, otherwise Completed; aborts report Interrupted (app-server/src/bespoke_event_handling.rs).
  • Sampling retries rebuild from recorded history. Preemption and mailbox stream errors return a follow-up without 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 excludes FINAL_ANSWER items (core/src/compact_remote_v2.rs). Compaction tasks emit a contextCompaction item (compact.rs, compact_remote_v2*.rs, compact_token_budget.rs).
  • Token-count notifications are also emitted after ContextWindowExceeded, on rate-limit events and during compaction (core/src/session/turn.rs, compact*.rs).
  • Non-OpenAI providers have internal_chat_message_metadata_passthrough cleared before the request is sent (core/src/client.rs, model-provider-info/src/lib.rs).
  • Hook notifications are emitted for synchronous, non-built-in hooks (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 on turn/completed and 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 in native-subagent-delivery-receipts.ts and 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), head d7ca03a8938a66809aa7334a67daa2c273b7c7d7; native Codex 0.164.0 from the lockfile. The change was first developed on 89bc6de; 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 base ba1828c8. This is a source-drift check, not a rerun of tests on that newer main. #156070 remains open; #149490 remains open and unmerged at 9d4bc16a.

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, calls wait_agent and answers. After an ordinary turn, a fresh request re-tasks the same child and waits again.

Scenario Base This change
Restart, parent consumes the result via wait_agent Fails: the parent answers, then a separate announce:codex-native:…:succeeded run answers again (every base run) Passes: one answer per result, no automatic run, same child reused, session idle
Restart, parent yields instead (result never sampled) — Result delivered automatically exactly once
Restart, terminal provider error on the request carrying the result (turn fails) — Result stays pending and is delivered once; one answer
Restart, one-shot provider 503 on that request (native retries) — One answer, no automatic run
Restart, one-shot OpenClaw request-preparation failure on that request — One answer, no automatic run
No restart (fresh thread) — One answer per result, no automatic 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):
    • With the production change reverted, 5 cases fail: the duplicate (with and without a following Stop hook), both reused-child cases, and the release-lifetime case.
    • Against the previous revision of this change, 4 cases fail: a later request without the result, compaction after it, a non-Stop hook after it, and held evidence surviving release.
    • With this change, all 28 pass. The remaining new cases keep failed, interrupted and earlier-turn results pending.
  • inference-routing.test.ts: only ordinary /responses turn 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 in transport-startup.test.ts (ProcessInspectionError, from the local sandbox's process-inspection permission) and fail identically on base.
  • pnpm check:changed against 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-files reports 14 entries, also identical on base and none in the changed files. The monitor shrinks by 2 lines.
  • The change does not alter provider request bytes; agent-tools.prefix-stability.test.ts passes.
  • Local review: canonical autoreview was not run in the preparation lane because model-service access was outside that lane's authorization; only its P0–P2 dry run succeeded. No completed canonical-autoreview result is claimed for this submission.
  • Actual review evidence: independent Astra and Opus AI source reviews examined the r2 patch/tree on base 89bc6de4583cb2b3fd70a6bb52dd1a5e1db202c9, supplied head 42a1336656637c2df8829ce3d69ac1af8af665b6. 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_streaming warning did not appear on the tested main snapshots, although the duplicate announce:codex-native:…:succeeded run did.

…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
@clawsweeper

clawsweeper Bot commented Oct 27, 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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This 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.”

  • Before: The parent answers, then an automatic completion run answers again.
  • After: On covered OpenAI HTTP routes, the completed parent turn settles the receipt and prevents the second answer.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful partial repair with a source-confirmed false-consumption defect, an attributable CI failure, and no inspectable after-fix behavior proof.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: A resumed Codex parent can answer a child result and then send a second answer through an automatic completion run.
Reason: The existing contract promises deduplication of consumed foreground results; this bounded repair has clear value, while custom-provider and incremental WebSocket cases remain explicitly uncovered.

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
Reviewed head: d7ca03a8938a66809aa7334a67daa2c273b7c7d7

Before merge

  • Add real behavior proof - The body describes isolated Gateway/native HTTP runs on the patch, but supplies no inspectable after-fix terminal output, logs, or artifact; the downloaded screenshots establish only the original bug. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Require completed sampling before settling held receipts (P2) - A request carrying a child result can be preempted before response completion, after which native starts mid-turn compaction. In Codex 0.164.0, failure while building compaction world state occurs before a contextCompaction item is emitted; the caller invokes extension error lifecycle callbacks and returns Ok(None), without recording the app-server Error event. Native therefore reports the turn completed. These lines accept the held receipt even though no sampling completed, and applyReceipts marks the child delivered so prepareDelivery clears its pending result. The PR discloses this path, and direct native source confirms it. Preserve pending delivery unless completed sampling is positively established.
  • Resolve the added-test-line ratchet failure (P2) - The exact-head baseline job fails its test-lines lane. The verified merge candidate contains 6,286,120 test lines against a 6,285,587 ceiling, and this PR introduces 164 test lines. The ratchet exempts an inherited over-ceiling tree only when the patch adds no test lines, so this addition triggers the failure. Consolidate the new coverage and offset remaining growth through focused test simplification while retaining the distinct lifecycle regressions.

Findings

  • [P2] Require completed sampling before settling held receipts — extensions/codex/src/app-server/native-subagent-parent-owner.ts:139-143
  • [P2] Resolve the added-test-line ratchet failure — extensions/codex/src/app-server/native-subagent-monitor.completion-delivery.test.ts:377-381

Tests

  • Low-value test extensions/codex/src/app-server/inference-routing.test.ts: The added table only asserts argument shape against mocked captureModelSource; replace it with a dispatch-to-real-receipt-owner scenario or remove it.
  • Missing end-to-end proof: Attach inspectable after-fix Gateway/native output for restart → wait_agent → one answer and the unconsumed-result control, with IPs, credentials, phone numbers, and private endpoints redacted.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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:

  • [P2] Require completed sampling before settling held receipts — extensions/codex/src/app-server/native-subagent-parent-owner.ts:139-143
    A request carrying a child result can be preempted before response completion, after which native starts mid-turn compaction. In Codex 0.164.0, failure while building compaction world state occurs before a contextCompaction item is emitted; the caller invokes extension error lifecycle callbacks and returns Ok(None), without recording the app-server Error event. Native therefore reports the turn completed. These lines accept the held receipt even though no sampling completed, and applyReceipts marks the child delivered so prepareDelivery clears its pending result. The PR discloses this path, and direct native source confirms it. Preserve pending delivery unless completed sampling is positively established.
    Confidence: 0.96
  • [P2] Resolve the added-test-line ratchet failure — extensions/codex/src/app-server/native-subagent-monitor.completion-delivery.test.ts:377-381
    The exact-head baseline job fails its test-lines lane. The verified merge candidate contains 6,286,120 test lines against a 6,285,587 ceiling, and this PR introduces 164 test lines. The ratchet exempts an inherited over-ceiling tree only when the patch adds no test lines, so this addition triggers the failure. Consolidate the new coverage and offset remaining growth through focused test simplification while retaining the distinct lifecycle regressions.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2e333671f594.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test extensions/codex/src/app-server/native-subagent-monitor.completion-delivery.test.ts --maxWorkers=1
  • pnpm test extensions/codex/src/app-server/inference-routing.test.ts --maxWorkers=1
  • pnpm check:test-lines-ratchet --base ca7f339
  • pnpm check:changed --base ca7f339
  • Show the false-consumption regression failing before repair and passing afterward.

What I checked:

PR surface

Source +111, Tests +164. Total +275 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 127 16 +111
Tests 2 164 0 +164
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 291 16 +275

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The PR repairs duplicate replies in a bounded native-child workflow, with no demonstrated widespread outage.
  • merge-risk: 🚨 message-delivery: False receipt acceptance can remove an unconsumed child result from automatic delivery.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 27, 2026, 12:58 PM ET / 16:58 UTC.

@cassthebandit

Copy link
Copy Markdown
Contributor Author

Original-head live behavior evidence for #186128

These 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 boundary

Both passing receipts contain this identity (verbatim field values):

{
  "head": "d7ca03a8938a66809aa7334a67daa2c273b7c7d7",
  "dirty": [],
  "binary": "codex-cli 0.164.0",
  "binarySha256": "d8990e3ee7acfbc26f91265b12a1a83f0fee40d0e0f8f1f40a37d4ec21f499cf"
}

Base sources: ba1828c8fb5554b752e11cdba0306fa2d1d4c634. Environment: isolated Gateway state, a real native app-server with V2 multi-agent, Codex 0.164.0, and a scripted loopback Responses provider named exactly OpenAI; HTTP inference, synthetic credentials. The disposable build had a test-only fetch redirection to that fixture. This is live Gateway/native integration evidence, not a live model-service or channel-delivery test.

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. cold_resume in the output records the resumed parent requests. The unconsumed control calls sessions_yield instead of wait_agent.

Counts are not merely response-label expectations: finalB/finalC are exact assistant-answer counts from chat.history; announceRuns counts distinct automatic run IDs from Gateway agent events; activeRun comes from sessions.describe. The harness waits for session-message delivery, observes 20 seconds after B, and another 20 seconds after the last answer before checking idle/history. Absence of duplicates is bounded by that observation window.

After fix: restart → wait_agent → one answer per result

Verbatim retained terminal stdout, gate-scenario-final-restart-wait-1.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 restart: true, reuse: true, and announceRunIds: []. Its trace has B and C on the same child; every post-restart parent request is cold_resume. Both owned Gateway processes exited 0 and the test-only build instrumentation was restored.

Unconsumed-result control: automatic delivery remains

Verbatim retained terminal stdout, gate-scenario-final-restart-unconsumed-1.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 restart: true, reuse: false, and one automatic run ID with the shape announce:codex-native:<id>:<id>:succeeded. Retained Gateway terminal excerpt (identifiers were already redacted in the package):

2026-10-27T10:21:28.644-05:00 [agents/agent-command] [agent] run announce:codex-native:<id>:<id>:succeeded ended with stopReason=stop

This control establishes one answer and one automatic continuation for the yielded, unsampled result. It does not exercise same-child reuse; the generic sameChild: true field here covers only the one child turn.

Before fix: duplicate reproduced

For this baseline the checkout's HEAD remained d7ca03a8, but all nine changed files were checked out at base ba1828c8 and the build was regenerated. The receipt therefore correctly reports nine modified files, not a clean base commit. This provenance comes from the retained gate/build report; the baseline stdout by itself does not establish the source reset.

Verbatim retained terminal stdout, gate-scenario-baseline-restart-wait-2.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 final-b followed by unexpected-parent; the latter request has historyInitialization: "new" after the first answer's cold_resume. Retained Gateway terminal excerpt:

2026-10-27T10:14:19.816-05:00 [agents/agent-command] [agent] run announce:codex-native:<id>:<id>:succeeded ended with stopReason=stop

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.

Limits

No new live run is claimed. These receipts cover original head d7ca03a8, not any subsequent repair. The package retains compact results, selected provider traces and announce log excerpts, not the complete Gateway/session event streams; the counts can be inspected alongside the harness, but cannot be independently recounted from full raw streams in this package.

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.

@cassthebandit

Copy link
Copy Markdown
Contributor Author

Follow-up: receipt settlement remains blocked

The current head d7ca03a8938a66809aa7334a67daa2c273b7c7d7 is not ready to merge. I accept the review finding about false consumption. No production repair has been pushed.

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 response.completed is not a sufficient replacement acknowledgment either. In Codex 0.164.0, the provider reader buffers events separately from the turn consumer. Provider completion can be queued before preemption abandons that consumer. If compaction setup then exits without a recorded turn error or a compaction item, turn/completed can still report completed. Request freshness and successful forwarding do not prove native consumed the completion. This is a source-supported schedule, not an end-to-end reproduction or a measured frequency.

The existing positive boundary is native's handling of ResponseEvent::Completed, which produces rawResponse/completed. Resumed listeners do not receive that signal in the inspected 0.164.0 contract. The sound direction is to make native sampling completion available after resume, then use it in the existing receipt owner. Until then, uncertain receipts must stay pending, even if that permits a duplicate. I am not proposing another timing heuristic or a new delivery ledger.

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.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant