Files
OmniRoute/tests/unit/call-log-artifact-worker.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

169 lines
5.5 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-call-log-worker-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const { writeCallArtifactAsync, closeCallLogArtifactWriter, resolveCallLogArtifactWorker } =
await import("../../src/lib/usage/callLogArtifactWriter.ts");
test.after(async () => {
await closeCallLogArtifactWriter();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
function buildArtifact(id: string) {
return {
schemaVersion: 5 as const,
summary: {
id,
timestamp: "2026-08-11T12:34:56.789Z",
method: "POST",
path: "/v1/chat/completions",
status: 200,
model: "test-model",
requestedModel: null,
provider: "test-provider",
account: "test-account",
connectionId: null,
duration: 10,
tokens: {
in: 1,
out: 2,
cacheRead: null,
cacheWrite: null,
reasoning: null,
compressed: null,
},
requestType: "chat",
sourceFormat: "openai",
targetFormat: "openai",
apiKeyId: null,
apiKeyName: null,
comboName: null,
comboStepId: null,
comboExecutionKey: null,
},
requestBody: { worker: true },
responseBody: { content: "written" },
error: null,
};
}
test("worker resolution covers npm, standalone, source, and missing layouts", () => {
const layoutRoot = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-worker-layout-"));
const createWorker = (workerFile: string) => {
fs.mkdirSync(path.dirname(workerFile), { recursive: true });
fs.writeFileSync(workerFile, "");
};
try {
const npmRoot = path.join(layoutRoot, "package", "dist");
const npmWorker = path.join(npmRoot, "src", "lib", "usage", "callLogArtifactWorker.js");
createWorker(npmWorker);
assert.deepEqual(
resolveCallLogArtifactWorker({
moduleDir: path.join(npmRoot, ".next", "server", "chunks"),
cwd: path.join(layoutRoot, "unrelated-caller"),
entryFile: path.join(npmRoot, "server.js"),
fileExists: fs.existsSync,
}),
{ workerFile: npmWorker, execArgv: [] }
);
const standaloneRoot = path.join(layoutRoot, "standalone");
const standaloneWorker = path.join(
standaloneRoot,
"src",
"lib",
"usage",
"callLogArtifactWorker.js"
);
createWorker(standaloneWorker);
assert.deepEqual(
resolveCallLogArtifactWorker({
moduleDir: path.join(standaloneRoot, ".next", "server", "chunks"),
cwd: standaloneRoot,
entryFile: null,
fileExists: fs.existsSync,
}),
{ workerFile: standaloneWorker, execArgv: [] }
);
const sourceDir = path.join(layoutRoot, "source", "src", "lib", "usage");
const sourceWorker = path.join(sourceDir, "callLogArtifactWorker.ts");
createWorker(sourceWorker);
assert.deepEqual(
resolveCallLogArtifactWorker({
moduleDir: sourceDir,
cwd: path.join(layoutRoot, "unrelated-source-caller"),
entryFile: null,
fileExists: fs.existsSync,
}),
{ workerFile: sourceWorker, execArgv: ["--import", "tsx/esm"] }
);
const missingRoot = path.join(layoutRoot, "missing");
assert.deepEqual(
resolveCallLogArtifactWorker({
moduleDir: path.join(missingRoot, ".next", "server", "chunks"),
cwd: path.join(layoutRoot, "unrelated-missing-caller"),
entryFile: path.join(missingRoot, "server.js"),
fileExists: fs.existsSync,
}),
{
workerFile: path.join(missingRoot, "src", "lib", "usage", "callLogArtifactWorker.js"),
execArgv: [],
}
);
} finally {
fs.rmSync(layoutRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
const resolved = resolveCallLogArtifactWorker();
assert.equal(fs.existsSync(resolved.workerFile), true);
assert.equal(path.basename(resolved.workerFile), "callLogArtifactWorker.ts");
assert.deepEqual(resolved.execArgv, ["--import", "tsx/esm"]);
const source = fs.readFileSync("src/lib/usage/callLogArtifactWriter.ts", "utf8");
assert.doesNotMatch(source, /firstAncestorWith|MAX_WALK_UP|runtimeAnchors/);
assert.doesNotMatch(source, /new Worker\(/);
assert.match(source, /Reflect\.construct\(Worker/);
});
test("async worker writes call-log artifact and returns matching metadata", async () => {
const artifact = buildArtifact("worker-write-1");
const result = await writeCallArtifactAsync(artifact);
assert.ok(result);
const artifactPath = path.join(TEST_DATA_DIR, "call_logs", result.relPath);
const serialized = fs.readFileSync(artifactPath, "utf8");
assert.equal(result.sizeBytes, Buffer.byteLength(serialized));
assert.match(result.sha256, /^[0-9a-f]{8}$/);
assert.deepEqual(JSON.parse(serialized), artifact);
});
test("bounded queue fails open and rate-limits saturation warnings", async () => {
const originalWarn = console.warn;
let warningCount = 0;
console.warn = () => {
warningCount++;
};
try {
const writes = Array.from({ length: 131 }, (_, index) =>
writeCallArtifactAsync(buildArtifact(`worker-overflow-${index}`))
);
assert.equal(warningCount, 1);
await closeCallLogArtifactWriter(0);
const results = await Promise.all(writes);
assert.ok(results.every((result) => result === null));
} finally {
console.warn = originalWarn;
}
});