Skip to content

Commit bb9b3f8

Browse files
committed
fix(gateway): harden fan-out identity, mixed action kinds, and body ceiling
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.
1 parent e6c41fe commit bb9b3f8

3 files changed

Lines changed: 147 additions & 46 deletions

File tree

‎src/gateway/hooks-mapping.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,11 +102,18 @@ export const HOOK_MAPPING_FAN_OUT_MAX_ITEMS = 200;
102102
const GMAIL_HOOK_BATCH_MAX_MESSAGES = 100;
103103
const GMAIL_HOOK_JSON_ESCAPING_FACTOR = 3;
104104
const GMAIL_HOOK_PER_MESSAGE_OVERHEAD_BYTES = 8 * 1024;
105+
// Hard ceiling on the derived allowance: hooks.gmail.maxBytes is
106+
// operator-controlled and unbounded, and the batch multiplier would otherwise
107+
// amplify a large-but-valid setting into a hundreds-of-megabytes in-memory
108+
// request buffer for authenticated callers. 32 MiB covers ~100 KB per-message
109+
// settings; larger configs fall back to this bound.
110+
const GMAIL_HOOK_MAX_BODY_BYTES_CEILING = 32 * 1024 * 1024;
105111

106112
function resolveGmailHookMaxBodyBytes(maxBytes: number): number {
107-
return (
113+
return Math.min(
114+
GMAIL_HOOK_MAX_BODY_BYTES_CEILING,
108115
GMAIL_HOOK_BATCH_MAX_MESSAGES *
109-
(maxBytes * GMAIL_HOOK_JSON_ESCAPING_FACTOR + GMAIL_HOOK_PER_MESSAGE_OVERHEAD_BYTES)
116+
(maxBytes * GMAIL_HOOK_JSON_ESCAPING_FACTOR + GMAIL_HOOK_PER_MESSAGE_OVERHEAD_BYTES),
110117
);
111118
}
112119

‎src/gateway/server/hooks-request-handler.fanout.test.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Fan-out hook dispatch tests protect the batched-producer contract: every
22
// pushed item ends in its own dispatch, retries replay instead of duplicating,
33
// and gmail-path bodies are bounded by the provisioned producer contract.
4+
import fs from "node:fs";
5+
import os from "node:os";
6+
import path from "node:path";
47
import { beforeEach, describe, expect, test, vi } from "vitest";
58
import type { createSubsystemLogger } from "../../logging/subsystem.js";
69
import { resolveHookMappings } from "../hooks-mapping.js";
@@ -197,6 +200,27 @@ describe("hook fan-out dispatch", () => {
197200
expect(dispatchAgentHook).toHaveBeenCalledTimes(2);
198201
});
199202

203+
test("dispatches identical items separately and replays each on redelivery", async () => {
204+
// Two batch elements can render byte-identical actions (generic payloads;
205+
// impossible for gmail ids). Both must run, and a redelivery must replay
206+
// both instead of dispatching a third run.
207+
let runSeq = 0;
208+
const { handler, dispatchAgentHook } = createFanOutHandler({
209+
dispatchAgentHook: () => ({ ok: true as const, runId: `run-${runSeq++}` }),
210+
});
211+
const payload = { messages: [gmailMessage("twin"), gmailMessage("twin")] };
212+
213+
const response = await postGmailPayload(handler, payload);
214+
expect(response.res.statusCode).toBe(200);
215+
const body = JSON.parse(response.getBody()) as { runIds?: string[] };
216+
expect(body.runIds).toEqual(["run-0", "run-1"]);
217+
expect(dispatchAgentHook).toHaveBeenCalledTimes(2);
218+
219+
const retry = await postGmailPayload(handler, payload);
220+
expect(JSON.parse(retry.getBody())).toMatchObject({ runIds: ["run-0", "run-1"] });
221+
expect(dispatchAgentHook).toHaveBeenCalledTimes(2);
222+
});
223+
200224
test("bounds fan-out and records the dropped tail", async () => {
201225
const { handler, dispatchAgentHook, logHooks } = createFanOutHandler();
202226
const messages = Array.from({ length: 205 }, (_, index) => gmailMessage(`m${index}`));
@@ -208,6 +232,63 @@ describe("hook fan-out dispatch", () => {
208232
expect(logHooks.warn).toHaveBeenCalledWith(expect.stringContaining("dropped 5 items"));
209233
});
210234

235+
test("mixed per-item transform kinds dispatch both wakes and agents", async () => {
236+
const transformsDir = fs.mkdtempSync(path.join(os.tmpdir(), "hook-fanout-transform-"));
237+
try {
238+
fs.mkdirSync(path.join(transformsDir, "hooks", "transforms"), { recursive: true });
239+
fs.writeFileSync(
240+
path.join(transformsDir, "hooks", "transforms", "mixed.mjs"),
241+
'export default (ctx) => ctx.payload.messages[0].kind === "wake" ? { kind: "wake", text: `wake:${ctx.payload.messages[0].id}` } : {};',
242+
);
243+
const canonical = createHooksConfig();
244+
const hooksConfig: HooksConfigResolved = {
245+
...canonical,
246+
mappings: resolveHookMappings(
247+
{
248+
mappings: [
249+
{
250+
id: "mixed",
251+
match: { path: "gmail" },
252+
action: "agent",
253+
forEach: "messages",
254+
sessionKey: "hook:gmail:{{messages[0].id}}",
255+
messageTemplate: "agent:{{messages[0].id}}",
256+
transform: { module: "mixed.mjs" },
257+
},
258+
],
259+
allowRequestSessionKey: true,
260+
allowedSessionKeyPrefixes: ["hook:gmail:"],
261+
},
262+
{ configDir: transformsDir },
263+
),
264+
sessionPolicy: {
265+
...canonical.sessionPolicy,
266+
allowRequestSessionKey: true,
267+
allowedSessionKeyPrefixes: ["hook:gmail:"],
268+
},
269+
};
270+
const { handler, dispatchAgentHook, dispatchWakeHook } = createFanOutHandler({ hooksConfig });
271+
272+
const response = await postGmailPayload(handler, {
273+
messages: [
274+
{ id: "w1", kind: "wake" },
275+
{ id: "a1", kind: "agent" },
276+
],
277+
});
278+
279+
expect(response.res.statusCode).toBe(200);
280+
expect(dispatchWakeHook).toHaveBeenCalledTimes(1);
281+
expect(dispatchWakeHook.mock.calls[0]?.[0]).toMatchObject({ text: "wake:w1" });
282+
expect(dispatchAgentHook).toHaveBeenCalledTimes(1);
283+
expect(dispatchAgentHook.mock.calls[0]?.[0]).toMatchObject({
284+
message: "agent:a1",
285+
sessionKey: "hook:gmail:a1",
286+
});
287+
} finally {
288+
fs.rmSync(transformsDir, { recursive: true, force: true });
289+
}
290+
});
291+
211292
test("derives the gmail body bound from the provisioned producer contract", async () => {
212293
const { resolveHooksConfig } =
213294
await vi.importActual<typeof import("../hooks.js")>("../hooks.js");
@@ -227,6 +308,13 @@ describe("hook fan-out dispatch", () => {
227308
hooks: { ...baseHooks, gmail: { maxBytes: 50_000 } },
228309
} as never);
229310
expect(larger?.maxBodyBytesByPath.get("gmail")).toBe(100 * (50_000 * 3 + 8_192));
311+
312+
// Operator-controlled maxBytes must not amplify into an unbounded
313+
// in-memory request allowance.
314+
const huge = resolveHooksConfig({
315+
hooks: { ...baseHooks, gmail: { maxBytes: 1_048_576 } },
316+
} as never);
317+
expect(huge?.maxBodyBytesByPath.get("gmail")).toBe(32 * 1024 * 1024);
230318
});
231319

232320
test("reads gmail-path bodies with the producer-derived bound", async () => {

‎src/gateway/server/hooks-request-handler.ts‎

Lines changed: 50 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -591,34 +591,11 @@ export function createHooksRequestHandler(
591591
res.end();
592592
return true;
593593
}
594-
if (mapped.actions[0]?.kind === "wake") {
595-
let wakeMode: "now" | "next-heartbeat" = "now";
596-
for (const action of mapped.actions) {
597-
if (action.kind !== "wake") {
598-
continue;
599-
}
600-
const target = resolveTargetAgentOrRespond(action.agentId, "mapping");
601-
if (!target) {
602-
return true;
603-
}
604-
const dispatched = dispatchWakeActionOrRespond(
605-
{
606-
text: action.text,
607-
mode: action.mode,
608-
sessionKey: action.sessionKey,
609-
},
610-
target.effectiveAgentId,
611-
action.sessionKeySource === "static" ? "mapping-static" : "mapping-templated",
612-
);
613-
if (!dispatched) {
614-
return true;
615-
}
616-
wakeMode = action.mode;
617-
}
618-
sendJson(res, 200, { ok: true, mode: wakeMode });
619-
return true;
620-
}
621-
594+
// Within-batch duplicates: content identity alone would collapse two
595+
// identical rendered items into one dispatch while the response
596+
// claims both ran. Numbering repeated scopes keeps one replay entry
597+
// per occurrence, and identical redeliveries renumber identically.
598+
const fanOutScopeOccurrences = new Map<string, number>();
622599
// Resolves policy for one mapped agent action and returns its
623600
// dispatch closure; a null return means an error response was sent.
624601
const prepareMappedAgentDispatchOrRespond = (
@@ -665,6 +642,26 @@ export function createHooksRequestHandler(
665642
if (dispatchSessionKey === null) {
666643
return null;
667644
}
645+
const dispatchScope: Record<string, unknown> = {
646+
agentId: target.effectiveAgentId,
647+
sessionKey: action.sessionKey ?? hooksConfig.sessionPolicy.defaultSessionKey ?? null,
648+
message: action.message,
649+
name: action.name ?? "Hook",
650+
wakeMode: action.wakeMode,
651+
sessionMode: action.sessionMode,
652+
deliver,
653+
channel,
654+
to: action.to ?? null,
655+
model: action.model ?? null,
656+
thinking: action.thinking ?? null,
657+
timeoutSeconds: action.timeoutSeconds ?? null,
658+
};
659+
if (mapped.fanout) {
660+
const fingerprint = JSON.stringify(dispatchScope);
661+
const occurrence = fanOutScopeOccurrences.get(fingerprint) ?? 0;
662+
fanOutScopeOccurrences.set(fingerprint, occurrence + 1);
663+
dispatchScope.occurrence = occurrence;
664+
}
668665
const replayKey = buildHookReplayCacheKey({
669666
pathKey: subPath || "mapping",
670667
token,
@@ -675,21 +672,7 @@ export function createHooksRequestHandler(
675672
idempotencyKey: mapped.fanout
676673
? (idempotencyKey ?? HOOK_FAN_OUT_DERIVED_IDEMPOTENCY)
677674
: idempotencyKey,
678-
dispatchScope: {
679-
agentId: target.effectiveAgentId,
680-
sessionKey:
681-
action.sessionKey ?? hooksConfig.sessionPolicy.defaultSessionKey ?? null,
682-
message: action.message,
683-
name: action.name ?? "Hook",
684-
wakeMode: action.wakeMode,
685-
sessionMode: action.sessionMode,
686-
deliver,
687-
channel,
688-
to: action.to ?? null,
689-
model: action.model ?? null,
690-
thinking: action.thinking ?? null,
691-
timeoutSeconds: action.timeoutSeconds ?? null,
692-
},
675+
dispatchScope,
693676
});
694677
return () =>
695678
dispatchAgentHookWithReplay(replayKey, now, () =>
@@ -721,11 +704,29 @@ export function createHooksRequestHandler(
721704
);
722705
};
723706

707+
// One pass over every action so a per-item transform emitting mixed
708+
// kinds loses nothing: wakes enqueue immediately (no replay
709+
// identity — a producer retry after a partial agent failure
710+
// re-enqueues them), agents collect for dispatch.
724711
const dispatches: Array<
725712
() => HookAgentDispatchResult | Promise<HookAgentDispatchResult>
726713
> = [];
714+
let wakeMode: "now" | "next-heartbeat" | undefined;
727715
for (const action of mapped.actions) {
728-
if (action.kind !== "agent") {
716+
if (action.kind === "wake") {
717+
const target = resolveTargetAgentOrRespond(action.agentId, "mapping");
718+
if (!target) {
719+
return true;
720+
}
721+
const dispatched = dispatchWakeActionOrRespond(
722+
{ text: action.text, mode: action.mode, sessionKey: action.sessionKey },
723+
target.effectiveAgentId,
724+
action.sessionKeySource === "static" ? "mapping-static" : "mapping-templated",
725+
);
726+
if (!dispatched) {
727+
return true;
728+
}
729+
wakeMode = action.mode;
729730
continue;
730731
}
731732
const prepared = prepareMappedAgentDispatchOrRespond(action);
@@ -734,7 +735,12 @@ export function createHooksRequestHandler(
734735
}
735736
dispatches.push(prepared);
736737
}
738+
if (dispatches.length === 0) {
739+
sendJson(res, 200, { ok: true, mode: wakeMode ?? "now" });
740+
return true;
741+
}
737742
if (!mapped.fanout) {
743+
// Non-fanout mappings produce exactly one action.
738744
const dispatched = await dispatches[0]!();
739745
sendAgentDispatchResult(res, dispatched);
740746
return true;

0 commit comments

Comments
 (0)