// X IN SMALL, UNEVEN SITTINGS (lane x-sittings; lib/xSitting.ts, jobs/xSitting.ts): // the sitting's count over every kind of X job, through the real job funnel // (runManagedFunction → the network guard), across an "editor restart", and // reset by nothing but a later cookie refresh; the one-kind rule; the drawn // gap; the account marked suspended; the 429 cooldown over every X kind. // Temp dirs only; no job here asks anything of any site (each job's work is a // stub that only records that it ran). // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/xSittings.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "x-sittings-")); process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); delete process.env.E2E_JOB_GAP_SECONDS; delete process.env.E2E_X_SITTINGS; delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; delete process.env.E2E_TEST_ROUTES; // A fake gallery-dl (it asks nothing of anyone): FAKE_GDL=ratelimit prints the // line gallery-dl prints when it aborts at X's rate limit, and exits 1. const FAKE_GDL = path.join(ROOT, "fake-gallery-dl.mjs"); await writeFile( FAKE_GDL, `#!/usr/bin/env node if (process.env.FAKE_GDL === "ratelimit") { process.stderr.write("[twitter][error] Rate limit exceeded\\n"); process.exit(1); } process.exit(0); `, ); const { chmod } = await import("node:fs/promises"); await chmod(FAKE_GDL, 0o755); process.env.GALLERY_DL_BIN = FAKE_GDL; async function writeSettings(x: Record = {}): Promise { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ social: { x: { cookieSource: "profile", ...x } } })); } await writeSettings(); const transcripts = path.join(ROOT, "transcripts"); async function channel(slug: string, extra: Record = {}): Promise { const dir = path.join(transcripts, "channels", slug); await mkdir(dir, { recursive: true }); await writeFile( path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", sourceKind: "social", postFetcher: "x-gallery-dl", platform: "twitter", name: slug, socialHandle: slug.replace(/-/g, ""), url: `https://x.com/${slug.replace(/-/g, "")}`, ...extra }), ); } const ACCOUNTS = ["acct-one", "acct-two", "acct-three", "acct-four", "acct-five", "acct-six", "acct-seven"]; for (const s of ACCOUNTS) await channel(s); await channel("demo-library", { xTrending: {}, url: undefined, postFetcher: undefined }); await channel("demo-search", { xSearch: { query: "kettles" } }); const SESSION = path.join(transcripts, ".x-session"); const JAR = path.join(SESSION, "cookies.txt"); // A jar written `ageMs` ago, as an old jar is: its mtime is its time (no // broker stamp). `refresh` also writes the broker's stamp, as a Refresh does. async function writeJar(ageMs: number, opts: { refresh?: boolean } = {}): Promise { await mkdir(path.join(SESSION, "profile"), { recursive: true }); await writeFile(JAR, "# Netscape HTTP Cookie File\n.x.com\tTRUE\t/\tTRUE\t0\tauth_token\tv\n"); const t = new Date(Date.now() - ageMs); await utimes(JAR, t, t); if (opts.refresh) await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: t.toISOString() })); return t.toISOString(); } const { getPaths } = await import("../lib/paths"); const { runManagedFunction } = await import("./streamCommand"); const { setQueueGapClock, clearQueueGaps, noteQueueJobEnd, queueGapWait, queueGapLine, setXGapRandom, xQueueGapRange } = await import("./queueGap"); const { xJobStartsFile } = await import("./xJobCap"); const { xSittingFile } = await import("./xSitting"); const { xSessionReport, guardNetworkJob, xCapRoom, xCapHeldReason } = await import("./networkGuard"); const { recordPlatformCooldown } = await import("./downloadBackoff"); const { writeAutoQueueState, readAutoQueueState } = await import("./autoQueueState"); const { writeXAccountState, xAccountStateFile, keepVerdictsTrustedWhileSuspended } = await import("../social/xAccountState"); const { readXSessionStatus } = await import("../social/xSessionBroker"); const { getRegistry } = await import("./registry"); const { parseXSittingJobs, xSittingJobs, X_SITTING_MAX_JOBS, drawXGapSeconds, xGapRange } = await import("../lib/xSitting"); const { sanitizeSocial } = await import("../social/xCookieSource"); const paths = getPaths(); let fakeNow = Date.now(); setQueueGapClock({ now: () => fakeNow, sleep: async (ms) => { fakeNow += ms; } }); async function reset(): Promise { clearQueueGaps(); // X's queue gap: a known end long ago (a lost file is answered from the // job records — review 1 F7 — whose clock is the wall's, not this test's). await mkdir(paths.jobsDir, { recursive: true }); await writeFile(path.join(paths.jobsDir, "queue-gaps.json"), JSON.stringify({ version: 1, ends: { "platform:twitter": 1 } })); await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true }); await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); await rm(xSittingFile(paths), { force: true }); await rm(xAccountStateFile(paths), { force: true }); await rm(path.join(SESSION, "refreshed.json"), { force: true }); // No cooldown on record. const st = await readAutoQueueState(paths); st.download.platformBackoff = {}; st.download.platformHolds = {}; await writeAutoQueueState(paths, st); await writeSettings(); } // One X job through the funnel, its work a stub. Answers how it ended. async function xJob(kind: string, slug: string | undefined, params?: Record): Promise<{ queued: boolean; error?: string; status?: string; deferred?: { until: number; sentence: string }; ran: boolean; log?: string }> { let ran = false; const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), ...(params ? { spec: { kind, slug: slug ?? "x", params } } : {}), fn: async () => { ran = true; fakeNow += 2_000; }, } as Parameters[0]); if (!res.ok) return { queued: false, error: res.error, ran }; const status = (await res.done).status; const rec = getRegistry().get(res.jobId); const log = await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8").catch(() => ""); return { queued: true, status, ran, log, ...(rec?.deferred ? { deferred: rec.deferred } : {}) }; } test("N: a sitting admits 4 X job starts by default; the setting is bounded 1-6 in the code", () => { assert.equal(xSittingJobs(undefined), 4); assert.equal(xSittingJobs({ sittingJobs: 2 }), 2); assert.equal(xSittingJobs({ sittingJobs: 60 }), X_SITTING_MAX_JOBS); assert.equal(xSittingJobs({ sittingJobs: 0 }), 1); assert.equal(parseXSittingJobs("4"), undefined); assert.equal(parseXSittingJobs(9.7), 6); assert.deepEqual(sanitizeSocial({ x: { sittingJobs: 99, gapMinMinutes: 1, gapMaxMinutes: 600 } }).x, { sittingJobs: 6, gapMinMinutes: 5, gapMaxMinutes: 120 }); assert.deepEqual(sanitizeSocial({ x: { sittingJobs: "lots" } }).x, {}); }); test("the 5th X start after a refresh is refused — over every kind of timelines job together — and ends deferred, not failed", async () => { await reset(); await writeJar(2 * 60_000, { refresh: true }); const ends = [ await xJob("fetch-posts", ACCOUNTS[0]), await xJob("capture-posts", ACCOUNTS[1], { ids: ["1"], shots: true }), await xJob("check-post-availability", ACCOUNTS[2]), await xJob("import-post", ACCOUNTS[3]), ]; for (const e of ends) { assert.equal(e.queued, true, e.error); assert.equal(e.status, "done"); assert.equal(e.ran, true); } // Each job's log says where the sitting stands. assert.match(ends[0].log ?? "", /X sitting: 1 of 4 started \(timelines, since the refresh at \d\d:\d\d UTC\); 3 left\./); assert.match(ends[3].log ?? "", /X sitting: 4 of 4 started .*; 0 left\./); // The 5th: refused at enqueue (no job), with the sentence. const fifth = await xJob("fetch-posts", ACCOUNTS[4]); assert.equal(fifth.queued, false); assert.equal(fifth.ran, false); assert.match(fifth.error ?? "", /^This X sitting is used up: 4 of 4 X jobs started since the cookies were refreshed at \d\d:\d\d UTC \(social\.x\.sittingJobs, at most 6\)\. A new Refresh cookies on \/cookies starts the next sitting; nothing queues or retries by itself\.$/); // get x-session shows it: used, left, kind, when it began. const report = await xSessionReport({ paths }); assert.equal(report.allowed, false); assert.equal(report.refusedBy, "sitting"); assert.deepEqual({ ...report.sitting, began: typeof report.sitting.began }, { began: "string", kind: "timelines", used: 4, left: 0, limit: 4 }); // A job queued while there was room, started after it is gone: done, DEFERRED (until a Refresh), never run. await writeFile(xSittingFile(paths), JSON.stringify({ ...JSON.parse(await readFile(xSittingFile(paths), "utf8")), starts: JSON.parse(await readFile(xSittingFile(paths), "utf8")).starts.slice(0, 3) })); let ran = false; let release!: () => void; const blocker = new Promise((r) => (release = r)); // Hold X's queue with one job so the next one queues while the sitting has room. const hold = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], fn: async () => { await blocker; } }); assert.equal(hold.ok, true); const late = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[5], fn: async () => { ran = true; } }); assert.equal(late.ok, true, late.ok ? "" : late.error); release(); if (hold.ok) await hold.done; if (late.ok) { assert.equal((await late.done).status, "done"); const rec = getRegistry().get(late.jobId); assert.equal(rec?.deferred?.until, 0); assert.match(rec?.deferred?.sentence ?? "", /^This X sitting is used up: 4 of 4/); } assert.equal(ran, false); }); test("ONE KIND PER SITTING: the first job fixes it; a job of the other kind is refused until the next refresh", async () => { await reset(); await writeJar(60_000, { refresh: true }); const read = await xJob("read-x-trending", "demo-library"); assert.equal(read.status, "done", read.error); // A search channel's walk and a library's capture are browse too. assert.equal((await xJob("fetch-posts", "demo-search")).status, "done"); assert.equal((await xJob("capture-posts", "demo-library", { ids: ["9"], shots: true })).status, "done"); // A timeline fetch: refused, saying why. const timeline = await xJob("fetch-posts", ACCOUNTS[0]); assert.equal(timeline.queued, false); assert.match(timeline.error ?? "", /^This X sitting is a browse sitting \(its first job, read-x-trending at \d\d:\d\d UTC, fixed it\): a timelines job does not start in it/); assert.equal((await xSessionReport({ paths })).sitting.kind, "browse"); // A later refresh begins a new sitting, of either kind. await writeJar(0, { refresh: true }); const after = await xJob("fetch-posts", ACCOUNTS[0]); assert.equal(after.status, "done", after.error); const r = await xSessionReport({ paths }); assert.deepEqual([r.sitting.kind, r.sitting.used], ["timelines", 1]); }); test("the sitting survives an editor restart and is reset by nothing but a LATER refresh", async () => { await reset(); const refreshed = await writeJar(5 * 60_000, { refresh: true }); for (const s of ACCOUNTS.slice(0, 3)) assert.equal((await xJob("fetch-posts", s)).status, "done"); // A restart: every in-memory store is gone; the file is not. clearQueueGaps(); assert.equal((await xSessionReport({ paths })).sitting.used, 3); // gallery-dl (or anything) rewriting the jar moves its mtime, not the refresh. const t = new Date(); await utimes(JAR, t, t); assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, refreshed); assert.equal((await xSessionReport({ paths })).sitting.used, 3); // A jar restored from an older refresh continues the sitting on record. await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(Date.parse(refreshed) - 3600_000).toISOString() })); assert.equal((await xSessionReport({ paths })).sitting.used, 3); await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: refreshed })); // The sitting file deleted: rebuilt from the records and X's job count, kind and all. await rm(xSittingFile(paths)); const rebuilt = await xSessionReport({ paths }); assert.deepEqual([rebuilt.sitting.used, rebuilt.sitting.kind], [3, "timelines"]); // Deleted, with the records' kinds gone too: counted from X's job count, kind unknown — both kinds refused. await rm(xSittingFile(paths)); for (const id of getRegistry().list().map((r) => r.id)) { const meta = path.join(paths.jobsDir, `${id}.meta.json`); const m = JSON.parse(await readFile(meta, "utf8").catch(() => "{}")); if (m.xSittings) { delete m.xSittings; await writeFile(meta, JSON.stringify(m)); } } const unknown = await xSessionReport({ paths, sittingKind: "timelines" }); assert.equal(unknown.sitting.kind, "unknown"); assert.equal(unknown.allowed, false); assert.match(unknown.reason ?? "", /^This X sitting's kind cannot be told/); // An unreadable file: every counted X job is refused. await writeFile(xSittingFile(paths), "{ not json"); const bad = await xJob("fetch-posts", ACCOUNTS[3]); assert.equal(bad.queued, false); assert.match(bad.error ?? "", /^X's sitting cannot be read/); // Only a later refresh begins a new one (stamped on the jobs' clock, which ran ahead of the wall's here). await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: refreshed, kind: "timelines", starts: [] })); await writeFile(path.join(SESSION, "refreshed.json"), JSON.stringify({ version: 1, at: new Date(fakeNow + 1000).toISOString() })); const fresh = await xSessionReport({ paths }); assert.deepEqual([fresh.sitting.used, fresh.sitting.kind], [0, null]); }); test("N is the setting, bounded: sittingJobs 2 refuses the 3rd; 50 admits 6 and refuses the 7th", async () => { await reset(); await writeSettings({ sittingJobs: 2 }); await writeJar(60_000, { refresh: true }); assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); assert.equal((await xJob("fetch-posts", ACCOUNTS[1])).status, "done"); assert.match((await xJob("fetch-posts", ACCOUNTS[2])).error ?? "", /used up: 2 of 2/); await writeSettings({ sittingJobs: 50 }); await writeJar(0, { refresh: true }); // Out of the hourly cap's way: the first part's starts are forgotten. await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] })); for (const s of ACCOUNTS.slice(0, 6)) { const e = await xJob("fetch-posts", s); assert.equal(e.status, "done", e.error); fakeNow += 11 * 60_000; // out of the hourly cap's way } assert.match((await xJob("fetch-posts", ACCOUNTS[6])).error ?? "", /used up: 6 of 6/); }); test("UNEVEN GAPS: X's gap is drawn per job within 5-12 min, never below 5, logged with its draw; seeded only in a test", async () => { // The pure draw: the bounds, always. const range = xGapRange(undefined); assert.deepEqual(range, { minSeconds: 300, maxSeconds: 720 }); assert.equal(drawXGapSeconds(range, 0), 300); assert.equal(drawXGapSeconds(range, 0.999999), 720); for (let i = 0; i < 200; i++) { const s = drawXGapSeconds(range, Math.random()); assert.ok(s >= 300 && s <= 720, String(s)); } // The floor holds against any setting; an explicit jobGapSeconds.twitter above it raises the minimum, never lowers it. // …and the range is never one value (review 1 F4): at least 3 minutes wide, whatever is set. assert.deepEqual(xGapRange({ gapMinMinutes: 1, gapMaxMinutes: 2 }), { minSeconds: 300, maxSeconds: 480 }); assert.deepEqual(xGapRange({ gapMinMinutes: 6, gapMaxMinutes: 9 }), { minSeconds: 360, maxSeconds: 540 }); assert.deepEqual(xGapRange({ gapMinMinutes: 8, gapMaxMinutes: 8 }), { minSeconds: 480, maxSeconds: 660 }); assert.deepEqual(xGapRange(undefined, 900), { minSeconds: 900, maxSeconds: 1080 }); assert.deepEqual(xGapRange(undefined, 0), { minSeconds: 300, maxSeconds: 720 }); assert.deepEqual(xQueueGapRange({ jobGapSeconds: { twitter: 30 } }, undefined), { minSeconds: 300, maxSeconds: 720 }); // The wait: drawn once per end, kept across re-reads, seeded draws repeat. clearQueueGaps(); setXGapRandom(42); const end = fakeNow; await noteQueueJobEnd(paths, "platform:twitter", end); const w1 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); const w2 = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 60_000, xGap: {} }); assert.ok(w1 && w2); assert.equal(w1!.until, w2!.until, "a re-read keeps the draw"); assert.ok(w1!.drawn!.seconds >= 300 && w1!.drawn!.seconds <= 720); assert.match(queueGapLine(w1!), /^waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\): X jobs are spaced 5-12 min apart, drawn per job/); clearQueueGaps(); setXGapRandom(42); await noteQueueJobEnd(paths, "platform:twitter", end); const again = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + 1000, xGap: {} }); assert.equal(again!.drawn!.seconds, w1!.drawn!.seconds, "the same seed, the same draw"); // Different ends draw differently (not one fixed beat): over 30 ends, more than one value. const draws = new Set(); for (let i = 0; i < 30; i++) { await noteQueueJobEnd(paths, "platform:twitter", end + (i + 1) * 3_600_000); const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: end + (i + 1) * 3_600_000 + 1, xGap: {} }); draws.add(w!.drawn!.seconds); } assert.ok(draws.size > 5, `${draws.size} distinct draws`); setXGapRandom(null); clearQueueGaps(); // Through the funnel: two X jobs, the second starts 5-12 min after the first ended, and its log says the draw. await reset(); await writeJar(60_000, { refresh: true }); const first = await xJob("fetch-posts", ACCOUNTS[0]); const t1 = fakeNow; const second = await xJob("fetch-posts", ACCOUNTS[1]); assert.equal(second.status, "done", second.error); assert.match(second.log ?? "", /waiting \d+m\d\ds \(a \d+m\d\ds gap drawn from 5-12 min\)/); const waited = fakeNow - 2_000 - t1; assert.ok(waited >= 300_000 && waited <= 720_000, `${waited} ms`); assert.equal(first.status, "done"); }); test("SUSPENDED: marked by hand, it refuses availability checks and captures that record deleted posts; other X jobs log it", async () => { await reset(); await writeJar(60_000, { refresh: true }); await writeXAccountState(paths, "suspended", { note: "read-only since the 21st" }); const report = await xSessionReport({ paths }); assert.equal(report.account.state, "suspended"); assert.match(report.account.alert ?? "", /^The X account is marked suspended \(since .* UTC: read-only since the 21st\)/); for (const [kind, params] of [ ["check-post-availability", undefined], ["capture-posts", { ids: ["1"] }], ["capture-posts", { ids: ["1"], shots: true }], ] as const) { const e = await xJob(kind, ACCOUNTS[0], params); assert.equal(e.queued, false, kind); assert.match(e.error ?? "", /^The X account is marked suspended .*is refused, because a suspended account's answers are thinned/, kind); } // A capture with its screenshots AND its articles off reads no page's verdict: it runs (review 1 F5). assert.equal((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false, articles: false })).status, "done"); // A fetch runs, and its log says the account is suspended. const fetch = await xJob("fetch-posts", ACCOUNTS[1]); assert.equal(fetch.status, "done"); assert.match(fetch.log ?? "", /The X account is marked suspended .* What X answers it may be thinned\./); // The last line before a verdict is written (a mark made while a job ran): only "available" is kept. const lines: string[] = []; const kept = await keepVerdictsTrustedWhileSuspended(paths, new Map([["1", "deleted"], ["2", "available"], ["3", "account_unavailable"]]), (l) => lines.push(l)); assert.deepEqual([...kept], [["2", "available"]]); assert.match(lines.join("\n"), /2 "deleted" or "unavailable" verdict\(s\) from its answers were NOT recorded/); // Marked ok: the check runs again. await writeXAccountState(paths, "ok"); assert.equal((await xJob("check-post-availability", ACCOUNTS[2])).status, "done"); const all = new Map([["1", "deleted"]]); assert.equal(await keepVerdictsTrustedWhileSuspended(paths, all, () => {}), all); // An unreadable state file is taken as suspended. await writeFile(xAccountStateFile(paths), "nope"); assert.match((await xJob("check-post-availability", ACCOUNTS[3])).error ?? "", /marked suspended/); }); test("A 429 STOPS EVERY X JOB FOR 15 MINUTES: fetch, capture, availability check, import, X run channel, trending read, search walk", async () => { await reset(); await writeJar(60_000, { refresh: true }); await recordPlatformCooldown("twitter", 15 * 60_000, paths); for (const [kind, slug] of [ ["fetch-posts", ACCOUNTS[0]], ["sync", ACCOUNTS[0]], ["capture-posts", ACCOUNTS[1]], ["check-post-availability", ACCOUNTS[2]], ["import-post", ACCOUNTS[3]], ["read-x-trending", "demo-library"], ["fetch-posts", "demo-search"], ] as const) { const e = await xJob(kind, slug); assert.equal(e.queued, false, kind); assert.match(e.error ?? "", /^X answered a rate limit \(429\) a short while ago: no X job starts before \d\d:\d\d UTC \(1[45] min from now\)/, kind); } // Each channel of an X run is guarded the same way. const runGuard = await guardNetworkJob({ kind: "x-run", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[4], job: { id: "01JXRUN0000000000000000000" }, countStart: true }); assert.equal(runGuard.ok, false); // Nothing was counted against the sitting or the cap. const r = await xSessionReport({ paths }); assert.equal(r.sitting.used, 0); assert.equal(r.cap.lastHour, 0); assert.equal(r.refusedBy, "cooldown"); assert.ok(r.cooldown && Date.parse(r.cooldown.until) > Date.now() + 14 * 60_000); // Once it has passed, X jobs start again. const st = await readAutoQueueState(paths); st.download.platformBackoff = {}; await writeAutoQueueState(paths, st); assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); }); test("the scheduler queues no more X syncs than the sitting has left, and none into a browse sitting", async () => { await reset(); await writeJar(60_000, { refresh: true }); assert.equal(await xCapRoom(paths, fakeNow), 4); assert.equal(await xCapHeldReason(paths, fakeNow), null); assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); assert.equal(await xCapRoom(paths, fakeNow), 3); // A browse sitting has no room for a timeline sync. await writeJar(0, { refresh: true }); assert.equal((await xJob("read-x-trending", "demo-library")).status, "done"); assert.equal(await xCapRoom(paths, fakeNow), 0); assert.match((await xCapHeldReason(paths, fakeNow)) ?? "", /^This X sitting is a browse sitting/); // Used up: the sentence says so. await writeFile(xSittingFile(paths), JSON.stringify({ version: 1, began: JSON.parse(await readFile(xSittingFile(paths), "utf8")).began, kind: "timelines", starts: [1, 2, 3, 4].map((i) => ({ at: fakeNow - i, jobKind: "fetch-posts", kind: "timelines" })) })); assert.equal(await xCapRoom(paths, fakeNow), 0); assert.match((await xCapHeldReason(paths, fakeNow)) ?? "", /^This X sitting is used up: 4 of 4/); }); // ── review 1 ─────────────────────────────────────────────────────────────── const { applyXStop, X_STOP_MS } = await import("./platformBackoff"); const { recordDownloadBackoff, recordXStop, xStopRemainingMs } = await import("./downloadBackoff"); const { downloadXPostMedia } = await import("../social/xGalleryDlFetcher"); const { clearXSession } = await import("../social/xSessionBroker"); const { runInJobContext } = await import("../lib/jobContext"); const { writePostCapture, readPostCapture } = await import("../social/postCapture"); const { writeDownloadOutcome, loadDownloadOutcome } = await import("../lib/downloadOutcome-server"); const { recordAvailability } = await import("../lib/availability-server"); const { xSuspendedRefuses } = await import("../lib/xSitting"); const { X_RATE_LIMIT_HOLD_MS } = await import("../lib/xJobRule"); test("F1: a 429 from ANY X reader is the same 15-minute X stop — yt-dlp on an X address, a named cooldown, a post's media download — never the 60 s backoff", async () => { assert.equal(X_STOP_MS, X_RATE_LIMIT_HOLD_MS); assert.equal(X_STOP_MS, 15 * 60_000); const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); // yt-dlp on an X window / import / download (recordDownloadBackoff is what they call). await reset(); await recordDownloadBackoff("twitter", paths, "rate_limit"); assert.equal(await left(), 15); // Any caller that names its own length for X gets the X stop. await reset(); const { recordPlatformCooldown } = await import("./downloadBackoff"); await recordPlatformCooldown("twitter", 60_000, paths); assert.equal(await left(), 15); // The auto-download lane's unit (pure, on the live state): the X stop too. const st = { platformBackoff: {} as Record }; const e = applyXStop(st, 1_000); assert.equal(e.until, 1_000 + 15 * 60_000); // gallery-dl's media download of one post: its rate-limit line is the X stop, and the capture is told to stop. await reset(); process.env.FAKE_GDL = "ratelimit"; try { const dir = path.join(ROOT, "media-1"); await mkdir(dir, { recursive: true }); const got = await downloadXPostMedia({ id: "123", dir, login: {}, signal: new AbortController().signal }); assert.equal(got.ok, false); assert.match(got.ok ? "" : (got.stop ?? ""), /rate limit/); } finally { delete process.env.FAKE_GDL; } assert.equal(await left(), 15); // And then every X job is refused. await writeJar(60_000, { refresh: true }); assert.match((await xJob("fetch-posts", ACCOUNTS[0])).error ?? "", /^X answered a rate limit \(429\)/); // A generic platform keeps its own backoff. await reset(); await recordDownloadBackoff("odysee", paths, "rate_limit"); const od = (await readAutoQueueState(paths)).download.platformBackoff.odysee; assert.ok(od && od.until - Date.now() < 5 * 60_000, "odysee's first step is short"); }); test("F2: a job that meets the X stop ends DEFERRED at once, saying so, with what it read kept", async () => { await reset(); await writeJar(60_000, { refresh: true }); const e = await (async () => { let ran = false; const res = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: ACCOUNTS[0], fn: async () => { ran = true; await recordXStop("a rate limit (gallery-dl)", paths); throw new Error("gallery-dl exited 1"); }, }); assert.ok(res.ok); const done = await res.done; return { ran, done, rec: getRegistry().get(res.jobId), log: await readFile(path.join(paths.jobsDir, `${res.jobId}.log`), "utf8") }; })(); assert.equal(e.ran, true); assert.equal(e.done.status, "done"); assert.ok(e.rec?.deferred); assert.match(e.rec!.deferred!.sentence, /^X answered a rate limit \(gallery-dl\) at \d\d:\d\d UTC: this job stopped there and kept what it read; no X job starts before/); assert.ok(e.rec!.deferred!.until > Date.now() + 14 * 60_000); assert.match(e.log, /X answered a rate limit \(gallery-dl\): X is left alone until \d\d:\d\d UTC \(15 minutes\); this job stops here\./); assert.doesNotMatch(e.log, /^\[error\]/m); }); test("F3: Clear session forgets the login only — the suspended mark, the sitting, X's count and the 429 stop stay", async () => { await reset(); await writeJar(60_000, { refresh: true }); assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); await writeXAccountState(paths, "suspended", { note: "kept across a clear" }); await recordXStop("a rate limit", paths); await clearXSession(paths); const { existsSync } = await import("node:fs"); assert.equal(existsSync(JAR), false); assert.equal(existsSync(path.join(SESSION, "profile")), false); assert.equal(existsSync(path.join(SESSION, "refreshed.json")), false); assert.equal(existsSync(xAccountStateFile(paths)), true); assert.equal(existsSync(xSittingFile(paths)), true); assert.equal(existsSync(xJobStartsFile(paths)), true); const r = await xSessionReport({ paths }); assert.equal(r.account.state, "suspended"); assert.equal(r.sitting.used, 1); assert.ok(r.cooldown); }); test("F4: an explicit pacing.jobGapSeconds.twitter of 900 still draws unevenly — never one fixed beat", async () => { const range = xQueueGapRange({ jobGapSeconds: { twitter: 900 } }, { gapMinMinutes: 5, gapMaxMinutes: 5 }); assert.deepEqual(range, { minSeconds: 900, maxSeconds: 1080 }); const draws = new Set(); for (let i = 0; i < 50; i++) draws.add(drawXGapSeconds(range, i / 50)); assert.ok(draws.size > 20, `${draws.size} distinct gaps`); for (const d of draws) assert.ok(d >= 900 && d <= 1080); }); test("F5: while suspended nothing records a post or a video as gone from X's answer — captures with articles, video checks, outcomes, availability, capture records", async () => { // The guard: a capture with its shots off but its articles on, and the video checks. assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false, articles: true } }), true); assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false } }), true); assert.equal(xSuspendedRefuses({ kind: "capture-posts", params: { shots: false, articles: false } }), false); for (const kind of ["check-availability", "quick-availability-check", "check-maybe-missing", "check-kept-deleted"]) { assert.equal(xSuspendedRefuses({ kind }), true, kind); } await reset(); await writeJar(60_000, { refresh: true }); await writeXAccountState(paths, "suspended"); assert.match((await xJob("capture-posts", ACCOUNTS[0], { ids: ["1"], shots: false, articles: true })).error ?? "", /marked suspended/); assert.match((await xJob("check-availability", ACCOUNTS[0])).error ?? "", /marked suspended/); // The writers, inside an X job (its context carries the mark). const ctx = { jobId: "j", kind: "fetch-window", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set(), xSuspended: async () => true }; const dir = path.join(ROOT, "writers"); await mkdir(dir, { recursive: true }); await runInJobContext(ctx, async () => { await writePostCapture(dir, { version: 1, id: "9", url: "https://x.com/i/status/9", capturedAt: "2026-11-21T00:00:00.000Z", state: "deleted", mediaState: "skipped", media: [] } as never); await writeDownloadOutcome(dir, { status: "failed", videoId: "v", startedAt: "a", finishedAt: "b", attempts: [{ n: 1, kind: "full", handling: "transcribe", usedCookies: false, ytdlpExitCode: 1, availabilityClass: "deleted" }] } as never); await recordAvailability(dir, { availability: "deleted", observedAt: "2026-11-21T00:00:00.000Z", source: "download" }); }); assert.equal((await readPostCapture(dir))!.state, "error"); assert.equal((await loadDownloadOutcome(dir))!.attempts[0].availabilityClass, undefined); const { existsSync } = await import("node:fs"); assert.equal(existsSync(path.join(dir, "availability.json")), false, "no availability recorded"); // Not suspended: written as said. await runInJobContext({ ...ctx, xSuspended: async () => false }, () => writePostCapture(dir, { version: 1, id: "9", url: "u", capturedAt: "c", state: "deleted", mediaState: "skipped", media: [] } as never), ); assert.equal((await readPostCapture(dir))!.state, "deleted"); }); test("F6: in a production-shaped environment the e2e hooks are ignored — the gap, the sittings and the jar rule all hold", async () => { await reset(); process.env.E2E_JOB_GAP_SECONDS = "0"; process.env.E2E_X_SITTINGS = "off"; process.env.E2E_X_MAX_COOKIE_AGE_MINUTES = "0"; delete process.env.E2E_TEST_ROUTES; try { assert.deepEqual(xQueueGapRange(undefined, undefined), { minSeconds: 300, maxSeconds: 720 }); await writeJar(3 * 3600_000, { refresh: true }); assert.match((await xSessionReport({ paths })).reason ?? "", /^X cookies were last refreshed 3 h ago/); await writeSettings({ sittingJobs: 1 }); await writeJar(60_000, { refresh: true }); assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); assert.match((await xJob("fetch-posts", ACCOUNTS[1])).error ?? "", /used up: 1 of 1/); // The test server's gate opens them. process.env.E2E_TEST_ROUTES = "1"; assert.deepEqual(xQueueGapRange(undefined, undefined), { minSeconds: 0, maxSeconds: 0 }); assert.equal((await xSessionReport({ paths })).allowed, true); } finally { delete process.env.E2E_JOB_GAP_SECONDS; delete process.env.E2E_X_SITTINGS; delete process.env.E2E_X_MAX_COOKIE_AGE_MINUTES; delete process.env.E2E_TEST_ROUTES; } }); test("F7a: the three reads fail closed — an unreadable stop file, an unreadable refresh stamp, a lost queue-gaps.json", async () => { await reset(); await writeJar(60_000, { refresh: true }); // 1. The stop cannot be read: every X job is refused. const { writeFile: wf } = await import("node:fs/promises"); await wf(paths.autoQueueStateFile, "{ broken"); assert.match((await xJob("fetch-posts", ACCOUNTS[0])).error ?? "", /^X's rate-limit stop cannot be read/); await reset(); // 2. A stamp that is there and unreadable: the jar reads as never refreshed. await writeJar(60_000, { refresh: true }); await wf(path.join(SESSION, "refreshed.json"), "nope"); assert.equal((await readXSessionStatus(paths)).cookiesUpdatedAt, new Date(0).toISOString()); assert.equal((await xSessionReport({ paths })).allowed, false); // 3. queue-gaps.json lost after X jobs ran: the next waits a gap from the records. await reset(); await writeJar(60_000, { refresh: true }); assert.equal((await xJob("fetch-posts", ACCOUNTS[0])).status, "done"); clearQueueGaps(); await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true }); const w = await queueGapWait({ paths, queueKey: "platform:twitter", pacing: undefined, now: Date.now(), xGap: {} }); assert.ok(w && w.remainingMs > 200_000, "a gap is waited from the last X job on record"); }); test("F8: one X walk reads at most social.x.maxPostsPerJob posts (300; 20-400 in code)", async () => { const { xJobPostLimit, X_POSTS_PER_JOB_CEILING } = await import("../lib/xSitting"); assert.equal(xJobPostLimit(undefined), 300); assert.equal(xJobPostLimit(undefined, 200), 200); assert.equal(xJobPostLimit(undefined, 900), 300); assert.equal(xJobPostLimit({ maxPostsPerJob: 5000 }), X_POSTS_PER_JOB_CEILING); assert.equal(xJobPostLimit({ maxPostsPerJob: 1 }), 20); assert.deepEqual(sanitizeSocial({ x: { maxPostsPerJob: 9999 } }).x, { maxPostsPerJob: 400 }); }); test("F1: the auto-download lane's X unit that met a rate limit sets the 15-minute X stop, not the backoff's first step", async () => { const { applyUnitOutcome } = await import("./unitOutcome"); const state = { platformBackoff: {}, videoDeferrals: {}, platformPace: {}, platformHolds: {}, subtitleDeferrals: {} } as Parameters[0]; const fx = applyUnitOutcome(state, { platform: "twitter", videoId: "v1", channelSlug: ACCOUNTS[0], outcome: "failed", failureClass: "rate_limit" }, 10_000); assert.equal(state.platformBackoff.twitter.until, 10_000 + 15 * 60_000); assert.deepEqual(state.platformHolds, {}, "no hold"); assert.match(fx.line ?? "", /X answered a rate limit — X is left alone until/); }); test("review 2 G3: a capture takes at most social.x.maxPostsPerJob posts (the rest owed); a trending read's tabs share the setting", async () => { const { capturePosts } = await import("../controller/capturePosts"); const { xTrendingPostsPerTab } = await import("../controller/readXTrending"); const { getSettings } = await import("../lib/settings"); await reset(); await writeSettings({ maxPostsPerJob: 50 }); const ids = Array.from({ length: 51 }, (_, i) => String(1000 + i)); const log: string[] = []; const ctx = { jobId: "g3", kind: "capture-posts", queueKey: "platform:twitter", onLog: () => {}, staleServices: new Set() }; await runInJobContext(ctx, () => capturePosts({ paths, slug: ACCOUNTS[0], settings: getSettings(), ids, onLog: (l) => log.push(l) })); assert.ok(log.some((l) => /^This X capture takes the first 50 of 51 posts \(social\.x\.maxPostsPerJob\); the other 1 are left for a later job, from 1050\.$/.test(l)), log.join("\n")); // The trending read: the setting over its tabs, never past what was asked. assert.equal(xTrendingPostsPerTab(200, 2, undefined), 150); assert.equal(xTrendingPostsPerTab(200, 2, { maxPostsPerJob: 20 }), 10); assert.equal(xTrendingPostsPerTab(200, 1, { maxPostsPerJob: 9999 }), 200); assert.equal(xTrendingPostsPerTab(400, 1, { maxPostsPerJob: 9999 }), 400); await writeSettings(); }); test("review 2 G4: nothing ends the X stop before its time — not a clean answer, not Clear hold — but 'Clear the X stop', confirmed and logged", async () => { const { recordPlatformClean, clearPlatformHold, clearXStop } = await import("./downloadBackoff"); const { settlePlatformClean } = await import("./platformBackoff"); const left = async () => Math.round((await xStopRemainingMs(paths)) / 60_000); await reset(); await recordXStop("a rate limit", paths); // A clean answer from another reader (a window fetch, a sync) and the lane page's Clear hold. await recordPlatformClean("twitter", paths); assert.equal(await left(), 15); await clearPlatformHold("twitter", paths); assert.equal(await left(), 15); // The pure settle, too. const st = { platformBackoff: { twitter: { until: Date.now() + 600_000, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; settlePlatformClean(st, "twitter", { baseSeconds: 1 }); assert.ok((st as { platformBackoff: Record }).platformBackoff.twitter); // The operator's act: unconfirmed, it clears nothing and says what it risks. const asked = await clearXStop(paths, { confirm: false, by: "test" }); assert.equal(asked.ok, false); assert.match(asked.message, /^Clearing the X stop lets the next X job ask X at once, inside the 15 minutes/); assert.equal(await left(), 15); const done = await clearXStop(paths, { confirm: true, by: "test", note: "checked" }); assert.equal(done.ok, true); assert.equal(await left(), 0); const logged = (await readFile(path.join(paths.jobsDir, "x-stop-cleared.jsonl"), "utf8")).trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual([logged.at(-1).by, logged.at(-1).note], ["test", "checked"]); // An ended stop is pruned as before (a clean answer clears an expired entry). const expired = { platformBackoff: { twitter: { until: Date.now() - 1, fails: 1 } }, platformHolds: {}, platformPace: {} } as never; settlePlatformClean(expired, "twitter", { baseSeconds: 1 }); assert.equal((expired as { platformBackoff: Record }).platformBackoff.twitter, undefined); });