Repository navigation
Conversation
Run the full Gateway close under its lifecycle owner's plugin context so an expired requesting invocation cannot refuse memory, channel or hook cleanup. Wake the loop when retained cleanup rejects, and retire deadline watchdogs once no resource remains pending. Bound generic failed exits after CLI finalization with a failure signal while preserving special supervisor codes. Keep pending persistence, retained resources, restart markers and transcript settlement with their existing owners. Add regressions that fail on the base and extend the loaded shutdown fixture with four synthetic channel transports.
|
🦞👀 Pull request received. I will update this pull request when review starts. |
Codex Review Summary: ✅ CompletedThis 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. |
|
@clawsweeper review Please review the final code at 6d09b0c, especially Gateway-owned cleanup context, settled-rejection wake-up, and preserving supervisor failure semantics after finalizers settle. Pending or retained resources must keep their hard deadline. The PR body records red-on-base regressions, focused proof, and exact-parent global-check failures. |
|
🦞👀 Re-review progress:
|
|
Codex review: needs maintainer review before merge. What this changesThis PR clears inherited plugin scopes during Gateway cleanup, wakes the run loop on settled rejection, and bounds failed exits while preserving supervisor failure status. Example: Gateway close inherits a released plugin invocation scope containing Discord, Slack, ClickClack, and X registrations.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR addresses shutdown failures still present on fetched main; the pinned diff has no actionable code findings. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe Gateway lifecycle closes plugin resources and persistence, then the CLI run loop retires watchdogs and finalizes process output before exit. flowchart TD
A[Stop or restart request] --> B[Gateway close owner]
B --> C[Memory channels and hooks]
C --> D[Run loop cleanup]
D --> E[Pending work hard deadline]
D --> F[Settled CLI finalization]
F --> G[Natural exit or tail signal]
Technical reviewBest possible solution: Keep shutdown authority in the existing Gateway close owner and distinguish settled failure from retained work in the existing cleanup owner. Do we have a high-confidence way to reproduce the issue? Source inspection confirms the expired-scope lookup failure and sleeping-loop rejection path; the author reports three exact-base regressions, but this read-only review executed no target code. Is this the best way to solve the issue? The patch is a focused repair using existing lifecycle and exit owners, preserves retained-work handling, and introduces no competing cleanup mechanism. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 8c70f579729d. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +7, Tests +57, Docs +5, Other +34. Total +103 across 12 files. Added test files: 0. View PR surface stats
Preflight sourceSource 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
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 November 13, 2026, 11:52 PM ET / November 14, 2026, 04:52 UTC. |
|
Merged via squash auto-merge.
|
…w#198652) Run the full Gateway close under its lifecycle owner's plugin context so an expired requesting invocation cannot refuse memory, channel or hook cleanup. Wake the loop when retained cleanup rejects, and retire deadline watchdogs once no resource remains pending. Bound generic failed exits after CLI finalization with a failure signal while preserving special supervisor codes. Keep pending persistence, retained resources, restart markers and transcript settlement with their existing owners. Add regressions that fail on the base and extend the loaded shutdown fixture with four synthetic channel transports.
… refusing late calls (#199618) ## Problem A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended. Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example #196700, #196750, #197658, #197990, #198652, #198732 and #198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches: - 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`) - 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run` ## Fix A released scope stops routing. It no longer refuses calls. - `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before. - `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission. - A released scope drops its instance views, so a stale async context does not retain them. - Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged. - The per-hook workarounds are reverted: - #198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts` - #198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts` - #197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope) - #196700: activity recap scope exit in `session-activity-summaries.ts` - #196750: session-event delivery scope exit - #197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts` - #198652: Gateway close scope exit in `server-lifecycle-close.ts` - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts` - Kept on purpose: `runInDetachedAsyncContext` for auth publication (#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope. - `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs. This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks. ## Proof | Claim | Tier | Base (`5d5ca9d2ba8c`) | Head | |---|---|---|---| | Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once | | `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted | | `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the #197990 helper removed) | vitest-source | — | passes | | Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) | | All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) | | `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 | | Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 | | `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass | | `ocx build --dts` | full | — | pass | | Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries | The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines. Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter. ## Net lines `28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464. Co-authored-by: Ayaan Zaidi <[email protected]>
… refusing late calls (openclaw#199618) ## Problem A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended. Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example openclaw#196700, openclaw#196750, openclaw#197658, openclaw#197990, openclaw#198652, openclaw#198732 and openclaw#198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches: - 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`) - 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run` ## Fix A released scope stops routing. It no longer refuses calls. - `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before. - `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission. - A released scope drops its instance views, so a stale async context does not retain them. - Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged. - The per-hook workarounds are reverted: - openclaw#198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts` - openclaw#198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts` - openclaw#197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope) - openclaw#196700: activity recap scope exit in `session-activity-summaries.ts` - openclaw#196750: session-event delivery scope exit - openclaw#197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts` - openclaw#198652: Gateway close scope exit in `server-lifecycle-close.ts` - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts` - Kept on purpose: `runInDetachedAsyncContext` for auth publication (openclaw#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope. - `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs. This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks. ## Proof | Claim | Tier | Base (`5a640d63290f`) | Head | |---|---|---|---| | Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once | | `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted | | `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the openclaw#197990 helper removed) | vitest-source | — | passes | | Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) | | All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) | | `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 | | Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 | | `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass | | `ocx build --dts` | full | — | pass | | Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries | The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines. Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter. ## Net lines `28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464. Co-authored-by: Ayaan Zaidi <[email protected]>
…w#198652) (cherry picked from commit ca2bf94) Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit a070447b7ead57d4d6167abd98775858fe5698ab)
What Problem This Solves
Fixes Gateway shutdown refusing memory and channel cleanup when it inherits an expired plugin invocation scope, and waiting for the hard deadline after cleanup has already rejected and settled.
User Impact
Memory, channel transports, and shutdown hooks close under the Gateway lifecycle owner. A settled cleanup failure wakes the run loop and bounds any remaining process tail after CLI finalization, without using SIGKILL. Pending persistence and genuinely retained resources still keep their hard deadline. Restart markers and transcripts keep their existing settlement order.
Why This Change Was Made
The close boundary cleared the current plugin call but left its enclosing invocation scope attached. Clear both at the owner boundary, including the full close prelude and hooks. The cleanup owner now notifies the loop when an asynchronous rejection settles, replacing a later failure check that could not wake the sleeping loop.
Deadline retirement follows retained resources rather than a failed result. Generic failed status
1uses default SIGUSR2 after the existing one-second settled tail watchdog; SIGTERM would hide failure from an on-failure supervisor. Special supervisor exit codes remain report-only. Production code grows by 7 lines (+29/-22) to carry the owner notification and failure signal; no new config, cache, or schema.Evidence
0b7cd35571e7cbfb7544305379c7c4a1dac26b03: expired-scope memory/four-channel close; settled failed close with a leaked handle; rejected log cleanup leaving the loop asleep. The fixed real Gateway case also verifies all four shutdown hooks.pnpm check:changed --base HEADcompleted; an introduced unused test import was removed and core typecheck re-passed. All remaining failures are the two exact-parent dead exports listed below. Targeted lint/format and other selected guards passed.The serial campaign passed all 12 runs: two baseline A/A controls, then five interleaved baseline/candidate pairs. Every run exited naturally with code 0, stopped all four mock transports, settled both children, recovered all 18 sessions exactly once, and preserved partial text, tool receipts, and cron outcomes.
p95 is the nearest-rank maximum with n=5. The A/A controls were 9,353 / 2,409 ms to exit, 1,432 / 813 ms CPU, and 176.5 / 172.4 MiB sampled allocation. That spread prevents a speedup claim. The Gateway-close median increased 74 ms and allocation p95 increased 4.6 MiB; both are reported rather than hidden. The measured benefit is removal of the reproduced failure/idle-wait paths, with normal loaded durability preserved.
Rerunnable workload:
TMPDIR=<safe-synthetic-root> node --import ./scripts/tsx.mjs scripts/perf/shutdown-loaded-measure.ts --checkout <built-head> --fixture <shutdown-loaded-fixture-root> --output <new-directory> --channel-transports --allocation. Allocation sampling uses 32 KiB intervals and includes collected objects. CPU/allocation cover the main isolate, not workers or children. A separate candidate CPU profile was captured with--cpu-profile.Evidence limits: mock transports exercise the real registry/channel lifecycle, not the bundled Discord/Slack/ClickClack/X adapters. The expired-scope injection establishes a failure mechanism, not the provenance of a production signal's scope. Large-fixture storage is a temporary APFS sparse image on APFS; Linux/btrfs proof is unavailable because the configured remote provider could not allocate without its credential.
Existing main regressions
Both unused-export failures reproduce on the clean exact parent with
node --import tsx scripts/check-deadcode-exports.mts; neither file is changed here:prepareTranscriptFactsBackfillStress72f90dde293d5e99d6852545a0d7b2590a5aa56e/ #194519MAX_COMPLETION_CLAIMSc1ca2d7b14c6de87939ec0e1207808cf1816d434/ #197471The existing pending-close process test also contained a main-thread file-write interception made ineffective by the worker logging migration in
5358d05ca2c1dc8c8a4770704a03c1a8f89b5f78(#197586). That assertion failed on the exact parent. This PR removes the obsolete interception while keeping the real pending-close watchdog test; accepted logging writes remain covered by the finalization process suite.