Skip to content

fix(gateway): harden hook admission and shutdown - #125893

Merged
steipete merged 4 commits into
mainfrom
steipete/blissful-merkle-7ad022
Aug 18, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/blissful-merkle-7ad022

Conversation

@steipete

@steipete steipete commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where Gateway and plugin webhook callers could receive a reset without the structured 413/408 body when an oversized or timed-out request was terminated before the response transport closed.

It also fixes two shutdown/admission inconsistencies: deferred /hooks/wake requests accepted an explicit session even though next-heartbeat delivery is owned by the agent main session, and a direct Gateway close could remain startup-ready while shutdown was already underway. When multiple HTTP listeners were present, one incomplete close could also prevent later listeners from being closed.

Why This Change Was Made

The repair puts response-first request closing in the shared HTTP-body owner and reuses it from Gateway, installed plugin guards, and plugin webhook readers. Hook normalization now rejects next-heartbeat plus sessionKey; the generation-local lifecycle state marks direct close as draining immediately; and HTTP listener shutdown independently settles every listener before propagating an incomplete-close failure.

The branch was rebased after review so current main’s five-second agent-harness disposal bound and never-settling regression remain intact. The scope is deliberately bounded: no storage, SQLite schema/version, Gateway protocol field, durable replay/idempotency design, dependency, generated-file, or release-note change.

User Impact

Operators now receive complete structured 413/408 hook and plugin-webhook errors before terminal connection closure. Deferred wake requests cannot misleadingly target an explicit session, health probes report draining as soon as a direct close begins, every bound HTTP listener gets a shutdown attempt even when another listener is stuck, and a stuck agent harness cannot block listener teardown.

