Skip to content

fix: shorten Gateway restart when active commands need cleanup - #197457

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-shutdown-supervisor-reap-blocks-db-seal-20260919
Nov 12, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-shutdown-supervisor-reap-blocks-db-seal-20260919

Conversation

@steipete

@steipete steipete commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Gateway restart can wait an extra child-cancellation grace after draining an active turn that has yielded an ordinary exec command.

User Impact

Active requests signal their ordinary commands as soon as restart interrupts the turn. The existing five-second child grace, physical cleanup, accepted finalizer writes, and restart recovery remain intact. Independent services and idle commands without a live request turn retain their existing owners. No configuration or schema changes.

Why This Change Was Made

Request custody forwarded explicit Stop but filtered out the typed restart-abort reason. A yielded command therefore missed cancellation and survived until the late process-supervisor join immediately before agent-database retirement. Forward restart interruption through the same owner so child cleanup overlaps the other accepted work. Keep leases through finalization and retain the late supervisor/database ordering; closing the entire supervisor earlier would also reject cleanup commands.

A seal arriving immediately after supervisor shutdown establishes ordering, not which process held a lease. The change makes no claim that ordinary exec children themselves open agent databases. Likewise, two pipe/socket handles may be Gateway stdout/stderr; a child TLS connection cannot appear in the Gateway handle inventory. The existing detailed exit diagnostics remain the attribution path.

Production confirmation requires the handoff after deployment carrying this fix, because the outgoing Gateway executes shutdown.

Evidence

Acceptance: a real supervised child ignores SIGTERM, a request has 2.2 seconds of independent accepted work, its exec finalizer retains a native database borrow and writes before close. Five serial interleaved baseline/candidate pairs must reduce median/p95 shutdown while preserving every finalizer write, physical child cleanup and written clean-close receipt. Separate allocation samples and identical-source A/A controls are reported separately.

Owner measurement Before After
Shutdown/seal median 7,253.16 ms 5,046.86 ms
p95 (five samples, nearest rank) 7,279.26 ms 5,053.49 ms
Child SIGTERM median 2,203 ms 1 ms
Late supervisor wait median 5,020.27 ms 0.065 ms
Finalizer write median 7,222.88 ms 5,018.62 ms
Written receipt median 7,249 ms 5,043 ms
Host CPU median 38.398 ms 39.599 ms
Separate sampled allocation 5,290,864 B 5,614,144 B

All ten paired runs preserved the write and seal. CPU is neutral within observed spread; the single allocation sample increased 6.11%, so no allocation improvement is claimed. Identical-source direct-Stop A/A controls sealed in 5,064.10/5,111.38 ms (0.93% spread); the baseline/candidate direct-Stop negative control was 5,055.98/5,040.77 ms. These are owner-level macOS measurements with one database, not whole-Gateway/btrfs attribution.

Commands:

node --import ./scripts/tsx.mjs scripts/perf/exec-restart-shutdown-measure.ts --state-dir /absolute/new-fixture
# Baseline: add --source /saved/exec-request-context.ts; controls: --control; allocation: --allocation.
node scripts/run-vitest.mjs src/agents/bash-tools.exec.background-abort.test.ts src/agents/bash-tools.exec-runtime.cleanup.test.ts --maxWorkers=1

The restart row fails on the original implementation ([] cancellation instead of the command ID); all 27 focused tests pass with the fix. Test wrapper wall time: 51.61 seconds including cold worker compilation; behavior-test time was about two seconds. The existing table gained four lines, recorded in its own allocation file. Production runtime delta is +6 lines for the imported typed predicate and condition; no new state, API, timeout, cache, or owner.

The built Gateway also passed a local scale/recovery run using a synthetic 37,694,242,816-byte database with 5,000 seeded sessions and a 62,000-file / 1,100,004,000-byte workspace. A real yielded child ignored SIGTERM. Shutdown took 5,680.72 ms; the late supervisor join took 0.2 ms; the actual Gateway published written, exited cleanly, left no child alive, and resumed both interrupted runs exactly once with durable replies and tool receipts. Offline full integrity verification of each copied destination precedes startup, outside timing, to model an already verified long-lived database. Two serial full Linux/btrfs A/B pairs passed. This synthetic database has compressible padding; it models logical scale and ownership, not production disk saturation.

