Skip to content

Commit c773a37

Browse files
authored
feat: apply streamingProfile timing to non-streaming responses (#545)
## What `ttft`/`tps`/`jitter` (and `recordedTimings`) only ever applied on the SSE path — a non-streaming request (`stream: false`) wrote its JSON body back immediately, ignoring whatever `streamingProfile` the fixture declared. Adds `calculateTotalDelay`, which sums `calculateDelay` over the same chunk count a streamed response at the same `chunkSize` would use, so a fixture's timing is identical whether it's served streamed or not. Wired into all three non-streaming completion branches (text, tool calls, and the refusal/content_filter/reasoning misbehavior terminal) in the OpenAI chat-completions handler. ## Why Matters for load/perf-testing agent setups where a lot of real traffic is non-streaming on purpose (sub-agent calls, tool-chain orchestration, guardrail/classifier calls) — those got zero simulated latency before this, which throws off any test trying to reproduce realistic timing across a call tree. ## Gates - `pnpm format:check`, `pnpm lint`, `pnpm typecheck`, `pnpm build`: pass - `pnpm test`: full suite green (0 failures) - Directly relevant files: `streaming-physics.test.ts` (28 tests, including new `calculateTotalDelay` unit tests) + `server.test.ts` (85 tests, including a new non-streaming timing regression test): pass ## Tests - `src/__tests__/streaming-physics.test.ts`: unit tests for `calculateTotalDelay` — fallback-latency-once semantics, ttft + per-chunk tps, sub-chunk and zero-length content, parity with summing `calculateDelay` over the same range, `recordedTimings` support, `replaySpeed` scaling, non-negativity under jitter. - `src/__tests__/server.test.ts`: a non-streaming request against a fixture with `streamingProfile: { ttft: 60, tps: 1000 }` now takes at least the ttft floor, where it previously returned in a few ms.
2 parents a0f1482 + 054a5eb commit c773a37

5 files changed

Lines changed: 202 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333

3434
- MCP `resources/read`: a resource whose content has neither `text` nor `blob` (including one added without content) now reads as `"text": ""` (#533)
3535
- MCP `resources/read`: the read uses the resource definition's `mimeType` when its content has none (#533)
36+
- OpenAI chat completions only, non-streaming (`stream: false`): opt-in timing. A fixture with an explicit `streamingProfile` (`ttft`/`tps`/`jitter`) or `recordedTimings` now delays the JSON response by about the total its streamed content chunks would take. Before, only the SSE path used these values. Fixtures without them are not delayed: bare `latency` and the global `--latency` stay inter-SSE-chunk gaps and do not slow down non-streaming responses. Other providers are unchanged (#545)
3637

3738
## [1.45.1] - 2026-10-11
3839

‎src/__tests__/server.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,82 @@ describe("POST /v1/chat/completions (non-streaming)", () => {
538538
expect(tc[0].function.name).toBe("get_weather");
539539
expect(tc[0].function.arguments).toBe('{"city":"NYC"}');
540540
});
541+
542+
it("applies streamingProfile timing to a non-streaming response too", async () => {
543+
const fixture: Fixture = {
544+
match: { userMessage: "slow-non-streaming" },
545+
response: { content: "Hi there!" },
546+
streamingProfile: { ttft: 60, tps: 1000 },
547+
};
548+
instance = await createServer([fixture]);
549+
550+
const started = Date.now();
551+
const res = await post(`${instance.url}/v1/chat/completions`, {
552+
model: "gpt-4",
553+
messages: [{ role: "user", content: "slow-non-streaming" }],
554+
stream: false,
555+
});
556+
const elapsed = Date.now() - started;
557+
558+
expect(res.status).toBe(200);
559+
// 60ms ttft dominates here (tps is fast); allow scheduling slack, but a
560+
// regression back to "non-streaming ignores streamingProfile" would
561+
// return in a few ms, well under this floor.
562+
expect(elapsed).toBeGreaterThanOrEqual(50);
563+
});
564+
565+
it("applies streamingProfile timing to a non-streaming tool-call response too", async () => {
566+
const fixture: Fixture = {
567+
match: { userMessage: "slow-non-streaming-tool" },
568+
response: { toolCalls: [{ name: "get_weather", arguments: '{"city":"NYC"}' }] },
569+
streamingProfile: { ttft: 60, tps: 1000 },
570+
};
571+
instance = await createServer([fixture]);
572+
573+
const started = Date.now();
574+
const res = await post(`${instance.url}/v1/chat/completions`, {
575+
model: "gpt-4",
576+
messages: [{ role: "user", content: "slow-non-streaming-tool" }],
577+
stream: false,
578+
});
579+
const elapsed = Date.now() - started;
580+
581+
expect(res.status).toBe(200);
582+
expect(JSON.parse(res.body).choices[0].finish_reason).toBe("tool_calls");
583+
expect(elapsed).toBeGreaterThanOrEqual(50);
584+
});
585+
586+
it("does not delay a non-streaming response for bare latency (no streamingProfile)", async () => {
587+
// `latency` / `--latency` is the gap between SSE chunks. It is not a
588+
// non-streaming delay: only an explicit streamingProfile opts in.
589+
const fixtures: Fixture[] = [
590+
{ match: { userMessage: "bare-latency-text" }, response: { content: "x".repeat(200) } },
591+
{
592+
match: { userMessage: "bare-latency-fixture" },
593+
response: { content: "x".repeat(200) },
594+
latency: 200,
595+
},
596+
{
597+
match: { userMessage: "bare-latency-tool" },
598+
response: { toolCalls: [{ name: "get_weather", arguments: '{"city":"NYC"}' }] },
599+
},
600+
];
601+
instance = await createServer(fixtures, { latency: 200 });
602+
603+
for (const content of ["bare-latency-text", "bare-latency-fixture", "bare-latency-tool"]) {
604+
const started = Date.now();
605+
const res = await post(`${instance.url}/v1/chat/completions`, {
606+
model: "gpt-4",
607+
messages: [{ role: "user", content }],
608+
stream: false,
609+
});
610+
const elapsed = Date.now() - started;
611+
612+
expect(res.status).toBe(200);
613+
// One latency gap alone is 200ms; a regression would wait at least that.
614+
expect(elapsed).toBeLessThan(150);
615+
}
616+
});
541617
});
542618

543619
describe("routing", () => {

‎src/__tests__/streaming-physics.test.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, it, expect, vi, afterEach } from "vitest";
22
import { PassThrough } from "node:stream";
33
import type * as http from "node:http";
4-
import { writeSSEStream, calculateDelay } from "../sse-writer.js";
4+
import { writeSSEStream, calculateDelay, calculateTotalDelay } from "../sse-writer.js";
55
import type { SSEChunk, StreamingProfile, RecordedTimings } from "../types.js";
66
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
77
import { tmpdir } from "node:os";
@@ -330,3 +330,65 @@ describe("fixture loader streamingProfile passthrough", () => {
330330
expect(fixtures[0].streamingProfile).toEqual({ ttft: 300 });
331331
});
332332
});
333+
334+
// ─── calculateTotalDelay unit tests ──────────────────────────────────────────
335+
// The non-streaming total: sums calculateDelay over the content chunk count a
336+
// streamed response at the same chunkSize would use. It takes no fallback
337+
// latency, so bare `latency` never delays a non-streaming response.
338+
339+
describe("calculateTotalDelay", () => {
340+
it("returns 0 when there is no profile and no recorded timings", () => {
341+
expect(calculateTotalDelay(25, 10, undefined, undefined)).toBe(0);
342+
});
343+
344+
it("charges ttft once plus tps for every remaining would-be chunk", () => {
345+
const profile: StreamingProfile = { ttft: 200, tps: 50 };
346+
// 25 chars at chunkSize 10 -> 3 chunks: ttft (200) + 2 * (1000/50 = 20)
347+
expect(calculateTotalDelay(25, 10, profile)).toBe(240);
348+
});
349+
350+
it("treats content shorter than chunkSize as a single chunk", () => {
351+
const profile: StreamingProfile = { ttft: 150, tps: 50 };
352+
expect(calculateTotalDelay(5, 10, profile)).toBe(150);
353+
});
354+
355+
it("treats zero-length content as a single chunk (still pays ttft)", () => {
356+
const profile: StreamingProfile = { ttft: 120, tps: 50 };
357+
expect(calculateTotalDelay(0, 10, profile)).toBe(120);
358+
});
359+
360+
it("matches summing calculateDelay over the same chunk range", () => {
361+
const profile: StreamingProfile = { ttft: 300, tps: 40 };
362+
const contentLength = 47;
363+
const chunkSize = 10;
364+
const chunkCount = Math.ceil(contentLength / chunkSize);
365+
let expected = 0;
366+
for (let i = 0; i < chunkCount; i++) {
367+
expected += calculateDelay(i, profile);
368+
}
369+
expect(calculateTotalDelay(contentLength, chunkSize, profile)).toBe(expected);
370+
});
371+
372+
it("uses recordedTimings (ttft + inter-chunk delays) across the chunk range", () => {
373+
const recordedTimings: RecordedTimings = {
374+
ttftMs: 80,
375+
interChunkDelaysMs: [15, 25],
376+
totalDurationMs: 120,
377+
};
378+
// 30 chars at chunkSize 10 -> 3 chunks: ttft (80) + recorded gaps (15, 25)
379+
expect(calculateTotalDelay(30, 10, undefined, recordedTimings)).toBe(120);
380+
});
381+
382+
it("divides by replaySpeed, same as calculateDelay", () => {
383+
const profile: StreamingProfile = { ttft: 200, tps: 50 };
384+
// 25 chars at chunkSize 10 -> 240ms at 1x (see earlier test), 120ms at 2x
385+
expect(calculateTotalDelay(25, 10, profile, undefined, 2)).toBe(120);
386+
});
387+
388+
it("stays non-negative when jitter or replaySpeed could otherwise push it below zero", () => {
389+
const profile: StreamingProfile = { ttft: 10, tps: 500, jitter: 1 };
390+
for (let i = 0; i < 50; i++) {
391+
expect(calculateTotalDelay(100, 10, profile)).toBeGreaterThanOrEqual(0);
392+
}
393+
});
394+
});

