Skip to content

fix(gateway): post-ack webhook work fails with "Async work scope is closed" - #144801

Merged
vincentkoc merged 1 commit into
openclaw:mainfrom
LiuwqGit:feat/issue-144788-detached-webhook-async-scope
Sep 13, 2026
Merged

vincentkoc merged 1 commit into
openclaw:mainfrom
LiuwqGit:feat/issue-144788-detached-webhook-async-scope

Conversation

@LiuwqGit

@LiuwqGit LiuwqGit commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

AI-assisted: yes

Closes #144788

What Problem This Solves

Why This Change Was Made

  • Intended outcome: runDetachedWebhookWork now 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 fresh AsyncWorkScope instead of inheriting the caller's scope, so work tracked from it stays accepted after that scope closes.
  • Out of scope: No changes to other callers of 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).
  • Highest-risk area: admission/root reservation semantics in src/process/gateway-work-admission.ts.
  • How is that risk mitigated? The detached flag only flows into the existing runWithDetachedAsyncWork machinery 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

  • Success criteria: Work started via runDetachedWebhookWork after 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.
  • What should reviewers focus on? src/process/gateway-work-admission.ts (runWithGatewayDetachedWorkContinuation), src/plugin-sdk/webhook-request-guards.ts; regression tests keeps tracked work accepted after the caller's async work scope closes (webhook-request-guards.test.ts) and keeps a detached continuation's reservation while it owns its async lifetime (gateway-work-admission.test.ts).

Evidence

  • Real environment tested: repository worktree at 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 real node:http server on a real socket, requests admitted through the real runWithGatewayHttpWorkAdmission chain, a real AsyncWorkScope as the triggering turn's scope, and the public runDetachedWebhookWork helper 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.
  • Exact steps or commands run after this patch:
    # real-runtime before/after proof (zero mocks; same script both runs)
    # before: git checkout origin/main -- src/plugin-sdk/webhook-request-guards.ts src/process/gateway-work-admission.ts
    # after:  git checkout HEAD --  <same two files>
    node --import ./scripts/tsx.mjs webhook-agent-end-runtime-proof.mts
    # focused regression shards (rebased head, all green)
    node scripts/run-vitest.mjs run src/plugin-sdk/webhook-request-guards.test.ts src/process/gateway-work-admission.test.ts
    skills/fix-pr/scripts/validate.sh src/plugin-sdk/webhook-request-guards.ts src/plugin-sdk/webhook-request-guards.test.ts src/process/gateway-work-admission.ts src/process/gateway-work-admission.test.ts
  • Evidence after fix: (first: unpatched origin/main, same real-HTTP agent_end flow — the deferred plugin callback's tracked L1 extraction is rejected with the reporter's exact error; second: this patch, same flow — deferred tracked work completes after the triggering scope closed and the gateway reservation is released afterwards)
    # BEFORE (origin/main):
    [2026-09-11T09:36:19.806Z] server: POST /webhook/agent-end received
    [2026-09-11T09:36:19.808Z] handler: acknowledgement written (200 OK)
    [2026-09-11T09:36:19.809Z] plugin callback: started (after ack)
    [2026-09-11T09:36:19.809Z] handler: triggering turn settled (its async work scope closed)
    [2026-09-11T09:36:19.815Z] handler: gateway root work holders while deferred work pending: ["http:request","webhook:detached"]
    [2026-09-11T09:36:19.826Z] client: ack response 200 {"ok":true}
    [2026-09-11T09:36:19.861Z] plugin callback: invoking tracked L1 extraction
    [2026-09-11T09:36:19.878Z] RESULT: FAIL - deferred tracked work rejected: Async work scope is closed
    
    # AFTER (this patch):
    [2026-09-11T09:36:30.487Z] server: POST /webhook/agent-end received
    [2026-09-11T09:36:30.489Z] handler: acknowledgement written (200 OK)
    [2026-09-11T09:36:30.490Z] plugin callback: started (after ack)
    [2026-09-11T09:36:30.490Z] handler: triggering turn settled (its async work scope closed)
    [2026-09-11T09:36:30.492Z] handler: gateway root work holders while deferred work pending: ["http:request","webhook:detached"]
    [2026-09-11T09:36:30.499Z] client: ack response 200 {"ok":true}
    [2026-09-11T09:36:30.541Z] plugin callback: invoking tracked L1 extraction
    [2026-09-11T09:36:30.572Z] plugin callback: tracked work COMPLETED -> L1 extraction: extracted=1, stored=1
    [2026-09-11T09:36:30.575Z] RESULT: PASS - deferred tracked work completed after the triggering scope closed: L1 extraction: extracted=1, stored=1
    [2026-09-11T09:36:30.575Z] RESULT: gateway root work count after deferred completion: 0
    
  • Observed result after fix: in the real-HTTP agent_end flow the request is still acknowledged first (200 {"ok":true} before any processing), the webhook:detached admission 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 — and validate.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.
  • What was not tested: no live memory-tencentdb plugin install / real TencentDB + tencent-maas provider turn was exercised (needs external TencentDB and model credentials); the real-runtime proof above drives the exact public helper + admission + async-work-scope chain the plugin hits — real socket, real HTTP admission, real scopes, real timers — with a plugin-shaped deferred callback, per the issue's source-level analysis.
  • Proof tier: L2 (real-runtime before/after on a real socket through the real admission chain, deterministic terminal output, plus deterministic boundary regression tests).
  • Proof limitations: end-to-end plugin memory generation with a real TencentDB/model provider was not tested. The available CI receipt does not establish that external integration behavior.
  • Review state: Exact-head CI is green; native maintainer preparation and a fresh ClawSweeper review are in progress.