Full Gateway, Linux/btrfs Before After
SIGTERM → exit, pair 1 7,470.85 ms 5,361.36 ms
SIGTERM → exit, pair 2 7,526.71 ms 5,504.24 ms
Median 7,498.78 ms 5,432.80 ms
Late supervisor join, median 5,026.35 ms 0.20 ms
Main-thread CPU, median 559.59 ms 518.20 ms
Separate sampled main-heap allocation 54,553,760 B 54,375,872 B

The median reduction is 2,065.98 ms (27.55%). Identical baseline A/A controls were 7,668.13 / 7,686.98 ms (18.85 ms, 0.246% spread). Separate allocation/CPU-profile samples were excluded from those timing statistics; their CPU was 696.00 / 650.31 ms. CPU excludes workers/children, and two timing pairs plus one allocation sample per arm do not establish a robust CPU or allocation improvement.

All eight Linux runs published written, exited cleanly with no surviving child, retained the seeded session scale, and resumed both interrupted runs exactly once with durable replies. In the first pair, supervisor completion moved from +7,273.5 to +5,154.4 ms after the received-SIGTERM trace, and agent-database close finished at +7,277.8 / +5,158.7 ms. The actual written receipt is asserted inside that close phase; merged stdout/stderr does not support a finer receipt timestamp. Every initial-exit resource sample contained only three pipes, with no TCP socket, timer, or exit-margin diagnostic; this does not identify the production TLS client.

Reproduce each full-Gateway arm with its independently built revision and a fresh output directory:

TMPDIR=/absolute/btrfs-temp node --import ./scripts/tsx.mjs scripts/perf/shutdown-loaded-measure.ts \
  --output /absolute/new-output --fixture /absolute/synthetic-fixture \
  --sessions 1 --crons 1 --tools 1 --clients 1 --yield-tools --ignore-term --hold-ms 2200

pnpm check:changed, the full pnpm build:ci-artifacts, final script typecheck/lint and git diff --check passed. Codex autoreview of the complete local change against e0dd0206412af448b324387435dd8fed6575fd7b at P0–P2 found no actionable findings. Hosted Codex review completed without findings and exact-head CI is green. No UI-imported production module changed.

Forward typed restart interruption through active request custody so yielded exec commands begin their existing graceful cancellation while other accepted work drains. Keep physical process settlement, finalizer writes, database sealing, and restart recovery ordered.
@clawsweeper

clawsweeper Bot commented Nov 12, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T01:51:20.958257Z c22e6a5 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 12, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR starts request-owned command cleanup when restart interrupts an active turn, allowing cleanup to overlap request draining.

Example: A yielded command ignores SIGTERM while its request has 2.2 seconds of other accepted work.

  • Before: Reported owner measurements start child cancellation after that work and seal the database at a median 7,253 ms.
  • After: Cancellation starts immediately, with a reported median seal time of 5,047 ms and finalizer writes preserved.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is narrow and source-supported; supplied runtime evidence supports the direction with limited independent inspectability.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; its body reports real supervised-child measurements and built-Gateway shutdown/recovery on macOS and Linux, but supplies result summaries rather than linked raw logs, and additional loaded controls remain pending.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Restart can incur a second cleanup wait because a yielded command misses the active request's restart interruption.
Reason: The maintainer-authored direction removes measured latency with a narrow owner-level change and preserves existing lifecycle contracts.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current restart delay through the existing cancellation owner, and review found no actionable introduced defect.

Priority: P2
Reviewed head: c22e6a546e9498fda20c70f2dcd96211c96393fe

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway shutdown records restart markers and interrupts active requests; request custody forwards cancellation to supervised commands, whose physical cleanup and finalizers settle before database retirement.

flowchart TD
A[Gateway shutdown] --> B[Persist restart markers]
B --> C[Interrupt active requests]
C --> D[Request custody]
D --> E[Supervised command cleanup]
E --> F[Accepted finalizer writes]
F --> G[Database retirement]
Loading

Technical review