‎src/server.ts‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ import {
5252
responsesToolsExtendedView,
5353
responsesToolsViewSource,
5454
} from "./fixture-loader.js";
55-
import { writeSSEStream, writeErrorResponse } from "./sse-writer.js";
55+
import { writeSSEStream, writeErrorResponse, delay, calculateTotalDelay } from "./sse-writer.js";
5656
import { createInterruptionSignal } from "./interruption.js";
5757
import {
5858
prepareOpenAIChatMisbehavior,
@@ -2415,19 +2415,37 @@ async function handleCompletions(
24152415
): { prompt_tokens: number; completion_tokens: number; total_tokens: number } =>
24162416
appliedUsage ?? resolveUsage(overrides, streamingPromptText, completionText);
24172417

2418-
const resolveRecordedTimings = (chunks: SSEChunk[]) => {
2418+
const resolveRecordedTimings = (chunkCount: number) => {
24192419
const timings = fixture.recordedTimings;
24202420
if (!appliedPlan?.duplicateId || !timings) return timings;
24212421
const gaps = timings.interChunkDelaysMs;
24222422
return {
24232423
...timings,
24242424
interChunkDelaysMs: Array.from(
2425-
{ length: Math.max(gaps.length, chunks.length - 1) },
2425+
{ length: Math.max(gaps.length, chunkCount - 1) },
24262426
(_, index) => gaps[index] ?? gaps.at(-1) ?? 0,
24272427
),
24282428
};
24292429
};
24302430

2431+
// Non-streaming (`stream: false`) timing is opt-in: only an explicit fixture
2432+
// `streamingProfile` or `recordedTimings` delays the single JSON write, by the
2433+
// total a streamed reply at the same chunkSize would take. Bare `latency` /
2434+
// `--latency` is the gap between SSE chunks only and never delays this path.
2435+
const awaitNonStreamingTiming = (contentLength: number): Promise<void> => {
2436+
if (!fixture.streamingProfile && !fixture.recordedTimings) return Promise.resolve();
2437+
const chunkCount = Math.max(1, Math.ceil(contentLength / chunkSize));
2438+
return delay(
2439+
calculateTotalDelay(
2440+
contentLength,
2441+
chunkSize,
2442+
fixture.streamingProfile,
2443+
resolveRecordedTimings(chunkCount),
2444+
fixture.replaySpeed ?? defaults.replaySpeed,
2445+
),
2446+
);
2447+
};
2448+
24312449
// OpenRouter response shaping (no-op for OpenAI callers). Applied as a
24322450
// post-pass over the objects the shared OpenAI builders produce so the
24332451
// OpenAI code path is untouched. All OpenRouter-specific field shapes live in
@@ -2547,6 +2565,13 @@ async function handleCompletions(
25472565
overrides,
25482566
body.messages,
25492567
);
2568+
const nonStreamedContent =
2569+
appliedPlan.stop === "refusal"
2570+
? (appliedPlan.refusal ?? "")
2571+
: appliedPlan.stop === "content_filter"
2572+
? ""
2573+
: (appliedPlan.reasoning ?? "");
2574+
await awaitNonStreamingTiming(nonStreamedContent.length);
25502575
res.writeHead(200, { "Content-Type": "application/json" });
25512576
res.end(JSON.stringify(shapeORCompletion(completion, overrides)));
25522577
} else {
@@ -2579,7 +2604,7 @@ async function handleCompletions(
25792604
signal: interruption?.signal,
25802605
onChunkSent: interruption?.tick,
25812606
usageChunk,
2582-
recordedTimings: resolveRecordedTimings(chunks),
2607+
recordedTimings: resolveRecordedTimings(chunks.length),
25832608
replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
25842609
openRouterProcessing,
25852610
});
@@ -2681,7 +2706,7 @@ async function handleCompletions(
26812706
signal: interruption?.signal,
26822707
onChunkSent: interruption?.tick,
26832708
usageChunk,
2684-
recordedTimings: resolveRecordedTimings(chunks),
2709+
recordedTimings: resolveRecordedTimings(chunks.length),
26852710
replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
26862711
openRouterProcessing,
26872712
});
@@ -2724,6 +2749,7 @@ async function handleCompletions(
27242749
});
27252750
recordOutcome(journalEntry);
27262751
if (body.stream !== true) {
2752+
await awaitNonStreamingTiming((effReasoning?.length ?? 0) + response.content.length);
27272753
const completion = buildTextCompletion(
27282754
response.content,
27292755
responseModel,
@@ -2758,7 +2784,7 @@ async function handleCompletions(
27582784
signal: interruption?.signal,
27592785
onChunkSent: interruption?.tick,
27602786
usageChunk,
2761-
recordedTimings: resolveRecordedTimings(chunks),
2787+
recordedTimings: resolveRecordedTimings(chunks.length),
27622788
replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
27632789
openRouterProcessing,
27642790
});
@@ -2802,6 +2828,8 @@ async function handleCompletions(
28022828
recordOutcome(journalEntry);
28032829
const toolCalls = requireServedFunctionToolCalls(response, wire);
28042830
if (body.stream !== true) {
2831+
const toolCallText = toolCalls.map((tc) => tc.name + tc.arguments).join("");
2832+
await awaitNonStreamingTiming((effReasoning?.length ?? 0) + toolCallText.length);
28052833
const completion = buildToolCallCompletion(
28062834
toolCalls,
28072835
responseModel,
@@ -2837,7 +2865,7 @@ async function handleCompletions(
28372865
signal: interruption?.signal,
28382866
onChunkSent: interruption?.tick,
28392867
usageChunk,
2840-
recordedTimings: resolveRecordedTimings(chunks),
2868+
recordedTimings: resolveRecordedTimings(chunks.length),
28412869
replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
28422870
openRouterProcessing,
28432871
});

‎src/sse-writer.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,33 @@ export function calculateDelay(
8989
return speed > 0 ? delayMs / speed : delayMs;
9090
}
9191

92+
// Internal (not part of the public API): the total wait before a non-streaming
93+
// (`stream: false`) JSON response is written. Sums calculateDelay over the
94+
// content chunk count that `contentLength` at `chunkSize` would produce, so a
95+
// fixture with an explicit `streamingProfile` or `recordedTimings` pays roughly
96+
// the same ttft/tps cost as its streamed content chunks. It is an
97+
// approximation, not an exact match: a streamed reply also pays delays for its
98+
// role and finish chunks. There is deliberately no fallback-latency parameter:
99+
// bare `latency` / `--latency` is an inter-SSE-chunk gap and never delays a
100+
// non-streaming response. With neither a profile nor recorded timings, this
101+
// returns 0.
102+
// Kept as a line comment, not JSDoc: the bundled .d.ts drops this non-public
103+
// declaration but keeps a JSDoc block, which would then attach to writeSSEStream.
104+
export function calculateTotalDelay(
105+
contentLength: number,
106+
chunkSize: number,
107+
profile?: StreamingProfile,
108+
recordedTimings?: RecordedTimings,
109+
replaySpeed?: number,
110+
): number {
111+
const chunkCount = Math.max(1, Math.ceil(contentLength / chunkSize));
112+
let total = 0;
113+
for (let chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++) {
114+
total += calculateDelay(chunkIndex, profile, undefined, recordedTimings, replaySpeed);
115+
}
116+
return total;
117+
}
118+
92119
export async function writeSSEStream(
93120
res: http.ServerResponse,
94121
chunks: SSEChunk[],

0 commit comments

Comments
 (0)