Skip to content

fix(gateway): rehome stale native completion authorization - #167638

Closed
Leon-SK668 wants to merge 3 commits into
openclaw:mainfrom
Leon-SK668:leon/fix-codex-completion-work-scope-20261009
Closed

Leon-SK668 wants to merge 3 commits into
openclaw:mainfrom
Leon-SK668:leon/fix-codex-completion-work-scope-20261009

Conversation

@Leon-SK668

@Leon-SK668 Leon-SK668 commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #167410

October 13 maintenance status: current-main acceptance gap requires revalidation

The original regression is no longer red on current main 0cbcfbe8721360edcfbf9412e29bdbb9c1454255. During conflict triage, the contributor temporarily used that main's exact production facade, without this PR's production patch, and ran the three real authorization/projection cases introduced here. All three passed (39 other cases skipped, exit 0). Measured wall time: 123.83 seconds; wrapper: 122.72 seconds; Vitest: 113.98 seconds. Local log SHA-256: 42df424325b4564ad6ba136d3acd8d819dbe73d09d29b1b2afc2af66f0c80802.

That result invalidates a current-main acceptance-red claim for this test seam. Main has meanwhile moved session reads and authority into workers in #169622, and added pre-dispatch custody cleanup in #170855. The contributor is holding further patch publication pending a current-main native spawn/yield replay that demonstrates a remaining gap. No claim is made that the full native behavior is already fixed, or that these focused cases replace the missing native trace. Contributor head remains d17eeb73bdffba8da20ffe329481385feac1ff75; the conflict integration was not published. Historical before/after evidence below remains explicitly tied to its older baseline.

What Problem This Solves

Native Codex completion callbacks can re-enter the Gateway after the originating foreground run has closed. The retained completion still has valid custody, but the in-process agent dispatch performs its authorization projection under the already-aborted caller AsyncWorkScope; the parent continuation is rejected before it can start.

This restores parent continuation for that stale-scope path while keeping the existing authorization, revocation, admission, and request-entry checks intact.

Why This Change Was Made

createInternalAgentTurnFacade is the owner of in-process agent dispatch. Its caller is dispatchGatewayMethodInProcess, and its authorization callee reads the session-row placement projection. The existing GatewayRequestContext.trackExecution already owns the live Gateway execution scope. When the ambient signal is aborted, this change runs only the pre-dispatch authorization through that owner before projection reads; ordinary requests retain the existing single execution entry.

The implementation reuses the existing Gateway work owner rather than adding a new scope, bypassing authorization, or adding a Codex-specific fallback. The Codex protocol contract remains unchanged: the app-server emits a terminal turn completion notification, and OpenClaw continues to use its existing retained completion custody and agent dispatch path.

User Impact

Users whose native Codex child completes after its parent foreground run yields can resume the parent session instead of receiving an aborted-scope admission error. Normal Gateway agent requests and cancellation/revocation behavior are unchanged.

Evidence

Independent native-runtime reproduction and repaired readback — October 11, 2026

Independent public verification by jeanmonet reports the failure and a successful model/native-runtime replay. This is the verifier's reported execution, not a contributor-run replay or an independently downloaded trace artifact.

  • Environment: installed OpenClaw and the official Codex plugin, both 2026.10.1.
  • Before: a parent spawned one native Codex child and called sessions_yield; the child completed normally and saved its result, but the parent transcript remained at the yielded tool result, with no successor model turn. Ordinary foreground authentication/replies and separately tested channel delivery worked.
  • Deterministic comparison: the verifier exercised the actual original/candidate facade with the real core AsyncWorkScope. The original failed with AbortError; the candidate passed the stale-scope authorization preflight. Ordinary live-scope dispatch, permission denial, explicit cancellation before/during authorization, context revocation, closed request entry, and closed Gateway-owner rejection remained intact. This comparison used boundary stubs and stopped at validation; it is separate from the native-runtime replay below.
  • After: the verifier activated only the executable core hunk from contributor head 3efeb8dc52f1a4d5be50de00511eefbe5dda9285 on that installed core, warmed the shared native connection with a completed foreground turn, then used a separate isolated parent to spawn a child with a 70-second wait and immediately yield.
  • Real readback: child completion automatically produced an inter-session input with sourceTool: agent_harness_completion; the parent committed the expected final answer and reached done. No queued input remained; the assignment was removed from its active binding; no announce failure or retry exhaustion was observed.

