Files
HealthLog/src/lib/ai/__tests__/codex-slug-fallback.test.ts
T
Marc-André BombeckandClaude Opus 4.7 4bba951121 feat(ai): fallback-chain slug discovery with 1h positive cache
Phase C1 (v1.4.15) — slug-drift defence per Marc's hard mandate:
"Die Integration des Slug Drift Risiko darf halt immer überhaupt nicht
sein." ("Slug-drift risk must NEVER happen.")

Background: the ChatGPT-Codex backend rotates its allow-list silently.
v1.4.7..v1.4.13 lost a week to chasing the rotation manually
(`gpt-5-codex` → `gpt-5.3-codex`). A single hard-coded `CODEX_MODEL`
flips invalid the moment upstream rotates it.

Solution — the client now walks an ordered fallback chain on every
fresh request series and caches the first slug that returns 200 +
`response.completed` for 1 hour. Subsequent requests skip the chain
walk entirely on a cache hit.

Spec: extends `docs/codex-protocol-spec.md` with new §7b documenting
the chain semantics, cache TTL, walk triggers (400 + "not supported
when using Codex with a ChatGPT account" / `model_not_found` /
"does not exist" / 404), non-walk responses (5xx, 429, 401-with-
refresh, `invalid_prompt`), and the all-failed structured-503 error
shape. Per Marc's v1.4.6 hard rule ("read source-of-truth before
iterating; no more 6-iteration line-fixes"), the spec was extended
FIRST and the implementation cross-referenced against it.

