Files
OmniRoute/tests/integration/sse-correctness.test.ts
Xiangzhe c51d74213e fix(ci): drain the electron packaging regression, the models-catalog e2e assertion and 10 integration reds
Electron Package Smoke — a packaging defect that had been hidden behind another
packaging defect for nine days. Once the loginHeaderCapture fix let the main process
start, the server underneath died on 'Cannot find module next': resources/app/server.js
shipped without resources/app/node_modules.

electron-builder discards the ROOT node_modules in code, not by configuration —
app-builder-lib/out/util/filter.js:42 has a hard-coded `if (relative === "node_modules")
return false` that runs before any filter pattern. The second extraResources entry
pointing INTO ../.build/electron-standalone/node_modules is what sidesteps it, because
those relative paths are never equal to "node_modules". #10325 removed that entry as an
apparent duplicate and flipped the test to assert "exactly once", freezing the
regression as if it were the contract. Restored, and the unit guard now pins both
entries — proven by mutation: reverting package.json to the post-#10325 shape fails the
guard 3/4, restoring it passes 4/4.

group-b-quota-plans-config — the assertion was impossible to satisfy on ANY route, and
the page was never broken. layout.tsx hands the whole message catalogue to
NextIntlClientProvider, React serialises that prop into the RSC payload, and en.json
carries "Internal Server Error" twice, so page.content() always contains it: probing
/dashboard, /dashboard/costs, /dashboard/settings and /login showed the string present
with every page rendering fine, and a pageerror probe on the failing run captured zero
client exceptions. This is the same trap that killed the sibling not.toContain("500")
in fc77100c3f ("raw HTML is unreliable") — that one was removed, this one was kept.
Now asserts on rendered text, which still catches a real error boundary. The pageerror
capture stays: the CI failure carried no stack trace, which is why it was misread twice.

