commit c98e1e8a761088d545ffc8ff33592499bafcf6ca
parent 0e7d41ebc4faf040c62a630c7f01ab5a8e31e218
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 18 Nov 2026 21:44:31 -0500
x: review 2 M1, R-a, R-b, R-c -- one X job count for the machine, decided from the job's own plan, deferred at a start, and rebuilt when its file is gone
- M1: X's job cap is ONE bucket for the machine (jobs/xJobCap.ts, file
version 2 `{starts}`): a flipped login source, a respelled cookie spec, a
channel's own spec or an X run over channels of different specs no longer
open a fresh count. A version-1 file (one list per login key) is read as
the sum of its lists and rewritten as one; `get x-session` names no login.
- R-a: what counts is one predicate over the job's plan (lib/xJobRule.ts
xJobCounts, read by the guard from the job's spec and its channel): a
trending library's media-only capture (shots, articles, avatars, context
off by name; no thread, avatars-only, context-only or keep capture) is not
counted and not held by the cap; it still runs on X's queue under X's gap,
cooldown and the watch's jar rule. Every other X job counts.
- R-b: a job that meets the cap at its start ends `done`, deferred (record
and meta `deferred: {until, sentence}`, log `[deferred] ...`): no failure,
no strike, no banner. The scheduler folds it as neither (failures kept, not
eligible before `until`) -- foldScheduledSyncOutcome, shared by the tick.
The /jobs row says "deferred"; the job page says why.
- R-c: a missing job-starts.json is rebuilt from the job records (each X
queue job's meta now carries `xStarts`; a record from before counts once at
its start when its kind counts) and written. X activity (X's queue gap
ended a job in the last day) with records that cannot be listed, a torn
record of the day, or none left: every X job is refused. A corpus where no
X job ran starts at zero.
- The cap's file module moves from lib/ to jobs/ (it reads the job records).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
24 files changed, 911 insertions(+), 236 deletions(-)
diff --git a/common/controller/xTrendingWatch.test.ts b/common/controller/xTrendingWatch.test.ts
@@ -386,7 +386,6 @@ test("M1: the watch asks a jar under its limit whatever the source, the setting
maxAgeMinutes: 60,
ageChecked: true,
alert: null,
- login: "profile",
cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: false },
// What the guard says of a person's job: allowed, in every case below.
allowed: true,
@@ -399,7 +398,7 @@ test("M1: the watch asks a jar under its limit whatever the source, the setting
// The control: a fresh jar ticks.
assert.equal(await ask({}), null);
// Added scope R2: X's job cap is reached — a pause like a cooldown's (the tick is skipped, no strike, it goes on by itself), not the jar's.
- const cap = "X's job cap is reached for this login: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …";
+ const cap = "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …";
assert.deepEqual(await ask({ allowed: false, reason: cap, cap: { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true } } as never), { reason: "cooldown", sentence: cap });
assert.deepEqual(await ask({ allowed: false, reason: "X's job count cannot be read (f): no X job starts while it is unreadable", cap: { lastHour: 0, perHour: 12, lastDay: 0, perDay: 150, reached: true, unreadable: true } } as never), {
reason: "cooldown",
diff --git a/common/controller/xTrendingWatch.ts b/common/controller/xTrendingWatch.ts
@@ -113,6 +113,10 @@ export type WatchRefusalDeps = {
// Whether settings.json can be read at all.
settingsReadable?: () => boolean;
held?: (paths: Paths, now: number) => Promise<string | null>;
+ // False: the job asked about does not count against X's job cap (a
+ // library's media-only capture, lib/xJobRule.ts xJobCounts — review 2,
+ // ruling R-a), so the cap does not hold it. Every other rule here does.
+ counts?: boolean;
};
function settingsCanBeRead(): boolean {
@@ -138,7 +142,7 @@ function settingsCanBeRead(): boolean {
// 60 minutes) — an age that cannot be read, or is negative (a clock set
// back), refuses — and never when settings cannot be read.
export async function watchRefusal(paths: Paths, slug: string, now: number, deps: WatchRefusalDeps = {}): Promise<WatchRefusal | null> {
- const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now });
+ const report = await (deps.report ?? xSessionReport)({ paths, channelSlug: slug, now, ...(deps.counts === false ? { counts: false } : {}) });
if (!report.hasProfile) {
return {
reason: "no-profile",
@@ -173,7 +177,7 @@ export async function watchRefusal(paths: Paths, slug: string, now: number, deps
// X'S JOB CAP IS REACHED (lib/xJobRule.ts): like a cooldown — the tick is
// skipped, the watch waits, and it goes on by itself once the cap has room.
// Not the jar's fault and not a failed read.
- if (!report.allowed && report.cap.reached && report.alert === null && /^X's job (cap|count)/.test(report.reason ?? "")) {
+ if (deps.counts !== false && !report.allowed && report.cap.reached && report.alert === null && /^X's job (cap|count)/.test(report.reason ?? "")) {
return { reason: "cooldown", sentence: report.reason ?? "X's job cap is reached." };
}
// Whatever else the guard would refuse a person's job for.
diff --git a/common/jobs/instagramSchedule.test.ts b/common/jobs/instagramSchedule.test.ts
@@ -76,7 +76,7 @@ test("an Instagram channel told only by its URL (no platform in its config) is h
// Added scope R2 (lane x-followups): X's job cap is reached — the scheduler skips X's channels, like a cooldown.
test("R2b: while X's job cap is reached every X posts channel is skipped with the sentence and takes no slot; Instagram is not X's business", async () => {
const { xSyncHold } = await import("./syncScheduler");
- const CAP = "X's job cap is reached for this login: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …";
+ const CAP = "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); …";
const r = selectDueChannels({ ...base, xCapHeld: CAP });
assert.ok(!r.due.includes("x-chan"));
assert.ok(r.due.includes("ig-ready"));
diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts
@@ -3,6 +3,7 @@ import { readFile, writeFile } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type { JobRecord, JobStatus } from "./registry";
import { parseJobSpec, type JobSpec } from "./jobSpec";
+import { X_QUEUE_KEY } from "../lib/xJobRule";
// A serializable sidecar (`<id>.meta.json`) written alongside each job's
// `<id>.log`. The in-memory registry keeps only the 100 most-recent finished
@@ -44,6 +45,13 @@ export type JobMeta = {
// On an interrupted job's meta: the job that resumed it. Written only by the
// resume pass, so it is never resumed twice.
resumedAs?: string;
+ // The starts X's job cap counted this job for (JobRecord.xStarts): written
+ // on every meta of X's queue, [] for a job that counted none, so the count
+ // can be rebuilt from the records (jobs/xJobCap.ts). Absent on metas from
+ // before it.
+ xStarts?: number[];
+ // The job ended deferred by X's job cap (JobRecord.deferred).
+ deferred?: { until: number; sentence: string };
};
export function metaPath(paths: Paths, id: string): string {
@@ -74,6 +82,8 @@ export async function writeJobMeta(
...(record.handedOffTo ? { handedOffTo: record.handedOffTo } : {}),
...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
...(record.resumeCount ? { resumeCount: record.resumeCount } : {}),
+ ...(record.queueKey === X_QUEUE_KEY ? { xStarts: [...(record.xStarts ?? [])] } : {}),
+ ...(record.deferred ? { deferred: { ...record.deferred } } : {}),
};
await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8");
} catch {
@@ -105,6 +115,9 @@ export async function readJobMeta(
if (m.handedOffTo !== undefined && typeof m.handedOffTo !== "string") delete meta.handedOffTo;
if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom;
if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs;
+ if (m.xStarts !== undefined && !(Array.isArray(m.xStarts) && m.xStarts.every((t) => typeof t === "number" && Number.isFinite(t)))) delete meta.xStarts;
+ const d = m.deferred as { until?: unknown; sentence?: unknown } | undefined;
+ if (d !== undefined && !(d && typeof d === "object" && typeof d.until === "number" && typeof d.sentence === "string")) delete meta.deferred;
if (
m.resumeCount !== undefined &&
!(typeof m.resumeCount === "number" && Number.isInteger(m.resumeCount) && m.resumeCount > 0)
diff --git a/common/jobs/listJobs.ts b/common/jobs/listJobs.ts
@@ -37,6 +37,9 @@ export type JobListEntry = {
cancelReason?: string;
// The job this one handed its work on to (JobRecord.handedOffTo).
handedOffTo?: string;
+ // The job ended `done` DEFERRED by X's job cap (JobRecord.deferred): it did
+ // not run; when the next X job may start, and the sentence.
+ deferred?: { until: number; sentence: string };
};
export type JobsPage = {
@@ -117,6 +120,7 @@ async function buildEntry(
replayable: Boolean(live_.spec),
detail: jobSpecDetail(live_.kind, live_.spec),
...(live_.handedOffTo ? { handedOffTo: live_.handedOffTo } : {}),
+ ...(live_.deferred ? { deferred: { ...live_.deferred } } : {}),
logPath,
logSize,
};
@@ -149,6 +153,7 @@ async function buildEntry(
? { cancelReason: meta.cancelReason }
: {}),
...(meta.handedOffTo ? { handedOffTo: meta.handedOffTo } : {}),
+ ...(meta.status === "done" && meta.deferred ? { deferred: meta.deferred } : {}),
logPath,
logSize,
};
diff --git a/common/jobs/networkGuard.ts b/common/jobs/networkGuard.ts
@@ -47,8 +47,12 @@ import {
} from "../social/xSessionBroker";
import { resolveXCookieSource, xMaxCookieAgeMinutes, type XCookieSource } from "../social/xCookieSource";
import { jobKindLabel, kindIsNetwork } from "./jobKinds";
-import { xLoginKey, xQueueRefusal } from "../lib/xJobRule";
-import { recordXJobStart, xJobCapStatus } from "../lib/xJobCap-server";
+import { xJobCounts, xQueueRefusal, type XJobPlan } from "../lib/xJobRule";
+import { isXTrendingChannel } from "../lib/xTrending/config";
+import { recordXJobStart, xJobCapStatus } from "./xJobCap";
+import { writeJobMeta } from "./jobMeta";
+import type { JobSpec } from "./jobSpec";
+import { getRegistry } from "./registry";
import { queueGapClock, queueGapPlatform } from "./queueGap";
export type NetworkJobOpts = {
@@ -62,6 +66,9 @@ export type NetworkJobOpts = {
// guards before it — at enqueue, and at the start before the queue's gap —
// only look.
countStart?: boolean;
+ // The job's replay descriptor — what its function runs with. X's job cap
+ // reads its PLAN from it (lib/xJobRule.ts xJobCounts): never a flag.
+ spec?: JobSpec;
};
// ── 1. the empty queue ─────────────────────────────────────────────────────
@@ -200,11 +207,11 @@ async function channelCookieSpec(paths: Paths, slug: string | undefined, setting
return resolveCookiePolicy(settings, config).cookies;
}
-// `login`: the X login the job would use, as X's job count names it.
-// `capped`: the refusal is the job cap's (no cookie banner is raised for it).
+// `capped`: the refusal is the job cap's (no cookie banner is raised for it),
+// with `nextAt`, when the next X job may start.
export type XGuardResult =
- | { ok: true; note?: string; login: string }
- | { ok: false; message: string; alert: boolean; capped?: true };
+ | { ok: true; note?: string }
+ | { ok: false; message: string; alert: boolean; capped?: true; nextAt?: number };
// WHAT AN X JOB WOULD BE TOLD NOW, and why — the fresh-jar rule's inputs and
// its verdict in one record, for `pnpm ops get x-session` (an agent asks it
@@ -230,10 +237,10 @@ export type XSessionReport = {
ageChecked: boolean;
// The X cookie alert, when it is up (a challenge or a login wall).
alert: { raisedAt: string; line: string } | null;
- // X'S JOB CAP (lib/xJobRule.ts): the login the count is kept for, the X
- // jobs started in the last 60 minutes and 24 hours, the caps (constants of
- // the code), and — when the cap is reached — when the next may start.
- login: string;
+ // X'S JOB CAP (lib/xJobRule.ts): the X jobs started ON THIS MACHINE in
+ // the last 60 minutes and 24 hours — one count, whatever the login source,
+ // cookie spec or channel (review 2 M1) — the caps (constants of the code),
+ // and, when the cap is reached, when the next may start.
cap: { lastHour: number; perHour: number; lastDay: number; perDay: number; reached: boolean; nextAt?: string; unreadable?: true };
// Would an X job start now? `reason` is the refusal it would get.
allowed: boolean;
@@ -245,6 +252,10 @@ export async function xSessionReport(opts: {
paths: Paths;
channelSlug?: string;
now?: number;
+ // False: the job asked about does not count against X's job cap (ruling
+ // R-a: xJobCounts), so the cap does not refuse it. The count is reported
+ // all the same.
+ counts?: boolean;
}): Promise<XSessionReport> {
const now = opts.now ?? Date.now();
const status = await readXSessionStatus(opts.paths);
@@ -258,10 +269,9 @@ export async function xSessionReport(opts: {
const ageMinutes = status.cookiesUpdatedAt
? Math.max(0, Math.floor((now - Date.parse(status.cookiesUpdatedAt)) / 60_000))
: null;
- const login = xLoginKey(resolved.source, resolved.browserSpec);
// The count's clock is the queue gap's (jobs/queueGap.ts): the two rules
// that space X jobs read one clock.
- const capStatus = await xJobCapStatus(opts.paths, login, opts.now ?? queueGapClock().now());
+ const capStatus = await xJobCapStatus(opts.paths, opts.now ?? queueGapClock().now());
const cap = {
lastHour: capStatus.lastHour,
perHour: capStatus.perHour,
@@ -273,9 +283,8 @@ export async function xSessionReport(opts: {
};
// The cap refuses whatever else would let the job through.
const capped = <T extends { allowed: boolean; reason: string | null }>(r: T): T =>
- r.allowed && !capStatus.ok ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r;
+ r.allowed && !capStatus.ok && opts.counts !== false ? { ...r, allowed: false, reason: capStatus.sentence ?? "X's job cap is reached." } : r;
const base = {
- login,
cap,
source: resolved.source,
sourceChosen: resolved.chosen,
@@ -317,28 +326,52 @@ export async function xSessionReport(opts: {
// Why no X job starts now BECAUSE OF X'S JOB CAP (or its unreadable count),
// or null: for the scheduler, which then skips X's channels rather than
// queue syncs that would each be refused.
-export async function xCapHeldReason(paths: Paths, now?: number): Promise<string | null> {
- const r = await xSessionReport({ paths, ...(now !== undefined ? { now } : {}) });
- if (!r.cap.reached) return null;
- return (await xJobCapStatus(paths, r.login, now ?? queueGapClock().now())).sentence ?? "X's job cap is reached.";
+export async function xCapHeldReason(paths: Pick<Paths, "transcriptsDir" | "jobsDir">, now?: number): Promise<string | null> {
+ const status = await xJobCapStatus(paths, now ?? queueGapClock().now());
+ return status.ok ? null : (status.sentence ?? "X's job cap is reached.");
}
export async function xJobGuard(opts: {
paths: Paths;
channelSlug?: string;
now?: number;
+ counts?: boolean;
}): Promise<XGuardResult> {
const r = await xSessionReport(opts);
- if (r.allowed) return { ok: true, login: r.login, ...(r.note ? { note: r.note } : {}) };
+ if (r.allowed) return { ok: true, ...(r.note ? { note: r.note } : {}) };
const capped = r.cap.reached && r.alert === null && r.reason !== null && /^X's job (cap|count)/.test(r.reason);
- return { ok: false, message: r.reason ?? "X job refused.", alert: r.alert !== null, ...(capped ? { capped: true as const } : {}) };
+ const nextAt = capped && r.cap.nextAt ? Date.parse(r.cap.nextAt) : undefined;
+ return {
+ ok: false,
+ message: r.reason ?? "X job refused.",
+ alert: r.alert !== null,
+ ...(capped ? { capped: true as const } : {}),
+ ...(nextAt !== undefined && Number.isFinite(nextAt) ? { nextAt } : {}),
+ };
+}
+
+// THE JOB'S PLAN, for X's job cap (lib/xJobRule.ts xJobCounts): its kind, its
+// spec's params, and whether its channel is a trending library (read here,
+// never taken from the caller).
+async function xJobPlanOf(opts: NetworkJobOpts): Promise<XJobPlan> {
+ const params = opts.spec?.params as Record<string, unknown> | undefined;
+ let channel: XJobPlan["channel"];
+ if (opts.channelSlug) {
+ const read = await readJsonFile(path.join(opts.paths.channelsDir, opts.channelSlug, "config.json")).catch(() => null);
+ const config = read?.ok ? channelConfigSchema.parse(read.value) : null;
+ if (config) channel = { library: isXTrendingChannel(config), ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) };
+ }
+ return { kind: opts.kind, ...(params ? { params } : {}), ...(channel ? { channel } : {}) };
}
// ── the one entry point ────────────────────────────────────────────────────
+// `deferUntil`: the refusal is X's job cap, reached — at a job's start the
+// job ends DEFERRED (not failed; review 2, ruling R-b), and this is when the
+// next X job may start.
export type NetworkGuardResult =
| { ok: true; notes: string[] }
- | { ok: false; error: string };
+ | { ok: false; error: string; deferUntil?: number };
// One platform's guard: asked with the job's options, at enqueue and at start.
type PlatformGuard = (opts: NetworkJobOpts & { job?: { id: string } }) => Promise<NetworkGuardResult>;
@@ -348,14 +381,31 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi
// X's queue only, whatever the job and whoever named the queue.
const queue = xQueueRefusal(`${jobKindLabel(opts.kind)}${opts.channelSlug ? ` for ${opts.channelSlug}` : ""}`, opts.queueKey);
if (queue) return { ok: false, error: queue };
- const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug });
+ // WHAT COUNTS (ruling R-a): decided from the job's own plan. A job that
+ // does not count is not refused by the cap either; everything else of X's
+ // guard holds for it.
+ const counts = xJobCounts(await xJobPlanOf(opts));
+ const x = await xJobGuard({ paths: opts.paths, channelSlug: opts.channelSlug, counts });
if (x.ok) {
// THE START, COUNTED: checked and recorded in one step. An X run's own
// start asks X nothing: each of its channels is a start (it is guarded,
// with its slug, before each one).
- if (opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) {
- const counted = await recordXJobStart(opts.paths, x.login, queueGapClock().now());
- if (!counted.ok) return { ok: false, error: counted.sentence ?? "X's job cap is reached." };
+ if (counts && opts.countStart && opts.job && !(opts.kind === "x-run" && !opts.channelSlug)) {
+ const counted = await recordXJobStart(opts.paths, queueGapClock().now());
+ if (!counted.ok) {
+ return {
+ ok: false,
+ error: counted.sentence ?? "X's job cap is reached.",
+ ...(!counted.unreadable && counted.nextAt !== undefined ? { deferUntil: counted.nextAt } : {}),
+ };
+ }
+ // The start on the job's own record (and its sidecar), so a lost count
+ // is rebuilt from the records (jobs/xJobCap.ts).
+ const record = getRegistry().get(opts.job.id);
+ if (record && counted.at !== undefined) {
+ (record.xStarts ??= []).push(counted.at);
+ await writeJobMeta(opts.paths, record);
+ }
}
// The jar passed at a job's START: a jar-age banner from an earlier
// refusal clears. (Not at enqueue — the start follows, and enqueue stays
@@ -375,7 +425,7 @@ async function guardXJob(opts: NetworkJobOpts & { job?: { id: string } }): Promi
...(opts.job ? { job: { id: opts.job.id, kind: opts.kind } } : {}),
});
}
- return { ok: false, error: x.message };
+ return { ok: false, error: x.message, ...(x.capped && x.nextAt !== undefined ? { deferUntil: x.nextAt } : {}) };
}
// Instagram's: its alert, then its cooldown (jobs/instagramGuard.ts).
diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts
@@ -82,7 +82,7 @@ const { runManagedFunction } = await import("./streamCommand");
const { fetchPosts } = await import("../controller/fetchPosts");
const { getSettings } = await import("../lib/settings");
const { setQueueGapClock, clearQueueGaps } = await import("./queueGap");
-const { xJobStartsFile } = await import("../lib/xJobCap-server");
+const { xJobStartsFile } = await import("./xJobCap");
const { readServiceCookieState, serviceCookiesFile } = await import("../lib/serviceCookies-server");
await import("../social/xGalleryDlFetcher");
@@ -127,8 +127,10 @@ async function reset(): Promise<void> {
await rm(RUNS, { force: true });
await rm(serviceCookiesFile(paths), { force: true });
await rm(path.join(paths.jobsDir, "queue-gaps.json"), { force: true });
- // X's job count (lib/xJobCap-server.ts): each test starts from none.
- await rm(xJobStartsFile(paths), { force: true });
+ // X's job count (jobs/xJobCap.ts): each test starts from none. (Deleting
+ // the file would not: it is rebuilt from the earlier tests' job records.)
+ await mkdir(path.dirname(xJobStartsFile(paths)), { recursive: true });
+ await writeFile(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [] }));
}
async function readLog(jobId: string): Promise<string> {
@@ -325,7 +327,7 @@ test("get x-session reports what the guard would answer: source, age, limit, all
assert.equal(fresh.allowed, true);
assert.equal(fresh.reason, null);
assert.equal(fresh.profileDir, path.join(transcripts, ".x-session", "profile"));
- assert.deepEqual(await xJobGuard({ paths }), { ok: true, login: "profile" });
+ assert.deepEqual(await xJobGuard({ paths }), { ok: true });
await writeJar(2 * 60 * 60_000);
const stale = await xSessionReport({ paths });
@@ -352,7 +354,7 @@ test("a network job is never run unqueued: the override \"\" is refused", async
// ── added scope R2 (lane x-followups): X's queue only, and X's job cap ─────
const { guardNetworkJob, jobAsksX, xSessionReport: xReport } = await import("./networkGuard");
-const { recordXJobStart, xJobCapStatus } = await import("../lib/xJobCap-server");
+const { recordXJobStart, xJobCapStatus } = await import("./xJobCap");
const { xQueueRefusal } = await import("../lib/xJobRule");
const { runInJobContext } = await import("../lib/jobContext");
@@ -390,23 +392,22 @@ test("R2b: X's job cap — the 13th X job in an hour is refused before it starts
await writeJar(5 * 60_000);
const before = await runCount();
// Eleven starts on record, of whatever kinds; then one fetch through the funnel is the twelfth.
- for (let i = 0; i < 11; i++) await recordXJobStart(paths, "profile", fakeNow);
+ for (let i = 0; i < 11; i++) await recordXJobStart(paths, fakeNow);
const twelfth = await fetchJob(SLUGS[0], new Map());
assert.equal(twelfth.ok, true, twelfth.ok ? "" : twelfth.error);
if (twelfth.ok) assert.equal((await twelfth.done).status, "done");
- assert.equal((await xJobCapStatus(paths, "profile", fakeNow)).lastHour, 12);
+ assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12);
// The thirteenth, of ANOTHER kind: refused at enqueue, no job at all, with when the next may start.
for (const [kind, slug] of [["fetch-posts", SLUGS[1]], ["capture-posts", SLUGS[1]], ["check-post-availability", SLUGS[2]], ["import-post", SLUGS[2]], ["read-x-trending", undefined], ["x-run", undefined]] as const) {
const res = await runManagedFunction({ kind, queueKey: "platform:twitter", paths, ...(slug ? { channelSlug: slug } : {}), fn: async () => assert.fail("the job ran") });
assert.equal(res.ok, false, kind);
- assert.match(res.ok ? "" : res.error, /^X's job cap is reached for this login: 12 X jobs started in the last 60 minutes \(the cap is 12\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind);
+ assert.match(res.ok ? "" : res.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes \(the cap is 12\)\. The next X job may start at \d\d:\d\d UTC \(in \d+ min\); ask again then/, kind);
}
assert.equal(await runCount(), before + 1);
// The cap raises no cookie banner: it is not the jar's fault.
assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined);
// get x-session: the count, the caps, and the refusal.
const report = await xReport({ paths });
- assert.equal(report.login, "profile");
assert.equal(report.allowed, false);
assert.deepEqual({ ...report.cap, nextAt: typeof report.cap.nextAt }, { lastHour: 12, perHour: 12, lastDay: 12, perDay: 150, reached: true, nextAt: "string" });
assert.match(report.reason ?? "", /^X's job cap is reached/);
@@ -421,7 +422,7 @@ test("R2b: X's job cap — the 13th X job in an hour is refused before it starts
test("R2b: the start is counted once, by the last guard before the work; a look counts nothing; a job that met the cap while it waited is refused at its start", async () => {
await reset();
await writeJar(5 * 60_000);
- const count = async () => (await xJobCapStatus(paths, "profile", fakeNow)).lastHour;
+ const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour;
const job = { id: "job-1" };
const opts = { kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0] };
// Enqueue, and the start's first guard: looks.
@@ -440,7 +441,7 @@ test("R2b: the start is counted once, by the last guard before the work; a look
assert.equal((await guardNetworkJob({ kind: "reparse-x-trending", queueKey: "platform:twitter", paths, job, countStart: true })).ok, true);
assert.equal(await count(), 2);
// The cap fills while a job waits its turn: its start is refused, and the refused start is not counted.
- for (let i = 0; i < 10; i++) await recordXJobStart(paths, "profile", fakeNow);
+ for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow);
const late = await guardNetworkJob({ ...opts, job, countStart: true });
assert.equal(late.ok, false);
assert.match(late.ok ? "" : late.error, /^X's job cap is reached/);
@@ -453,3 +454,144 @@ test("R2b: the start is counted once, by the last guard before the work; a look
}
await reset();
});
+
+// ── review 2 (lane x-followups): one bucket, what counts, deferred ─────────
+
+const { getRegistry } = await import("./registry");
+const { readJobMeta } = await import("./jobMeta");
+
+async function writeSettings(x: Record<string, unknown>, top: Record<string, unknown> = {}): Promise<void> {
+ await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ ...top, social: { x } }));
+}
+async function channelSpec(slug: string, spec: string | undefined): Promise<void> {
+ const file = path.join(transcripts, "channels", slug, "config.json");
+ const config = JSON.parse(await readFile(file, "utf8"));
+ if (spec === undefined) delete config.cookiesFromBrowser;
+ else config.cookiesFromBrowser = spec;
+ await writeFile(file, JSON.stringify(config));
+}
+
+test("M1: ONE count for the machine — a flipped login source, a respelled cookie spec, a channel's own spec and an X run over channels of different specs all fill the same cap", async () => {
+ await reset();
+ await writeJar(5 * 60_000);
+ const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour;
+ const start = (kind: string, slug: string) => guardNetworkJob({ kind, queueKey: "platform:twitter", paths, channelSlug: slug, job: { id: `m1-${kind}-${slug}` }, countStart: true });
+ try {
+ // Three starts on the connected profile.
+ for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true);
+ assert.equal(await count(), 3);
+ // The login source flipped to the browser: the same count, not a fresh one.
+ await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" });
+ assert.equal((await xReport({ paths })).cap.lastHour, 3);
+ for (let i = 0; i < 3; i++) assert.equal((await start("fetch-posts", SLUGS[0])).ok, true);
+ assert.equal(await count(), 6);
+ // The same browser spelled another way: still the same count.
+ await writeSettings({ cookieSource: "browser" }, { cookiesFromBrowser: " firefox:default " });
+ assert.equal((await xReport({ paths })).cap.lastHour, 6);
+ assert.equal((await start("capture-posts", SLUGS[1])).ok, true);
+ // A channel with a cookie spec of its own: the same count.
+ await channelSpec(SLUGS[2], "chromium");
+ assert.equal((await xReport({ paths, channelSlug: SLUGS[2] })).cap.lastHour, 7);
+ assert.equal((await start("check-post-availability", SLUGS[2])).ok, true);
+ // An X run over channels of different specs: each channel one start, in the one count.
+ await channelSpec(SLUGS[3], "brave");
+ await channelSpec(SLUGS[4], "chromium:Profile 2");
+ for (const slug of [SLUGS[3], SLUGS[4], SLUGS[5], SLUGS[6]]) assert.equal((await start("x-run", slug)).ok, true);
+ assert.equal(await count(), 12);
+ // The thirteenth is refused whatever it uses.
+ for (const [x, top, slug] of [
+ [{ cookieSource: "profile" }, {}, SLUGS[7]],
+ [{ cookieSource: "browser" }, { cookiesFromBrowser: "firefox" }, SLUGS[7]],
+ [{ cookieSource: "browser" }, { cookiesFromBrowser: "safari" }, SLUGS[3]],
+ ] as const) {
+ await writeSettings(x, top);
+ const refused = await start("fetch-posts", slug);
+ assert.equal(refused.ok, false);
+ assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/);
+ }
+ // get x-session names no login: the count is the machine's.
+ const report = await xReport({ paths });
+ assert.equal("login" in report, false);
+ assert.deepEqual([report.cap.lastHour, report.cap.reached], [12, true]);
+ } finally {
+ await writeSettings({ cookieSource: "profile" });
+ for (const slug of [SLUGS[2], SLUGS[3], SLUGS[4]]) await channelSpec(slug, undefined);
+ await reset();
+ }
+});
+
+test("R-a: a trending library's media-only capture is not counted and not refused by the cap; its keep capture and a capture with shots are", async () => {
+ await reset();
+ await writeJar(5 * 60_000);
+ const lib = "x-trending-lib";
+ await mkdir(path.join(transcripts, "channels", lib), { recursive: true });
+ await writeFile(
+ path.join(transcripts, "channels", lib, "config.json"),
+ JSON.stringify({ handling: "transcribe", sourceKind: "social", platform: "twitter", name: lib, xTrending: {} }),
+ );
+ const mediaOnly = { ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true };
+ const capture = (params: Record<string, unknown>, countStart = true) =>
+ guardNetworkJob({ kind: "capture-posts", queueKey: "platform:twitter", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params }, job: { id: "ra" }, ...(countStart ? { countStart: true } : {}) });
+ const count = async () => (await xJobCapStatus(paths, fakeNow)).lastHour;
+ assert.equal((await capture(mediaOnly)).ok, true);
+ assert.equal(await count(), 0, "the media-only capture is not a start");
+ assert.equal((await capture({ ...mediaOnly, keptMedia: true })).ok, true);
+ assert.equal((await capture({ ...mediaOnly, shots: true })).ok, true);
+ assert.equal(await count(), 2, "the keep capture and the capture with shots are");
+ // The cap reached: the media-only capture still starts (it asks x.com nothing); the others are refused.
+ for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow);
+ assert.equal((await capture(mediaOnly, false)).ok, true);
+ assert.equal((await capture(mediaOnly)).ok, true);
+ for (const params of [{ ...mediaOnly, keptMedia: true }, { ...mediaOnly, shots: true }, { ...mediaOnly, articles: undefined }]) {
+ const refused = await capture(params, false);
+ assert.equal(refused.ok, false);
+ assert.match(refused.ok ? "" : refused.error, /^X's job cap is reached/);
+ }
+ // It still meets the rest of X's guard: the queue, and the jar.
+ const moved = await guardNetworkJob({ kind: "capture-posts", queueKey: "manual", paths, channelSlug: lib, spec: { kind: "capture-posts", slug: lib, params: mediaOnly } });
+ assert.equal(moved.ok, false);
+ await writeJar(5 * 60 * 60_000);
+ const stale = await capture(mediaOnly, false);
+ assert.equal(stale.ok, false);
+ assert.doesNotMatch(stale.ok ? "" : stale.error, /job cap/);
+ await rm(path.join(transcripts, "channels", lib), { recursive: true, force: true });
+ await reset();
+});
+
+test("R-b: a job that meets the cap AT ITS START ends deferred — done, not failed, the sentence and when the next may start, no banner, nothing asked", async () => {
+ await reset();
+ await writeJar(5 * 60_000);
+ const before = await runCount();
+ // An X job holds the queue (it is the first start).
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const blocker = await runManagedFunction({ kind: "fetch-posts", queueKey: "platform:twitter", paths, channelSlug: SLUGS[0], fn: async () => gate });
+ assert.equal(blocker.ok, true);
+ for (let i = 0; i < 100 && (await xJobCapStatus(paths, fakeNow)).lastHour < 1; i++) await new Promise((r) => setTimeout(r, 20));
+ // Ten more: eleven. The next passes its enqueue (a slot is left)…
+ for (let i = 0; i < 10; i++) await recordXJobStart(paths, fakeNow);
+ const late = await fetchJob(SLUGS[1], new Map());
+ assert.equal(late.ok, true, late.ok ? "" : late.error);
+ // …and the cap fills while it waits behind the first.
+ await recordXJobStart(paths, fakeNow);
+ release();
+ if (!blocker.ok || !late.ok) return;
+ await blocker.done;
+ const end = await late.done;
+ assert.equal(end.status, "done");
+ const record = getRegistry().get(late.jobId)!;
+ assert.ok(record.deferred, "the record says it was deferred");
+ assert.match(record.deferred!.sentence, /^X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes/);
+ assert.equal(record.deferred!.until, (await xJobCapStatus(paths, fakeNow)).nextAt);
+ assert.match(await readLog(late.jobId), /^\[deferred\] X's job cap is reached/m);
+ assert.doesNotMatch(await readLog(late.jobId), /^\[error\]/m);
+ const meta = await readJobMeta(paths, late.jobId);
+ assert.deepEqual([meta?.status, meta?.deferred?.until, meta?.xStarts], ["done", record.deferred!.until, []]);
+ // Nothing was asked, no start was counted, and no cookie banner was raised.
+ assert.equal(await runCount(), before);
+ assert.equal((await xJobCapStatus(paths, fakeNow)).lastHour, 12);
+ assert.equal((await readServiceCookieState(paths)).services.x?.raisedAt, undefined);
+ // The first job's own record carries its start (the count can be rebuilt from it).
+ assert.equal((await readJobMeta(paths, blocker.jobId))?.xStarts?.length, 1);
+ await reset();
+});
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -181,6 +181,15 @@ export type JobRecord = {
resumeCount?: number;
// The line the job's log opens with when it is a resume (what it resumes).
resumeNote?: string;
+ // X'S JOB CAP (lib/xJobRule.ts, jobs/xJobCap.ts): the starts this job was
+ // counted for (one for a job; one per channel for an X run). Kept on its
+ // sidecar, so a count file that is lost is rebuilt from the records.
+ xStarts?: number[];
+ // A JOB THAT ENDED DEFERRED (review 2, ruling R-b): X's job cap was reached
+ // when its queue started it, so it did not run — not a failure. It ends
+ // `done` with this: the sentence, and when the next X job may start.
+ // Nothing re-queues it by itself.
+ deferred?: { until: number; sentence: string };
};
// Store a progress snapshot on the record, stamping `progressAt` only when the
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -419,6 +419,18 @@ async function refuseForUnreachableMedia(
}
}
+// A job its queue started that may not run yet (X's job cap): it ends
+// deferred, not failed (JobRecord.deferred).
+export class JobDeferredError extends Error {
+ constructor(
+ message: string,
+ readonly until: number,
+ ) {
+ super(message);
+ this.name = "JobDeferredError";
+ }
+}
+
export async function runManagedFunction(
opts: RunManagedFunctionOpts,
): Promise<StreamActionResult> {
@@ -532,7 +544,7 @@ export async function runManagedFunction(
const network = opts.network !== false && kindIsNetwork(opts.kind);
const guard = async (countStart = false) => {
const res = await guardNetworkJob({ ...opts, job: { id }, ...(countStart ? { countStart: true } : {}) });
- if (!res.ok) throw new Error(res.error);
+ if (!res.ok) throw res.deferUntil !== undefined ? new JobDeferredError(res.error, res.deferUntil) : new Error(res.error);
return res.notes;
};
const run = async () => {
@@ -589,6 +601,15 @@ export async function runManagedFunction(
registry.finalize(id, "cancelled");
return;
}
+ // X'S JOB CAP, MET AT THE START (review 2, ruling R-b): the job did
+ // not run and did not fail. It ends `done`, DEFERRED, with the
+ // sentence and when the next X job may start; nothing re-queues it.
+ if (err instanceof JobDeferredError) {
+ record.deferred = { until: err.until, sentence: err.message };
+ onLog(`[deferred] ${err.message}`);
+ registry.finalize(id, "done");
+ return;
+ }
onLog(`[error] ${(err as Error).message}`);
// A job that met a stale service's cookies (a cookie refresh alert)
// ends naming the cause and the fix, after its own error line.
diff --git a/common/jobs/syncScheduler.test.ts b/common/jobs/syncScheduler.test.ts
@@ -7,7 +7,7 @@ import {
} from "../lib/channelPriority";
import { defaultSyncScheduler } from "../lib/settings";
import type { SyncSchedulerSettings } from "../lib/settings";
-import { emptySchedulerState } from "./syncSchedulerState";
+import { emptyChannelSyncState, emptySchedulerState } from "./syncSchedulerState";
import {
buildScheduleView,
selectDueChannels,
@@ -15,6 +15,7 @@ import {
syncJitterMs,
SYNC_JITTER_CAP_MS,
nextEligibleAfterFailure,
+ foldScheduledSyncOutcome,
} from "./syncScheduler";
// Run with:
@@ -294,3 +295,37 @@ test("a remote-only channel never syncs, even with a url, and the console says s
const view = buildScheduleView({ channels, scheduler: scheduler(), state: emptySchedulerState(), now: NOW, priority: NO_MODEL });
assert.deepEqual(view.map((v) => [v.slug, v.autoSyncEligible]), [["own", true], ["remote", false]]);
});
+
+// REVIEW 2, RULING R-b (lane x-followups): a scheduled sync X's job cap
+// deferred at its start did not run. It is no failure (no strike, no growing
+// backoff) and no success, and nothing queues it again before the next X job
+// may start.
+test("R-b: a sync deferred by X's job cap is not a failure, and the channel waits until the time the next X job may start", () => {
+ const sched = scheduler({ backoffBaseMinutes: 10, backoffMaxMinutes: 600 });
+ const now = NOW;
+ const until = now + 40 * 60_000;
+ const cs = { ...emptyChannelSyncState(), consecutiveFailures: 2, lastQueuedJobId: "j1", lastOutcome: "failed" as const, lastOutcomeAt: now - 3_600_000 };
+ assert.equal(foldScheduledSyncOutcome(cs, { status: "done", endedAt: now, deferred: { until } }, now, sched, 0), true);
+ assert.deepEqual(
+ { f: cs.consecutiveFailures, next: cs.nextEligibleAt, job: cs.lastQueuedJobId, outcome: cs.lastOutcome, at: cs.lastOutcomeAt },
+ { f: 2, next: until, job: null, outcome: "failed", at: now - 3_600_000 },
+ );
+ // The scheduler does not pick it before then — and does after.
+ const state = { ...emptySchedulerState(), channels: { "x-chan": cs } };
+ const pick = (at: number) => selectDueChannels({ channels: [channel("x-chan", DAY)], scheduler: sched, state, activeSlugs: new Set<string>(), now: at, priority: NO_MODEL }).due.map((d) => (typeof d === "string" ? d : (d as { slug: string }).slug));
+ assert.deepEqual(pick(until - 1), []);
+ assert.deepEqual(pick(until + 1), ["x-chan"]);
+ // A plain end is folded as before: done resets, failed grows, cancelled is neutral, queued/running wait.
+ const done = { ...emptyChannelSyncState(), consecutiveFailures: 2, lastQueuedJobId: "j" };
+ foldScheduledSyncOutcome(done, { status: "done", endedAt: now }, now, sched, 0);
+ assert.deepEqual([done.consecutiveFailures, done.nextEligibleAt, done.lastOutcome], [0, null, "ok"]);
+ const failed = { ...emptyChannelSyncState(), lastQueuedJobId: "j" };
+ foldScheduledSyncOutcome(failed, { status: "failed", endedAt: now }, now, sched, 0);
+ assert.deepEqual([failed.consecutiveFailures, failed.nextEligibleAt, failed.lastOutcome], [1, nextEligibleAfterFailure(now, 1, sched, 0), "failed"]);
+ const cancelled = { ...emptyChannelSyncState(), lastQueuedJobId: "j" };
+ foldScheduledSyncOutcome(cancelled, { status: "cancelled" }, now, sched, 0);
+ assert.deepEqual([cancelled.consecutiveFailures, cancelled.nextEligibleAt, cancelled.lastQueuedJobId], [0, null, null]);
+ const running = { ...emptyChannelSyncState(), lastQueuedJobId: "j" };
+ assert.equal(foldScheduledSyncOutcome(running, { status: "running" }, now, sched, 0), false);
+ assert.equal(running.lastQueuedJobId, "j");
+});
diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts
@@ -10,7 +10,7 @@ import {
tierOrder,
} from "../lib/channelPriority";
import { resolveFullSweepIntervalMinutes } from "./deepSync";
-import type { SchedulerSkip, SchedulerState } from "./syncSchedulerState";
+import type { ChannelSyncState, SchedulerSkip, SchedulerState } from "./syncSchedulerState";
import { jitterUp, stableUnit } from "../lib/jitter.mjs";
// Pure, side-effect-free scheduling logic for the cron-driven sync system. It
@@ -150,6 +150,38 @@ export function isInQuietHours(
return hour >= start || hour < end;
}
+// ONE SCHEDULED SYNC'S END, FOLDED INTO ITS CHANNEL'S BACKOFF (the tick's
+// reconcile, editor/app/scheduler/runTick.ts). `done` resets the failures;
+// `failed` grows them and the backoff; `cancelled` is neutral. A job that
+// ended DEFERRED by X's job cap (review 2, ruling R-b: it did not run) is no
+// failure and no success: the failures stay as they were, and the channel is
+// not eligible again before the time the next X job may start — nothing
+// re-queues it earlier. True when the job had ended (and was folded).
+export function foldScheduledSyncOutcome(
+ cs: ChannelSyncState,
+ job: { status: string; endedAt?: number; deferred?: { until: number } },
+ now: number,
+ scheduler: SyncSchedulerSettings,
+ spread: number,
+): boolean {
+ if (job.status === "queued" || job.status === "running") return false;
+ if (job.status === "done" && job.deferred) {
+ cs.nextEligibleAt = Math.max(cs.nextEligibleAt ?? 0, job.deferred.until);
+ } else if (job.status === "done") {
+ cs.consecutiveFailures = 0;
+ cs.nextEligibleAt = null;
+ cs.lastOutcome = "ok";
+ cs.lastOutcomeAt = job.endedAt ?? now;
+ } else if (job.status === "failed") {
+ cs.consecutiveFailures += 1;
+ cs.nextEligibleAt = nextEligibleAfterFailure(now, cs.consecutiveFailures, scheduler, spread);
+ cs.lastOutcome = "failed";
+ cs.lastOutcomeAt = job.endedAt ?? now;
+ }
+ cs.lastQueuedJobId = null;
+ return true;
+}
+
// Exponential backoff (minutes) after N consecutive failures: base * 2^(N-1),
// capped at max. 0 failures => no backoff.
export function backoffMinutes(
diff --git a/common/jobs/xJobCap.test.ts b/common/jobs/xJobCap.test.ts
@@ -0,0 +1,188 @@
+// 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 { 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<typeof corpus>) => JSON.parse(readFileSync(xJobStartsFile(paths), "utf8"));
+const meta = (paths: ReturnType<typeof corpus>, m: Record<string, unknown>, 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;
+};
+
+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 < 12; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true);
+ const refused = await recordXJobStart(paths, T0 + 12 * MIN);
+ assert.equal(refused.ok, false);
+ assert.match(refused.sentence ?? "", /^X's job cap is reached on this machine: 12 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, 12);
+ // "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, 12, 12, T0 + 60 * MIN]);
+ // A start recorded with the clock set back is recorded no earlier than the latest on record.
+ const p2 = corpus("disk-back");
+ await recordXJobStart(p2, T0);
+ await recordXJobStart(p2, T0 - 600 * MIN);
+ assert.deepEqual(fileOf(p2).starts, [T0, T0]);
+ // 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: 12 }, (_, i) => recordXJobStart(p3, T0 + i)));
+ assert.equal(fileOf(p3).starts.length, 12);
+ 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 });
+ // 7 starts under the profile, 5 under a browser spec: the same machine's twelve.
+ const logins = {
+ profile: Array.from({ length: 7 }, (_, i) => T0 + i * MIN),
+ "browser:firefox": Array.from({ length: 5 }, (_, 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, 12]);
+ assert.equal(fileOf(paths).version, 2);
+ assert.equal(fileOf(paths).starts.length, 12);
+ 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: 12, 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");
+ // 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");
+ 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<typeof corpus>, 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);
+ }
+ }
+});
diff --git a/common/jobs/xJobCap.ts b/common/jobs/xJobCap.ts
@@ -0,0 +1,220 @@
+// X'S JOB COUNT, ON DISK (lane x-followups, R2; review 2 M1 and ruling R-c):
+// every counted X job's start on this machine, ONE list, in
+// `<transcripts>/.x-session/job-starts.json`:
+// { "version": 2, "starts": [<ms>, …] }
+// The rule and its numbers are lib/xJobRule.ts. Here:
+// - the file is read and written under its lock (one check-and-record at a
+// time) and survives a restart;
+// - ONE BUCKET: the count is the machine's, whatever login source, cookie
+// spec or channel a job uses. A file of the first shape (version 1, one
+// list per login key) is read as the SUM of its lists and rewritten as one;
+// - it FAILS CLOSED: a file that is there and cannot be read or parsed
+// refuses every X job until it is repaired;
+// - A FILE THAT IS NOT THERE IS NOT AN EMPTY COUNT (ruling R-c): the last
+// 24 hours of counted starts are rebuilt from the job records (each job's
+// `<id>.meta.json` carries the starts it was counted for, `xStarts`) and
+// written. When X jobs ran (X's queue gap names an end in the last day)
+// but their records cannot be read — the directory refuses, a record of
+// the day is unreadable, or none is left — every X job is refused. A
+// corpus where no X job ever ran starts at zero.
+//
+// SERVER-ONLY (node:fs). In jobs/ (not lib/) because it reads the job records.
+
+import path from "node:path";
+import { readdir, readFile } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+import {
+ X_JOB_CAP,
+ X_QUEUE_KEY,
+ xCapClock,
+ xJobCapSentence,
+ xJobCapUnreadableSentence,
+ xJobCapUnrebuildableSentence,
+ xJobCapVerdict,
+ xJobCounts,
+ type XJobCapVerdict,
+} from "../lib/xJobRule";
+import { kindIsNetwork } from "./jobKinds";
+import { QUEUE_GAPS_FILE } from "./queueGap";
+import { jobIdTime } from "./ulid";
+
+type CapPaths = Pick<Paths, "transcriptsDir" | "jobsDir">;
+
+export function xJobStartsFile(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, ".x-session", "job-starts.json");
+}
+
+type StartsFile = { version: 2; starts: number[] };
+
+const finite = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);
+
+// The file as it is: absent, unreadable (fail closed), or its starts (a
+// version-1 file's lists summed into one — `migrated`).
+async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { state: "bad" } | { state: "ok"; starts: number[]; migrated: boolean }> {
+ const read = await readJsonFile(xJobStartsFile(paths));
+ if (!read.ok) return read.reason === "absent" ? { state: "absent" } : { state: "bad" };
+ const v = read.value as { version?: unknown; starts?: unknown; logins?: unknown } | null;
+ if (!v || typeof v !== "object") return { state: "bad" };
+ if (v.version === 2) {
+ if (!Array.isArray(v.starts) || !v.starts.every(finite)) return { state: "bad" };
+ return { state: "ok", starts: [...v.starts], migrated: false };
+ }
+ if (v.version === 1) {
+ // THE FIRST SHAPE, ONE LIST PER LOGIN KEY: every login's starts are the
+ // machine's, so they are summed.
+ if (!v.logins || typeof v.logins !== "object" || Array.isArray(v.logins)) return { state: "bad" };
+ const starts: number[] = [];
+ for (const list of Object.values(v.logins as Record<string, unknown>)) {
+ if (!Array.isArray(list) || !list.every(finite)) return { state: "bad" };
+ starts.push(...list);
+ }
+ return { state: "ok", starts: starts.sort((a, b) => a - b), migrated: true };
+ }
+ return { state: "bad" };
+}
+
+// ── the rebuild (ruling R-c) ───────────────────────────────────────────────
+
+export type XJobStartsRebuild =
+ | { ok: true; starts: number[]; records: number }
+ | { ok: false; why: string; until?: number };
+
+// The last day's counted X starts, from the job records. A record written by
+// this code says its starts (`xStarts`, [] for an X job that counted none); a
+// record of X's queue from before it is counted once at its start when its
+// kind and plan count (lib/xJobRule.ts xJobCounts) — more rather than fewer.
+export async function rebuildXJobStarts(paths: Pick<Paths, "jobsDir">, now: number): Promise<XJobStartsRebuild> {
+ const since = now - X_JOB_CAP.dayMs;
+ // The evidence that X jobs ran in the last day: X's queue gap's last end.
+ let lastXEnd: number | undefined;
+ const gaps = await readJsonFile(path.join(paths.jobsDir, QUEUE_GAPS_FILE));
+ if (gaps.ok) {
+ const end = (gaps.value as { ends?: Record<string, unknown> } | null)?.ends?.[X_QUEUE_KEY];
+ if (finite(end) && end > since) lastXEnd = end;
+ }
+ const until = lastXEnd !== undefined ? lastXEnd + X_JOB_CAP.dayMs : undefined;
+ let names: string[];
+ try {
+ names = await readdir(paths.jobsDir);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException)?.code;
+ if (code === "ENOENT" || code === "ENOTDIR") return { ok: true, starts: [], records: 0 };
+ return { ok: false, why: `the job records cannot be listed (${code ?? (err as Error).message})`, ...(until ? { until } : {}) };
+ }
+ const starts: number[] = [];
+ let records = 0;
+ for (const name of names) {
+ if (!name.endsWith(".meta.json")) continue;
+ const id = name.slice(0, -".meta.json".length);
+ const born = jobIdTime(id);
+ let m: Record<string, unknown> | null = null;
+ try {
+ const parsed = JSON.parse(await readFile(path.join(paths.jobsDir, name), "utf8")) as unknown;
+ m = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null;
+ } catch {
+ m = null;
+ }
+ if (!m) {
+ // A record of the last day (or of no known day) that cannot be read may
+ // be an X job's: nothing is counted on a guess.
+ if (born === 0 || born > since) return { ok: false, why: `the job record ${name} cannot be read`, ...(until ? { until } : {}) };
+ continue;
+ }
+ if (m.queueKey !== X_QUEUE_KEY) continue;
+ if (Array.isArray(m.xStarts)) {
+ records++;
+ for (const t of m.xStarts) if (finite(t) && t > since) starts.push(t);
+ continue;
+ }
+ // A record from before `xStarts`: once, at its start, when it would count.
+ const kind = typeof m.kind === "string" ? m.kind : "";
+ const at = finite(m.startedAt) ? m.startedAt : undefined;
+ if (!kindIsNetwork(kind) || at === undefined) continue;
+ records++;
+ const spec = m.spec as { params?: Record<string, unknown> } | undefined;
+ // The channel is not read: a record of a library's media-only capture is
+ // counted (more rather than fewer).
+ if (at > since && xJobCounts({ kind, ...(spec?.params ? { params: spec.params } : {}) })) starts.push(at);
+ }
+ // X jobs ran, and not one record of them is left.
+ if (lastXEnd !== undefined && records === 0) {
+ return { ok: false, why: "X's queue ended a job within the last 24 hours and no record of an X job is left", ...(until ? { until } : {}) };
+ }
+ return { ok: true, starts: starts.sort((a, b) => a - b), records };
+}
+
+// ── the count ──────────────────────────────────────────────────────────────
+
+export type XJobCapStatus = XJobCapVerdict & {
+ perHour: number;
+ perDay: number;
+ // The count could not be read or rebuilt: `ok` is false and nothing starts.
+ unreadable?: true;
+ // The refusal, when `ok` is false.
+ sentence?: string;
+};
+
+function statusOf(starts: ReadonlyArray<number>, now: number): XJobCapStatus {
+ const v = xJobCapVerdict(starts, now);
+ return { ...v, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, ...(v.ok ? {} : { sentence: xJobCapSentence(v, now) }) };
+}
+
+function closed(sentence: string): XJobCapStatus {
+ return { ok: false, lastHour: 0, lastDay: 0, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, unreadable: true, sentence };
+}
+
+// What a day can still count (the longer window), as of `now`.
+function keptOf(starts: ReadonlyArray<number>, now: number): number[] {
+ const clock = xCapClock(starts, now);
+ return starts.filter((t) => t > clock - X_JOB_CAP.dayMs);
+}
+
+async function writeStarts(paths: CapPaths, starts: number[]): Promise<void> {
+ await writeJsonAtomic(xJobStartsFile(paths), { version: 2, starts } satisfies StartsFile, { mkdir: true });
+}
+
+// The starts, HOLDING THE FILE'S LOCK: a version-1 file rewritten as one
+// list; an absent one rebuilt from the job records and written; or the
+// refusal's sentence.
+async function loadLocked(paths: CapPaths, now: number): Promise<{ ok: true; starts: number[] } | { ok: false; sentence: string }> {
+ const file = await readStartsFile(paths);
+ if (file.state === "bad") return { ok: false, sentence: xJobCapUnreadableSentence(xJobStartsFile(paths)) };
+ if (file.state === "ok") {
+ if (file.migrated) await writeStarts(paths, keptOf(file.starts, now));
+ return { ok: true, starts: file.starts };
+ }
+ const rebuilt = await rebuildXJobStarts(paths, now);
+ if (!rebuilt.ok) return { ok: false, sentence: xJobCapUnrebuildableSentence(xJobStartsFile(paths), rebuilt.why, rebuilt.until) };
+ await writeStarts(paths, keptOf(rebuilt.starts, now));
+ return { ok: true, starts: rebuilt.starts };
+}
+
+// Would an X job start now? Nothing is counted (a file to migrate or rebuild
+// is written, under the lock).
+export async function xJobCapStatus(paths: CapPaths, now: number = Date.now()): Promise<XJobCapStatus> {
+ const file = await readStartsFile(paths);
+ if (file.state === "ok" && !file.migrated) return statusOf(file.starts, now);
+ if (file.state === "bad") return closed(xJobCapUnreadableSentence(xJobStartsFile(paths)));
+ const loaded = await withJsonFileLock(xJobStartsFile(paths), () => loadLocked(paths, now));
+ return loaded.ok ? statusOf(loaded.starts, now) : closed(loaded.sentence);
+}
+
+// ONE X JOB STARTS: checked and recorded in one step, under the file's lock.
+// `ok: false` — the cap is reached, or the count cannot be read — records
+// nothing, and the job does not start. `at` is the time recorded, never
+// earlier than the latest start on record (xCapClock).
+export async function recordXJobStart(paths: CapPaths, now: number = Date.now()): Promise<XJobCapStatus & { at?: number }> {
+ return withJsonFileLock(xJobStartsFile(paths), async () => {
+ const loaded = await loadLocked(paths, now);
+ if (!loaded.ok) return closed(loaded.sentence);
+ const before = statusOf(loaded.starts, now);
+ if (!before.ok) return before;
+ const at = xCapClock(loaded.starts, now);
+ const starts = [...keptOf(loaded.starts, now), at];
+ await writeStarts(paths, starts);
+ // This start was within the cap: said so, with the count it leaves.
+ const after = statusOf(starts, now);
+ return { ok: true, lastHour: after.lastHour, lastDay: after.lastDay, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, at };
+ });
+}
diff --git a/common/lib/xJobCap-server.ts b/common/lib/xJobCap-server.ts
@@ -1,87 +0,0 @@
-// X'S JOB COUNT, ON DISK (lane x-followups, R2): every X job's start, per X
-// login, in `<transcripts>/.x-session/job-starts.json`:
-// { "version": 1, "logins": { "profile": [<ms>, …], "browser:firefox": […] } }
-// The rule and its numbers are lib/xJobRule.ts. Here: the file is read and
-// written under its lock (one check-and-record at a time), it survives a
-// restart, and it FAILS CLOSED — a file that is there and cannot be read or
-// parsed refuses every X job until it is repaired; only a file that does not
-// exist is an empty count (a fresh install).
-//
-// SERVER-ONLY (node:fs).
-
-import path from "node:path";
-import type { Paths } from "./paths";
-import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server";
-import { X_JOB_CAP, xCapClock, xJobCapSentence, xJobCapUnreadableSentence, xJobCapVerdict, type XJobCapVerdict } from "./xJobRule";
-
-export function xJobStartsFile(paths: Paths): string {
- return path.join(paths.transcriptsDir, ".x-session", "job-starts.json");
-}
-
-type StartsFile = { version: 1; logins: Record<string, number[]> };
-
-async function readStarts(paths: Paths): Promise<{ ok: true; logins: Record<string, number[]> } | { ok: false }> {
- const read = await readJsonFile(xJobStartsFile(paths));
- if (!read.ok) return read.reason === "absent" ? { ok: true, logins: {} } : { ok: false };
- const v = read.value as Partial<StartsFile> | null;
- if (!v || typeof v !== "object" || v.version !== 1 || !v.logins || typeof v.logins !== "object" || Array.isArray(v.logins)) return { ok: false };
- const logins: Record<string, number[]> = {};
- for (const [login, starts] of Object.entries(v.logins)) {
- if (!Array.isArray(starts) || !starts.every((t) => typeof t === "number" && Number.isFinite(t))) return { ok: false };
- logins[login] = [...starts];
- }
- return { ok: true, logins };
-}
-
-export type XJobCapStatus = XJobCapVerdict & {
- login: string;
- perHour: number;
- perDay: number;
- // The count could not be read: `ok` is false and nothing starts.
- unreadable?: true;
- // The refusal, when `ok` is false.
- sentence?: string;
-};
-
-function statusOf(login: string, starts: ReadonlyArray<number>, now: number): XJobCapStatus {
- const v = xJobCapVerdict(starts, now);
- return { ...v, login, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, ...(v.ok ? {} : { sentence: xJobCapSentence(v, now) }) };
-}
-
-function unreadable(paths: Paths, login: string): XJobCapStatus {
- return { ok: false, lastHour: 0, lastDay: 0, login, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, unreadable: true, sentence: xJobCapUnreadableSentence(xJobStartsFile(paths)) };
-}
-
-// Would an X job of this login start now? Nothing is written.
-export async function xJobCapStatus(paths: Paths, login: string, now: number = Date.now()): Promise<XJobCapStatus> {
- const read = await readStarts(paths);
- return read.ok ? statusOf(login, read.logins[login] ?? [], now) : unreadable(paths, login);
-}
-
-// ONE X JOB STARTS: checked and recorded in one step, under the file's lock.
-// `ok: false` — the cap is reached, or the count is unreadable — records
-// nothing, and the job does not start. The time recorded is never earlier
-// than the latest start on record (xCapClock).
-export async function recordXJobStart(paths: Paths, login: string, now: number = Date.now()): Promise<XJobCapStatus> {
- const file = xJobStartsFile(paths);
- return withJsonFileLock(file, async () => {
- const read = await readStarts(paths);
- if (!read.ok) return unreadable(paths, login);
- const starts = read.logins[login] ?? [];
- const before = statusOf(login, starts, now);
- if (!before.ok) return before;
- const at = xCapClock(starts, now);
- // Kept: what the longer window can still count.
- const logins: Record<string, number[]> = {};
- for (const [key, list] of Object.entries(read.logins)) {
- const clock = xCapClock(list, now);
- const kept = list.filter((t) => t > clock - X_JOB_CAP.dayMs);
- if (kept.length || key === login) logins[key] = kept;
- }
- logins[login] = [...(logins[login] ?? []), at];
- await writeJsonAtomic(file, { version: 1, logins } satisfies StartsFile, { mkdir: true });
- // This start was within the cap: said so, with the count it leaves.
- const after = statusOf(login, logins[login], now);
- return { ok: true, lastHour: after.lastHour, lastDay: after.lastDay, login, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay };
- });
-}
diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts
@@ -1,20 +1,14 @@
-// X's two rules (lib/xJobRule.ts) and the count on disk (lib/xJobCap-server.ts).
+// X's two rules (lib/xJobRule.ts) and what counts. The count on disk is jobs/xJobCap.test.ts.
//
// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/xJobRule.test.ts
-import { after, test } from "node:test";
+import { test } from "node:test";
import assert from "node:assert/strict";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
+import { readFileSync } from "node:fs";
import path from "node:path";
-import type { Paths } from "./paths";
import { runInJobContext } from "./jobContext";
-import { X_JOB_CAP, X_QUEUE_KEY, xJobCapSentence, xJobCapVerdict, xJobContextRefusal, xLoginKey, xQueueRefusal } from "./xJobRule";
-import { recordXJobStart, xJobCapStatus, xJobStartsFile } from "./xJobCap-server";
+import { X_JOB_CAP, X_QUEUE_KEY, xJobCapSentence, xJobCapVerdict, xJobContextRefusal, xJobCounts, xQueueRefusal } from "./xJobRule";
-const TMP = mkdtempSync(path.join(tmpdir(), "x-job-rule-"));
-after(() => rmSync(TMP, { recursive: true, force: true }));
-const corpus = (name: string) => ({ transcriptsDir: path.join(TMP, name) }) as unknown as Paths;
const T0 = Date.parse("2026-11-18T12:00:00.000Z");
const MIN = 60_000;
@@ -23,7 +17,7 @@ test("the numbers: 12 X jobs in any 60 minutes, 150 in any 24 hours, and they ar
assert.ok(Object.isFrozen(X_JOB_CAP));
assert.equal(X_QUEUE_KEY, "platform:twitter");
// Nothing in the rule's two modules reads a setting, an environment variable or an option.
- for (const file of ["xJobRule.ts", "xJobCap-server.ts"]) {
+ for (const file of ["xJobRule.ts", "../jobs/xJobCap.ts"]) {
const code = readFileSync(path.join(import.meta.dirname, file), "utf8").replace(/^\s*\/\/.*$/gm, "");
assert.doesNotMatch(code, /process\.env|getSettings|settings\b|\bforce\b/i, file);
}
@@ -36,7 +30,7 @@ test("the hour window: the 13th start in 60 minutes is refused, and says when th
assert.deepEqual(full, { ok: false, lastHour: 12, lastDay: 12, nextAt: T0 + 60 * MIN, window: "hour" });
assert.equal(
xJobCapSentence(full, T0 + 56 * MIN),
- "X's job cap is reached for this login: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); " +
+ "X's job cap is reached on this machine: 12 X jobs started in the last 60 minutes (the cap is 12). The next X job may start at 13:00 UTC (in 4 min); " +
"ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it.",
);
// Rolling: at 13:00 the 12:00 start has left the window (a start exactly 60 minutes old is out).
@@ -73,54 +67,6 @@ test("a clock set back never frees a start early", () => {
assert.equal(xJobCapVerdict(starts, T0 + 60 * MIN).ok, true);
});
-test("the count is on disk: checked and recorded in one step, kept across a restart, per login", async () => {
- const paths = corpus("disk");
- for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, "profile", T0 + i * MIN)).ok, true);
- const refused = await recordXJobStart(paths, "profile", T0 + 12 * MIN);
- assert.equal(refused.ok, false);
- assert.match(refused.sentence ?? "", /^X's job cap is reached for this login: 12 X jobs started in the last 60 minutes/);
- // A refused start records nothing.
- const file = JSON.parse(readFileSync(xJobStartsFile(paths), "utf8"));
- assert.deepEqual(Object.keys(file.logins), ["profile"]);
- assert.equal(file.logins.profile.length, 12);
- // "Restart": nothing is in memory; the file is the count.
- const again = await xJobCapStatus(paths, "profile", T0 + 13 * MIN);
- assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]);
- // Another login has its own count.
- assert.equal((await recordXJobStart(paths, xLoginKey("browser", "firefox"), T0 + 13 * MIN)).ok, true);
- assert.equal(xLoginKey("browser"), "browser:default");
- assert.equal(xLoginKey("profile", "ignored"), "profile");
- // A start recorded with the clock set back is recorded no earlier than the latest on record.
- const p2 = corpus("disk-back");
- await recordXJobStart(p2, "profile", T0);
- await recordXJobStart(p2, "profile", T0 - 600 * MIN);
- assert.deepEqual(JSON.parse(readFileSync(xJobStartsFile(p2), "utf8")).logins.profile, [T0, T0]);
- // Starts older than a day are dropped when the next is recorded.
- await recordXJobStart(p2, "profile", T0 + 25 * 60 * MIN);
- assert.deepEqual(JSON.parse(readFileSync(xJobStartsFile(p2), "utf8")).logins.profile, [T0 + 25 * 60 * MIN]);
- // Two at once: both recorded, neither lost.
- const p3 = corpus("disk-race");
- await Promise.all(Array.from({ length: 12 }, (_, i) => recordXJobStart(p3, "profile", T0 + i)));
- assert.equal(JSON.parse(readFileSync(xJobStartsFile(p3), "utf8")).logins.profile.length, 12);
- assert.equal((await recordXJobStart(p3, "profile", T0 + 20)).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":1,"logins":[]}'], ["version", '{"version":2,"logins":{}}'], ["times", '{"version":1,"logins":{"profile":["soon"]}}']] as const) {
- const paths = corpus(`closed-${name}`);
- mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true });
- writeFileSync(xJobStartsFile(paths), text);
- const status = await xJobCapStatus(paths, "profile", 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, "profile", T0)).ok, false);
- assert.equal(readFileSync(xJobStartsFile(paths), "utf8"), text);
- }
- // A file that is not there is an empty count.
- assert.deepEqual(await xJobCapStatus(corpus("closed-absent"), "profile", T0), { ok: true, lastHour: 0, lastDay: 0, login: "profile", perHour: 12, perDay: 150 });
-});
-
test("X jobs run on X's queue only: any other queue is refused, when queued and where the job runs", () => {
assert.equal(xQueueRefusal("fetch-posts for example-x", "platform:twitter"), null);
assert.equal(
@@ -139,3 +85,36 @@ test("X jobs run on X's queue only: any other queue is refused, when queued and
// X's queue.
assert.equal(runInJobContext(ctx("platform:twitter"), () => xJobContextRefusal("example-x", "d")), null);
});
+
+test("ruling R-a: what counts is decided from the job's own plan — only a library's media-only capture, with no way to the login, does not", () => {
+ // The watch's follow-up capture with shots off, as the editor queues it (xTrendingActions.ts afterXTrendingRead).
+ const mediaOnly = { queueKey: undefined, ids: ["1"], shots: false, media: true, force: false, articles: false, avatars: false, context: false, watch: true };
+ const library = { library: true };
+ assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: library }), false);
+ // Each way to a page or to the login makes it count.
+ for (const [what, params] of [
+ ["shots on", { ...mediaOnly, shots: true }],
+ ["shots by default", { ...mediaOnly, shots: undefined }],
+ ["articles by default", { ...mediaOnly, articles: undefined }],
+ ["avatars by default", { ...mediaOnly, avatars: undefined }],
+ ["context by default", { ...mediaOnly, context: undefined }],
+ ["a thread shot", { ...mediaOnly, thread: true }],
+ ["avatars only", { ...mediaOnly, avatarsOnly: true }],
+ ["context only", { ...mediaOnly, contextOnly: true }],
+ ["the keep capture (login fallback)", { ...mediaOnly, keptMedia: true }],
+ ] as const) {
+ assert.equal(xJobCounts({ kind: "capture-posts", params, channel: library }), true, what);
+ }
+ // The channel's thread default counts when the plan does not say no.
+ assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: true, postCaptureThread: true } }), true);
+ assert.equal(xJobCounts({ kind: "capture-posts", params: { ...mediaOnly, thread: false }, channel: { library: true, postCaptureThread: true } }), false);
+ // Not a library: an X channel's media comes through gallery-dl with X's cookies.
+ assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly, channel: { library: false } }), true);
+ assert.equal(xJobCounts({ kind: "capture-posts", params: mediaOnly }), true);
+ // No plan to read: it counts.
+ assert.equal(xJobCounts({ kind: "capture-posts", channel: library }), true);
+ // Every other kind of X job counts, whatever its params say.
+ for (const kind of ["fetch-posts", "x-run", "read-x-trending", "import-post", "check-post-availability", "sync", "download-missing"]) {
+ assert.equal(xJobCounts({ kind, params: mediaOnly, channel: library }), true, kind);
+ }
+});
diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts
@@ -12,9 +12,17 @@
// run beside the job on X's and outside the gap between X jobs.
//
// 2. A CAP NOBODY CAN RAISE: at most X_JOB_CAP.perHour X jobs started in any
-// rolling 60 minutes and X_JOB_CAP.perDay in any rolling 24 hours, per X
-// login, over every kind of X job together. A job past it is refused
-// before it starts, with the time the next may start.
+// rolling 60 minutes and X_JOB_CAP.perDay in any rolling 24 hours, ON
+// THIS MACHINE, over every kind of X job together (review 2 M1: ONE
+// bucket — never one per login source, cookie spec or channel, which a
+// flipped source or a respelled spec would turn into a fresh count for
+// the same X account). A job past it is refused before it starts, with
+// the time the next may start; one that meets it AT its start ends
+// deferred, not failed (jobs/networkGuard.ts).
+//
+// WHAT COUNTS (review 2, ruling R-a): a job that can ask x.com with the
+// login or X's cookies — xJobCounts below, decided from the job's own plan
+// (its kind and its spec), never from a flag a caller passes.
//
// THE CAP IS A CONSTANT OF THE CODE. It is not in settings.json, not in a
// channel's config, not an environment variable, not an option of any action
@@ -22,7 +30,7 @@
// like one. Nothing in this module reads a setting.
//
// Pure but for xJobContextRefusal, which reads the running job's context
-// (lib/jobContext.ts). The count's file is lib/xJobCap-server.ts.
+// (lib/jobContext.ts). The count's file is jobs/xJobCap.ts.
import { currentJobContext } from "./jobContext";
@@ -112,7 +120,7 @@ export function xJobCapSentence(v: XJobCapVerdict, now: number): string {
const when = `${day(v.nextAt) === day(now) ? "" : `${day(v.nextAt)} `}${hhmm(v.nextAt)} UTC`;
const wait = minutes >= 120 ? `about ${Math.round(minutes / 60)} h` : `${minutes} min`;
return (
- `X's job cap is reached for this login: ${full}. The next X job may start at ${when} (in ${wait}); ` +
+ `X's job cap is reached on this machine: ${full}. The next X job may start at ${when} (in ${wait}); ` +
"ask again then — nothing queues or retries by itself. The cap is fixed in the code (common/lib/xJobRule.ts): no setting, option or queue raises it."
);
}
@@ -121,12 +129,54 @@ export function xJobCapSentence(v: XJobCapVerdict, now: number): string {
export function xJobCapUnreadableSentence(file: string): string {
return (
`X's job count cannot be read (${file}): no X job starts while it is unreadable, because the cap on X jobs ` +
- "is counted there. Repair the file (it is JSON: {version, logins: {<login>: [times]}}), then ask again."
+ "is counted there. Repair the file (it is JSON: {version: 2, starts: [times]}), then ask again."
+ );
+}
+
+// The sentence for a count that is not on disk and cannot be rebuilt from the
+// job records (review 2, ruling R-c): `why` says what is missing; `until`,
+// when known, is when no X job on record can still count.
+export function xJobCapUnrebuildableSentence(file: string, why: string, until?: number): string {
+ return (
+ `X's job count is not on disk (${file}) and cannot be rebuilt from the job records: ${why}. ` +
+ "No X job starts while the last day's X jobs cannot be counted" +
+ (until !== undefined ? ` — at the latest until ${day(until)} ${hhmm(until)} UTC, when none on record can still count` : "") +
+ ". Restore the job records (the corpus's .jobs directory) and ask again."
);
}
-// Which login a job uses, as the count's key: the connected profile, or the
-// browser whose cookies are read (by its spec).
-export function xLoginKey(source: "profile" | "browser", browserSpec?: string): string {
- return source === "browser" ? `browser:${(browserSpec ?? "").trim() || "default"}` : "profile";
+// ── 3. what counts ─────────────────────────────────────────────────────────
+
+// The job as it will run: its kind, its spec's params (jobs/jobSpec.ts — what
+// the job's function runs with), and the channel it is for.
+export type XJobPlan = {
+ kind: string;
+ params?: Readonly<Record<string, unknown>>;
+ channel?: { library?: boolean; postCaptureThread?: boolean };
+};
+
+// DOES THIS X JOB COUNT AGAINST THE CAP? Every X job does — a read, a fetch in
+// any mode, an X run's channel, an import, an availability check, a capture
+// with its shots — EXCEPT the one job that cannot ask x.com: a trending
+// library's capture of MEDIA ONLY, which takes files from X's two media CDN
+// hosts by the addresses already in the saved captures, with no cookie, no
+// page and no logged-in fallback. Every half that would open a page must be
+// off BY NAME in the plan (shots, articles, avatars, context; no thread shot,
+// by the plan or the channel's default; no avatars-only or context-only run),
+// and it is not a keep capture (`keptMedia`: a post the CDN cannot serve whole
+// is then downloaded the logged-in way). A capture that COULD fall back to
+// the login counts. A plan that cannot be read counts.
+//
+// It still runs on X's queue, spaced from the others by X's gap, under X's
+// cooldown and the watch's jar rule: only the count is not asked.
+export function xJobCounts(plan: XJobPlan): boolean {
+ if (plan.kind !== "capture-posts" || plan.channel?.library !== true) return true;
+ const p = plan.params;
+ if (!p || typeof p !== "object") return true;
+ const off = (k: string) => p[k] === false;
+ if (!(off("shots") && off("articles") && off("avatars") && off("context"))) return true;
+ if (p.thread === true || (p.thread !== false && plan.channel.postCaptureThread === true)) return true;
+ if (p.avatarsOnly === true || p.contextOnly === true) return true;
+ if (p.keptMedia === true) return true;
+ return p.media === false;
}
diff --git a/common/views/jobRowView.ts b/common/views/jobRowView.ts
@@ -98,6 +98,9 @@ export type JobRowView = {
// boot pass's reason for a job a restart left queued ("server restarted;
// the scheduler re-derives syncs"). History rows only; see listJobs.ts.
cancelReason?: string;
+ // A `done` row that did not run: X's job cap was reached at its start
+ // (JobRecord.deferred). Drawn as "deferred" in place of "done".
+ deferred?: { until: number; sentence: string };
// A network job its queue has started, waiting out the gap after the
// previous one on that platform queue (jobs/queueGap.ts): when it may begin
// (epoch ms) and why. Live rows only. Drawn as "waiting 4m12s: X jobs are
diff --git a/common/views/jobRows.ts b/common/views/jobRows.ts
@@ -305,6 +305,7 @@ export function fromEntry(e: JobListEntry): JobRowView {
replayable: e.replayable,
detail: e.detail,
...(e.cancelReason ? { cancelReason: e.cancelReason } : {}),
+ ...(e.deferred ? { deferred: e.deferred } : {}),
source: "archive",
};
}
diff --git a/editor/app/api/jobs/[id]/log/route.ts b/editor/app/api/jobs/[id]/log/route.ts
@@ -61,5 +61,7 @@ export async function GET(
// The job its work went on in (JobRecord.handedOffTo): `pnpm ops --wait`
// follows it there.
...(record?.handedOffTo ? { handedOffTo: record.handedOffTo } : {}),
+ // Ended deferred by X's job cap (JobRecord.deferred): it did not run.
+ ...(record?.deferred ? { deferred: record.deferred } : {}),
});
}
diff --git a/editor/app/channels/[slug]/socialActions.ts b/editor/app/channels/[slug]/socialActions.ts
@@ -27,6 +27,7 @@ import { isSourcelessPostsChannel, SOURCELESS_POSTS_CHANNEL } from "yt-dlp-trans
import { readXTrendingPostIds } from "yt-dlp-transcript-common/lib/xTrending/store";
import { readXTrendingKeptIds } from "yt-dlp-transcript-common/lib/xTrending/judgements";
import { refuseWatchJob } from "yt-dlp-transcript-common/controller/xTrendingWatch";
+import { xJobCounts } from "yt-dlp-transcript-common/lib/xJobRule";
import { fakeXMediaFetch, fakeXProfileChromium } from "yt-dlp-transcript-common/social/fakeXProfileBrowser";
import { X_SEARCH_OLDER_REFUSAL } from "yt-dlp-transcript-common/controller/fetchXSearch";
import { WAYBACK_PAGES_NOT_FETCHED } from "yt-dlp-transcript-common/controller/fetchPosts";
@@ -452,6 +453,24 @@ export async function capturePostsAction(
}
const key = resolveQueueKey(pages ? WAYBACK_PAGES_QUEUE : downloadQueueKey(config), queueKey);
+ // THE JOB'S PLAN: its spec, and what the network guard reads to decide
+ // whether it counts against X's job cap (lib/xJobRule.ts xJobCounts).
+ const params = {
+ queueKey, ids: wanted, shots, media, force, articles,
+ ...(thread !== undefined ? { thread } : {}),
+ ...(threadRedact !== undefined ? { threadRedact } : {}),
+ ...(avatars !== undefined ? { avatars } : {}),
+ ...(avatarsOnly ? { avatarsOnly } : {}),
+ ...(context !== undefined ? { context } : {}),
+ ...(contextOnly ? { contextOnly } : {}),
+ ...(keptMedia ? { keptMedia } : {}),
+ ...(watch ? { watch } : {}),
+ };
+ const counts = xJobCounts({
+ kind: "capture-posts",
+ params,
+ channel: { library, ...(config.postCaptureThread === true ? { postCaptureThread: true } : {}) },
+ });
return runManagedFunction({
kind: "capture-posts",
queueKey: key,
@@ -460,17 +479,7 @@ export async function capturePostsAction(
spec: {
kind: "capture-posts",
slug,
- params: {
- queueKey, ids: wanted, shots, media, force, articles,
- ...(thread !== undefined ? { thread } : {}),
- ...(threadRedact !== undefined ? { threadRedact } : {}),
- ...(avatars !== undefined ? { avatars } : {}),
- ...(avatarsOnly ? { avatarsOnly } : {}),
- ...(context !== undefined ? { context } : {}),
- ...(contextOnly ? { contextOnly } : {}),
- ...(keptMedia ? { keptMedia } : {}),
- ...(watch ? { watch } : {}),
- },
+ params,
},
fn: async (onLog, signal, _progress, ctx) => {
// AN X CAPTURE'S START (lib/cookieRefreshGuard.ts xCaptureStartRefusal),
@@ -489,7 +498,8 @@ export async function capturePostsAction(
// of 0, the browser as login source). Refused: nothing is opened or
// fetched, and the library's watches pause.
if (watch && library) {
- const refusal = await refuseWatchJob(paths, slug);
+ // A media-only capture asks x.com nothing: X's job cap does not hold it (ruling R-a).
+ const refusal = await refuseWatchJob(paths, slug, undefined, { counts });
if (refusal) throw new Error(`This capture was queued by a watch and did not start: ${refusal.sentence}`);
}
// UNDER THE E2E TEST SERVER a library's capture never reaches X or its
diff --git a/editor/app/channels/[slug]/xTrendingActions.ts b/editor/app/channels/[slug]/xTrendingActions.ts
@@ -80,6 +80,7 @@ import {
import { publishXTrendingTopic, type PublishXTrendingResult } from "yt-dlp-transcript-common/controller/publishXTrending";
import { safeRevalidate } from "../../lib/safeRevalidate";
import { capturePostsAction } from "./socialActions";
+import { xJobCounts } from "yt-dlp-transcript-common/lib/xJobRule";
import { recompileChannelPriorityAction } from "../actions";
import { xPressInFlight } from "../../lib/cookieRefreshGuard";
@@ -170,7 +171,11 @@ async function afterXTrendingRead(
// THE CAPTURE IS THE WATCH'S JOB TOO (review 2 N1): the watch's jar rule is
// asked before it is queued, and again inside the job when it starts
// (`watch: true`) — with "screenshot everything new" it opens pages on X.
- const refusal = await refuseWatchJob(getPaths(), slug);
+ // Media only (no shots) asks x.com nothing and does not count against X's
+ // job cap (lib/xJobRule.ts xJobCounts, ruling R-a): the cap does not hold it.
+ const plan = { shots: follow.shots, media: true, articles: false, ...(follow.shots ? {} : { avatars: false, context: false }) };
+ const counts = xJobCounts({ kind: "capture-posts", params: plan, channel: { library: true } });
+ const refusal = await refuseWatchJob(getPaths(), slug, undefined, { counts });
if (refusal) {
onLog(`The media of ${what} was not queued, and the watch is paused: ${refusal.sentence}`);
return;
diff --git a/editor/app/jobs/[id]/page.tsx b/editor/app/jobs/[id]/page.tsx
@@ -98,6 +98,15 @@ export default async function JobDetailPage({
/>
{/* Why, when no person pressed Cancel: the boot pass's reason for a
job a restart left queued (JobMeta.cancelReason). */}
+ {/* A job X's job cap deferred at its start: it did not run (JobMeta.deferred). */}
+ {job.status === "done" && job.deferred && (
+ <Cell
+ label="Deferred"
+ value={job.deferred.sentence}
+ className="col-span-2 sm:col-span-4"
+ testId="job-deferred"
+ />
+ )}
{job.status === "cancelled" && job.cancelReason && (
<Cell
label="Cancelled because"
diff --git a/editor/app/jobs/components/JobRow.tsx b/editor/app/jobs/components/JobRow.tsx
@@ -264,9 +264,9 @@ function JobRowHeading({
? `uppercase tracking-wide px-1.5 py-0.5 rounded text-[10px] ${statusColor(job.status)}`
: `text-xs uppercase tracking-wide px-2 py-0.5 rounded ${statusColor(job.status)}`
}
- title={cancelReasonOf(job)}
+ title={cancelReasonOf(job) ?? job.deferred?.sentence}
>
- {job.status}
+ {job.status === "done" && job.deferred ? "deferred" : job.status}
</span>
)}
<span
diff --git a/editor/app/scheduler/runTick.ts b/editor/app/scheduler/runTick.ts
@@ -13,7 +13,7 @@ import { activeSyncJobs } from "yt-dlp-transcript-common/jobs/syncJobs";
import type { SyncSchedulerSettings } from "yt-dlp-transcript-common/lib/settings";
import {
isInQuietHours,
- nextEligibleAfterFailure,
+ foldScheduledSyncOutcome,
selectDueChannels,
isInstagramPostsConfig,
xSyncHold,
@@ -281,23 +281,8 @@ function reconcileOutcomes(
cs.lastQueuedJobId = null; // evicted; can't read outcome
continue;
}
- if (job.status === "queued" || job.status === "running") continue;
- if (job.status === "done") {
- cs.consecutiveFailures = 0;
- cs.nextEligibleAt = null;
- cs.lastOutcome = "ok";
- cs.lastOutcomeAt = job.endedAt ?? now;
- } else if (job.status === "failed") {
- cs.consecutiveFailures += 1;
- cs.nextEligibleAt = nextEligibleAfterFailure(
- now,
- cs.consecutiveFailures,
- scheduler,
- pacingJitter(),
- );
- cs.lastOutcome = "failed";
- cs.lastOutcomeAt = job.endedAt ?? now;
- }
- cs.lastQueuedJobId = null;
+ // Done, failed, cancelled — and DEFERRED by X's job cap, which is
+ // neither a success nor a failure (common/jobs/syncScheduler.ts).
+ foldScheduledSyncOutcome(cs, job, now, scheduler, pacingJitter());
}
}