Skip to content

fix: preserve async scope for detached webhook work - #144806

Closed
sunlit-deng wants to merge 3 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/issue-144788
Closed

sunlit-deng wants to merge 3 commits into
openclaw:mainfrom
sunlit-deng:sunlit/fix/issue-144788

Conversation

@sunlit-deng

@sunlit-deng sunlit-deng commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where plugins that schedule post-ack webhook work could fail with Async work scope is closed after the triggering request scope closed.

Fixes #144788

Why This Change Was Made

runDetachedWebhookWork now uses a detached continuation: it reserves the root synchronously from the live parent, including across a closed suspension fence, while executing the callback in a fresh async work scope. This preserves acknowledgement ordering and drain accounting.

User Impact

Deferred webhook/plugin work can complete after the triggering request scope closes without becoming untracked or rejected.

Evidence

  • Real call-chain loopback proof: node --import ./scripts/tsx.mjs webhook-agent-end-runtime-proof.mts started a real TCP/HTTP server and exercised runWithGatewayHttpWorkAdmission through the public runDetachedWebhookWork helper. No external credentials or private data were used.
  • The same script and input on pinned base 227e7ae2 reproduced Async work scope is closed (exit 1); on this head it completed successfully (exit 0).
  • The webhook:detached root remained reserved while the triggering scope was closed and was released after tracked work completed. The unchanged inherited-admission negative control still rejects with Gateway is draining.
$ node --import ./scripts/tsx.mjs webhook-agent-end-runtime-proof.mts
base 227e7ae26af4e4f3f8a256c4fa808c7b046f4c88 (exit 1): result: rejected: Error: Async work scope is closed
head e9d92f7a5d758f019b1f42fd31ad83f13708169d (exit 0):
ack written (200 OK)
plugin callback started (after ack)
triggering turn settled (async work scope closed)
gateway holders while deferred work pending: ["http:request","webhook:detached"]
client received ack 200 {"ok":true}
tracked L1 extraction completed
result: L1 extraction: extracted=1, stored=1
gateway root work count after completion: 0
webhook-agent-end-runtime-proof.mts
import { createServer, request } from "node:http";
import { setTimeout as delay } from "node:timers/promises";
import { AsyncWorkScope, captureAsyncWorkTracker } from "./src/shared/async-work-scope.js";
import { runWithGatewayHttpWorkAdmission } from "./src/gateway/server/http-work-admission.js";
import {
  getActiveGatewayRootWorkCount,
  getActiveGatewayRootWorkHolders,
  resetGatewayWorkAdmission,
} from "./src/process/gateway-work-admission.js";
import { runDetachedWebhookWork } from "./src/plugin-sdk/webhook-request-guards.js";

const events: string[] = [];
let releaseProcessing!: () => void;
const processingGate = new Promise<void>((resolve) => {
  releaseProcessing = resolve;
});
let resolvePending!: () => void;
const pendingReady = new Promise<void>((resolve) => {
  resolvePending = resolve;
});
let detached: Promise<string> | undefined;

const server = createServer((_req, res) => {
  void (async () => {
    const triggeringScope = new AsyncWorkScope();
    await runWithGatewayHttpWorkAdmission(res, async () => {
      await triggeringScope.track(async () => {
        detached = runDetachedWebhookWork(async () => {
          events.push("plugin callback started (after ack)");
          const trackOwner = captureAsyncWorkTracker();
          await delay(25);
          await processingGate;
          return await trackOwner(async () => {
            events.push("tracked L1 extraction completed");
            return "L1 extraction: extracted=1, stored=1";
          });
        });
        res.statusCode = 200;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ ok: true }));
        events.push("ack written (200 OK)");
        return true;
      });
      await triggeringScope.drain();
      events.push("triggering turn settled (async work scope closed)");
      events.push(
        `gateway holders while deferred work pending: ${JSON.stringify(getActiveGatewayRootWorkHolders())}`,
      );
      resolvePending();
      return true;
    });
  })().catch((error: unknown) => {
    events.push(`server error: ${String(error)}`);
  });
});

const listen = (): Promise<number> =>
  new Promise((resolve, reject) => {
    server.once("error", reject);
    server.listen(0, "127.0.0.1", () => {
      const address = server.address();
      if (!address || typeof address === "string") {
        reject(new Error("server did not bind to a TCP port"));
        return;
      }
      resolve(address.port);
    });
  });

