Repository navigation
fix(codex): reap orphaned app-servers before reconnect - #132610
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: needs maintainer review before merge. Reviewed August 29, 2026, 11:03 AM ET / 15:03 UTC. ClawSweeper reviewWhat this changesThe PR records POSIX Codex stdio app-server processes durably, reaps verified children left by a dead Gateway before reconnecting, and makes startup awaitable for deadline and authorization checks. Merge readinessKeep open for maintainer review: current main still lacks the orphan-registration/reaping path, and the PR is maintainer-labeled. No source-level defect was confirmed, but this reviewer could not perform the repository-required direct sibling Codex source check. Priority: P1 Review scores
Verification
How this fits togetherThe Codex plugin launches an app-server subprocess for native work. The new startup path reads prior process registrations, removes a verified orphan when its Gateway parent is gone, then persists the replacement process identity before Codex initialization. flowchart LR
A[Gateway requests Codex work] --> B[Codex stdio startup]
B --> C[Process registration store]
C --> D[Inspect prior Gateway owner]
D -->|dead and identity verified| E[Reap orphan process tree]
D -->|live or uncertain| F[Skip or fail visibly]
E --> G[Spawn and register app-server]
G --> H[Codex initialize and native work]
Decision needed
Why: The PR directly launches and drives the Codex app-server, and repository policy requires direct sibling-source inspection before a Codex verdict or proof-sufficient claim; that checkout is unavailable here. Before merge
Agent review detailsSecurityNone. PR surfaceSource +406, Tests +289, Docs +33. Total +728 across 22 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Retain the owner-plugin registration design if a Codex-area maintainer confirms the direct upstream initialization and shutdown contract, then merge only after the normal exact-head CI gates are green. Do we have a high-confidence way to reproduce the issue? Yes, source-reproducible with high confidence: current main starts a detached POSIX stdio child without a durable registration or reconnect-time reaper, and the added crash test encodes the hard-kill/reconnect sequence. This reviewer did not execute that sequence. Is this the best way to solve the issue? Unclear: the repair is located at the spawn owner and reuses the existing containment owner, which is the right architectural boundary, but the required direct Codex runtime-contract inspection remains unavailable. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 3399dd67b7e8. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
b8ec3a6 to
d7aa5dc
Compare
|
The final head The PR body now includes the full local checks/build results, Alpine compatibility proof, direct upstream source references, and disposition of the previous review's rank-up request. The deliberate fail-closed cleanup is retained: no replacement child is started when an old registered child cannot be verified gone. Linux uses procfs and needs no procps package. No config or SQLite schema changes. Exact-head CI 33260972583 completed successfully with no failed jobs. Native review artifacts are validated and the PR is land-ready. A refreshed review was requested for the additional startup lifecycle correction. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
… boot The reaper landed in #132610 authorizes SIGKILL from pid+pgid+startedAt. On macOS, startedAt comes from ps lstart and is only second-granular, so a registered child that dies and has its pid recycled within the same second could hand its identity to an unrelated process that then gets killed (group-killed when it is a leader); Linux is already tick-granular with a boot id. Registration now also records the child's exact command line (/proc cmdline on Linux, ps -o command= elsewhere) and the reap loop compares it before entering containment: a mismatch deletes only the stale row, an unreadable command with a still-matching identity refuses the spawn fail-closed, and rows written by earlier unreleased builds keep identity-only reaping via an optional schema field. Verified against pinned codex 0.150.1 (rust-v0.150.1) that the app-server never retitles its argv. The regression "never kills a same-second replacement process running a different command" fails without the gate. Also registers a best-effort boot sweep service (codex-app-server-process-reaper) so orphans from a hard-killed gateway die at the next startup instead of waiting for the next codex spawn; the before-spawn fail-closed check remains authoritative. Docs updated. Follow-up to #132610 from #132621's review findings.
…nup until next use (#132745) * fix(codex): gate orphan reaper kills on command identity and sweep at boot The reaper landed in #132610 authorizes SIGKILL from pid+pgid+startedAt. On macOS, startedAt comes from ps lstart and is only second-granular, so a registered child that dies and has its pid recycled within the same second could hand its identity to an unrelated process that then gets killed (group-killed when it is a leader); Linux is already tick-granular with a boot id. Registration now also records the child's exact command line (/proc cmdline on Linux, ps -o command= elsewhere) and the reap loop compares it before entering containment: a mismatch deletes only the stale row, an unreadable command with a still-matching identity refuses the spawn fail-closed, and rows written by earlier unreleased builds keep identity-only reaping via an optional schema field. Verified against pinned codex 0.150.1 (rust-v0.150.1) that the app-server never retitles its argv. The regression "never kills a same-second replacement process running a different command" fails without the gate. Also registers a best-effort boot sweep service (codex-app-server-process-reaper) so orphans from a hard-killed gateway die at the next startup instead of waiting for the next codex spawn; the before-spawn fail-closed check remains authoritative. Docs updated. Follow-up to #132610 from #132621's review findings. * fix(codex): persist only a command fingerprint in reaper registrations appServer.args is operator-configurable and can carry secrets, and the spawn-identity precedent (argsFingerprint) deliberately hashes argv. Durable reaper rows now store a sha256 fingerprint of the observed command line instead of the raw string; the kill gate reads the live command fresh and compares digests, and the registration test asserts raw argv never reaches the durable store. Addresses the ClawSweeper P1 on #132745; the companion final-signal finding is refuted in the PR thread (identity monotonicity: a post-gate replacement cannot carry the registered start time, and containment revalidates identity before every signal).
* fix(codex): reap orphaned app-servers before reconnect * style(codex): avoid returning the containment timer handle * fix(codex): inspect Linux children without requiring procps * fix(codex): tolerate processes exiting during procfs reads * test(codex): normalize socket fixture binary frames * fix(codex): preserve startup errors during process registration
…nup until next use (openclaw#132745) * fix(codex): gate orphan reaper kills on command identity and sweep at boot The reaper landed in openclaw#132610 authorizes SIGKILL from pid+pgid+startedAt. On macOS, startedAt comes from ps lstart and is only second-granular, so a registered child that dies and has its pid recycled within the same second could hand its identity to an unrelated process that then gets killed (group-killed when it is a leader); Linux is already tick-granular with a boot id. Registration now also records the child's exact command line (/proc cmdline on Linux, ps -o command= elsewhere) and the reap loop compares it before entering containment: a mismatch deletes only the stale row, an unreadable command with a still-matching identity refuses the spawn fail-closed, and rows written by earlier unreleased builds keep identity-only reaping via an optional schema field. Verified against pinned codex 0.150.1 (rust-v0.150.1) that the app-server never retitles its argv. The regression "never kills a same-second replacement process running a different command" fails without the gate. Also registers a best-effort boot sweep service (codex-app-server-process-reaper) so orphans from a hard-killed gateway die at the next startup instead of waiting for the next codex spawn; the before-spawn fail-closed check remains authoritative. Docs updated. Follow-up to openclaw#132610 from openclaw#132621's review findings. * fix(codex): persist only a command fingerprint in reaper registrations appServer.args is operator-configurable and can carry secrets, and the spawn-identity precedent (argsFingerprint) deliberately hashes argv. Durable reaper rows now store a sha256 fingerprint of the observed command line instead of the raw string; the kill gate reads the live command fresh and compares digests, and the registration test asserts raw argv never reaches the durable store. Addresses the ClawSweeper P1 on openclaw#132745; the companion final-signal finding is refuted in the PR thread (identity monotonicity: a post-gate replacement cannot carry the registered start time, and containment revalidates identity before every signal).
Related: #132413 (bounded terminal settlement), follow-up 3.
What Problem This Solves
Fixes an issue where a hard-killed Gateway left its detached Codex app-server alive, allowing pre-restart native work to overlap a fresh connection against the same state. Graceful transport shutdown already contained descendants, but the next process had no durable spawn fact identifying the old child.
Why This Change Was Made
The stdio spawn owner now reaps registrations belonging to dead parents before creating a fresh child, and commits the new parent/child process identities to the existing state-directory-scoped SQLite plugin store before Codex initialization. It reuses the existing bounded process containment algorithm instead of adding command-name discovery or another supervisor; asynchronous startup retains acquisition deadlines, late-client disposal, and node exec authorization revalidation.
Registrations have unique keys, no expiry/eviction, and no schema change. Live parents are skipped. Start-time/PID/group checks reject reused or ambiguous identities; uncertain cleanup keeps the row and fails visibly. Normal exit removes the registration. WebSocket/Unix endpoints are externally owned and unaffected. The async client-start API is plugin-private.
User Impact
On POSIX, reconnecting after a hard Gateway stop cannot start another registered stdio child until the previous dead owner's app-server is confirmed gone. Healthy concurrent instances remain running. Recovery is automatic on connection, with no new configuration.
Limits: pre-upgrade unregistered children are not guessed from command names; Windows has no equivalent reaper in this change. The PID/start-time checks are not atomic OS handles and cannot recover independently reparented descendants outside the verified tree/group. A kill between spawn and registration can still leave an uninitialized child, but Codex rejects native requests before initialize. Linux reads kernel procfs identities (boot ID plus start ticks); macOS uses native
ps. Supported Alpine/BusyBox installs need no extra package.Evidence
32bd1602e54009287f24157f8a1776691f56f77e: after parent SIGKILL and a fresh same-state spawn, the old child was still alive. The repaired test removes the child and its independently detached descendant while preserving live same-state and separate-state controls.command/exec, SIGSTOP its app-server to prevent EOF cleanup, SIGKILL the OpenClaw parent, and reconnect. The old app-server and command are gone before the replacement reports ready. This is real native execution with isolated homes and no provider inference or saved credentials.psblocks startup without consuming the registration; retry with working inspection reaps it. Linux crash-recovery tests run with an intentionally failingpsto prove no dependency on procps. Stale start identity and process-group mismatch are covered separately from existing descendant PID-reuse/cleanup tests. An isolated acquisition deadline disposes a client returned late, and node authorization is rechecked after awaited setup.tbx_01m16sv1xtrxp72r7bkt0p6m10: 124 tests passed across crash recovery, shared client, stdio, WebSocket/Unix, and node exec policy. A later expanded rerun was blocked by missingtsxafter full sync and a frozen-lockfile dependency-bootstrap error; that lease was stopped. Final hosted checks will be recorded below.openai/codex@6478a751fde8884b2fdc76486fe23175a8e795d4:codex-rs/app-server/src/message_processor.rs:837-889(initialization gate),codex-rs/app-server-transport/src/transport/stdio.rs:24-78(EOF),codex-rs/app-server/src/lib.rs:1015-1035,1176-1186(connection shutdown/drain), andcodex-rs/app-server-protocol/src/protocol/v2/command_exec.rs:24-109(native command proof).The inspected shallow baseline already contains detached spawning; the exact original introduction was not established. This repairs the explicitly named follow-up, without changing terminal settlement or native rollout recovery policy.
Production LOC: +436/-113 (net +323); tests and test support: +857/-442; docs: +33. These totals include the platform inspector extraction; pure moves do not contribute to the net. Growth supplies the previously missing durable spawn ownership, first-connect reaping, and bounded asynchronous startup. Existing descendant containment is reused and the former synchronous spawn path is replaced; there is no second supervisor, compatibility fallback, or new database schema.
Final local sibling proof:
node scripts/run-vitest.mjsovertransport.process.test.ts,shared-client.test.ts,attempt-startup.test.ts,models.test.ts,run-attempt-thread-cleanup.test.ts, andthread-lifecycle.binding.test.ts: 293 passed, including the new stale-root-identity and group-drift cases. The final macOS native hard-kill probe also passed after the fixture reused isolated native setup and disabled unrelated native proxy/snapshot discovery.Linux proof ran on Blacksmith Testbox workflow 33254010522; the wrapper's successful command exit/timing JSON is the proof result (the lease was subsequently stopped).
Local gates: full
pnpm buildpassed.node scripts/check-changed.mjspassed all formatting, typechecking, boundary, dead-code and policy gates; its final lint batch caught an implicit Promise-executor return, corrected without a behavior change. The full affected lint batch then passed, as did the four process-containment tests and a fresh Codex autoreview of that correction.Review corrections and final proof
ClawSweeper correctly identified a supported-platform compatibility problem: stable
v2026.7.1already recommendsnode:24-alpine, whose BusyBoxpslackslstart. The fix now uses one canonical Linux procfs inspector; macOS retains nativeps. This removes the new Linux system-package prerequisite without silently skipping registration or allowing overlapping old work. The kernel documents process stat fields and boot identity.Alpine before/after proof used a minimal
node:26-alpineDocker container (Node 26.8.1, no added procps, no network during the probe). The previous PR head fails at registration with “Cannot register the Codex child process.” The corrected registration/containment and real SQLite store, bundled from source for this environment probe, survive the exact sequence: spawn/register; SIGKILL parent; prove old tree alive; reconnect; prove old root and detached descendant gone while live same-state and separate-state controls remain. This is a real subprocess/store probe, not a packaged-install or provider-inference claim.The first hosted CI run 33255824607 passed all 17 changed-plugin shards but exposed a stale catalog test mock lacking PID/spawn lifecycle. That test now uses the supported user-home Unix socket transport and retains catalog, account-change, route-isolation and disconnect assertions. The generated fake-ps fault driver was replaced by tests at the shared inspection boundary, retaining real signals and all nine fault scenarios; dedicated native-ps tests preserve inspector timeout/leak coverage.
Final combined macOS proof:
node scripts/run-vitest.mjs extensions/codex/src/app-server/transport.process.test.ts extensions/codex/src/app-server/transport-process-snapshot.test.ts extensions/codex/src/app-server/transport-orphan.test.ts test/plugins/codex-model-catalog.gateway.test.ts— 17 tests passed across 4 files, including real native crash/reconnect. Fresh Codex autoreview of the complete correction found no actionable issue at its P0 threshold.Rank-up disposition: the POSIX prerequisite finding is repaired and demonstrated on the affected Alpine environment. The upstream initialization-gate source was personally inspected and is directly available at message_processor.rs:880-889. The review worker's unavailable checkout was an access gap; no initialization assumption substitutes for this source proof. The flagged serialized-state file is a test subprocess fixture; runtime records use the existing plugin KV schema.
The procfs adapter also distinguishes
ESRCH/ENOENT(a process exited during inspection) fromEACCES(inspection failed). An Alpine injected-read reproduction failed before theESRCHcorrection; all three outcomes pass afterward, and Linux-only regression cases cover the documented kernel contract plus command names containing spaces and closing parentheses. The correction received a fresh clean Codex autoreview.Final builds passed: full
pnpm buildand the canonicalnode --import ./scripts/tsx.mjs scripts/build-all.mts gatewayWatchruntime refresh. Root-test typechecking then caught an ArrayBuffer overload in the socket fixture; the test now converts that variant through Uint8Array, matching the WebSocket binary contract. The corrected root-test typecheck, focused catalog/inspector rerun, and fresh Codex autoreview passed.Final startup-order correction: hosted CI exposed a child that exited with a retryable SQLite failure while registration was still inspecting processes. Attaching the JSON-RPC client only afterward lost its stderr/exit event and masked the failure as registration error. The client now observes lifecycle events immediately after spawn, while initialization still waits for durable registration. A forced-order real-child regression failed before the fix; the final startup/shared-client/stdio run passed 111 tests without changing timeouts. Extension-test types, focused lint and Codex autoreview passed. Two intermediate local stress reruns timed out on this heavily loaded host; the clean full rerun passed, and no timeout was increased.
The unrelated shared-worker benchmark failure came from a preceding async-task fixture retaining a running task. The branch was rebased once to absorb its existing owner cleanup in #132643; no duplicate workaround was added. After rebase, 17 async-task/benchmark tests and both real native/fixture crash-recovery tests passed. Full local changed-file checks passed; the small startup correction additionally passed focused types/lint. Current head:
d7aa5dc488657caed44d8da2e8de0a67c290be3a; exact-head CI33260972583 passed with no failed jobs.Latest ClawSweeper disposition: the refreshed review has no concrete source finding. Its missing sibling checkout is covered by the personally inspected upstream initialization/EOF/drain source cited above. The deliberate fail-closed behavior is retained: when an old registered owner cannot be inspected or confirmed gone, spawning overlapping native work would violate this repair. Linux procfs removes the supported-Alpine prerequisite issue. The flagged serialization in the snapshot adapter is kernel process identity, and the helper is a test fixture; neither changes the SQLite schema.
Final focused command:
node scripts/run-vitest.mjs extensions/codex/src/app-server/attempt-startup-retry.test.ts extensions/codex/src/app-server/shared-client.test.ts extensions/codex/src/app-server/transport-stdio.test.ts— 111 passed. Rebase sanity command:node scripts/run-vitest.mjs extensions/codex/src/app-server/transport-orphan.test.ts src/agents/embedded-agent-runner/run/attempt.async-tasks.test.ts test/scripts/bench-agent-concurrency.test.ts— 19 passed, including both real fixture/native crash-recovery cases. Exact-head CI completed successfully.