Skip to content

Commit c1f9733

Browse files
committed
feat: apply streamingProfile timing to non-streaming responses
ttft/tps/jitter (and recordedTimings) only ever applied on the SSE path - a non-streaming request wrote its JSON body back immediately regardless of what streamingProfile was set to. 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. 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.
1 parent 843c5df commit c1f9733

5 files changed

Lines changed: 163 additions & 3 deletions

File tree

‎src/__tests__/server.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,29 @@ 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+
});
541564
});
542565

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

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

Lines changed: 70 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,72 @@ describe("fixture loader streamingProfile passthrough", () => {
330330
expect(fixtures[0].streamingProfile).toEqual({ ttft: 300 });
331331
});
332332
});
333+
334+
// ─── calculateTotalDelay unit tests ──────────────────────────────────────────
335+
// The non-streaming equivalent of calculateDelay: sums it over the same chunk
336+
// count a streamed response at the same chunkSize would use, so a fixture's
337+
// timing is identical whether served streamed or not.
338+
339+
describe("calculateTotalDelay", () => {
340+
it("returns fallback latency once, not per would-be chunk, when no profile is set", () => {
341+
// 25 chars at chunkSize 10 -> 3 chunks, but a flat fallback applies per
342+
// chunk the same way streaming's calculateDelay does, so the total is
343+
// fallback * chunkCount here too.
344+
expect(calculateTotalDelay(25, 10, undefined, 50)).toBe(150);
345+
});
346+
347+
it("returns 0 when there is no profile and no fallback", () => {
348+
expect(calculateTotalDelay(25, 10, undefined, undefined)).toBe(0);
349+
});
350+
351+
it("charges ttft once plus tps for every remaining would-be chunk", () => {
352+
const profile: StreamingProfile = { ttft: 200, tps: 50 };
353+
// 25 chars at chunkSize 10 -> 3 chunks: ttft (200) + 2 * (1000/50 = 20)
354+
expect(calculateTotalDelay(25, 10, profile)).toBe(240);
355+
});
356+
357+
it("treats content shorter than chunkSize as a single chunk", () => {
358+
const profile: StreamingProfile = { ttft: 150, tps: 50 };
359+
expect(calculateTotalDelay(5, 10, profile)).toBe(150);
360+
});
361+
362+
it("treats zero-length content as a single chunk (still pays ttft)", () => {
363+
const profile: StreamingProfile = { ttft: 120, tps: 50 };
364+
expect(calculateTotalDelay(0, 10, profile)).toBe(120);
365+
});
366+
367+
it("matches summing calculateDelay over the same chunk range", () => {
368+
const profile: StreamingProfile = { ttft: 300, tps: 40 };
369+
const contentLength = 47;
370+
const chunkSize = 10;
371+
const chunkCount = Math.ceil(contentLength / chunkSize);
372+
let expected = 0;
373+
for (let i = 0; i < chunkCount; i++) {
374+
expected += calculateDelay(i, profile);
375+
}
376+
expect(calculateTotalDelay(contentLength, chunkSize, profile)).toBe(expected);
377+
});
378+
379+
it("uses recordedTimings (ttft + inter-chunk delays) across the chunk range", () => {
380+
const recordedTimings: RecordedTimings = {
381+
ttftMs: 80,
382+
interChunkDelaysMs: [15, 25],
383+
totalDurationMs: 120,
384+
};
385+
// 30 chars at chunkSize 10 -> 3 chunks: ttft (80) + recorded gaps (15, 25)
386+
expect(calculateTotalDelay(30, 10, undefined, undefined, recordedTimings)).toBe(120);
387+
});
388+
389+
it("divides by replaySpeed, same as calculateDelay", () => {
390+
const profile: StreamingProfile = { ttft: 200, tps: 50 };
391+
// 25 chars at chunkSize 10 -> 240ms at 1x (see earlier test), 120ms at 2x
392+
expect(calculateTotalDelay(25, 10, profile, undefined, undefined, 2)).toBe(120);
393+
});
394+
395+
it("stays non-negative when jitter or replaySpeed could otherwise push it below zero", () => {
396+
const profile: StreamingProfile = { ttft: 10, tps: 500, jitter: 1 };
397+
for (let i = 0; i < 50; i++) {
398+
expect(calculateTotalDelay(100, 10, profile)).toBeGreaterThanOrEqual(0);
399+
}
400+
});
401+
});

‎src/index.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,13 @@ export { createInterruptionSignal } from "./interruption.js";
252252
export type { InterruptionControl } from "./interruption.js";
253253

