mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-09-14 02:42:24 +03:00
* test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966) Two shards on release/v3.8.51 went red in one day with the same signature — "ENOTEMPTY, Directory not empty: /tmp/omniroute-<test>-XXXXXX" — from combo-same-provider-cascade (Unit Tests fast-path 4/4, on a PR that touches only .github/) and auth-policy-embeddings-webfetch-7785 (the 20k-test TIA step). Both pass alone and on re-run: the cleanup races something still writing into the directory (SQLite WAL/-shm checkpoint, a worker, the backup) and under a loaded hosted runner the window opens. 1154 test files do their own cleanup with fs.rmSync(dir, { recursive: true, force: true }); 57 already asked for retries. One-shot codemod (scripts/ad-hoc/codemod-rm-maxretries.mjs, kept for the record): every rm / rmSync / rmdirSync option object with `recursive: true` and no `maxRetries` gains `maxRetries: 5, retryDelay: 100` — Node itself then retries ENOTEMPTY/EBUSY/EPERM for up to ~0.5 s before giving up. 2243 call sites in 1292 files under tests/, the shared tests/_setup/isolateDataDir.ts exit hook included. Only the option object changes: no call site, assertion or import is touched. Validation: prettier and ESLint (with the frozen suppressions) clean on all 1292 files; a random 20-file sample runs green (quota-redis-store hangs identically on the untouched tree — it needs a Redis on localhost, an environment matter). The four unit shards on this PR are the full run. * fix(quality): let check-forgotten-sibling-tests read a 1,000-file diff The gate shells out to `git diff` through execFileSync with Node's default 1 MB maxBuffer; the 1,292-file codemod in this PR is the first diff large enough to overflow it, and the gate died with `spawnSync git ENOBUFS` before comparing anything. 64 MB is far above any real PR and costs nothing when unused.
156 lines
6.6 KiB
TypeScript
156 lines
6.6 KiB
TypeScript
/**
|
|
* tests/unit/catalog-order-contract.test.ts
|
|
*
|
|
* Provider-grouped ordering contract for the unified model catalog.
|
|
*
|
|
* Red-first: proves the current tree publishes fragmented provider blocks.
|
|
* Uses the same DB module set and reset pattern as models-catalog-route.test.ts.
|
|
* /api/models, quota-short-circuit, and inbound-alias cases are split into
|
|
* separate files to avoid extra module imports that break the sql.js lifecycle.
|
|
*/
|
|
|
|
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-catalog-order-"));
|
|
process.env.DATA_DIR = TEST_DATA_DIR;
|
|
process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "catalog-order-secret";
|
|
|
|
const core = await import("../../src/lib/db/core.ts");
|
|
const providersDb = await import("../../src/lib/db/providers.ts");
|
|
const modelsDb = await import("../../src/lib/db/models.ts");
|
|
const combosDb = await import("../../src/lib/db/combos.ts");
|
|
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
|
|
const v1ModelsCatalog = await import("../../src/app/api/v1/models/catalog.ts");
|
|
|
|
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();
|
|
}
|
|
|
|
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 });
|
|
});
|
|
|
|
async function seedConnection(provider: string, overrides: Record<string, unknown> = {}) {
|
|
return providersDb.createProviderConnection({
|
|
provider,
|
|
authType: (overrides.authType as string) || "apikey",
|
|
name: `${provider}-test-${Math.random().toString(16).slice(2, 8)}`,
|
|
apiKey: (overrides.apiKey as string) || "sk-test",
|
|
accessToken: overrides.accessToken as string | undefined,
|
|
isActive: true,
|
|
testStatus: "active",
|
|
providerSpecificData: {},
|
|
}) as Promise<{ id: string }>;
|
|
}
|
|
|
|
function countProviderBlocks(ownedBySequence: string[]): number {
|
|
const blocks: string[] = [];
|
|
for (const ownedBy of ownedBySequence) {
|
|
if (blocks.length === 0 || blocks[blocks.length - 1] !== ownedBy) {
|
|
blocks.push(ownedBy);
|
|
}
|
|
}
|
|
return blocks.length;
|
|
}
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Exact provider-grouped order: blocks === distinct owned_by
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
test("catalog /v1/models: exact provider-grouped order (blocks === distinct owned_by)", async () => {
|
|
// Seed 3 providers with synced models to guarantee fragmentation if unsorted.
|
|
// The static registry also emits models for active providers, so the catalog
|
|
// will contain rows from openai, anthropic, and opencode from multiple loops.
|
|
const conn1 = await seedConnection("openai");
|
|
const conn2 = await seedConnection("anthropic");
|
|
const conn3 = await seedConnection("opencode");
|
|
|
|
await modelsDb.replaceSyncedAvailableModelsForConnection("openai", (conn1 as { id: string }).id, [
|
|
{ id: "gpt-4", name: "GPT-4" },
|
|
{ id: "gpt-3.5-turbo", name: "GPT-3.5 Turbo" },
|
|
]);
|
|
await modelsDb.replaceSyncedAvailableModelsForConnection(
|
|
"anthropic",
|
|
(conn2 as { id: string }).id,
|
|
[{ id: "claude-3-opus", name: "Claude 3 Opus" }]
|
|
);
|
|
await modelsDb.replaceSyncedAvailableModelsForConnection(
|
|
"opencode",
|
|
(conn3 as { id: string }).id,
|
|
[
|
|
{ id: "kimi-k2", name: "Kimi K2" },
|
|
{ id: "glm-4", name: "GLM-4" },
|
|
]
|
|
);
|
|
|
|
const response = await v1ModelsCatalog.getUnifiedModelsResponse(
|
|
new Request("http://localhost/v1/models?configuredOnly=true")
|
|
);
|
|
assert.equal(response.status, 200);
|
|
const body = (await response.json()) as { data: Array<{ owned_by: string }> };
|
|
|
|
// Guarantee rows from all 3 seeded providers are present
|
|
const ownedByValues = body.data.map((m) => m.owned_by);
|
|
const distinctOwnedBy = new Set(ownedByValues);
|
|
assert.ok(distinctOwnedBy.has("openai"), "openai rows present");
|
|
assert.ok(distinctOwnedBy.has("anthropic"), "anthropic rows present");
|
|
assert.ok(distinctOwnedBy.has("opencode"), "opencode rows present");
|
|
|
|
// Exact invariant: each provider appears in exactly one contiguous block
|
|
const blockCount = countProviderBlocks(ownedByValues);
|
|
assert.equal(
|
|
blockCount,
|
|
distinctOwnedBy.size,
|
|
`Fragmented: ${blockCount} blocks for ${distinctOwnedBy.size} distinct providers. ` +
|
|
`Sequence: ${ownedByValues.join(", ")}`
|
|
);
|
|
});
|
|
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
// Combo block pinned first
|
|
// ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
test("catalog /v1/models: combo block appears first", async () => {
|
|
const conn = await seedConnection("openai");
|
|
await modelsDb.replaceSyncedAvailableModelsForConnection("openai", (conn as { id: string }).id, [
|
|
{ id: "gpt-4", name: "GPT-4" },
|
|
]);
|
|
await combosDb.createCombo({
|
|
name: "test-combo",
|
|
modelIds: ["openai/gpt-4"],
|
|
strategy: "fallback",
|
|
isActive: true,
|
|
});
|
|
|
|
const response = await v1ModelsCatalog.getUnifiedModelsResponse(
|
|
new Request("http://localhost/v1/models?configuredOnly=true")
|
|
);
|
|
const body = (await response.json()) as { data: Array<{ owned_by: string }> };
|
|
|
|
const hasCombo = body.data.some((m) => m.owned_by === "combo");
|
|
const hasNonCombo = body.data.some((m) => m.owned_by !== "combo");
|
|
assert.ok(hasCombo, "combo rows present");
|
|
assert.ok(hasNonCombo, "non-combo rows present");
|
|
|
|
const firstNonComboIndex = body.data.findIndex((m) => m.owned_by !== "combo");
|
|
const lastComboIndex = body.data.map((m) => m.owned_by).lastIndexOf("combo");
|
|
assert.ok(
|
|
lastComboIndex < firstNonComboIndex,
|
|
`Combo block not first: last combo at ${lastComboIndex}, first non-combo at ${firstNonComboIndex}`
|
|
);
|
|
});
|