Skip to content

fix(codex): await app-server cleanup when startup rejects - #157229

Merged
steipete merged 2 commits into
mainfrom
upd/codex-app-server-reap-on-secretref-failure
Sep 24, 2026
Merged

steipete merged 2 commits into
mainfrom
upd/codex-app-server-reap-on-secretref-failure

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Refs #157107. Thanks @mmartoccia for the report.

What Problem This Solves

Fixes Codex startup failures returning before their app-server child has exited. The reporter observed 47 orphaned app-server processes in 30 minutes while an authored provider API-key SecretRef pointed to an unset environment variable.

User Impact

Failed, canceled, and timed-out startup now waits for its spawned transport to finish cleanup. A healthy shared caller keeps its client. Cleanup can extend beyond the startup deadline while process registration settles. No configuration, dependency, schema, or migration changes are required.

Why This Change Was Made

createStdioTransport() spawns the child at extensions/codex/src/app-server/transport-stdio.ts:169. In shared-client.ts, failed initialization/authentication and late transport creation scheduled closeAndWait() without awaiting it; the final abandoned shared claimant also retired the child through the non-awaited close() path.

The existing shared-client lifecycle now records the transport-creation promise and joins physical cleanup before returning the failure. Work that has not begun transport creation remains independently cancellable. Spawn ownership stays in createStdioTransport; cleanup ownership stays in shared-client / shared-client-lifecycle. The ordering change is failure-after-cleanup; secret resolution and provider retry policy are unchanged. The exact SecretRef trigger remains the reporter's observed reproduction; the regression independently reproduces and fixes the same early-rejection lifecycle defect.

Sibling inspection found no equivalent leak: Claude CLI prepares credentials before spawning and awaits transport exit in finally; ACPX catalog inspection receives its generation's AbortSignal, and its runtime closes and awaits the helper during abort/disposal.

The sibling Codex source was personally inspected at commit 41e22fee981a63b3698df7ed36bad393cda24715: codex-rs/app-server-transport/src/transport/stdio.rs:71–80 turns stdin EOF into connection closure; codex-rs/app-server/src/lib.rs:1036 exits the stdio connection loop, and :1187 awaits thread shutdown. OpenClaw retains its existing bounded force-kill fallback.

Evidence

  • The eight lifecycle cases fail on the original production code because acquisition settles while a fixture child remains live. Shared and isolated cases cover validation failure, abort, timeout, and late transport creation; repeated attempts assert the fixture process registry is empty after cleanup.
  • Final focused suite: 132 tests passed three times with pnpm test extensions/codex/src/app-server/shared-client.test.ts --maxWorkers=1. Wall times: 22.26 / 21.62 / 20.26 seconds; test execution accounts for about 2–2.5 seconds per run, with most time in transformation/imports.
  • Two existing fake-clock fixtures now emit their process-exit event explicitly before awaiting rejection. Their initial 120-second stalls were fixture ordering errors exposed by awaited cleanup; deadlines were not raised. An initial wait on all startup work was narrowed to the transport promise to preserve pre-spawn cancellation.
  • Dependent suites: 55 files / 1,793 tests passed in 473.40 seconds wall time; five opt-in live files were excluded by the regular runner. pnpm check:changed --base ba65d492cf3e3dd8e49999b30133c09684eaf7ea passed on the exact committed head, including extension/test typechecks, dead-code scans, extension lint, and runtime import cycles. Its initial unused import and obsolete export findings were fixed.
  • Independent pre-commit Codex review: scoped-clean through P2. Required --mode branch --base origin/main review: scoped-clean through P2 on 1451edb1ac1a4a4f52dd7f83f284fa8b11380fe4.
  • Proof environments: Blacksmith Testbox tbx_01m39edvjwj8t2seepv6qj2vg3 for tests (provisioning run); tbx_01m39gbz7bgct6h22291g7k3n8 for final checks (exact-commit provisioning run). Proof results come from remote command exit status; stopping a lease can cancel its provisioning workflow.
  • Diff accounting, including moved lifecycle/test code: production +50/−27; tests +117/−27; docs +6. No live credentials or operator Gateway state were used. PR CI timings are pending.

@clawsweeper

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

@steipete
steipete marked this pull request as ready for review September 24, 2026 11:05
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: codex size: M labels Sep 24, 2026
@steipete
steipete enabled auto-merge (squash) September 24, 2026 11:12
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 24, 2026
@clawsweeper

clawsweeper Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 24, 2026, 8:43 AM ET / 12:43 UTC (Revision 2).

ClawSweeper review

What this changes

The Codex plugin waits for app-server child cleanup before failed shared or isolated startup returns, with lifecycle tests and updated runtime documentation.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this PR open. Current main still has the reported early-return cleanup path, but the proposed fix can leave a timed-out or canceled startup pending indefinitely when child-process registration stalls.

Priority: P1
Reviewed head: a77f5a99d9564bf2d70190a040aea8537caf36ce

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The repair has useful focused coverage, but the unresolved post-spawn stall prevents a correctness-ready verdict.
Proof confidence 🌊 off-meta tidepool Not applicable: The member-authored internal reliability PR is exempt from the external contributor proof gate. Its reported remote tests use mocked client starts and do not cover a production registration write that stays pending; no stored-data contract changes.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The member-authored internal reliability PR is exempt from the external contributor proof gate. Its reported remote tests use mocked client starts and do not cover a production registration write that stays pending; no stored-data contract changes.
Evidence reviewed 10 items Introduced blocking wait: The PR changes failed transport startup from scheduled cleanup to awaiting the startup promise and cleanup before rethrowing.
Registration can remain pending: After spawn, transport creation awaits registration; registration awaits the plugin-state store write without a deadline at that call site. The inspection deadline does not bound that write.
Production startup boundary: The app-server child is spawned before registration completes, and the client-start promise does not resolve until transport creation returns.
Findings 1 actionable finding [P2] Let startup cancellation settle if registration stalls
Security None None.