Evidence

  • Current-head focused proof: node scripts/run-vitest.mjs src/infra/http-body.test.ts src/plugin-sdk/webhook-request-guards.test.ts src/gateway/hooks.test.ts src/gateway/http-common.test.ts src/gateway/server-close.test.ts src/gateway/server-http.hooks-request-timeout.test.ts src/gateway/server-kernel.test.ts src/gateway/server.hooks-admission.test.ts src/gateway/http-common.fuzz.test.ts extensions/feishu/src/monitor.webhook-security.test.ts passed 10 files / 196 tests after rebase.
  • Full Feishu raw-socket coverage now requires complete 413 and 408 status, headers, and bodies before the terminal connection event; the prior bare-ECONNRESET allowance is gone.
  • node scripts/run-vitest.mjs extensions/telegram/src/miniapp/routes.test.ts passed 14/14 after its request double was updated to model response transport close.
  • Changed TypeScript passed direct oxfmt and oxlint; git diff --check passed. Fresh branch-wide Codex autoreview against origin/main and the follow-up Telegram autoreview were clean with no accepted/actionable findings.
  • Final exact-head hosted CI is green for a2581370489c40da51cf92b5205cb1656fcb134f: https://github.com/openclaw/openclaw/actions/runs/32165730816
  • The local changed gate passed guards, formatting, SDK, boundary, and dead-export stages. Its core typecheck remains blocked only by unrelated stale undici/undici-types conflicts in src/agents/mcp-oauth-fetch.ts, src/gateway/mcp-app-standalone.ts, and src/infra/net/**; no changed-file type errors were reported. Exact-head hosted CI is authoritative for the clean dependency environment.
  • Production LOC: +98/-64 (net +34). Tests: +319/-39 (net +280). Docs: +2/-2. Shrink-only assertion-safety baseline: +1/-1.
  • ClawSweeper’s two P1 findings and all derived rank-up moves were applied: installed guards use the shared response-close owner with real plugin proof; current main’s bounded harness disposal remains; redundant immediate guard destruction was removed; and production growth is limited to the shared ownership/lifecycle capabilities.
  • AI-assisted maintainer repair; the implementation and proof were reviewed before publication.

@clawsweeper

clawsweeper Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels Aug 18, 2026
@steipete
steipete marked this pull request as ready for review August 18, 2026 16:21
@openclaw-barnacle openclaw-barnacle Bot added size: M maintainer Maintainer-authored PR labels Aug 18, 2026
@steipete

steipete commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Land-ready evidence

Verified head: a2581370489c40da51cf92b5205cb1656fcb134f

Root cause and best-fix verdict

The repair closes four owner gaps: the shared HTTP-body path could terminate oversized/timed-out requests before response transport closure; the installed plugin guard still destroyed immediately; deferred wakes accepted an explicit session despite main-session next-heartbeat ownership; and direct-close readiness plus multi-listener shutdown lacked generation-local/all-listener ownership.

This is the best fix, not a downstream mitigation. Shared response-close policy now owns Gateway readers, installed plugin guards, and plugin webhook readers; hook normalization owns the invalid mode/session combination; lifecycle state owns direct-close draining; and listener teardown independently settles every listener. Immediate request destruction, consumer-only guards, and sequential listener closure were rejected because they retain response loss or incomplete cleanup.

ClawSweeper rank-up moves

Latest completed review: #125893 (comment)

All eight moves were applied; none were skipped:

  • Installed body-limit guard now calls the shared response-close owner and removes immediate req.destroy().
  • Feishu raw-socket tests require complete 413 and 408 status, headers, and bodies before the terminal connection event; bare ECONNRESET is no longer accepted.
  • The branch was rebased onto current main so fix(gateway): enforce shutdown deadline during event-loop stalls #125863’s five-second agent-harness disposal bound and never-settling regression remain intact.
  • Both derived availability/merge risks are resolved.
  • Production growth is +98/-64 (net +34); the added capability is shared response/lifecycle ownership, and redundant installed-guard close logic was deleted.
  • The requested P2 next step and both patch-quality proofs are complete.

The review is under 12 hours old and all post-review pushes were limited to its findings, the required conflict rebase, and the resulting sibling-test correction, so policy does not require a re-review request.

Local proof

  • node scripts/run-vitest.mjs src/infra/http-body.test.ts src/plugin-sdk/webhook-request-guards.test.ts src/gateway/hooks.test.ts src/gateway/http-common.test.ts src/gateway/server-close.test.ts src/gateway/server-http.hooks-request-timeout.test.ts src/gateway/server-kernel.test.ts src/gateway/server.hooks-admission.test.ts src/gateway/http-common.fuzz.test.ts extensions/feishu/src/monitor.webhook-security.test.ts — 10 files / 196 tests passed after rebase.
  • node scripts/run-vitest.mjs extensions/telegram/src/miniapp/routes.test.ts — 1 file / 14 tests passed after the response-close test-double correction.
  • Direct oxfmt and oxlint over changed TypeScript — passed.
  • git diff --check — passed.
  • .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main — clean; no accepted/actionable findings.
  • Follow-up Telegram .agents/skills/autoreview/scripts/autoreview --mode local — clean.
  • Changed gate — all guard, format, SDK, boundary, and dead-export stages passed. Core typecheck was blocked only by unrelated stale undici/undici-types conflicts in untouched src/agents/mcp-oauth-fetch.ts, src/gateway/mcp-app-standalone.ts, and src/infra/net/**; no changed-file type errors.

Hosted CI, Testbox, and retries

Scope, size, and proof gaps

Production LOC: +98/-64 (net +34). Tests: +319/-39 (net +280). Docs: +2/-2. Shrink-only assertion-safety baseline: +1/-1.

No storage behavior, SQLite schema/version, protocol field, durable replay/idempotency design, dependency, generated-file, or release-note change is included.

Known gap: no operator-owned live Gateway was restarted or mutated. This bounded deterministic HTTP/lifecycle repair instead has real raw-socket Gateway and Feishu response-order proof, shutdown lifecycle regressions, 210 focused passing tests across the final local commands, exact-head hosted CI, and native Testbox gate reuse. No external provider API is involved.

@clawsweeper

clawsweeper Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 18, 2026, 12:36 PM ET / 16:36 UTC.

ClawSweeper review

What this changes

Updates Gateway and plugin webhook body-limit handling, deferred wake admission, draining readiness, and multi-listener shutdown behavior.

Merge readiness

⛔ Blocked by patch quality or review findings - 8 items remain

Keep open: the patch leaves the installed plugin webhook guard able to reset 413/408 responses and removes current main’s bounded agent-harness shutdown.

Priority: P1
Reviewed head: 42254ec7b93b363b9bcdb6535ebfba828601539c

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Focused coverage supports part of the change, but two P1 owner-boundary regressions block merge.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored reliability PR is exempt from the external contributor proof gate; its committed real-socket Gateway test does not cover the remaining installed-guard path.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored reliability PR is exempt from the external contributor proof gate; its committed real-socket Gateway test does not cover the remaining installed-guard path.
Evidence reviewed 7 items Shared helper is not applied to the installed guard: The new response-first helper is added here, but the installed request-body guard still ends its error response and immediately destroys the request, so the claimed shared owner does not cover that owner path.
Plugin webhook path remains reachable: Feishu installs the unchanged guard before its body reader; Slack HTTP does the same before handing the request to Bolt.
Existing transport test permits the failure: The Feishu real-socket oversized-body test explicitly accepts ECONNRESET instead of requiring the complete 413 response, confirming the remaining behavior is not covered by the new Gateway-only proof.
Findings 2 actionable findings [P1] Apply response-first closure in the installed limit guard
[P1] Retain bounded agent-harness disposal
Security None None.

Live Verification

Command: pnpm test src/gateway/server.hooks-admission.test.ts

Result: FAIL (partial) — step 2 expect_output flushes an oversized chunked hook response before closing the socket: expected terminal output was not visible within 30 seconds: "flushes an oversized chunked hook response before closing the socket"

pnpm test src/gateway/server.hooks-admission.test.ts
runner@runnervmzvulz:/tmp/clawsweeper-live-proof-125893-4hyl7M/target$ pnpm test src/gateway/server.hooks-admission.test.ts
$ node --import tsx scripts/test-projects.mts src/gateway/server.hooks-admission.test.ts
pnpm test src/gateway/server.hooks-admission.test.ts
[test] starting test/vitest/vitest.gateway.config.ts

 RUN  v4.1.10 /tmp/clawsweeper-live-proof-125893-4hyl7M/target












































Assertions:

  • FAIL expect_output: flushes an oversized chunked hook response before closing the socket

How this fits together

Gateway HTTP handlers and plugin webhook transports read untrusted request bodies before dispatching work or returning structured errors. Gateway lifecycle code also transitions health probes to draining and tears down listeners and runtime owners during shutdown.

flowchart LR
A[Webhook client] --> B[Gateway or plugin body reader]
B --> C{Body limit or timeout?}
C -->|yes| D[Structured HTTP error]
D --> E[Flush response then close socket]
C -->|no| F[Hook dispatch]
G[Gateway shutdown] --> H[Draining state and listener cleanup]
Loading

Before merge

  • Apply response-first closure in the installed limit guard (P1) - The new helper only covers reader callers. installRequestBodyLimitGuard still sends the 413/408 and immediately destroys the request, which is the path Feishu and Slack install before their readers; Feishu’s socket test currently permits ECONNRESET. Arm the post-finish closer there and require the complete response before socket close.
  • Retain bounded agent-harness disposal (P1) - This replaces current main’s five-second disposal grace with an unbounded await disposeRegisteredAgentHarnesses(). A registered harness whose dispose() never resolves now blocks all later cleanup and prevents Gateway close from completing; keep the grace wrapper and add a never-settling harness regression.
  • Resolve merge risk (P1) - Plugin webhook callers using the installed limit guard can still receive a reset instead of the promised complete 413/408 response.
  • Resolve merge risk (P1) - Replacing the current-main grace race with an unbounded harness-disposal await can stall Gateway shutdown.
  • Resolve merge risk (P1) - Production code is net +36 lines; shared ownership may justify it, but the repair should avoid retaining redundant per-owner close logic.
  • Complete next step (P2) - This maintainer-labeled PR needs the two defined owner-boundary repairs before normal merge review.
  • Improve patch quality - Make installed guard failures flush before socket destruction and prove a full plugin 413/408 response.
  • Improve patch quality - Restore bounded agent-harness disposal and test a never-settling harness.

Findings

  • [P1] Apply response-first closure in the installed limit guard — src/infra/http-body.ts:159-169
  • [P1] Retain bounded agent-harness disposal — src/gateway/server-close.ts:908
Agent review details

Security

None.

PR surface

Source +36, Tests +246, Docs 0, Other 0. Total +282 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 8 95 59 +36
Tests 8 260 14 +246
Docs 2 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 19 358 76 +282

Review metrics

Metric Value Why it matters
Production versus test delta production +95/-59 (net +36); tests +252/-13 (net +239) The added shared HTTP and shutdown behavior has positive runtime growth, so the final repair should preserve consolidation rather than add another parallel path.

Merge-risk options

Maintainer options:

  1. Repair the shared limit and shutdown owners (recommended)
    Route installed guard failures through response-first closure and restore the bounded harness-disposal race with focused real-listener regressions.

Technical review

Best possible solution:

Apply the shared post-finish close policy to every body-limit owner, retain grace-bounded harness disposal, and prove both with real listener regressions.

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

Yes—source establishes both paths: the installed guard destroys the request immediately after a 413/408, and agent-harness disposal can await a never-settling promise.

Is this the best way to solve the issue?

No; the response-first invariant must be enforced in the installed guard as well as reader helpers, and the existing bounded harness cleanup must remain.

Full review comments:

  • [P1] Apply response-first closure in the installed limit guard — src/infra/http-body.ts:159-169
    The new helper only covers reader callers. installRequestBodyLimitGuard still sends the 413/408 and immediately destroys the request, which is the path Feishu and Slack install before their readers; Feishu’s socket test currently permits ECONNRESET. Arm the post-finish closer there and require the complete response before socket close.
    Confidence: 0.98
  • [P1] Retain bounded agent-harness disposal — src/gateway/server-close.ts:908
    This replaces current main’s five-second disposal grace with an unbounded await disposeRegisteredAgentHarnesses(). A registered harness whose dispose() never resolves now blocks all later cleanup and prevents Gateway close from completing; keep the grace wrapper and add a never-settling harness regression.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against d8c1d90edb49.

Labels

Label changes:

  • add P1: The patch leaves real plugin webhook error responses unreliable and can make Gateway shutdown hang.
  • add merge-risk: 🚨 availability: Removing the existing harness-disposal timeout can prevent Gateway close from completing when a harness never settles.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🌊 off-meta tidepool and patch quality is 🦪 silver shellfish.

Label justifications:

  • P1: The patch leaves real plugin webhook error responses unreliable and can make Gateway shutdown hang.
  • merge-risk: 🚨 availability: Removing the existing harness-disposal timeout can prevent Gateway close from completing when a harness never settles.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🌊 off-meta tidepool and patch quality is 🦪 silver shellfish.

Evidence

What I checked:

  • Shared helper is not applied to the installed guard: The new response-first helper is added here, but the installed request-body guard still ends its error response and immediately destroys the request, so the claimed shared owner does not cover that owner path. (src/infra/http-body.ts:159, 42254ec7b93b)
  • Plugin webhook path remains reachable: Feishu installs the unchanged guard before its body reader; Slack HTTP does the same before handing the request to Bolt. (extensions/feishu/src/monitor.transport.ts:433, 42254ec7b93b)
  • Existing transport test permits the failure: The Feishu real-socket oversized-body test explicitly accepts ECONNRESET instead of requiring the complete 413 response, confirming the remaining behavior is not covered by the new Gateway-only proof. (extensions/feishu/src/monitor.webhook-security.test.ts:270, 42254ec7b93b)
  • Current main has a shutdown bound that this branch removes: Current main wraps agent-harness disposal in a 5-second grace race, while this branch replaces it with an unbounded await; a never-settling harness then blocks later cleanup and close completion. (src/gateway/server-close.ts:908, 42254ec7b93b)
  • Current-main behavior inspected: The current-main guard still performs the immediate destruction, while current main retains the agent-harness grace wrapper; the central response-flush problem is therefore not already fixed on main. (src/infra/http-body.ts:552, d8c1d90edb49)
  • Feature-history routing: The current body-limit guard lines blame to Peter Steinberger’s current-main work, and recent history includes the current PR head plus a main-branch Gateway/runtime change by the same contributor. (src/infra/http-body.ts:545, 7f0a87de1d1f)

Likely related people:

  • Peter Steinberger: Authored the current body-limit guard history and the current PR; current main also contains related Gateway lifecycle work. (role: recent area contributor; confidence: high; commits: 7f0a87de1d1f, 42254ec7b93b; files: src/infra/http-body.ts, src/gateway/server-close.ts)

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.

@openclaw-barnacle openclaw-barnacle Bot added channel: feishu Channel integration: feishu size: L and removed size: M labels Aug 18, 2026
Flush structured 413 and 408 hook responses before closing oversized or timed-out request sockets, and reject deferred wake requests that target an explicit session.

Direct Gateway close now marks startup and readiness as draining immediately and attempts every HTTP listener shutdown before reporting an incomplete close.
Give the HTTP request fuzz double the IncomingMessage destroy contract exercised after 413 and 408 responses finish.
Route installed webhook body-limit failures through the shared response-first close owner and require complete Feishu 413/408 responses before terminal connection closure.

Retain the current-main grace bound for agent-harness disposal so one stuck harness cannot block listener teardown.
@steipete
steipete force-pushed the steipete/blissful-merkle-7ad022 branch from 3d4e578 to ea73a97 Compare August 18, 2026 17:20
Keep the slow-body request alive through response finish, then assert cleanup when the mock response transport closes.
@openclaw-barnacle openclaw-barnacle Bot added the channel: telegram Channel integration: telegram label Aug 18, 2026
@steipete
steipete merged commit 0684f50 into main Aug 18, 2026
236 checks passed
@steipete
steipete deleted the steipete/blissful-merkle-7ad022 branch August 18, 2026 17:40
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 20, 2026
* fix(gateway): harden hook admission and shutdown

Flush structured 413 and 408 hook responses before closing oversized or timed-out request sockets, and reject deferred wake requests that target an explicit session.

Direct Gateway close now marks startup and readiness as draining immediately and attempts every HTTP listener shutdown before reporting an incomplete close.

* test(gateway): model request destruction in fuzzing

Give the HTTP request fuzz double the IncomingMessage destroy contract exercised after 413 and 408 responses finish.

* fix(gateway): preserve response and shutdown bounds

Route installed webhook body-limit failures through the shared response-first close owner and require complete Feishu 413/408 responses before terminal connection closure.

Retain the current-main grace bound for agent-harness disposal so one stuck harness cannot block listener teardown.

* test(telegram): model response-close request cleanup

Keep the slow-body request alive through response finish, then assert cleanup when the mock response transport closes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: feishu Channel integration: feishu channel: telegram Channel integration: telegram docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant