Repository navigation
fix(gateway): stop late request failures after shutdown - #136998
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: blocked before merge. Reviewed September 3, 2026, 9:54 PM ET / September 4, 2026, 01:54 UTC. ClawSweeper reviewWhat this changesThe PR adds a Gateway-instance request-entry lifetime that prevents delayed authorization and lazy-handler preparation from entering a retiring Gateway after shutdown begins. Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 3 items remain Keep open: this protected maintainer PR owns a concrete P1 Gateway shutdown fix. The reviewed request-entry owner fences asynchronous preparation before handler invocation across transport, in-process, typed, and lazy-handler paths; no introduced correctness defect was found, but exact-head CI is still in progress. Priority: P1 Review scores
Verification
How this fits togetherGateway requests arrive through WebSocket, internal agent, and in-process paths, then authorize and resolve lazy handler code before invoking a method. The new lifetime owns that preparation interval and joins it during shutdown, while already-started method execution remains with its existing owner. flowchart LR
A[Client or internal request] --> B[Gateway request entry]
B --> C[Authorization and handler loading]
C --> D{Gateway still open?}
D -->|Yes| E[Method execution]
D -->|No| F[Retryable refusal]
G[Gateway shutdown] --> B
E --> H[Response or existing lifecycle owner]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +153, Tests +443, Docs +7, Other 0. Total +603 across 14 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Copy recommended automerge instructionTechnical reviewBest possible solution: Land one shared pre-handler lifetime owner only after the exact refreshed head proves the transport and Gateway lifecycle suites green; retain the explicit handoff so shutdown never becomes an indiscriminate RPC drain. Do we have a high-confidence way to reproduce the issue? Yes — the new boundary suite provides a high-confidence controlled reproduction by pausing each preparation stage, starting close, and observing that the handler never starts. This read-only review did not execute the test. Is this the best way to solve the issue? Yes — a single Gateway-instance owner covers the preparation stages before a synchronous handoff to existing handler owners, avoiding downstream guards or an all-RPC shutdown drain. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against f1e49edfb85c. LabelsLabel 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
HistoryReview history (5 earlier review cycles)
|
3f97d26 to
27fe197
Compare
27fe197 to
15ca092
Compare
Land-ready — exact head
|
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
🦞👀 Re-review progress:
|
15ca092 to
75620e9
Compare
…ginal commits (#1409) <details> <summary>Additional instructions</summary> **MUST:** Keep **Allow edits from maintainers** enabled for this PR so maintainers can help update the branch when needed. </details> ## What Problem This Solves Resolves a problem where a ClawSweeper review could attribute a GitHub test merge's main parent to the original PR commit. The [historical review of the Gateway PR](openclaw/openclaw#136998 (comment)), reviewed at `2026-09-04T01:20:32.984Z`, claimed that original head `15ca0925f5d164df5283783aea5f4a01ffe3924e` had current main as its recorded parent. The original raw commit proves otherwise. The [producer run](https://github.com/openclaw/clawsweeper/actions/runs/33825006229) ran code `8440386ebd92f39c5d6812d74cda3793a67530a3`. Its archived report (`exact-review-33825006229-1`, artifact ID `9919776836`, report SHA-256 `3db6dce3fe4050873ad4131159604ecd62b11432eed98a73fd962cba873772bb`) preserves the incorrect claim; the linked durable comment is mutable and now contains later reviews. The raw report is deliberately not reproduced here. | Object role | Exact commit | Raw recorded parents, in order | | --- | --- | --- | | Original PR head | `15ca0925f5d164df5283783aea5f4a01ffe3924e` | `cd8c74889d21ddcc9f3a2d47fe868224a0e44acb` | | Historical GitHub test merge | `782c712e2dad405a2e9010354b5291fb94d42fe6` | `3c0eb9fd822f8101dc3117ce40dbd2b0f5e01930`, `15ca0925f5d164df5283783aea5f4a01ffe3924e` | ## Why This Change Was Made The evidence generator supplied identities and test-merge parents but omitted the original head's raw parents, and the model's prose conflated those distinct identities. Reuse the hardened Git reader and canonical parent parser to provide typed, role-labeled `originalHead` and `checkout` records, and explicitly label `testMerge`. The prompt requires public ancestry claims to keep these roles separate. Exact object-type checks prevent tag peeling. Reads retain the existing five-second/1 MiB bounds and cap parent lists at eight; unavailable, malformed, or oversized reads return `parents: null`, while only an inspected root returns `[]`. The old scalar head/checkout aliases are removed. This is reviewer input, with no decision schema, dependency, configuration, routing, persistent-data, or publication-authority change and no prose scrubber. Source preparation materializes the pinned original head. There is no evidence that a historical rebase caused the bad claim, and an integration checkout cannot rewrite an existing original SHA's parent. ## User Impact Maintainers and contributors receive explicit original-commit ancestry in review evidence, reducing false provenance and ownership claims when the actual checkout, fetched main, merge base, or test merge differs. Unknown inspection remains visibly unknown. Raw parent records alone do not establish causal introduction, authorship, or parent-object availability. ## OpenClaw Bay Impact Bay is unaffected: the change only adds reviewer-input provenance. No observer data contract, lifecycle/publication authority, queue state, telemetry, routes, or controls change. ## Documentation Impact Updated the active implementation documentation in `docs/pr-review-comments.md`, section “PR Introduction Evidence,” and the owning reviewer prompt in `prompts/review-item.md`. ClawSweeper review maintainers own this contract; `src/pr-review-evidence.ts` is the source of truth. Verified against this PR's four-file patch; changes to record roles, raw-object bounds, unknown/root semantics, or source acquisition trigger a documentation update. Reviewed `CONTRIBUTING.md`, `docs/README.md`, `README.md`, and `VISION.md`; no other documentation changes are needed. Release-note context is preserved here without editing the changelog. ## Evidence - Before the production change, the new regressions failed: initial focused run 89 passed / 7 failed; additional boundary cases 2 failed; exact-object-type case 1 failed. With the patch, all four focused files passed, 98/98, under Node 24.20.0 and pnpm 11.10.0 with standard Git configuration. - Real Git fixtures cover synthetic merges, rebased checkouts, original heads with multiple commits, merge heads, replacement refs, legacy grafts, shallow history, missing objects, trees/tags, malformed raw parents, oversized objects, and genuine roots. Production prompt serialization is exercised, including preservation of introduced versus main-only changes. - Static checks, all builds, lint, and the existing changed-surface coverage gate passed (13/13). The original full local `pnpm run check` was interrupted under severe host load and did not pass. A representative agent-runner failure was reproduced: that command set `TMPDIR` inside the checkout, which the scanner correctly rejects as `unsafe_path`. The unchanged test passes with the default external temp directory. This diagnoses that local failure only. The full gate subsequently passed in [exact-head Linux CI](https://github.com/openclaw/clawsweeper/actions/runs/33845765111/job/100937182439) on `f1a20200c0b22ccd309d38939879b8ec66fb7a85`; the same run also passed Windows launcher and sparse repair build checks, with no retry. [CodeQL](https://github.com/openclaw/clawsweeper/actions/runs/33845765036) passed at the same head. The hosted scan smoke is dispatch-only and was correctly skipped. - Fresh isolated Codex reviews before commit and after rebase both passed with no actionable P0–P3 findings. On head `f1a20200c0b22ccd309d38939879b8ec66fb7a85` against base `b4f7d36406ed1e375dc8eac17abc00ff63a93f02`, the production build, exact historical-object probe, and selected rebase/unknown/type/size regression cases passed (3/3). The rebased four-file patch is byte-identical to the original 98/98-tested patch (SHA-256 `e0c149f62c70876b121df9dfb497ec23a6e72fb5cdaf9c8b8cbbfb7387188128`); upstream did not change its evidence or prompt-serialization owners. - The [initial ClawSweeper review](#1409 (comment)) found no actionable issues or rank-up requests and judged the proof sufficient. No code changes were needed in response; this body now includes the completed CI result. - Scope: four files, production TypeScript +40/-4 (net +36), prompt +15/-3 (net +12), tests +172/-3 (net +169), documentation +13/-4 (net +9). No other owner's files changed. The related [owner simplification PR](#1407) changes different files. ## Real Behavior Proof **Claim:** compiled production evidence generation preserves the exact original PR head's raw parents independently of the actual integration/rebased checkout and GitHub test merge, and production prompt assembly carries those roles to the reviewer. **Surface and scenarios:** `buildPullRequestReviewEvidence` and production `buildReviewPrompt` against real disposable Git histories; additionally, compiled evidence generation against the exact historical original and test-merge objects in a task-owned bare object store. Historical source objects and active PR checkouts were not modified. **Commands/environment:** local macOS, Node 24.20.0, pinned pnpm 11.10.0, standard Git configuration. Build and focused proof: ```sh pnpm run build TMPDIR="$PWD/.artifacts/original-commit-provenance/tmp" CLAWSWEEPER_PROVENANCE_PROOF_DIR="$PWD/.artifacts/original-commit-provenance" node --test test/pr-review-evidence.test.ts test/review-prompt-context.test.ts test/review-prompt-policy.test.ts test/review-provenance.test.ts ``` The post-rebase boundary rerun used the default external temp directory and passed all three selected cases: ```sh node --test --test-name-pattern='original head parents survive synthetic|unavailable raw commits|invalid or oversized raw parent' test/review-provenance.test.ts ``` The historical probe calls the compiled `buildPullRequestReviewEvidence` with `head.sha=15ca0925f5d164df5283783aea5f4a01ffe3924e`, `base.sha=3c0eb9fd822f8101dc3117ce40dbd2b0f5e01930`, `mergeCommitSha=782c712e2dad405a2e9010354b5291fb94d42fe6`, `mainSha` equal to that base, and the bare fixture's `HEAD` at the test merge. It first verifies both objects with `git --no-replace-objects cat-file -p <exact-sha>` and asserts the following production output: ```text originalHead: verified, role=original_pr_head sha=15ca0925f5d164df5283783aea5f4a01ffe3924e parents=[cd8c74889d21ddcc9f3a2d47fe868224a0e44acb] checkout: verified, role=actual_checkout sha=782c712e2dad405a2e9010354b5291fb94d42fe6 parents=[3c0eb9fd822f8101dc3117ce40dbd2b0f5e01930,15ca0925f5d164df5283783aea5f4a01ffe3924e] testMerge: verified, role=github_test_merge sha=782c712e2dad405a2e9010354b5291fb94d42fe6 parents=[3c0eb9fd822f8101dc3117ce40dbd2b0f5e01930,15ca0925f5d164df5283783aea5f4a01ffe3924e] mergeBase: verified, sha=cd8c74889d21ddcc9f3a2d47fe868224a0e44acb PASS: immutable original-head parentage is separate from integration ancestry. ``` **Artifact/trace:** bounded historical output above, the original producer/artifact identities above, and reproducible real-Git regression assertions in `test/review-provenance.test.ts`. Red/green logs, fixture JSON, and historical production JSON are retained locally; raw reports and agent transcripts are not published on this branch. **Limits:** this proves evidence generation and prompt assembly, not model compliance, a replay of the historical model session, or GitHub review publication. It does not guarantee that model prose never makes another provenance mistake. No Gateway PR or lifecycle session was changed.
Own router loading, bounded starts, authorization and lazy handler preparation until refusal or atomic handoff. Preserve reconnect-safe requests and exact pending node cleanup without draining arbitrary handler execution. Related: #127256 and #136145. Separate from the Full Access and metadata repair in #136036. Deferred regressions fail before the repair; source-matched built Gateway/browser proof covers catalog loading, reconnect and quiet shutdown.
Keep parent synthetic-auth capture bound to its original immutable plugin generation. Construct worker transfer input in the catalog factory and restore metadata only after actual worker cloning, rather than refreezing a shallow parent projection. A retained snapshot from another module evaluation previously failed with Cannot redefine property: clear before a worker could start. Add a fail-first outer-build regression covering parent snapshot, cache, normalizer and registry identity plus a real worker catalog request. Preserve cloned-worker mismatch, secret-reference, scope and cancellation behavior. Found while validating the Gateway request-entry repair in #136998. This is separate from the request-entry lifetime and broader test-fixture ownership.
75620e9 to
1b34bf0
Compare
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Merged via squash.
|
) * fix(gateway): stop late request entry during shutdown Own router loading, bounded starts, authorization and lazy handler preparation until refusal or atomic handoff. Preserve reconnect-safe requests and exact pending node cleanup without draining arbitrary handler execution. Related: openclaw#127256 and openclaw#136145. Separate from the Full Access and metadata repair in openclaw#136036. Deferred regressions fail before the repair; source-matched built Gateway/browser proof covers catalog loading, reconnect and quiet shutdown. * fix(agents): retain canonical parent catalog metadata Keep parent synthetic-auth capture bound to its original immutable plugin generation. Construct worker transfer input in the catalog factory and restore metadata only after actual worker cloning, rather than refreezing a shallow parent projection. A retained snapshot from another module evaluation previously failed with Cannot redefine property: clear before a worker could start. Add a fail-first outer-build regression covering parent snapshot, cache, normalizer and registry identity plus a real worker catalog request. Preserve cloned-worker mismatch, secret-reference, scope and cancellation behavior. Found while validating the Gateway request-entry repair in openclaw#136998. This is separate from the request-entry lifetime and broader test-fixture ownership.
Related: #127256 (Gateway-generation admission), #136145 (received-work/fixture lifetime), and #136036 (separate Full Access and metadata repair).
What Problem This Solves
Closing or restarting a Gateway while the Control UI was loading could leave asynchronous request preparation running after shutdown completed. In the observed cold-browser case,
update.status,taskSuggestions.list,chat.startup, andtalk.catalogimports continued into torn-down dependencies after the UI assertion passed.This repairs the generic pre-handler request-entry boundary. The historical cold case did not reach
chat.metadata; the separate Full Access/metadata repair is not claimed to fix this broader entry gap. Stable-tag inspection found the structural gap inv2026.8.2; no introducing commit is attributed.Why This Change Was Made
One Gateway-instance owner retains credential-mutation waits, router loading, bounded start scheduling, authorization, and nested lazy-handler preparation. Shutdown fences ordinary entry and joins pending preparation before teardown. The final liveness check, ownership release, and actual handler invocation are synchronous. WebSocket, raw in-process, typed-agent, and directly callable lazy-handler paths share this boundary.
Already-started handlers retain their existing lifecycle owners: this is not an all-RPC drain. Ordinary UI/SDK requests remain reconnect-safe, existing disconnect-cancelled operations remain cancelled, and exact pending node progress/results remain available until transport shutdown seals entry. A credential waiter interrupted by shutdown receives retryable
UNAVAILABLEbefore its lease releases, without cancelling or joining its running predecessor.The handler registry uses the existing rejection-caching lazy-promise helper; the duplicate cache implementation and unsafe family-key assertion are removed. All 97 handler-family mappings and 108 runtime import targets are preserved. Reconciliation retains main's policy-response close ordering, host/caller fences, session-mutation commit guards, combined delivery-recovery shutdown, discovery ownership, and mention/update-check cleanup.
Validation also exposed a separate catalog composition defect: the parent factory restored an untransferred shallow projection of an already-frozen metadata graph. Across module evaluation, replacing its nonconfigurable collection mutators threw
Cannot redefine property: clearbefore a worker could start. The factory now receives canonical parent facts and builds its own transfer input, retaining the original snapshot/cache/normalizer/registry for parent capture. Restoration remains only at the actual cloned child boundary. This removes three production lines and adds a fail-first real-worker regression; it is a functional validation repair, not cosmetic deslop.Production LOC: +693/-543, net +150. Tests/support: +624/-74, net +550. Docs: +7. The positive production delta supplies the missing shared preparation/execution ownership boundary, while removing duplicate preparation/reconstruction paths. The assertion allowance only shrinks. No new configuration/env option, dependency, database schema, protocol version, timeout, logger suppression, or Vitest patch.
User Impact
A retiring Gateway cannot start an ordinary handler when delayed preparation resumes. Normal reconnect and node-cleanup behavior are preserved. Catalog preparation retains its authoritative parent metadata instead of reconstructing a second graph. The entry contract is documented in Gateway protocol.
The separately coordinated #136146 owns broader received/cooperative execution, startup/disconnect, post-response, and fixture lifetimes. This PR does not claim those guarantees or close the broader linked issues. The source-only cold Talk/plugin-discovery stall is also separate.
Evidence
Current head:
1b34bf0a6367ffd86124db5cefa34145dae40520, based on3b710e4b75c94675a0e1f1b1c31754635c08a1a6. Both commits' final tree matches the verified 22-path candidate and all 52 recorded source inputs.clearerror, then passed through a real Worker while preserving parent identity and child cloning.node scripts/check-changed.mjs --base 3b710e4b75c94675a0e1f1b1c31754635c08a1a6passed, including core/test types, formatting, lint, dead exports, architecture and ownership guards.pnpm buildandpnpm plugin-sdk:surface:checkpassed in an exact-source normal checkout with copied dependencies. The first worktree build detected an ancestor dependency input changing during compilation; the isolated build passed with the consistency guard unchanged. Startup JS was 348,749 B gzip against the unchanged 350,141 B enforcement limit; all 149 public SDK subpaths passed.run_7533a481fa76passed runtime/UI builds and real built-browser/wire flows. All 52 inputs matched nine checkpoints. The catalog card and startup RPCs worked, ordinary TCP loss reconnected, shutdown resolved in 78.00 ms, and the child remained quiet for 20 seconds before natural exit 0. The wire probe observed retryable refusal before close, zero follower handler entries, and a predecessor held until explicit release. Five screenshots and the 25.16-second recording were inspected; the lease is released.Live fixtures are fresh synthetic loopback auth-none environments, with no hydration, instance role, Tailnet, operator state or operator service. This is not real credential rotation/provider authentication, native hosted-service proof, a green source-only cold Vitest run, or proof of the original warmed metadata path. Broker heartbeat/event warnings were retained; complete downloaded logs and source receipts were verified. Two prior proof-assembly errors stopped before product execution and were repaired only in ignored harness scripts.
The earlier grouped run's timeout/root-count failures are not all attributed to the metadata repair: their exact historical causal chain remains unobserved. The final unchanged-assertion original-order replay passed every case. An isolated base/candidate diagnostic also passed and observed slow startup imports near the baseline deadline, not a proven pairing-read deadlock.
Exact proof, inspected media, and retained earlier-head history. Current main deliberately restored fail-closed audits in #137989 (audit retry hardening). The refreshed head's first CI attempt passed the code/test checks but exhausted four npm advisory attempts and returned incomplete coverage. After a public readiness probe returned valid JSON, only the failed security job and aggregate gate were retried. CI run 33850254675, attempt 2 completed successfully on this exact head. No rebase, audit exception or gate bypass was applied; the strict audit completed rather than being downgraded to a warning. The verified candidate is ready for native prepare/merge.