Maintainer acceptance and landing scope (2026-09-13)

Accepted the cancellation-lifetime tradeoff identified in the latest review: runDetachedWebhookWork explicitly 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 6f6370415df781bc784380706969c076e81d22c4 against 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_send announcement fix. The latter has independent real Gateway/MCP evidence and remains a separate caller change. Release-note context: fix post-ack webhook work failing with Async work scope is closed after the request finishes.

@clawsweeper

clawsweeper Bot commented Sep 11, 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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@clawsweeper

clawsweeper Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 13, 2026, 11:34 AM ET / 15:34 UTC (Revision 3).

ClawSweeper review

What this changes

Give 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
Reviewed head: 6f6370415df781bc784380706969c076e81d22c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with convincing boundary proof, meaningful regressions, and an explicitly accepted compatibility tradeoff.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The pinned-head real HTTP trace exercises the public webhook helper, Gateway admission, and actual async scopes; deferred tracking succeeds after parent closure and all roots release. Live TencentDB/provider behavior is explicitly outside this proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The pinned-head real HTTP trace exercises the public webhook helper, Gateway admission, and actual async scopes; deferred tracking succeeds after parent closure and all roots release. Live TencentDB/provider behavior is explicitly outside this proof.
Evidence reviewed 10 items Introduced change and continuity: The verified merge-base-to-head diff changes only the webhook helper, continuation implementation, and their regressions. The previously reviewed head equals the current checkout; the prior review had no findings.
Current-main necessity: Fetched main still routes the public helper through the ordinary independent continuation, which creates its root without detachedWork. Closing the inherited AsyncWorkScope therefore still rejects later tracked work.
Latest-release comparison: The supplied latest release, v2026.9.4, also uses the non-detached continuation; this repair is not present there.
Findings None None.
Security None None.

How this fits together

The 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]
Loading

Before merge

  • Resolve merge risk (P1) - Third-party callbacks that relied on inherited request cancellation can continue longer after this change; maintainer acceptance is recorded, but individual external plugin assumptions remain unknown.
Agent review details

Security

None.

PR surface

Source +28, Tests +78. Total +106 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 33 5 +28
Tests 2 78 0 +78
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 111 5 +106

Review metrics

Metric Value Why it matters
Cancellation contract 1 public helper changes lifetime; ordinary continuations remain unchanged The compatibility effect is confined to the explicitly detached webhook contract accepted in maintainer discussion.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #144788
Summary: This is the maintainer-selected candidate for the webhook lifetime report; the alternative helper PR overlaps, while automatic-reset work adds a separate caller.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Retain the accepted detached lifetime (recommended)
    Proceed with the recorded maintainer acceptance that explicitly detached webhook callbacks survive requester-scope cancellation.

Technical review

Best 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.

Labels

Label justifications:

  • P1: The reported release regression prevents deferred plugin processing and higher-level memory generation.
  • merge-risk: 🚨 compatibility: The public helper intentionally stops inheriting requester cancellation, an accepted change that external plugins may observe.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The pinned-head real HTTP trace exercises the public webhook helper, Gateway admission, and actual async scopes; deferred tracking succeeds after parent closure and all roots release. Live TencentDB/provider behavior is explicitly outside this proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The pinned-head real HTTP trace exercises the public webhook helper, Gateway admission, and actual async scopes; deferred tracking succeeds after parent closure and all roots release. Live TencentDB/provider behavior is explicitly outside this proof.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-09-11T09:05:47.389Z sha 457ce744b21e6d7ff3736b52575c73dac1490ff0 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-11T09:45:41.858Z sha 6f63704 :: blocked before merge. :: none