How this fits together

The Codex plugin starts an app-server child for agent runs and records its process identity before handing out a client. Failed acquisition should close the child and return an error to the waiting agent run.

flowchart LR
 A[Agent run] --> B[Codex client acquisition]
 B --> C[Spawn app-server child]
 C --> D[Register child process]
 D --> E{Startup succeeds?}
 E -->|Yes| F[Ready client]
 E -->|No| G[Close child and report error]
Loading

Before merge

  • Let startup cancellation settle if registration stalls (P2) - After spawn, CodexAppServerClient.start() waits for the process-registration store write. If that write remains pending past timeout or abort, this new await waits for starting forever, so the caller cannot receive its error and cleanup cannot close the child. Preserve custody of late registration while letting cancellation settle after child exit.
  • Resolve merge risk (P2) - If the process-registration write remains pending after spawn, a timeout or abort cannot finish the new cleanup await; the caller remains pending and the child may remain live.
  • Complete next step (P2) - Repair post-spawn registration stalls so timeout and abort return after child exit, and add a regression that holds the registration write pending.

Findings

  • [P2] Let startup cancellation settle if registration stalls — extensions/codex/src/app-server/shared-client.ts:1052-1058
Agent review details

Security

None.

PR surface

Source +23, Tests +90, Docs +6. Total +119 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 2 50 27 +23
Tests 2 117 27 +90
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 173 54 +119

Review metrics

Metric Value Why it matters
Production versus test growth production +23 net; tests +90 net The production growth centralizes cleanup, while the added tests do not exercise the pending registration write.

Merge-risk options

Maintainer options:

  1. Settle cancellation despite a stalled write (recommended)
    Close the spawned child without awaiting an unbounded registration write, retain ownership of late write cleanup, and cover that exact fault before merge.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Keep process custody and eventual registration cleanup, but make post-spawn abort and timeout settle after child exit even when the registration store write remains pending; add a focused production-boundary regression.

Technical review

Best possible solution:

Keep child custody with the transport owner after abort, close the spawned process promptly, and let the caller settle after process exit while a service-owned task completes any late registration cleanup.

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

Yes, at source level: hold the post-spawn registration write pending, then abort or expire acquisition. This read-only review did not execute that fault.

Is this the best way to solve the issue?

No. Joining physical cleanup addresses the orphan symptom, but acquisition must not await the unbounded registration write after its deadline.

Full review comments:

  • [P2] Let startup cancellation settle if registration stalls — extensions/codex/src/app-server/shared-client.ts:1052-1058
    After spawn, CodexAppServerClient.start() waits for the process-registration store write. If that write remains pending past timeout or abort, this new await waits for starting forever, so the caller cannot receive its error and cleanup cannot close the child. Preserve custody of late registration while letting cancellation settle after child exit.
    Confidence: 0.94

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Failed Codex startup can leave agent acquisition pending and app-server children live for affected users.
  • merge-risk: 🚨 availability: The introduced cleanup await can prevent timeout or cancellation from returning when process registration stalls.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The member-authored internal reliability PR is exempt from the external contributor proof gate. Its reported remote tests use mocked client starts and do not cover a production registration write that stays pending; no stored-data contract changes.

Evidence

Acceptance criteria:

  • [P1] pnpm test extensions/codex/src/app-server/shared-client.test.ts --maxWorkers=1.
  • [P1] pnpm test extensions/codex/src/app-server/transport-process-registration.lifecycle.test.ts --maxWorkers=1.
  • [P1] pnpm check:changed --base ead3b2e.

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason (Json): Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Exercise a post-spawn registration write that remains pending beyond abort or timeout, and show the caller settles after child exit without losing custody of the eventual write cleanup.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-24T11:16:30.046Z sha 1451edb :: blocked before merge. :: [P2] Let startup cancellation settle if registration stalls

@steipete
steipete merged commit 890ab59 into main Sep 24, 2026
112 checks passed
@steipete
steipete deleted the upd/codex-app-server-reap-on-secretref-failure branch September 24, 2026 13:11
steipete added a commit that referenced this pull request Sep 24, 2026
Startup validation observes the catalog home through real filesystem I/O.
Advancing the fake clock cannot establish that stdin teardown has started,
so the shared and isolated cleanup checks could race that lookup.

Subscribe to the existing stdin close event before acquisition and await
it while retaining the separate assertion that acquisition stays pending
until the synthetic process exits. Preserve all eight lifecycle variants.

The original 23-file shard reproduced the premature assertion on main.
Validation: 20 standalone runs (132 tests each), three original-shard runs
(864 tests each), scoped lint/format, and independent review passed.
Fixes the fixture introduced in #157229.
@roboclaw-bot roboclaw-bot mentioned this pull request Sep 24, 2026
2 of 8 tasks
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 25, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 25, 2026
Startup validation observes the catalog home through real filesystem I/O.
Advancing the fake clock cannot establish that stdin teardown has started,
so the shared and isolated cleanup checks could race that lookup.

Subscribe to the existing stdin close event before acquisition and await
it while retaining the separate assertion that acquisition stays pending
until the synthetic process exits. Preserve all eight lifecycle variants.

The original 23-file shard reproduced the premature assertion on main.
Validation: 20 standalone runs (132 tests each), three original-shard runs
(864 tests each), scoped lint/format, and independent review passed.
Fixes the fixture introduced in openclaw#157229.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation extensions: codex merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant