mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-09-13 18:32:12 +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.
143 lines
4.8 KiB
TypeScript
143 lines
4.8 KiB
TypeScript
/**
|
|
* TDD regression for port of https://github.com/decolua/9router/pull/2044:
|
|
* "Fix usage logging dedupe and reduce stats churn"
|
|
*
|
|
* Asserts:
|
|
* 1. Inserting the same request usage entry twice results in exactly ONE row
|
|
* in usage_history (dedup guard).
|
|
* 2. emitUsageRecorded fires only when a row is actually inserted — not on
|
|
* a duplicate.
|
|
*/
|
|
|
|
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";
|
|
|
|
// Isolate the DB from other tests and from the real data dir.
|
|
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-usage-dedup-"));
|
|
process.env.DATA_DIR = TEST_DATA_DIR;
|
|
|
|
// Dynamic imports so DATA_DIR is set before any module initialises the DB.
|
|
const { resetDbInstance, getDbInstance } = await import("../../../src/lib/db/core.ts");
|
|
const { onUsageRecorded } = await import("../../../src/lib/usage/usageEvents.ts");
|
|
const { saveRequestUsage } = await import("../../../src/lib/usage/usageHistory.ts");
|
|
|
|
// Cleanup: close DB handle and temp directory so the test runner doesn't hang.
|
|
test.after(() => {
|
|
resetDbInstance();
|
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
|
|
});
|
|
|
|
// ── helpers ──────────────────────────────────────────────────────────────────
|
|
|
|
let entrySeq = 0;
|
|
|
|
function makeEntry(overrides: Record<string, unknown> = {}) {
|
|
entrySeq++;
|
|
const timestamp = new Date(Date.now() + entrySeq).toISOString();
|
|
|
|
return {
|
|
provider: "test-provider",
|
|
model: "test-model",
|
|
connectionId: `conn-abc123-${entrySeq}`,
|
|
apiKeyId: null,
|
|
apiKeyName: null,
|
|
tokens: { input_tokens: 10, output_tokens: 20 },
|
|
status: "success",
|
|
success: true,
|
|
latencyMs: 100,
|
|
timeToFirstTokenMs: 50,
|
|
errorCode: null,
|
|
comboStrategy: null,
|
|
endpoint: "/v1/chat/completions",
|
|
timestamp,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function countRows(db: ReturnType<typeof getDbInstance>): number {
|
|
const row = db.prepare("SELECT COUNT(*) AS cnt FROM usage_history").get() as { cnt: number };
|
|
return row.cnt;
|
|
}
|
|
|
|
// ── tests ─────────────────────────────────────────────────────────────────────
|
|
|
|
test("saveRequestUsage: first insert creates exactly one row", async () => {
|
|
const db = getDbInstance();
|
|
const before = countRows(db);
|
|
const entry = makeEntry({ timestamp: new Date().toISOString() });
|
|
|
|
await saveRequestUsage(entry);
|
|
|
|
assert.equal(countRows(db), before + 1, "Expected exactly one new row after first insert");
|
|
});
|
|
|
|
test("saveRequestUsage: duplicate entry (same key fields) inserts only ONE row", async () => {
|
|
const db = getDbInstance();
|
|
const ts = new Date().toISOString();
|
|
const entry = makeEntry({ timestamp: ts });
|
|
|
|
await saveRequestUsage(entry);
|
|
const afterFirst = countRows(db);
|
|
|
|
// Insert identical entry a second time — should be a no-op.
|
|
await saveRequestUsage(entry);
|
|
const afterSecond = countRows(db);
|
|
|
|
assert.equal(
|
|
afterSecond,
|
|
afterFirst,
|
|
"Duplicate insert must not create a second row (dedup guard)"
|
|
);
|
|
});
|
|
|
|
test("saveRequestUsage: emitUsageRecorded fires on real insert but NOT on duplicate", async () => {
|
|
const ts = new Date().toISOString();
|
|
const entry = makeEntry({ timestamp: ts });
|
|
|
|
let fireCount = 0;
|
|
const unsub = onUsageRecorded(() => {
|
|
fireCount++;
|
|
});
|
|
|
|
try {
|
|
await saveRequestUsage(entry); // real insert → should fire
|
|
await saveRequestUsage(entry); // duplicate → must NOT fire
|
|
|
|
assert.equal(fireCount, 1, "emitUsageRecorded should fire exactly once (not on duplicate)");
|
|
} finally {
|
|
unsub();
|
|
}
|
|
});
|
|
|
|
test("saveRequestUsage: two entries with different timestamps are both inserted", async () => {
|
|
const db = getDbInstance();
|
|
const before = countRows(db);
|
|
|
|
await saveRequestUsage(makeEntry({ timestamp: new Date(Date.now() - 5000).toISOString() }));
|
|
await saveRequestUsage(makeEntry({ timestamp: new Date(Date.now() - 4000).toISOString() }));
|
|
|
|
assert.equal(
|
|
countRows(db),
|
|
before + 2,
|
|
"Two distinct entries (different timestamps) should both be inserted"
|
|
);
|
|
});
|
|
|
|
test("saveRequestUsage: two entries with different providers are both inserted", async () => {
|
|
const db = getDbInstance();
|
|
const before = countRows(db);
|
|
const ts = new Date().toISOString();
|
|
|
|
await saveRequestUsage(makeEntry({ timestamp: ts, provider: "provider-A" }));
|
|
await saveRequestUsage(makeEntry({ timestamp: ts, provider: "provider-B" }));
|
|
|
|
assert.equal(
|
|
countRows(db),
|
|
before + 2,
|
|
"Two entries with different providers should both be inserted"
|
|
);
|
|
});
|