Skip to content

fix(gateway): fan out batched gmail hook pushes and bound gmail hook bodies - #130002

Merged
steipete merged 6 commits into
mainfrom
steipete/jolly-gould-14144a
Aug 26, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/jolly-gould-14144a

Conversation

@steipete

@steipete steipete commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes the Gmail hook batched-push defect pair:

  • Gmail hook preset silently drops messages[1..n] of a batched push #120277 — the built-in gmail hook preset rendered only messages[0] of a Pub/Sub push. gog batches up to 100 messages per push (gogcli internal/cmd/gmail_watch_types.go defaultHistoryMaxResults = 100); the gateway dispatched one agent run, answered 200 for the whole batch, and messages[1..n] were silently dropped with no visible outcome and no recorded reason — the repo's worst bug class (silent failure on the default path).
  • Gmail batch payloads over the 256 KiB hook body cap wedge the watch in a permanent 413 retry loop #120278 — the shared 256 KiB hook body cap rejected large batches with 413. gog treats any non-2xx as delivery failure, rewinds its history cursor (internal/gmailwatch/processor.go RestoreProgress), and returns 500 to Pub/Sub, which redelivers the same (or larger) batch: a permanent poison-message wedge that stops all inbound mail.

Why This Change Was Made

Per-message fan-out is now an explicit mapping contract. hooks.mappings[].forEach: "<top-level array key>" dispatches one action per array element; templates and transforms see a payload whose array holds only the current element, so the existing single-message templates ({{messages[0].id}}) become per-item renderers unchanged. The gmail preset sets forEach: "messages", and the documented restricted gmail-safe-reader mapping gains it in docs. Fan-out is bounded (200 items, 2x gog's contract; the tail beyond the cap is dropped with a recorded warn).

Batch cardinality, replay, and partial-failure semantics (the contract questions from the ClawSweeper review on #120277):

  • Each item gets its own replay identity derived from its dispatch scope (gog sends no idempotency key). A partially dispatched batch answers non-2xx so gog rewinds and Pub/Sub redelivers; on redelivery, already-dispatched items replay from the dedupe cache and only missing items dispatch — converging to exactly-once within the 5-minute replay TTL, at-least-once beyond it (duplicates preferred over drops, matching repo doctrine).
  • gog's hook HTTP client aborts at 10 s (defaultHookRequestTimeoutSec), shorter than the gateway's 15 s admission timeout, so batches answer within an 8 s deadline; items still admitting at the deadline are reported pending (503), continue in the background, and reconcile with the redelivery through the replay cache.
  • Single-item batches keep the exact single-dispatch response shape ({ok, runId}); non-fanout mappings keep today's semantics and replay behavior untouched.

Fan-out items admit in the background. Live testing against the real gog binary exposed a livelock the unit rig could not: ~8 concurrent cold isolated-run workspace preps take ~15 s (embedded-runner attempt-workspace convoy), exceeding the 15 s admission deadline — every item of a large cold batch was admission-canceled, nothing reached the replay cache, and each redelivery repeated the identical cold burst forever. Fan-out items now use admissionMode: "background" (no start deadline, never canceled for admitting slowly; their eventual result feeds the replay cache), while direct /hooks/agent dispatches keep the documented bounded 15 s admission-cancel contract. The workspace-prep event-loop convoy itself is filed as a named follow-up with traces.

The gmail-path body bound is derived from the contract OpenClaw itself provisions. Mappings on the gmail path carry 100 messages x (hooks.gmail.maxBytes x3 JSON-escaping headroom + 8 KiB metadata) (~6.8 MB at the 20 KB default), folded per path with the 256 KiB floor. Every other hook path keeps the shared default cap, and the body is still read only after bearer-token auth. No new config surface; the retired hooks.maxBodyBytes key stays retired.

User Impact

Gmail hooks on the default path now dispatch one isolated hook:gmail:<id> run per email in a batch — after gateway downtime or a newsletter burst, every email reaches the agent instead of only the first. Large backlogs no longer wedge the watcher in a 413 retry loop that silently stops all future mail. Custom mappings without forEach behave exactly as before.

Evidence

  • gog producer contract verified from gogcli source (sibling checkout, v0.38.x): batch size (defaultHistoryMaxResults=100), payload shape (internal/gmailwatch/history.go), no idempotency header (internal/gmailwatch/hook.go), non-2xx rewind + Pub/Sub 500 redelivery (processor.go, http.go), 10 s hook client timeout (gmail_watch_types.go).
  • Regression tests fail pre-fix (verified by restoring the pre-fix production files and re-running: 7/8 fail, the single pass being the deliberately compat-preserving single-message response shape):
    • multi-message payload → N dispatches with per-message session keys/messages
    • oversized-bound selection (gmail path reads with derived bound, other paths with the shared cap; derivation from hooks.gmail.maxBytes)
    • partial failure → non-2xx; identical redelivery replays successes and re-dispatches only the failed item
    • hung admission → response within the deadline (503 pending), background settle, no duplicate on redelivery
    • fan-out cap with recorded drop; empty batch → 204 recorded no-op
  • pnpm test on src/gateway/hooks-mapping*.test.ts, hooks-request-handler.fanout.test.ts, server-http.hooks-delivery.test.ts, server/hooks.*.test.ts, server-reload-handlers.test.ts: all green. pnpm tsgo, pnpm check:test-types, node scripts/check-changed.mjs lanes green.
  • Live proof (real producer, real Gmail): ran on an isolated dev gateway (own OPENCLAW_STATE_DIR, port 19789, dist built from this head) with the real gog gmail watch serve binary (v0.37.0) pointed at it, real Gmail (3 self-sent test emails plus ~10 organic inbox arrivals since a seeded history cursor), and synthetic Pub/Sub push envelopes standing in for Pub/Sub delivery:
    • Real push -> gog fetched real Gmail history and POSTed a ~13-message batch -> the gateway dispatched one isolated run per message (16 distinct embedded runs observed across pushes, each rendering that message's from/subject/body), every run ending in a recorded outcome.
    • Cold-burst first delivery exceeded gog's 10 s hook client timeout (embedded-runner workspace-prep convoy, ~15 s at 8-wide concurrency; filed as a named follow-up with traces) -> gog rewound and redelivered, exactly as Pub/Sub would; redeliveries got the designed 503-pending answer, background admission completed and populated the replay cache, and the next redelivery returned 200 with zero new dispatches - gog recorded lastDeliveryStatus: ok and advanced its history cursor 61974894 -> 62001570. The former permanent wedge now converges.
    • Oversized 1.5 MB gmail-path payload -> 204 (pre-fix: 413); the same payload on /hooks/agent -> 413 (shared cap intact).
    • Direct 3-message batch in gog's exact payload shape -> 200 with 3 per-message hook:gmail:<id> dispatches; byte-identical redelivery -> replayed the same runIds with no duplicate dispatch.

Production LOC: +475/-166 (net +309) | Tests+docs: +520/-23. Growth is the explicit fan-out contract (cardinality, per-item replay identity, bounded batch response, background admission) plus the producer-derived per-path body bound - the two capabilities the ClawSweeper reviews on both issues asked to be made explicit; the bug could not be absorbed into existing structure because single-action mapping semantics were the bug.

Follow-up (producer side): gog could additionally bound or split hook batches by byte size; tracked as a gogcli follow-up, not required for correctness here.

CI Notes

  • check-lint on the first head flagged hooks-mapping.test.ts over the max-lines cap after the fan-out coverage; the fan-out describe now lives in hooks-mapping.fanout.test.ts (no suppression).
  • build-artifacts was red on current main (not this diff): the Absolutely theme's self-hosted typography (80ecc7c, feat(control-ui): add the Absolutely theme with self-hosted typography #129885) landed 12 B over the 45 KiB Control UI startup-CSS gzip ceiling. This PR carries the main-heal: budget raised to 46 KiB with a dated comment.

@clawsweeper

clawsweeper Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 26, 2026 08:17
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Aug 26, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 26, 2026
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 26, 2026, 5:39 AM ET / 09:39 UTC.

ClawSweeper review

What this changes

Adds generic hook-mapping fan-out for Gmail batches, Gmail-specific request-body limits, and replay-aware background agent admission.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 6 items remain

Keep open: the latest head fixes the prior replay and mixed-action findings, but its 32 MiB Gmail body ceiling still permits valid hooks.gmail.maxBytes settings whose 100-message batch is rejected with 413, recreating the delivery wedge this PR targets.

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

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The branch has detailed behavior evidence and focused boundary tests, but the high-setting body-limit incompatibility is a merge-blocking delivery defect.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: Not applicable to the contributor-proof gate because repository context identifies the author as a MEMBER; the PR body nevertheless describes real Gmail after-fix runs, but no linked redacted artifact was available here for independent inspection.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable to the contributor-proof gate because repository context identifies the author as a MEMBER; the PR body nevertheless describes real Gmail after-fix runs, but no linked redacted artifact was available here for independent inspection.
Evidence reviewed 6 items Fan-out owner boundary: The mapping engine renders each top-level array item in a single-item payload and returns all resulting actions; the request handler then prepares each agent action with its own replay scope.
Ceiling conflicts with accepted configuration: hooks.gmail.maxBytes is a positive unbounded integer and is forwarded to gog --max-bytes, but the derived request allowance is capped at 32 MiB. At 1 MiB per message, the included test confirms the 32 MiB cap despite the code’s own 100-message formula requiring far more capacity.
413 is the actual terminal request path: After successful bearer-token authentication, the handler reads the body at the resolved path limit and maps an oversized body to HTTP 413 before mapping or dispatch; the PR’s stated producer contract treats non-2xx as retry-worthy.
Findings 1 actionable finding [P1] Reject Gmail body settings that exceed the 32 MiB ceiling
Security None None.

Live Verification

Command: node scripts/run-vitest.mjs src/gateway/server/hooks-request-handler.fanout.test.ts

Result: FAIL (partial) — step 2 expect_output hook fan-out dispatch: expected terminal output was not visible within 30 seconds: "hook fan-out dispatch"

[test] starting test/vitest/vitest.gateway.config.ts

 RUN  v4.1.11 /tmp/clawsweeper-live-proof-130002-UDlmfX/target

 ✓  gateway-core  ../../src/gateway/server/hooks-request-handler.fanout.test.ts (10 tests) 115ms

 Test Files  1 passed (1)
      Tests  10 passed (10)
   Start at  09:40:31
   Duration  10.61s (transform 8.34s, setup 961ms, import 9.14s, tests 115ms, environment 0ms)

[test] passed 1 Vitest shard in 17.05s
[test] starting test/vitest/vitest.gateway.config.ts

 RUN  v4.1.11 /tmp/clawsweeper-live-proof-130002-UDlmfX/target

 ✓  gateway-core  ../../src/gateway/server/hooks-request-handler.fanout.test.ts (10 tests) 128ms

 Test Files  1 passed (1)
      Tests  10 passed (10)
   Start at  09:40:49
   Duration  4.78s (transform 2.60s, setup 450ms, import 3.97s, tests 128ms, environment 0ms)

[test] passed 1 Vitest shard in 11.16s

Assertions:

  • FAIL expect_output: hook fan-out dispatch

How this fits together

Gmail watch posts authenticated batches to the Gateway hook endpoint; mappings turn each payload item into a wake or agent action, and the HTTP result determines whether the producer advances or retries. This PR changes the mapping-to-dispatch boundary and the size limit applied before payload parsing.

flowchart LR
  A[Gmail watch batch] --> B[Gateway hook endpoint]
  B --> C[Token check and body limit]
  C --> D[Mapping fan-out]
  D --> E[Per-item replay and admission]
  E --> F[Agent runs]
  E --> G[HTTP retry response]
Loading

Decision needed

Question Recommendation
Should OpenClaw support only Gmail body-size settings that fit the 32 MiB Gateway ceiling, or should it preserve larger settings by changing the producer/request-size design? Bound and migrate the setting: Define and document the maximum hooks.gmail.maxBytes compatible with the 32 MiB cap, with an explicit upgrade/Doctor path for existing larger values.

Why: The current branch exposes an unbounded public setting while silently applying a smaller runtime ceiling; choosing validation/migration, a larger resource budget, or producer-side batching is an operator-facing contract decision.

Before merge

  • Reject Gmail body settings that exceed the 32 MiB ceiling (P1) - hooks.gmail.maxBytes remains an unbounded accepted setting and is forwarded to gog --max-bytes, but this cap limits the corresponding 100-message request to 32 MiB. A valid 1 MiB setting therefore still produces a 413 for a sufficiently full batch—the retry wedge this PR is meant to remove. Validate/migrate unsupported values or ensure valid batches are byte-bounded before they reach this handler.
  • Resolve merge risk (P1) - A valid high hooks.gmail.maxBytes setting can still yield 413 for a full batch, causing message delivery to retry indefinitely rather than honoring the advertised producer-derived bound.
  • Resolve merge risk (P1) - The generic forEach option is a new public mapping contract; its long-term API shape and the high-setting upgrade policy need maintainer confirmation.
  • Resolve merge risk (P1) - Exact-head CI remains incomplete, and this read-only environment could not resolve the PR base/current-main history or run the docs command because Corepack could not create its cache.
  • Complete next step (P2) - A maintainer must choose the supported Gmail size envelope before the ceiling can be repaired without silently breaking configured delivery.

Findings

  • [P1] Reject Gmail body settings that exceed the 32 MiB ceiling — src/gateway/hooks-mapping.ts:110-117
Agent review details

Security

None.

PR surface

Source +322, Tests +580, Docs +13. Total +915 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 10 479 157 +322
Tests 6 608 28 +580
Docs 3 14 1 +13
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 1101 186 +915

Review metrics

Metric Value Why it matters
Production versus test/docs delta production +475/-166; tests/docs +520/-23 The repair expands the public hook-mapping and admission paths substantially, so the configuration contract and its regression coverage both need maintainer review.
Public mapping setting 1 added: hooks.mappings[].forEach This new generic configuration field changes the supported mapping contract beyond the Gmail preset.

Merge-risk options

Maintainer options:

  1. Align the supported size envelope (recommended)
    Reject or migrate Gmail body-size settings that cannot fit a 100-message batch under the 32 MiB request ceiling, and add success coverage at the maximum supported value.
  2. Adopt a byte-bounded producer flow
    Keep larger configured snippets only after the producer or delivery protocol splits batches so no valid request exceeds the Gateway limit.
  3. Pause the ceiling change
    Pause this PR if maintainers do not want to establish an upgrade contract for previously accepted high body-size settings.

Technical review

Best possible solution:

Make the accepted Gmail body-size configuration fit the enforced ceiling—through a documented validated maximum and upgrade path, or producer byte-batching—then prove a full batch succeeds at every supported setting.

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

Yes—source proves that an accepted 1 MiB hooks.gmail.maxBytes setting is capped at 32 MiB while a 100-item batch’s declared allowance is far larger, and the handler returns 413 at that boundary. This read-only review did not execute the reproduction because the environment cannot initialize Corepack’s cache.

Is this the best way to solve the issue?

No—the ceiling is sensible as a resource bound, but it is not a complete solution while an unbounded supported setting can exceed it and recreate the retry wedge.

Full review comments:

  • [P1] Reject Gmail body settings that exceed the 32 MiB ceiling — src/gateway/hooks-mapping.ts:110-117
    hooks.gmail.maxBytes remains an unbounded accepted setting and is forwarded to gog --max-bytes, but this cap limits the corresponding 100-message request to 32 MiB. A valid 1 MiB setting therefore still produces a 413 for a sufficiently full batch—the retry wedge this PR is meant to remove. Validate/migrate unsupported values or ensure valid batches are byte-bounded before they reach this handler.
    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 430de50d6735.

Labels

Label justifications:

  • P1: A supported high Gmail body-size setting can still make a full batch return 413 and halt inbound delivery through retries.
  • merge-risk: 🚨 compatibility: The branch introduces a public mapping option and changes behavior for accepted Gmail size settings without an upgrade envelope for values above the ceiling.
  • merge-risk: 🚨 message-delivery: An oversized valid batch is rejected before dispatch, so its messages are not delivered.
  • merge-risk: 🚨 availability: Repeated 413 responses can keep a Gmail watch batch retrying and prevent later inbound mail from progressing.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Not applicable to the contributor-proof gate because repository context identifies the author as a MEMBER; the PR body nevertheless describes real Gmail after-fix runs, but no linked redacted artifact was available here for independent inspection.

Evidence

What I checked:

  • Fan-out owner boundary: The mapping engine renders each top-level array item in a single-item payload and returns all resulting actions; the request handler then prepares each agent action with its own replay scope. (src/gateway/hooks-mapping.ts:279, bb9b3f8c0dde)
  • Ceiling conflicts with accepted configuration: hooks.gmail.maxBytes is a positive unbounded integer and is forwarded to gog --max-bytes, but the derived request allowance is capped at 32 MiB. At 1 MiB per message, the included test confirms the 32 MiB cap despite the code’s own 100-message formula requiring far more capacity. (src/gateway/hooks-mapping.ts:110, bb9b3f8c0dde)
  • 413 is the actual terminal request path: After successful bearer-token authentication, the handler reads the body at the resolved path limit and maps an oversized body to HTTP 413 before mapping or dispatch; the PR’s stated producer contract treats non-2xx as retry-worthy. (src/gateway/server/hooks-request-handler.ts:344, bb9b3f8c0dde)
  • Focused regression coverage: The new tests exercise fan-out cardinality, partial retry, pending admission, duplicate actions, mixed wake/agent transforms, and the body-limit ceiling; the last test demonstrates the problematic capped high-setting case rather than a successful high-setting batch. (src/gateway/server/hooks-request-handler.fanout.test.ts:145, bb9b3f8c0dde)
  • Current-head provenance: Sparse blame attributes the touched Gmail preset and fan-out configuration to the current reviewed head; its commit is authored by Peter Steinberger. (src/gateway/hooks-mapping.ts:120, bb9b3f8c0dde)
  • Current-main comparison unavailable: This review checkout contains only a grafted PR head; resolving the supplied base/current-main objects and history required a promisor fetch, but DNS/network access failed. The verdict therefore does not claim a current-main or release comparison.

Likely related people:

  • steipete: Sparse blame attributes the current Gmail mapping/fan-out lines to Peter Steinberger, and the reviewed head commit is authored by him; full feature-history ownership was unavailable in this partial checkout. (role: current-head gateway hook contributor; confidence: medium; commits: bb9b3f8c0dde; files: src/gateway/hooks-mapping.ts, src/gateway/server/hooks-request-handler.ts, src/hooks/gmail.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Make every accepted hooks.gmail.maxBytes value compatible with a full supported batch, with an explicit upgrade path or producer-side byte batching.
  • Add a boundary regression that posts a batch at the maximum supported configured body size and verifies it does not return 413.

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-08-26T08:24:07.348Z sha 1864b90b49ee62b9dec59e6686395fdff81ba144 :: found issues before merge. :: [P1] Handle mixed action kinds in fan-out | [P2] Correct the mapped-hook admission contract
  • reviewed 2026-08-26T09:00:44.873Z sha e6c41fe :: found issues before merge. :: [P1] Preserve a unique replay identity for every fan-out item | [P1] Handle mixed fan-out action kinds without dropping one | [P1] Cap the Gmail-derived request-body limit

…bodies

The built-in gmail hook preset rendered only messages[0] of a Pub/Sub push
that batches up to 100 messages, silently dropping the rest (#120277), and
the shared 256KiB hook body cap 413-wedged gog's history-rewind retry loop
on large batches (#120278).

Hook mappings gain an explicit forEach fan-out contract: one action per
payload array element, per-item replay identity derived from dispatch scope
so producer redeliveries converge instead of duplicating, and batch
responses bounded under gog's 10s hook client timeout. gmail-path mappings
inherit a body bound derived from the provisioned producer contract
(hooks.gmail.maxBytes x gog's 100-message batch).
Live proof against the real gog producer exposed a livelock: eight
concurrent cold isolated-run workspace preps take ~15s, exceeding the 15s
admission deadline, so every fan-out item was canceled, nothing reached the
replay cache, and each Pub/Sub redelivery repeated the same cold burst
forever. Fan-out items now admit without the start deadline; the producer's
redelivery plus per-item replay identity own retry semantics, and direct
/hooks/agent dispatches keep the bounded 15s admission contract.
hooks-mapping.test.ts crossed the max-lines lint cap after the fan-out
coverage landed; the fan-out describe moves to hooks-mapping.fanout.test.ts.
@steipete
steipete force-pushed the steipete/jolly-gould-14144a branch from c4bc5da to e6c41fe Compare August 26, 2026 08:53
…eiling

Addresses the ClawSweeper P1 findings on #130002: within-batch identical
rendered items now get occurrence-numbered replay identities (both run,
redeliveries replay both); per-item transforms emitting mixed wake/agent
kinds dispatch every action through one unified loop instead of silently
dropping the non-first kind; and the gmail-derived body allowance is
capped at 32 MiB so an operator-set hooks.gmail.maxBytes cannot amplify
into an unbounded in-memory request buffer.
@steipete

Copy link
Copy Markdown
Contributor Author

All three actionable findings from the ClawSweeper review are fixed in bb9b3f8, each with a regression test that fails on the pre-fix code (verified by A/B):

  • Per-item replay identity (P1) — within-batch identical rendered items are now occurrence-numbered inside the fan-out replay scope (fanOutScopeOccurrences), so both dispatch and a byte-identical redelivery replays both. Content identity (not an ordinal) remains the cross-request key on purpose: gog redeliveries can change batch composition, and ordinals would break retry convergence. Test: dispatches identical items separately and replays each on redelivery.
  • Mixed action kinds (P1) — the kind-split branches are replaced by one unified loop: wakes enqueue immediately, agents collect for dispatch, nothing is skipped. Test: mixed per-item transform kinds dispatch both wakes and agents. (Noted in code: wakes carry no replay identity, so a producer retry after a partial agent failure re-enqueues them — accepted for this degenerate config shape.)
  • Body-limit ceiling (P1 + security) — the derived gmail allowance is hard-capped at 32 MiB (GMAIL_HOOK_MAX_BODY_BYTES_CEILING), so a large-but-valid hooks.gmail.maxBytes cannot amplify into a hundreds-of-MB in-memory buffer. Test asserts a 1 MiB per-message setting caps at 32 MiB.

On the two P2 items:

  • gog contract verification — done directly against the gogcli source before the design (not from memory): internal/cmd/gmail_watch_types.go (defaultHistoryMaxResults = 100, defaultHookRequestTimeoutSec = 10), internal/gmailwatch/processor.go (RestoreProgress rewind on delivery failure), internal/gmailwatch/hook.go (no idempotency header), internal/gmailwatch/http.go (500 to Pub/Sub on hook failure). The PR body's live-proof section additionally exercised the real gog gmail watch serve binary end-to-end.
  • Generic forEach contract — keeping it generic follows both the maintainer direction in Gmail hook preset silently drops messages[1..n] of a batched push #120277 (fan-out at the mapping/dispatch layer) and this review's own recommendation ("Retain generic fan-out"); the docs' recommended restricted gmail-safe-reader mapping needs it, so a preset-only capability would leave the documented config broken.

The "Live Verification" FAIL above is the review harness's own 30s command timeout; its embedded output shows the suite passing 8/8.

@steipete
steipete merged commit 03f3334 into main Aug 26, 2026
198 checks passed
@steipete
steipete deleted the steipete/jolly-gould-14144a branch August 26, 2026 10:00
steipete added a commit that referenced this pull request Aug 27, 2026
…untime registry (#130167)

First hook/cron isolated-run dispatch in a gateway process cold-loaded every
discovered plugin (~70 bundled providers) because the registry loader's
startup-scope fallback chain came up empty on that path and dropped
onlyPluginIds entirely. In dev checkouts each provider plugin loads from
TypeScript source through jiti's synchronous babel transform: a CPU profile of
a live 13-message gmail hook burst showed one contiguous 42.6s event-loop
block (36.2s extension module loading; amazon-bedrock 16.8s, opencode 13.1s),
the gateway HTTP server unresponsive for ~31s, and the fan-out handler's own
8s response deadline unable to fire - the livelock recorded in #130002.

The fallback chain now consults the process's active plugin registry before
giving up to full discovery: explicit base -> request-scope registry ->
metadata snapshot pluginIds -> active runtime plugin ids -> unrestricted.
resolveAgentRuntimePluginLoadPlan still adds the run's selected provider,
harness, memory, and context-engine owners on top, so any selected provider
outside the startup set keeps joining the immutable run generation. Hosts
with no active registry (pure library use) keep full discovery.

Live re-verification on the same rig: cold burst answered in 8.03s with the
designed 503 partial fan-out response, probe max latency 4.56s (was a 31.5s
outage), longest event-loop block 5.5s (was 42.6s), and only startup-registry
plugins load.

Follow-up of the gmail hook fan-out landing (#130002); same defect family as
the channel-path fix in #125596.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 27, 2026
…bodies (openclaw#130002)

* fix(gateway): fan out batched gmail hook pushes and bound gmail hook bodies

The built-in gmail hook preset rendered only messages[0] of a Pub/Sub push
that batches up to 100 messages, silently dropping the rest (openclaw#120277), and
the shared 256KiB hook body cap 413-wedged gog's history-rewind retry loop
on large batches (openclaw#120278).

Hook mappings gain an explicit forEach fan-out contract: one action per
payload array element, per-item replay identity derived from dispatch scope
so producer redeliveries converge instead of duplicating, and batch
responses bounded under gog's 10s hook client timeout. gmail-path mappings
inherit a body bound derived from the provisioned producer contract
(hooks.gmail.maxBytes x gog's 100-message batch).

* fix(gateway): guard null transform action before fan-out merge

* fix(gateway): admit fan-out hook items in the background

Live proof against the real gog producer exposed a livelock: eight
concurrent cold isolated-run workspace preps take ~15s, exceeding the 15s
admission deadline, so every fan-out item was canceled, nothing reached the
replay cache, and each Pub/Sub redelivery repeated the same cold burst
forever. Fan-out items now admit without the start deadline; the producer's
redelivery plus per-item replay identity own retry semantics, and direct
/hooks/agent dispatches keep the bounded 15s admission contract.

* test(gateway): adapt reload-handler hook assertions to actions[] shape

* test(gateway): split hook fan-out mapping tests into their own file

hooks-mapping.test.ts crossed the max-lines lint cap after the fan-out
coverage landed; the fan-out describe moves to hooks-mapping.fanout.test.ts.

* fix(gateway): harden fan-out identity, mixed action kinds, and body ceiling

Addresses the ClawSweeper P1 findings on openclaw#130002: within-batch identical
rendered items now get occurrence-numbered replay identities (both run,
redeliveries replay both); per-item transforms emitting mixed wake/agent
kinds dispatch every action through one unified loop instead of silently
dropping the non-first kind; and the gmail-derived body allowance is
capped at 32 MiB so an operator-set hooks.gmail.maxBytes cannot amplify
into an unbounded in-memory request buffer.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 27, 2026
…untime registry (openclaw#130167)

First hook/cron isolated-run dispatch in a gateway process cold-loaded every
discovered plugin (~70 bundled providers) because the registry loader's
startup-scope fallback chain came up empty on that path and dropped
onlyPluginIds entirely. In dev checkouts each provider plugin loads from
TypeScript source through jiti's synchronous babel transform: a CPU profile of
a live 13-message gmail hook burst showed one contiguous 42.6s event-loop
block (36.2s extension module loading; amazon-bedrock 16.8s, opencode 13.1s),
the gateway HTTP server unresponsive for ~31s, and the fan-out handler's own
8s response deadline unable to fire - the livelock recorded in openclaw#130002.

The fallback chain now consults the process's active plugin registry before
giving up to full discovery: explicit base -> request-scope registry ->
metadata snapshot pluginIds -> active runtime plugin ids -> unrestricted.
resolveAgentRuntimePluginLoadPlan still adds the run's selected provider,
harness, memory, and context-engine owners on top, so any selected provider
outside the startup set keeps joining the immutable run generation. Hosts
with no active registry (pure library use) keep full discovery.

Live re-verification on the same rig: cold burst answered in 8.03s with the
designed 503 partial fan-out response, probe max latency 4.56s (was a 31.5s
outage), longest event-loop block 5.5s (was 42.6s), and only startup-registry
plugins load.

Follow-up of the gmail hook fan-out landing (openclaw#130002); same defect family as
the channel-path fix in openclaw#125596.
obviyus added a commit that referenced this pull request Nov 17, 2026
#200514)

Related: #111382, #120278, #130002

## What Problem This Solves

Every custom hook path had a fixed 256 KiB body limit. A meeting-notes webhook (Circleback) carrying the full transcript of a 3 h 16 min meeting sent 332,553 bytes. The gateway answered `413 payload too large` on all nine retries, so the meeting never reached the agent. The rejection was not logged anywhere, so the operator could not see that a delivery was lost.

256 KiB was the smallest limit among the gateway's authenticated endpoints: generic webhooks allow 1 MiB, tools invoke 2 MiB and chat completions 20 MiB.

## Fix

- The default hook body limit is now 1 MiB, the shared webhook default (`DEFAULT_WEBHOOK_MAX_BODY_BYTES`). The Gmail-path allowance is unchanged; its floor rises from 256 KiB to 1 MiB.
- An authenticated hook request whose body is rejected (`413`, `408` or `400`) now logs `hook request rejected for <path>: status=<code> bodyLimitBytes=<limit>`. No body content is logged, because parse errors can quote it.
- No new config key. The first revision of this PR added a per-mapping `hooks.mappings[].maxBodyBytes`, up to 32 MiB. It is replaced by the default, which keeps `hooks.maxBodyBytes` retired as #111382 intended.

Why 1 MiB and not more: the Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). A larger body that is templated into an agent message is cut from the front before the model sees it, which removes the mapping's instruction. On the first revision, an 8 MiB accepted body made the agent ignore the hook and do unrelated tool work, and the run still reported `status=ok`. A visible 413 is better than that. Stopping the Codex runtime from cutting the current request is separate follow-up work.

## User Impact

Hook senders whose payloads are between 256 KiB and 1 MiB now work with no config change. That is about 10 hours of meeting transcript at the rate above. Bodies over 1 MiB still get 413, and the gateway log now names the path and the limit. Auth still runs before the body is read.

## Evidence

**Real gateway from source, real agent turns** (`openai/gpt-5.4-mini`, Codex runtime). Bodies are synthetic but use Circleback's documented JSON shape (`transcript` segments with speaker, text and timestamp), with a codeword in the last segment. The mapping asks the agent to return it.

| build | body | result |
|---|---:|---|
| `main` | 332,553 B | 413, nothing logged |
| this PR | 332,553 B | 200; agent returns the codeword (94k input tokens) |
| this PR | 1,000,000 B | 200; agent returns the codeword (231k input tokens); no truncation in the Codex rollout |
| this PR | 2,097,152 B | 413; `hook request rejected for /hooks/circleback: status=413 bodyLimitBytes=1048576` |
| this PR, other path | 332,553 B | 200 (wake) |

**First revision (per-mapping limit of 8 MiB), same setup:**

| body | result |
|---|---|
| 2 MiB | accepted; Codex input cut to the last 1,048,576 chars (`[truncated 1049630 chars from older context]`) |
| 8 MiB | accepted; instruction lost, agent ran unrelated tool calls, hook logged `status=ok` |

**Memory** (accepted bodies, 10–20 concurrent): about 1.7× the concurrent body bytes. 20 × 2 MiB added about 60 MB of RSS.

**Tests:** two request-handler tests in `src/gateway/server/hooks.wake-admission.test.ts`. One accepts a 332,553-byte body; the other checks that a rejected body logs its path and limit without its content. Both fail on `main` and pass here. The hook suites pass (125 tests in 6 files), as do `tsgo:core`, oxlint, oxfmt, `config:docs:check` and `git diff --check`.

Thanks @garrytan for the report and the detailed proof.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
openclaw#200514)

Related: openclaw#111382, openclaw#120278, openclaw#130002

## What Problem This Solves

Every custom hook path had a fixed 256 KiB body limit. A meeting-notes webhook (Circleback) carrying the full transcript of a 3 h 16 min meeting sent 332,553 bytes. The gateway answered `413 payload too large` on all nine retries, so the meeting never reached the agent. The rejection was not logged anywhere, so the operator could not see that a delivery was lost.

256 KiB was the smallest limit among the gateway's authenticated endpoints: generic webhooks allow 1 MiB, tools invoke 2 MiB and chat completions 20 MiB.

## Fix

- The default hook body limit is now 1 MiB, the shared webhook default (`DEFAULT_WEBHOOK_MAX_BODY_BYTES`). The Gmail-path allowance is unchanged; its floor rises from 256 KiB to 1 MiB.
- An authenticated hook request whose body is rejected (`413`, `408` or `400`) now logs `hook request rejected for <path>: status=<code> bodyLimitBytes=<limit>`. No body content is logged, because parse errors can quote it.
- No new config key. The first revision of this PR added a per-mapping `hooks.mappings[].maxBodyBytes`, up to 32 MiB. It is replaced by the default, which keeps `hooks.maxBodyBytes` retired as openclaw#111382 intended.

Why 1 MiB and not more: the Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). A larger body that is templated into an agent message is cut from the front before the model sees it, which removes the mapping's instruction. On the first revision, an 8 MiB accepted body made the agent ignore the hook and do unrelated tool work, and the run still reported `status=ok`. A visible 413 is better than that. Stopping the Codex runtime from cutting the current request is separate follow-up work.

## User Impact

Hook senders whose payloads are between 256 KiB and 1 MiB now work with no config change. That is about 10 hours of meeting transcript at the rate above. Bodies over 1 MiB still get 413, and the gateway log now names the path and the limit. Auth still runs before the body is read.

## Evidence

**Real gateway from source, real agent turns** (`openai/gpt-5.4-mini`, Codex runtime). Bodies are synthetic but use Circleback's documented JSON shape (`transcript` segments with speaker, text and timestamp), with a codeword in the last segment. The mapping asks the agent to return it.

| build | body | result |
|---|---:|---|
| `main` | 332,553 B | 413, nothing logged |
| this PR | 332,553 B | 200; agent returns the codeword (94k input tokens) |
| this PR | 1,000,000 B | 200; agent returns the codeword (231k input tokens); no truncation in the Codex rollout |
| this PR | 2,097,152 B | 413; `hook request rejected for /hooks/circleback: status=413 bodyLimitBytes=1048576` |
| this PR, other path | 332,553 B | 200 (wake) |

**First revision (per-mapping limit of 8 MiB), same setup:**

| body | result |
|---|---|
| 2 MiB | accepted; Codex input cut to the last 1,048,576 chars (`[truncated 1049630 chars from older context]`) |
| 8 MiB | accepted; instruction lost, agent ran unrelated tool calls, hook logged `status=ok` |

**Memory** (accepted bodies, 10–20 concurrent): about 1.7× the concurrent body bytes. 20 × 2 MiB added about 60 MB of RSS.

**Tests:** two request-handler tests in `src/gateway/server/hooks.wake-admission.test.ts`. One accepts a 332,553-byte body; the other checks that a rejected body logs its path and limit without its content. Both fail on `main` and pass here. The hook suites pass (125 tests in 6 files), as do `tsgo:core`, oxlint, oxfmt, `config:docs:check` and `git diff --check`.

Thanks @garrytan for the report and the detailed proof.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
#200514)

Related: #111382, #120278, #130002

## What Problem This Solves

Every custom hook path had a fixed 256 KiB body limit. A meeting-notes webhook (Circleback) carrying the full transcript of a 3 h 16 min meeting sent 332,553 bytes. The gateway answered `413 payload too large` on all nine retries, so the meeting never reached the agent. The rejection was not logged anywhere, so the operator could not see that a delivery was lost.

256 KiB was the smallest limit among the gateway's authenticated endpoints: generic webhooks allow 1 MiB, tools invoke 2 MiB and chat completions 20 MiB.

## Fix

- The default hook body limit is now 1 MiB, the shared webhook default (`DEFAULT_WEBHOOK_MAX_BODY_BYTES`). The Gmail-path allowance is unchanged; its floor rises from 256 KiB to 1 MiB.
- An authenticated hook request whose body is rejected (`413`, `408` or `400`) now logs `hook request rejected for <path>: status=<code> bodyLimitBytes=<limit>`. No body content is logged, because parse errors can quote it.
- No new config key. The first revision of this PR added a per-mapping `hooks.mappings[].maxBodyBytes`, up to 32 MiB. It is replaced by the default, which keeps `hooks.maxBodyBytes` retired as #111382 intended.

Why 1 MiB and not more: the Codex runtime accepts at most 1 MiB of text per turn (`MAX_USER_INPUT_TEXT_CHARS` in codex-rs). A larger body that is templated into an agent message is cut from the front before the model sees it, which removes the mapping's instruction. On the first revision, an 8 MiB accepted body made the agent ignore the hook and do unrelated tool work, and the run still reported `status=ok`. A visible 413 is better than that. Stopping the Codex runtime from cutting the current request is separate follow-up work.

## User Impact

Hook senders whose payloads are between 256 KiB and 1 MiB now work with no config change. That is about 10 hours of meeting transcript at the rate above. Bodies over 1 MiB still get 413, and the gateway log now names the path and the limit. Auth still runs before the body is read.

## Evidence

**Real gateway from source, real agent turns** (`openai/gpt-5.4-mini`, Codex runtime). Bodies are synthetic but use Circleback's documented JSON shape (`transcript` segments with speaker, text and timestamp), with a codeword in the last segment. The mapping asks the agent to return it.

| build | body | result |
|---|---:|---|
| `main` | 332,553 B | 413, nothing logged |
| this PR | 332,553 B | 200; agent returns the codeword (94k input tokens) |
| this PR | 1,000,000 B | 200; agent returns the codeword (231k input tokens); no truncation in the Codex rollout |
| this PR | 2,097,152 B | 413; `hook request rejected for /hooks/circleback: status=413 bodyLimitBytes=1048576` |
| this PR, other path | 332,553 B | 200 (wake) |

**First revision (per-mapping limit of 8 MiB), same setup:**

| body | result |
|---|---|
| 2 MiB | accepted; Codex input cut to the last 1,048,576 chars (`[truncated 1049630 chars from older context]`) |
| 8 MiB | accepted; instruction lost, agent ran unrelated tool calls, hook logged `status=ok` |

**Memory** (accepted bodies, 10–20 concurrent): about 1.7× the concurrent body bytes. 20 × 2 MiB added about 60 MB of RSS.

**Tests:** two request-handler tests in `src/gateway/server/hooks.wake-admission.test.ts`. One accepts a 332,553-byte body; the other checks that a rejected body logs its path and limit without its content. Both fail on `main` and pass here. The hook suites pass (125 tests in 6 files), as do `tsgo:core`, oxlint, oxfmt, `config:docs:check` and `git diff --check`.

Thanks @garrytan for the report and the detailed proof.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit df82bcf)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 57caad23e2defdf33bdf6735fb165eadb08b73e9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant