Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion config/quality/file-size-baseline.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"_comment": "Catraca de tamanho (check-file-size.mjs). frozen so pode encolher; arquivos novos <= cap. --update ratcheta.",
"_rebaseline_2026_06_21_qg9_chatcore_key_health": "QG v2 Fase 9 T5 (#3501), stacked on the service-tier leaf — chatCore.ts 5110->5055 (shrink -55). The `recordKeyHealthStatus` closure (~56 LOC: 401 -> recordKeyFailure + persist; 2xx -> recordKeySuccess + persist-on-recovery; non-401/2xx no-op) moved byte-identically into the new leaf open-sse/handlers/chatCore/keyHealth.ts; the handler keeps a thin binding closure that passes `log`, so the two call sites stay unchanged. The orphaned recordKeyFailure/recordKeySuccess/trackConnectionExtraKeys/KeyHealth imports moved to the leaf (connectionHasExtraKeys stays — still used at the rotation site); updateProviderConnection is imported in both (still used elsewhere in the handler). Covered by tests/unit/chatcore-key-health.test.ts (in-memory apiKeyRotator transitions).",
"_rebaseline_2026_06_21_qg9_chatcore_service_tier": "QG v2 Fase 9 T5 (#3501) — chatCore.ts 5137->5110 (shrink -27). The two inline Codex service-tier resolvers (resolveEffectiveServiceTier / resolveReportedServiceTier, ~36 LOC) were extracted byte-identically into the new pure leaf open-sse/handlers/chatCore/serviceTier.ts; the handler now keeps a `let effectiveServiceTier` + two thin binding closures that pass provider/credentials?.providerSpecificData to the extracted functions, so every call site stays unchanged. The orphaned getCodexRequestDefaults/normalizeCodexServiceTier/CodexServiceTier imports moved to the leaf. Ratcheted the frozen value down to lock the freed budget. Covered by tests/unit/chatcore-service-tier.test.ts.",
"_rebaseline_2026_06_20_reviewprs_mine_r2_filesize": "Reconciliacao file-size pos-lote /review-prs 'apenas minhas' r2: dois frozen cresceram cumulativamente sem bump (cada PR media OK na sua base, mas o crescimento empilhou acima do frozen no tip de merge; o fast-path do release nao roda check:file-size, so release->main). (1) src/shared/constants/pricing.ts 1620->1623 (+3 = linhas de pricing Claude Code (cc) do #4440, sobre o 1620 que o #4447 ja setara para gpt-4.1-mini/nano + o3/o4-mini). (2) open-sse/executors/base.ts 1399->1407 (+8 = handling granular de reasoning_effort para Claude no Copilot do #4443). Ambos dados/wiring coesos nos chokepoints existentes; nao extraiveis. Cobertos por tests/unit (claude-code pricing / base-executor-sanitize-effort + github-claude-reasoning-effort-granular).",
"_rebaseline_2026_06_20_4023_web_cookie_noauth_validation": "PR #4023 (oyi77) own growth: src/lib/providers/validation.ts 4450->4518 (+68 = a new validateWebCookieProvider that probes the provider's /models endpoint — 401/403 => AUTH_007 SESSION_EXPIRED, any other status => valid session, empty cookie => invalid, provider-not-in-registry => unsupported — plus a local STANDARD_USER_AGENT const for the probe). Cohesive validator at the validateProviderApiKey dispatch; not extractable. Covered by tests/unit/provider-validation-web-cookie-auth007.test.ts. Heavily curated on merge — the PR's branch was badly stale-based (squash-base-stale), so its tree was DESTRUCTIVE: providers/index.ts deleted live providers openadapter/dit/tokenrouter (added by #4313) and the executor/base.ts edits reverted release fixes (#4037 duckduckgo host, theoldllm gpt5 models, base.ts fetch-start-timeout). Only the purely-additive validation feature was kept (validation.ts validateWebCookieProvider + errorCodes AUTH_007 + the test). Dropped: 5 malformed new registry entries (used non-RegistryEntry fields defaultModel/auth + referenced non-existent executors -> tsc TS2353), the destructive providers/index.ts + executor reverts, the unrelated pr-*.sh automation scripts, and evals/types.ts (belongs to the deferred evals modularization #4422). Also removed the PR's fragile 'Phase 2' executor probe (ran a live upstream chat during validation + classified any 'auth'-containing error as SESSION_EXPIRED) and rewrote the test to install its fetch mock before module load (the original mocked too late and silently hit live chatgpt.com).",
Expand Down Expand Up @@ -104,7 +105,7 @@
"open-sse/executors/muse-spark-web.ts": 1284,
"open-sse/executors/perplexity-web.ts": 1013,
"open-sse/handlers/audioSpeech.ts": 965,
"open-sse/handlers/chatCore.ts": 5110,
"open-sse/handlers/chatCore.ts": 5055,
"open-sse/handlers/imageGeneration.ts": 3777,
"open-sse/handlers/responseSanitizer.ts": 1103,
"open-sse/handlers/search.ts": 1546,
Expand Down
65 changes: 5 additions & 60 deletions open-sse/handlers/chatCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,8 @@ import {
} from "../services/errorClassifier.ts";
import { updateProviderConnection, getProviderConnectionById } from "@/lib/db/providers";
import { wasRefreshTokenRotated } from "@omniroute/open-sse/services/refreshSerializer.ts";
import {
recordKeyFailure,
recordKeySuccess,
trackConnectionExtraKeys,
connectionHasExtraKeys,
type KeyHealth,
} from "../services/apiKeyRotator.ts";
import { connectionHasExtraKeys } from "../services/apiKeyRotator.ts";
import { recordKeyHealthStatus as recordKeyHealthStatusFor } from "./chatCore/keyHealth.ts";