…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
@LiuwqGit
LiuwqGit force-pushed the feat/issue-144788-detached-webhook-async-scope branch from 457ce74 to 6f63704 Compare September 11, 2026 09:37
@LiuwqGit

Copy link
Copy Markdown
Contributor Author

Real-behavior proof for the "deferred tracked work completing after the triggering scope closes" gap, run on the rebased head (6f6370415df, upstream main 0b52dc467b3 + this patch):

Zero-mock real-runtime flow mirroring the memory-tencentdb agent_end lifecycle — a real node:http server on a real socket, admitted through the real runWithGatewayHttpWorkAdmission chain, with a real AsyncWorkScope as the triggering turn's scope and the public runDetachedWebhookWork helper deferring a plugin-shaped tracked callback (ambient tracker capture + tracked L1-extraction run) past the acknowledgement and past the scope's close.

Before (unpatched origin/main), same script — reproduces the reporter's exact failure:

[09:36:19.808Z] handler: acknowledgement written (200 OK)
[09:36:19.809Z] plugin callback: started (after ack)
[09:36:19.809Z] handler: triggering turn settled (its async work scope closed)
[09:36:19.815Z] handler: gateway root work holders while deferred work pending: ["http:request","webhook:detached"]
[09:36:19.826Z] client: ack response 200 {"ok":true}
[09:36:19.861Z] plugin callback: invoking tracked L1 extraction
[09:36:19.878Z] RESULT: FAIL - deferred tracked work rejected: Async work scope is closed

After (this patch), same flow:

[09:36:30.489Z] handler: acknowledgement written (200 OK)
[09:36:30.490Z] plugin callback: started (after ack)
[09:36:30.490Z] handler: triggering turn settled (its async work scope closed)
[09:36:30.492Z] handler: gateway root work holders while deferred work pending: ["http:request","webhook:detached"]
[09:36:30.499Z] client: ack response 200 {"ok":true}
[09:36:30.541Z] plugin callback: invoking tracked L1 extraction
[09:36:30.572Z] plugin callback: tracked work COMPLETED -> L1 extraction: extracted=1, stored=1
[09:36:30.575Z] RESULT: PASS - deferred tracked work completed after the triggering scope closed: L1 extraction: extracted=1, stored=1
[09:36:30.575Z] RESULT: gateway root work count after deferred completion: 0

What this shows end-to-end on the real admission chain:

  1. Ack-first ordering preserved — the 200 acknowledgement is written before any deferred processing runs.
  2. Deferred tracked work completes after the triggering scope closes — the AsyncWorkScope is closed rejection is gone; the captured tracker invokes into a fresh detached scope.
  3. Gateway reservation lifecycle — the webhook:detached root stays reserved while the deferred work is pending and is released after the deferred work (and its descendants) finish (root work count back to 0).

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), validate.sh fully green. The previous head's security-sensitive-guard-detect / dependency-guard-detect failures were GitHub API 500 Internal Server Errors (infra flake visible in the job logs); the rebase + re-push re-triggers them.

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 clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@obviyus obviyus self-assigned this Sep 11, 2026
@vincentkoc vincentkoc self-assigned this Sep 13, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Please review the unchanged exact head 6f6370415df781bc784380706969c076e81d22c4. The prior completion is older than the native landing gate's 12-hour window. The PR body now records maintainer acceptance of the explicitly detached callback's independent cancellation lifetime, with ordinary continuations and capability closures preserved. The recorded real HTTP/admission/scope proof remains scoped to this helper; no live TencentDB/provider claim is added.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

VasuBansal7576 added a commit to VasuBansal7576/openclaw that referenced this pull request Sep 13, 2026
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.
@vincentkoc
vincentkoc merged commit 48ed702 into openclaw:main Sep 13, 2026
547 of 549 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

vincentkoc added a commit that referenced this pull request Sep 13, 2026
* 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)
  ...
vincentkoc added a commit that referenced this pull request Sep 13, 2026
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.
vincentkoc added a commit that referenced this pull request Sep 13, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…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
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 14, 2026
…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]>
obviyus added a commit that referenced this pull request Sep 15, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 15, 2026
…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]>
@LiuwqGit
LiuwqGit deleted the feat/issue-144788-detached-webhook-async-scope branch September 22, 2026 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: runDetachedWebhookWork no longer acquires an AsyncWorkScope in 2026.9.4, breaking async post-agent_end embedded-agent work

3 participants