Skip to content

fix(gateway): stop optional placement work from delaying shutdown - #172971

Merged
steipete merged 4 commits into
mainfrom
steipete/team-shutdown
Oct 15, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/team-shutdown

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes Gateway shutdown spending its remaining stop budget on optional worker-placement maintenance after restart drain has begun.

User Impact

Draining Gateways stop optional scans and preparation instead of starting more maintenance candidates, while accepted durable effects finish before their database or transport closes. This reduces the risk of reaching the supervisor's stop deadline on loaded Gateways without increasing timeout budgets or abandoning writers.

Why This Change Was Made

On the base revision, src/gateway/server-worker-placement-startup.ts:467 checks stopping only between whole reconciliation phases and :568 joins the complete running operation. The retirement loop at src/gateway/worker-environments/placement-session-retirement.ts:185 can continue through every candidate. Optional evidence reads can also wait behind writer admission without observing shutdown.

The placement owner now carries the existing drain/scheduler cancellation signal through optional session discovery, identity reads, exact idle-session reads, and disk probes. Recovery, retirement, retention, and publication owners stop before new candidates or effects. Once a retirement, recovery, reclaim, or publication effect is accepted, its existing settlement path remains joined. Node-retention stop starts alongside the reconciliation joins. Pending-close diagnostics identify the reconciliation subphase.

The shutdown ordering stays intact: sidecars need worker transports and shared state to settle accepted effects; terminal-session disposal handles PTYs, not chat persistence. Agent database sealing already runs independently while sidecars drain. The restart-marker join and hard-exit watchdog are unchanged.

A shared worker-bundle artifact build already in progress still settles: its producer performs staged filesystem writes and has no cancellation contract. Caller-only cancellation would abandon that producer or disrupt another consumer. This change does not guarantee completion within 90 seconds for an arbitrarily slow accepted effect.

Evidence

The supplied Team journal covers 61 hours: 40 stops, 22 recorded SIGKILL exits, and connection-dependent sidecars named in 20 of 23 deadline warnings. Sanitized evidence from October 15, 2026 (UTC; decompressed journal line numbers):

  • L975984: 06:57:03.519 — SIGTERM accepted.
  • L976005–L976201: 20-second drain, ending 06:57:23.695.
  • L976387: 06:57:32.858 — session-admission cleanup settled.
  • L976432: 06:58:28.408 — sidecars and worker-placement reconciliation still pending after approximately 57.2 seconds.
  • L976437: 06:58:30 — process exited with signal 9/KILL.

The journal identifies the owning reconciliation phase, not its exact leaf await; the new diagnostic narrows future stalls to a named reconciliation subphase.

The new owner-boundary regression passed with the fix. Reverting the placement runtime to the base revision made the same test fail at the intended assertion: shutdown retired the next candidate instead of leaving it requested. The regression holds an actual SQLite retirement, starts shutdown mid-candidate, verifies the accepted writer is not aborted, releases it, and checks both durable rows and the exact pending subphase.

Separate regressions passed for cancellation during discovery/identity admission behind a writer, idle-read cancellation, disk-probe cancellation, and stopping between accepted local/repository publications. Existing startup, recovery, maintenance, retirement, and node-retention contracts were exercised. A former startup expectation that retirement must start after shutdown during an unresolved evidence read is updated to the new pre-effect deferral contract; accepted-effect settlement has independent real-SQLite coverage.

Focused invocation Result Wall time
Database workers: evidence, publication reconciliation, idle sweep 42 passed 732.57 s
Database workers: startup maintenance and retirement 24 passed 246.35 s
Core: node retention 28 passed 6.38 s
Core: disk-space monitor 18 passed 35.40 s
Server: startup cleanup 6 passed; includes new accepted-retirement regression 519.45 s combined initial run, including three subsequently repaired fixture failures
Server: startup, recovery events, session events 24 passed; corrected retirement expectation passed in a focused rerun 286.57 s + 107.80 s rerun
Isolated Gateway: accepted placement retirement through full close 1 passed 348.10 s (108.14 s test, including Gateway boot)