Integration — 10 of the 14 shard-2 reds, all sibling-test gaps behind security fixes:
monitoring health now takes a Request and requires management auth (GHSA-mvf8-qc78-5mxm);
the OAuth import routes moved to requireManagementAuth (GHSA-mg76) — the test accepts
both guard shapes and gained a stronger anchor that every exported handler awaits a
guard on its own request, mutation-verified; skill tool names are derived from
encodeSkillToolName() and the fake upstream now returns the encoded name so
decodeSkillToolName() is exercised too; previous_response_id now fails closed (#10262);
proxy_logs persist as an async batch (#11182) so the test flushes first;
providerQuotaOverrides joined GET /api/resilience (#9871); the reasoning fixture used a
model that stopped being thinking-incompatible, replaced and pinned with a premise
assert so it cannot rot silently again.

A vacuous assert.ok(true, "all 10 streams completed without hanging") was replaced with
real anchors — content must arrive on every stream and the active Timeout count must not
grow.

Four are deliberately left red rather than aligned, each now tracked: #11551 (the
/v1/models after() wiring is dead — the route passes a third argument to a two-parameter
function and catalogCache never imports after, so the #8728 contract is unimplemented),
#11552 (~27% of requests emit an extra discarded upstream call; the delivered
distribution is exactly 0.70, so weighted routing is correct and the waste is the real
finding), the fixed-account combo pin (aligning it would destroy the per-step attribution
the test exists for), and the web_search fallback already tracked as #11524.

Package Artifact — the provenance stamp I added last round used git rev-parse HEAD, which
under pull_request is the ephemeral merge commit and therefore never an ancestor of the
release branch. Now takes the PR head sha.

Refs #10692
2026-08-25 16:46:23 -03:00

147 lines
5.7 KiB
TypeScript

/**
* SSE-correctness integration tests (Task 11, Fase 8 B).
*
* Drives the real createSSEStream pipeline through a controllable fake upstream.
* Run with: node --import tsx/esm --test --test-concurrency=1 tests/integration/sse-correctness.test.ts
*
* Notes on observed createSSEStream behavior (calibrated invariants):
* - The TransformStream processes SSE events and emits translated chunks to the client.
* - [DONE] is consumed by the pipeline: it closes the upstream readable and the
* TransformStream flushes + terminates, but does NOT re-emit "data: [DONE]" to the output.
* The output stream closes naturally (reader.read() returns {done:true}).
* - Upstream errors propagate as TransformStream errors (reader.read() rejects).
* - Cancel propagates via ReadableStream cancel callback (pipeThrough wires it).
*/
import test from "node:test";
import assert from "node:assert/strict";
import { fakeUpstreamStream } from "../helpers/fakeUpstreamStream.ts";
import { createSSEStream } from "../../open-sse/utils/stream.ts";
import { FORMATS } from "../../open-sse/translator/formats.ts";
/** Drain a ReadableStream to a string, with optional timeout guard. */
async function drain(out: ReadableStream, timeoutMs = 5000): Promise<string> {
const r = out.getReader();
const dec = new TextDecoder();
let s = "";
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error(`drain timeout after ${timeoutMs}ms`)), timeoutMs)
);
const read = async () => {
for (;;) {
const { done, value } = await r.read();
if (done) break;
s += dec.decode(value);
}
return s;
};
return Promise.race([read(), timeout]);
}
function makeStream(extraOpts: Record<string, unknown> = {}) {
const up = fakeUpstreamStream();
const transform = createSSEStream({
sourceFormat: FORMATS.OPENAI,
targetFormat: FORMATS.OPENAI,
model: "m",
...extraOpts,
});
const out = up.stream.pipeThrough(transform as TransformStream);
return { up, out };
}
test("1. stream closes after [DONE] (no hang)", async () => {
const { up, out } = makeStream();
up.push('data: {"choices":[{"delta":{"content":"hi"}}]}\n\n');
up.push("data: [DONE]\n\n");
up.close();
// drain() must return within the timeout — proves the stream closed
const text = await drain(out);
assert.ok(text.includes("hi"), `expected 'hi' in output: ${JSON.stringify(text)}`);
});
test("2. client cancel propagates to upstream (abort propagation)", async () => {
const { up, out } = makeStream();
let cancelled = false;
up.onCancel(() => {
cancelled = true;
});
const r = out.getReader();
await r.cancel("client-abort");
// Allow microtask queue to flush
await new Promise((res) => setTimeout(res, 50));
assert.equal(cancelled, true, "upstream cancel callback must have been called");
});
test("3. no leaked idle timers across N sequential streams", async () => {
// createSSEStream installs a setInterval idle watchdog per stream.
// If cleanup (clearInterval) does not run on stream close, timers accumulate.
// Each stream carries a real content delta: a stream whose upstream forwards
// no valuable chunk is rejected by the empty-content guard
// (open-sse/utils/streamEmptyChoices.ts) and would never reach the flush path
// whose cleanup this test is about.
//
// Drained inline, without drain()'s timeout guard: that guard leaves its own
// uncleared setTimeout behind and would drown out the very signal measured here.
const activeTimers = () =>
process.getActiveResourcesInfo().filter((resource) => resource === "Timeout").length;
const timersBefore = activeTimers();
const N = 10;
for (let i = 0; i < N; i++) {
const { up, out } = makeStream();
up.push(`data: {"choices":[{"delta":{"content":"chunk-${i}"}}]}\n\n`);
up.push("data: [DONE]\n\n");
up.close();
const reader = out.getReader();
const decoder = new TextDecoder();
let text = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
text += decoder.decode(value);
}
// Positive anchor: the stream really ran and really closed.
assert.ok(text.includes(`chunk-${i}`), `stream ${i} lost its content: ${JSON.stringify(text)}`);
}
// The watchdog of every closed stream must have been cleared. One slot of slack
// absorbs unrelated runtime timers, but N leaked watchdogs cannot hide in it.
const timersAfter = activeTimers();
assert.ok(
timersAfter <= timersBefore + 1,
`idle watchdog timers leaked across ${N} streams: ${timersBefore} active before, ${timersAfter} after`
);
});
test("4. final snapshot does not duplicate tail text", async () => {
// Regression guard for the SSE snapshot bug (CLAUDE.md §2, Fase 8 B spec §4.2):
// the text 'Hello' should appear EXACTLY ONCE in the output, not duplicated.
const { up, out } = makeStream();
up.push('data: {"choices":[{"delta":{"content":"Hello"}}]}\n\n');
up.push("data: [DONE]\n\n");
up.close();
const text = await drain(out);
const occurrences = (text.match(/Hello/g) ?? []).length;
assert.equal(
occurrences,
1,
`'Hello' appeared ${occurrences} times; expected 1. Output: ${JSON.stringify(text)}`
);
});
test("5. upstream error propagates and closes stream (no hang, Hard Rule #6)", async () => {
// If upstream errors, the TransformStream must propagate the error so the
// consumer sees a rejection — never silently swallow and never hang.
const { up, out } = makeStream();
up.error(new Error("upstream boom"));
await assert.rejects(
async () => {
await drain(out, 2000);
},
undefined, // any error is acceptable — just must not hang
"upstream error must propagate as a rejection to the consumer"
);
});