import {
getCallLogPipelineCaptureStreamChunks,
Expand Down Expand Up @@ -765,62 +760,12 @@ export async function handleChatCore({
}).catch(() => {});
};

// Key-health updater extracted to chatCore/keyHealth.ts (#3501); bind the per-request log once
// and delegate so the existing call sites stay byte-identical.
const recordKeyHealthStatus = (
status: number,
creds: Record<string, unknown> | null | undefined
): void => {
const connId = creds?.connectionId as string | undefined;
if (!connId) return;

const psd = creds.providerSpecificData as Record<string, unknown> | undefined;
const extraKeys = (psd?.extraApiKeys as string[] | undefined) ?? [];
const health = psd?.apiKeyHealth as Record<string, KeyHealth> | undefined;
const currentKeyId = (psd?.selectedKeyId as string | undefined) ?? "primary";

trackConnectionExtraKeys(connId, extraKeys);

if (status === 401) {
const updatedHealth = recordKeyFailure(connId, currentKeyId);
log?.warn?.(
"AUTH",
`401 on connection ${connId.slice(0, 8)} - key marked as failed (failure #${updatedHealth.failures})`
);

// Persist health status to DB on every failure (not just invalid transitions)
// This ensures in-memory state survives process restarts
const prevStatus = health?.[currentKeyId]?.status;
const prevFailures = health?.[currentKeyId]?.failures ?? 0;
if (updatedHealth.status !== prevStatus || updatedHealth.failures !== prevFailures) {
updateProviderConnection(connId, {
providerSpecificData: {
...psd,
apiKeyHealth: { ...health, [currentKeyId]: updatedHealth },
},
}).catch((err: unknown) => {
log?.error?.(
"DB",
`Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}`
);
});
}
} else if (status >= 200 && status < 300) {
const updatedHealth = recordKeySuccess(connId, currentKeyId);
const prevStatus = health?.[currentKeyId]?.status;
if (prevStatus === "warning" || prevStatus === "invalid") {
updateProviderConnection(connId, {
providerSpecificData: {
...psd,
apiKeyHealth: { ...health, [currentKeyId]: updatedHealth },
},
}).catch((err: unknown) => {
log?.error?.(
"DB",
`Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}`
);
});
}
}
};
): void => recordKeyHealthStatusFor(status, creds, log);