Cold worker compilation and source verification dominate the long invocations on the loaded development host. The database-backed suites exercise actual admission, SQLite settlement, and Git/worktree publication custody, which a cheaper mocked assertion would not prove.

Focused commands
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-database-workers.config.ts src/gateway/server-worker-placement-session-evidence.worker.test.ts src/gateway/github-publication-reconciliation.test.ts src/gateway/worker-environments/placement-idle-sweep.test.ts --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-database-workers.config.ts src/gateway/worker-environments/placement-session-retirement.test.ts src/gateway/server-worker-placement-startup-maintenance.test.ts --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-core.config.ts src/gateway/worker-environments/node-workspace-retain-coordinator.test.ts --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-core.config.ts src/gateway/worker-environments/placement-disk-space.test.ts --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts src/gateway/server-worker-placement-startup-cleanup.test.ts src/gateway/server-worker-placement-session-events.test.ts --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts src/gateway/server-worker-placement-session-events.test.ts src/gateway/server-worker-placement-startup.test.ts src/gateway/server-worker-placement-recovery-events.test.ts --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts src/gateway/server-worker-placement-startup.test.ts --testNamePattern 'defers unaccepted retirement when shutdown begins during its evidence read' --maxWorkers=1
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server-isolated.config.ts src/gateway/server-close.placement.test.ts src/gateway/server-close.agent-databases.test.ts --testNamePattern 'settles accepted placement retirement|releases restart-aborted run leases' --maxWorkers=1
pnpm tsgo:core
git diff --check

Core typecheck, the targeted gateway-root/server/other test graphs (run-tsgo-core-test-shards.mjs), targeted type-aware lint (run-oxlint.mjs), formatting (oxfmt --check), and whitespace checks passed. The repository test wrapper and canonical owning project configs were used after aggregate test preparation stalled; no aggregate run is counted as passing proof.

The Linux-only managed-SIGTERM integration test cannot run on this macOS host. The requested remote allocation queued and was stopped before test execution; no remote pass is claimed. The portable full-close harness passed: an accepted retirement survives the close prelude, persists its outcome, and finishes before shared-state teardown. This proves ordering and custody, not a real-time 90-second bound; the harness uses controlled timers. Codex branch autoreview on final head 3dd8269e193d1c49d91e7e2452e16c0dc5a16fbb: scoped-clean, no accepted/actionable P0–P2 findings. The automated P3 documentation finding was fixed: node retention stops new preparation and cancellable requests, but joins an in-progress shared bundle build. The focused documentation review was also clean; formatting, whitespace checks, and pnpm docs:check-links passed (15,523 internal links; zero broken).

CI on runtime head 5db4e20010ed6afe90f05d78183782a0bb6a83ec failed one selected test in run 38709674325: checks-node-changed-5, test/e2e/qa-lab/runtime/node-worker-launch-wire.e2e.test.ts, “transfers and reconciles a gateway-push workspace through a device runner,” exceeded its 240-second budget. The classifier reported unknown, with no matching main job. That run reached fixture cleanup after the post-restart audit assertions, began cleanup at 249.024 seconds, and completed with no pending cleanup owners.

The required pnpm test:ci-failed 172971 --run replay also timed out, this time during load wave 2/3 finalization. It began cleanup at 240.043 seconds and reported failure after 269.704 seconds, with no pending cleanup owners. The Gateway completed its drain and logged a clean close in 92 ms. The replay did not reach the post-restart assertions. Its cold runtime build took 17m03s outside the test budget; Vitest took 651.18 seconds including worker compilation. This reproduces a broader E2E duration problem, but does not establish a cause or a baseline attribution. No timeouts, assertions, or retry policy were changed. After two ambiguous failures, investigation of that timeout stops here for maintainer follow-up.

Final-head CI at lane closeout: run 38714066515 on 3dd8269e193d1c49d91e7e2452e16c0dc5a16fbb remains in progress: 33 successful jobs, no failed jobs, 31 pending jobs. The two ambiguous timeout attempts reached this lane's stop condition. The task-owned watcher was stopped; GitHub jobs continue. The final-head run is not claimed green.