Scope and limits: this verifies the proposed production hunk in a real spawn → yield → successor path on installed 2026.10.1, with external delivery and the message tool disabled. It does not establish a complete PR-branch build, automatic external-channel delivery, recovery of previously interrupted inputs, or other stale-scope consumers. Session IDs, raw .jsonl traces and downloaded proof artifacts were not included in the public report, so none are invented here. The public report is the available provenance for these observations.

Contributor source and focused validation

  • Issue [Bug]: Native Codex completion inherits an aborted run scope and fails before parent admission #167410 includes a deterministic reproduction on 60f703...: the current-main path fails after native Codex completion because the stale signal is observed during session authorization.
  • Source inspection traced the historical failure through src/gateway/agent-turn/internal-facade.ts → authorizeGatewayRequestPreDispatch → session-row placement projection. Earlier main dcbceeb0cae158494469b6946608ea932ec46a2e still invoked authorization directly. The newer current-main comparison above passes without the production patch, so the older call ordering alone is not evidence of a remaining defect.
  • The earlier mocked scope-identity test has been replaced with three behavior cases in src/gateway/server-plugin-in-process-dispatch.authorization.test.ts. They bind and materialize a real SQLite-backed session-row projection, drain the foreground work, then dispatch under a live Gateway owner through the actual authorization and preflight paths. The allowed case is accepted; missing operator.write and explicit cancellation remain rejected. Only final model execution is mocked. This proves the authorization/projection regression, not a native model spawn/yield replay.
  • Direct Codex source inspection: codex-rs/core/src/agent/control.rs subscribes to child status; codex-rs/core/src/agent/status.rs maps TurnComplete to Completed; codex-rs/app-server/src/bespoke_event_handling.rs emits TurnCompletedNotification. No dependency protocol change is needed.
  • Existing-solutions preflight: no plugin or maintained external library can repair this core Gateway execution-lifetime boundary. The existing trackExecution seam is the appropriate owner.
  • No config, protocol, storage, migration, dependency, or security surface changes.

Passed during the October 9 implementation at contributor head 3efeb8dc52f1a4d5be50de00511eefbe5dda9285:

node scripts/run-vitest.mjs src/gateway/agent-turn/internal-facade.test.ts --maxWorkers=1
  1 file, 23 tests passed
oxfmt --check --threads=1 src/gateway/agent-turn/internal-facade.ts src/gateway/agent-turn/internal-facade.test.ts
git diff --check
node scripts/check-changed.mjs --timed --base refs/remotes/upstream/p01-main-20261009 -- <changed files>
  all completed checks passed through core production, gateway-root, and gateway-server type graphs;
  the remaining broad core-test graph was intentionally stopped after the relevant gateway graphs passed

October 13 exact-head regression receipt

Contributor head: d17eeb73bdffba8da20ffe329481385feac1ff75; tree: de3c8bb05c089094977550e5182448f12bee0e1c. The production hunk is byte-identical to 3efeb8dc52f1a4d5be50de00511eefbe5dda9285. Commit 7e4fd468472a6aff6f91e927cf185ddabf211d9b replaced the mocked test with the real authorization/projection cases above; the final test-only follow-up explicitly publishes the fixture's runtime config before writing its session, matching current main's prepared-config contract.

Paired acceptance command:

