Repository navigation
feat(exec): keep durable session processes across Gateway restarts - #188465
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
|
Codex review: needs real behavior proof before merge. What this changesThis PR adds opt-in Linux systemd execution that retains background-process handles, output, and completion handling across Gateway restarts. Example: A session launches npm run build with background:true,durable:true on Linux with systemd 252.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 9 items remain Keep open: this maintainer-directed feature has clear value, but restart bookkeeping, launch and stop authority, and a diff-caused startup-test failure need correction. Priority: P2 Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherThe exec pipeline prepares and authorizes commands, the process registry owns their lifecycle, systemd hosts durable process trees, and shared-state workers persist restart facts for later observation and session completion. flowchart TD
A[Session exec request] --> B[Exec policy and approval]
B --> C[Process registry]
C --> D[Systemd user unit]
C --> E[Shared state worker]
E --> F[Restart adoption]
F --> C
D --> G[Output and terminal status]
G --> C
C --> H[Process controls and session completion]
Technical reviewBest possible solution: Keep the existing registry and shared-state owners, preserve final launch and stop authorization, and distinguish surviving durable work in restart snapshots. Do we have a high-confidence way to reproduce the issue? Source establishes the ordinary restart limitation and the introduced integration failures; exact-head CI independently confirms the startup-fixture mismatch, but this review ran no target code. Is this the best way to solve the issue? Using systemd behind the existing registry is coherent, but the cutover must include restart snapshots and preserve authorization through the new asynchronous launch and stop paths. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 54def34074cc. Provenance checked
TestingProof path: shipped entry point. SecurityNeeds attention: The new asynchronous execution paths leave gaps in final script-binding checks and RPC stop authorization. EvidenceSecurity concerns:
What I checked:
Likely related people:
PR surfaceSource +1037, Tests +774, Docs +133, Other +13. Total +1957 across 48 files. Added test files: 6. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 30, 2026, 12:02 PM ET / 16:02 UTC. |
Select sidecar cleanup owners without depending on Linux publication order, keep durable persistence outside the worker-free startup fixture, and wait for the readiness owner. Exercise the Linux branch on every host. All 77 startup tests pass after reproducing the ownership failure, targeted checks pass, and final P2 autoreview is scoped-clean. The separate tool-cancelled delegation assertion fails identically on main at 6a550b0.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 073bb5c448
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| finalize: () => | ||
| enqueue(async () => { | ||
| record.notificationSettled = true; | ||
| await persistence.upsert(record); |
There was a problem hiding this comment.
Retire durable state after removing a running process
When process remove targets a running durable process, the process tool sets backgrounded = false and removes its visible registry entry. On exit, moveToFinished consequently skips finished-session retention, but this finalizer still persists the durable record. Since durable.remove() is only called when a finished registry entry is deleted, the SQLite row and log never expire during the current Gateway lifetime, and the removed process reappears if the Gateway restarts before its retention deadline. Retire the durable record and log after a hidden process finishes settling instead of relying exclusively on finished-session eviction.
Useful? React with 👍 / 👎.
The optional durable process table raises the complete state-port inventory from 135 to 136 tables. Preserve the existing round-trip, exact and sanitized backup, optional-fragment, and schema-drift coverage. Reproduced the count failure against isolated PostgreSQL 17, then passed both state-port tests in 66.07 seconds. Scoped lint/format and independent P2 autoreview pass.
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…penclaw#188465) * feat(exec): add durable session background processes * docs(exec): state durable unit environment exposure * test(gateway): isolate durable startup lifecycle fixtures Select sidecar cleanup owners without depending on Linux publication order, keep durable persistence outside the worker-free startup fixture, and wait for the readiness owner. Exercise the Linux branch on every host. All 77 startup tests pass after reproducing the ownership failure, targeted checks pass, and final P2 autoreview is scoped-clean. The separate tool-cancelled delegation assertion fails identically on main at f5d6eb2. * test(state): include durable processes in PostgreSQL inventory The optional durable process table raises the complete state-port inventory from 135 to 136 tables. Preserve the existing round-trip, exact and sanitized backup, optional-fragment, and schema-drift coverage. Reproduced the count failure against isolated PostgreSQL 17, then passed both state-port tests in 66.07 seconds. Scoped lint/format and independent P2 autoreview pass.
What Problem This Solves
Long-running session commands end when the Gateway restarts, so durable work currently needs an external launcher and loses the session's process controls and completion wake.
User Impact
execcan opt intodurable: truewithbackground: trueoryieldMson Gateway-host Linux with a reachable systemd user manager, version 250 or newer. The session retains list/poll/log/kill controls after a Gateway restart. Durable work does not block cooperative suspension or safe restart. Unsupported hosts refuse instead of falling back.Durable processes have no interactive input. Raw append-only logs consume disk until process retention removes them; operators must provision disk space. Direct managed GitHub credentials are captured at launch and are not refreshed, so long jobs can outlive their tokens. Secret-egress proxy grants are refused because their lifetime belongs to the Gateway.
Why This Change Was Made
The existing background-process registry remains the owner. It launches an opaque transient user unit outside the Gateway cgroup, using
ExitType=cgroup,RemainAfterExit=yes,KillMode=control-group,RuntimeMaxSec, and the ordinary exec memory bound asMemoryMax. Command policy, approval, cwd, environment preparation, and final launch authority stay on the ordinary exec path. Infrastructure executables resolve from Gateway PATH; credential values are passed through the prepared environment rather than command arguments.The shared-state worker creates one optional
durable_background_processestable on first write (id,record_json); Kysely and existing schema admission own it. No schema-version bump is needed. Reads do not create storage. The record contains registry/restart facts, a generic command summary, and final status; it contains no environment values, output, or requester continuation. PostgreSQL-generated schema artifacts and the update contract are updated too.Startup restores registry entries, then the existing observation cadence reconciles units. Real terminal status is persisted before unit cleanup, and final output is drained after checking exit. Post-restart completion is fresh session input under the session principal's current authority, with notification and session eligibility rechecked. Live requester completion behavior stays unchanged.
The simplification consolidated persistence into one module and removed the global pending/finalizer maps, duplicate settlement paths, and separate runtime notification flags. Production is +1,014/-60 lines (net +954); tests are +841/-55 (net +786). This is about 25% smaller than the previous +1,277 production delta, but does not meet the requested well-under-half target. Generated schema churn is separate (+375/-281).
Evidence
Base public-launch regression:
node scripts/run-vitest.mjs src/agents/bash-process-durable-base-launch.test.ts --maxWorkers=1in an isolated base checkout with a temporary native fixture. It reached the real exec entry point and failed because a running handle was returned without creating the external unit. Supervisor cleanup completed; this was not a setup failure.Green:
node scripts/run-vitest.mjs src/agents/bash-process-durable.test.ts src/agents/bash-durable-process-store.test.ts --maxWorkers=1passed after the final fixes. The wider run passed 237 tests across 16 scoped files, covering exec policy/approvals, registry/observation, requester notifications, prefix stability, schemas, and migration contracts. The launch/adoption and persistence proofs run through native main-thread host-broker fixtures; only the external manager is synthetic. The final focused rerun also covers output written during the terminal status check and startup without synchronous unit queries.Published upgrade: installed
[email protected], created its real schema-20 database, ran candidatedoctor --non-interactive --fixin isolated state with external service-repair policy, and verified schema 36 plus both Doctor backups withquick_check. The same native store fixture passed over a verified copy of that upgraded database, including first-use table creation, preserved metadata, worker-only SQL, and close/reopen.pnpm tsgo; scoped lint and format; baseline, database-worker/dialect, assertion, line-cap, test-line, timeout, and mock-export ratchets; generated Kysely/PostgreSQL verification;git diff --checkpassed. Codex autoreview finished scoped-clean through P2 after fixing final-output ordering and startup reconciliation latency.Unused-file inventory: production scan passed with zero entries. The full-tree scan reports five unchanged performance scripts; none of this PR's files appear.
Local real-systemd proof (partial, source
291b281081e0): OrbStack Docker with cgroup v2, privileged container built fromnode:24-bookworm-slim(Debian 12), systemd 252.39 as PID 1, unprivileged UID 1001 with lingering and a reachable real user manager. Copied source, container-localpnpm install --frozen-lockfile(pnpm 12.15.0, Node 24.22.2), and the repositoryqaRuntimebuild passed. A real isolated Gateway plus a scripted loopback Responses provider launchedexecwithbackground:true,durable:true; the command and child ran in a transient user-unit cgroup outside the Gateway cgroup, andsessions.processes.listfound the running handle.Stopped proof requirement: the owning
sessions.listrow had no background-process count (status: done,hasActiveRun: falsewhile the unit was running), confirming the separate session-count integration gap already noted below. The harness stopped at that failed requirement; SIGTERM/SIGKILL restart-and-adoption, process-tool tree kill, downtime-exit/completion deduplication, and both refusal scenarios were not executed. No runtime code was changed. Descendant timeout and memory-limit live proof also remain unexecuted.Environment exposure PASS: a unique synthetic value injected through
secrets store set ... --kind envwas absent fromdurable_background_processes.record_json(false) and Gateway/process logs, including the persisted Gateway log (false), and present insystemctl --user show <unit> -p Environment(true) and the transient unit file under$XDG_RUNTIME_DIR/systemd/transient/(true, tmpfs). Unit-property exposure is readable by the same Unix user and is now stated indocs/tools/exec.md. The non-persistence statement is scoped to durable bookkeeping: the shared secret store intentionally stores env entries in SQLite, and commands may explicitly print or persist them.Docs follow-up:
docs(exec): state durable unit environment exposure(34c9db137824). Targeted formatter and MDX validation,git diff --check, and Codex autoreview through P2 passed. No CI reruns or merge requested. Gateway and synthetic unit/container cleanup completed; manual systemctl cleanup is not process-tool kill proof.Landing CI repair (
073bb5c44821): Linux startup added an earlier lifetime sidecar, exposing positional cleanup-handle assumptions and an unisolated durable persistence import in the worker-free fixture. The existing update-check ownership case reproduced red locally with Linux selected. Select handles by identity/name, isolate the durable worker owner, await actual readiness, and exercise the Linux branch on every host. Extract the unchanged trace recorder into a sibling helper to satisfy the line-cap ratchet. All 77 startup tests pass (12.31s wall); targeted gateway test types, scoped lint/format, whitespace checks, commit hooks, and independent Codex autoreview through P2 pass. This fixture repair adds 12 net test lines, covered by its allocation.Baseline CI failure on final head (
e484c8e36a7e): run41090351803attempt 1, job124183102346,src/gateway/tool-resolution.test.ts > Gateway-built tool final effects > fences workspace-restricted persistent Gateway delegation: tool-cancelledexpects a retainedcancelledsnapshot but receivesundefinedattool-resolution.effects.test-support.ts:253. It reproduces identically on the PR and isolated main6a550b0a7ce01364035fbea8a60c0c7bc4d2a7d6(same assertion/stack). The baseline command wasnode scripts/run-vitest.mjs src/gateway/tool-resolution.test.ts --maxWorkers=1 -t 'fences workspace-restricted persistent Gateway delegation'(109.14s wall; one failed, three passed). No CI reruns were requested; this failure remains recorded, not relabeled green. The final attempt completed with 99 terminal jobs; all three PostgreSQL shards andsecurity-fastpassed. The aggregate classifier reportsunknownbecause scheduled main has no matching job. Independent reproduction on main and seven identical relevant test/owner Git objects across that main, CI baseline, and tested PR merge establish the unrelated-failure attribution. Native auto-merge was armed and then retired through the supported recovery owner before selecting the documented pre-existing-failure route.PostgreSQL CI repair (
e484c8e36a7e): prior-head run41086438511, job124170316671, exposed the complete-inventory expectation of 135 tables after this PR adds the 136th table. The same test failed locally against isolated PostgreSQL 17 with 135 versus 136 before the fix. Updated only that fixed count; bothstate-port.postgres.test.tstests then passed through the real PostgreSQL conformance entrypoint (66.07s wall), retaining complete round-trip, exact/sanitized backup, optional-fragment, and schema-drift coverage. Scoped lint/format, commit hooks, and independent P2 autoreview passed. The other two PostgreSQL CI shards passed. The synthetic local container was removed. No CI reruns requested.No sidebar UI changes or deployment are included. The parallel session-count projection has not landed on the checked main revision. Rollback to a binary without this feature requires inspecting/stopping retained user units through systemd; existing database-version rollback rules still apply.