LOC against the base: production +563/-332 (net +231), tests +318/-16 (net +302), docs +12/-0. The production growth propagates cancellation through existing owners; it adds no new persistence, ownership, or timeout mechanism. Release-note context is retained here; the release-owned changelog is unchanged.

Cancel read-only placement preparation and stop maintenance between candidates when the Gateway drains. Keep accepted retirement, recovery, and publication effects joined, and name the pending reconciliation phase in shutdown diagnostics.
@clawsweeper

clawsweeper Bot commented Oct 15, 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 Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-15T09:06:04.948038Z 5db4e20 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 size: XL labels Oct 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5db4e20010

ℹ️ 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".

Comment thread docs/gateway/restart-recovery.md Outdated
Comment on lines +354 to +355
Optional session-evidence reads, disk probes, and node-retention preparation are
canceled; an accepted retirement, workspace recovery, reclaim, or publication

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Qualify uncancelable node-retention preparation

When shutdown starts while bundleRetention.currentBuild() is already running, node-workspace-retain-coordinator.ts awaits that producer without passing a cancellation signal, and stop() then waits for the owning operation to settle. The statement that node-retention preparation is canceled is therefore inaccurate for exactly the slow-build shutdown scenario operators need this page to explain; clarify that new preparation and cancellable node requests stop, while an in-progress shared bundle build may still delay shutdown.

Useful? React with 👍 / 👎.

@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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR stops optional worker-placement preparation during Gateway shutdown while joining accepted effects through settlement.

Example: Shutdown begins while retiring placement shutdown-first, with shutdown-next still requested.

  • Before: Reconciliation can continue retiring shutdown-next after shutdown begins.
  • After: The accepted retirement finishes, and shutdown-next remains requested for later reconciliation.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful lifecycle repair with meaningful owner-boundary coverage, one low-impact documentation defect, and no demonstrated P0–P2 implementation defect; the CI timeout remains unattributed.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-authored context places this PR outside the ordinary contributor proof gate; its evidence exercises real SQLite settlement and Gateway close ordering through in-process harnesses, without claiming a post-fix managed-process deadline bound.