const readResponse = (port: number): Promise<{ statusCode: number; body: string }> =>
  new Promise((resolve, reject) => {
    const client = request(
      {
        hostname: "127.0.0.1",
        port,
        method: "POST",
        path: "/webhook/agent-end",
        headers: { "Content-Type": "application/json" },
      },
      (res) => {
        const chunks: Buffer[] = [];
        res.on("data", (chunk: Buffer) => chunks.push(chunk));
        res.on("end", () =>
          resolve({
            statusCode: res.statusCode ?? 0,
            body: Buffer.concat(chunks).toString("utf8"),
          }),
        );
      },
    );
    client.on("error", reject);
    client.end(JSON.stringify({ event: "agent_end" }));
  });

let failure: unknown;
resetGatewayWorkAdmission();
try {
  const port = await listen();
  const response = await readResponse(port);
  await pendingReady;
  events.push(`client received ack ${response.statusCode} ${response.body}`);
  releaseProcessing();
  const result = await detached;
  events.push(`result: ${result}`);
  events.push(`gateway root work count after completion: ${getActiveGatewayRootWorkCount()}`);
} catch (error: unknown) {
  failure = error;
  events.push(`result: rejected: ${String(error)}`);
} finally {
  await new Promise<void>((resolve) => server.close(() => resolve()));
  resetGatewayWorkAdmission();
}
for (const event of events) {
  console.log(event);
}
if (failure) {
  throw failure;
}

AI-assisted: built with Codex

@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. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. 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 11, 2026, 7:01 PM ET / 23:01 UTC (Revision 3).

ClawSweeper review

What this changes

The PR gives deferred webhook processing its own async-work scope while preserving immediate work reservation, acknowledgement ordering, and drain accounting.

Regression provenance

Possible regression — suspected (failure trace). No predecessor PR is attributed.

Merge readiness

⛔ Blocked before merge - 3 items remain

The previous P1 finding is resolved, and the current-head runtime evidence is sufficient. Current main and the latest release still need this repair. The overlapping PR retains the same unresolved cancellation-compatibility choice, so it is not yet a safe superseding target.

Likely related people: steipete (unverified routing candidate, medium confidence).

Priority: P1
Reviewed head: e9d92f7a5d758f019b1f42fd31ad83f13708169d
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with sufficient production-boundary proof and no remaining code findings; compatibility acceptance remains separate from patch quality.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied current-head trace drives a real HTTP client through production HTTP admission and the public webhook helper, showing acknowledgement first, requester-scope closure, successful deferred tracking, and zero remaining roots; it proves lifecycle recovery, not actual provider-backed memory extraction.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied current-head trace drives a real HTTP client through production HTTP admission and the public webhook helper, showing acknowledgement first, requester-scope closure, successful deferred tracking, and zero remaining roots; it proves lifecycle recovery, not actual provider-backed memory extraction.
Evidence reviewed 9 items Current main remains affected: Fetched main still routes the public helper through the independent continuation, whose root creation defaults to retaining the caller's async scope.
Latest release remains affected: Inspection of v2026.9.4 shows the same independent-continuation call. This is not an implemented-on-main or already-shipped close.
Existing public contract: The documented helper reserves a root synchronously, starts the callback in the next microtask, adopts its result, and keeps background work visible to drains. The repair preserves its signature and uses the existing detached-scope owner.
Findings None None.
Security None None.

How this fits together

Plugins use the webhook helper to acknowledge HTTP requests before background processing finishes. Gateway work admission tracks that processing and its descendants so suspension and restart can account for unfinished work.

flowchart TD
  A[Admitted webhook request] --> B[Reserve background work]
  B --> C[Write acknowledgement]
  B --> D[Create independent async scope]
  D --> E[Run deferred callback]
  E --> F[Finish tracked descendants]
  F --> G[Release work reservation]
Loading

Decision needed

Question Recommendation
Should the existing public webhook helper intentionally stop inheriting caller cancellation when it acquires its own async-work scope? Accept the detached lifetime: Accept cancellation isolation for this explicitly detached helper, supported by the completion-and-cleanup trace and preservation of ordinary continuation behavior.

Why: This repairs the documented post-ack lifetime, but changes an observable ambient signal for existing third-party callbacks; compatibility acceptance belongs to the SDK/admission owner.

Before merge

  • Resolve merge risk (P1) - After upgrade, webhook callbacks using the ambient async-work signal will no longer receive cancellation when their triggering scope closes; plugins relying on that behavior could continue work longer.
  • Complete next step (P2) - Obtain SDK/admission-owner acceptance that detached webhook callbacks intentionally outlive their caller's cancellation signal.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +28, Tests +64. Total +92 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 33 5 +28
Tests 1 64 0 +64
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 97 5 +92

Review metrics

None.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #144788
Summary: This PR and the overlapping open implementation address the canonical report's inherited closed-scope failure.

