Files
OmniRoute/tests/unit/combos-quota-protected.test.ts
Diego Rodrigues de Sa e Souza 3d4f3e4960 test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966) (#11968)
* 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.
2026-08-29 01:17:40 -03:00

204 lines
6.7 KiB
TypeScript

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-combo-quota-protected-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const combosDb = await import("../../src/lib/db/combos.ts");
const comboRoute = await import("../../src/app/api/combos/[id]/route.ts");
async function resetStorage() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
function makePutRequest(id: string, body: Record<string, unknown>) {
return new Request(`http://localhost/api/combos/${id}`, {
method: "PUT",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
}
function makeDeleteRequest(id: string) {
return new Request(`http://localhost/api/combos/${id}`, {
method: "DELETE",
});
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
// ---- quota-protected combos ----
test("DELETE /api/combos/[id] returns 409 for a qtSd/* combo and does NOT delete it", async () => {
const combo = await combosDb.createCombo({
name: "qtSd/groupdemo/openai/gpt-4o",
strategy: "priority",
models: [{ provider: "openai", model: "gpt-4o" }],
isHidden: true,
});
const response = await comboRoute.DELETE(makeDeleteRequest(combo.id), {
params: Promise.resolve({ id: combo.id }),
});
assert.equal(response.status, 409, "DELETE quota combo should return 409");
const body = (await response.json()) as any;
assert.ok(
body.error?.message?.includes("Quota Share"),
`Error message should mention Quota Share; got: ${JSON.stringify(body)}`
);
// Verify the combo was NOT deleted
const still = await combosDb.getComboById(combo.id);
assert.ok(still, "Quota combo must still exist after rejected DELETE");
});
test("PUT /api/combos/[id] returns 409 for a qtSd/* combo and does NOT mutate it", async () => {
const combo = await combosDb.createCombo({
name: "qtSd/groupdemo/openai/gpt-4o",
strategy: "priority",
models: [{ provider: "openai", model: "gpt-4o" }],
isHidden: true,
});
const response = await comboRoute.PUT(
makePutRequest(combo.id, { name: "qtSd/groupdemo/openai/gpt-4o", strategy: "random" }),
{ params: Promise.resolve({ id: combo.id }) }
);
assert.equal(response.status, 409, "PUT quota combo should return 409");
const body = (await response.json()) as any;
assert.ok(
body.error?.message?.includes("Quota Share"),
`Error message should mention Quota Share; got: ${JSON.stringify(body)}`
);
// Verify the combo was NOT mutated
const unchanged = await combosDb.getComboById(combo.id);
assert.equal(
unchanged?.strategy,
"priority",
"Strategy must remain unchanged after rejected PUT"
);
});
// ---- non-quota combos still work ----
test("DELETE /api/combos/[id] succeeds for a regular (non-quota) combo", async () => {
const combo = await combosDb.createCombo({
name: "regular-combo",
strategy: "priority",
models: [{ provider: "openai", model: "gpt-4o" }],
});
const response = await comboRoute.DELETE(makeDeleteRequest(combo.id), {
params: Promise.resolve({ id: combo.id }),
});
assert.equal(response.status, 200, "DELETE regular combo should return 200");
const body = (await response.json()) as any;
assert.equal(body.success, true);
// Verify the combo was actually deleted
const gone = await combosDb.getComboById(combo.id);
assert.equal(gone, null, "Regular combo must be gone after DELETE");
});
test("PUT merged state rejects partial updates that leave protected priority refs in flatten mode", async () => {
const combo = await combosDb.createCombo({
name: "protected-ref-update",
strategy: "priority",
models: [{ kind: "combo-ref", comboName: "child", fallbackOnlyOnQuotaExhaustion: true }],
config: { nestedComboMode: "execute" },
});
for (const update of [
{ config: { nestedComboMode: "flatten" } },
{
models: [{ kind: "combo-ref", comboName: "child", fallbackOnlyOnQuotaExhaustion: true }],
config: {},
},
{ strategy: "priority", config: {} },
]) {
const response = await comboRoute.PUT(makePutRequest(combo.id, update), {
params: Promise.resolve({ id: combo.id }),
});
assert.equal(response.status, 400);
}
});
test("PUT merged state accepts dormant weighted protected refs", async () => {
const combo = await combosDb.createCombo({
name: "dormant-protected-ref-update",
strategy: "priority",
models: [{ kind: "combo-ref", comboName: "child", fallbackOnlyOnQuotaExhaustion: true }],
config: { nestedComboMode: "execute" },
});
const response = await comboRoute.PUT(
makePutRequest(combo.id, { strategy: "weighted", config: { nestedComboMode: "flatten" } }),
{ params: Promise.resolve({ id: combo.id }) }
);
assert.equal(response.status, 200);
});
test("PUT /api/combos/[id] succeeds for a regular (non-quota) combo", async () => {
const combo = await combosDb.createCombo({
name: "regular-editable-combo",
strategy: "priority",
models: [{ provider: "openai", model: "gpt-4o" }],
});
const response = await comboRoute.PUT(
makePutRequest(combo.id, {
name: "regular-editable-combo",
strategy: "round-robin",
models: [{ providerId: "openai", model: "gpt-4o" }],
}),
{ params: Promise.resolve({ id: combo.id }) }
);
assert.equal(response.status, 200, "PUT regular combo should return 200");
const body = (await response.json()) as any;
assert.equal(body.strategy, "round-robin", "Strategy should be updated for regular combo");
});
// ---- 404 still works when combo doesn't exist ----
test("DELETE /api/combos/[id] returns 404 when combo does not exist", async () => {
const response = await comboRoute.DELETE(makeDeleteRequest("nonexistent-id"), {
params: Promise.resolve({ id: "nonexistent-id" }),
});
assert.equal(response.status, 404, "DELETE nonexistent combo should return 404, not 409");
});
// ---- structural assertion: page filters isHidden ----
test("combos page source filters isHidden from rendered list", async () => {
const pageSource = fs.readFileSync(
new URL("../../src/app/(dashboard)/dashboard/combos/page.tsx", import.meta.url).pathname,
"utf8"
);
assert.ok(
pageSource.includes("!c.isHidden") || pageSource.includes("!combo.isHidden"),
"Combos page must filter out isHidden combos from the rendered list"
);
});