// X's job count on disk (jobs/xJobCap.ts): one bucket for the machine (review // 2 M1), kept across a restart, failing closed, and rebuilt from the job // records when its file is gone (ruling R-c). // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xJobCap.test.ts import { after, test } from "node:test"; import assert from "node:assert/strict"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { X_RECORDS_KEPT_FILE, rebuildXJobStarts, recordXJobStart, xJobCapStatus, xJobStartsFile } from "./xJobCap"; import { ulid } from "./ulid"; const TMP = mkdtempSync(path.join(tmpdir(), "x-job-cap-")); after(() => rmSync(TMP, { recursive: true, force: true })); const corpus = (name: string) => { const transcriptsDir = path.join(TMP, name); return { transcriptsDir, jobsDir: path.join(transcriptsDir, ".jobs") }; }; const T0 = Date.parse("2026-11-18T12:00:00.000Z"); const MIN = 60_000; const HOUR = 60 * MIN; const fileOf = (paths: ReturnType) => JSON.parse(readFileSync(xJobStartsFile(paths), "utf8")); const meta = (paths: ReturnType, m: Record, at: number = T0) => { mkdirSync(paths.jobsDir, { recursive: true }); const id = (m.id as string | undefined) ?? ulid(at); writeFileSync(path.join(paths.jobsDir, `${id}.meta.json`), JSON.stringify({ id, queuedAt: at, status: "done", ...m })); return id; }; // The pruner's word that it keeps every X record that may still count, since `since` (review 3 M3). const keptSince = (paths: ReturnType, since: number) => { mkdirSync(paths.jobsDir, { recursive: true }); writeFileSync(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), JSON.stringify({ version: 1, since })); }; test("M1: ONE count for the machine — checked and recorded in one step, kept across a restart", async () => { const paths = corpus("disk"); for (let i = 0; i < 6; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); const refused = await recordXJobStart(paths, T0 + 6 * MIN); assert.equal(refused.ok, false); assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 6 X jobs started in the last 60 minutes/); // A refused start records nothing; the file is one list, with no login in it. assert.deepEqual(Object.keys(fileOf(paths)).sort(), ["starts", "version"]); assert.equal(fileOf(paths).version, 2); assert.equal(fileOf(paths).starts.length, 6); // "Restart": nothing is in memory; the file is the count. const again = await xJobCapStatus(paths, T0 + 13 * MIN); assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 6, 6, T0 + 60 * MIN]); // A start recorded with the clock set back is recorded at the clock's time // (review 3 S4); the later start on record still counts, and is kept. const p2 = corpus("disk-back"); await recordXJobStart(p2, T0); await recordXJobStart(p2, T0 - 600 * MIN); assert.deepEqual(fileOf(p2).starts, [T0, T0 - 600 * MIN]); // Starts older than a day are dropped when the next is recorded. await recordXJobStart(p2, T0 + 25 * HOUR); assert.deepEqual(fileOf(p2).starts, [T0 + 25 * HOUR]); // Two at once: both recorded, neither lost. const p3 = corpus("disk-race"); await Promise.all(Array.from({ length: 6 }, (_, i) => recordXJobStart(p3, T0 + i))); assert.equal(fileOf(p3).starts.length, 6); assert.equal((await recordXJobStart(p3, T0 + 20)).ok, false); }); test("M1: a count of the first shape (one list per login key) is the SUM of its lists, and is rewritten as one", async () => { const paths = corpus("migrate"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); // 4 starts under the profile, 2 under a browser spec: the same machine's six. const logins = { profile: Array.from({ length: 4 }, (_, i) => T0 + i * MIN), "browser:firefox": Array.from({ length: 2 }, (_, i) => T0 + (10 + i) * MIN), }; writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 1, logins })); const status = await xJobCapStatus(paths, T0 + 20 * MIN); assert.deepEqual([status.ok, status.lastHour], [false, 6]); assert.equal(fileOf(paths).version, 2); assert.equal(fileOf(paths).starts.length, 6); assert.equal((await recordXJobStart(paths, T0 + 21 * MIN)).ok, false); }); test("a count that cannot be read fails closed: no X job starts, and nothing is written over it", async () => { for (const [name, text] of [ ["garbage", "{not json"], ["shape", '{"version":2,"starts":{}}'], ["v1-shape", '{"version":1,"logins":[]}'], ["version", '{"version":3,"starts":[]}'], ["times", '{"version":2,"starts":["soon"]}'], ] as const) { const paths = corpus(`closed-${name}`); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); writeFileSync(xJobStartsFile(paths), text); const status = await xJobCapStatus(paths, T0); assert.equal(status.ok, false, name); assert.equal(status.unreadable, true); assert.match(status.sentence ?? "", /^X's job count cannot be read \(.*job-starts\.json\): no X job starts while it is unreadable/); assert.equal((await recordXJobStart(paths, T0)).ok, false); assert.equal(readFileSync(xJobStartsFile(paths), "utf8"), text); } }); test("R-c: a fresh corpus where no X job ever ran starts at zero", async () => { const paths = corpus("fresh"); assert.deepEqual(await xJobCapStatus(paths, T0), { ok: true, lastHour: 0, lastDay: 0, perHour: 6, perDay: 150 }); // Records of other queues only: still zero. const p2 = corpus("fresh-other-queues"); meta(p2, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); assert.equal((await xJobCapStatus(p2, T0)).lastDay, 0); }); test("R-c: deleting job-starts.json does not reset the count — the last day is rebuilt from the job records", async () => { const paths = corpus("rebuild"); keptSince(paths, T0 - 25 * HOUR); // Jobs that ran through the funnel: each meta says the starts it was counted for. for (let i = 0; i < 10; i++) meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - i * MIN, xStarts: [T0 - i * MIN] }, T0 - i * MIN); // An X run's channels: one start each. meta(paths, { kind: "x-run", queueKey: "platform:twitter", startedAt: T0 - 30 * MIN, xStarts: [T0 - 30 * MIN, T0 - 25 * MIN] }, T0 - 30 * MIN); // An X job that counted nothing (deferred, or a media-only capture): []. meta(paths, { kind: "capture-posts", queueKey: "platform:twitter", startedAt: T0 - 2 * MIN, xStarts: [] }, T0 - 2 * MIN); // Older than a day: not counted. meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - 25 * HOUR, xStarts: [T0 - 25 * HOUR] }, T0 - 25 * HOUR); // Twelve in the hour: the cap is reached although the file is gone. const status = await xJobCapStatus(paths, T0 + MIN); assert.deepEqual([status.ok, status.lastHour, status.lastDay], [false, 12, 12]); assert.match(status.sentence ?? "", /^X's job cap is reached on this machine/); // …and the rebuilt count is written. assert.equal(fileOf(paths).starts.length, 12); // Deleted again, then a start asked for: rebuilt under the lock, then refused. rmSync(xJobStartsFile(paths)); assert.equal((await recordXJobStart(paths, T0 + MIN)).ok, false); assert.equal(fileOf(paths).starts.length, 12); }); test("R-c: a record from before `xStarts` counts once at its start when its kind counts", async () => { const paths = corpus("legacy"); keptSince(paths, T0 - 25 * HOUR); meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - MIN }, T0 - MIN); meta(paths, { kind: "read-x-trending", queueKey: "platform:twitter", startedAt: T0 - 2 * MIN }, T0 - 2 * MIN); // A library's media-only capture of that time: its channel is not read, so it counts (more rather than fewer). meta(paths, { kind: "capture-posts", queueKey: "platform:twitter", startedAt: T0 - 3 * MIN, spec: { kind: "capture-posts", params: { shots: false, articles: false, avatars: false, context: false } } }, T0 - 3 * MIN); // Not network (a reparse), never started, another queue: not counted. meta(paths, { kind: "reparse-x-trending", queueKey: "platform:twitter", startedAt: T0 - 4 * MIN }, T0 - 4 * MIN); meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", status: "cancelled" }, T0 - 5 * MIN); meta(paths, { kind: "fetch-posts", queueKey: "platform:bluesky", startedAt: T0 - 6 * MIN }, T0 - 6 * MIN); const rebuilt = await rebuildXJobStarts(paths, T0); assert.equal(rebuilt.ok, true); assert.deepEqual(rebuilt.ok ? rebuilt.starts : [], [T0 - 3 * MIN, T0 - 2 * MIN, T0 - MIN]); }); test("R-c: X activity whose records cannot be read is refused — fail closed", async () => { const gaps = (paths: ReturnType, end: number) => { mkdirSync(paths.jobsDir, { recursive: true }); writeFileSync(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": end } })); }; // X's queue ended a job an hour ago, and no record of an X job is left. const gone = corpus("closed-no-records"); gaps(gone, T0 - HOUR); meta(gone, { kind: "download-missing", queueKey: "platform:youtube", startedAt: T0 - MIN }); const refused = await xJobCapStatus(gone, T0); assert.equal(refused.ok, false); assert.equal(refused.unreadable, true); assert.match( refused.sentence ?? "", /^X's job count is not on disk \(.*job-starts\.json\) and cannot be rebuilt from the job records: X's queue ended a job within the last 24 hours and no record of an X job is left\. No X job starts .* at the latest until 2026-11-19 11:00 UTC/, ); assert.equal((await recordXJobStart(gone, T0)).ok, false); // Nothing is written on a guess. assert.throws(() => readFileSync(xJobStartsFile(gone))); // A day after that end, nothing on record can still count: zero. assert.equal((await xJobCapStatus(gone, T0 + 24 * HOUR)).ok, true); // A record of the last day that cannot be read may be an X job's. const torn = corpus("closed-torn"); mkdirSync(torn.jobsDir, { recursive: true }); writeFileSync(path.join(torn.jobsDir, `${ulid(T0 - MIN)}.meta.json`), "{torn"); const tornStatus = await xJobCapStatus(torn, T0); assert.equal(tornStatus.ok, false); assert.match(tornStatus.sentence ?? "", /cannot be rebuilt from the job records: the job record .*\.meta\.json cannot be read/); // …but one older than a day cannot count, and is passed over. const old = corpus("old-torn"); mkdirSync(old.jobsDir, { recursive: true }); writeFileSync(path.join(old.jobsDir, `${ulid(T0 - 30 * HOUR)}.meta.json`), "{torn"); assert.equal((await xJobCapStatus(old, T0)).ok, true); // The records' directory refuses to be listed. if (process.getuid?.() !== 0) { const locked = corpus("closed-locked"); mkdirSync(locked.jobsDir, { recursive: true }); chmodSync(locked.jobsDir, 0o000); try { const status = await xJobCapStatus(locked, T0); assert.equal(status.ok, false); assert.match(status.sentence ?? "", /the job records cannot be listed \(EACCES\)/); } finally { chmodSync(locked.jobsDir, 0o755); } } }); test("review 3 S4: a start in the future counts in both windows and never prunes the real ones", async () => { const paths = corpus("future"); mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); // Ten real starts and one stamped a year ahead (a clock that jumped forward, then back). const real = Array.from({ length: 4 }, (_, i) => T0 + i * MIN); writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [...real, T0 + 365 * 24 * HOUR] })); const status = await xJobCapStatus(paths, T0 + 10 * MIN); assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 5, 5]); const r = await recordXJobStart(paths, T0 + 10 * MIN); assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 6]); // The real starts are kept beside the future one. assert.deepEqual(fileOf(paths).starts, [...real, T0 + 365 * 24 * HOUR, T0 + 10 * MIN]); assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds six"); }); test("review 3 M3: a rebuild that cannot show its records cover the last day refuses, writes nothing, and ends by itself", async () => { const xs = (paths: ReturnType) => { for (let i = 0; i < 5; i++) meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - i * MIN, endedAt: T0 - i * MIN + 1000, xStarts: [T0 - i * MIN] }, T0 - i * MIN); }; // X jobs ran today; nothing says the records of the day are all there. const paths = corpus("m3-unshown"); xs(paths); const refused = await xJobCapStatus(paths, T0 + MIN); assert.equal(refused.ok, false); assert.equal(refused.unreadable, true); assert.match(refused.sentence ?? "", /cannot be rebuilt from the job records: records of the last 24 hours may have been deleted .* at the latest until 2026-11-19 12:01 UTC/); assert.equal((await recordXJobStart(paths, T0 + MIN)).ok, false); assert.throws(() => readFileSync(xJobStartsFile(paths)), "nothing is written on a guess"); // The refusal itself starts the day after which the records are known kept. assert.equal(JSON.parse(readFileSync(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), "utf8")).since, T0 + MIN); // A day later the count is rebuilt (the five can no longer count). const later = await xJobCapStatus(paths, T0 + MIN + 24 * HOUR); assert.deepEqual([later.ok, later.lastDay], [true, 0]); // A FINISHED JOB THAT ENDED OVER A DAY AGO IS NO PROOF (review 4 A): a // record of a job cancelled while queued has no log and is never pruned, and // retention goes by id and queue time, not start time. const shown = corpus("m3-old-finished-no-proof"); xs(shown); meta(shown, { kind: "sync", queueKey: "platform:youtube", status: "done", startedAt: T0 - 26 * HOUR, endedAt: T0 - 25 * HOUR }, T0 - 26 * HOUR); meta(shown, { kind: "fetch-posts", queueKey: "platform:twitter", status: "cancelled", endedAt: T0 - 30 * HOUR }, T0 - 30 * HOUR); const s = await xJobCapStatus(shown, T0 + MIN); assert.equal(s.ok, false); assert.throws(() => readFileSync(xJobStartsFile(shown)), "nothing is written on a guess"); // SHOWN BY THE PRUNER: it has kept X's records for over a day. const pruner = corpus("m3-shown-by-pruner"); xs(pruner); keptSince(pruner, T0 - 25 * HOUR); assert.deepEqual([(await xJobCapStatus(pruner, T0 + MIN)).ok, (await xJobCapStatus(pruner, T0 + MIN)).lastDay], [true, 5]); // …for less than a day: not yet. const recent = corpus("m3-pruner-recent"); xs(recent); keptSince(recent, T0 - 2 * HOUR); const r = await xJobCapStatus(recent, T0 + MIN); assert.equal(r.ok, false); assert.match(r.sentence ?? "", /at the latest until 2026-11-19 10:00 UTC/); // A MARKER IN THE FUTURE IS NO PROOF (review 4 A): refused, as with none, // and the refusal ends within a day. const ahead = corpus("m3-pruner-future"); xs(ahead); keptSince(ahead, T0 + 365 * 24 * HOUR); const f = await xJobCapStatus(ahead, T0 + MIN); assert.equal(f.ok, false); assert.match(f.sentence ?? "", /at the latest until 2026-11-19 12:01 UTC/); assert.throws(() => readFileSync(xJobStartsFile(ahead)), "nothing is written on a guess"); const aheadLater = await xJobCapStatus(ahead, T0 + MIN + 24 * HOUR); assert.deepEqual([aheadLater.ok, aheadLater.lastDay], [true, 0]); });