From 0461722b05bf60170c4b4491c0694164d4563bc4 Mon Sep 17 00:00:00 2001 From: Diego Rodrigues de Sa e Souza Date: Sat, 7 Nov 2026 16:41:01 -0300 Subject: [PATCH 01/13] fix(electron): make the shared standalone bundle portable and fast to restore (#19283) Port of #19239 (release/v3.8.54) to main, so the v3.8.53 macOS arm64 installer can be built through the shared standalone job. The per-leg Next build on the arm64 runner hit the 6 h job limit on 2026-11-06. Keeps traced symlinks verbatim in the colocated optionals, normalizes Windows separators in the manifest and refuses relative escapes under standalone/, and replaces the quadratic tarball block reader with a bounded chunk queue. Scripts and tests only; the changelog fragment stays on release/v3.8.54. --- scripts/build/colocateOptionals.mjs | 45 ++- scripts/build/standaloneManifest.mjs | 56 ++-- scripts/build/standaloneTarball.mjs | 81 +++-- tests/unit/build/standalone-bundle.test.ts | 87 +++++ ...alone-manifest-symlink-portability.test.ts | 305 +++++++++++++++++- 5 files changed, 496 insertions(+), 78 deletions(-) diff --git a/scripts/build/colocateOptionals.mjs b/scripts/build/colocateOptionals.mjs index 7b03a5c53fc1..497ff835447b 100644 --- a/scripts/build/colocateOptionals.mjs +++ b/scripts/build/colocateOptionals.mjs @@ -47,7 +47,15 @@ * fail-open, so this never throws into the install. */ -import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync } from "node:fs"; +import { + cpSync, + existsSync, + lstatSync, + mkdirSync, + readFileSync, + realpathSync, + rmSync, +} from "node:fs"; import { createRequire } from "node:module"; import { dirname, join, sep } from "node:path"; @@ -113,9 +121,7 @@ export function computeDependencyClosure(nodeModulesDir, seeds = SEED_PACKAGES) function isPackageIntact(targetNodeModulesDir, name) { if (!existsSync(join(targetNodeModulesDir, name))) return false; try { - const probe = createRequire( - join(targetNodeModulesDir, "__colocate_probe__.js") - ); + const probe = createRequire(join(targetNodeModulesDir, "__colocate_probe__.js")); const resolved = probe.resolve(name); // A resolution that walked past the target into an ancestor tree does not // prove the target copy is usable. @@ -127,6 +133,26 @@ function isPackageIntact(targetNodeModulesDir, name) { } } +/** + * `cpSync` filter for the no-clobber merge. With `verbatimSymlinks`, cpSync + * throws EEXIST when a link already sits at the destination, which would stop + * the merge halfway through a partially traced package. A link has no payload + * to preserve, so the traced one gives way to the source package's. + * + * @param {string} source + * @param {string} destination + * @returns {true} + */ +function replaceTracedSymlink(source, destination) { + if ( + lstatSync(source).isSymbolicLink() && + lstatSync(destination, { throwIfNoEntry: false })?.isSymbolicLink() + ) { + rmSync(destination); + } + return true; +} + /** * Co-locate the SLM optional dependency closure from `/node_modules` * into a standalone bundle's `node_modules`. @@ -174,10 +200,7 @@ export function colocateLlmlinguaOptionals({ // Check the complete closure rather than only the entry package, and judge // presence by entrypoint integrity — a partially traced directory (see // isPackageIntact) must still receive its missing files. - if ( - closure.length > 0 && - closure.every((name) => isPackageIntact(targetNm, name)) - ) { + if (closure.length > 0 && closure.every((name) => isPackageIntact(targetNm, name))) { return { skipped: true, reason: "already co-located" }; } @@ -192,10 +215,16 @@ export function colocateLlmlinguaOptionals({ // force:false merges into a partially traced directory: files the trace // already materialized are kept, missing ones (the package payload) are // filled in from the root tree. + // verbatimSymlinks: without it cpSync rewrites a package's relative links + // (global-agent's node_modules/.bin/semver) to absolute paths into this + // machine's root node_modules, which dangle in any shipped bundle and + // make the Electron web-build refuse to pack it. cpSync(join(rootNm, name), dest, { recursive: true, force: false, errorOnExist: false, + verbatimSymlinks: true, + filter: replaceTracedSymlink, }); copied++; } catch (err) { diff --git a/scripts/build/standaloneManifest.mjs b/scripts/build/standaloneManifest.mjs index 3751dd6c5e7a..3e39dc4bbdc2 100644 --- a/scripts/build/standaloneManifest.mjs +++ b/scripts/build/standaloneManifest.mjs @@ -32,42 +32,56 @@ async function sha256File(filePath) { } /** - * Rewrite a symlink target so it is anchored to the tree being packed/verified - * instead of the machine that happened to create it (issue #11979). + * Reduce a symlink target to the portable form the manifest records, or refuse + * it when it leaves the tree (issue #11979). * - * `npm`'s bin-links usually produce a target already relative to the - * symlink's own directory (e.g. `../semver/bin/semver.js`), which survives an - * archive/restore round trip unchanged on every OS. Some `npm ci` legs - * (observed on the ubuntu web-build runner) instead emit an ABSOLUTE target - * tied to that machine's checkout path. An absolute target is inherently - * non-portable: POSIX restores it as a dangling symlink once the packing - * machine's path is gone, and Windows' `CreateSymbolicLink` rewrites a - * leading `/` into a drive-relative path on read-back, so a byte-for-byte - * comparison against the recorded value fails outright. + * The portable form is relative to the symlink's own directory with `/` + * separators -- what `npm` writes for its bin links (e.g. + * `../semver/bin/semver.js`). It survives an archive/restore round trip on + * every OS, with one exception handled here: Node stores `\\` in a Windows + * symlink, so a restored link reads back with the other separator. * - * A relative target has no such ambiguity, so an absolute target is resolved - * against `rootDir` and re-expressed relative to the symlink's own directory - * -- the same portable shape `npm install` already produces natively. + * An ABSOLUTE target is inherently non-portable: POSIX restores it as a + * dangling symlink once the packing machine's path is gone, and Windows' + * `CreateSymbolicLink` rewrites a leading `/` into a drive-relative path on + * read-back. One that points inside `rootDir` is re-expressed in the relative + * form. One that points elsewhere is refused: only the step that wrote the link + * knows where it should point, so the refusal never tries to find a same-named + * file in the tree. + * + * A relative target that climbs out of the tree is refused under `standalone/`, + * the part that ships and must be self-contained. Elsewhere it is legitimate: + * Turbopack's hashed externals in `/node_modules` are relative links + * to the checkout's own `node_modules`, and they resolve on every desktop leg + * because each leg has the same checkout layout. * * @param {string} rootDir absolute path to the tree root * @param {string} entryRelPath the symlink's own path, relative to rootDir (posix-separated) * @param {string} rawTarget the raw string from fs.readlinkSync + * @param {string} [sep] the platform separator readlink reports (override for tests) * @returns {{ok: true, value: string} | {ok: false, reason: string}} */ -export function normalizeSymlinkTarget(rootDir, entryRelPath, rawTarget) { - if (!path.isAbsolute(rawTarget)) { - return { ok: true, value: rawTarget }; - } +export function normalizeSymlinkTarget(rootDir, entryRelPath, rawTarget, sep = path.sep) { + const target = sep === "\\" ? rawTarget.replaceAll("\\", "/") : rawTarget; const rootResolved = path.resolve(rootDir); - const resolvedTarget = path.resolve(rawTarget); + const symlinkDir = path.dirname(path.join(rootResolved, ...entryRelPath.split("/"))); + const resolvedTarget = path.resolve(symlinkDir, target); const relFromRoot = path.relative(rootResolved, resolvedTarget); - if (relFromRoot === "" || relFromRoot.startsWith("..") || path.isAbsolute(relFromRoot)) { + const leavesTree = + relFromRoot === "" || + relFromRoot === ".." || + relFromRoot.startsWith(`..${path.sep}`) || + path.isAbsolute(relFromRoot); + const isAbsolute = path.isAbsolute(target); + if (leavesTree && (isAbsolute || entryRelPath.startsWith("standalone/"))) { return { ok: false, reason: `symlink ${entryRelPath} target escapes the tree root: ${rawTarget}`, }; } - const symlinkDir = path.dirname(path.join(rootResolved, ...entryRelPath.split("/"))); + if (!isAbsolute) { + return { ok: true, value: target }; + } const relFromSymlink = path.relative(symlinkDir, resolvedTarget).split(path.sep).join("/"); return { ok: true, value: relFromSymlink }; } diff --git a/scripts/build/standaloneTarball.mjs b/scripts/build/standaloneTarball.mjs index a5a1c8f1b0e4..124e50a587f4 100644 --- a/scripts/build/standaloneTarball.mjs +++ b/scripts/build/standaloneTarball.mjs @@ -179,19 +179,32 @@ export async function createTarGz(srcDir, outFile) { // ─── extraction ────────────────────────────────────────────────────────────────── +/** Decompressed bytes held ahead of the extractor before the stream is paused. */ +export const READ_AHEAD_BYTES = 8 * 1024 * 1024; + /** * Promise-based byte source over a gunzip stream. `read(n)` waits until `n` - * bytes are buffered (or EOF); `readSome()` returns whatever is available, for - * streaming large payloads into files without whole-file buffering. + * bytes are buffered (or EOF); `readSome(max)` returns up to `max` of whatever + * is available, for streaming large payloads into files without whole-file + * buffering. + * + * Chunks stay in a queue and reads hand out subarrays of them, so the cost per + * entry does not depend on how much is buffered. Gunzip outruns the extractor, + * which writes one file at a time; pausing it keeps the queue small on bundles + * of a hundred thousand entries. */ -class BlockSource { +export class BlockSource { constructor(stream) { - this.buffer = Buffer.alloc(0); + this.stream = stream; + this.chunks = []; + this.buffered = 0; this.error = null; this.ended = false; this.waiter = null; stream.on("data", (chunk) => { - this.buffer = this.buffer.length === 0 ? chunk : Buffer.concat([this.buffer, chunk]); + this.chunks.push(chunk); + this.buffered += chunk.length; + if (this.buffered >= READ_AHEAD_BYTES) stream.pause(); this.notify(); }); stream.on("end", () => { @@ -212,15 +225,21 @@ class BlockSource { } } - readSome() { + take(max) { + const head = this.chunks[0]; + const out = head.length > max ? head.subarray(0, max) : head; + if (out.length === head.length) this.chunks.shift(); + else this.chunks[0] = head.subarray(max); + this.buffered -= out.length; + if (this.buffered < READ_AHEAD_BYTES && this.stream.isPaused()) this.stream.resume(); + return out; + } + + readSome(max = Infinity) { return new Promise((resolve, reject) => { const attempt = () => { if (this.error) return reject(this.error); - if (this.buffer.length > 0) { - const out = this.buffer; - this.buffer = Buffer.alloc(0); - return resolve(out); - } + if (this.chunks.length > 0) return resolve(this.take(max)); if (this.ended) return resolve(null); this.waiter = attempt; }; @@ -228,28 +247,16 @@ class BlockSource { }); } - unshift(buf) { - if (buf && buf.length > 0) this.buffer = Buffer.concat([buf, this.buffer]); - } - async read(n) { - let acc = null; + const parts = []; let remaining = n; while (remaining > 0) { - const chunk = await this.readSome(); + const chunk = await this.readSome(remaining); if (chunk === null) return null; // EOF before n bytes - if (chunk.length > remaining) { - acc = acc - ? Buffer.concat([acc, chunk.subarray(0, remaining)]) - : chunk.subarray(0, remaining); - this.unshift(chunk.subarray(remaining)); - remaining = 0; - } else { - acc = acc ? Buffer.concat([acc, chunk]) : chunk; - remaining -= chunk.length; - } + parts.push(chunk); + remaining -= chunk.length; } - return acc ?? Buffer.alloc(0); + return parts.length === 1 ? parts[0] : Buffer.concat(parts, n); } } @@ -277,14 +284,12 @@ function checksumMatches(header) { async function copyN(reader, size, outStream) { let remaining = size; while (remaining > 0) { - const chunk = await reader.readSome(); + const chunk = await reader.readSome(remaining); if (chunk === null) { throw new Error(`unexpected EOF after ${size - remaining} of ${size} bytes`); } - const take = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk; - if (chunk.length > remaining) reader.unshift(chunk.subarray(remaining)); - remaining -= take.length; - if (!outStream.write(take)) await once(outStream, "drain"); + remaining -= chunk.length; + if (!outStream.write(chunk)) await once(outStream, "drain"); } } @@ -298,7 +303,16 @@ export async function extractTarGz(archiveFile, destDir) { const gunzip = createGunzip(); src.pipe(gunzip); const reader = new BlockSource(gunzip); + try { + return await extractEntries(reader, gunzip, destDir); + } finally { + // A paused gunzip never reaches `end`, so it has to be closed explicitly. + src.destroy(); + gunzip.destroy(); + } +} +async function extractEntries(reader, gunzip, destDir) { const zeros = Buffer.alloc(BLOCK); let longName = null; let longLink = null; @@ -381,7 +395,6 @@ export async function extractTarGz(archiveFile, destDir) { entries += 1; } - src.destroy(); return { entries }; } diff --git a/tests/unit/build/standalone-bundle.test.ts b/tests/unit/build/standalone-bundle.test.ts index 038779fa2249..fb76a8db7bc7 100644 --- a/tests/unit/build/standalone-bundle.test.ts +++ b/tests/unit/build/standalone-bundle.test.ts @@ -4,6 +4,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { createHash } from "node:crypto"; +import { PassThrough } from "node:stream"; /** * Stage 8 (issue #10321) — shared standalone web bundle. @@ -20,6 +21,7 @@ import { createHash } from "node:crypto"; const bundleMod = await import("../../../scripts/build/standaloneBundle.mjs"); const manifestMod = await import("../../../scripts/build/standaloneManifest.mjs"); const hydrateMod = await import("../../../scripts/build/hydrateNativeDeps.mjs"); +const tarballMod = await import("../../../scripts/build/standaloneTarball.mjs"); const { runPack, runRestore } = bundleMod as typeof bundleMod & { runPack: (opts: { dir?: string; out: string; manifest?: string }) => Promise<{ @@ -53,6 +55,18 @@ const { hydratePlatformNatives, verifyBundledNatives } = hydrateMod as typeof hy }; }; +const { BlockSource, READ_AHEAD_BYTES, createTarGz, extractTarGz } = + tarballMod as typeof tarballMod & { + READ_AHEAD_BYTES: number; + BlockSource: new (stream: PassThrough) => { + buffered: number; + read: (n: number) => Promise; + readSome: (max?: number) => Promise; + }; + createTarGz: (srcDir: string, outFile: string) => Promise; + extractTarGz: (archive: string, destDir: string) => Promise<{ entries: number }>; + }; + const IS_WINDOWS = process.platform === "win32"; function tmpDir(prefix: string): string { @@ -166,6 +180,79 @@ test("restore rejects a corrupted archive before extraction", async () => { } }); +test("extraction does not recopy the buffered stream for every entry", async () => { + const src = tmpDir("s8-copies-src-"); + const outDir = tmpDir("s8-copies-out-"); + const dst = tmpDir("s8-copies-dst-"); + const realConcat = Buffer.concat; + try { + // Restore time on a real bundle (123k entries) went quadratic through + // Buffer.concat. Counting the copied bytes proves it without a timing assertion. + const entries = 2000; + const body = Buffer.alloc(1500, "x"); + for (let i = 0; i < entries; i++) { + fs.writeFileSync(path.join(src, `f${i}.txt`), body); + } + const archive = path.join(outDir, "web-bundle.tar.gz"); + await createTarGz(src, archive); + const tarBytes = entries * (512 + 2048); + + let copied = 0; + Buffer.concat = ((list: Uint8Array[], length?: number) => { + const joined = realConcat(list, length); + copied += joined.length; + return joined; + }) as typeof Buffer.concat; + const result = await extractTarGz(archive, dst); + Buffer.concat = realConcat; + + assert.equal(result.entries, entries); + assert.equal(fs.readFileSync(path.join(dst, "f1999.txt")).length, body.length); + assert.ok(copied <= tarBytes, `copied ${copied} bytes extracting a ${tarBytes}-byte tar`); + } finally { + Buffer.concat = realConcat; + fs.rmSync(src, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + fs.rmSync(outDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + fs.rmSync(dst, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); + } +}); + +test("BlockSource pauses the stream ahead of a slow reader and loses no bytes", async () => { + const stream = new PassThrough({ highWaterMark: 64 * 1024 }); + const source = new BlockSource(stream); + const chunk = Buffer.alloc(256 * 1024, 7); + const total = (READ_AHEAD_BYTES / chunk.length) * 4 * chunk.length; + let written = 0; + const writer = (async () => { + while (written < total) { + written += chunk.length; + if (!stream.write(chunk)) await new Promise((resolve) => stream.once("drain", resolve)); + } + stream.end(); + })(); + + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.ok(stream.isPaused(), "a reader that is behind must pause the stream"); + assert.ok( + source.buffered <= READ_AHEAD_BYTES + chunk.length, + `read-ahead ${source.buffered} exceeds the limit` + ); + assert.ok(written < total, "the writer must feel the backpressure"); + + // Reads cross chunk boundaries and must see every byte exactly once. + let received = 0; + const odd = 1000; + for (;;) { + const part = await source.read(odd); + if (part === null) break; + assert.equal(part.length, odd); + received += part.length; + } + await writer; + assert.equal(received, Math.floor(total / odd) * odd); + assert.equal(await source.readSome(), null, "the stream is exhausted"); +}); + test("manifest verification flags modified and smuggled files in a restored tree", async () => { const src = tmpDir("s8-verify-"); const outDir = tmpDir("s8-verify-out-"); diff --git a/tests/unit/build/standalone-manifest-symlink-portability.test.ts b/tests/unit/build/standalone-manifest-symlink-portability.test.ts index 21e9359c0f1b..e055826f48a8 100644 --- a/tests/unit/build/standalone-manifest-symlink-portability.test.ts +++ b/tests/unit/build/standalone-manifest-symlink-portability.test.ts @@ -9,19 +9,31 @@ import path from "node:path"; * manifest verification on Windows because symlink targets were stored as * absolute, packing-machine-specific paths). * - * npm ci on the ubuntu web-build leg is observed (run 33238093090) to - * produce at least one ABSOLUTE .bin symlink target (an npm/bin-links - * implementation detail) instead of the RELATIVE target a local `npm - * install` produces for the identical file - * (node_modules/global-agent/node_modules/.bin/semver -> ../semver/bin/semver.js). - * An absolute target is not portable: it dangles once the packing machine's - * path is gone (silent false-positive on POSIX) and Windows' - * CreateSymbolicLink rewrites it to a drive-relative path on read-back - * (outright verification failure) -- both symptoms share the same root - * cause of never normalizing to a relative, tree-anchored form. + * The one absolute link in a real bundle is + * standalone/node_modules/global-agent/node_modules/.bin/semver. npm writes it + * relative; colocateLlmlinguaOptionals' cpSync rewrote it to the build + * checkout's root node_modules, which is OUTSIDE the packed `.build/next` tree + * (run 33238093090 on the hosted runner, run 42206099467 on omni-build). Such a + * target is not portable: it dangles once the packing machine's path is gone + * and Windows' CreateSymbolicLink rewrites it to a drive-relative path on + * read-back. The colocation cases below reproduce that shape; the #11979 cases + * cover an absolute target that does sit inside the tree. */ +const bundleMod = await import("../../../scripts/build/standaloneBundle.mjs"); +const colocateMod = await import("../../../scripts/build/colocateOptionals.mjs"); const manifestMod = await import("../../../scripts/build/standaloneManifest.mjs"); +const { runPack, runRestore } = bundleMod as typeof bundleMod & { + runPack: (opts: { dir?: string; out: string }) => Promise<{ files: number }>; + runRestore: (opts: { archive: string; dir?: string }) => Promise<{ files: number }>; +}; +const { colocateLlmlinguaOptionals } = colocateMod as typeof colocateMod & { + colocateLlmlinguaOptionals: (opts: { + rootDir: string; + targetNodeModulesDir: string; + seeds: string[]; + }) => { skipped: boolean; copied?: number }; +}; const { buildStandaloneManifest, verifyStandaloneManifest, normalizeSymlinkTarget } = manifestMod as typeof manifestMod & { buildStandaloneManifest: ( @@ -34,7 +46,8 @@ const { buildStandaloneManifest, verifyStandaloneManifest, normalizeSymlinkTarge normalizeSymlinkTarget: ( rootDir: string, entryRelPath: string, - rawTarget: string + rawTarget: string, + sep?: string ) => { ok: true; value: string } | { ok: false; reason: string }; }; @@ -107,10 +120,7 @@ test("#11979: a relativized manifest restores to a working (non-dangling) symlin "bin" ); fs.mkdirSync(semverDir2, { recursive: true }); - fs.writeFileSync( - path.join(semverDir2, "semver.js"), - "#!/usr/bin/env node\n// fake semver cli\n" - ); + fs.writeFileSync(path.join(semverDir2, "semver.js"), "#!/usr/bin/env node\n// fake semver cli\n"); const binDir = path.join(restoredRoot, "node_modules", "global-agent", "node_modules", ".bin"); fs.mkdirSync(binDir, { recursive: true }); fs.symlinkSync(entry.symlink!, path.join(binDir, "semver")); @@ -173,3 +183,268 @@ test("#11979: normalizeSymlinkTarget rejects an absolute target that escapes the assert.equal(result.ok, false); fs.rmSync(rootDir, { recursive: true, force: true }); }); + +const BIN_LINK = "node_modules/global-agent/node_modules/.bin/semver"; + +/** + * A build checkout laid out like the real one: global-agent installed by npm at + * the root with its relative .bin link, and a `.build/next` tree that Next did + * not trace global-agent into. + */ +function makeBuildCheckout(checkout: string): { packDir: string; standaloneNm: string } { + const pkg = path.join(checkout, "node_modules", "global-agent"); + const nestedBin = path.join(pkg, "node_modules", ".bin"); + const semverBin = path.join(pkg, "node_modules", "semver", "bin"); + fs.mkdirSync(nestedBin, { recursive: true }); + fs.mkdirSync(semverBin, { recursive: true }); + fs.writeFileSync( + path.join(pkg, "package.json"), + JSON.stringify({ name: "global-agent", version: "4.1.3", main: "index.js" }) + ); + fs.writeFileSync(path.join(pkg, "index.js"), "module.exports = {};\n"); + fs.writeFileSync(path.join(semverBin, "semver.js"), "// semver cli\n"); + fs.symlinkSync("../semver/bin/semver.js", path.join(nestedBin, "semver")); + + const packDir = path.join(checkout, ".build", "next"); + const standaloneNm = path.join(packDir, "standalone", "node_modules"); + fs.mkdirSync(standaloneNm, { recursive: true }); + fs.writeFileSync(path.join(packDir, "standalone", "server.js"), "// server\n"); + return { packDir, standaloneNm }; +} + +function colocateGlobalAgent(checkout: string, standaloneNm: string): void { + const result = colocateLlmlinguaOptionals({ + rootDir: checkout, + targetNodeModulesDir: standaloneNm, + seeds: ["global-agent"], + }); + assert.equal(result.copied, 1, "global-agent must be co-located"); +} + +test("colocation keeps a package's nested .bin link relative", () => { + const checkout = tmpDir("standalone-checkout-"); + try { + const { standaloneNm } = makeBuildCheckout(checkout); + colocateGlobalAgent(checkout, standaloneNm); + assert.equal( + fs.readlinkSync(path.join(standaloneNm, "global-agent/node_modules/.bin/semver")), + "../semver/bin/semver.js", + "the copy must not point back at the build checkout's root node_modules" + ); + } finally { + fs.rmSync(checkout, { recursive: true, force: true }); + } +}); + +test("colocation fills a partially traced package without breaking its .bin link", () => { + const checkout = tmpDir("standalone-checkout-"); + try { + const { standaloneNm } = makeBuildCheckout(checkout); + // The trace left the link and the manifest but not the entrypoint, so the + // package is not intact and the copy merges over the existing link. + const traced = path.join(standaloneNm, "global-agent"); + fs.mkdirSync(path.join(traced, "node_modules", ".bin"), { recursive: true }); + fs.copyFileSync( + path.join(checkout, "node_modules", "global-agent", "package.json"), + path.join(traced, "package.json") + ); + fs.symlinkSync("../semver/bin/semver.js", path.join(traced, "node_modules", ".bin", "semver")); + + colocateGlobalAgent(checkout, standaloneNm); + + assert.ok(fs.existsSync(path.join(traced, "index.js")), "missing entrypoint filled in"); + assert.equal( + fs.readlinkSync(path.join(traced, "node_modules", ".bin", "semver")), + "../semver/bin/semver.js" + ); + } finally { + fs.rmSync(checkout, { recursive: true, force: true }); + } +}); + +test("a colocated tree packs here and restores where the build checkout is gone", async () => { + const checkout = tmpDir("standalone-checkout-"); + const outDir = tmpDir("standalone-out-"); + const restored = path.join(outDir, "restored"); + try { + const { packDir, standaloneNm } = makeBuildCheckout(checkout); + colocateGlobalAgent(checkout, standaloneNm); + + const archive = path.join(outDir, "web-bundle.tar.gz"); + await runPack({ dir: packDir, out: archive }); + // Only the archive and its manifest travel to the desktop legs. + fs.rmSync(checkout, { recursive: true, force: true }); + await runRestore({ archive, dir: restored }); + + const restoredLink = path.join(restored, "standalone", BIN_LINK); + assert.equal(fs.readlinkSync(restoredLink), "../semver/bin/semver.js"); + assert.equal(fs.readFileSync(restoredLink, "utf8"), "// semver cli\n"); + } finally { + fs.rmSync(checkout, { recursive: true, force: true }); + fs.rmSync(outDir, { recursive: true, force: true }); + } +}); + +test("pack refuses an absolute link into the build checkout even when the tree has that path", async () => { + const checkout = tmpDir("standalone-checkout-"); + const outDir = tmpDir("standalone-out-"); + try { + const { packDir, standaloneNm } = makeBuildCheckout(checkout); + colocateGlobalAgent(checkout, standaloneNm); + // The exact v3.8.53 shape: the same file exists inside the tree, but the + // link itself leaves it. Guessing the in-tree twin would hide a broken build. + const link = path.join(standaloneNm, "global-agent/node_modules/.bin/semver"); + fs.rmSync(link); + fs.symlinkSync( + path.join(checkout, "node_modules/global-agent/node_modules/semver/bin/semver.js"), + link + ); + + await assert.rejects( + () => runPack({ dir: packDir, out: path.join(outDir, "web-bundle.tar.gz") }), + /target escapes the tree root/ + ); + } finally { + fs.rmSync(checkout, { recursive: true, force: true }); + fs.rmSync(outDir, { recursive: true, force: true }); + } +}); + +for (const [label, target] of [ + ["absolute", "/opt/actions-runner/_work/secret.txt"], + ["relative", "../../../../secret.txt"], +] as const) { + test(`pack refuses a ${label} link that escapes the tree`, async () => { + const root = tmpDir("standalone-escape-"); + const outDir = tmpDir("standalone-out-"); + try { + const binDir = path.join(root, "standalone", "node_modules", ".bin"); + fs.mkdirSync(binDir, { recursive: true }); + fs.symlinkSync(target, path.join(binDir, "escape")); + + await assert.rejects( + () => runPack({ dir: root, out: path.join(outDir, "web-bundle.tar.gz") }), + /target escapes the tree root/ + ); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + fs.rmSync(outDir, { recursive: true, force: true }); + } + }); +} + +test("pack keeps Turbopack's relative externals, which resolve in every checkout", async () => { + const checkout = tmpDir("standalone-checkout-"); + const outDir = tmpDir("standalone-out-"); + const restoredCheckout = tmpDir("standalone-leg-"); + try { + const { packDir } = makeBuildCheckout(checkout); + // The real shape: 15 of these sit beside standalone/ in a Turbopack build. + const links = [ + ["ws-a972e7ffa40ff725", "../../../node_modules/ws"], + ["@ngrok/ngrok-0f98e1294a0b09d5", "../../../../node_modules/@ngrok/ngrok"], + ]; + for (const [name, target] of links) { + const link = path.join(packDir, "node_modules", name); + fs.mkdirSync(path.dirname(link), { recursive: true }); + fs.symlinkSync(target, link); + } + + const archive = path.join(outDir, "web-bundle.tar.gz"); + await runPack({ dir: packDir, out: archive }); + const restored = path.join(restoredCheckout, ".build", "next"); + await runRestore({ archive, dir: restored }); + + for (const [name, target] of links) { + assert.equal(fs.readlinkSync(path.join(restored, "node_modules", name)), target); + } + // The leg's own npm ci provides the package the link lands on. + fs.mkdirSync(path.join(restoredCheckout, "node_modules", "ws"), { recursive: true }); + fs.writeFileSync(path.join(restoredCheckout, "node_modules", "ws", "index.js"), "// ws\n"); + assert.equal( + fs.readFileSync(path.join(restored, "node_modules", links[0][0], "index.js"), "utf8"), + "// ws\n" + ); + } finally { + fs.rmSync(checkout, { recursive: true, force: true }); + fs.rmSync(outDir, { recursive: true, force: true }); + fs.rmSync(restoredCheckout, { recursive: true, force: true }); + } +}); + +test("under standalone/, normalizeSymlinkTarget refuses relative targets that leave the tree", () => { + const entry = "standalone/node_modules/.bin/tool"; + const rootDir = tmpDir("standalone-root-"); + try { + assert.deepEqual(normalizeSymlinkTarget(rootDir, entry, "../tool/cli.js"), { + ok: true, + value: "../tool/cli.js", + }); + assert.deepEqual(normalizeSymlinkTarget(rootDir, entry, "../../../static/app.css"), { + ok: true, + value: "../../../static/app.css", + }); + for (const target of ["../../../..", "../../../../outside.js", "../../..", "../../../"]) { + const result = normalizeSymlinkTarget(rootDir, entry, target); + assert.equal(result.ok, false, `${target} must be refused`); + } + } finally { + fs.rmSync(rootDir, { recursive: true, force: true }); + } +}); + +test("Windows read-back of a relative link compares equal to the manifest's posix target", () => { + const entry = "standalone/node_modules/global-agent/node_modules/.bin/semver"; + const rootDir = tmpDir("standalone-root-"); + try { + // fs.symlinkSync stores `\\` on Windows, so readlink never returns the `/` + // the Linux pack recorded. + assert.deepEqual(normalizeSymlinkTarget(rootDir, entry, "..\\semver\\bin\\semver.js", "\\"), { + ok: true, + value: "../semver/bin/semver.js", + }); + const escaping = "..\\..\\..\\..\\..\\..\\outside.js"; + assert.equal(normalizeSymlinkTarget(rootDir, entry, escaping, "\\").ok, false); + // A backslash is an ordinary filename character on POSIX. + assert.deepEqual(normalizeSymlinkTarget(rootDir, entry, "..\\semver"), { + ok: true, + value: "..\\semver", + }); + } finally { + fs.rmSync(rootDir, { recursive: true, force: true }); + } +}); + +test("verification still fails a restored link that was retargeted", async () => { + const checkout = tmpDir("standalone-checkout-"); + const outDir = tmpDir("standalone-out-"); + const restored = path.join(outDir, "restored"); + try { + const { packDir, standaloneNm } = makeBuildCheckout(checkout); + colocateGlobalAgent(checkout, standaloneNm); + const archive = path.join(outDir, "web-bundle.tar.gz"); + await runPack({ dir: packDir, out: archive }); + await runRestore({ archive, dir: restored }); + const manifest = JSON.parse(fs.readFileSync(`${archive}.manifest.json`, "utf8")); + const link = path.join(restored, "standalone", BIN_LINK); + + fs.rmSync(link); + fs.symlinkSync("../semver/package.json", link); + const inTree = await verifyStandaloneManifest(restored, manifest); + assert.equal(inTree.ok, false); + assert.match( + (inTree as { errors: string[] }).errors.join("; "), + /symlink target \.\.\/semver\/package\.json != \.\.\/semver\/bin\/semver\.js/ + ); + + fs.rmSync(link); + fs.symlinkSync("../../../../../../../outside.js", link); + await assert.rejects( + () => verifyStandaloneManifest(restored, manifest), + /target escapes the tree root/ + ); + } finally { + fs.rmSync(checkout, { recursive: true, force: true }); + fs.rmSync(outDir, { recursive: true, force: true }); + } +}); From 7eb1b69b51f10049cd1e4d67aab813af67803524 Mon Sep 17 00:00:00 2001 From: Diego Rodrigues de Sa e Souza Date: Sat, 7 Nov 2026 17:13:02 -0300 Subject: [PATCH 02/13] fix(ci): give the Sonar JS/TS analyzer enough heap (#19280) Cherry-pick of #19179 to main, so PRs based on main scan with the same heap as the release branch. --- sonar-project.properties | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sonar-project.properties b/sonar-project.properties index 4194c660c375..a45546d77ecf 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -7,6 +7,12 @@ sonar.test.inclusions=tests/**/*.test.ts,tests/**/*.spec.ts sonar.exclusions=tests/**,src/i18n/messages/**,docs/**,coverage/**,.next/**,dist/**,build/**,node_modules/** sonar.javascript.lcov.reportPaths=coverage/lcov.info +# The JS/TS analyzer runs in its own Node.js process. On the hosted runner (16 GB) its default +# heap is 4288 MB, which this codebase outgrew: the first scan that really executed after the +# move to the cheaper-inference org (2026-11-05, CI run 42015741745) stopped with "the Node.js +# process running out of memory (heap size limit 4288 MB)". Value is in MB. +sonar.javascript.node.maxspace=10240 + # ── "Clean as You Code" — new-code quality gate ─────────────────────────── # New code must not introduce any bug, vulnerability, hotspot or code smell. # Legacy code is grandfathered (sonar.newCode.referenceBranch baseline). From 094a1aa1c0b2c54a4c4e3065948b3d4e9c1d0165 Mon Sep 17 00:00:00 2001 From: Diego Rodrigues de Sa e Souza Date: Sun, 8 Nov 2026 22:33:19 -0300 Subject: [PATCH 03/13] fix(ci): stop the Codecov uploader from scanning the coverage shards (main) (#19332) --- .github/workflows/ci.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 46be6ae40c5e..504180baf9f4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1326,6 +1326,11 @@ jobs: uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: files: coverage/lcov.info + # `files` does not stop the uploader from also searching the workspace: on the + # v3.8.53 release push (run 42180292091) it found the 22207 per-shard JSON files + # under coverage-shards/, hit the 5-minute ceiling and never uploaded anything, + # while continue-on-error kept the step green. lcov.info is the only report. + disable_search: true token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: false - name: Upload coverage artifacts From a3b27ba4d37b2144f58dfaafb88d9a3e8e1ae681 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:27:37 +0330 Subject: [PATCH 04/13] fix(sse): bound the non-SSE body read behind an early keepalive After the early keepalive committed a 200 event stream, the wrapper stopped the slow-path deadline as soon as the handler resolved. A handler response that was not an event stream (text/plain or JSON) was then read with response.text(), with no deadline and no way to cancel. A body that trickled forever held the client stream open and the upstream connection with it. Keep the deadline armed through the non-SSE body read. Read the body through upstreamReader so the deadline, client abort and consumer cancel paths all cancel it. Stop the deadline only when a real event stream starts, as before. (cherry picked from commit abcee9b2380321e16acc72afeee0d5b6da52382b) --- .../0000-keepalive-nonsse-body-deadline.md | 1 + open-sse/utils/earlyStreamKeepalive.ts | 26 +++- ...eam-keepalive-nonsse-body-deadline.test.ts | 112 ++++++++++++++++++ 3 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md create mode 100644 tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts diff --git a/changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md b/changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md new file mode 100644 index 000000000000..e64c89207714 --- /dev/null +++ b/changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md @@ -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. diff --git a/open-sse/utils/earlyStreamKeepalive.ts b/open-sse/utils/earlyStreamKeepalive.ts index a18c1955d6e0..ed664bca41c0 100644 --- a/open-sse/utils/earlyStreamKeepalive.ts +++ b/open-sse/utils/earlyStreamKeepalive.ts @@ -632,6 +632,7 @@ export async function withEarlyStreamKeepalive( aborted = true; stopDeadline(); stopKeepalive(); + upstreamReader?.cancel().catch(() => {}); try { deadlineController?.abort(); } catch { @@ -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. @@ -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). @@ -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, { diff --git a/tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts b/tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts new file mode 100644 index 000000000000..774a265ac055 --- /dev/null +++ b/tests/unit/early-stream-keepalive-nonsse-body-deadline.test.ts @@ -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 { + 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 | undefined; + const trickling = new ReadableStream({ + start(controller) { + trickle = setInterval(() => controller.enqueue(encoder.encode("x")), 10); + }, + cancel() { + sourceCancelled = true; + clearInterval(trickle); + }, + }); + const handler = new Promise((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((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"); +}); From 93aff25221cb75929503de2805918306dc177582 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:48:33 +0330 Subject: [PATCH 05/13] fix(sse): drain batched frames when a failure terminates the stream With SSE_FRAME_COALESCE_MS on, the output sink holds frames in a batch. A preserved upstream failure ends the stream with controller.terminate() from inside transform(). flush() never runs after that, so the sink could not drain. A bare OpenAI error envelope is not a terminal frame for the sink, so the last content frame and the real error frame were lost and the client saw a truncated stream. The sink now wraps the controller handed to transform(). Its terminate() drains the batch and disposes the sink before it closes the stream. (cherry picked from commit 10c610715a49206fd29a96fa2771f250ab2e9bf1) --- .../0000-sse-coalesce-terminate-flush.md | 1 + open-sse/utils/sseOutputSink.ts | 22 +++++ ...-output-coalescing-terminate-flush.test.ts | 94 +++++++++++++++++++ 3 files changed, 117 insertions(+) create mode 100644 changelog.d/fixes/0000-sse-coalesce-terminate-flush.md create mode 100644 tests/unit/sse-output-coalescing-terminate-flush.test.ts diff --git a/changelog.d/fixes/0000-sse-coalesce-terminate-flush.md b/changelog.d/fixes/0000-sse-coalesce-terminate-flush.md new file mode 100644 index 000000000000..c0dc89f63e98 --- /dev/null +++ b/changelog.d/fixes/0000-sse-coalesce-terminate-flush.md @@ -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. diff --git a/open-sse/utils/sseOutputSink.ts b/open-sse/utils/sseOutputSink.ts index dfa8d28b3bf6..3714c2798bd4 100644 --- a/open-sse/utils/sseOutputSink.ts +++ b/open-sse/utils/sseOutputSink.ts @@ -163,10 +163,32 @@ export function createSSEOutputSink( const wrap = >(transformer: T): T => { if (!deltaStage && frameWindowMs <= 0) return transformer; + const originalTransform = transformer.transform; const originalFlush = transformer.flush; const originalCancel = (transformer as CancelableTransformer).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); diff --git a/tests/unit/sse-output-coalescing-terminate-flush.test.ts b/tests/unit/sse-output-coalescing-terminate-flush.test.ts new file mode 100644 index 000000000000..80de0ba45208 --- /dev/null +++ b/tests/unit/sse-output-coalescing-terminate-flush.test.ts @@ -0,0 +1,94 @@ +/** + * Opt-in SSE frame batching (SSE_FRAME_COALESCE_MS) must not eat the tail of a failed stream: + * when a preserved upstream failure terminates the transform, flush() never runs, so the + * sink has to drain the queued delta and the failure frame itself. + */ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-sse-coalesce-terminate-")); +process.env.DATA_DIR = TEST_DATA_DIR; +const core = await import("../../src/lib/db/core.ts"); + +const { createSSEStream } = await import("../../open-sse/utils/stream.ts"); +const { FORMATS } = await import("../../open-sse/translator/formats.ts"); + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +const chunk = (delta: Record) => + `data: ${JSON.stringify({ + id: "chatcmpl-abcdefgh1", + object: "chat.completion.chunk", + created: 1, + model: "m", + choices: [{ index: 0, delta, finish_reason: null }], + })}\n\n`; +// A bare OpenAI error envelope: no `event: error` line, no `"type":"error"` marker. +const BARE_ERROR = `data: ${JSON.stringify({ + error: { message: "upstream exploded", type: "server_error", code: "500" }, +})}\n\n`; + +async function run(frameCoalesceMs: string | undefined) { + const saved = process.env.SSE_FRAME_COALESCE_MS; + if (frameCoalesceMs === undefined) delete process.env.SSE_FRAME_COALESCE_MS; + else process.env.SSE_FRAME_COALESCE_MS = frameCoalesceMs; + try { + const stream = createSSEStream({ + mode: "passthrough", + provider: "openai", + model: "m", + clientResponseFormat: FORMATS.OPENAI, + body: { messages: [{ role: "user", content: "hi" }] }, + }); + const frames = [ + chunk({ role: "assistant", content: "A" }), + chunk({ content: "B" }), + BARE_ERROR, + ]; + const source = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(frames.join(""))); + controller.close(); + }, + }); + const reader = source.pipeThrough(stream).getReader(); + let out = ""; + let error: unknown = null; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + out += decoder.decode(value); + } + } catch (err) { + error = err; + } + return { out, error }; + } finally { + if (saved === undefined) delete process.env.SSE_FRAME_COALESCE_MS; + else process.env.SSE_FRAME_COALESCE_MS = saved; + } +} + +test.after(() => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +}); + +test("unbatched stream delivers the queued delta and the upstream failure frame", async () => { + const { out } = await run(undefined); + assert.ok(out.includes('"content":"B"'), "queued delta B reaches the client"); + assert.ok(out.includes("upstream exploded"), "upstream failure frame reaches the client"); +}); + +test("batched stream delivers the queued delta and the upstream failure frame on terminate", async () => { + const plain = await run(undefined); + const batched = await run("200"); + assert.ok(batched.out.includes('"content":"B"'), "queued delta B survives the terminate"); + assert.ok(batched.out.includes("upstream exploded"), "upstream failure frame survives"); + assert.equal(batched.out, plain.out, "batching changes enqueue grouping, not bytes"); +}); From 539305e9ad5cc90fc223b0af39a7e2a28a3f60c1 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:57:56 +0330 Subject: [PATCH 06/13] fix(sse): cap bytes held before the first stream readiness signal ensureStreamReadiness kept every pre-signal chunk. The 64 KiB hand-off limit only applied after the content probe started. A body of comment lines, pings or invalid data lines never reaches a signal, so it grew with upstream rate times the readiness deadline. Stop at 1 MiB without a signal. Cancel the upstream and return the same STREAM_READINESS_TIMEOUT result as a deadline stall, so retry and combo fallback keep working. The limit is far above one real first frame. (cherry picked from commit 2bad345ad509307c12234018097401ced66bad8f) --- ...0000-stream-readiness-pre-signal-budget.md | 1 + open-sse/utils/streamReadiness.ts | 30 ++++++ ...m-readiness-pre-signal-byte-budget.test.ts | 98 +++++++++++++++++++ 3 files changed, 129 insertions(+) create mode 100644 changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md create mode 100644 tests/unit/stream-readiness-pre-signal-byte-budget.test.ts diff --git a/changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md b/changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md new file mode 100644 index 000000000000..a94c3c3da50b --- /dev/null +++ b/changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md @@ -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. diff --git a/open-sse/utils/streamReadiness.ts b/open-sse/utils/streamReadiness.ts index 069a511dfe02..20b4b10aafba 100644 --- a/open-sse/utils/streamReadiness.ts +++ b/open-sse/utils/streamReadiness.ts @@ -857,6 +857,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"); @@ -1260,6 +1265,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) { diff --git a/tests/unit/stream-readiness-pre-signal-byte-budget.test.ts b/tests/unit/stream-readiness-pre-signal-byte-budget.test.ts new file mode 100644 index 000000000000..00d491c8782f --- /dev/null +++ b/tests/unit/stream-readiness-pre-signal-byte-budget.test.ts @@ -0,0 +1,98 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "or9r-readiness-budget-")); + +const { ensureStreamReadiness } = await import("../../open-sse/utils/streamReadiness.ts"); + +const encoder = new TextEncoder(); +const CHUNK_BYTES = 16 * 1024; +const READY_FRAME = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\n'; + +// Pull-driven source: `junk` chunks first, then one real frame, then close. +function junkThenReady(junk: () => string, junkChunks: number) { + const state = { pulled: 0, cancelled: false }; + const body = new ReadableStream({ + pull(controller) { + state.pulled += 1; + if (state.pulled <= junkChunks) controller.enqueue(encoder.encode(junk())); + else if (state.pulled === junkChunks + 1) controller.enqueue(encoder.encode(READY_FRAME)); + else controller.close(); + }, + cancel() { + state.cancelled = true; + }, + }); + return { + state, + response: new Response(body, { headers: { "Content-Type": "text/event-stream" } }), + }; +} + +const commentChunk = () => `:${"x".repeat(CHUNK_BYTES)}\n\n`; +const invalidDataChunk = () => `data: ${"y".repeat(CHUNK_BYTES)}\n\n`; + +for (const [name, junk] of [ + ["comment-only", commentChunk], + ["invalid-data", invalidDataChunk], +] as const) { + test(`${name} body is rejected once the pre-signal byte budget is spent`, async () => { + const { state, response } = junkThenReady(junk, 200); + const result = await ensureStreamReadiness(response, { timeoutMs: 5000 }); + + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.code, "STREAM_READINESS_TIMEOUT"); + assert.equal(result.response.status, 504); + assert.equal(typeof result.anyByteAt, "number"); + assert.equal(state.cancelled, true, "upstream reader is cancelled"); + assert.ok(state.pulled < 100, `stopped reading early, pulled ${state.pulled} chunks`); + }); +} + +test("a few heartbeat comments before the first real frame still pass", async () => { + const { response } = junkThenReady(commentChunk, 5); + const result = await ensureStreamReadiness(response, { timeoutMs: 5000 }); + assert.equal(result.ok, true); +}); + +// A Responses `response.created` frame echoes instructions and tools, so a real first +// frame can pass 64 KiB. The budget must stay well above that. +test("one large first frame split over many chunks still passes", async () => { + const big = `data: {"choices":[{"delta":{"content":"${"z".repeat(100 * 1024)}"}}]}\n\n`; + const parts: string[] = []; + for (let i = 0; i < big.length; i += CHUNK_BYTES) parts.push(big.slice(i, i + CHUNK_BYTES)); + const body = new ReadableStream({ + pull(controller) { + const next = parts.shift(); + if (next === undefined) controller.close(); + else controller.enqueue(encoder.encode(next)); + }, + }); + const result = await ensureStreamReadiness(new Response(body), { timeoutMs: 5000 }); + assert.equal(result.ok, true); +}); + +test("a single unterminated line cannot grow without bound before the first signal", async () => { + const state = { pulled: 0, cancelled: false }; + const body = new ReadableStream({ + pull(controller) { + state.pulled += 1; + if (state.pulled <= 300) controller.enqueue(encoder.encode("y".repeat(CHUNK_BYTES))); + else if (state.pulled === 301) controller.enqueue(encoder.encode(`\n\n${READY_FRAME}`)); + else controller.close(); + }, + cancel() { + state.cancelled = true; + }, + }); + const result = await ensureStreamReadiness(new Response(body), { timeoutMs: 5000 }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.code, "STREAM_READINESS_TIMEOUT"); + assert.equal(state.cancelled, true); + assert.ok(state.pulled < 100, `stopped reading early, pulled ${state.pulled} chunks`); +}); From 4780197bb3a0115b81808d73032caffaea62dfa3 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:10:10 +0330 Subject: [PATCH 07/13] perf(sse): stop scanning stream frames after content is seen The content watcher in createDisconnectAwareStream ran for every client chunk. After the first content it still split frames, parsed JSON for error frames and regex-scanned stop reasons. Every reader of those flags tests sawContent() first or only needs them for a stream without content. sawNormalStopTerminal has no reader. Make note() and finish() return early once content is seen. The separate client terminal watcher, the disconnect drain and the upstream stall watcher are unchanged. Median time for 2,000 OpenAI frames: 17.5 ms before, 0.12 ms after. (cherry picked from commit 593c0a4f817e6143d00289888c3639de090082e6) --- .../0000-stream-content-watcher-inert.md | 1 + open-sse/utils/streamReadiness.ts | 14 +++- ...ontent-watcher-inert-after-content.test.ts | 83 +++++++++++++++++++ 3 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 changelog.d/maintenance/0000-stream-content-watcher-inert.md create mode 100644 tests/unit/stream-content-watcher-inert-after-content.test.ts diff --git a/changelog.d/maintenance/0000-stream-content-watcher-inert.md b/changelog.d/maintenance/0000-stream-content-watcher-inert.md new file mode 100644 index 000000000000..b0b6d4d7d9d0 --- /dev/null +++ b/changelog.d/maintenance/0000-stream-content-watcher-inert.md @@ -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. diff --git a/open-sse/utils/streamReadiness.ts b/open-sse/utils/streamReadiness.ts index 20b4b10aafba..ad33071b1046 100644 --- a/open-sse/utils/streamReadiness.ts +++ b/open-sse/utils/streamReadiness.ts @@ -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; /** @@ -567,13 +568,20 @@ 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); @@ -581,7 +589,7 @@ export function createStreamContentWatcher( } }, finish(): void { - inspect(pending); + if (!content) inspect(pending); pending = ""; }, sawContent: () => content, diff --git a/tests/unit/stream-content-watcher-inert-after-content.test.ts b/tests/unit/stream-content-watcher-inert-after-content.test.ts new file mode 100644 index 000000000000..33f6b869bce9 --- /dev/null +++ b/tests/unit/stream-content-watcher-inert-after-content.test.ts @@ -0,0 +1,83 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "or9r-content-watcher-")); + +const { createStreamContentWatcher } = await import("../../open-sse/utils/streamReadiness.ts"); + +const contentFrame = (text: string) => + `data: ${JSON.stringify({ choices: [{ delta: { content: text } }] })}\n\n`; + +// Count JSON.parse calls made while `run` executes (the watcher parses every data line). +function countParses(run: () => void): number { + const original = JSON.parse; + let calls = 0; + JSON.parse = ((...args: Parameters) => { + calls += 1; + return original(...args); + }) as typeof JSON.parse; + try { + run(); + } finally { + JSON.parse = original; + } + return calls; +} + +test("content watcher stops parsing frames once content is proven", () => { + const watcher = createStreamContentWatcher(); + watcher.note(contentFrame("first")); + assert.equal(watcher.sawContent(), true); + + const parses = countParses(() => { + for (let i = 0; i < 500; i += 1) watcher.note(contentFrame(`token ${i}`)); + watcher.finish(); + }); + + assert.equal(parses, 0, "no frame is parsed after content is seen"); + assert.equal(watcher.sawContent(), true); +}); + +test("content watcher keeps scanning every frame while content is absent", () => { + const watcher = createStreamContentWatcher(); + const parses = countParses(() => { + for (let i = 0; i < 50; i += 1) watcher.note(`data: ${JSON.stringify({ choices: [] })}\n\n`); + }); + assert.ok(parses >= 50, `every frame is parsed while content is absent, got ${parses}`); + assert.equal(watcher.sawContent(), false); + assert.equal(watcher.sawSseFrame(), true); +}); + +test("pre-content flags still work: error frame, legit empty terminal, reasoning progress", () => { + const errored = createStreamContentWatcher(); + errored.note('data: {"type":"error","error":{"type":"overloaded_error","message":"busy"}}\n\n'); + assert.equal(errored.sawError(), true); + assert.equal(errored.sawContent(), false); + + const empty = createStreamContentWatcher(); + empty.note('data: {"choices":[{"delta":{},"finish_reason":"length"}]}\n\n'); + assert.equal(empty.sawLegitEmptyTerminal(), true); + assert.equal(empty.sawContent(), false); + + const thinking = createStreamContentWatcher(); + thinking.note( + 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":""}}\n\n' + ); + thinking.note( + 'event: content_block_delta\ndata: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}\n\n' + ); + assert.equal(thinking.sawContent(), false); + assert.equal(thinking.reasoningProgress(), 2); +}); + +test("a content frame split across chunks is still detected", () => { + const watcher = createStreamContentWatcher(); + const frame = contentFrame("split"); + watcher.note(frame.slice(0, 12)); + assert.equal(watcher.sawContent(), false); + watcher.note(frame.slice(12)); + assert.equal(watcher.sawContent(), true); +}); From df2f8f660f3ee3c134ce92e643b8b234c9ad8e6d Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:28:28 +0330 Subject: [PATCH 08/13] fix(sse): clear the stream idle watchdog when the transform throws The idle watchdog interval is cleared in flush() and cancel(). An exception thrown inside transform() (for example a translator that meets a malformed frame) errors both sides of the stream without running either hook. The interval then kept the failed stream alive until the idle timeout. transform() now clears the watchdog before it rethrows. A stream that is still running keeps its watchdog. (cherry picked from commit 23ee6cb10756165ff02051299a8a665879e50e43) --- ...eam-watchdog-cleared-on-transform-error.md | 1 + open-sse/utils/stream.ts | 12 +++ ...atchdog-cleared-on-transform-error.test.ts | 99 +++++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md create mode 100644 tests/unit/stream-watchdog-cleared-on-transform-error.test.ts diff --git a/changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md b/changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md new file mode 100644 index 000000000000..db69076b8e3b --- /dev/null +++ b/changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md @@ -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. diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts index cf361c1ac7ad..ec24d889ad71 100644 --- a/open-sse/utils/stream.ts +++ b/open-sse/utils/stream.ts @@ -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) { if (streamTimedOut) return; const now = Date.now(); timing.markByte(); diff --git a/tests/unit/stream-watchdog-cleared-on-transform-error.test.ts b/tests/unit/stream-watchdog-cleared-on-transform-error.test.ts new file mode 100644 index 000000000000..b3de86e326a5 --- /dev/null +++ b/tests/unit/stream-watchdog-cleared-on-transform-error.test.ts @@ -0,0 +1,99 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-watchdog-")); +process.env.DATA_DIR = TEST_DATA_DIR; +const core = await import("../../src/lib/db/core.ts"); +const { createSSEStream } = await import("../../open-sse/utils/stream.ts"); +const { FORMATS } = await import("../../open-sse/translator/formats.ts"); + +const textEncoder = new TextEncoder(); + +type Handle = ReturnType; + +const frame = (choice: Record) => + `data: ${JSON.stringify({ + id: "c1", + object: "chat.completion.chunk", + model: "m", + choices: [{ index: 0, ...choice }], + })}\n\n`; + +/** Run `fn` while counting the setInterval handles it leaves live. */ +async function withIntervalCount(fn: (liveCount: () => number) => Promise): Promise { + const realSet = globalThis.setInterval; + const realClear = globalThis.clearInterval; + const live = new Set(); + globalThis.setInterval = ((...args: Parameters) => { + const handle = realSet(...args); + live.add(handle); + return handle; + }) as typeof setInterval; + globalThis.clearInterval = ((handle: Handle) => { + live.delete(handle); + return realClear(handle); + }) as typeof clearInterval; + try { + return await fn(() => live.size); + } finally { + for (const handle of live) realClear(handle); + globalThis.setInterval = realSet; + globalThis.clearInterval = realClear; + } +} + +function translateStream() { + return createSSEStream({ + mode: "translate", + targetFormat: FORMATS.OPENAI, + sourceFormat: FORMATS.CLAUDE, + provider: "test", + model: "m", + body: { messages: [{ role: "user", content: "hi" }] }, + } as never); +} + +test.after(() => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +}); + +test("a transform that throws leaves no live idle watchdog interval", async () => { + await withIntervalCount(async (liveCount) => { + const source = new ReadableStream({ + start(controller) { + controller.enqueue( + textEncoder.encode(frame({ delta: { role: "assistant", content: "hi" } })) + ); + // A malformed frame makes the translator throw inside transform(). + controller.enqueue(textEncoder.encode(frame({ delta: { tool_calls: [null] } }))); + controller.close(); + }, + }); + await assert.rejects(new Response(source.pipeThrough(translateStream())).text()); + assert.equal(liveCount(), 0, "the idle watchdog must be cleared once the stream failed"); + }); +}); + +test("a stream that is still running keeps its idle watchdog armed", async () => { + await withIntervalCount(async (liveCount) => { + let finish: () => void = () => {}; + const source = new ReadableStream({ + start(controller) { + controller.enqueue( + textEncoder.encode(frame({ delta: { role: "assistant", content: "hi" } })) + ); + finish = () => controller.close(); + }, + }); + const reader = source.pipeThrough(translateStream()).getReader(); + await reader.read(); + assert.equal(liveCount(), 1, "a live stream needs its watchdog"); + finish(); + while (!(await reader.read()).done); + assert.equal(liveCount(), 0, "a completed stream clears it"); + }); +}); From 3b9bd05b9f3be69adac60124e51441b327b36ed2 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:19:15 +0330 Subject: [PATCH 09/13] perf(usage): count fallback input tokens in one pass When a provider sends no usage, estimateInputTokens split the whole serialized request into arrays and filtered them into a second array, only to read the length. A 3 MiB body left tens of MiB of garbage and cost tens of ms per estimate on the stream completion path. Count the same boundaries in one character pass: runs of word chars cut at each lower-to-upper step, one token per other non-space UTF-16 unit, BMP and astral CJK counted separately. Results are unchanged; a parity test checks every UTF-16 code unit and 3000 random texts against the old split implementation. (cherry picked from commit 9679b8272eeb91358ab2711fccf5f5712cb0de7e) --- .../0000-token-estimate-single-pass.md | 1 + open-sse/utils/usageTracking.ts | 64 +++++++--- ...racking-token-estimate-single-pass.test.ts | 116 ++++++++++++++++++ 3 files changed, 167 insertions(+), 14 deletions(-) create mode 100644 changelog.d/maintenance/0000-token-estimate-single-pass.md create mode 100644 tests/unit/usage-tracking-token-estimate-single-pass.test.ts diff --git a/changelog.d/maintenance/0000-token-estimate-single-pass.md b/changelog.d/maintenance/0000-token-estimate-single-pass.md new file mode 100644 index 000000000000..c08e30ead667 --- /dev/null +++ b/changelog.d/maintenance/0000-token-estimate-single-pass.md @@ -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. diff --git a/open-sse/utils/usageTracking.ts b/open-sse/utils/usageTracking.ts index 43cc6093e98d..191a200868e7 100644 --- a/open-sse/utils/usageTracking.ts +++ b/open-sse/utils/usageTracking.ts @@ -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); } /** diff --git a/tests/unit/usage-tracking-token-estimate-single-pass.test.ts b/tests/unit/usage-tracking-token-estimate-single-pass.test.ts new file mode 100644 index 000000000000..e59a6ae682a6 --- /dev/null +++ b/tests/unit/usage-tracking-token-estimate-single-pass.test.ts @@ -0,0 +1,116 @@ +// The fallback input-token estimate runs when a provider sends no usage. It used to split the +// whole serialized request into arrays just to read `.length`. It must now count in one pass, +// with exactly the same numbers as before (CJK, astral CJK, camelCase, punctuation, whitespace). +import test from "node:test"; +import assert from "node:assert/strict"; + +const { estimateInputTokens } = await import("../../open-sse/utils/usageTracking.ts"); + +// Frozen copy of the previous split/filter implementation: the parity oracle. +function referenceEstimate(text: unknown) { + if (!text || typeof text !== "string") return 0; + const cjkMatches = text.match(/[\u3000-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}]/gu); + const cjkCount = cjkMatches ? cjkMatches.length : 0; + const nonCJK = text.replace(/[\u3000-\u9fff\uf900-\ufaff]/g, " "); + const tokens = nonCJK + .split(/(\s+|[^\w\s]|(?<=[a-z])(?=[A-Z]))/) + .filter((t) => t && t.trim().length > 0); + return cjkCount + Math.ceil(tokens.length * 1.3); +} + +const FIXTURES = [ + "", + "hello world", + "camelCaseIdentifier and snake_case_name", + "XMLHttpRequest parseJSON getHTTPResponse", + "a,b;c.d!e?f (g) [h] {i} \"j\" 'k'", + "tabs\tand\nnewlines\r\nand\u00a0nbsp\u2003em\u2028ls\ufeffbom", + "你好,世界。こんにちは 안녕하세요 한글", + "mixed你好World好camelCase世界", + "astral \u{20000}\u{2a6d6}\u{2fa1f} cjk and emoji \u{1f600}\u{1f4a9} end", + "accents café naïve Ünïcödé", + "lone \ud800 high and \udc00 low surrogates", + "\u3000ideographic\u3000space\u3000", + "ABC DEF aBC abC a1B2 _Under_Score", +]; + +function* randomTexts(count: number) { + const alphabet = [ + ..."abcxyzABCXYZ019_", + ..." \t\n,.;:!?()[]{}\"'\\/-+=<>@#$%^&*|~`", + ..."\u3000\u4e00\u9fff\uf900\ufaff\u00e9\u00a0\u2003\ufeff", + "\u{20000}", + "\u{2fa1f}", + "\u{1f600}", + "\ud800", + "\udc00", + ]; + let seed = 123456789; + const next = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff); + for (let i = 0; i < count; i++) { + const length = next() % 60; + let out = ""; + for (let j = 0; j < length; j++) out += alphabet[next() % alphabet.length]; + yield out; + } +} + +// The body is serialized first, so the oracle runs on the same JSON text as production. +function expected(body: Record) { + return referenceEstimate(JSON.stringify(body)); +} + +test("estimateInputTokens keeps the exact previous numbers on fixtures", () => { + for (const text of FIXTURES) { + assert.equal(estimateInputTokens({ a: text }), expected({ a: text }), JSON.stringify(text)); + } + assert.equal(estimateInputTokens(undefined), 0); + assert.equal(estimateInputTokens("text"), 0); +}); + +test("estimateInputTokens keeps the exact previous numbers for every UTF-16 code unit", () => { + for (let code = 0; code <= 0xffff; code++) { + const text = `aB${String.fromCharCode(code)}cD${String.fromCharCode(code)}`; + assert.equal(estimateInputTokens({ a: text }), expected({ a: text }), `U+${code.toString(16)}`); + } +}); + +test("estimateInputTokens keeps the exact previous numbers on 3000 random texts", () => { + for (const text of randomTexts(3000)) { + assert.equal(estimateInputTokens({ a: text }), expected({ a: text }), JSON.stringify(text)); + } +}); + +test("estimateInputTokens counts without split or filter arrays", () => { + const body = { + model: "m", + messages: [{ role: "user", content: "parse the HTTPResponse now, 你好 world ".repeat(2000) }], + tools: [{ type: "function", function: { name: "getThing", parameters: { type: "object" } } }], + }; + const { tools, ...withoutTools } = body; + const want = expected(withoutTools) + Math.ceil(JSON.stringify(tools).length / 6); + + const origSplit = String.prototype.split; + const origFilter = Array.prototype.filter; + let splitCalls = 0; + let filterCalls = 0; + String.prototype.split = function (this: string, ...args: unknown[]) { + splitCalls++; + return Reflect.apply(origSplit, this, args); + } as typeof String.prototype.split; + Array.prototype.filter = function (this: unknown[], ...args: unknown[]) { + filterCalls++; + return Reflect.apply(origFilter, this, args); + } as typeof Array.prototype.filter; + let actual: number; + try { + actual = estimateInputTokens(body); + } finally { + String.prototype.split = origSplit; + Array.prototype.filter = origFilter; + } + + assert.equal(actual, want); + assert.equal(splitCalls, 0, "no String.split on the request text"); + assert.equal(filterCalls, 0, "no Array.filter over a token array"); +}); From 155e58e0ff2543abc4a2715d978c0246ee0bf6c3 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Tue, 10 Nov 2026 17:13:45 +0330 Subject: [PATCH 10/13] docs(changelog): number the fragment (#19713) --- ...body-deadline.md => 19713-keepalive-nonsse-body-deadline.md} | 2 +- ...terminate-flush.md => 19713-sse-coalesce-terminate-flush.md} | 2 +- ...al-budget.md => 19713-stream-readiness-pre-signal-budget.md} | 2 +- ...r.md => 19713-stream-watchdog-cleared-on-transform-error.md} | 2 +- ...t-watcher-inert.md => 19713-stream-content-watcher-inert.md} | 2 +- ...imate-single-pass.md => 19713-token-estimate-single-pass.md} | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) rename changelog.d/fixes/{0000-keepalive-nonsse-body-deadline.md => 19713-keepalive-nonsse-body-deadline.md} (69%) rename changelog.d/fixes/{0000-sse-coalesce-terminate-flush.md => 19713-sse-coalesce-terminate-flush.md} (51%) rename changelog.d/fixes/{0000-stream-readiness-pre-signal-budget.md => 19713-stream-readiness-pre-signal-budget.md} (51%) rename changelog.d/fixes/{0000-stream-watchdog-cleared-on-transform-error.md => 19713-stream-watchdog-cleared-on-transform-error.md} (60%) rename changelog.d/maintenance/{0000-stream-content-watcher-inert.md => 19713-stream-content-watcher-inert.md} (56%) rename changelog.d/maintenance/{0000-token-estimate-single-pass.md => 19713-token-estimate-single-pass.md} (50%) diff --git a/changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md b/changelog.d/fixes/19713-keepalive-nonsse-body-deadline.md similarity index 69% rename from changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md rename to changelog.d/fixes/19713-keepalive-nonsse-body-deadline.md index e64c89207714..dbd31e309f58 100644 --- a/changelog.d/fixes/0000-keepalive-nonsse-body-deadline.md +++ b/changelog.d/fixes/19713-keepalive-nonsse-body-deadline.md @@ -1 +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. +- **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. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/fixes/0000-sse-coalesce-terminate-flush.md b/changelog.d/fixes/19713-sse-coalesce-terminate-flush.md similarity index 51% rename from changelog.d/fixes/0000-sse-coalesce-terminate-flush.md rename to changelog.d/fixes/19713-sse-coalesce-terminate-flush.md index c0dc89f63e98..749ad341e092 100644 --- a/changelog.d/fixes/0000-sse-coalesce-terminate-flush.md +++ b/changelog.d/fixes/19713-sse-coalesce-terminate-flush.md @@ -1 +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. +- **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. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md b/changelog.d/fixes/19713-stream-readiness-pre-signal-budget.md similarity index 51% rename from changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md rename to changelog.d/fixes/19713-stream-readiness-pre-signal-budget.md index a94c3c3da50b..c2ed45608a6f 100644 --- a/changelog.d/fixes/0000-stream-readiness-pre-signal-budget.md +++ b/changelog.d/fixes/19713-stream-readiness-pre-signal-budget.md @@ -1 +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. +- **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. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md b/changelog.d/fixes/19713-stream-watchdog-cleared-on-transform-error.md similarity index 60% rename from changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md rename to changelog.d/fixes/19713-stream-watchdog-cleared-on-transform-error.md index db69076b8e3b..3062bf3ac3d8 100644 --- a/changelog.d/fixes/0000-stream-watchdog-cleared-on-transform-error.md +++ b/changelog.d/fixes/19713-stream-watchdog-cleared-on-transform-error.md @@ -1 +1 @@ -- **fix(sse):** a translated stream that fails inside its transform no longer leaves its idle-timeout timer running until the idle timeout. +- **fix(sse):** a translated stream that fails inside its transform no longer leaves its idle-timeout timer running until the idle timeout. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/maintenance/0000-stream-content-watcher-inert.md b/changelog.d/maintenance/19713-stream-content-watcher-inert.md similarity index 56% rename from changelog.d/maintenance/0000-stream-content-watcher-inert.md rename to changelog.d/maintenance/19713-stream-content-watcher-inert.md index b0b6d4d7d9d0..b16a69dc75fa 100644 --- a/changelog.d/maintenance/0000-stream-content-watcher-inert.md +++ b/changelog.d/maintenance/19713-stream-content-watcher-inert.md @@ -1 +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. +- **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. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) diff --git a/changelog.d/maintenance/0000-token-estimate-single-pass.md b/changelog.d/maintenance/19713-token-estimate-single-pass.md similarity index 50% rename from changelog.d/maintenance/0000-token-estimate-single-pass.md rename to changelog.d/maintenance/19713-token-estimate-single-pass.md index c08e30ead667..18f2eab86099 100644 --- a/changelog.d/maintenance/0000-token-estimate-single-pass.md +++ b/changelog.d/maintenance/19713-token-estimate-single-pass.md @@ -1 +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. +- **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. ([#19713](https://github.com/cheaper-inference/OmniRoute/pull/19713)) From 98b4063e37f37e2ec6c9be6d88733a671a0092e5 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Wed, 11 Nov 2026 09:37:01 +0330 Subject: [PATCH 11/13] refactor(sse): split the token-estimate char classes into helpers The single-pass estimateTokenCount reached cyclomatic complexity over 15 and cognitive complexity over 15, which broke the new-code complexity ratchet. Move the character-class tests into charKind and the astral CJK test into astralCjkAt. The counts are unchanged: the parity tests against the old split/filter implementation pass on every UTF-16 unit and on random texts. --- open-sse/utils/usageTracking.ts | 48 ++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 16 deletions(-) diff --git a/open-sse/utils/usageTracking.ts b/open-sse/utils/usageTracking.ts index 191a200868e7..e64c60fa53af 100644 --- a/open-sse/utils/usageTracking.ts +++ b/open-sse/utils/usageTracking.ts @@ -1022,6 +1022,29 @@ function isSpaceCode(c: number) { ); } +const CHAR_CJK = 0; +const CHAR_SPACE = 1; +const CHAR_LOWER = 2; +const CHAR_UPPER = 3; +const CHAR_WORD = 4; // digit or underscore +const CHAR_OTHER = 5; + +function charKind(c: number) { + if ((c >= 0x3000 && c <= 0x9fff) || (c >= 0xf900 && c <= 0xfaff)) return CHAR_CJK; + if (isSpaceCode(c)) return CHAR_SPACE; + if (c >= 97 && c <= 122) return CHAR_LOWER; + if (c >= 65 && c <= 90) return CHAR_UPPER; + if ((c >= 48 && c <= 57) || c === 95) return CHAR_WORD; + return CHAR_OTHER; +} + +// 1 when the high surrogate at `i` starts an astral CJK code point, else 0. +function astralCjkAt(text: string, i: number, c: number) { + if (c < 0xd800 || c > 0xdbff) return 0; + const cp = text.codePointAt(i)!; + return cp >= 0x20000 && cp <= 0x2fa1f ? 1 : 0; +} + function estimateTokenCount(text: unknown) { if (!text || typeof text !== "string") return 0; @@ -1035,28 +1058,21 @@ function estimateTokenCount(text: unknown) { 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)) { + const kind = charKind(c); + if (kind === CHAR_CJK) { cjkCount++; inWord = false; - } else if (isSpaceCode(c)) { + } else if (kind === CHAR_SPACE) { 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++; - } + } else if (kind === CHAR_OTHER) { + cjkCount += astralCjkAt(text, i, c); tokens++; inWord = false; + } else { + if (!inWord || (prevLower && kind === CHAR_UPPER)) tokens++; + inWord = true; } - prevLower = isLower; + prevLower = kind === CHAR_LOWER; } // Apply sub-word correction: BPE tokenizers often split long words From 45937d8cd82a4ed2bafbcdd4f5b55c16ffaf8584 Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Wed, 18 Nov 2026 00:18:19 +0330 Subject: [PATCH 12/13] refactor(sse): move the transform-error idle-timer guard out of stream.ts to keep it under its frozen size --- open-sse/utils/stream.ts | 18 +++--------------- open-sse/utils/streamFailureBoundary.ts | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts index e4bda14082c8..280626db5d56 100644 --- a/open-sse/utils/stream.ts +++ b/open-sse/utils/stream.ts @@ -74,7 +74,7 @@ import { projectStreamFailureEvent, type StreamFailurePayload, } from "./streamErrorFormat.ts"; -import { createStreamFailureAborter } from "./streamFailureBoundary.ts"; +import { createStreamFailureAborter, clearIdleTimerOnError } from "./streamFailureBoundary.ts"; import { buildStreamFailureSnapshot } from "./streamFailureSnapshot.ts"; import { nativeFinishFailure, readPassthroughChatId } from "./streamPassthroughFinish.ts"; import { createReasoningStreamObserver } from "./responsesReasoningObservation.ts"; @@ -1669,19 +1669,7 @@ 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) { + transform: clearIdleTimerOnError(clearIdleTimer, (chunk, controller) => { if (streamTimedOut) return; const now = Date.now(); timing.markByte(); @@ -2963,7 +2951,7 @@ export function createSSEStream(options: StreamOptions = {}) { deferredCompletionTimer.unref?.(); } } - }, + }), async flush(controller) { flushing = true; diff --git a/open-sse/utils/streamFailureBoundary.ts b/open-sse/utils/streamFailureBoundary.ts index f864170a8f79..592b5b817ca6 100644 --- a/open-sse/utils/streamFailureBoundary.ts +++ b/open-sse/utils/streamFailureBoundary.ts @@ -91,3 +91,22 @@ export function createStreamFailureAborter(context: AborterContext) { } }; } + +/** + * 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. + */ +export function clearIdleTimerOnError( + clearIdleTimer: () => void, + transform: (chunk: Uint8Array, controller: TransformStreamDefaultController) => void +) { + return (chunk: Uint8Array, controller: TransformStreamDefaultController): void => { + try { + transform(chunk, controller); + } catch (error) { + clearIdleTimer(); + throw error; + } + }; +} From a53da31f949a63cf18fb18e7f1719150fd84efbf Mon Sep 17 00:00:00 2001 From: serenity <295272363+serenity-X@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:53:57 +0330 Subject: [PATCH 13/13] fix(usage): count U+3000 as whitespace in the single-pass token estimator isSpaceCode() is documented as the same set as /\s/ but left out U+3000 (IDEOGRAPHIC SPACE). Counts do not change today, because charKind() tests the CJK range first, but a reorder would. Add it and a test that compares the predicate with /\s/ on every UTF-16 code unit. Reported in review by BillyOutlast. --- open-sse/utils/usageEstimation.ts | 3 ++- .../usage-tracking-token-estimate-single-pass.test.ts | 9 +++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/open-sse/utils/usageEstimation.ts b/open-sse/utils/usageEstimation.ts index c30cd0a05ddc..6dfdcb17e0b7 100644 --- a/open-sse/utils/usageEstimation.ts +++ b/open-sse/utils/usageEstimation.ts @@ -2,7 +2,7 @@ const CHARS_PER_TOKEN_SCHEMA = 6; // ~6 chars/token for JSON schemas (more verbose per token) // Same set as the regex \s (and String.trim) in V8. -function isSpaceCode(c: number) { +export function isSpaceCode(c: number) { return ( c === 32 || (c >= 9 && c <= 13) || @@ -13,6 +13,7 @@ function isSpaceCode(c: number) { c === 0x2029 || c === 0x202f || c === 0x205f || + c === 0x3000 || c === 0xfeff ); } diff --git a/tests/unit/usage-tracking-token-estimate-single-pass.test.ts b/tests/unit/usage-tracking-token-estimate-single-pass.test.ts index e59a6ae682a6..063edef70969 100644 --- a/tests/unit/usage-tracking-token-estimate-single-pass.test.ts +++ b/tests/unit/usage-tracking-token-estimate-single-pass.test.ts @@ -114,3 +114,12 @@ test("estimateInputTokens counts without split or filter arrays", () => { assert.equal(splitCalls, 0, "no String.split on the request text"); assert.equal(filterCalls, 0, "no Array.filter over a token array"); }); + +test("isSpaceCode matches /\\s/ on every UTF-16 code unit", async () => { + const { isSpaceCode } = await import("../../open-sse/utils/usageEstimation.ts"); + const wrong: string[] = []; + for (let c = 0; c <= 0xffff; c++) { + if (isSpaceCode(c) !== /\s/.test(String.fromCharCode(c))) wrong.push(c.toString(16)); + } + assert.deepEqual(wrong, []); +});