Skip to content

Commit 6de4b47

Browse files
RileyJJYsteipete
andauthored
fix(ollama): release failed discovery bodies (#109967)
* fix(ollama): release failed discovery bodies * test(ollama): prove failed discovery sockets close --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent c371331 commit 6de4b47

2 files changed

Lines changed: 166 additions & 0 deletions

File tree

‎extensions/ollama/src/provider-models.test.ts‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
// Ollama tests cover provider models plugin behavior.
2+
import { once } from "node:events";
3+
import { createServer } from "node:http";
4+
import type { Socket } from "node:net";
25
import { expectDefined } from "@openclaw/normalization-core";
36
import { jsonResponse, requestBodyText, requestUrl } from "openclaw/plugin-sdk/test-env";
47
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -14,6 +17,28 @@ import {
1417
type OllamaTagModel,
1518
} from "./provider-models.js";
1619

20+
function cancelTrackedResponse(
21+
text: string,
22+
init: ResponseInit,
23+
): {
24+
response: Response;
25+
wasCanceled: () => boolean;
26+
} {
27+
let canceled = false;
28+
const stream = new ReadableStream<Uint8Array>({
29+
start(controller) {
30+
controller.enqueue(new TextEncoder().encode(text));
31+
},
32+
cancel() {
33+
canceled = true;
34+
},
35+
});
36+
return {
37+
response: new Response(stream, init),
38+
wasCanceled: () => canceled,
39+
};
40+
}
41+
1742
describe("ollama provider models", () => {
1843
afterEach(() => {
1944
vi.unstubAllGlobals();
@@ -431,6 +456,145 @@ describe("ollama provider models", () => {
431456
expect(info.contextWindow).toBe(expected);
432457
});
433458

459+
it("cancels non-OK discovery response bodies before fallback results", async () => {
460+
const tagsResponse = cancelTrackedResponse("ollama unavailable", { status: 503 });
461+
vi.stubGlobal(
462+
"fetch",
463+
vi.fn(async () => tagsResponse.response),
464+
);
465+
466+
await expect(fetchOllamaModels("http://127.0.0.1:11434")).resolves.toEqual({
467+
reachable: true,
468+
models: [],
469+
});
470+
expect(tagsResponse.wasCanceled()).toBe(true);
471+
472+
const showResponse = cancelTrackedResponse("model unavailable", { status: 503 });
473+
vi.stubGlobal(
474+
"fetch",
475+
vi.fn(async () => showResponse.response),
476+
);
477+
478+
await expect(queryOllamaModelShowInfo("http://127.0.0.1:11434", "llama3:8b")).resolves.toEqual(
479+
{},
480+
);
481+
expect(showResponse.wasCanceled()).toBe(true);
482+
});
483+
484+
it("closes real failed discovery sockets while preserving successful discovery", async () => {
485+
const sockets = new Set<Socket>();
486+
const socketClosures = new Map<string, Promise<void>>();
487+
let mode: "failure" | "success" = "failure";
488+
489+
const server = createServer((request, response) => {
490+
const path = request.url;
491+
if (path !== "/api/tags" && path !== "/api/show") {
492+
response.writeHead(404);
493+
response.end();
494+
return;
495+
}
496+
497+
if (mode === "failure") {
498+
socketClosures.set(
499+
path,
500+
new Promise<void>((resolve) => {
501+
request.socket.once("close", () => resolve());
502+
}),
503+
);
504+
response.writeHead(503, { "content-type": "text/plain" });
505+
// Leave the body open so only real client cancellation can close its socket.
506+
response.write("ollama unavailable");
507+
return;
508+
}
509+
510+
response.writeHead(200, { "content-type": "application/json" });
511+
if (path === "/api/tags") {
512+
response.end(JSON.stringify({ models: [{ name: "llama3:8b" }] }));
513+
return;
514+
}
515+
response.end(
516+
JSON.stringify({
517+
model_info: { "llama.context_length": 32768 },
518+
capabilities: ["completion", "tools"],
519+
}),
520+
);
521+
});
522+
523+
server.on("connection", (socket) => {
524+
sockets.add(socket);
525+
socket.once("close", () => sockets.delete(socket));
526+
});
527+
528+
const waitForSocketClose = async (path: string): Promise<void> => {
529+
const closed = socketClosures.get(path);
530+
if (!closed) {
531+
throw new Error(`No failed discovery socket was recorded for ${path}`);
532+
}
533+
534+
let timeout: ReturnType<typeof setTimeout> | undefined;
535+
try {
536+
await Promise.race([
537+
closed,
538+
new Promise<never>((_resolve, reject) => {
539+
timeout = setTimeout(() => {
540+
reject(new Error(`Failed discovery socket was not closed for ${path}`));
541+
}, 2_000);
542+
}),
543+
]);
544+
} finally {
545+
if (timeout !== undefined) {
546+
clearTimeout(timeout);
547+
}
548+
}
549+
};
550+
551+
const listening = once(server, "listening");
552+
try {
553+
server.listen(0, "127.0.0.1");
554+
await listening;
555+
556+
const address = server.address();
557+
if (!address || typeof address === "string") {
558+
throw new Error("Ollama test server did not expose a TCP address");
559+
}
560+
const baseUrl = `http://127.0.0.1:${address.port}`;
561+
562+
await expect(fetchOllamaModels(baseUrl)).resolves.toEqual({
563+
reachable: true,
564+
models: [],
565+
});
566+
await waitForSocketClose("/api/tags");
567+
568+
await expect(queryOllamaModelShowInfo(baseUrl, "llama3:8b")).resolves.toEqual({});
569+
await waitForSocketClose("/api/show");
570+
571+
mode = "success";
572+
await expect(fetchOllamaModels(baseUrl)).resolves.toEqual({
573+
reachable: true,
574+
models: [{ name: "llama3:8b" }],
575+
});
576+
await expect(queryOllamaModelShowInfo(baseUrl, "llama3:8b")).resolves.toEqual({
577+
contextWindow: 32768,
578+
capabilities: ["completion", "tools"],
579+
});
580+
} finally {
581+
for (const socket of sockets) {
582+
socket.destroy();
583+
}
584+
if (server.listening) {
585+
await new Promise<void>((resolve, reject) => {
586+
server.close((error) => {
587+
if (error) {
588+
reject(error);
589+
return;
590+
}
591+
resolve();
592+
});
593+
});
594+
}
595+
}
596+
});
597+
434598
it("fails soft and stops reading when discovery streams exceed the JSON byte cap", async () => {
435599
// Larger than the shared 16 MiB readProviderJsonResponse cap so the bounded reader cancels
436600
// the stream mid-flight; if the cap were removed the reader would buffer the whole payload.

‎extensions/ollama/src/provider-models.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@ export async function queryOllamaModelShowInfo(
154154
});
155155
try {
156156
if (!response.ok) {
157+
await response.body?.cancel().catch(() => undefined);
157158
return {};
158159
}
159160
const data = await readProviderJsonResponse<{
@@ -376,6 +377,7 @@ export async function fetchOllamaModels(
376377
});
377378
try {
378379
if (!response.ok) {
380+
await response.body?.cancel().catch(() => undefined);
379381
return { reachable: true, models: [] };
380382
}
381383
const data = await readProviderJsonResponse<OllamaTagsResponse>(

0 commit comments

Comments
 (0)