Skip to content

Commit d8ba00f

Browse files
authored
fix(openai): clear ChatGPT SSE fallback per session (#117123)
* fix(openai): clear ChatGPT SSE fallback per session * test(openai): prove ChatGPT fallback cleanup * docs(openai): clarify fallback cleanup ownership
1 parent f8aa383 commit d8ba00f

2 files changed

Lines changed: 171 additions & 48 deletions

File tree

‎packages/ai/src/providers/openai-chatgpt-responses.cache.test.ts‎

Lines changed: 167 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import { once } from "node:events";
2+
import { createServer } from "node:http";
23
import type { AddressInfo } from "node:net";
34
import { zstdDecompressSync } from "node:zlib";
45
import { afterEach, describe, expect, it, vi } from "vitest";
56
import { WebSocket, WebSocketServer } from "ws";
67
import { configureAiTransportHost } from "../host.js";
8+
import { cleanupSessionResources } from "../session-resources.js";
79
import type { Context, Model } from "../types.js";
810
import {
911
closeOpenAICodexWebSocketSessions,
@@ -499,58 +501,175 @@ describe("ChatGPT Responses cached transport", () => {
499501
}
500502
});
501503

502-
it("lazily builds authenticated SSE requests after session-scoped websocket fallback", async () => {
503-
let websocketAttempts = 0;
504-
505-
class FailingWebSocket {
506-
constructor() {
507-
websocketAttempts += 1;
508-
throw new Error("websocket connect failed");
509-
}
510-
511-
send(): void {}
512-
close(): void {}
513-
addEventListener(): void {}
514-
removeEventListener(): void {}
515-
}
516-
517-
const captured: Array<{ headers: Headers; body: BodyInit | null | undefined }> = [];
518-
const fetchMock = vi.fn(async (_input: unknown, init?: RequestInit) => {
519-
captured.push({ headers: new Headers(init?.headers), body: init?.body });
520-
return new Response(
521-
`data: ${JSON.stringify(completion(`resp_sse_${captured.length}`))}\n\n`,
522-
{
523-
status: 200,
524-
headers: { "content-type": "text/event-stream" },
525-
},
526-
);
504+
it("keeps SSE fallback sticky only for the active session lifecycle", async () => {
505+
const websocketUpgrades: Array<{
506+
method: string;
507+
path: string;
508+
authorization?: string;
509+
accountId?: string;
510+
openaiBeta?: string;
511+
sessionId?: string;
512+
requestId?: string;
513+
}> = [];
514+
const sseRequests: Array<{
515+
method: string;
516+
path: string;
517+
authorization?: string;
518+
accountId?: string;
519+
sessionId?: string;
520+
requestId?: string;
521+
accept?: string;
522+
contentType?: string;
523+
contentEncoding?: string;
524+
body: Buffer;
525+
}> = [];
526+
const server = createServer((request, response) => {
527+
const chunks: Buffer[] = [];
528+
request.on("data", (chunk: Buffer) => chunks.push(Buffer.from(chunk)));
529+
request.on("end", () => {
530+
const requestNumber = sseRequests.length + 1;
531+
sseRequests.push({
532+
method: request.method ?? "",
533+
path: request.url ?? "",
534+
authorization: request.headers.authorization,
535+
accountId: request.headers["chatgpt-account-id"] as string | undefined,
536+
sessionId: request.headers.session_id as string | undefined,
537+
requestId: request.headers["x-client-request-id"] as string | undefined,
538+
accept: request.headers.accept,
539+
contentType: request.headers["content-type"],
540+
contentEncoding: request.headers["content-encoding"],
541+
body: Buffer.concat(chunks),
542+
});
543+
response.writeHead(200, {
544+
connection: "close",
545+
"content-type": "text/event-stream",
546+
});
547+
response.end(`data: ${JSON.stringify(completion(`resp_sse_${requestNumber}`))}\n\n`);
548+
});
527549
});
528-
vi.stubGlobal("WebSocket", FailingWebSocket);
529-
vi.stubGlobal("fetch", fetchMock);
550+
server.on("upgrade", (request, socket) => {
551+
websocketUpgrades.push({
552+
method: request.method ?? "",
553+
path: request.url ?? "",
554+
authorization: request.headers.authorization,
555+
accountId: request.headers["chatgpt-account-id"] as string | undefined,
556+
openaiBeta: request.headers["openai-beta"] as string | undefined,
557+
sessionId: request.headers.session_id as string | undefined,
558+
requestId: request.headers["x-client-request-id"] as string | undefined,
559+
});
560+
socket.end("HTTP/1.1 426 Upgrade Required\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
561+
});
562+
server.listen(0, "127.0.0.1");
563+
await once(server, "listening");
564+
const port = (server.address() as AddressInfo).port;
565+
const loopbackModel = {
566+
...model,
567+
baseUrl: `http://127.0.0.1:${port}/backend-api`,
568+
} satisfies Model<"openai-chatgpt-responses">;
569+
vi.stubGlobal("WebSocket", WebSocket);
530570
const apiKey = createJwt();
531-
const options = { apiKey, sessionId: "sticky-sse-fallback" };
571+
const runSession = (sessionId: string) =>
572+
streamOpenAICodexResponses(loopbackModel, context, { apiKey, sessionId }).result();
532573

533-
const first = await streamOpenAICodexResponses(model, context, options).result();
534-
const second = await streamOpenAICodexResponses(model, context, options).result();
574+
try {
575+
const firstStickyResult = await runSession("sticky-sse-fallback");
576+
expect(firstStickyResult).toMatchObject({
577+
stopReason: "stop",
578+
diagnostics: [
579+
{
580+
type: "provider_transport_failure",
581+
error: { message: "Unexpected server response: 426" },
582+
details: {
583+
configuredTransport: "auto",
584+
fallbackTransport: "sse",
585+
eventsEmitted: false,
586+
phase: "before_message_stream_start",
587+
},
588+
},
589+
],
590+
});
591+
const stickyResult = await runSession("sticky-sse-fallback");
592+
expect(stickyResult.stopReason).toBe("stop");
593+
expect(stickyResult.diagnostics).toBeUndefined();
594+
expect((await runSession("unrelated-sse-fallback")).stopReason).toBe("stop");
595+
expect(websocketUpgrades).toHaveLength(2);
596+
597+
cleanupSessionResources("sticky-sse-fallback");
598+
expect((await runSession("unrelated-sse-fallback")).stopReason).toBe("stop");
599+
expect(websocketUpgrades).toHaveLength(2);
600+
expect((await runSession("sticky-sse-fallback")).stopReason).toBe("stop");
601+
expect((await runSession("sticky-sse-fallback")).stopReason).toBe("stop");
602+
expect(websocketUpgrades).toHaveLength(3);
603+
604+
cleanupSessionResources();
605+
expect((await runSession("sticky-sse-fallback")).stopReason).toBe("stop");
606+
expect((await runSession("unrelated-sse-fallback")).stopReason).toBe("stop");
607+
expect(websocketUpgrades).toHaveLength(5);
608+
expect(sseRequests).toHaveLength(8);
609+
610+
expect(websocketUpgrades.map((request) => request.sessionId)).toEqual([
611+
"sticky-sse-fallback",
612+
"unrelated-sse-fallback",
613+
"sticky-sse-fallback",
614+
"sticky-sse-fallback",
615+
"unrelated-sse-fallback",
616+
]);
617+
expect(sseRequests.map((request) => request.sessionId)).toEqual([
618+
"sticky-sse-fallback",
619+
"sticky-sse-fallback",
620+
"unrelated-sse-fallback",
621+
"unrelated-sse-fallback",
622+
"sticky-sse-fallback",
623+
"sticky-sse-fallback",
624+
"sticky-sse-fallback",
625+
"unrelated-sse-fallback",
626+
]);
627+
628+
for (const request of websocketUpgrades) {
629+
expect(request).toMatchObject({
630+
method: "GET",
631+
path: "/backend-api/codex/responses",
632+
authorization: `Bearer ${apiKey}`,
633+
accountId: "acct-1",
634+
openaiBeta: "responses_websockets=2026-02-06",
635+
requestId: request.sessionId,
636+
});
637+
}
638+
for (const request of sseRequests) {
639+
expect(request).toMatchObject({
640+
method: "POST",
641+
path: "/backend-api/codex/responses",
642+
authorization: `Bearer ${apiKey}`,
643+
accountId: "acct-1",
644+
requestId: request.sessionId,
645+
accept: "text/event-stream",
646+
contentType: "application/json",
647+
contentEncoding: "zstd",
648+
});
649+
expect(request.body).not.toHaveLength(0);
650+
const payload = JSON.parse(zstdDecompressSync(request.body).toString("utf8"));
651+
expect(payload).toMatchObject({
652+
model: model.id,
653+
prompt_cache_key: request.sessionId,
654+
});
655+
}
535656

536-
expect(first.stopReason).toBe("stop");
537-
expect(second.stopReason).toBe("stop");
538-
expect(websocketAttempts).toBe(1);
539-
expect(fetchMock).toHaveBeenCalledTimes(2);
540-
541-
for (const { headers, body } of captured) {
542-
expect(headers.get("authorization")).toBe(`Bearer ${apiKey}`);
543-
expect(headers.get("chatgpt-account-id")).toBe("acct-1");
544-
expect(headers.get("session_id")).toBe("sticky-sse-fallback");
545-
expect(headers.get("accept")).toBe("text/event-stream");
546-
expect(headers.get("content-type")).toBe("application/json");
547-
expect(headers.get("content-encoding")).toBe("zstd");
548-
expect(body).toBeInstanceOf(Uint8Array);
549-
expect(
550-
JSON.parse(Buffer.from(zstdDecompressSync(body as Uint8Array)).toString("utf8")),
551-
).toMatchObject({
552-
model: model.id,
553-
prompt_cache_key: "sticky-sse-fallback",
657+
console.info(
658+
"[behavior-evidence] chatgpt-sse-fallback-cleanup",
659+
JSON.stringify({
660+
transport: "real ws client and loopback HTTP server",
661+
rejectedUpgradeStatus: 426,
662+
websocketSessionIds: websocketUpgrades.map((request) => request.sessionId),
663+
sseSessionIds: sseRequests.map((request) => request.sessionId),
664+
firstFallbackError: firstStickyResult.diagnostics?.[0]?.error?.message,
665+
scopedCleanupRetriedOnly: "sticky-sse-fallback",
666+
globalCleanupRetried: ["sticky-sse-fallback", "unrelated-sse-fallback"],
667+
}),
668+
);
669+
} finally {
670+
cleanupSessionResources();
671+
await new Promise<void>((resolve, reject) => {
672+
server.close((error) => (error ? reject(error) : resolve()));
554673
});
555674
}
556675
});

‎packages/ai/src/providers/openai-chatgpt-responses.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,7 +920,10 @@ export function closeOpenAICodexWebSocketSessions(sessionId?: string): void {
920920
}
921921
closeWebSocketSilently(entry.socket, 1000, "debug_close");
922922
};
923+
// Sticky SSE fallback follows the provider session-resource lifecycle;
924+
// otherwise reused session ids stay degraded and the set grows indefinitely.
923925
if (sessionId) {
926+
websocketSseFallbackSessions.delete(sessionId);
924927
const entry = websocketSessionCache.get(sessionId);
925928
if (entry) {
926929
closeEntry(entry);
@@ -932,6 +935,7 @@ export function closeOpenAICodexWebSocketSessions(sessionId?: string): void {
932935
closeEntry(entry);
933936
}
934937
websocketSessionCache.clear();
938+
websocketSseFallbackSessions.clear();
935939
}
936940

937941
registerSessionResourceCleanup(closeOpenAICodexWebSocketSessions);

0 commit comments

Comments
 (0)