@@ -58,25 +58,27 @@ function makeGeminiClient(): GeminiEmbeddingClient {
5858type GeminiBatchRequest = Parameters<typeof runGeminiEmbeddingBatches>[0]["requests"][number];
5959
6060function 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- },
61+ return makeRequests(1);
62+ }
63+
64+ function makeRequests(count: number): GeminiBatchRequest[] {
65+ return Array.from({ length: count }, (_, index) => ({
66+ custom_id: `r${index}`,
67+ request: {
68+ model: "models/text-embedding-004",
69+ content: { parts: [{ text: `hello-${index}` }] },
70+ taskType: "RETRIEVAL_DOCUMENT",
6971 },
70- ] ;
72+ })) ;
7173}
7274
73- function makeOversizedResponse(): {
75+ function makeOversizedResponse(init?: ResponseInit ): {
7476 response: Response;
7577 getReadCount: () => number;
7678 wasCanceled: () => boolean;
7779} {
7880 const chunkSize = 1024 * 1024;
79- const chunkCount = 20; // 20 MiB — over 16 MiB cap
81+ const chunkCount = 20; // 20 MiB, over the 16 MiB provider response cap.
8082 let readCount = 0;
8183 let canceled = false;
8284 return {
@@ -94,14 +96,103 @@ function makeOversizedResponse(): {
9496 canceled = true;
9597 },
9698 }),
97- { status: 200, headers: { "Content-Type": "application/json" } },
99+ { status: 200, headers: { "Content-Type": "application/json" }, ...init },
100+ ),
101+ getReadCount: () => readCount,
102+ wasCanceled: () => canceled,
103+ };
104+ }
105+
106+ function makeJsonlLinesResponse(lines: string[]): {
107+ response: Response;
108+ getReadCount: () => number;
109+ wasCanceled: () => boolean;
110+ } {
111+ let readCount = 0;
112+ let canceled = false;
113+ return {
114+ response: new Response(
115+ new ReadableStream<Uint8Array>({
116+ pull(controller) {
117+ if (readCount >= lines.length) {
118+ controller.close();
119+ return;
120+ }
121+ controller.enqueue(new TextEncoder().encode(`${lines[readCount]}\n`));
122+ readCount += 1;
123+ },
124+ cancel() {
125+ canceled = true;
126+ },
127+ }),
128+ { status: 200, headers: { "Content-Type": "application/jsonl" } },
98129 ),
99130 getReadCount: () => readCount,
100131 wasCanceled: () => canceled,
101132 };
102133}
103134
104135describe("Google embedding-batch bounded JSON reads", () => {
136+ it("bounds oversized file-upload error bodies and cancels the stream", async () => {
137+ const streamed = makeOversizedResponse({ status: 500 });
138+ vi.stubGlobal(
139+ "fetch",
140+ vi.fn(async (input: RequestInfo | URL) => {
141+ if (fetchInputUrl(input).includes("/upload/")) {
142+ return streamed.response;
143+ }
144+ return new Response("unexpected", { status: 500 });
145+ }),
146+ );
147+
148+ await expect(
149+ runGeminiEmbeddingBatches({
150+ gemini: makeGeminiClient(),
151+ agentId: "main",
152+ requests: singleRequest(),
153+ wait: true,
154+ concurrency: 1,
155+ pollIntervalMs: 50,
156+ timeoutMs: 5_000,
157+ }),
158+ ).rejects.toThrow(/gemini batch file upload failed: 500/);
159+
160+ expect(streamed.wasCanceled()).toBe(true);
161+ expect(streamed.getReadCount()).toBeLessThan(20);
162+ });
163+
164+ it("bounds oversized batch-create error bodies and cancels the stream", async () => {
165+ const streamed = makeOversizedResponse({ status: 500 });
166+ vi.stubGlobal(
167+ "fetch",
168+ vi.fn(async (input: RequestInfo | URL) => {
169+ const url = fetchInputUrl(input);
170+ if (url.includes("/upload/")) {
171+ return jsonResponse({ name: "files/f-ok" });
172+ }
173+ if (url.includes(":asyncBatchEmbedContent")) {
174+ return streamed.response;
175+ }
176+ return new Response("unexpected", { status: 500 });
177+ }),
178+ );
179+
180+ await expect(
181+ runGeminiEmbeddingBatches({
182+ gemini: makeGeminiClient(),
183+ agentId: "main",
184+ requests: singleRequest(),
185+ wait: true,
186+ concurrency: 1,
187+ pollIntervalMs: 50,
188+ timeoutMs: 5_000,
189+ }),
190+ ).rejects.toThrow(/gemini batch create failed: 500/);
191+
192+ expect(streamed.wasCanceled()).toBe(true);
193+ expect(streamed.getReadCount()).toBeLessThan(20);
194+ });
195+
105196 it("bounds oversized file-upload JSON response and cancels the stream", async () => {
106197 const streamed = makeOversizedResponse();
107198 vi.stubGlobal(
@@ -243,4 +334,202 @@ describe("Google embedding-batch bounded JSON reads", () => {
243334
244335 expect(result.get("r0")).toEqual([1, 0, 0]);
245336 });
337+
338+ it("streams valid batch output files larger than the provider text cap", async () => {
339+ const requestCount = 18;
340+ const requests = makeRequests(requestCount);
341+ const padding = "x".repeat(1024 * 1024);
342+ const output = requests
343+ .map((request) =>
344+ JSON.stringify({
345+ key: request.custom_id,
346+ embedding: { values: [1, 0, 0] },
347+ padding,
348+ }),
349+ )
350+ .join("\n");
351+ expect(new TextEncoder().encode(output).byteLength).toBeGreaterThan(16 * 1024 * 1024);
352+
353+ let statusCalled = false;
354+ vi.stubGlobal(
355+ "fetch",
356+ vi.fn(async (input: RequestInfo | URL) => {
357+ const url = fetchInputUrl(input);
358+ if (url.includes("/upload/")) {
359+ return jsonResponse({ name: "files/f-ok" });
360+ }
361+ if (url.includes(":asyncBatchEmbedContent")) {
362+ return jsonResponse({ name: "batches/b-0", state: "PENDING" });
363+ }
364+ if (url.includes("/batches/") && !statusCalled) {
365+ statusCalled = true;
366+ return jsonResponse({
367+ name: "batches/b-0",
368+ state: "SUCCEEDED",
369+ outputConfig: { file: "files/out-0" },
370+ });
371+ }
372+ if (url.includes(":download")) {
373+ return new Response(output, { status: 200 });
374+ }
375+ return new Response("unexpected", { status: 500 });
376+ }),
377+ );
378+
379+ const result = await runGeminiEmbeddingBatches({
380+ gemini: makeGeminiClient(),
381+ agentId: "main",
382+ requests,
383+ wait: true,
384+ concurrency: 1,
385+ pollIntervalMs: 50,
386+ timeoutMs: 5_000,
387+ });
388+
389+ expect(result.size).toBe(requestCount);
390+ expect(result.get("r0")).toEqual([1, 0, 0]);
391+ expect(result.get("r17")).toEqual([1, 0, 0]);
392+ });
393+
394+ it("bounds oversized batch output downloads and cancels the stream", async () => {
395+ const streamed = makeOversizedResponse({ headers: { "Content-Type": "application/jsonl" } });
396+ let statusCalled = false;
397+ vi.stubGlobal(
398+ "fetch",
399+ vi.fn(async (input: RequestInfo | URL) => {
400+ const url = fetchInputUrl(input);
401+ if (url.includes("/upload/")) {
402+ return jsonResponse({ name: "files/f-ok" });
403+ }
404+ if (url.includes(":asyncBatchEmbedContent")) {
405+ return jsonResponse({ name: "batches/b-0", state: "PENDING" });
406+ }
407+ if (url.includes("/batches/") && !statusCalled) {
408+ statusCalled = true;
409+ return jsonResponse({
410+ name: "batches/b-0",
411+ state: "SUCCEEDED",
412+ outputConfig: { file: "files/out-0" },
413+ });
414+ }
415+ if (url.includes(":download")) {
416+ return streamed.response;
417+ }
418+ return new Response("unexpected", { status: 500 });
419+ }),
420+ );
421+
422+ await expect(
423+ runGeminiEmbeddingBatches({
424+ gemini: makeGeminiClient(),
425+ agentId: "main",
426+ requests: singleRequest(),
427+ wait: true,
428+ concurrency: 1,
429+ pollIntervalMs: 50,
430+ timeoutMs: 5_000,
431+ }),
432+ ).rejects.toThrow(/gemini\.batch-file-content: JSONL line exceeds/);
433+
434+ expect(streamed.wasCanceled()).toBe(true);
435+ expect(streamed.getReadCount()).toBeLessThan(20);
436+ });
437+
438+ it("bounds batch output record count to the submitted request group", async () => {
439+ const streamed = makeJsonlLinesResponse([
440+ JSON.stringify({ key: "r0", embedding: { values: [1, 0, 0] } }),
441+ ...Array.from({ length: 19 }, (_, index) =>
442+ JSON.stringify({ key: `unexpected-${index}`, embedding: { values: [1, 0, 0] } }),
443+ ),
444+ ]);
445+ let statusCalled = false;
446+ vi.stubGlobal(
447+ "fetch",
448+ vi.fn(async (input: RequestInfo | URL) => {
449+ const url = fetchInputUrl(input);
450+ if (url.includes("/upload/")) {
451+ return jsonResponse({ name: "files/f-ok" });
452+ }
453+ if (url.includes(":asyncBatchEmbedContent")) {
454+ return jsonResponse({ name: "batches/b-0", state: "PENDING" });
455+ }
456+ if (url.includes("/batches/") && !statusCalled) {
457+ statusCalled = true;
458+ return jsonResponse({
459+ name: "batches/b-0",
460+ state: "SUCCEEDED",
461+ outputConfig: { file: "files/out-0" },
462+ });
463+ }
464+ if (url.includes(":download")) {
465+ return streamed.response;
466+ }
467+ return new Response("unexpected", { status: 500 });
468+ }),
469+ );
470+
471+ await expect(
472+ runGeminiEmbeddingBatches({
473+ gemini: makeGeminiClient(),
474+ agentId: "main",
475+ requests: singleRequest(),
476+ wait: true,
477+ concurrency: 1,
478+ pollIntervalMs: 50,
479+ timeoutMs: 5_000,
480+ }),
481+ ).rejects.toThrow(/gemini\.batch-file-content: JSONL output exceeds 1 records/);
482+
483+ expect(streamed.wasCanceled()).toBe(true);
484+ expect(streamed.getReadCount()).toBeLessThan(20);
485+ });
486+
487+ it("counts blank batch output records against the submitted request group", async () => {
488+ const streamed = makeJsonlLinesResponse([
489+ JSON.stringify({ key: "r0", embedding: { values: [1, 0, 0] } }),
490+ "",
491+ "",
492+ "",
493+ ]);
494+ let statusCalled = false;
495+ vi.stubGlobal(
496+ "fetch",
497+ vi.fn(async (input: RequestInfo | URL) => {
498+ const url = fetchInputUrl(input);
499+ if (url.includes("/upload/")) {
500+ return jsonResponse({ name: "files/f-ok" });
501+ }
502+ if (url.includes(":asyncBatchEmbedContent")) {
503+ return jsonResponse({ name: "batches/b-0", state: "PENDING" });
504+ }
505+ if (url.includes("/batches/") && !statusCalled) {
506+ statusCalled = true;
507+ return jsonResponse({
508+ name: "batches/b-0",
509+ state: "SUCCEEDED",
510+ outputConfig: { file: "files/out-0" },
511+ });
512+ }
513+ if (url.includes(":download")) {
514+ return streamed.response;
515+ }
516+ return new Response("unexpected", { status: 500 });
517+ }),
518+ );
519+
520+ await expect(
521+ runGeminiEmbeddingBatches({
522+ gemini: makeGeminiClient(),
523+ agentId: "main",
524+ requests: singleRequest(),
525+ wait: true,
526+ concurrency: 1,
527+ pollIntervalMs: 50,
528+ timeoutMs: 5_000,
529+ }),
530+ ).rejects.toThrow(/gemini\.batch-file-content: JSONL output exceeds 1 records/);
531+
532+ expect(streamed.wasCanceled()).toBe(true);
533+ expect(streamed.getReadCount()).toBeLessThan(4);
534+ });
246535});
0 commit comments