Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
0461722
fix(electron): make the shared standalone bundle portable and fast to…
diegosouzapw Nov 7, 2026
7eb1b69
fix(ci): give the Sonar JS/TS analyzer enough heap (#19280)
diegosouzapw Nov 7, 2026
094a1aa
fix(ci): stop the Codecov uploader from scanning the coverage shards …
diegosouzapw Nov 9, 2026
a3b27ba
fix(sse): bound the non-SSE body read behind an early keepalive
serenity-X Nov 9, 2026
93aff25
fix(sse): drain batched frames when a failure terminates the stream
serenity-X Nov 9, 2026
539305e
fix(sse): cap bytes held before the first stream readiness signal
serenity-X Nov 9, 2026
4780197
perf(sse): stop scanning stream frames after content is seen
serenity-X Nov 9, 2026
df2f8f6
fix(sse): clear the stream idle watchdog when the transform throws
serenity-X Nov 9, 2026
3b9bd05
perf(usage): count fallback input tokens in one pass
serenity-X Nov 9, 2026
155e58e
docs(changelog): number the fragment (#19713)
serenity-X Nov 10, 2026
7478bd2
Merge remote-tracking branch 'origin/release/v3.8.54' into ci/19713
serenity-X Nov 11, 2026
98b4063
refactor(sse): split the token-estimate char classes into helpers
serenity-X Nov 11, 2026
a953908
Merge main into release/v3.8.54 (generate-release 0a.0b back-merge)
diegosouzapw Nov 16, 2026
b0f0a10
Merge release/v3.8.54 into this branch
serenity-X Nov 16, 2026
45937d8
refactor(sse): move the transform-error idle-timer guard out of strea…
serenity-X Nov 17, 2026
a53da31
fix(usage): count U+3000 as whitespace in the single-pass token estim…
serenity-X Nov 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(sse):** a chat stream that already sent its keepalive no longer hangs when the upstream sends a non-event-stream body that never ends. The slow-path deadline now covers that body read and cancels it.
1 change: 1 addition & 0 deletions changelog.d/fixes/0000-sse-coalesce-terminate-flush.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(sse):** with `SSE_FRAME_COALESCE_MS` on, a stream that ends on an upstream failure now still delivers the last queued content frame and the real error frame to the client.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(sse):** a streaming upstream that sends only comment lines or invalid data now fails readiness after 1 MiB, instead of filling gateway memory until the readiness deadline.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **fix(sse):** a translated stream that fails inside its transform no longer leaves its idle-timeout timer running until the idle timeout.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **perf(sse):** the client stream content check stops parsing frames once the first content is seen, which saves about 4 ms of CPU for a 2,000-event stream.
1 change: 1 addition & 0 deletions changelog.d/maintenance/0000-token-estimate-single-pass.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- **perf(usage):** the fallback input-token estimate for responses without provider usage counts in one pass, so a 3 MiB request no longer allocates tens of MiB of temporary arrays.
26 changes: 23 additions & 3 deletions open-sse/utils/earlyStreamKeepalive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,7 @@ export async function withEarlyStreamKeepalive(
aborted = true;
stopDeadline();
stopKeepalive();
upstreamReader?.cancel().catch(() => {});
try {
deadlineController?.abort();
} catch {
Expand Down Expand Up @@ -674,7 +675,7 @@ export async function withEarlyStreamKeepalive(

try {
const result = await settled;
stopDeadline();
// The deadline stays armed here: a non-SSE body is read below and must be bound too.
stopKeepalive();
if (aborted) {
// The synthetic keepalive response can be cancelled before the handler resolves.
Expand All @@ -695,7 +696,9 @@ export async function withEarlyStreamKeepalive(
const isSse = contentType.includes("text/event-stream");

if (response.body && isSse) {
// Real SSE stream — forward it verbatim.
// Real SSE stream — forward it verbatim. The deadline guards only the
// handler wait and the non-SSE body read, never a long-lived stream.
stopDeadline();
upstreamReader = response.body.getReader();
let bytesForwarded = 0;
// Last four forwarded bytes. A finished SSE event ends in \n\n (or \r\n\r\n).
Expand Down Expand Up @@ -750,7 +753,24 @@ export async function withEarlyStreamKeepalive(
// committed to a 200 event-stream, so the HTTP status can no longer
// change. Frame the (already-sanitized) body as an in-band error event
// instead of forwarding raw JSON, which would be malformed SSE.
const text = response.body ? await response.text().catch(() => "") : "";
// Read through upstreamReader so the deadline, abort and cancel paths can
// cancel a body that trickles forever.
let text = "";
if (response.body) {
upstreamReader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await upstreamReader.read();
if (done) break;
if (value) text += decoder.decode(value, { stream: true });
}
text += decoder.decode();
} catch {
text = "";
}
}
if (aborted) return;
const dataLine =
errorFrameFormat === "responses"
? buildResponsesErrorDataLine(text, {
Expand Down
22 changes: 22 additions & 0 deletions open-sse/utils/sseOutputSink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,32 @@ export function createSSEOutputSink(

const wrap = <T extends Transformer<Uint8Array, Uint8Array>>(transformer: T): T => {
if (!deltaStage && frameWindowMs <= 0) return transformer;
const originalTransform = transformer.transform;
const originalFlush = transformer.flush;
const originalCancel = (transformer as CancelableTransformer<Uint8Array, Uint8Array>).cancel;
// A preserved stream failure ends the stream with `controller.terminate()` from inside
// `transform()`. `flush()` never runs after that, so drain the queued delta and the failure
// frame (they may be held in the batch) right before the readable side closes.
let drainingController: OutputController | null = null;
const withDrainOnTerminate = (controller: OutputController): OutputController =>
(drainingController ??= {
get desiredSize() {
return controller.desiredSize;
},
enqueue: (chunk) => controller.enqueue(chunk),
error: (reason) => controller.error(reason),
terminate: () => {
drain(controller);
dispose();
controller.terminate();
},
});
return {
...transformer,
transform: originalTransform
? (chunk: Uint8Array, controller: OutputController) =>
originalTransform.call(transformer, chunk, withDrainOnTerminate(controller))
: undefined,
async flush(controller: OutputController) {
try {
await originalFlush?.call(transformer, controller);
Expand Down
12 changes: 12 additions & 0 deletions open-sse/utils/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1557,7 +1557,19 @@ export function createSSEStream(options: StreamOptions = {}) {
}
},

// An exception thrown while translating errors both stream sides without running
// flush() or cancel(): clear the idle watchdog here, or its interval keeps the failed
// stream alive until the idle timeout.
transform(chunk, controller) {
try {
this.transformChunk(chunk, controller);
} catch (error) {
clearIdleTimer();
throw error;
}
},

transformChunk(chunk: Uint8Array, controller: TransformStreamDefaultController<Uint8Array>) {
if (streamTimedOut) return;
const now = Date.now();
timing.markByte();
Expand Down
44 changes: 41 additions & 3 deletions open-sse/utils/streamReadiness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,8 @@ export type StreamContentWatcher = {
/**
* True once a terminal frame declared a NORMAL stop (finish_reason "stop",
* stop_reason "end_turn"/"stop_sequence") — the upstream's own verdict that
* the turn is complete, even when no content followed (#16072).
* the turn is complete, even when no content followed (#16072). Not updated once
* content is seen: the verdict only matters for a stream that carried no content.
*/
sawNormalStopTerminal: () => boolean;
/**
Expand Down Expand Up @@ -567,21 +568,28 @@ export function createStreamContentWatcher(

return {
note(text: string): void {
if (!text) return;
// Once content is proven every reader is satisfied (each tests `!sawContent()` or ORs
// it with the other flags), so later frames are not parsed or buffered and the
// other flags keep the value they had at that point.
if (!text || content) return;
pending += text;
for (;;) {
const boundary = pending.search(/\r?\n\r?\n/);
if (boundary === -1) break;
inspect(pending.slice(0, boundary));
pending = pending.slice(boundary).replace(/^\r?\n\r?\n/, "");
if (content) {
pending = "";
return;
}
}
if (pending.length > MAX_BUFFERED) {
inspect(pending);
pending = "";
}
},
finish(): void {
inspect(pending);
if (!content) inspect(pending);
pending = "";
},
sawContent: () => content,
Expand Down Expand Up @@ -857,6 +865,11 @@ export function prependBufferedChunks(
});
}

// Ceiling on bytes held before the first readiness signal. Comment-only or non-JSON bodies
// never signal readiness, so without it they grow with upstream rate x deadline. Kept far
// above one real first frame (a Responses `response.created` echoes instructions and tools).
const PRE_SIGNAL_MAX_BYTES = 1024 * 1024;

class StreamReadinessReadTimeout extends Error {
constructor() {
super("STREAM_READINESS_TIMEOUT");
Expand Down Expand Up @@ -1260,6 +1273,31 @@ export async function ensureStreamReadiness(
response: buildReadyResponse(),
};
}

if (bufferedBytes > PRE_SIGNAL_MAX_BYTES) {
const reason = `Stream sent ${bufferedBytes} bytes without a non-ping SSE event (limit=${PRE_SIGNAL_MAX_BYTES})`;
options.log?.warn?.(
"STREAM",
`${reason} (${options.provider || "provider"}/${options.model || "unknown"})`
);
await reader.cancel(reason).catch(() => {});
return {
ok: false,
reason,
classificationReason: reason,
code: "STREAM_READINESS_TIMEOUT",
type: "stream_timeout",
anyByteAt: lastChunkAt,
response: createErrorResponse(
HTTP_STATUS.GATEWAY_TIMEOUT,
reason,
"STREAM_READINESS_TIMEOUT",
"stream_timeout",
undefined,
buildAnyByteAtHeader(lastChunkAt)
),
};
}
}
} finally {
if (!handedOffReader) {
Expand Down
64 changes: 50 additions & 14 deletions open-sse/utils/usageTracking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1006,26 +1006,62 @@ const CHARS_PER_TOKEN_SCHEMA = 6; // ~6 chars/token for JSON schemas (more verbo
* @param {string} text - Text to estimate tokens for
* @returns {number} Estimated token count
*/
// Same set as the regex \s (and String.trim) in V8.
function isSpaceCode(c: number) {
return (
c === 32 ||
(c >= 9 && c <= 13) ||
c === 0xa0 ||
c === 0x1680 ||
(c >= 0x2000 && c <= 0x200a) ||
c === 0x2028 ||
c === 0x2029 ||
c === 0x202f ||
c === 0x205f ||
c === 0xfeff
);
}

function estimateTokenCount(text: unknown) {
if (!text || typeof text !== "string") return 0;

// Count CJK ideographs separately — each is roughly 1 token
const cjkMatches = text.match(/[\u3000-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}]/gu);
const cjkCount = cjkMatches ? cjkMatches.length : 0;

// Remove CJK chars for the remaining estimation
const nonCJK = text.replace(/[\u3000-\u9fff\uf900-\ufaff]/g, " ");

// Split on token boundaries: whitespace, punctuation, camelCase transitions
const tokens = nonCJK
.split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/)
.filter((t) => t && t.trim().length > 0);
// One pass, no split/filter arrays (a 3 MiB body used to leave ~45 MiB of garbage).
// Token boundaries: a run of [A-Za-z0-9_] (cut at each lower->UPPER step), or any other
// non-space UTF-16 unit on its own. A BMP CJK unit counts 1 and acts as a space; an astral
// CJK code point counts 1 and its two surrogate units still count as punctuation tokens.
let cjkCount = 0;
let tokens = 0;
let inWord = false;
let prevLower = false;
for (let i = 0; i < text.length; i++) {
const c = text.charCodeAt(i);
let isLower = false;
if ((c >= 0x3000 && c <= 0x9fff) || (c >= 0xf900 && c <= 0xfaff)) {
cjkCount++;
inWord = false;
} else if (isSpaceCode(c)) {
inWord = false;
} else if (c >= 97 && c <= 122) {
isLower = true;
if (!inWord) tokens++;
inWord = true;
} else if ((c >= 65 && c <= 90) || (c >= 48 && c <= 57) || c === 95) {
if (!inWord || (prevLower && c >= 65 && c <= 90)) tokens++;
inWord = true;
} else {
if (c >= 0xd800 && c <= 0xdbff) {
const cp = text.codePointAt(i)!;
if (cp >= 0x20000 && cp <= 0x2fa1f) cjkCount++;
}
tokens++;
inWord = false;
}
prevLower = isLower;
}

// Apply sub-word correction: BPE tokenizers often split long words
// into sub-word pieces, so raw token count underestimates slightly
const estimatedNonCJK = Math.ceil(tokens.length * 1.3);

return cjkCount + estimatedNonCJK;
return cjkCount + Math.ceil(tokens * 1.3);
}

/**
Expand Down
112 changes: 112 additions & 0 deletions tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* @file early-stream-keepalive-nonsse-body-deadline.test.ts
* @description The slow-path deadline must keep running while a non-SSE handler body is read,
* and the in-flight body read must be cancelled when the deadline fires.
*/
import test from "node:test";
import assert from "node:assert/strict";

import {
OPENAI_CHAT_ERROR_FRAME,
withDeadlineSignal,
withEarlyStreamKeepalive,
} from "../../open-sse/utils/earlyStreamKeepalive.ts";

async function readAll(response: Response): Promise<string> {
const reader = response.body!.getReader();
const decoder = new TextDecoder();
let out = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (value) out += decoder.decode(value, { stream: true });
}
return out;
}

function newDeadlineController() {
return withDeadlineSignal(
new Request("http://localhost/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: "m", stream: true }),
})
).deadlineController;
}

test("a text/plain body that trickles forever hits the slow-path deadline and is cancelled", async () => {
const deadlineController = newDeadlineController();
const encoder = new TextEncoder();
let sourceCancelled = false;
let trickle: ReturnType<typeof setInterval> | undefined;
const trickling = new ReadableStream<Uint8Array>({
start(controller) {
trickle = setInterval(() => controller.enqueue(encoder.encode("x")), 10);
},
cancel() {
sourceCancelled = true;
clearInterval(trickle);
},
});
const handler = new Promise<Response>((resolve) => {
setTimeout(
() =>
resolve(
new Response(trickling, { status: 200, headers: { "Content-Type": "text/plain" } })
),
30
);
});

try {
const result = await withEarlyStreamKeepalive(handler, {
thresholdMs: 10,
intervalMs: 250,
slowPathDeadlineMs: 200,
deadlineController,
errorFrame: OPENAI_CHAT_ERROR_FRAME,
});
const outcome = await Promise.race([
readAll(result).then((body) => ({ body })),
new Promise<{ body: null }>((resolve) => setTimeout(() => resolve({ body: null }), 1500)),
]);

assert.notEqual(outcome.body, null, "client stream must end once the deadline expires");
assert.match(outcome.body!, /"error":/, "deadline must emit the route error frame");
assert.equal(deadlineController.signal.aborted, true, "deadline must abort the controller");
assert.equal(sourceCancelled, true, "the in-flight body read must be cancelled");
} finally {
clearInterval(trickle);
}
});

test("a non-SSE error body that finishes in time is still framed as one error event", async () => {
const deadlineController = newDeadlineController();
const handler = new Promise<Response>((resolve) => {
setTimeout(
() =>
resolve(
new Response(
JSON.stringify({ error: { message: "upstream_busy", type: "rate_limit" } }),
{
status: 429,
headers: { "Content-Type": "application/json" },
}
)
),
30
);
});

const result = await withEarlyStreamKeepalive(handler, {
thresholdMs: 10,
intervalMs: 250,
slowPathDeadlineMs: 5000,
deadlineController,
errorFrame: OPENAI_CHAT_ERROR_FRAME,
});
const body = await readAll(result);

assert.match(body, /data: \{"error":\{"message":"upstream_busy","type":"rate_limit"\}\}\n\n/);
assert.equal(deadlineController.signal.aborted, false, "no abort when the body ends in time");
});
Loading
Loading