Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(fallback): reset model-failure windows between tests and thread an injectable now (#856)

OhOkThisIsFine1fea8d5f4af7
diff --git a/server/src/__tests__/lib/fallback-loop-model-bench.test.ts b/server/src/__tests__/lib/fallback-loop-model-bench.test.ts
index eaf90ffa..a98323db 100644
--- a/server/src/__tests__/lib/fallback-loop-model-bench.test.ts
+++ b/server/src/__tests__/lib/fallback-loop-model-bench.test.ts
@@ -19,6 +19,8 @@ import {
recordUpstreamSuccess,
MODEL_FAILURE_COOLDOWN_MS,
MODEL_FAILURE_THRESHOLD,
+ MODEL_FAILURE_WINDOW_MS,
+ resetModelFailureWindows,
} from '../../lib/fallback-loop.js';
import {
getActiveCooldownsForKeys,
@@ -61,9 +63,9 @@ function routeFor(model: { id: number; model_id: string }, keyId: number): Route
// assertions below able to tell the two apart.
const upstream500 = () => Object.assign(new Error('Groq API error 500: upstream'), { status: 500 });
-function failOnce(model: { id: number; model_id: string }, keyId: number) {
+function failOnce(model: { id: number; model_id: string }, keyId: number, now?: number) {
// Fresh state per call: each failure stands for a separate request.
- recordRetryableFailure(routeFor(model, keyId), upstream500(), newFallbackState());
+ recordRetryableFailure(routeFor(model, keyId), upstream500(), newFallbackState(), now);
}
function cooldownFor(model: { id: number; model_id: string }, keyId: number) {
@@ -89,6 +91,9 @@ beforeAll(() => {
beforeEach(() => {
getDb().prepare('DELETE FROM rate_limit_cooldowns').run();
+ // The failure windows are module state and outlive the DB wipe above, so a
+ // case would otherwise start partway to the threshold.
+ resetModelFailureWindows();
});
describe('model-level failure benching covers every key of the model', () => {
@@ -123,4 +128,30 @@ describe('model-level failure benching covers every key of the model', () => {
expect(benchedA).toBeDefined();
expect(benchedA!.remainingMs).toBeLessThan(MODEL_FAILURE_COOLDOWN_MS / 2);
});
+
+ // The window is a SLIDING one, which is only observable if the clock can be
+ // moved. Without an injectable `now` this case would have to sleep for 15
+ // real minutes, so the behaviour was never pinned.
+ it('does not trip when the failures are spread beyond the sliding window', () => {
+ const t0 = Date.now();
+ failOnce(modelA, keyA, t0);
+ failOnce(modelA, keyA, t0 + MODEL_FAILURE_WINDOW_MS + 1);
+ failOnce(modelA, keyA, t0 + 2 * (MODEL_FAILURE_WINDOW_MS + 1));
+
+ // Three failures, but never three inside one window: no model-wide bench.
+ const benched = cooldownFor(modelA, keyB);
+ expect(benched).toBeUndefined();
+ });
+
+ it('trips when the same three failures fall inside one window', () => {
+ const t0 = Date.now();
+ failOnce(modelA, keyA, t0);
+ failOnce(modelA, keyA, t0 + 1000);
+ failOnce(modelA, keyA, t0 + 2000);
+
+ // keyB never failed, but the model-wide bench covers it.
+ const benched = cooldownFor(modelA, keyB);
+ expect(benched).toBeDefined();
+ expect(benched!.remainingMs).toBeGreaterThan(MODEL_FAILURE_COOLDOWN_MS / 2);
+ });
});
diff --git a/server/src/lib/fallback-loop.ts b/server/src/lib/fallback-loop.ts
index 6920e6f8..ece1273d 100644
--- a/server/src/lib/fallback-loop.ts
+++ b/server/src/lib/fallback-loop.ts
@@ -72,7 +72,7 @@ export const FALLBACK_MAX_RETRIES = 20;
// key simply re-trips the streak). Client-cancels never reach
// recordRetryableFailure (the loop returns on isClientAbortError before this
// bookkeeping), so they don't count.
-const MODEL_FAILURE_WINDOW_MS = 15 * 60 * 1000; // sliding window: 15 min
+export const MODEL_FAILURE_WINDOW_MS = 15 * 60 * 1000; // sliding window: 15 min
export const MODEL_FAILURE_THRESHOLD = 3; // failures within window
export const MODEL_FAILURE_COOLDOWN_MS = 10 * 60 * 1000; // bench duration: 10 min
const modelFailureTimestamps = new Map<number, number[]>(); // model_db_id → times
@@ -81,8 +81,7 @@ const modelFailureTimestamps = new Map<number, number[]>(); // model_db_id → t
* holds ≥ MODEL_FAILURE_THRESHOLD failures, bench the model on EVERY key that
* can route to it so the model sinks out of routing until upstream heals, then
* reset the counter (one bench per streak). */
-function noteModelFailure(route: RouteResult): void {
- const now = Date.now();
+function noteModelFailure(route: RouteResult, now: number): void {
const window = (modelFailureTimestamps.get(route.modelDbId) ?? [])
.filter(t => now - t < MODEL_FAILURE_WINDOW_MS);
window.push(now);
@@ -235,6 +234,14 @@ export function resetEmptyCompletionStreaks(): void {
emptyCompletionStreaks.clear();
}
+/** Drop every model's sliding failure window. Module state outlives a test
+ * case, so without this a case inherits the previous one's failure counts and
+ * trips the threshold early — clearing `rate_limit_cooldowns` alone does not
+ * reach it. */
+export function resetModelFailureWindows(): void {
+ modelFailureTimestamps.clear();
+}
+
// Advance (or break) the streak for this failure and report whether the
// skipBench exemption still holds. Called exactly once per retryable failure,
// from recordRetryableFailure; the loop reuses its returned decision for the
@@ -282,7 +289,7 @@ function consumeSkipBenchExemption(route: RouteResult, err: any): boolean {
*
* Callers add the just-failed key to skipKeys via this function (do not pre-add).
*/
-export function recordRetryableFailure(route: RouteResult, err: any, state: FallbackState): boolean {
+export function recordRetryableFailure(route: RouteResult, err: any, state: FallbackState, now: number = Date.now()): boolean {
// `skipModelForRequest: true` = the failure is MODEL behavior, not key
// state (ignored response_format, JSON truncated at max_tokens): a sibling
// key would reproduce it exactly, so rule out the whole model for this
@@ -315,7 +322,7 @@ export function recordRetryableFailure(route: RouteResult, err: any, state: Fall
setCooldown(route.platform, route.modelId, route.keyId, decision.durationMs, decision.source);
// Model-level failure benching: a model failing across keys (or repeatedly on
// one key) must sink out of routing instead of being re-picked every request.
- noteModelFailure(route);
+ noteModelFailure(route, now);
// Model-level penalty only when no sibling key can still serve (#454).
if (!hasOtherUsableKey(route.modelDbId, route.keyId, state.skipKeys)) {
// Hard limit signals (429/402) carry the heavier demotion; ordinary