Repository navigation
fix(gateway): post-ack webhook work fails with "Async work scope is closed" - #144801
vincentkoc merged 1 commit into
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: blocked before merge. Reviewed September 13, 2026, 11:34 AM ET / 15:34 UTC (Revision 3). ClawSweeper reviewWhat this changesGive deferred webhook callbacks an independent async-work lifetime so tracked processing can finish after the originating request closes. Merge readiness⛔ Blocked before merge - 1 item remains This PR remains necessary: current main and v2026.9.4 still inherit the caller’s async scope. No actionable patch defects remain, and the verified maintainer comment resolves the previous cancellation-lifetime decision. Priority: P1 Review scores
Verification
How this fits togetherThe webhook SDK helper connects acknowledged plugin requests to Gateway background-work accounting. It reserves work before the handler returns and keeps that work visible to shutdown and suspension drains. flowchart TD
A[Admitted webhook request] --> B[Reserve independent work root]
B --> C[Write acknowledgement]
B --> D[Create independent async scope]
C --> E[Deferred plugin callback]
D --> E
E --> F[Drain tracked descendants]
F --> G[Release work root]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +28, Tests +78. Total +106 across 4 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Preserve the accepted independent webhook lifetime through the existing scope owner, while keeping ordinary continuations and caller-specific authorization unchanged. Do we have a high-confidence way to reproduce the issue? Yes: current source exposes the closed-parent-scope failure, and the contributor recorded its before/after reproduction through real HTTP admission. This review did not execute target code. Is this the best way to solve the issue? Yes: selecting the existing detached scope owner fixes the lifetime mismatch without changing the public signature or ordinary continuation semantics. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against a0cce74d389d. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (2 earlier review cycles)
|
…losed" Plugins that defer work through runDetachedWebhookWork after a turn ends (e.g. post-agent_end memory extraction) now keep an independently owned async work lifetime: the detached callback runs in a fresh AsyncWorkScope so tracked work stays accepted after the caller's scope closes, while the live-parent root reservation and acknowledgement ordering are preserved. Fixes openclaw#144788 AI-assisted: yes
457ce74 to
6f63704
Compare
|
Real-behavior proof for the "deferred tracked work completing after the triggering scope closes" gap, run on the rebased head ( Zero-mock real-runtime flow mirroring the memory-tencentdb agent_end lifecycle — a real Before (unpatched origin/main), same script — reproduces the reporter's exact failure: After (this patch), same flow: What this shows end-to-end on the real admission chain:
The PR body's Evidence section has been updated with the same before/after transcripts and commands. Focused regression shards on the rebased head are green (webhook-request-guards incl. new regression test, gateway-work-admission 35/35), Not covered: a live memory-tencentdb install with real TencentDB + tencent-maas credentials (external services unavailable here) — the flow above drives the exact public helper + admission + scope chain the plugin hits, with no mocks. |
|
@clawsweeper re-review Please review the unchanged exact head |
|
🦞🧹 I asked ClawSweeper to review this item again. |
|
🦞👀 |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Keep the automatic-reset repair on the shared internal detached continuation, but restore the public webhook helper and its tests exactly to main. The public-helper migration remains in openclaw#144801; this PR no longer changes third-party cancellation inheritance.
|
Merged via squash.
|
* commit '2d87daf04b78992382299d552f15ac84a86a23ed': (1815 commits) fix(ui): distinguish tool activity with semantic icons (#147207) fix(linux): recover completed Quick Chat replies without resending (#146048) feat(desktop): unify Tauri title bar and window controls (#147097) refactor(test): share plugin fixture server shims (#147225) perf(gateway): defer worker workspace execution imports (#143496) fix(gateway): post-ack webhook work fails with "Async work scope is closed" (#144801) refactor(scripts): centralize upgrade survivor version floors (#146975) fix(ci): check publication registries before FRV fanout (#147184) fix(qa): align system-agent delegation with channel contracts (#145905) improve: reduce repeated chat message identity work (#147210) fix(channels): remove stale pre-tool previews from Slack and Telegram (#147106) fix: keep catalog discovery scoped and execution lazy (#147159) fix: serialize reclamation worker shutdown with foreground writes (#147178) test(sessions): cover abrupt committed transcript recovery (#143984) fix: stop transcript storms during context overflow recovery (#147202) fix: reduce CPU overhead for small history and usage reads (#147205) fix: resume tasks after tools finish and the model times out (#147203) refactor(scripts): share SQLite reliability message waits (#146900) feat(exec): configure approval reviewer thinking and fastMode (#147192) test: remove redundant Bonjour module headers (#146981) ...
Integrate the landed detached-continuation owner from #144801. Keep the sessions_send caller repair, post-foreground announcement regression, and nonduplicate admission-fence coverage. Preserve the canonical helper and descendant tests.
…nds (#146350) * fix(gateway): post-ack webhook work fails with "Async work scope is closed" Plugins that defer work through runDetachedWebhookWork after a turn ends (e.g. post-agent_end memory extraction) now keep an independently owned async work lifetime: the detached callback runs in a fresh AsyncWorkScope so tracked work stays accepted after the caller's scope closes, while the live-parent root reservation and acknowledgement ordering are preserved. Fixes #144788 AI-assisted: yes * fix(hooks): keep automatic reset hooks alive after request completion * fix(agents): classify a Code Mode host-exchange deadline as a timeout A headless run and the host exchange it drives observe the same deadline. When the exchange rejects with that scope's own timeout or abort error before the scope's abort controller settles, runCodeModeWorker only inspects signal.reason, so the typed error falls through to codeModeFailureCode and the run reports internal_error. That code is the closed failure code cron automations classify with: only timeout is retryable, so an expired wall clock was recorded as a permanent internal failure and its notification lost the timeout cause. (cherry picked from commit d586df5) * test(agents): prove the headless deadline path through a real tool leg The classification cells exercise runCodeModeWorker through a substituted host. Add a case that runs the production headless entry end to end: a real worker, a real tool and the real deadline scope, with only the timer clock virtual, so the scope observes its own deadline inside the host exchange. Without the classification repair this case reports internal_error while its own message reads "code mode headless wall-clock timeout exceeded". (cherry picked from commit 38752f6) * test(agents): force the headless deadline ordering without a startup assumption The deadline case advanced the clock by a fixed margin below the wall clock and relied on worker startup taking longer than that margin. A faster run left both the inner deadline and the outer abort pending, and the assertion that would have caught it ran after an await on a tool that never settles. Park the run on a first tool leg for a fixed real span instead. The scope measures its remaining budget with an unfaked performance clock, so the second leg's deadline is always armed at least that far ahead of the abort timer, on warm runs as well as cold ones. (cherry picked from commit ff36535) * fix(hooks): preserve existing webhook cancellation semantics Keep the automatic-reset repair on the shared internal detached continuation, but restore the public webhook helper and its tests exactly to main. The public-helper migration remains in #144801; this PR no longer changes third-party cancellation inheritance. * chore(hooks): remove temporary Code Mode dependency Keep the automatic-reset lifetime repair and its shared helper unchanged. Restore the two Code Mode files to their pre-stack bytes while preserving the contributor history and webhook scope reduction. The complete four-file PR diff remains f51a1a4c after the contributor rebase. Fresh full-candidate autoreview is scoped-clean. Earlier-base remote proof passed 66 focused tests and pinned formatting; the native command ended with exit 255 before changed-gates returned a result. Current-head hosted CI must qualify the new base before landing. * fix(ci): route QA Profile Evidence to its run-status owner test #143968 added test/scripts/qa-profile-run-status.test.ts, which references .github/workflows/qa-profile-evidence.yml, so changed-target routing now selects it for that workflow. The routing expectation in test-projects.test.ts still listed the previous five owners, which turned main's tooling shard red. Add the new owner to the expected target list. (cherry picked from commit 9aecc88) --------- Co-authored-by: LiuwqGit <[email protected]> Co-authored-by: Yigtwxx <[email protected]> Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
…losed" (openclaw#144801) Plugins that defer work through runDetachedWebhookWork after a turn ends (e.g. post-agent_end memory extraction) now keep an independently owned async work lifetime: the detached callback runs in a fresh AsyncWorkScope so tracked work stays accepted after the caller's scope closes, while the live-parent root reservation and acknowledgement ordering are preserved. Fixes openclaw#144788 AI-assisted: yes
…nds (openclaw#146350) * fix(gateway): post-ack webhook work fails with "Async work scope is closed" Plugins that defer work through runDetachedWebhookWork after a turn ends (e.g. post-agent_end memory extraction) now keep an independently owned async work lifetime: the detached callback runs in a fresh AsyncWorkScope so tracked work stays accepted after the caller's scope closes, while the live-parent root reservation and acknowledgement ordering are preserved. Fixes openclaw#144788 AI-assisted: yes * fix(hooks): keep automatic reset hooks alive after request completion * fix(agents): classify a Code Mode host-exchange deadline as a timeout A headless run and the host exchange it drives observe the same deadline. When the exchange rejects with that scope's own timeout or abort error before the scope's abort controller settles, runCodeModeWorker only inspects signal.reason, so the typed error falls through to codeModeFailureCode and the run reports internal_error. That code is the closed failure code cron automations classify with: only timeout is retryable, so an expired wall clock was recorded as a permanent internal failure and its notification lost the timeout cause. (cherry picked from commit d586df5) * test(agents): prove the headless deadline path through a real tool leg The classification cells exercise runCodeModeWorker through a substituted host. Add a case that runs the production headless entry end to end: a real worker, a real tool and the real deadline scope, with only the timer clock virtual, so the scope observes its own deadline inside the host exchange. Without the classification repair this case reports internal_error while its own message reads "code mode headless wall-clock timeout exceeded". (cherry picked from commit 38752f6) * test(agents): force the headless deadline ordering without a startup assumption The deadline case advanced the clock by a fixed margin below the wall clock and relied on worker startup taking longer than that margin. A faster run left both the inner deadline and the outer abort pending, and the assertion that would have caught it ran after an await on a tool that never settles. Park the run on a first tool leg for a fixed real span instead. The scope measures its remaining budget with an unfaked performance clock, so the second leg's deadline is always armed at least that far ahead of the abort timer, on warm runs as well as cold ones. (cherry picked from commit ff36535) * fix(hooks): preserve existing webhook cancellation semantics Keep the automatic-reset repair on the shared internal detached continuation, but restore the public webhook helper and its tests exactly to main. The public-helper migration remains in openclaw#144801; this PR no longer changes third-party cancellation inheritance. * chore(hooks): remove temporary Code Mode dependency Keep the automatic-reset lifetime repair and its shared helper unchanged. Restore the two Code Mode files to their pre-stack bytes while preserving the contributor history and webhook scope reduction. The complete four-file PR diff remains f51a1a4c after the contributor rebase. Fresh full-candidate autoreview is scoped-clean. Earlier-base remote proof passed 66 focused tests and pinned formatting; the native command ended with exit 255 before changed-gates returned a result. Current-head hosted CI must qualify the new base before landing. * fix(ci): route QA Profile Evidence to its run-status owner test openclaw#143968 added test/scripts/qa-profile-run-status.test.ts, which references .github/workflows/qa-profile-evidence.yml, so changed-target routing now selects it for that workflow. The routing expectation in test-projects.test.ts still listed the previous five owners, which turned main's tooling shard red. Add the new owner to the expected target list. (cherry picked from commit 9aecc88) --------- Co-authored-by: LiuwqGit <[email protected]> Co-authored-by: Yigtwxx <[email protected]> Co-authored-by: Vincent Koc <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
…pe is closed" before the agent replies (#148548) Related: #144801, #148025 ## What Problem This Solves Fixes LINE messages failing with “Something went wrong while processing your request” before the agent replies. SMS and Zalo use the same webhook pump. ## User Impact Turns can answer, wait for an exec approval, and answer queued follow-ups after the first turn ends. No configuration or migration is required. ## Why This Change Was Made The ingress drain starts dispatches that outlive the pump. Dispatch now leaves the pump's async-work scope while retaining its existing Gateway root until the task settles. Claim settlement and cancellation are unchanged. Cleanup after dispatch no longer holds the incidental webhook root; independently owned plugin cleanup keeps its own lifetime. ## Evidence - A self-signed POST to `/line/webhook` on an isolated Gateway reproduced `Async work scope is closed` on main `a81fd6123fdc`, with a failed transcript turn and no inference request. - The repaired dispatch completed the same flow with synthetic credentials and a local receiver: ordinary reply, approval prompt, denial, approval-turn answer, queued answer, and next answer. All six sends arrived. The dedicated `openclaw approvals pending` and `openclaw approvals resolve <id> deny` commands drove the real approval. - 251 tests across 23 owner/channel files passed on merge `5384b5a718a2` with main `62a4d0c547bc`. Both new lifetime tests fail with the original production code. Type, lint, format, export, architecture and test-partition checks pass. - The original Bash CI timeout did not reproduce in six focused head/base/merge/parent controls. Full CI remains pending on the repaired head. This pass proves the Gateway and delivery boundary, not live LINE service delivery. The contributor also recorded real LINE push receipts at `138cd4fb4b1b`. ## Consumers The shared monitor and plugin state API use the drain. LINE, SMS and Zalo supply detached webhook pumps; boot-started Discord is a scope-free sibling. Public plugin signatures stay unchanged. ## Dispatch and cleanup ownership The owner's intended boundary is: “the completed pump must not be held open for unrelated follow-ups.” Dispatch leaves the pump's async-work scope and retains an existing live Gateway root until dispatch settles. The incidental webhook root then releases. Required plugin cleanup keeps its separate owner and existing shutdown bounds. The decision to leave the pump scope is made once, by `runClaimed` in `src/channels/message/ingress-drain.ts`. Production changes are +10/−2 lines, net +8, across the dispatch owner and its private storage helper. Claim settlement, cancellation, restart admission, and completed-message deduplication remain unchanged. ## Evidence boundaries The signed `/line/webhook` experiment used a real isolated Gateway, synthetic credentials, deterministic inference, and a local LINE request receiver. It captured an ordinary answer, approval prompt, denial notice, approval-turn answer, queued answer, and next answer. Recipient delivery through the real LINE service is not proved by this experiment. The live green build was `6c7067918343`; production bytes are identical at `2b94019ae275`. The final commit changes only an optional test callback invocation. All 251 selected tests passed on merge `5384b5a718a2`, with parents `2b94019ae275` and main `62a4d0c547bc`. Restoring the original production code makes both new lifetime tests fail. The live approval sequence includes #148228. The fresh merge also includes #148301; its reply-source receipt uses separate state that the dispatch scope exit preserves. The live sequence does not include #148301, and this validation does not claim a new streamed-tail recovery experiment. The earlier Bash failure remains classified as a non-reproduced child startup/import timeout. Six focused head, base, merge, and relevant-parent controls passed. Different hosted runtime and shard conditions prevent treating those local passes as proof that the timeout cannot recur. Hosted CI remains a separate landing check. Co-authored-by: Ayaan Zaidi <[email protected]>
…pe is closed" before the agent replies (openclaw#148548) Related: openclaw#144801, openclaw#148025 ## What Problem This Solves Fixes LINE messages failing with “Something went wrong while processing your request” before the agent replies. SMS and Zalo use the same webhook pump. ## User Impact Turns can answer, wait for an exec approval, and answer queued follow-ups after the first turn ends. No configuration or migration is required. ## Why This Change Was Made The ingress drain starts dispatches that outlive the pump. Dispatch now leaves the pump's async-work scope while retaining its existing Gateway root until the task settles. Claim settlement and cancellation are unchanged. Cleanup after dispatch no longer holds the incidental webhook root; independently owned plugin cleanup keeps its own lifetime. ## Evidence - A self-signed POST to `/line/webhook` on an isolated Gateway reproduced `Async work scope is closed` on main `4e8dd8e1859f`, with a failed transcript turn and no inference request. - The repaired dispatch completed the same flow with synthetic credentials and a local receiver: ordinary reply, approval prompt, denial, approval-turn answer, queued answer, and next answer. All six sends arrived. The dedicated `openclaw approvals pending` and `openclaw approvals resolve <id> deny` commands drove the real approval. - 251 tests across 23 owner/channel files passed on merge `5384b5a718a2` with main `d229f4a2ba41`. Both new lifetime tests fail with the original production code. Type, lint, format, export, architecture and test-partition checks pass. - The original Bash CI timeout did not reproduce in six focused head/base/merge/parent controls. Full CI remains pending on the repaired head. This pass proves the Gateway and delivery boundary, not live LINE service delivery. The contributor also recorded real LINE push receipts at `138cd4fb4b1b`. ## Consumers The shared monitor and plugin state API use the drain. LINE, SMS and Zalo supply detached webhook pumps; boot-started Discord is a scope-free sibling. Public plugin signatures stay unchanged. ## Dispatch and cleanup ownership The owner's intended boundary is: “the completed pump must not be held open for unrelated follow-ups.” Dispatch leaves the pump's async-work scope and retains an existing live Gateway root until dispatch settles. The incidental webhook root then releases. Required plugin cleanup keeps its separate owner and existing shutdown bounds. The decision to leave the pump scope is made once, by `runClaimed` in `src/channels/message/ingress-drain.ts`. Production changes are +10/−2 lines, net +8, across the dispatch owner and its private storage helper. Claim settlement, cancellation, restart admission, and completed-message deduplication remain unchanged. ## Evidence boundaries The signed `/line/webhook` experiment used a real isolated Gateway, synthetic credentials, deterministic inference, and a local LINE request receiver. It captured an ordinary answer, approval prompt, denial notice, approval-turn answer, queued answer, and next answer. Recipient delivery through the real LINE service is not proved by this experiment. The live green build was `6c7067918343`; production bytes are identical at `2b94019ae275`. The final commit changes only an optional test callback invocation. All 251 selected tests passed on merge `5384b5a718a2`, with parents `2b94019ae275` and main `d229f4a2ba41`. Restoring the original production code makes both new lifetime tests fail. The live approval sequence includes openclaw#148228. The fresh merge also includes openclaw#148301; its reply-source receipt uses separate state that the dispatch scope exit preserves. The live sequence does not include openclaw#148301, and this validation does not claim a new streamed-tail recovery experiment. The earlier Bash failure remains classified as a non-reproduced child startup/import timeout. Six focused head, base, merge, and relevant-parent controls passed. Different hosted runtime and shard conditions prevent treating those local passes as proof that the timeout cannot recur. Hosted CI remains a separate landing check. Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #144788
What Problem This Solves
runDetachedWebhookWorkhelper after a turn ends (for example the memory-tencentdb plugin's post-agent_end L1/L2/L3 extraction) always fail withError: Async work scope is closed, so no higher-level memories are ever generated.Why This Change Was Made
runDetachedWebhookWorknow routes its post-ack callback through a detached work continuation: a live parent still synchronously reserves a tracked root (the fence-crossing continuation behavior that fix: keep background completion wakes alive after replies #143866 deliberately preserved for delayed producers), but the callback runs inside a freshAsyncWorkScopeinstead of inheriting the caller's scope, so work tracked from it stays accepted after that scope closes.runWithGatewayIndependentRootWorkContinuation; no new public plugin-sdk surface (the existing helper's documented contract — "its own tracked admission root" with post-ack ordering — is simply honored again).src/process/gateway-work-admission.ts.runWithDetachedAsyncWorkmachinery introduced by fix: keep background completion wakes alive after replies #143866 (already used by session-event wakes and skill review); acknowledgement ordering is unchanged (the callback still starts in the next microtask), and the full gateway-work-admission test file (35 tests) passes unchanged.User Impact
runDetachedWebhookWorkafter agent_end (memory extraction, webhook event processing) completes instead of rejecting with "Async work scope is closed"; restart/suspension drains still wait for it, and the request handler's acknowledgement is still written before processing starts.src/process/gateway-work-admission.ts(runWithGatewayDetachedWorkContinuation),src/plugin-sdk/webhook-request-guards.ts; regression testskeeps tracked work accepted after the caller's async work scope closes(webhook-request-guards.test.ts) andkeeps a detached continuation's reservation while it owns its async lifetime(gateway-work-admission.test.ts).Evidence
aispace/worktrees/issue-144788(upstream main 0b52dc4 + this patch; initially developed against e7ebacf and rebased without conflicts — upstream did not touch the four changed files), Node v26.7.0. Zero-mock real-runtime proof of the exact agent_end webhook lifecycle: a realnode:httpserver on a real socket, requests admitted through the realrunWithGatewayHttpWorkAdmissionchain, a realAsyncWorkScopeas the triggering turn's scope, and the publicrunDetachedWebhookWorkhelper deferring embedded-agent-style tracked work (ambient tracker capture, then a tracked L1-extraction run) past the acknowledgement and past the triggering scope's close. No mocks anywhere on the exercised path.{"ok":true}before any processing), thewebhook:detachedadmission root stays reserved while the deferred work is pending, the triggering turn's async work scope closes while the deferred callback is still running, and the deferred tracked work then completes (L1 extraction: extracted=1, stored=1) instead of rejecting with "Async work scope is closed"; after completion the gateway root work count returns to 0, i.e. the reservation is released once deferred work and cleanup finish. Focused vitest shards on the rebased head are green — webhook-request-guards (incl. the new regression test) and gateway-work-admission 35/35 — andvalidate.sh(oxfmt + oxlint + same-directory tests +tsgo:core) is fully green. The before-run on unpatched origin/main reproduces the exact reporter failure (run() failed: Error: Async work scope is closed) through the same helper chain.Maintainer acceptance and landing scope (2026-09-13)
Accepted the cancellation-lifetime tradeoff identified in the latest review:
runDetachedWebhookWorkexplicitly promises work that survives the HTTP handler returning. Its callback needs a fresh async-work scope as well as its reserved Gateway root. Inheriting the handler's cancellation scope violates that documented post-ack contract. Independent cancellation is intentional here; ordinary independent continuations retain their existing cancellation behavior.The new detached continuation preserves live-parent reservation across admission fences, descendant drain, Gateway affinity, and existing authorization/capability closures. It does not revive retired host capabilities or broaden tool policy. The current Google Chat non-turn webhook and Mattermost model-picker callers already use this post-return contract. Public contract: post-ack webhook work.
Reviewed exact head
6f6370415df781bc784380706969c076e81d22c4against current main and the async-work/admission owners. The contributor's recorded real HTTP/admission/scope trace and added regressions cover this PR's boundary; they are not a live TencentDB, external-provider, or channel-delivery claim. Production delta is +33/-5 lines; the growth introduces one explicit resource-lifetime owner while preserving the ordinary continuation path. Tests add 78 lines.Land this contributor PR intact, then use its helper in a separate
sessions_sendannouncement fix. The latter has independent real Gateway/MCP evidence and remains a separate caller change. Release-note context: fix post-ack webhook work failing withAsync work scope is closedafter the request finishes.