node scripts/run-vitest.mjs src/gateway/server-plugin-in-process-dispatch.authorization.test.ts --maxWorkers=1 -t 'handoff from drained foreground'
  • RED: temporarily restore only the production facade to the unfixed parent 70c839ac6bc812bf930ee7cc06a6895117c09d9c, keeping the new tests identical. The allowed handoff fails with AbortError; the denied and canceled cases pass. Result: 1 failed, 2 passed, 36 skipped, exit 1. Measured wall time 103.51 seconds; wrapper 102.63 seconds.
  • Paired GREEN at committed head 7e4fd468472a6aff6f91e927cf185ddabf211d9b: the same command passed 3 tests, skipped 36, exit 0. Measured wall time 44.47 seconds; wrapper 43.69 seconds. The unfixed production source was fully restored to the candidate before commit.
  • Full touched-file coverage: node scripts/run-vitest.mjs src/gateway/server-plugin-in-process-dispatch.authorization.test.ts src/gateway/agent-turn/internal-facade.test.ts --maxWorkers=1 passed all 61 tests in 2 files, exit 0, both before the first test commit and after the explicit runtime-config fixture correction. The final run used the exact source bytes committed at d17eeb73bdffba8da20ffe329481385feac1ff75, with wrapper duration 74.34 seconds and Vitest duration 67.16 seconds; no separate wall measurement was captured for that final run. The earlier run measured wall time 149.15 seconds and wrapper duration 148.20 seconds.
  • Both files passed oxfmt --check --threads=1, focused node scripts/run-oxlint.mjs --openclaw-focused-config, and git diff --check.

Local log integrity (SHA-256; logs are retained locally, not represented as downloadable public artifacts):

RED   62f508667768ebd24db046af765ae2914a93314ca4ba02c612a6d8ff9f325e7f
GREEN c97a0bc19b0e6050f1de97a0faa68cfd5b797340370ea2f521f2803305a2ab68
FULL  e711363fa391ec3244952333cdc9dc54bfa10a0dc6a53d0875246cb625d4326f
production facade 60d4bc0bddfaf6f1f756cfe7c12888be9af552e2b7ca181d4b38f622cc4bb4fd
authorization test 7792dc291eed0df9a7502691461eb6e50cefd045017b20e17118f18516ca9342
final full run     a45ea6888462c66cae90f841a51da51449e18f12d51b5b26af72ebaf8342c8ba
final test source  d37c26ce2788ca04749bd438770350d6d82ed73344fe96487dcc6f43af2ae0c0

Production LOC: +15 / -7. Test LOC: +69 / -0. Files changed: 2. The former facade test has no net change against the PR base. Production growth selects the existing work owner before asynchronous authorization; it adds no second authorization policy or runtime fallback.

CI maintenance: CI run 38363611143, failed shard 115183957123 checked head 7e4fd468472a6aff6f91e927cf185ddabf211d9b merged into 14c5ff2371a0095fe5cfd9976c294b01ffa008ef. All three new cases stopped during fixture session creation with Runtime config is not prepared, before testing dispatch. Current main now requires a prepared runtime snapshot; the final follow-up initializes that snapshot before the write. The local final run passes, and new-head CI is being checked separately. No required-CI-green claim is made here.

Current limits: no fresh independent code review is claimed. The independent installed-runtime report above concerns the identical production hunk, but inspectable native after-fix logs or traces are still missing. These focused tests are not substituted for that native behavior artifact. The available Crabbox CLI is installed, but the broker preflight returns whoami requires a configured coordinator; no remote lease or full native replay has been run during this maintenance.

Compatibility and risk

This is an internal Gateway execution-scope repair. It does not add configuration, alter public protocol shapes, change persisted data, or loosen authorization. If the Gateway owner is unavailable, trackExecution still fails closed; the patch does not bypass lifecycle admission. The changed preflight scope and ordinary dispatch/cancellation guards have focused coverage, while the independent native-runtime replay verifies the repaired continuation path within the limits stated above.

AI disclosure

This PR was prepared and maintained with AI assistance. The contributor inspected the source ownership path, dependency protocol, patch, validation results and the linked independent public verification. No credentials, private session data, or undisclosed live-provider execution are included.

@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR runs authorization under the existing Gateway execution owner when a completion callback inherits an aborted foreground work scope.

