Skip to content

Commit 2cd2363

Browse files
fix(reef): close provider streams after guard errors (#109196)
1 parent 6d20432 commit 2cd2363

2 files changed

Lines changed: 35 additions & 11 deletions

File tree

‎extensions/reef/protocol/guard-adapters.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ export function createOpenAiGuard(options: AdapterOptions): GuardAdapter {
5858
}),
5959
});
6060
if (!response.ok) {
61+
await response.body?.cancel().catch(() => undefined);
6162
throw new Error(`guard HTTP ${response.status}`);
6263
}
6364
const envelope = await parseJsonResponse(response);
@@ -113,6 +114,7 @@ export function createAnthropicGuard(options: AdapterOptions): GuardAdapter {
113114
}),
114115
});
115116
if (!response.ok) {
117+
await response.body?.cancel().catch(() => undefined);
116118
throw new Error(`guard HTTP ${response.status}`);
117119
}
118120
const envelope = await parseJsonResponse(response);

‎extensions/reef/protocol/guard.test.ts‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -169,17 +169,39 @@ describe("provider adapters", () => {
169169
});
170170
});
171171

172-
it("fails closed on non-200 provider responses", async () => {
173-
const guard = createOpenAiGuard({
174-
apiKey: "test",
175-
pinnedModel: model,
176-
fetch: async () => jsonResponse({ error: "no" }, 500),
177-
});
178-
await expect(guard.classify(request)).resolves.toMatchObject({
179-
decision: "deny",
180-
category: "guard_failure",
181-
});
182-
});
172+
it.each([
173+
[
174+
"OpenAI",
175+
(fetch: FetchLike) => createOpenAiGuard({ apiKey: "test", pinnedModel: model, fetch }),
176+
],
177+
[
178+
"Anthropic",
179+
(fetch: FetchLike) => createAnthropicGuard({ apiKey: "test", pinnedModel: model, fetch }),
180+
],
181+
])(
182+
"cancels %s non-200 provider response bodies before failing closed",
183+
async (_name, createGuard) => {
184+
let cancelled = false;
185+
const response = new Response(
186+
new ReadableStream<Uint8Array>({
187+
start(controller) {
188+
controller.enqueue(new TextEncoder().encode("partial error body"));
189+
},
190+
cancel() {
191+
cancelled = true;
192+
},
193+
}),
194+
{ status: 503 },
195+
);
196+
const guard = createGuard(async () => response);
197+
198+
await expect(guard.classify(request)).resolves.toMatchObject({
199+
decision: "deny",
200+
category: "guard_failure",
201+
});
202+
expect(cancelled).toBe(true);
203+
},
204+
);
183205

184206
it("cancels oversized provider response streams before buffering them fully", async () => {
185207
const maxBytes = 256 * 1024;

0 commit comments

Comments
 (0)