Patch quality 🐚 platinum hermit (4/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Loaded Gateways can spend their remaining shutdown budget on optional placement maintenance and reach the supervisor's kill deadline.
Reason: The maintainer-authored direction addresses observed shutdown failures while retaining accepted-effect custody and explicitly accepting uncancelable shared builds.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it addresses a concrete shutdown problem still present on main, with one documentation correction identified.

Priority: P1
Reviewed head: 5db4e20010ed6afe90f05d78183782a0bb6a83ec

Before merge

  • Qualify the node-retention cancellation statement (P3) - If shutdown begins while bundleRetention.currentBuild() is running, the retention coordinator continues awaiting that shared producer and stop() joins it. Saying node-retention preparation is canceled therefore misdescribes a remaining shutdown wait. State that new preparation and cancellable requests stop, while an in-progress shared bundle build remains joined, matching the limitation already recorded in the PR body and existing review discussion.

Findings

  • [P3] Qualify the node-retention cancellation statement — docs/gateway/restart-recovery.md:354-355

Tests

  • Missing end-to-end proof: The supplied post-fix full-close evidence uses controlled timers; a real managed-SIGTERM run of this head is not supplied.
Agent review details

How this fits together

The Gateway placement runtime coordinates session evidence, worker recovery, idle suspension, publication, and retention; shutdown must stop optional preparation while preserving database and transport access for accepted effects.

flowchart TD
  A[Gateway drain] --> B[Placement runtime]
  B --> C[Cancel optional preparation]
  C --> D[Session readers and disk probes]
  B --> E[Join accepted effects]
  E --> F[Durable settlement]
  F --> G[Close databases and transports]
Loading

Technical review

Best possible solution:

Preserve the cancellation and settlement boundaries, and document that an in-progress shared bundle build can still delay shutdown.

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

Current-main source permits whole candidate loops and optional read admission to continue after drain begins; the supplied regression reports a matching base failure, but no target code was executed during this review.

Is this the best way to solve the issue?

The implementation addresses the owning lifecycle boundary without increasing deadlines or abandoning accepted writers; the shared-build exception is deliberate and should be reflected in the docs.

Full review comments:

  • [P3] Qualify the node-retention cancellation statement — docs/gateway/restart-recovery.md:354-355
    If shutdown begins while bundleRetention.currentBuild() is running, the retention coordinator continues awaiting that shared producer and stop() joins it. Saying node-retention preparation is canceled therefore misdescribes a remaining shutdown wait. State that new preparation and cancellable requests stop, while an in-progress shared bundle build remains joined, matching the limitation already recorded in the PR body and existing review discussion.
    Confidence: 0.99

Overall correctness: patch is correct
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Placement shutdown ordering keeps the original intent (5e616e1: Cancel environment producers before joining reconciliation while preserving durable allocations for restart adoption.)
  • Session evidence and worker admission keeps the original intent (ad3fc06: Move placement evidence into existing workers while retaining physical reader custody and conservative unknown evidence.)
  • Ordered session lookup and read-error validation keeps the original intent (949dbc5: Prepare session targets through workers while retaining selected physical sources and current-authority checks; the simplified error assertion still receives the composed caller check.)
  • Incremental session retirement keeps the original intent (bd00389: Batch dirty session identities and retain unknown or failed cleanup for subsequent sweeps.)
  • Idle suspension keeps the original intent (d2d055b: Suspend configured idle workers while preserving turn-claim and session-work admission checks.)
  • Node bundle retention keeps the original intent (4cf8d68: Retain installed current builds independently per node without turning maintenance into automatic installation.)
  • Publication reconciliation keeps the original intent (8b34405: Move placement result settlement into workers; this patch preserves existing per-publication settlement and only stops between requests.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • git diff --check
  • pnpm docs:check-links

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5e616e1 adds src/gateway/server-worker-placement-startup.ts:567 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5e616e1b6f38; files: src/gateway/server-worker-placement-startup.ts)

PR surface

Source +231, Tests +302, Docs +11. Total +544 across 33 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 22 563 332 +231
Tests 10 318 16 +302
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 33 892 348 +544

Review metrics

Metric Value Why it matters
Production versus test growth Production +563/-332; tests +318/-16 The production growth carries cancellation through existing owners and adds phase diagnostics; the principal regression verifies durable settlement and deferred candidates.

Labels

Label changes:

  • add P1: The supplied operational trace records repeated supervisor kills while worker-placement shutdown remains pending, affecting Gateway restart reliability.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: The supplied operational trace records repeated supervisor kills while worker-placement shutdown remains pending, affecting Gateway restart reliability.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 October 15, 2026, 5:15 AM ET / 09:15 UTC.

@steipete
steipete merged commit 593176c into main Oct 15, 2026
158 checks passed
@steipete
steipete deleted the steipete/team-shutdown branch October 15, 2026 11:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…enclaw#172971)

* fix(gateway): stop optional placement work during shutdown

Cancel read-only placement preparation and stop maintenance between candidates when the Gateway drains. Keep accepted retirement, recovery, and publication effects joined, and name the pending reconciliation phase in shutdown diagnostics.

* test(gateway): complete placement shutdown fixtures

* test(gateway): assert deferred retirement during shutdown

* docs(gateway): clarify shared build shutdown settlement
tideclaw-bot added a commit that referenced this pull request Nov 4, 2026
Release adaptation: frozen candidate C=df22eeb1f74e935ab3d7877742a1332779cdb1b6.
Join the existing physical owner preparation before session discovery. Include only the scoped history-discovery cancellation prerequisite from #172971; retain candidate startup FTS and read-open retirement repairs. Do not import the unrelated placement migration.

Main-origin: 55d9dab
Main-origin: 593176c

Reviewed-patch: heartbeat-firstbirth-backport.patch
Reviewed-patch-SHA256: ebb37dcede8e1f2b45e2be7eba30ef366f681c430aacd9f15dd450f5b4a77bcf
The independently reviewed patch bytes are unchanged.

Proof: Final signal-corrected public RPC and worker-lane/target selection: 28 passed; native-idle siblings: 6 passed. Exact eight-file independent review found no actionable findings. No credentialed live-heartbeat pass is claimed.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit e2f2f857eac2fbe5f92eb6a9cc426b14051762f0)
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 gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL 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