Members:

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

Merge-risk options

Maintainer options:

  1. Accept cancellation isolation for detached callbacks (recommended)
    Record owner acceptance that this public helper outlives caller cancellation while retaining drain accounting.
  2. Pause for a different cancellation contract
    Keep both implementation candidates unmerged if caller cancellation must remain observable to detached callbacks.

Technical review

Best possible solution:

Preserve the existing public helper and accept its explicitly detached cancellation lifetime while keeping ordinary continuations tied to their callers and all descendants visible to drains.

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

Yes: capture the ambient tracker inside deferred webhook work, close the triggering scope, then invoke tracked work. Current-main source explains the rejection, and the contributor supplies matching before/after HTTP traces; this review did not execute code.

Is this the best way to solve the issue?

Yes, subject to cancellation compatibility acceptance: reusing the existing detached-scope machinery repairs the owner boundary without adding a public SDK API or changing unrelated continuations.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 92c01b7e86de.

Labels

Label justifications:

  • P1: The linked report describes deferred plugin memory extraction failing consistently on the current release.
  • merge-risk: 🚨 compatibility: The existing public helper now supplies an independent cancellation signal instead of inheriting its caller's signal.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 supplied current-head trace drives a real HTTP client through production HTTP admission and the public webhook helper, showing acknowledgement first, requester-scope closure, successful deferred tracking, and zero remaining roots; it proves lifecycle recovery, not actual provider-backed memory extraction.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied current-head trace drives a real HTTP client through production HTTP admission and the public webhook helper, showing acknowledgement first, requester-scope closure, successful deferred tracking, and zero remaining roots; it proves lifecycle recovery, not actual provider-backed memory extraction.

Evidence

What I checked:

  • Current main remains affected: Fetched main still routes the public helper through the independent continuation, whose root creation defaults to retaining the caller's async scope. (src/plugin-sdk/webhook-request-guards.ts:318, 92c01b7e86de)
  • Latest release remains affected: Inspection of v2026.9.4 shows the same independent-continuation call. This is not an implemented-on-main or already-shipped close. (src/plugin-sdk/webhook-request-guards.ts:318, 3a9d69db306c)
  • Existing public contract: The documented helper reserves a root synchronously, starts the callback in the next microtask, adopts its result, and keeps background work visible to drains. The repair preserves its signature and uses the existing detached-scope owner. Public docs: docs/plugins/sdk-overview/infrastructure.md. (docs/plugins/sdk-overview/infrastructure.md:104, e9d92f7a5d75)
  • Previous blocker resolved: The pinned introduced patch now reserves a detached root synchronously from a live parent, including across closed fences. The new public-helper test checks reservation across suspension; existing admission tests cover restart rejection and cleanup. Historical comparison and blame encountered unavailable blobs, so no exact earlier-line attribution is claimed. (src/process/gateway-work-admission.ts:526, e9d92f7a5d75)
  • Current-head real runtime proof: The supplied body snapshot, sourceRevision 8e8d7d4d2446ceeec32513d168bf4e6630a127a29286afa388ab452cb7ddec12, includes the complete loopback script and a trace naming the current head. A real HTTP client exercises HTTP admission and the public helper: acknowledgement precedes processing, the requester scope closes, deferred tracked work completes, and root count returns to zero. The extraction result is a synthetic callback value, not proof of TencentDB or provider execution. The embedded script was inspected, not executed. (e9d92f7a5d75)
  • Cancellation compatibility: The helper now selects detachedWork=true, which creates a fresh AsyncWorkScope and cancellation signal. Ordinary independent continuations retain detachedWork=false. Existing detached-work tests explicitly assert that the background signal differs from the foreground signal and remains un-aborted after foreground closure. (src/process/gateway-work-admission.ts:146, e9d92f7a5d75)

Likely related people:

  • steipete: 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:22:13.740Z sha 39efc38 :: needs real behavior proof before merge. :: [P1] Preserve live-parent reservation when detaching the async scope
  • reviewed 2026-09-11T11:50:07.119Z sha 39efc38 :: needs real behavior proof before merge. :: [P1] Preserve live-parent reservation when detaching the async scope

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 11, 2026
@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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 11, 2026
@vincentkoc vincentkoc self-assigned this Sep 13, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Thanks @sunlit-deng for the independent fix, suspension-fence regression, and real HTTP lifetime trace. The equivalent production repair has now landed through #144801 as 48ed702. The detached cancellation contract was accepted in that review, and fresh exact-head CI and Workflow Sanity passed. Closing this as superseded by the landed canonical fix.

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: XS 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

2 participants