diff --git a/test/anthropic.test.ts b/test/anthropic.test.ts index 7fc853c..41347b2 100644 --- a/test/anthropic.test.ts +++ b/test/anthropic.test.ts @@ -319,7 +319,20 @@ describe("POST /v1/messages", () => { }); it("resolves the media blocks of one message concurrently, keeping declaration order", async () => { - const fixture = createServer((_request, response) => { + // The fixture stays open for 60 ms per request and records how many it was + // answering at once: overlap is asserted on that counter, never on elapsed + // wall-clock time, because a shared CI runner adds tens of milliseconds to a + // whole request and a margin below that flakes (it did, on Windows). + let inFlight = 0; + let maxConcurrent = 0; + const requests: string[] = []; + const fixture = createServer((request, response) => { + inFlight += 1; + maxConcurrent = Math.max(maxConcurrent, inFlight); + requests.push(request.url ?? ""); + response.once("close", () => { + inFlight -= 1; + }); setTimeout(() => { response.writeHead(200, { "content-type": "image/png" }); response.end(Buffer.from(PNG_1X1, "base64")); @@ -340,7 +353,6 @@ describe("POST /v1/messages", () => { }, }); try { - const started = performance.now(); const response = await post(app, "/v1/messages", { model: MODEL, max_tokens: 64, @@ -354,15 +366,16 @@ describe("POST /v1/messages", () => { }, ], }); - const elapsed = performance.now() - started; expect(response.statusCode).toBe(200); const origins = capture.request?.messages[0]?.attachments?.map((attachment) => attachment.origin); // `Attachment.origin` stores `host + pathname` only, so a remote URL can // never leak its scheme, userinfo or query string (P16). expect(origins).toEqual([`127.0.0.1:${address.port}/first.png`, `127.0.0.1:${address.port}/second.png`]); - // Serial resolution would need at least 120 ms for two 60 ms responses. - expect(elapsed).toBeLessThan(110); + // Both downloads were open at once, in declaration order. A serial resolver + // would never exceed one in-flight request. + expect(maxConcurrent).toBe(2); + expect(requests).toEqual(["/first.png", "/second.png"]); } finally { fixture.closeAllConnections(); await new Promise((resolve) => fixture.close(() => resolve())); diff --git a/test/openai-chat.test.ts b/test/openai-chat.test.ts index fc744ec..6b02b08 100644 --- a/test/openai-chat.test.ts +++ b/test/openai-chat.test.ts @@ -17,10 +17,40 @@ const MODEL = "opencode/deepseek-v4.1-flash-free"; const PNG_BASE64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; -/** Serve one tiny PNG per request after `delayMs`, so serial fetches are measurable. */ -async function startPngFixture(delayMs: number): Promise<{ origin: string; close: () => Promise }> { +/** What the fixture observed while it answered: the overlap, not the clock. */ +interface PngFixtureObservation { + /** Highest number of requests the fixture was answering at the same time. */ + maxConcurrent: number; + /** Request paths in arrival order. */ + requests: string[]; +} + +/** + * Serve one tiny PNG per request after `delayMs`, for `delayMs` long enough that + * two overlapping downloads are provably simultaneous. + * + * `delayMs` is held open on the server side so concurrent requests overlap; the + * tests assert that overlap on `observed.maxConcurrent` rather than on elapsed + * wall-clock time. A shared CI runner can add tens of milliseconds of scheduling + * latency to a fast request, so a margin of a few dozen milliseconds against the + * serial sum flakes — it did, once, on the Windows CI job (123 ms against a + * 120 ms bound), while the same tree passed everywhere else. + */ +async function startPngFixture( + delayMs: number, +): Promise<{ origin: string; observed: PngFixtureObservation; close: () => Promise }> { const body = Buffer.from(PNG_BASE64, "base64"); - const server = http.createServer((_request, response) => { + const observed: PngFixtureObservation = { maxConcurrent: 0, requests: [] }; + let inFlight = 0; + const server = http.createServer((request, response) => { + inFlight += 1; + observed.maxConcurrent = Math.max(observed.maxConcurrent, inFlight); + observed.requests.push(request.url ?? ""); + // `close` fires once the response is finished or the connection is dropped, + // whichever happens first, so the counter cannot drift upwards. + response.once("close", () => { + inFlight -= 1; + }); setTimeout(() => { response.writeHead(200, { "content-type": "image/png", "content-length": String(body.byteLength) }); response.end(body); @@ -30,6 +60,7 @@ async function startPngFixture(delayMs: number): Promise<{ origin: string; close const address = server.address() as AddressInfo; return { origin: `http://127.0.0.1:${address.port}`, + observed, close: () => new Promise((resolve) => server.close(() => resolve())), }; } @@ -830,7 +861,6 @@ describe("POST /v1/chat/completions (non-streaming)", () => { const ctx = createTestContext({ config: { allowPrivateMediaUrls: true }, onRun: (request) => captured.push(request) }); const app = await buildServer(ctx); - const startedAt = Date.now(); const response = await app.inject({ method: "POST", url: "/v1/chat/completions", @@ -848,7 +878,6 @@ describe("POST /v1/chat/completions (non-streaming)", () => { ], }, }); - const elapsed = Date.now() - startedAt; expect(response.statusCode).toBe(200); const attachments = captured[0]?.messages[0]?.attachments ?? []; @@ -860,9 +889,11 @@ describe("POST /v1/chat/completions (non-streaming)", () => { expect(attachments[0]?.origin).toBe(`${fixtureHost}/first.png`); expect(attachments[1]?.origin).toBe(`${fixtureHost}/second.png`); - // Serial resolution would cost at least 2 x 80 ms; concurrent resolution - // costs max(latency), so anything well under the serial sum proves the overlap. - expect(elapsed).toBeLessThan(DELAY_MS * 2 - 40); + // Both downloads were open at the same time: the fixture was answering two + // requests at once and received them in declaration order. A serial resolver + // would never exceed one. + expect(fixture.observed.maxConcurrent).toBe(2); + expect(fixture.observed.requests).toEqual(["/first.png", "/second.png"]); await app.close(); } finally { @@ -878,7 +909,6 @@ describe("POST /v1/chat/completions (non-streaming)", () => { const ctx = createTestContext({ config: { allowPrivateMediaUrls: true }, onRun: (request) => captured.push(request) }); const app = await buildServer(ctx); - const startedAt = Date.now(); const response = await app.inject({ method: "POST", url: "/v1/chat/completions", @@ -892,7 +922,6 @@ describe("POST /v1/chat/completions (non-streaming)", () => { ], }, }); - const elapsed = Date.now() - startedAt; expect(response.statusCode).toBe(200); const attachments = captured[0]?.messages.flatMap((message) => message.attachments ?? []) ?? []; @@ -902,8 +931,11 @@ describe("POST /v1/chat/completions (non-streaming)", () => { `${fixtureHost}/first.png`, `${fixtureHost}/second.png`, ]); - // Resolving message by message serialises the pools: two fixture delays. - expect(elapsed).toBeLessThan(DELAY_MS * 2 - 40); + // One pool per request: resolving message by message would serialise the + // two downloads, so the fixture would never see them at the same time (and + // the arrival order would be the message order either way). + expect(fixture.observed.maxConcurrent).toBe(2); + expect([...fixture.observed.requests].sort()).toEqual(["/first.png", "/second.png"]); await app.close(); } finally { diff --git a/test/openai-responses.test.ts b/test/openai-responses.test.ts index bed0673..031e8dd 100644 --- a/test/openai-responses.test.ts +++ b/test/openai-responses.test.ts @@ -6,7 +6,7 @@ */ import http from "node:http"; import type { AddressInfo } from "node:net"; -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify"; import { registerOpenAiResponsesRoutes } from "../src/adapter/openai/responses.js"; import { requireApiKey } from "../src/auth.js"; @@ -1839,11 +1839,27 @@ describe("POST /v1/responses (streaming)", () => { describe("POST /v1/responses (media concurrency)", () => { let server: http.Server; let baseUrl: string; + /** + * What the fixture saw while it answered. + * + * The overlap is asserted on this counter rather than on elapsed wall-clock + * time: a shared CI runner adds tens of milliseconds to a whole request, so a + * margin below that cannot tell concurrent resolution from serial (the + * equivalent assertion flaked on the Windows CI job). A serial resolver never + * exceeds one in-flight request; the delay only exists to keep two overlapping + * downloads open at the same time. + */ + const observed = { maxConcurrent: 0, requests: [] as string[] }; beforeAll(async () => { - server = http.createServer((_request, response) => { - // Every response is delayed, so resolving N parts serially costs N times - // the delay while resolving them concurrently costs roughly one delay. + let inFlight = 0; + server = http.createServer((request, response) => { + inFlight += 1; + observed.maxConcurrent = Math.max(observed.maxConcurrent, inFlight); + observed.requests.push(request.url ?? ""); + response.once("close", () => { + inFlight -= 1; + }); setTimeout(() => { response.writeHead(200, { "content-type": "image/png" }); response.end(PNG_BUFFER); @@ -1853,6 +1869,11 @@ describe("POST /v1/responses (media concurrency)", () => { baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); + beforeEach(() => { + observed.maxConcurrent = 0; + observed.requests.length = 0; + }); + afterAll(async () => { await new Promise((resolve) => server.close(() => resolve())); }); @@ -1864,7 +1885,6 @@ describe("POST /v1/responses (media concurrency)", () => { onRun: (request) => (captured = request), }); - const startedAt = Date.now(); const response = await app.inject({ method: "POST", url: "/v1/responses", @@ -1883,7 +1903,6 @@ describe("POST /v1/responses (media concurrency)", () => { ], }, }); - const elapsed = Date.now() - startedAt; expect(response.statusCode).toBe(200); const attachments = captured?.messages.at(-1)?.attachments ?? []; @@ -1894,8 +1913,9 @@ describe("POST /v1/responses (media concurrency)", () => { `${mediaHost}/second.png`, ]); expect(attachments.every((attachment) => attachment.mime === "image/png")).toBe(true); - // Serial resolution would need at least two full fixture delays. - expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); + // Both downloads were open at once, in declaration order. + expect(observed.maxConcurrent).toBe(2); + expect(observed.requests).toEqual(["/first.png", "/second.png"]); }); it("downloads the media of different input items through one request pool", async () => { @@ -1905,7 +1925,6 @@ describe("POST /v1/responses (media concurrency)", () => { onRun: (request) => (captured = request), }); - const startedAt = Date.now(); const response = await app.inject({ method: "POST", url: "/v1/responses", @@ -1919,7 +1938,6 @@ describe("POST /v1/responses (media concurrency)", () => { ], }, }); - const elapsed = Date.now() - startedAt; expect(response.statusCode).toBe(200); const attachments = captured?.messages.flatMap((message) => message.attachments ?? []) ?? []; @@ -1929,8 +1947,10 @@ describe("POST /v1/responses (media concurrency)", () => { `${mediaHost}/first.png`, `${mediaHost}/second.png`, ]); - // Resolving item by item would serialise two pools and cost two delays. - expect(elapsed).toBeLessThan(MEDIA_DELAY_MS * 2 - 10); + // One pool per request: resolving item by item would serialise the two + // downloads, so the fixture would never see them at the same time. + expect(observed.maxConcurrent).toBe(2); + expect([...observed.requests].sort()).toEqual(["/first.png", "/second.png"]); }); });