Best possible solution:

Forward restart interruption through existing request custody while retaining physical cleanup, accepted finalizer writes, and the late supervisor/database ordering.

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

Current main visibly filters out the typed restart reason, and the supplied baseline regression and owner measurements exercise that path; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch is the smallest complete runtime repair: extend the existing cancellation predicate rather than move supervisor shutdown earlier or weaken finalizer settlement.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Request cancellation changes intended behavior with a stated reason (109bd47: Separate request Stop from tool-call disposal, preserve independent services, and join physical cleanup.)
  • Cancellation regression table keeps the original intent (109bd47: Prove yielded commands retain request ownership after invocation disposal.)
  • Loaded shutdown measurement keeps the original intent (e32051e: Exercise real Gateway shutdown and durable recovery with accepted finalizers and a large synthetic state fixture.)
  • Documented shutdown cleanup keeps the original intent (a535fbc: Preserve command outcomes and broker availability until process cleanup settles.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned production change: The introduced diff adds recognition of the existing typed restart reason to withExecRequestTurn; it retains the existing cancellation operation and pending-process join. (src/infra/exec-request-context.ts:221, c22e6a546e94)
  • Current main still needs the fix: Fetched main recognizes only explicit Stop in this owner, leaving restart interruption filtered out. (src/infra/exec-request-context.ts:218, cb8c84949925)
  • Cleanup ordering preserved: Shutdown persists restart markers before interruption, and the late supervisor join still precedes agent-database closure; independent background services are excluded from request custody by the existing exec caller. (src/gateway/server-close.ts:605, c22e6a546e94)
  • Original cancellation contract: fix: stop yielded commands with their Gateway request #166753 established request-owned cancellation, physical cleanup settlement, independent-service preservation, and cancellation-notification suppression; this PR extends that owner with an explained restart case. (src/infra/exec-request-context.ts:218, 109bd4791099)
  • Reported behavior evidence: The full PR body reports five interleaved owner-level pairs, Stop controls, preserved finalizer writes and written receipts, plus built-Gateway macOS and Linux shutdown/recovery results with no surviving child and exactly-once recovery; further loaded controls are explicitly still pending. (c22e6a546e94)
  • Exact-head gates: The reviewed head has successful CI, dependency-review, and security-sensitive-review statuses; the canceled auto-response jobs establish no patch failure, and GitHub reports a clean merge candidate. (c22e6a546e94)

Likely related people:

  • Shakker: Raw commit 109bd47 adds src/infra/exec-request-context.ts:187 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 109bd4791099; files: src/infra/exec-request-context.ts)
  • Peter Steinberger: Raw commit 1b620a7 adds src/infra/exec-request-context.ts:57 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1b620a76abb4; files: src/infra/exec-request-context.ts)
  • Vincent Koc: Raw commit d4820c4 adds src/infra/exec-request-context.ts:84 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: d4820c404e00; files: src/infra/exec-request-context.ts)

PR surface

Source +6, Tests +4, Docs 0, Other +315. Total +325 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 9 3 +6
Tests 1 47 43 +4
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 320 5 +315
Total 6 377 52 +325

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime versus regression growth Runtime +9/-3 lines; regression tests +47/-43 lines The runtime growth adds the existing typed predicate; test churn extends the existing cancellation table with one distinct restart case.
Measurement options 7 developer measurement switches; 0 runtime configuration settings The new owner-measurement script has six options, and the existing loaded-Gateway script gains --yield-tools.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The change removes a measured additional wait during restart with active yielded commands, with limited scope and no demonstrated urgent availability failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 November 11, 2026, 9:06 PM ET / November 12, 2026, 02:06 UTC.

@steipete
steipete merged commit 9a1052a into main Nov 12, 2026
151 of 155 checks passed
@steipete
steipete deleted the steipete/perf-micro-shutdown-supervisor-reap-blocks-db-seal-20260919 branch November 12, 2026 02:14
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
…197457)

Forward typed restart interruption through active request custody so yielded exec commands begin their existing graceful cancellation while other accepted work drains. Keep physical process settlement, finalizer writes, database sealing, and restart recovery ordered.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant