Files
OmniRoute/tests/unit/9147-catalog-eventloop-yield.test.ts
Diego Rodrigues de Sa e Souza d032431a5f test(catalog): stop the yield guard from dying on production's build budget (#13906)
tests/unit/9147-catalog-eventloop-yield.test.ts exists to prove the /v1/models
builder yields to the event loop while assembling a catalog-scale dataset. It
asserts res.status === 200 first, and only then the two checks that carry the
invariant: the max event-loop gap and the traversal to the last seeded model.

The case did not set CATALOG_BUILD_TIMEOUT_MS, so it inherited production's 8s
cold-path budget. When the seeded build overruns that on a loaded runner,
getUnifiedModelsResponse answers 503 catalog_build_timeout and the status check
fails BEFORE either real assertion runs — the guard goes silently dead exactly
when the machine is under the load that would make a pin most visible. CI hit
it at 8350ms, right at the bound.

Measured on the release tip, pristine file, 3 runs at load ~21: 2 pass with max
gaps of 247ms and 180ms, 1 fails with 503 !== 200 — roughly a 1-in-3 flake, and
the flake has nothing to do with yielding.

Pinning a 120s budget lets the invariant be evaluated. The 800ms gap bound is
untouched, and with the budget pinned the builder measures 261ms (idle) to
790ms (loaded) against it — still failing a true pin, which is seconds.
Build-latency budgeting is a separate concern from this case.

Refs #12732
2026-09-17 10:46:17 -03:00

114 lines
4.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-9147-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "catalog-9147-test-secret";
// This case measures whether the builder YIELDS, not how fast it finishes. The
// production cold-path budget (CATALOG_BUILD_TIMEOUT_MS, 8s) is not the subject:
// when the seeded catalog-scale build overruns it, getUnifiedModelsResponse
// answers 503 `catalog_build_timeout` and the two assertions that actually guard
// the invariant — the max event-loop gap and the traversal to the last seeded
// model — are never reached, because the status check precedes them. That is how
// this guard went silently dead on loaded runners (CI observed 8350ms, right at
// the bound). Pin a budget far above any healthy build so the yield invariant is
// evaluated; build-latency budgeting is a separate concern from this test.
process.env.CATALOG_BUILD_TIMEOUT_MS = "120000";
const core = await import("../../src/lib/db/core.ts");
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const v1ModelsCatalog = await import("../../src/app/api/v1/models/catalog.ts");
const CONNECTION_COUNT = 60;
const MODELS_PER_CONNECTION = 12; // ~720 synced models total
async function resetStorage() {
core.resetDbInstance();
apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
v1ModelsCatalog.__resetCatalogBuilderRunsForTest();
}
async function seedCatalogScaleDataset() {
const db = core.getDbInstance();
const now = new Date().toISOString();
const insertConn = db.prepare(
`INSERT INTO provider_connections (id, provider, auth_type, name, priority, is_active, api_key, created_at, updated_at)
VALUES (?, 'openai-compatible', 'apikey', ?, ?, 1, ?, ?, ?)`
);
const insertModels = db.prepare(
`INSERT INTO key_value (namespace, key, value) VALUES ('syncedAvailableModels', ?, ?)`
);
const seedTx = db.transaction(() => {
for (let i = 0; i < CONNECTION_COUNT; i++) {
const id = `probe-conn-${i}`;
insertConn.run(id, `probe-connection-${i}`, i, `sk-probe-${i}`, now, now);
const models = Array.from({ length: MODELS_PER_CONNECTION }, (_, m) => ({
id: `probe-model-${i}-${m}`,
name: `Probe Model ${i}-${m}`,
contextLength: 128000,
}));
insertModels.run(`openai-compatible:${id}`, JSON.stringify(models));
}
});
seedTx();
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
test("#9147 — catalog build at catalog-scale must not pin the event loop for a long stretch", async (t) => {
await seedCatalogScaleDataset();
const req = new Request("http://localhost/v1/models");
let settled = false;
const buildPromise = v1ModelsCatalog.getUnifiedModelsResponse(req).then((res) => {
settled = true;
return res;
});
let lastTick = performance.now();
let maxGapMs = 0;
let ticks = 0;
while (!settled) {
await new Promise((resolve) => setTimeout(resolve, 0));
const now = performance.now();
maxGapMs = Math.max(maxGapMs, now - lastTick);
lastTick = now;
ticks++;
if (ticks > 20000) break;
}
const res = await buildPromise;
assert.equal(res.status, 200);
t.diagnostic(
`maximum event-loop gap: ${maxGapMs.toFixed(1)}ms across ${ticks} interleaved ticks`
);
// 2026-08-30: 400 → 800. With the catalog at 352 providers the hosted shards measure
// 410633ms gaps (runs 33325191658, 33327592128, 33328119934); 800ms still fails a
// true pin (seconds) — re-tighten with the v4.0 catalog modularization.
// 150ms is tight on GitHub-hosted unit shards (`--test-concurrency=4`):
// sibling tests share the event loop, so a healthy yielding builder still
// records 200260ms gaps. 400ms still fails a true pin (seconds) while
// absorbing shard contention. Observed CI: 252.5ms on run 32494847431.
assert.ok(
maxGapMs < 800,
`event loop was blocked for ${maxGapMs.toFixed(1)}ms in a single stretch while building the ` +
`catalog for ${CONNECTION_COUNT} connections / ${CONNECTION_COUNT * MODELS_PER_CONNECTION} models ` +
`(${ticks} interleaved ticks observed) — the builder is not yielding to the event loop`
);
const body = (await res.json()) as { data?: Array<{ root?: string }> };
assert.ok(
body.data?.some((model) => model.root === "probe-model-59-11"),
"the responsiveness probe must still traverse and return the last seeded catalog model"
);
});