|
| 1 | +// Google tests cover embedding batch bounded JSON response reads. |
| 2 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 3 | +import { runGeminiEmbeddingBatches } from "./embedding-batch.js"; |
| 4 | +import type { GeminiEmbeddingClient } from "./embedding-provider.js"; |
| 5 | + |
| 6 | +// Pass-through so onResponse receives real Response objects (required by |
| 7 | +// readProviderJsonResponse which needs a real .body ReadableStream). |
| 8 | +vi.mock("openclaw/plugin-sdk/memory-core-host-engine-embeddings", async (importOriginal) => { |
| 9 | + const actual = |
| 10 | + await importOriginal<typeof import("openclaw/plugin-sdk/memory-core-host-engine-embeddings")>(); |
| 11 | + return { |
| 12 | + ...actual, |
| 13 | + withRemoteHttpResponse: async <T>(params: { |
| 14 | + url: string; |
| 15 | + ssrfPolicy?: unknown; |
| 16 | + init?: RequestInit; |
| 17 | + onResponse: (response: Response) => Promise<T>; |
| 18 | + }): Promise<T> => { |
| 19 | + const response = await fetch(params.url, params.init); |
| 20 | + return await params.onResponse(response); |
| 21 | + }, |
| 22 | + }; |
| 23 | +}); |
| 24 | + |
| 25 | +afterEach(() => { |
| 26 | + vi.restoreAllMocks(); |
| 27 | + vi.unstubAllGlobals(); |
| 28 | +}); |
| 29 | + |
| 30 | +function fetchInputUrl(input: RequestInfo | URL): string { |
| 31 | + if (typeof input === "string") { |
| 32 | + return input; |
| 33 | + } |
| 34 | + if (input instanceof URL) { |
| 35 | + return input.href; |
| 36 | + } |
| 37 | + return input.url; |
| 38 | +} |
| 39 | + |
| 40 | +function jsonResponse(body: unknown, status = 200): Response { |
| 41 | + return new Response(JSON.stringify(body), { |
| 42 | + status, |
| 43 | + headers: { "Content-Type": "application/json" }, |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +function makeGeminiClient(): GeminiEmbeddingClient { |
| 48 | + return { |
| 49 | + baseUrl: "https://gemini-compatible.example/v1beta", |
| 50 | + model: "text-embedding-004", |
| 51 | + modelPath: "models/text-embedding-004", |
| 52 | + headers: { "x-goog-api-key": "test-key" }, |
| 53 | + apiKeys: ["test-key"], |
| 54 | + ssrfPolicy: undefined, |
| 55 | + }; |
| 56 | +} |
| 57 | + |
| 58 | +type GeminiBatchRequest = Parameters<typeof runGeminiEmbeddingBatches>[0]["requests"][number]; |
| 59 | + |
| 60 | +function singleRequest(): GeminiBatchRequest[] { |
| 61 | + return [ |
| 62 | + { |
| 63 | + custom_id: "r0", |
| 64 | + request: { |
| 65 | + model: "models/text-embedding-004", |
| 66 | + content: { parts: [{ text: "hello" }] }, |
| 67 | + taskType: "RETRIEVAL_DOCUMENT", |
| 68 | + }, |
| 69 | + }, |
| 70 | + ]; |
| 71 | +} |
| 72 | + |
| 73 | +function makeOversizedResponse(): { |
| 74 | + response: Response; |
| 75 | + getReadCount: () => number; |
| 76 | + wasCanceled: () => boolean; |
| 77 | +} { |
| 78 | + const chunkSize = 1024 * 1024; |
| 79 | + const chunkCount = 20; // 20 MiB — over 16 MiB cap |
| 80 | + let readCount = 0; |
| 81 | + let canceled = false; |
| 82 | + return { |
| 83 | + response: new Response( |
| 84 | + new ReadableStream<Uint8Array>({ |
| 85 | + pull(controller) { |
| 86 | + if (readCount >= chunkCount) { |
| 87 | + controller.close(); |
| 88 | + return; |
| 89 | + } |
| 90 | + readCount += 1; |
| 91 | + controller.enqueue(new Uint8Array(chunkSize)); |
| 92 | + }, |
| 93 | + cancel() { |
| 94 | + canceled = true; |
| 95 | + }, |
| 96 | + }), |
| 97 | + { status: 200, headers: { "Content-Type": "application/json" } }, |
| 98 | + ), |
| 99 | + getReadCount: () => readCount, |
| 100 | + wasCanceled: () => canceled, |
| 101 | + }; |
| 102 | +} |
| 103 | + |
| 104 | +describe("Google embedding-batch bounded JSON reads", () => { |
| 105 | + it("bounds oversized file-upload JSON response and cancels the stream", async () => { |
| 106 | + const streamed = makeOversizedResponse(); |
| 107 | + vi.stubGlobal( |
| 108 | + "fetch", |
| 109 | + vi.fn(async (input: RequestInfo | URL) => { |
| 110 | + if (fetchInputUrl(input).includes("/upload/")) { |
| 111 | + return streamed.response; |
| 112 | + } |
| 113 | + return new Response("unexpected", { status: 500 }); |
| 114 | + }), |
| 115 | + ); |
| 116 | + |
| 117 | + await expect( |
| 118 | + runGeminiEmbeddingBatches({ |
| 119 | + gemini: makeGeminiClient(), |
| 120 | + agentId: "main", |
| 121 | + requests: singleRequest(), |
| 122 | + wait: true, |
| 123 | + concurrency: 1, |
| 124 | + pollIntervalMs: 50, |
| 125 | + timeoutMs: 5_000, |
| 126 | + }), |
| 127 | + ).rejects.toThrow(/gemini\.batch-file-upload/); |
| 128 | + |
| 129 | + expect(streamed.wasCanceled()).toBe(true); |
| 130 | + expect(streamed.getReadCount()).toBeLessThan(20); |
| 131 | + }); |
| 132 | + |
| 133 | + it("bounds oversized batch-create JSON response and cancels the stream", async () => { |
| 134 | + const streamed = makeOversizedResponse(); |
| 135 | + vi.stubGlobal( |
| 136 | + "fetch", |
| 137 | + vi.fn(async (input: RequestInfo | URL) => { |
| 138 | + const url = fetchInputUrl(input); |
| 139 | + if (url.includes("/upload/")) { |
| 140 | + return jsonResponse({ name: "files/f-ok" }); |
| 141 | + } |
| 142 | + if (url.includes(":asyncBatchEmbedContent")) { |
| 143 | + return streamed.response; |
| 144 | + } |
| 145 | + return new Response("unexpected", { status: 500 }); |
| 146 | + }), |
| 147 | + ); |
| 148 | + |
| 149 | + await expect( |
| 150 | + runGeminiEmbeddingBatches({ |
| 151 | + gemini: makeGeminiClient(), |
| 152 | + agentId: "main", |
| 153 | + requests: singleRequest(), |
| 154 | + wait: true, |
| 155 | + concurrency: 1, |
| 156 | + pollIntervalMs: 50, |
| 157 | + timeoutMs: 5_000, |
| 158 | + }), |
| 159 | + ).rejects.toThrow(/gemini\.batch-create/); |
| 160 | + |
| 161 | + expect(streamed.wasCanceled()).toBe(true); |
| 162 | + expect(streamed.getReadCount()).toBeLessThan(20); |
| 163 | + }); |
| 164 | + |
| 165 | + it("bounds oversized batch-status poll JSON response and cancels the stream", async () => { |
| 166 | + const streamed = makeOversizedResponse(); |
| 167 | + let statusCalled = false; |
| 168 | + vi.stubGlobal( |
| 169 | + "fetch", |
| 170 | + vi.fn(async (input: RequestInfo | URL) => { |
| 171 | + const url = fetchInputUrl(input); |
| 172 | + if (url.includes("/upload/")) { |
| 173 | + return jsonResponse({ name: "files/f-ok" }); |
| 174 | + } |
| 175 | + if (url.includes(":asyncBatchEmbedContent")) { |
| 176 | + return jsonResponse({ name: "batches/b-0", state: "PENDING" }); |
| 177 | + } |
| 178 | + if (url.includes("/batches/") && !statusCalled) { |
| 179 | + statusCalled = true; |
| 180 | + return streamed.response; |
| 181 | + } |
| 182 | + return new Response("unexpected", { status: 500 }); |
| 183 | + }), |
| 184 | + ); |
| 185 | + |
| 186 | + await expect( |
| 187 | + runGeminiEmbeddingBatches({ |
| 188 | + gemini: makeGeminiClient(), |
| 189 | + agentId: "main", |
| 190 | + requests: singleRequest(), |
| 191 | + wait: true, |
| 192 | + concurrency: 1, |
| 193 | + pollIntervalMs: 50, |
| 194 | + timeoutMs: 5_000, |
| 195 | + }), |
| 196 | + ).rejects.toThrow(/gemini\.batch-status/); |
| 197 | + |
| 198 | + expect(streamed.wasCanceled()).toBe(true); |
| 199 | + expect(streamed.getReadCount()).toBeLessThan(20); |
| 200 | + }); |
| 201 | + |
| 202 | + it("parses small responses on all three JSON paths correctly", async () => { |
| 203 | + // Use a unit-length vector so sanitizeAndNormalizeEmbedding preserves values. |
| 204 | + const outputLine = JSON.stringify({ |
| 205 | + key: "r0", |
| 206 | + embedding: { values: [1, 0, 0] }, |
| 207 | + }); |
| 208 | + let statusCalled = false; |
| 209 | + vi.stubGlobal( |
| 210 | + "fetch", |
| 211 | + vi.fn(async (input: RequestInfo | URL) => { |
| 212 | + const url = fetchInputUrl(input); |
| 213 | + if (url.includes("/upload/")) { |
| 214 | + return jsonResponse({ name: "files/f-ok" }); |
| 215 | + } |
| 216 | + if (url.includes(":asyncBatchEmbedContent")) { |
| 217 | + return jsonResponse({ name: "batches/b-0", state: "PENDING" }); |
| 218 | + } |
| 219 | + if (url.includes("/batches/") && !statusCalled) { |
| 220 | + statusCalled = true; |
| 221 | + return jsonResponse({ |
| 222 | + name: "batches/b-0", |
| 223 | + state: "SUCCEEDED", |
| 224 | + outputConfig: { file: "files/out-0" }, |
| 225 | + }); |
| 226 | + } |
| 227 | + if (url.includes(":download")) { |
| 228 | + return new Response(outputLine, { status: 200 }); |
| 229 | + } |
| 230 | + return new Response("unexpected", { status: 500 }); |
| 231 | + }), |
| 232 | + ); |
| 233 | + |
| 234 | + const result = await runGeminiEmbeddingBatches({ |
| 235 | + gemini: makeGeminiClient(), |
| 236 | + agentId: "main", |
| 237 | + requests: singleRequest(), |
| 238 | + wait: true, |
| 239 | + concurrency: 1, |
| 240 | + pollIntervalMs: 50, |
| 241 | + timeoutMs: 5_000, |
| 242 | + }); |
| 243 | + |
| 244 | + expect(result.get("r0")).toEqual([1, 0, 0]); |
| 245 | + }); |
| 246 | +}); |
0 commit comments