Skip to content

Commit d54968a

Browse files
fix(ollama): bound native streaming 200 success-body NDJSON reads at 16 MiB (v2, no SDK subpath)
Version 2 of #99585 — removes the Plugin SDK subpath (`openclaw/plugin-sdk/stream-reader-with-limit`) based on ClawSweeper feedback (merge-risk: compatibility). Changes: - Bounds Ollama chat (/api/chat) NDJSON success-stream reads at 16 MiB with reader cancellation on overflow - Bounds Ollama model-pull (/api/pull) NDJSON success-stream reads at 16 MiB with reader cancellation on overflow - Plugin-local `createSseByteGuard` helper in `extensions/ollama/src/sse-byte-guard.ts` (internal seam, no new SDK subpath) - Full test coverage: deterministic overflow, negative control, real TCP loopback proof - No new Plugin SDK entrypoint, no config/env changes, no public API changes Diff: +249/-4 across 5 files (4 modified + 1 new)
1 parent f32c36c commit d54968a

5 files changed

Lines changed: 334 additions & 4 deletions

File tree

‎extensions/ollama/src/setup.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,59 @@ describe("ollama setup", () => {
557557
}
558558
});
559559

560+
it("bounds oversized pull body and cancels the stream", async () => {
561+
const chunk = new Uint8Array(1024 * 1024); // 1 MiB chunk
562+
let readCount = 0;
563+
let canceled = false;
564+
// 64 chunks × 1 MiB = 64 MiB — exceeds the 16 MiB cap
565+
const oversizedBody = new ReadableStream<Uint8Array>({
566+
pull(controller) {
567+
if (readCount >= 64) {
568+
controller.close();
569+
return;
570+
}
571+
readCount += 1;
572+
controller.enqueue(chunk);
573+
},
574+
cancel() {
575+
canceled = true;
576+
},
577+
});
578+
579+
const progress = { update: vi.fn(), stop: vi.fn() };
580+
const prompter = {
581+
progress: vi.fn(() => progress),
582+
} as unknown as WizardPrompter;
583+
584+
const fetchMock = vi.fn(async (input: string | URL | Request) => {
585+
const url = requestUrl(input);
586+
if (url.endsWith("/api/tags")) {
587+
return jsonResponse({ models: [] });
588+
}
589+
if (url.endsWith("/api/pull")) {
590+
return new Response(oversizedBody, { status: 200 });
591+
}
592+
throw new Error(`Unexpected fetch: ${url}`);
593+
});
594+
vi.stubGlobal("fetch", fetchMock);
595+
596+
await ensureOllamaModelPulled({
597+
config: createDefaultOllamaConfig("ollama/gemma4"),
598+
model: "ollama/gemma4",
599+
prompter,
600+
}).catch((err: unknown) => err);
601+
602+
// Stream must be cancelled well before all 64 MiB are consumed.
603+
expect(readCount).toBeLessThan(64);
604+
expect(canceled).toBe(true);
605+
// The spinner must surface the canonical bounded-read error.
606+
expect(progress.stop).toHaveBeenCalledWith(
607+
expect.stringMatching(
608+
/^Failed to download gemma4: Ollama pull body exceeded \d+ bytes \(received \d+\)$/,
609+
),
610+
);
611+
});
612+
560613
it("skips pull when model is already available", async () => {
561614
const prompter = {} as unknown as WizardPrompter;
562615

‎extensions/ollama/src/setup.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { applyAgentDefaultModelPrimary } from "openclaw/plugin-sdk/provider-onbo
1818
import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime";
1919
import { WizardCancelledError, type WizardPrompter } from "openclaw/plugin-sdk/setup";
2020
import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
21+
import { createSseByteGuard } from "./sse-byte-guard.js";
2122
import {
2223
normalizeLowercaseStringOrEmpty,
2324
normalizeOptionalLowercaseString,
@@ -48,6 +49,7 @@ const OLLAMA_CONTEXT_ENRICH_LIMIT = 200;
4849
const OLLAMA_CLOUD_MAX_DISCOVERED_MODELS = 500;
4950
const OLLAMA_PULL_RESPONSE_TIMEOUT_MS = 30_000;
5051
const OLLAMA_PULL_STREAM_IDLE_TIMEOUT_MS = 300_000;
52+
const OLLAMA_PULL_STREAM_MAX_BYTES = 16 * 1024 * 1024;
5153

5254
type OllamaSetupOptions = {
5355
customBaseUrl?: string;
@@ -177,7 +179,7 @@ type OllamaPullChunk = {
177179
type OllamaPullResult = { ok: true } | { ok: false; message: string };
178180

179181
async function readOllamaPullChunkWithIdleTimeout(
180-
reader: ReadableStreamDefaultReader<Uint8Array>,
182+
reader: Pick<ReadableStreamDefaultReader<Uint8Array>, "read" | "cancel">,
181183
): Promise<ReadableStreamReadResult<Uint8Array>> {
182184
let timeoutId: ReturnType<typeof setTimeout> | undefined;
183185
let timedOut = false;
@@ -251,7 +253,12 @@ async function pullOllamaModelCore(params: {
251253
return { ok: false, message: `Failed to download ${modelName} (no response body)` };
252254
}
253255

254-
const reader = response.body.getReader();
256+
const rawReader = response.body.getReader();
257+
const reader = createSseByteGuard(rawReader, {
258+
maxBytes: OLLAMA_PULL_STREAM_MAX_BYTES,
259+
onOverflow: ({ size, maxBytes }) =>
260+
new Error(`Ollama pull body exceeded ${maxBytes} bytes (received ${size})`),
261+
});
255262
const decoder = new TextDecoder();
256263
let buffer = "";
257264
const layers = new Map<string, { total: number; completed: number }>();
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* Plugin-local bounded SSE / NDJSON stream reader guard.
3+
*
4+
* Internal seam until `createSseByteGuard` is promoted to a public Plugin SDK
5+
* subpath in a future PR. The canonical implementation lives in
6+
* `packages/ai/src/utils/streaming-byte-guard.ts`.
7+
*
8+
* Wraps a `ReadableStreamDefaultReader<Uint8Array>` so the caller's existing
9+
* chunk-by-chunk parsing logic is unchanged, but accumulated bytes are tracked
10+
* against a hard cap. On overflow the underlying reader is cancelled and a
11+
* canonical error is thrown.
12+
*/
13+
14+
export type SseStreamOverflow = {
15+
size: number;
16+
maxBytes: number;
17+
};
18+
19+
export type ReadSseStreamWithLimitOptions = {
20+
maxBytes: number;
21+
onOverflow?: (params: SseStreamOverflow) => Error;
22+
};
23+
24+
export type SseByteGuard = {
25+
read(): Promise<ReadableStreamReadResult<Uint8Array>>;
26+
cancel(reason?: unknown): Promise<void>;
27+
totalBytes(): number;
28+
overflowed(): boolean;
29+
cancelled(): boolean;
30+
};
31+
32+
export function createSseByteGuard(
33+
reader: ReadableStreamDefaultReader<Uint8Array>,
34+
opts: ReadSseStreamWithLimitOptions,
35+
): SseByteGuard {
36+
if (!Number.isFinite(opts.maxBytes) || opts.maxBytes < 0) {
37+
throw new RangeError(`maxBytes must be a non-negative finite number: ${opts.maxBytes}`);
38+
}
39+
const onOverflow =
40+
opts.onOverflow ??
41+
((params) =>
42+
new Error(`SSE stream exceeds ${params.maxBytes} bytes (received ${params.size})`));
43+
let total = 0;
44+
let overflowedFlag = false;
45+
let cancelledFlag = false;
46+
return {
47+
read: async () => {
48+
if (overflowedFlag || cancelledFlag) {
49+
return { done: true, value: undefined };
50+
}
51+
const result = await reader.read();
52+
if (result.done) {
53+
return result;
54+
}
55+
const chunkLen = result.value?.byteLength ?? 0;
56+
const next = total + chunkLen;
57+
if (next > opts.maxBytes) {
58+
overflowedFlag = true;
59+
cancelledFlag = true;
60+
const err = onOverflow({ size: next, maxBytes: opts.maxBytes });
61+
try {
62+
await reader.cancel(err);
63+
} catch {
64+
// best-effort cancellation; caller observes the overflow error
65+
}
66+
throw err;
67+
}
68+
total = next;
69+
return result;
70+
},
71+
cancel: async (reason?: unknown) => {
72+
if (overflowedFlag) {
73+
return;
74+
}
75+
cancelledFlag = true;
76+
try {
77+
await reader.cancel(reason);
78+
} catch {
79+
// best-effort cancellation
80+
}
81+
},
82+
totalBytes: () => total,
83+
overflowed: () => overflowedFlag,
84+
cancelled: () => cancelledFlag,
85+
};
86+
}

‎extensions/ollama/src/stream-runtime.test.ts‎

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createSseByteGuard } from "./sse-byte-guard.js";
12
// Ollama tests cover stream runtime plugin behavior.
23
import { afterEach, describe, expect, it, vi } from "vitest";
34

@@ -1603,6 +1604,182 @@ describe("parseNdjsonStream", () => {
16031604
});
16041605
});
16051606

1607+
describe("parseNdjsonStream bounded read (16 MiB cap)", () => {
1608+
// Layer 1: inline deterministic overflow. 32 × 1 MiB chunks advertised by a
1609+
// fake pull stream. The wrapped reader must cancel and throw the canonical
1610+
// overflow error after ~16 MiB, long before the full 32 MiB is drained.
1611+
it("cancels and throws when bytes exceed 16 MiB", async () => {
1612+
const CHUNK = 1024 * 1024; // 1 MiB
1613+
const TOTAL_CHUNKS = 32; // 32 MiB server-side
1614+
let pullCount = 0;
1615+
let cancelReason: unknown;
1616+
const overflowing = new ReadableStream<Uint8Array>({
1617+
pull(controller) {
1618+
pullCount += 1;
1619+
if (pullCount > TOTAL_CHUNKS) {
1620+
controller.close();
1621+
return;
1622+
}
1623+
controller.enqueue(new Uint8Array(CHUNK));
1624+
},
1625+
cancel(reason) {
1626+
cancelReason = reason;
1627+
},
1628+
});
1629+
const guarded = createSseByteGuard(overflowing.getReader(), {
1630+
maxBytes: 16 * 1024 * 1024,
1631+
onOverflow: ({ size, maxBytes }) =>
1632+
new Error(`Ollama streaming body exceeded ${maxBytes} bytes (received ${size})`),
1633+
});
1634+
1635+
let thrown: Error | undefined;
1636+
try {
1637+
for await (const _ of parseNdjsonStream(guarded)) {
1638+
// exhaust — overflow must fire on the read that crosses 16 MiB
1639+
}
1640+
} catch (err) {
1641+
thrown = err as Error;
1642+
}
1643+
1644+
expect(thrown).toBeInstanceOf(Error);
1645+
expect(thrown?.message).toMatch(
1646+
/^Ollama streaming body exceeded 16777216 bytes \(received \d+\)$/,
1647+
);
1648+
// pullCount must be capped somewhere in [17, 20]: 16 MiB exact cap leaves
1649+
// room for one in-flight chunk read plus one TCP-coalesced tail.
1650+
expect(pullCount).toBeGreaterThanOrEqual(17);
1651+
expect(pullCount).toBeLessThanOrEqual(20);
1652+
expect(cancelReason).toBeInstanceOf(Error);
1653+
expect(guarded.overflowed()).toBe(true);
1654+
expect(guarded.cancelled()).toBe(true);
1655+
});
1656+
1657+
// Layer 2: negative control. A small valid NDJSON response must drain
1658+
// end-to-end without overflow. Proves the cap is the cause of rejection,
1659+
// not body structure.
1660+
it("drains small valid NDJSON without overflow", async () => {
1661+
const lines = [
1662+
'{"model":"m","created_at":"t","message":{"role":"assistant","content":"hello"},"done":false}',
1663+
'{"model":"m","created_at":"t","message":{"role":"assistant","content":""},"done":true,"prompt_eval_count":5,"eval_count":2}',
1664+
];
1665+
const reader = mockNdjsonReader(lines);
1666+
const guarded = createSseByteGuard(reader, {
1667+
maxBytes: 16 * 1024 * 1024,
1668+
onOverflow: ({ size, maxBytes }) =>
1669+
new Error(`Ollama streaming body exceeded ${maxBytes} bytes (received ${size})`),
1670+
});
1671+
1672+
const chunks = [];
1673+
for await (const chunk of parseNdjsonStream(guarded)) {
1674+
chunks.push(chunk);
1675+
}
1676+
expect(chunks).toHaveLength(2);
1677+
expect(chunks[1].done).toBe(true);
1678+
expect(guarded.totalBytes()).toBeLessThan(16 * 1024 * 1024);
1679+
expect(guarded.overflowed()).toBe(false);
1680+
});
1681+
1682+
// Layer 3: loopback http.createServer real-wire proof. Drives the
1683+
// production `createSseByteGuard` over a real TCP socket. Server streams
1684+
// unbounded 1 MiB chunks with no newline terminator; client overflows at
1685+
// 16 MiB and observes the same canonical error message.
1686+
it("bounds real TCP-streamed NDJSON body without content-length", async () => {
1687+
const { createServer } = await import("node:http");
1688+
type AddressInfo = { address: string; family: string; port: number };
1689+
const CHUNK = 1024 * 1024;
1690+
const TOTAL_CHUNKS = 64;
1691+
let bytesSent = 0;
1692+
let aborted = false;
1693+
1694+
const server = createServer((req, res) => {
1695+
res.writeHead(200, {
1696+
"Content-Type": "application/x-ndjson",
1697+
"Transfer-Encoding": "chunked",
1698+
});
1699+
let i = 0;
1700+
const interval = setInterval(() => {
1701+
if (aborted || i >= TOTAL_CHUNKS) {
1702+
clearInterval(interval);
1703+
res.end();
1704+
return;
1705+
}
1706+
i += 1;
1707+
bytesSent += CHUNK;
1708+
res.write(new Uint8Array(CHUNK));
1709+
}, 1);
1710+
req.on("close", () => {
1711+
aborted = true;
1712+
clearInterval(interval);
1713+
});
1714+
});
1715+
1716+
await new Promise<void>((resolve) => {
1717+
server.listen(0, "127.0.0.1", () => resolve());
1718+
});
1719+
const address = server.address() as AddressInfo;
1720+
const port = address.port;
1721+
1722+
try {
1723+
const response = await fetch(`http://127.0.0.1:${port}/api/chat`, {
1724+
method: "POST",
1725+
body: "{}",
1726+
});
1727+
if (!response.body) {
1728+
throw new Error("loopback test setup: empty response body");
1729+
}
1730+
const guarded = createSseByteGuard(response.body.getReader(), {
1731+
maxBytes: 16 * 1024 * 1024,
1732+
onOverflow: ({ size, maxBytes }) =>
1733+
new Error(`Ollama streaming body exceeded ${maxBytes} bytes (received ${size})`),
1734+
});
1735+
1736+
let thrown: Error | undefined;
1737+
let totalRead = 0;
1738+
try {
1739+
// Keep reading until overflow throws or stream closes. Don't cap the
1740+
// read count; trust the server will cancel once the cap fires.
1741+
while (true) {
1742+
const result = await guarded.read();
1743+
if (result.done) {
1744+
break;
1745+
}
1746+
totalRead += result.value.byteLength;
1747+
}
1748+
} catch (err) {
1749+
thrown = err as Error;
1750+
}
1751+
1752+
// Print quantitative read-out for PR body evidence.
1753+
console.log(
1754+
`[layer3 loopback proof] cap=16777216, totalRead=${totalRead}, bytesSent=${bytesSent}, overflowed=${guarded.overflowed()}, cancelled=${guarded.cancelled()}, receivedBytes=${thrown?.message.match(/received (\d+)/)?.[1] ?? "?"}`,
1755+
);
1756+
1757+
expect(thrown).toBeInstanceOf(Error);
1758+
expect(thrown?.message).toMatch(
1759+
/^Ollama streaming body exceeded 16777216 bytes \(received \d+\)$/,
1760+
);
1761+
// The cap fires when `total + chunkLen > cap`. The thrown error's
1762+
// `size` is that crossed value, so receivedBytes is strictly > cap.
1763+
// totalRead is the sum of chunks actually returned (none cross cap),
1764+
// so totalRead <= cap. bytesSent is what the server kept writing
1765+
// before our cancel propagated, so bytesSent > totalRead.
1766+
const receivedMatch = thrown?.message.match(/received (\d+)/);
1767+
const receivedBytes = receivedMatch ? Number(receivedMatch[1]) : 0;
1768+
expect(receivedBytes).toBeGreaterThan(16 * 1024 * 1024);
1769+
expect(totalRead).toBeLessThanOrEqual(16 * 1024 * 1024);
1770+
expect(totalRead).toBeLessThan(bytesSent);
1771+
expect(bytesSent).toBeLessThanOrEqual(TOTAL_CHUNKS * CHUNK);
1772+
expect(guarded.overflowed()).toBe(true);
1773+
expect(guarded.cancelled()).toBe(true);
1774+
} finally {
1775+
aborted = true;
1776+
await new Promise<void>((resolve) => {
1777+
server.close(() => resolve());
1778+
});
1779+
}
1780+
});
1781+
});
1782+
16061783
async function withMockNdjsonFetch(
16071784
lines: string[],
16081785
run: (fetchMock: typeof fetchWithSsrFGuardMock) => Promise<void>,

0 commit comments

Comments
 (0)