Implementation:

  - New `src/lib/ai/codex-slug-cache.ts` — process-local positive
    cache. Single-slot Map (per-account scoping is a one-line change
    when v1.4.16 multi-tenant rolls out). 1 h TTL. `getCachedCodexSlug`
    auto-evicts expired entries on read.
  - Rewritten `CodexClient.generateCompletion()` — walks the chain
    `[cached?, ...slugChain]` in order. On 401 → refresh + retry SAME
    slug (auth ≠ slug-state). On 400/404 with rejection body → drop
    cache, walk to next. On 5xx/429 → propagate immediately (walking
    won't help). On all-rejected → throw structured 503 with
    `attempted[]` list, `httpStatus: 503`, message "AI provider
    unreachable — all configured Codex slugs were rejected".
  - `CodexAttemptDiagnostics` exposes `{ attempted, cacheState,
    workingSlug }` for Wide-Event annotations the route can read via
    `client.getLastDiagnostics()`.
  - `CODEX_MODEL_FALLBACK_CHAIN` env override (comma-separated). When
    `CODEX_MODEL` is also set, it folds into chain position 0; the
    default chain (`gpt-5.3-codex` → `gpt-5-codex` → `gpt-5` →
    `gpt-4o`) survives behind it. Stable de-dup.

Tests: +20 across 2 new files.

  `codex-slug-cache.test.ts` (7 tests) — TTL-edge boundaries,
  invalidation, replacement semantics.

  `codex-slug-fallback.test.ts` (13 tests) — cold-cache happy path,
  walk on canonical 400 body, walk on `model_not_found`, walk on 404,
  no-walk on 500/429/401, all-rejected → 503-with-attempted-list,
  cache-hit shortcut, cache invalidation on rejection, isSlugRejection
  body classifier, loadFallbackChain env-pin merge.

The 5 existing `codex-client.test.ts` cases continue to pass without
edit — the new `slugChain` constructor parameter is opt-in and the
single-slug behaviour reduces to chain length 1.

Tests: 1028 → 1048 unit pass (+20). Typecheck clean for AI files.
Lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 21:55:38 +02:00

363 lines
12 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { CodexClient, __test } from "../codex-client";
import {
clearCodexSlugCache,
inspectCodexSlugCache,
setCachedCodexSlug,
CODEX_SLUG_CACHE_TTL_MS,
} from "../codex-slug-cache";
/**
* Phase C1 — slug-drift defence.
*
* Marc, verbatim 2026-05-09: "Die Integration des Slug Drift Risiko
* darf halt immer überhaupt nicht sein."
* ("Slug-drift risk must never happen.")
*
* Pattern from `docs/codex-protocol-spec.md` §7b:
* 1. Walk the fallback chain on each fresh request series.
* 2. Cache the working slug for 1 h.
* 3. On all-failed: throw structured 503 "AI provider unreachable".
*
* These tests stub `fetch` deterministically per-slug and assert:
* - Walk happens on 400 + "not supported when using Codex with a
* ChatGPT account" (the exact body OpenAI returns).
* - Walk happens on 400 + model_not_found.
* - Walk happens on 404.
* - Walk does NOT happen on 5xx, 429, or 401 (auth flow).
* - Cache entry is dropped on the first slug-rejection walk.
* - Cache hit causes the working slug to come first on the next
* call.
* - All-rejected case throws 503.
*/
function sseSuccessResponse(text = '{"ok":true}'): Response {
const encoder = new TextEncoder();
const events = [
`event: response.output_item.done\ndata: ${JSON.stringify({
type: "response.output_item.done",
item: {
type: "message",
role: "assistant",
content: [{ type: "output_text", text }],
},
})}\n\n`,
`event: response.completed\ndata: ${JSON.stringify({
type: "response.completed",
response: { id: "resp1", usage: { total_tokens: 10 } },
})}\n\n`,
];
const stream = new ReadableStream<Uint8Array>({
start(controller) {
for (const ev of events) controller.enqueue(encoder.encode(ev));
controller.close();
},
});
return new Response(stream, {
status: 200,
headers: { "content-type": "text/event-stream" },
});
}
function rejectionResponse(
status: number,
body = '{"detail":"The \'gpt-5\' model is not supported when using Codex with a ChatGPT account."}',
): Response {
// Use a real Response so .text() works, body returned once.
return new Response(body, {
status,
headers: { "content-type": "application/json" },
});
}
const onTokenRefresh = vi
.fn()
.mockResolvedValue({ accessToken: "x", accountId: "acct-test" });
describe("Codex slug fallback chain", () => {
beforeEach(() => {
vi.restoreAllMocks();
clearCodexSlugCache();
});
afterEach(() => {
clearCodexSlugCache();
});
it("first slug succeeds — uses head-of-chain and caches it", async () => {
const mockFetch = vi.fn().mockResolvedValue(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["gpt-5.3-codex", "gpt-5-codex", "gpt-4o"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
expect(mockFetch).toHaveBeenCalledTimes(1);
const sentBody = JSON.parse(mockFetch.mock.calls[0][1].body);
expect(sentBody.model).toBe("gpt-5.3-codex");
const diagnostics = client.getLastDiagnostics();
expect(diagnostics?.attempted).toEqual(["gpt-5.3-codex"]);
expect(diagnostics?.cacheState).toBe("miss");
expect(diagnostics?.workingSlug).toBe("gpt-5.3-codex");
expect(inspectCodexSlugCache()?.slug).toBe("gpt-5.3-codex");
});
it("walks past first slug on 'not supported when using Codex with a ChatGPT account' 400", async () => {
const mockFetch = vi
.fn()
.mockResolvedValueOnce(rejectionResponse(400))
.mockResolvedValueOnce(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["gpt-5", "gpt-5.3-codex", "gpt-4o"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
expect(mockFetch).toHaveBeenCalledTimes(2);
expect(JSON.parse(mockFetch.mock.calls[0][1].body).model).toBe("gpt-5");
expect(JSON.parse(mockFetch.mock.calls[1][1].body).model).toBe(
"gpt-5.3-codex",
);
const diagnostics = client.getLastDiagnostics();
expect(diagnostics?.attempted).toEqual(["gpt-5", "gpt-5.3-codex"]);
expect(diagnostics?.workingSlug).toBe("gpt-5.3-codex");
// The working slug — not the rejected one — is now cached.
expect(inspectCodexSlugCache()?.slug).toBe("gpt-5.3-codex");
});
it("walks past first slug on 400 with model_not_found body", async () => {
const mockFetch = vi
.fn()
.mockResolvedValueOnce(
rejectionResponse(
400,
'{"error":{"code":"model_not_found","message":"unknown slug"}}',
),
)
.mockResolvedValueOnce(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["nonexistent-slug", "gpt-5.3-codex"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
expect(mockFetch).toHaveBeenCalledTimes(2);
expect(client.getLastDiagnostics()?.workingSlug).toBe("gpt-5.3-codex");
});
it("walks past first slug on 404", async () => {
const mockFetch = vi
.fn()
.mockResolvedValueOnce(rejectionResponse(404, "Not found"))
.mockResolvedValueOnce(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["dead-slug", "gpt-5.3-codex"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
expect(mockFetch).toHaveBeenCalledTimes(2);
});
it("does NOT walk on 500 — propagates immediately", async () => {
const mockFetch = vi
.fn()
.mockResolvedValueOnce(rejectionResponse(500, "Internal server error"));
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["gpt-5.3-codex", "gpt-4o"],
});
await expect(
client.generateCompletion({ systemPrompt: "s", userPrompt: "u" }),
).rejects.toThrow("Codex request failed (500)");
expect(mockFetch).toHaveBeenCalledTimes(1); // no walk
});
it("does NOT walk on 429 — propagates immediately", async () => {
const mockFetch = vi
.fn()
.mockResolvedValueOnce(rejectionResponse(429, "Rate limited"));
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["gpt-5.3-codex", "gpt-4o"],
});
await expect(
client.generateCompletion({ systemPrompt: "s", userPrompt: "u" }),
).rejects.toThrow("Codex request failed (429)");
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it("does NOT walk on 401 — refreshes and retries same slug", async () => {
const mockFetch = vi
.fn()
.mockResolvedValueOnce(
new Response("unauthorized", { status: 401 }),
)
.mockResolvedValueOnce(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "expired",
accountId: "acct",
onTokenRefresh: vi
.fn()
.mockResolvedValue({ accessToken: "fresh", accountId: "acct" }),
slugChain: ["gpt-5.3-codex", "gpt-4o"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
// Both calls hit the SAME slug — auth retry didn't walk to gpt-4o.
expect(JSON.parse(mockFetch.mock.calls[0][1].body).model).toBe(
"gpt-5.3-codex",
);
expect(JSON.parse(mockFetch.mock.calls[1][1].body).model).toBe(
"gpt-5.3-codex",
);
expect(client.getLastDiagnostics()?.attempted).toEqual(["gpt-5.3-codex"]);
});
it("all slugs rejected → throws structured 503 with attempted list", async () => {
// mockImplementation returns a fresh Response each call — Response
// bodies can only be read once, so a single shared object would
// throw "body used already" on the second walk-step.
const mockFetch = vi.fn(() => Promise.resolve(rejectionResponse(400)));
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["a", "b", "c"],
});
let caught: unknown;
try {
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
} catch (e) {
caught = e;
}
const err = caught as Error & {
httpStatus?: number;
attempted?: string[];
};
expect(err.message).toMatch(/AI provider unreachable/);
expect(err.httpStatus).toBe(503);
expect(err.attempted).toEqual(["a", "b", "c"]);
expect(mockFetch).toHaveBeenCalledTimes(3);
expect(client.getLastDiagnostics()?.workingSlug).toBeNull();
expect(client.getLastDiagnostics()?.attempted).toEqual(["a", "b", "c"]);
});
it("cache hit — second call goes straight to the cached slug", async () => {
setCachedCodexSlug("gpt-4o");
const mockFetch = vi.fn().mockResolvedValue(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["gpt-5.3-codex", "gpt-5-codex", "gpt-4o"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
expect(mockFetch).toHaveBeenCalledTimes(1);
expect(JSON.parse(mockFetch.mock.calls[0][1].body).model).toBe("gpt-4o");
expect(client.getLastDiagnostics()?.cacheState).toBe("hit");
});
it("cache invalidated when cached slug starts rejecting", async () => {
setCachedCodexSlug("gpt-5-codex");
expect(inspectCodexSlugCache()?.slug).toBe("gpt-5-codex");
const mockFetch = vi
.fn()
.mockResolvedValueOnce(rejectionResponse(400))
.mockResolvedValueOnce(sseSuccessResponse());
vi.stubGlobal("fetch", mockFetch);
const client = new CodexClient({
accessToken: "test",
accountId: "acct",
onTokenRefresh,
slugChain: ["gpt-5.3-codex", "gpt-5-codex"],
});
await client.generateCompletion({ systemPrompt: "s", userPrompt: "u" });
// After walking to "gpt-5.3-codex" (the next entry after the
// cached one), the cache is updated to the new working slug.
expect(inspectCodexSlugCache()?.slug).toBe("gpt-5.3-codex");
});
it("isSlugRejection helper recognises canonical rejection bodies", () => {
const helper = __test.isSlugRejection;
expect(
helper(
400,
'{"detail":"The \'gpt-5\' model is not supported when using Codex with a ChatGPT account."}',
),
).toBe(true);
expect(helper(400, '{"error":{"code":"model_not_found"}}')).toBe(true);
expect(helper(400, "model gpt-5 does not exist")).toBe(true);
expect(helper(404, "anything")).toBe(true);
expect(helper(500, "internal error")).toBe(false);
expect(helper(429, "rate limited")).toBe(false);
expect(helper(400, "unrelated 400")).toBe(false);
});
it("loadFallbackChain folds CODEX_MODEL into position 0", () => {
const orig = process.env.CODEX_MODEL;
process.env.CODEX_MODEL = "custom-pinned-slug";
try {
const chain = __test.loadFallbackChain();
expect(chain[0]).toBe("custom-pinned-slug");
// Defaults still present after position 0.
expect(chain).toContain("gpt-5.3-codex");
// No duplicates.
const seen = new Set(chain);
expect(seen.size).toBe(chain.length);
} finally {
if (orig === undefined) delete process.env.CODEX_MODEL;
else process.env.CODEX_MODEL = orig;
}
});
it("CODEX_SLUG_CACHE_TTL_MS is exactly 1 hour per spec §7b", () => {
expect(CODEX_SLUG_CACHE_TTL_MS).toBe(60 * 60 * 1000);
});
});