Example: On OpenClaw 2026.10.1, a parent yields while its native Codex child waits 70 seconds and completes.

  • Before: Authorization encounters the drained foreground scope, and the parent receives no successor turn.
  • After: Jeanmonet reports that applying the identical production hunk lets the parent consume the child result and reach done.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The focused historical repair has no verified introduced correctness defect and meaningful boundary tests, but its production necessity is unsettled and the external-PR runtime-proof gate remains open.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A native child completes successfully, but its yielded parent never resumes automatically to consume the result.
Reason: The historical repair has clear user value, but recent owner changes remove the reproduced acceptance failure, leaving the value of this production hunk on current main unsettled.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open: it addresses a demonstrated native-completion failure, but current main now passes its focused acceptance cases without the patch, and no formally linked merged fix establishes that the complete native workflow is resolved.

Priority: P1
Reviewed head: d17eeb73bdffba8da20ffe329481385feac1ff75
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Does current-main native spawn → yield → completion still require this production scope handoff, or should this contribution retain only regression coverage?
  • Recommendation: Establish the remaining native failure: Use a current-main native comparison to identify whether a production repair remains necessary before carrying the hunk forward.
  • Why: The historical defect is supported, but the contributor’s unpatched current-main acceptance cases now pass and the native workflow has not been revalidated there.

Before merge

  • Add real behavior proof - Jeanmonet reports the identical production hunk succeeding through installed 2026.10.1 native spawn → yield → successor execution, but the full body and public comment provide no inspectable after-fix runtime output or trace artifact; attach redacted logs, terminal output, or a recording that also establishes the remaining current-main failure and candidate result, removing IPs, API keys, phone numbers, private identifiers, and non-public endpoints. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Complete next step - If the production repair remains necessary, reconcile the overlapping authorization block with current main while preserving both authorization-release calls added by fix(gateway): release leaked state after subagent launches #170855.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.

Findings

None.

Tests

  • Missing end-to-end proof: Inspectable native spawn → yield → successor output comparing current main with the candidate is missing; the supplied red/green acceptance receipt applies to the older baseline.
Agent review details

How this fits together

Native child results enter the completion SDK with retained requester custody, pass through in-process Gateway authorization and turn admission, and become a new parent model input.

flowchart TD
  A[Native child completion] --> B[Completion custody owner]
  B --> C[In-process Gateway dispatch]
  C --> D[Internal agent turn facade]
  D --> E[Gateway authorization]
  E --> F[Turn admission]
  F --> G[Parent successor turn]
Loading

Technical review

Best possible solution:

Preserve current main’s worker-backed authorization and cleanup, and retain a production scope repair only for a demonstrated remaining native-completion failure.

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

The historical failure has a concrete owned-source reproduction and an installed-release report, but no high-confidence current-main reproduction remains: the contributor reports the focused cases passing without this patch, consistent with the inspected worker-backed authorization path.

Is this the best way to solve the issue?

The historical hunk repairs preparation through the existing Gateway work owner without creating another authorization policy; carrying it onto current main requires evidence that the native path still fails.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 5a290d637963.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Shakker: Raw commit 715077a adds src/gateway/server-plugin-in-process-dispatch.authorization.test.ts:4 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 715077a3befb; files: src/gateway/server-plugin-in-process-dispatch.authorization.test.ts)

PR surface

Source +8, Tests +69. Total +77 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 15 7 +8
Tests 1 69 0 +69
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 84 7 +77

Review metrics

Metric Value Why it matters
Production versus test LOC Production +15/-7; tests +69/-0 The historical repair reuses the existing work owner and adds behavioral authorization coverage; current-main necessity must determine whether production growth remains justified.

Root-cause cluster

Relationship: same_root_cause
Canonical: #167410
Summary: The canonical report identifies the same aborted ambient scope before parent admission; other native-parent-wake patches address distinct completion stages.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The reported official-release failure blocks automatic continuation after native child completion and requires another user message to recover the result.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Attach redacted native spawn → yield → successor output comparing current main and the candidate.

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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-09T05:50:51.815Z sha 3efeb8d :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-13T07:18:35.861Z sha 3efeb8d :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-13T07:41:10.333Z sha 7e4fd46 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-13T11:21:22.220Z sha d17eeb7 :: needs real behavior proof before merge. :: none