const persistCodexQuotaState = async (headers: Record<string, string> | null, status = 0) => {
if (provider !== "codex" || !connectionId || !headers) return;
Expand Down
84 changes: 84 additions & 0 deletions open-sse/handlers/chatCore/keyHealth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* chatCore per-request API-key health updater (Quality Gate v2 / Fase 9 — chatCore god-file
* decomposition, #3501).
*
* Byte-identical extraction of the `recordKeyHealthStatus` closure that lived at the top of
* handleChatCore. Translates an upstream HTTP status into the in-memory key-health state
* (apiKeyRotator) for the connection's currently-selected key, and persists the change to the
* provider connection so it survives process restarts:
* - 401 → record a failure (warning, then invalid at the threshold), always persisted.
* - 2xx → record a success, persisted only when recovering from a warning/invalid state.
* Any other status only refreshes the tracked extra-key set. The handler binds its `log` once and
* delegates here, keeping the existing call sites unchanged.
*/

import {
recordKeyFailure,
recordKeySuccess,
trackConnectionExtraKeys,
type KeyHealth,
} from "../../services/apiKeyRotator.ts";
import { updateProviderConnection } from "@/lib/db/providers";

type KeyHealthLog = {
warn?: (tag: string, message: string) => void;
error?: (tag: string, message: string) => void;
} | null;

export function recordKeyHealthStatus(
status: number,
creds: Record<string, unknown> | null | undefined,
log?: KeyHealthLog
): void {
const connId = creds?.connectionId as string | undefined;
if (!connId) return;

const psd = creds.providerSpecificData as Record<string, unknown> | undefined;
const extraKeys = (psd?.extraApiKeys as string[] | undefined) ?? [];
const health = psd?.apiKeyHealth as Record<string, KeyHealth> | undefined;
const currentKeyId = (psd?.selectedKeyId as string | undefined) ?? "primary";

trackConnectionExtraKeys(connId, extraKeys);

if (status === 401) {
const updatedHealth = recordKeyFailure(connId, currentKeyId);
log?.warn?.(
"AUTH",
`401 on connection ${connId.slice(0, 8)} - key marked as failed (failure #${updatedHealth.failures})`
);

// Persist health status to DB on every failure (not just invalid transitions)
// This ensures in-memory state survives process restarts
const prevStatus = health?.[currentKeyId]?.status;
const prevFailures = health?.[currentKeyId]?.failures ?? 0;
if (updatedHealth.status !== prevStatus || updatedHealth.failures !== prevFailures) {
updateProviderConnection(connId, {
providerSpecificData: {
...psd,
apiKeyHealth: { ...health, [currentKeyId]: updatedHealth },
},
}).catch((err: unknown) => {
log?.error?.(
"DB",
`Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}`
);
});
}
} else if (status >= 200 && status < 300) {
const updatedHealth = recordKeySuccess(connId, currentKeyId);
const prevStatus = health?.[currentKeyId]?.status;
if (prevStatus === "warning" || prevStatus === "invalid") {
updateProviderConnection(connId, {
providerSpecificData: {
...psd,
apiKeyHealth: { ...health, [currentKeyId]: updatedHealth },
},
}).catch((err: unknown) => {
log?.error?.(
"DB",
`Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}`
);
});
}
}
Comment on lines +50 to +83

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation updates the database with the new apiKeyHealth but does not mutate the in-memory creds.providerSpecificData object in-place. This can lead to stale health status reads during retries or subsequent executions within the same request lifecycle if they share the same credentials reference. Mutating psd.apiKeyHealth in-place before calling updateProviderConnection ensures in-memory consistency.

    // Persist health status to DB on every failure (not just invalid transitions)
    // This ensures in-memory state survives process restarts
    const prevStatus = health?.[currentKeyId]?.status;
    const prevFailures = health?.[currentKeyId]?.failures ?? 0;
    if (updatedHealth.status !== prevStatus || updatedHealth.failures !== prevFailures) {
      if (psd) {
        if (!psd.apiKeyHealth) psd.apiKeyHealth = {};
        (psd.apiKeyHealth as Record<string, KeyHealth>)[currentKeyId] = updatedHealth;
      }
      updateProviderConnection(connId, {
        providerSpecificData: {
          ...psd,
        },
      }).catch((err: unknown) => {
        log?.error?.(
          "DB",
          `Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}`
        );
      });
    }
  } else if (status >= 200 && status < 300) {
    const updatedHealth = recordKeySuccess(connId, currentKeyId);
    const prevStatus = health?.[currentKeyId]?.status;
    if (prevStatus === "warning" || prevStatus === "invalid") {
      if (psd) {
        if (!psd.apiKeyHealth) psd.apiKeyHealth = {};
        (psd.apiKeyHealth as Record<string, KeyHealth>)[currentKeyId] = updatedHealth;
      }
      updateProviderConnection(connId, {
        providerSpecificData: {
          ...psd,
        },
      }).catch((err: unknown) => {
        log?.error?.(
          "DB",
          `Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}`
        );
      });
    }
  }

}
70 changes: 70 additions & 0 deletions tests/unit/chatcore-key-health.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// tests/unit/chatcore-key-health.test.ts
// Characterization of recordKeyHealthStatus — the per-request API-key health updater extracted
// from handleChatCore (chatCore god-file decomposition, #3501). Locks the observable in-memory
// transitions driven through apiKeyRotator: 401 → failure (warning, then invalid at the threshold),
// 2xx → success/recovery, selectedKeyId scoping, and the no-op paths (missing connectionId, and
// non-401/non-2xx statuses). The DB persistence side effect (updateProviderConnection) is moved
// byte-identically and is fire-and-forget; these tests assert the synchronous health mutations.
import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import { recordKeyHealthStatus } from "../../open-sse/handlers/chatCore/keyHealth.ts";
import { getAllKeyHealth, removeConnectionHealth } from "../../open-sse/services/apiKeyRotator.ts";

const noopLog = { warn: () => {}, error: () => {} };
const touched: string[] = [];

function creds(connectionId: string, psd: Record<string, unknown> = {}) {
touched.push(connectionId);
return { connectionId, providerSpecificData: psd };
}

afterEach(() => {
for (const c of touched.splice(0)) removeConnectionHealth(c);
});

test("missing connectionId is a no-op (no health entry created)", () => {
const before = Object.keys(getAllKeyHealth()).length;
const r = recordKeyHealthStatus(200, { providerSpecificData: {} }, noopLog);
assert.equal(r, undefined);
assert.equal(Object.keys(getAllKeyHealth()).length, before);
});

test("401 marks the selected key as failed → warning after the first failure", () => {
const conn = "kh-401-warning";
recordKeyHealthStatus(401, creds(conn), noopLog);
const h = getAllKeyHealth()[`${conn}:primary`];
assert.equal(h?.failures, 1);
assert.equal(h?.status, "warning");
});

test("401 reaches invalid at the failure threshold (2 consecutive)", () => {
const conn = "kh-401-invalid";
recordKeyHealthStatus(401, creds(conn), noopLog);
recordKeyHealthStatus(401, creds(conn), noopLog);
const h = getAllKeyHealth()[`${conn}:primary`];
assert.equal(h?.failures, 2);
assert.equal(h?.status, "invalid");
});

test("2xx after a failure resets the key to active with 0 failures", () => {
const conn = "kh-2xx-recover";
recordKeyHealthStatus(401, creds(conn), noopLog);
recordKeyHealthStatus(204, creds(conn), noopLog);
const h = getAllKeyHealth()[`${conn}:primary`];
assert.equal(h?.failures, 0);
assert.equal(h?.status, "active");
});

test("honors selectedKeyId — scopes the update to the active extra key, not primary", () => {
const conn = "kh-selected-key";
recordKeyHealthStatus(401, creds(conn, { selectedKeyId: "extra_1" }), noopLog);
const all = getAllKeyHealth();
assert.equal(all[`${conn}:extra_1`]?.status, "warning");
assert.equal(all[`${conn}:primary`], undefined);
});

test("non-401 / non-2xx status does not touch key health", () => {
const conn = "kh-5xx-noop";
recordKeyHealthStatus(500, creds(conn), noopLog);
assert.equal(getAllKeyHealth()[`${conn}:primary`], undefined);
});