254254
// SSE
255-
export { writeSSEStream, writeErrorResponse, delay, calculateDelay } from "./sse-writer.js";
255+
export {
256+
writeSSEStream,
257+
writeErrorResponse,
258+
delay,
259+
calculateDelay,
260+
calculateTotalDelay,
261+
} from "./sse-writer.js";
256262
export type { StreamOptions, ErrorResponseOptions } from "./sse-writer.js";
257263

258264
// Chaos

‎src/server.ts‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import {
4646
responsesToolsExtendedView,
4747
responsesToolsViewSource,
4848
} from "./fixture-loader.js";
49-
import { writeSSEStream, writeErrorResponse } from "./sse-writer.js";
49+
import { writeSSEStream, writeErrorResponse, delay, calculateTotalDelay } from "./sse-writer.js";
5050
import { createInterruptionSignal } from "./interruption.js";
5151
import {
5252
prepareOpenAIChatMisbehavior,
@@ -2531,6 +2531,22 @@ async function handleCompletions(
25312531
overrides,
25322532
body.messages,
25332533
);
2534+
const nonStreamedContent =
2535+
appliedPlan.stop === "refusal"
2536+
? (appliedPlan.refusal ?? "")
2537+
: appliedPlan.stop === "content_filter"
2538+
? ""
2539+
: (appliedPlan.reasoning ?? "");
2540+
await delay(
2541+
calculateTotalDelay(
2542+
nonStreamedContent.length,
2543+
chunkSize,
2544+
fixture.streamingProfile,
2545+
latency,
2546+
fixture.recordedTimings,
2547+
fixture.replaySpeed ?? defaults.replaySpeed,
2548+
),
2549+
);
25342550
res.writeHead(200, { "Content-Type": "application/json" });
25352551
res.end(JSON.stringify(shapeORCompletion(completion, overrides)));
25362552
} else {
@@ -2702,6 +2718,16 @@ async function handleCompletions(
27022718
});
27032719
recordOutcome(journalEntry);
27042720
if (body.stream !== true) {
2721+
await delay(
2722+
calculateTotalDelay(
2723+
(effReasoning?.length ?? 0) + response.content.length,
2724+
chunkSize,
2725+
fixture.streamingProfile,
2726+
latency,
2727+
fixture.recordedTimings,
2728+
fixture.replaySpeed ?? defaults.replaySpeed,
2729+
),
2730+
);
27052731
const completion = buildTextCompletion(
27062732
response.content,
27072733
responseModel,
@@ -2777,6 +2803,17 @@ async function handleCompletions(
27772803
recordOutcome(journalEntry);
27782804
const toolCalls = requireServedFunctionToolCalls(response, wire);
27792805
if (body.stream !== true) {
2806+
const toolCallText = toolCalls.map((tc) => tc.name + tc.arguments).join("");
2807+
await delay(
2808+
calculateTotalDelay(
2809+
(effReasoning?.length ?? 0) + toolCallText.length,
2810+
chunkSize,
2811+
fixture.streamingProfile,
2812+
latency,
2813+
fixture.recordedTimings,
2814+
fixture.replaySpeed ?? defaults.replaySpeed,
2815+
),
2816+
);
27802817
const completion = buildToolCallCompletion(
27812818
toolCalls,
27822819
responseModel,

‎src/sse-writer.ts‎

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

92+
/**
93+
* The non-streaming equivalent of calculateDelay: the total wait before a
94+
* single JSON response is written, matching what a streamed response with
95+
* the same profile/chunking would have taken in aggregate. Sums
96+
* calculateDelay over the same chunk count buildTextChunks/buildToolCallChunks
97+
* would use for `contentLength` at `chunkSize`, so ttft/tps/jitter and
98+
* recordedTimings behave identically whether a fixture is served streamed or
99+
* not — only the delivery (one write vs many) differs.
100+
*/
101+
export function calculateTotalDelay(
102+
contentLength: number,
103+
chunkSize: number,
104+
profile?: StreamingProfile,
105+
fallbackLatency?: number,
106+
recordedTimings?: RecordedTimings,
107+
replaySpeed?: number,
108+
): number {
109+
const chunkCount = Math.max(1, Math.ceil(contentLength / chunkSize));
110+
let total = 0;
111+
for (let chunkIndex = 0; chunkIndex < chunkCount; chunkIndex++) {
112+
total += calculateDelay(chunkIndex, profile, fallbackLatency, recordedTimings, replaySpeed);
113+
}
114+
return total;
115+
}
116+
92117
export async function writeSSEStream(
93118
res: http.ServerResponse,
94119
chunks: SSEChunk[],

0 commit comments

Comments
 (0)