Reviewed October 13, 2026, 7:50 AM ET / 11:50 UTC (Revision 5).

@jeanmonet

Copy link
Copy Markdown

Reproduced the completed-child / yielded-parent symptom with OpenClaw and the official Codex plugin both on 2026.10.1.

The parent spawned one native Codex child and called sessions_yield. The channel received the standard continuation acknowledgment. About four minutes later the child recorded a normal task_complete event with a substantive final answer and saved its report. The parent remained parked: no successor model turn and no channel answer. Its OpenClaw transcript still ended at the yielded tool result, and its session metadata retained a running state and active writer identity.

Subscription authentication and ordinary foreground replies worked. Channel access and outbound delivery also worked; a manually recovered answer was delivered and independently verified. This rules out an archived thread, exhausted subscription quota, or a general channel-send failure for this reproduction.

Native children now use the Codex harness's binding/assignment/result receipts rather than the retired Tasks view. Old task_runs rows are not evidence of the current completion state.

The completed result was preserved and recovered without repeating the research or other completed actions. Automatic parent wake remains the unresolved behavior.

The failure matches #167410: the completion's pre-dispatch authorization inherits a drained foreground AsyncWorkScope. The session-row projection observes its aborted ambient signal before a new parent turn is admitted. Rehoming only that stale authorization preflight into context.trackExecution, as proposed here at head 3efeb8dc52f1a4d5be50de00511eefbe5dda9285, repaired this path locally.

Verification of the proposed executable hunk on the installed 2026.10.1 core:

  • Exercised the actual original/candidate facade source with the real core AsyncWorkScope: original fails with AbortError; candidate passes the stale-scope preflight. Ordinary live-scope behavior, permission denial, explicit cancellation before/during authorization, context revocation, closed request entry and closed Gateway-owner rejection remain intact. These authorization tests use boundary stubs and stop at validation.
  • Activated only this core hunk, then completed a foreground turn to warm the shared native connection. A separate isolated parent spawned a child with a 70-second wait and immediately called sessions_yield.
  • The completed child automatically produced an inter-session input with sourceTool: agent_harness_completion. The parent then committed the expected final answer and reached done.
  • The probe had no queued inputs afterward, its native assignment was removed from the active binding, and no announce failure or retry exhaustion was observed for that probe.

This is an actual model/native-runtime spawn → yield → successor verification, with external delivery and the message tool disabled. It does not claim an automatic external-channel test or fixes for other stale-scope consumers or previously interrupted inputs. Independent reviews found no blocking correctness/security issue in this hunk.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 13, 2026
@SanderHelgesen

Copy link
Copy Markdown
Contributor

Heads-up: once this lands (or main otherwise stops aborting the stale-scope path), native child results the parent already consumed in the foreground will still be redelivered and wake the parent again, so users would get duplicate answers. On our 2026.10.1 install this affects 30 of 31 delegated children; today the abort hides it. That needs receipt matching fixed first or alongside, details: #149490 (comment)

@Leon-SK668

Copy link
Copy Markdown
Contributor Author

Withdrawing this proposal after rechecking its necessity against current main.

Unpatched main 0cbcfbe8721360edcfbf9412e29bdbb9c1454255 passes all three real authorization/projection cases introduced here. The worker-backed authorization and pre-dispatch custody cleanup have changed the responsible path, so the historical red/green comparison no longer establishes a remaining current-main defect. The latest source comparison retains those owner changes.

A complete current-main native spawn -> yield -> successor replay is still missing. The October 13 duplicate-result report also needs separate verification before extending this repair. I am stopping further integration and proof expenditure on this production hunk until a remaining failure can be demonstrated.

This withdrawal does not establish that the full native-completion workflow is fixed. Issue #167410 remains open, and the contribution branch and historical evidence are preserved for a future evidence-backed repair. No branch deletion or history rewrite is involved.

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

Labels

gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S 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.

[Bug]: Native Codex completion inherits an aborted run scope and fails before parent admission

3 participants