commit 1479b91dfbe9f545ab713207a7a46f392efce4e8 parent 8315a4b0678d0f86d83a4bf99c7deecb98ff9236 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sun, 25 Oct 2026 11:03:07 -0400 Every wait before a request varies upward by up to pacing.jitter (default 25 %), never shorter; three jitters that could undercut their floor fixed; four unpaced loops paced One upward-only helper (common/lib/jitter.mjs, the operator's share through lib/jitter.ts; `pacing.jitter`, /settings "Jitter on every wait before a request", 0 = off) stretches, by a random share of itself: - the gap between two downloads with no platform floor (downloadGapMs; it was exactly 10 s plus the pace on YouTube and Rumble), - yt-dlp's --sleep-requests and --sleep-subtitles, drawn once per run at every spawn and shown in the logged command line, - the job gap per platform queue (stable per wait, seeded by the last end), - notePlatformGap, the archive.org/Wayback and web-fetch gaps and back-offs, the platform hold's probe, Save Page Now and Kick polls, stored-URL pauses, the whole-copy gap, the lane's metadata-scan batch (60-75) and rest, - each channel's sync interval (stable per sync, at most 30 min later; the /operations/sync view shows the same due time) and its failure back-off. Upward-only now: the platform cooldown (was +-10 %), archive.org's back-off (+-20 %), a forum's page pause (reached 0.85 of a base held to its floor). Paced: Bluesky feed pages, Nitter pages, per-video availability probes (3 s +), umtool's network clip fetches (per platform, the clip-window floor). Test-only overrides: E2E_PACING_JITTER, E2E_AVAILABILITY_PROBE_GAP_MS, E2E_CLIP_FETCH_GAP_MS. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
60 files changed, 841 insertions(+), 110 deletions(-)
diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -235,6 +235,8 @@ Read only by a test harness, a fake binary or a test-mode branch. Never set one | `E2E_AUDIO_CHECK_RECOVER_STEP_MS` | the real step | Likewise, the recovery step. | common/ytdlp/audioCheckedDownload.ts | | `E2E_AUDIO_CHECK_RECOVER_AFTER` | the real count | Likewise, the recovery count. | common/ytdlp/audioCheckedDownload.ts | | `E2E_BACKOFF_BASE_MS` | `60000` (the real base) | The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse. | common/jobs/platformBackoff.ts | +| `E2E_AVAILABILITY_PROBE_GAP_MS` | the real gap (3 s, stretched by `pacing.jitter`) | The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once. | common/controller/checkAvailability.ts | +| `E2E_PACING_JITTER` | `pacing.jitter` from settings.json (0.25) | Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts). | common/lib/jitter.ts | | `E2E_CLIP_WINDOW_GAP_MS` | the real gap (30–45 s, more for Rumble) | The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes. | common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts | | `E2E_JOB_GAP_SECONDS` | the built-in gaps (20 s; X 300, forums and Bluesky 60) | Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own. | common/jobs/queueGap.ts | | `E2E_X_MAX_COOKIE_AGE_MINUTES` | the built-in 60 | Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own. | common/jobs/networkGuard.ts | diff --git a/SETTINGS.md b/SETTINGS.md @@ -222,6 +222,7 @@ How the download pace adapts to rate limits, per platform (release 17). Every yt | `holdAfterFailsAtCap` | `3` | How many consecutive failures AT the 30-minute cooldown cap put a platform in a hold: the lane then runs one probe unit per holdProbeMinutes instead of one per cooldown, and a manual Sync or download on it is refused with the next probe's time. A clean probe clears the hold and the backoff. Clamped 1–100; default 3. | | `holdProbeMinutes` | `60` | Minutes between probes while a platform is held. Clamped 1–1440; default 60. | | `jobGapSeconds` | `{}` | THE GAP BETWEEN TWO JOBS ON ONE PLATFORM QUEUE, in seconds, keyed by platform (the `<p>` of a `platform:<p>` queue — `twitter`, `youtube`, `megaphone.fm` …) or `default`. A job that sends requests to a platform (a kind declaring `network` in common/jobs/jobKinds.ts) does not start until this long after the previous such job on its queue ended; while it waits its log and its /jobs row say so ("waiting 4m12s: X jobs are spaced 5 min apart (pacing.jobGapSeconds.twitter)"). The last end per queue survives a restart (`.jobs/queue-gaps.json`). Built in, for a key not set here: default 20, twitter 300, xenforo 60, bluesky 60 — only the keys set here are stored. 0 for a key: no gap on that platform. At most 86400. Set on /settings beside the download sleep. common/jobs/queueGap.ts. | +| `jitter` | `0.25` | THE SHARE OF ITSELF EVERY WAIT BEFORE A REQUEST IS STRETCHED BY, AT RANDOM, so the archive does not ask a site on a fixed beat. 0.25 makes a 20 s job gap land anywhere from 20 to 25 s. It only ever ADDS time: every pacing number stays a minimum (Rumble's 120 s, X's 5 min, the between-downloads sleep). It stretches the gap between two downloads and two jobs on one platform, yt-dlp's `--sleep-requests` and `--sleep-subtitles` (drawn once per yt-dlp run), the archive.org, Wayback and web-fetch gaps, the rate-limit cooldowns, the download lane's metadata-scan batches and rests, and a channel's sync interval (by at most 30 minutes). 0 turns it off. Clamped 0–1; default 0.25. common/lib/jitter.mjs. | Default: @@ -231,7 +232,8 @@ Default: "decayAfterCleanUnits": 5, "holdAfterFailsAtCap": 3, "holdProbeMinutes": 60, - "jobGapSeconds": {} + "jobGapSeconds": {}, + "jitter": 0.25 } ``` diff --git a/common/controller/archiveOrgResearch.test.ts b/common/controller/archiveOrgResearch.test.ts @@ -8,6 +8,10 @@ import { startFakeArchiveOrg, type FakeArchiveOrg } from "../testing/archiveOrg/ import { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { describeArchiveOrgItem, searchArchiveOrgItems } from "./archiveOrgImport"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + let ia: FakeArchiveOrg; before(async () => { ia = await startFakeArchiveOrg(); diff --git a/common/controller/autoRunner.test.ts b/common/controller/autoRunner.test.ts @@ -8,7 +8,9 @@ import { focusHoldLine, laneDispatchRoot, makeFocusHoldReporter, + LANE_SCAN_BATCH, LANE_SCAN_REST_MS, + laneScanBatch, pickMetadataScanChannel, priorityContextFor, scanSkipPlatforms, @@ -25,6 +27,7 @@ import { type FocusSummary, } from "../lib/channelPriority"; import { LANES } from "../lib/autoQueueTypes"; +import { pacingJitter } from "../lib/jitter"; import { emptyAutoQueueState, readAutoQueueState, @@ -428,6 +431,7 @@ test("a clean batch with work left is readmitted, after the platform rests", () const settled = settleLaneScan( { scanned: 60, errors: 3, targets: 60, remaining: 1103 }, now, + () => 0, ); assert.deepEqual(settled, { restUntil: now + LANE_SCAN_REST_MS, @@ -464,13 +468,26 @@ test("a stopped batch, a finished backlog and a job with no result are not readm { scanned: 40, errors: 0, targets: 40, remaining: 0 }, null, ]) { - const settled = settleLaneScan(result, now); + const settled = settleLaneScan(result, now, () => 0); assert.equal(settled.readmit, false); // The platform rests either way: the downloads get their turn. assert.equal(settled.restUntil, now + LANE_SCAN_REST_MS); } }); +test("the rest and the batch are stretched by up to pacing.jitter, never shortened", () => { + const spread = pacingJitter(); + const top = settleLaneScan(null, 0, () => 1).restUntil; + assert.equal(top, Math.ceil(LANE_SCAN_REST_MS * (1 + spread))); + for (let i = 0; i < 50; i++) { + const rest = settleLaneScan(null, 0).restUntil; + assert.ok(rest >= LANE_SCAN_REST_MS && rest <= top, String(rest)); + const batch = laneScanBatch(); + assert.ok(batch >= LANE_SCAN_BATCH && batch <= Math.round(LANE_SCAN_BATCH * (1 + spread)), String(batch)); + } + assert.equal(laneScanBatch(() => 0), LANE_SCAN_BATCH); +}); + test("the scan's platform skip keeps the downloads' own skips and drops an expired rest", () => { const skip = scanSkipPlatforms( new Set(["rumble"]), diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts @@ -10,6 +10,7 @@ import { detectPlatform } from "../lib/platform"; import { compileDownloadFilter } from "../lib/downloadFilters"; import { runMetadataScanJob } from "./metadataScanJob"; import type { MetadataScanResult } from "../ytdlp/metadataScan"; +import { jitter, jitterMs } from "../lib/jitter"; import { getWorkerPool } from "../jobs/workerPool"; import { getRegistry } from "../jobs/registry"; import { runManagedFunction } from "../jobs/streamCommand"; @@ -1188,12 +1189,26 @@ export function pickMetadataScanChannel( // error), a cancelled or failed job (no result at all) and a finished backlog // all leave the channel in `scannedThisRun` — see the pre-pick. Pure, so the // rule is testable without a runner. +// +// The rest is stretched by up to `pacing.jitter` of itself (lib/jitter.mjs), +// so batches do not start on a 20-minute beat. export function settleLaneScan( result: MetadataScanResult | null, now: number, + rand: () => number = Math.random, ): { restUntil: number; readmit: boolean; remaining: number } { const remaining = result && !result.stopped ? result.remaining : 0; - return { restUntil: now + LANE_SCAN_REST_MS, readmit: remaining > 0, remaining }; + return { + restUntil: now + jitterMs(LANE_SCAN_REST_MS, rand), + readmit: remaining > 0, + remaining, + }; +} + +// One batch's size: LANE_SCAN_BATCH stretched by up to `pacing.jitter`, so a +// batch is not always exactly 60 titles. +export function laneScanBatch(rand: () => number = Math.random): number { + return Math.round(jitter(LANE_SCAN_BATCH, rand)); } // The platforms the scan pre-pick may not use this tick: the downloads' own @@ -1218,7 +1233,7 @@ type Picked = { // pre-pick: `pick.videoId` is then a synthetic key naming no video and // `pick.path` is empty, so no node's active count moves for it. `run()` // branches on this and nothing else. - scan?: { slug: string; targets: number }; + scan?: { slug: string; targets: number; batch: number }; // THE STORED-URL UNIT (release 32 R9, controller/laneStoredUrl.ts): picked // past a cooling or held platform because its record stores a media URL; it // downloads as `only`, `held` on a held platform. @@ -1880,7 +1895,8 @@ async function runLoop( const unitPlatform = platformKey(slug, slugToPlatform); scannedThisRun.add(slug); const videoId = `${METADATA_SCAN_UNIT_PREFIX}${slug}`; - const batch = Math.min(targets, LANE_SCAN_BATCH); + const batchSize = laneScanBatch(); + const batch = Math.min(targets, batchSize); const note = `scanning ${batch} listed video${batch === 1 ? "" : "s"}${ targets > batch ? ` of ${targets}` : "" } for ${slug}`; @@ -1913,7 +1929,7 @@ async function runLoop( pick: { leafId: METADATA_SCAN_LEAF_ID, videoId, path: [] }, channelSlug: slug, unitPlatform, - scan: { slug, targets }, + scan: { slug, targets, batch: batchSize }, }; } } @@ -2146,6 +2162,7 @@ async function runLoop( paths, slug: scanSlug, targets: picked.scan.targets, + batch: picked.scan.batch, tracker, onLog, onChildJob: (jid) => { childJobIds.set(pick.videoId, jid); const u = live.inFlight.get(pick.videoId); if (u) u.jobId = jid; }, @@ -2298,6 +2315,8 @@ async function launchMetadataScan(args: { paths: Paths; slug: string; targets: number; + // This batch's size (laneScanBatch at the pick). + batch: number; tracker: ReturnType<typeof makeTaskTracker>; onLog: (line: string) => void; onChildJob?: (jobId: string) => void; @@ -2310,7 +2329,7 @@ async function launchMetadataScan(args: { slug: args.slug, channelConfig: config, background: true, - maxTargets: LANE_SCAN_BATCH, + maxTargets: args.batch, ...(args.onResult ? { onResult: args.onResult } : {}), }); if (!res.ok) { diff --git a/common/controller/checkAvailability.test.ts b/common/controller/checkAvailability.test.ts @@ -6,6 +6,10 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import { runAvailabilityCheck } from "./checkAvailability"; +// The stub yt-dlp answers at once: no pause between probes (the production +// gap is AVAILABILITY_PROBE_GAP_MS plus jitter). +process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; + // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/checkAvailability.test.ts // diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts @@ -32,6 +32,8 @@ import { channelExtraArgs, pacedPlatformArgs } from "../ytdlp/channelArgs"; import { detectPlatform } from "../lib/platform"; import { resolveShardItems } from "./shard"; import type { Paths } from "../lib/paths"; +import { jitterYtdlpSleeps } from "../lib/jitter"; +import { jitterMs } from "../lib/jitter"; export type CheckAvailabilityMode = | "resume" @@ -73,8 +75,26 @@ export type CheckAvailabilityOpts = { // key a download's 429 and a manual Sync use. A test seam; production // callers pass nothing. onPlatformBackoff?: (platform: string) => void | Promise<void>; + // The pause after each probe (default AVAILABILITY_PROBE_GAP_MS, stretched + // by pacing.jitter). Tests pass 0. + probeGapMs?: number; }; +// THE GAP BETWEEN TWO PROBES. Each probe is its own yt-dlp run, and they used +// to follow each other with nothing between them but yt-dlp's own start-up — a +// keep-latest re-probe over a few hundred kept videos was a few hundred +// requests at about one a second. Now at least this long after each probe that +// asked the source, stretched by up to pacing.jitter (lib/jitter.mjs). +export const AVAILABILITY_PROBE_GAP_MS = 3_000; + +// TEST-ONLY: E2E_AVAILABILITY_PROBE_GAP_MS replaces the gap on the editor's e2e +// server (e2e/servers.ts), whose stub yt-dlp answers at once. +function defaultProbeGapMs(): number { + const raw = Number(process.env.E2E_AVAILABILITY_PROBE_GAP_MS); + if (process.env.E2E_AVAILABILITY_PROBE_GAP_MS !== undefined && Number.isFinite(raw) && raw >= 0) return raw; + return jitterMs(AVAILABILITY_PROBE_GAP_MS); +} + export type CheckAvailabilityResult = { attempted: number; checked: number; @@ -134,6 +154,7 @@ export async function runAvailabilityCheck({ onLog, signal, onPlatformBackoff, + probeGapMs, }: CheckAvailabilityOpts): Promise<CheckAvailabilityResult> { const log = onLog ?? ((m: string) => console.log(m)); const channelDir = path.join(paths.channelsDir, channelSlug); @@ -258,7 +279,8 @@ export async function runAvailabilityCheck({ url, ]; - const result = await execa(paths.ytdlpBin, args, { + // The fixed waits drawn once for this probe (lib/jitter.mjs). + const result = await execa(paths.ytdlpBin, jitterYtdlpSleeps(args), { cwd: channelDir, cancelSignal: signal, all: false, @@ -323,6 +345,9 @@ export async function runAvailabilityCheck({ byStatus[availability]++; probedIds.push(id); log(`Check ${id}: ${availability}`); + // The gap before this slot's next probe (see AVAILABILITY_PROBE_GAP_MS). + const gap = probeGapMs ?? defaultProbeGapMs(); + if (gap > 0 && !blocked && !signal?.aborted) await probeSleep(gap, signal); }), ), ); @@ -366,3 +391,16 @@ export async function runAvailabilityCheck({ probedIds, }; } + +function probeSleep(ms: number, signal?: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal?.aborted) return resolve(); + const t = setTimeout(done, ms); + function done() { + clearTimeout(t); + signal?.removeEventListener("abort", done); + resolve(); + } + signal?.addEventListener("abort", done, { once: true }); + }); +} diff --git a/common/controller/fetchCopies.ts b/common/controller/fetchCopies.ts @@ -57,6 +57,7 @@ import { import { FetchWindowError } from "../ytdlp/fetchWindowManaged"; import { fetchCopyManaged, holdsMedia, type FetchCopyOpts, type FetchCopyResult } from "../ytdlp/fetchCopyManaged"; import { readChannelConfig } from "./channels"; +import { jitterMs } from "../lib/jitter"; // The least time between two whole-copy fetches. export const WHOLE_COPY_MIN_GAP_SECONDS = 30; @@ -189,6 +190,8 @@ export async function fetchCopies({ const log = (line: string) => onLog?.(line.endsWith("\n") ? line : `${line}\n`); const fetchLog = (line: string) => onLog?.(line); const fetchSignal = signal ?? new AbortController().signal; + // The floor between two fetches (stretched by pacing.jitter where it is + // slept, below). const gap = gapMs ?? WHOLE_COPY_MIN_GAP_SECONDS * 1000; // One item per recording: the first ask wins. const seen = new Set<string>(); @@ -268,8 +271,11 @@ export async function fetchCopies({ } if (networkAttempts > 0 && gap > 0) { - log(`Sleeping ${Math.round(gap / 1000)}s before the next copy...`); - await deps.sleep(gap, signal); + // The default floor stretched by up to pacing.jitter; a gap the caller + // passed is waited exactly. + const pause = gapMs === undefined ? jitterMs(gap) : gap; + log(`Sleeping ${Math.round(pause / 1000)}s before the next copy...`); + await deps.sleep(pause, signal); const after = interrupted(); if (after) { stop(after, i); diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts @@ -17,6 +17,10 @@ import { } from "./persistVideos"; import { finalizeAppExtraction } from "../ytdlp/finalizeAppExtraction"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/persistVideos.test.ts // diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -88,6 +88,8 @@ import { } from "./landMedia"; import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata"; import { findVideoSourceUrl } from "./undownloadedVideos"; +import { jitterYtdlpSleeps } from "../lib/jitter"; +import { jitterMs } from "../lib/jitter"; export const RECORD_LIVE_JOB_KIND = "record-live"; export const RECORD_LIVE_RESULT_MARKER = "@@record-live "; @@ -411,7 +413,8 @@ export async function pollEventPlaylist(opts: { ended = `the VOD has not grown for ${Math.round(idle / 1000)} s${failures ? ` (${failures} failed read(s))` : ""}`; break; } - await wait(pollMs, opts.signal); + // Each read stretched by up to pacing.jitter (lib/jitter.mjs). + await wait(jitterMs(pollMs), opts.signal); } } finally { await new Promise<void>((resolve) => out.end(() => resolve())); @@ -547,7 +550,7 @@ async function defaultKickVod( const listing = `https://kick.com/${channel}/videos`; const r = await execa( paths.ytdlpBin, - ["--ignore-config", "--flat-playlist", "--playlist-items", "1", "-J", ...channelExtraArgs(cfg, cookies), "--", listing], + jitterYtdlpSleeps(["--ignore-config", "--flat-playlist", "--playlist-items", "1", "-J", ...channelExtraArgs(cfg, cookies), "--", listing]), { reject: false, cancelSignal: signal }, ); if (r.exitCode !== 0) return null; diff --git a/common/controller/savePageNow.ts b/common/controller/savePageNow.ts @@ -41,6 +41,7 @@ import { } from "../lib/waybackPages/savePageNow"; import { readSpnKeys, redactSpnKeys } from "../lib/waybackPages/savePageNow-server"; import { startImportPageJob, WAYBACK_PAGES_QUEUE, xCaptureRefusal } from "./importPage"; +import { jitterMs } from "../lib/jitter"; export const SAVE_PAGE_NOW_JOB_KIND = "save-page-now"; export const SAVE_PAGE_NOW_RESULT_MARKER = "@@save-page-now "; @@ -194,7 +195,8 @@ export async function savePageNow(opts: { error: `the capture was still pending after ${polls} status checks; archive.org may finish it later (look the page up with wayback-lookup, then import-page it)`, }; } - await deps.sleep(pollMs, opts.signal); + // Each poll stretched by up to pacing.jitter (lib/jitter.mjs). + await deps.sleep(jitterMs(pollMs), opts.signal); polls++; const st = await deps.client.send(spnStatusUrl(submit.jobId), { method: "GET", diff --git a/common/controller/verifyBeforeClean.test.ts b/common/controller/verifyBeforeClean.test.ts @@ -7,6 +7,10 @@ import type { Paths } from "../lib/paths"; import type { Availability } from "../lib/availability"; import { excludedIds, verifyBeforeClean } from "./verifyBeforeClean"; +// The stub yt-dlp answers at once: no pause between probes (the production +// gap is AVAILABILITY_PROBE_GAP_MS plus jitter). +process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; + // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/verifyBeforeClean.test.ts // diff --git a/common/jobs/downloadBackoff.test.ts b/common/jobs/downloadBackoff.test.ts @@ -22,6 +22,10 @@ import { writeAutoQueueState, } from "./autoQueueState"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test common/jobs/downloadBackoff.test.ts // // downloadBackoff only touches paths.autoQueueStateFile, so a stub Paths with diff --git a/common/jobs/pacingGuard.test.ts b/common/jobs/pacingGuard.test.ts @@ -188,7 +188,8 @@ test("13 X fetches with no challenge start at least pacing.jobGapSeconds.twitter } // The waiting job's log says why it waited. const log2 = await readLog(ends[1]!.jobId); - assert.match(log2, /waiting 5m00s: X jobs are spaced 5 min apart \(pacing\.jobGapSeconds\.twitter\)/); + // 5 min at least, stretched by up to pacing.jitter (lib/jitter.mjs). + assert.match(log2, /waiting [56]m\d\ds: X jobs are spaced 5 min apart \(pacing\.jobGapSeconds\.twitter\)/); // The end survives a restart: the file names the queue. const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(typeof file.ends["platform:twitter"], "number"); diff --git a/common/jobs/platformBackoff.test.ts b/common/jobs/platformBackoff.test.ts @@ -30,11 +30,13 @@ import { settlePlatformClean, } from "./platformBackoff"; import { sanitizePacing } from "../lib/settingsSchema"; +import { pacingJitter } from "../lib/jitter"; // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test common/jobs/platformBackoff.test.ts -// Deterministic jitter: no jitter (returns 0.5 -> factor 1.0). -const noJitter = () => 0.5; +// Deterministic jitter: no jitter (the jitter is upward-only, so a draw of 0 is +// factor 1.0). +const noJitter = () => 0; test("nextBackoff doubles the cooldown across consecutive failures", () => { const now = 1_000_000; @@ -59,12 +61,16 @@ test("nextBackoff caps the cooldown at BACKOFF_MAX_MS", () => { assert.ok(entry.fails > 1); }); -test("nextBackoff applies bounded jitter (±10%)", () => { +test("nextBackoff's jitter only lengthens the cooldown (it used to be ±10 %)", () => { const now = 0; - const low = nextBackoff(undefined, now, () => 0); // factor 0.9 - const high = nextBackoff(undefined, now, () => 1); // factor 1.1 - assert.equal(low.until, Math.round(BACKOFF_BASE_MS * 0.9)); - assert.equal(high.until, Math.round(BACKOFF_BASE_MS * 1.1)); + const low = nextBackoff(undefined, now, () => 0); + const high = nextBackoff(undefined, now, () => 1); + // A cooldown is a floor: the shortest draw is the base itself. + assert.equal(low.until, BACKOFF_BASE_MS); + // The longest: at least 10 % more, or the operator's pacing.jitter if larger. + const spread = Math.max(0.1, pacingJitter()); + assert.equal(high.until, Math.ceil(BACKOFF_BASE_MS * (1 + spread))); + assert.ok(high.until >= BACKOFF_BASE_MS * 1.1); }); test("E2E_BACKOFF_BASE_MS shortens the base; the cap and the hold arithmetic keep the real constants", () => { @@ -201,11 +207,13 @@ test("mergeBackoffEntry takes the max of until and of fails separately", () => { test("PACING_DEFAULTS are the settings schema's defaults", () => { // jobGapSeconds (plans/pacing-guard.md) stores only the keys set; its - // built-ins are jobGapSecondsFor's, never written. - assert.deepEqual({ ...PACING_DEFAULTS, jobGapSeconds: {} }, sanitizePacing({})); + // built-ins are jobGapSecondsFor's, never written. `jitter` is read through + // lib/jitter.ts, not by the runner. + assert.deepEqual({ ...PACING_DEFAULTS, jobGapSeconds: {}, jitter: 0.25 }, sanitizePacing({})); assert.deepEqual(sanitizePacing({ sleepRequestsCapSeconds: 999, holdProbeMinutes: 0 }), { ...PACING_DEFAULTS, jobGapSeconds: {}, + jitter: 0.25, sleepRequestsCapSeconds: 120, holdProbeMinutes: 1, }); @@ -218,12 +226,26 @@ test("the cap is reached at the sixth failure; failsAtCap counts from there", () }); test("the lane gap is the operator's sleep plus the pace above its base", () => { - assert.equal(downloadGapMs(0, 1, 1), 0); - assert.equal(downloadGapMs(30, 1, 1), 30_000); - assert.equal(downloadGapMs(30, 4, 1), 33_000); - assert.equal(downloadGapMs(0, 8, 1), 7_000); - assert.equal(downloadGapMs(10, 2, 0), 12_000); - assert.equal(downloadGapMs(-5, 0.5, 1), 0); + const r = { random: 0 }; + assert.equal(downloadGapMs(0, 1, 1, r), 0); + assert.equal(downloadGapMs(30, 1, 1, r), 30_000); + assert.equal(downloadGapMs(30, 4, 1, r), 33_000); + assert.equal(downloadGapMs(0, 8, 1, r), 7_000); + assert.equal(downloadGapMs(10, 2, 0, r), 12_000); + assert.equal(downloadGapMs(-5, 0.5, 1, r), 0); +}); + +test("with no floor the gap is stretched by up to pacing.jitter, never shortened", () => { + // 30 s + 3 s of pace above base, a quarter again at the top of the draw. + assert.equal(downloadGapMs(30, 4, 1, { random: 1, spread: 0.25 }), 41_250); + assert.equal(downloadGapMs(30, 4, 1, { random: 0.5, spread: 0.25 }), 37_125); + // jitter 0 is the old exact gap; no sleep stays no sleep. + assert.equal(downloadGapMs(30, 4, 1, { random: 1, spread: 0 }), 33_000); + assert.equal(downloadGapMs(0, 1, 1, { random: 1, spread: 0.25 }), 0); + for (let i = 0; i < 50; i++) { + const g = downloadGapMs(10, 1, 1); + assert.ok(g >= 10_000 && g <= 10_000 * (1 + pacingJitter()), String(g)); + } }); test("a platform floor raises the operator's sleep to it and jitters it by up to half again", () => { @@ -238,9 +260,9 @@ test("a platform floor raises the operator's sleep to it and jitters it by up to assert.equal(downloadGapMs(0, 3, 3, { minSeconds: 60, random: 7 }), 90_000); const g = downloadGapMs(0, 3, 3, { minSeconds: 60 }); assert.ok(g >= 60_000 && g <= 90_000, String(g)); - // No floor: exactly the old gap, never jittered. - assert.equal(downloadGapMs(30, 1, 1, { minSeconds: 0, random: 1 }), 30_000); - assert.equal(downloadGapMs(30, 1, 1, {}), 30_000); + // No floor: the operator's jitter instead (see the test below); with it off, + // exactly the old gap. + assert.equal(downloadGapMs(30, 1, 1, { minSeconds: 0, random: 1, spread: 0 }), 30_000); }); test("a held platform's backoff survives the prune; a hold with no backoff is dropped", () => { diff --git a/common/jobs/platformBackoff.ts b/common/jobs/platformBackoff.ts @@ -1,6 +1,8 @@ // Per-platform exponential backoff for the auto-download runner. Pure logic + // types, no I/O — so it's unit-testable and can be persisted by -// autoQueueState.ts and driven by autoRunner.ts. +// autoQueueState.ts and driven by autoRunner.ts. (The one read is the +// operator's jitter share, `pacing.jitter`, through lib/jitter.ts; every +// function that draws takes its draw injected.) // // When a download fails with a rate-limit (HTTP 429 / throttle) or network // error, the runner must stop launching downloads for THAT platform for a @@ -8,6 +10,9 @@ // source again (the original Odysee 429 storm). Each consecutive failure // doubles the cooldown up to a cap; a successful download resets it. +import { jitterUp } from "../lib/jitter.mjs"; +import { pacingJitter } from "../lib/jitter"; + export type PlatformBackoffEntry = { // Epoch ms: downloads for this platform are paused until this instant. until: number; @@ -22,8 +27,10 @@ export type PlatformBackoffState = Record<string, PlatformBackoffEntry>; export const BACKOFF_BASE_MS = 60_000; // 1 minute // Ceiling on the cooldown — long rate limits shouldn't park a platform forever. export const BACKOFF_MAX_MS = 30 * 60_000; // 30 minutes -// ±10% jitter so multiple platforms recovering at once don't sync up. -const JITTER = 0.1; +// At least 10% jitter so multiple platforms recovering at once don't sync up, +// or the operator's `pacing.jitter` when that is larger. UPWARD only: a +// cooldown is a floor, and it used to land up to 10% short of it. +const MIN_BACKOFF_JITTER = 0.1; // TEST-ONLY: E2E_BACKOFF_BASE_MS shortens the FIRST cooldown (and so every // doubling from it), so the e2e suite can watch one lapse in seconds instead @@ -44,8 +51,8 @@ export function nextBackoff( ): PlatformBackoffEntry { const fails = (prev?.fails ?? 0) + 1; const base = Math.min(backoffBaseMs() * 2 ** (fails - 1), BACKOFF_MAX_MS); - const jitter = 1 + (rand() * 2 - 1) * JITTER; - return { until: now + Math.round(base * jitter), fails }; + const spread = Math.max(MIN_BACKOFF_JITTER, pacingJitter()); + return { until: now + Math.ceil(jitterUp(base, spread, rand)), fails }; } // Fold two records of the same platform's backoff — the live one and the one @@ -317,21 +324,27 @@ export function currentPaceSeconds( // in ytdlp/platformArgs.mjs — BitChute's 60 s): the operator's sleep is raised // to at least the floor and then stretched by up to half again at random // (`floor.random`, in [0, 1)), so a platform that rate-limits is never asked on -// a fixed beat. With no floor the gap is exactly what it always was. +// a fixed beat. WITHOUT a floor the gap is stretched too, by up to +// `pacing.jitter` of itself (`floor.spread`, default the operator's; see +// lib/jitter.mjs) — it used to be exactly 10 s plus the pace on every platform +// with no floor, YouTube and Rumble included. Only ever longer, never shorter. export function downloadGapMs( sleepBetweenDownloadsSeconds: number, paceSeconds: number, baseSeconds: number, - floor: { minSeconds?: number; random?: number } = {}, + floor: { minSeconds?: number; random?: number; spread?: number } = {}, ): number { let sleep = Math.max(0, sleepBetweenDownloadsSeconds); const min = floor.minSeconds ?? 0; + const r = Math.min(1, Math.max(0, floor.random ?? Math.random())); + const extra = Math.max(0, paceSeconds - baseSeconds); if (min > 0) { - const r = Math.min(1, Math.max(0, floor.random ?? Math.random())); sleep = Math.max(min, sleep) * (1 + 0.5 * r); + return Math.round((sleep + extra) * 1000); } - const extra = Math.max(0, paceSeconds - baseSeconds); - return Math.round((sleep + extra) * 1000); + return Math.round( + jitterUp(sleep + extra, floor.spread ?? pacingJitter(), () => r) * 1000, + ); } export type PlatformPacingState = { @@ -375,7 +388,10 @@ export function escalatePlatform( const wasHeld = isPlatformHeld(state.platformHolds, platform); const held = wasHeld || failsAtCap(entry.fails) >= pacing.holdAfterFailsAtCap; if (held) { - entry.until = now + pacing.holdProbeMinutes * 60_000; + // The probe's time stretched by up to pacing.jitter (only ever later). + entry.until = + now + + Math.ceil(jitterUp(pacing.holdProbeMinutes * 60_000, pacingJitter(), opts.rand ?? Math.random)); state.platformHolds[platform] = { since: state.platformHolds[platform]?.since ?? now, probeAt: entry.until, diff --git a/common/jobs/platformGap.test.ts b/common/jobs/platformGap.test.ts @@ -6,6 +6,7 @@ import { platformGapRemainingMs, waitForPlatformGap, } from "./platformGap"; +import { pacingJitter } from "../lib/jitter"; beforeEach(() => clearPlatformGaps()); @@ -14,7 +15,7 @@ test("a platform with no import yet is asked at once", () => { }); test("the next import waits the gap from when the last one settled, per platform", () => { - notePlatformGap("odysee", 60_000, 1_000); + notePlatformGap("odysee", 60_000, 1_000, () => 0); assert.equal(platformGapRemainingMs("odysee", 1_000), 60_000); assert.equal(platformGapRemainingMs("odysee", 31_000), 30_000); assert.equal(platformGapRemainingMs("odysee", 61_000), 0); @@ -22,13 +23,13 @@ test("the next import waits the gap from when the last one settled, per platform }); test("a later start is never shortened by a shorter gap", () => { - notePlatformGap("odysee", 90_000, 0); - notePlatformGap("odysee", 10_000, 5_000); + notePlatformGap("odysee", 90_000, 0, () => 0); + notePlatformGap("odysee", 10_000, 5_000, () => 0); assert.equal(platformGapRemainingMs("odysee", 5_000), 85_000); }); test("the gap lives on globalThis, so every bundle shares it", () => { - notePlatformGap("odysee", 1_000, 0); + notePlatformGap("odysee", 1_000, 0, () => 0); assert.equal(globalThis.__yttPlatformGap__?.get("odysee"), 1_000); }); @@ -70,3 +71,14 @@ test("an aborted job stops waiting", async () => { ac.abort(); await assert.rejects(p, { name: "AbortError" }); }); + +test("the gap is stretched by up to pacing.jitter, never shortened", () => { + clearPlatformGaps(); + notePlatformGap("rumble", 60_000, 0, () => 1); + const top = platformGapRemainingMs("rumble", 0); + assert.equal(top, Math.ceil(60_000 * (1 + pacingJitter()))); + clearPlatformGaps(); + notePlatformGap("rumble", 60_000, 0); + const any = platformGapRemainingMs("rumble", 0); + assert.ok(any >= 60_000 && any <= top, String(any)); +}); diff --git a/common/jobs/platformGap.ts b/common/jobs/platformGap.ts @@ -9,6 +9,8 @@ // Process-wide (on globalThis, as the job registry is: a route bundle and the // job runner must share one view) and in memory: a restart is itself a gap. +import { jitterMs } from "../lib/jitter"; + declare global { // eslint-disable-next-line no-var var __yttPlatformGap__: Map<string, number> | undefined; @@ -26,10 +28,16 @@ export function platformGapRemainingMs(platform: string, now: number = Date.now( } // A unit on `platform` settled at `now`: the next one starts no sooner than -// `gapMs` later. A later start already set is kept (never shortened). -export function notePlatformGap(platform: string, gapMs: number, now: number = Date.now()): void { +// `gapMs` later — stretched by up to `pacing.jitter` of itself (lib/jitter.mjs; +// only ever longer). A later start already set is kept (never shortened). +export function notePlatformGap( + platform: string, + gapMs: number, + now: number = Date.now(), + rand: () => number = Math.random, +): void { if (gapMs <= 0) return; - const at = now + gapMs; + const at = now + jitterMs(gapMs, rand); const map = nextStartAt(); if ((map.get(platform) ?? 0) < at) map.set(platform, at); } diff --git a/common/jobs/queueGap.test.ts b/common/jobs/queueGap.test.ts @@ -76,11 +76,13 @@ test("no end yet: no wait; an end: wait out the rest; the end is persisted and r delete process.env.E2E_JOB_GAP_SECONDS; const paths = await jobsDir(); const q = "platform:twitter"; - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_000_000 }), null); + // jitter 0: the exact gap (the jittered one has its own test below). + const exact = { jobGapSeconds: {}, jitter: 0 }; + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_000_000 }), null); await noteQueueJobEnd(paths, q, 1_000_000); - const w = await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_048_000 }); + const w = await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_048_000 }); assert.equal(w?.remainingMs, 252_000); - assert.equal(await queueGapWait({ paths, queueKey: q, pacing: undefined, now: 1_300_000 }), null); + assert.equal(await queueGapWait({ paths, queueKey: q, pacing: exact, now: 1_300_000 }), null); const file = JSON.parse(await readFile(path.join(paths.jobsDir, "queue-gaps.json"), "utf8")); assert.equal(file.ends[q], 1_000_000); clearQueueGaps(); // the restart @@ -101,7 +103,7 @@ test("waitForQueueGap waits, logs once per wait, tells the row, clears it", asyn const waited = await waitForQueueGap({ paths, queueKey: q, - pacing: () => undefined, + pacing: () => ({ jobGapSeconds: {}, jitter: 0 }), onLog: (l) => lines.push(l), onWait: (w) => seen.push(w ? w.reason : null), clock: { now: () => now, sleep: async (ms) => void (now += ms) }, @@ -111,6 +113,30 @@ test("waitForQueueGap waits, logs once per wait, tells the row, clears it", asyn assert.deepEqual(seen, ["Forum jobs are spaced 1 min apart (pacing.jobGapSeconds.xenforo)", null]); }); +test("the gap is stretched by up to pacing.jitter, the same on every re-read of one wait", async () => { + const paths = await jobsDir(); + const q = "platform:youtube"; + const end = 50_000_000; + await noteQueueJobEnd(paths, q, end); + const pacing = { jobGapSeconds: {}, jitter: 0.25 }; + const a = await queueGapWait({ paths, queueKey: q, pacing, now: end + 1 }); + const b = await queueGapWait({ paths, queueKey: q, pacing, now: end + 5_000 }); + assert.ok(a && b); + // Never shorter than the 20 s default, never more than a quarter longer. + assert.ok(a.until >= end + 20_000 && a.until <= end + 25_000, String(a.until - end)); + // Stable: a later read of the same wait ends at the same instant. + assert.equal(b.until, a.until); + // A different previous end draws a different share (seeded by it). + const draws = new Set<number>(); + for (let i = 0; i < 20; i++) { + await noteQueueJobEnd(paths, q, end + i * 100_000); + const w = await queueGapWait({ paths, queueKey: q, pacing, now: end + i * 100_000 + 1 }); + draws.add(w!.until - (end + i * 100_000)); + } + assert.ok(draws.size > 10, `only ${draws.size} distinct gaps`); + for (const g of draws) assert.ok(g >= 20_000 && g <= 25_000, String(g)); +}); + test("waitForQueueGap rejects on abort", async () => { const paths = await jobsDir(); const q = "platform:twitter"; diff --git a/common/jobs/queueGap.ts b/common/jobs/queueGap.ts @@ -30,6 +30,8 @@ import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server"; import { spanText, waitText } from "./queueGapText"; import { JOB_GAP_DEFAULT_SECONDS, jobGapSecondsFor } from "../lib/jobGap"; import type { PacingSettingsBlock } from "../lib/settingsSchema"; +import { jitterUpStable } from "../lib/jitter.mjs"; +import { pacingJitter } from "../lib/jitter"; export { spanText, waitText }; @@ -185,10 +187,16 @@ export type QueueGapWait = { }; // How long a network job on `queueKey` must still wait, or null for none. +// +// THE GAP IS JITTERED, STABLY. It is stretched by up to `pacing.jitter` of +// itself (lib/jitter.mjs: only ever longer, so "X jobs are spaced 5 min apart" +// stays true), and the share is drawn from the queue and the previous job's +// end — the same for every re-read of one wait (waitForQueueGap re-reads after +// each sleep; a fresh draw per read would end the wait at the shortest one). export async function queueGapWait(opts: { paths: Pick<Paths, "jobsDir">; queueKey: string; - pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined; + pacing: (Pick<PacingSettingsBlock, "jobGapSeconds"> & { jitter?: number }) | undefined; now: number; }): Promise<QueueGapWait | null> { const platform = queueGapPlatform(opts.queueKey); @@ -197,7 +205,15 @@ export async function queueGapWait(opts: { if (gap.seconds <= 0) return null; const last = await lastQueueEnd(opts.paths, opts.queueKey); if (last === undefined) return null; - const until = last + gap.seconds * 1000; + const until = + last + + Math.ceil( + jitterUpStable( + gap.seconds * 1000, + `${opts.queueKey}@${last}`, + opts.pacing?.jitter ?? pacingJitter(), + ), + ); if (until <= opts.now) return null; return { until, remainingMs: until - opts.now, reason: gapReason(platform, gap) }; } @@ -215,7 +231,7 @@ export function queueGapLine(w: QueueGapWait): string { export async function waitForQueueGap(opts: { paths: Pick<Paths, "jobsDir">; queueKey: string; - pacing: () => Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined; + pacing: () => (Pick<PacingSettingsBlock, "jobGapSeconds"> & { jitter?: number }) | undefined; signal?: AbortSignal; onLog?: (line: string) => void; onWait?: (wait: QueueGapWait | null) => void; @@ -226,7 +242,7 @@ export async function waitForQueueGap(opts: { try { for (;;) { if (opts.signal?.aborted) throw abortError(); - let pacing: Pick<PacingSettingsBlock, "jobGapSeconds"> | undefined; + let pacing: (Pick<PacingSettingsBlock, "jobGapSeconds"> & { jitter?: number }) | undefined; try { pacing = opts.pacing(); } catch { diff --git a/common/jobs/syncScheduler.test.ts b/common/jobs/syncScheduler.test.ts @@ -12,6 +12,9 @@ import { buildScheduleView, selectDueChannels, type ChannelEntry, + syncJitterMs, + SYNC_JITTER_CAP_MS, + nextEligibleAfterFailure, } from "./syncScheduler"; // Run with: @@ -260,3 +263,27 @@ test("the projection is unchanged by an empty priority document", () => { ], ); }); + +test("the sync jitter: a stable share of the interval, at most 30 minutes, 0 when off", () => { + assert.equal(syncJitterMs(1440, 0, "a@x"), 0); + assert.equal(syncJitterMs(0, 0.25, "a@x"), 0); + // Stable per seed: the same answer on every tick until the next sync. + assert.equal(syncJitterMs(1440, 0.25, "a@2026-10-25T00:00:00.000Z"), syncJitterMs(1440, 0.25, "a@2026-10-25T00:00:00.000Z")); + const seen = new Set<number>(); + for (let i = 0; i < 40; i++) { + const j = syncJitterMs(1440, 0.25, `ch-${i}@2026-10-25T00:00:00.000Z`); + // A daily interval's quarter is 6 h: capped at 30 min. + assert.ok(j >= 0 && j < SYNC_JITTER_CAP_MS, String(j)); + seen.add(j); + // A 60-minute interval is pushed by at most a quarter of it. + assert.ok(syncJitterMs(60, 0.25, `ch-${i}@x`) < 15 * 60_000); + } + assert.ok(seen.size > 30, `only ${seen.size} distinct pushes`); +}); + +test("nextEligibleAfterFailure: the backoff only grows with the jitter", () => { + const sched = { backoffBaseMinutes: 30, backoffMaxMinutes: 1440 } as never; + assert.equal(nextEligibleAfterFailure(0, 1, sched), 30 * 60_000); + assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 0), 30 * 60_000); + assert.equal(nextEligibleAfterFailure(0, 1, sched, 0.25, () => 1), Math.ceil(30 * 60_000 * 1.25)); +}); diff --git a/common/jobs/syncScheduler.ts b/common/jobs/syncScheduler.ts @@ -9,6 +9,7 @@ import { } from "../lib/channelPriority"; import { resolveFullSweepIntervalMinutes } from "./deepSync"; import type { SchedulerSkip, SchedulerState } from "./syncSchedulerState"; +import { jitterUp, stableUnit } from "../lib/jitter.mjs"; // Pure, side-effect-free scheduling logic for the cron-driven sync system. It // decides WHICH channels are due to sync right now; the editor tick route does @@ -39,8 +40,19 @@ export type SelectDueInput = { // against `transcripts/sites/*/site.json`, which is I/O this pure module must // not do. The caller runs `resolveFocusSlugs` and hands the answer in. focusSlugs?: readonly string[]; + // UPWARD-ONLY JITTER on each channel's interval (`pacing.jitter`, + // lib/jitter.mjs): a channel is due up to this share of its interval LATER + // than its interval says, capped at SYNC_JITTER_CAP_MS, so a daily sync does + // not come at the same minute every day. Drawn from the channel and its last + // sync, so it is the same on every tick until the next sync. Absent = 0, the + // exact interval (this module reads no settings; the tick passes it). + jitter?: number; }; +// The most a channel's sync is pushed back by the jitter, whatever its +// interval: a share of a 24 h interval would otherwise be hours. +export const SYNC_JITTER_CAP_MS = 30 * 60_000; + export type SelectDueResult = { // Slugs that should be synced now, ordered focus first, then by tier, then // by rank, then most-overdue first. @@ -91,12 +103,17 @@ export function backoffMinutes( // The epoch-ms instant a channel becomes eligible again after `failures` // consecutive failures observed at `now`. +// +// `spread` (`pacing.jitter`) lengthens the backoff by up to that share of +// itself, at random — never shortens it. Absent = the exact backoff. export function nextEligibleAfterFailure( now: number, failures: number, scheduler: SyncSchedulerSettings, + spread: number = 0, + rand: () => number = Math.random, ): number { - return now + backoffMinutes(failures, scheduler) * 60_000; + return now + Math.ceil(jitterUp(backoffMinutes(failures, scheduler) * 60_000, spread, rand)); } // Core selection. Evaluates each channel against the config gates, the channel @@ -150,7 +167,10 @@ export function selectDueChannels(input: SelectDueInput): SelectDueResult { continue; } - const overdueMs = overdueAmount(config.lastSyncedAt, interval, now); + const overdueMs = overdueAmount(config.lastSyncedAt, interval, now, { + spread: input.jitter ?? 0, + seed: slug, + }); if (overdueMs === null) continue; // not yet due due.push({ slug, @@ -227,6 +247,9 @@ export function buildScheduleView(input: { // projection must agree with the scheduler about who is skipped. Focus is // not needed — it changes the ORDER, not who is eligible. priority: ChannelPriority; + // The scheduler's jitter (SelectDueInput.jitter), so the next-due time shown + // is the one selectDueChannels will act on. + jitter?: number; }): ChannelScheduleView[] { const { channels, scheduler, state, now, priority } = input; return channels.map(({ slug, config }) => { @@ -245,7 +268,8 @@ export function buildScheduleView(input: { if (Number.isNaN(parsed)) { overdue = true; } else { - nextDueAt = parsed + interval * 60_000; + nextDueAt = + parsed + interval * 60_000 + syncJitterMs(interval, input.jitter ?? 0, `${slug}@${last}`); overdue = now >= nextDueAt; } } @@ -292,15 +316,28 @@ function nextFullSweepAt( // How far past its interval a channel is, in ms. A never-synced channel is // maximally overdue (Infinity) so it sorts first. Returns null when not yet due. +// +// With `jitter.spread` the interval is first lengthened by a stable share of +// itself (see SelectDueInput.jitter), at most SYNC_JITTER_CAP_MS. function overdueAmount( lastSyncedAt: string | undefined, intervalMinutes: number, now: number, + jitter: { spread: number; seed: string } = { spread: 0, seed: "" }, ): number | null { if (!lastSyncedAt) return Number.POSITIVE_INFINITY; const last = Date.parse(lastSyncedAt); if (Number.isNaN(last)) return Number.POSITIVE_INFINITY; // unparseable => sync const elapsed = now - last; - const intervalMs = intervalMinutes * 60_000; + const intervalMs = + intervalMinutes * 60_000 + syncJitterMs(intervalMinutes, jitter.spread, `${jitter.seed}@${lastSyncedAt}`); return elapsed >= intervalMs ? elapsed - intervalMs : null; } + +// How much later than its interval a channel is due: a stable share of the +// interval, at most SYNC_JITTER_CAP_MS. Exported for the tests. +export function syncJitterMs(intervalMinutes: number, spread: number, seed: string): number { + if (!(spread > 0) || !(intervalMinutes > 0)) return 0; + const room = Math.min(SYNC_JITTER_CAP_MS, intervalMinutes * 60_000 * Math.min(1, spread)); + return Math.floor(room * stableUnit(seed)); +} diff --git a/common/jobs/unitOutcome.test.ts b/common/jobs/unitOutcome.test.ts @@ -13,9 +13,14 @@ import { } from "./platformBackoff"; import { type UnitOutcomeState, applyUnitOutcome } from "./unitOutcome"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/unitOutcome.test.ts -const noJitter = () => 0.5; +// No jitter: the cooldown jitter is upward-only, so a draw of 0 adds nothing. +const noJitter = () => 0; const empty = (): UnitOutcomeState => ({ platformBackoff: {}, videoDeferrals: {}, diff --git a/common/lib/archiveOrgClient.test.ts b/common/lib/archiveOrgClient.test.ts @@ -30,7 +30,7 @@ function harness(script: Scripted[], opts: ConstructorParameters<typeof ArchiveO sleeps.push(ms); now += ms; }, - random: () => 0.5, // no jitter + random: () => 0, // no jitter (it is upward-only: a draw of 0 adds nothing) fetch: async (url, init) => { const headers = new Headers(init.headers); calls.push({ url, at: now, ua: headers.get("user-agent") }); @@ -145,7 +145,7 @@ function fileHarness(steps: FileStep[]) { sleep: async (ms) => { sleeps.push(ms); }, - random: () => 0.5, + random: () => 0, fetch: async (url, init) => { const h = new Headers(init.headers); ranges.push(h.get("range")); diff --git a/common/lib/archiveOrgClient.ts b/common/lib/archiveOrgClient.ts @@ -41,6 +41,8 @@ import { } from "./archiveOrgId"; import { createWriteStream } from "node:fs"; import { rename, rm, stat } from "node:fs/promises"; +import { jitterUp } from "./jitter.mjs"; +import { pacingJitter } from "./jitter"; export const ARCHIVE_ORG_USER_AGENT = `${PROJECT_NAME} archive.org import (+${PROJECT_URL})`; @@ -72,6 +74,9 @@ export type ArchiveOrgClientOpts = { // A file download that receives no bytes for this long is dropped (and // retried, resuming). idleTimeoutMs?: number; + // The share of itself each gap and back-off is stretched by, at random + // (lib/jitter.mjs). Default: the operator's pacing.jitter. + jitter?: number; }; // What getBounded answers: a body within the cap, a redirect, or "too large". @@ -152,6 +157,7 @@ export class ArchiveOrgClient { cacheTtlMs: opts.cacheTtlMs ?? 6 * 60 * 60 * 1000, timeoutMs: opts.timeoutMs ?? 60_000, idleTimeoutMs: opts.idleTimeoutMs ?? 120_000, + jitter: opts.jitter ?? pacingJitter(), }; } @@ -162,10 +168,17 @@ export class ArchiveOrgClient { return run; } + // Up to 20 % (or the operator's pacing.jitter, if larger) LONGER than the + // doubling — upward only: it used to land as much as 20 % short of it. private backoffMs(attempt: number): number { const exp = Math.min(this.opts.maxBackoffMs, this.opts.baseBackoffMs * 2 ** (attempt - 1)); - const jitter = 1 + (this.deps.random() * 0.4 - 0.2); - return Math.round(exp * jitter); + return Math.ceil(jitterUp(exp, Math.max(0.2, this.opts.jitter), this.deps.random)); + } + + // The gap before one request: minGapMs stretched by up to pacing.jitter, a + // fresh draw per request (lib/jitter.mjs — never shorter than minGapMs). + private gapMs(): number { + return Math.ceil(jitterUp(this.opts.minGapMs, this.opts.jitter, this.deps.random)); } // One GET, with the gap before it and the retry policy around it. With @@ -180,7 +193,7 @@ export class ArchiveOrgClient { ): Promise<Response> { let lastError = ""; for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { - const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + const wait = this.lastDoneAt + this.gapMs() - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, signal); this.requests++; let res: Response | null = null; @@ -318,7 +331,7 @@ export class ArchiveOrgClient { return this.serial(async () => { let lastError = ""; for (let attempt = 1; attempt <= this.opts.maxAttempts; attempt++) { - const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + const wait = this.lastDoneAt + this.gapMs() - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, init.signal); this.requests++; let res: Response | null = null; @@ -362,7 +375,7 @@ export class ArchiveOrgClient { // reads the answer and stops on a 429/503 rather than asking again. paced<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> { return this.serial(async () => { - const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + const wait = this.lastDoneAt + this.gapMs() - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, signal); this.requests++; try { @@ -438,7 +451,7 @@ export class ArchiveOrgClient { await rename(part, dest); return { bytes: have }; } - const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + const wait = this.lastDoneAt + this.gapMs() - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, signal); this.requests++; const ctl = new AbortController(); diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -232,6 +232,8 @@ const DECLARED: EnvVarDecl[] = [ { name: "E2E_AUDIO_CHECK_RECOVER_STEP_MS", audience: "test", default: "the real step", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery step." }, { name: "E2E_AUDIO_CHECK_RECOVER_AFTER", audience: "test", default: "the real count", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "Likewise, the recovery count." }, { name: "E2E_BACKOFF_BASE_MS", audience: "test", default: "`60000` (the real base)", readBy: "common/jobs/platformBackoff.ts", doc: "The first rate-limit cooldown, which every doubling starts from; the cap and the hold arithmetic keep the real constants. The editor's e2e server sets 20 s, so pacing.spec watches one lapse." }, + { name: "E2E_AVAILABILITY_PROBE_GAP_MS", audience: "test", default: "the real gap (3 s, stretched by `pacing.jitter`)", readBy: "common/controller/checkAvailability.ts", doc: "The pause after each per-video availability probe. The editor's e2e server and the availability unit tests set 0: their stub yt-dlp answers at once." }, + { name: "E2E_PACING_JITTER", audience: "test", default: "`pacing.jitter` from settings.json (0.25)", readBy: "common/lib/jitter.ts", doc: "Replaces the operator's jitter share (0–1) for every request-pacing wait. The unit tests that assert an exact gap set 0; the jitter itself is tested with its share passed in (lib/jitter.test.ts)." }, { name: "E2E_CLIP_WINDOW_GAP_MS", audience: "test", default: "the real gap (30–45 s, more for Rumble)", readBy: "common/controller/fetchWindows.ts, common/ytdlp/fetchWindowManaged.ts, editor/app/channels/[slug]/videos/[id]/videoActions.ts", doc: "The pause between two clip-window fetches in one batch, and the rest a cut from the stored media URL sets before the platform's next new file (20 min for real). The editor's e2e server sets 2 s, so fetch-window.spec sees the one it owes." }, { name: "E2E_JOB_GAP_SECONDS", audience: "test", default: "the built-in gaps (20 s; X 300, forums and Bluesky 60)", readBy: "common/jobs/queueGap.ts", doc: "Replaces every BUILT-IN `pacing.jobGapSeconds` gap (plans/pacing-guard.md); a gap set in settings.json still applies. The editor's e2e server sets 0, so two fake fetches on one platform queue do not wait; pacing.spec sets its own." }, { name: "E2E_X_MAX_COOKIE_AGE_MINUTES", audience: "test", default: "the built-in 60", readBy: "common/jobs/networkGuard.ts", doc: "Replaces the BUILT-IN `social.x.maxCookieAgeMinutes` (the fresh-jar rule for X jobs); a limit set in settings.json still applies. The editor's e2e server sets 0, so a fake X fetch needs no jar; x-session.spec sets its own." }, diff --git a/common/lib/jitter.mjs b/common/lib/jitter.mjs @@ -0,0 +1,105 @@ +// UPWARD-ONLY JITTER for every wait that decides when a request reaches a site. +// +// A source that counts requests sees their rhythm as well as their rate: a job +// every 20.0 s, a page every 3.0 s, a sync at the same minute each day is a +// machine's beat. So each such number is stretched by a random share of itself +// before it is waited — and ONLY stretched. Every pacing number in this repo is +// a floor someone measured or was told to keep (Rumble's 120 s, X's 5 min): +// jitter may make a wait longer, never shorter, so a floor stays a floor. +// +// `spread` is the largest share added: 0.25 makes a 20 s gap land anywhere in +// [20, 25) s. 0 turns jitter off (the number is returned as is). The operator's +// value is `pacing.jitter` in settings.json — the TS wrapper (./jitter.ts) +// reads it; plain-JS callers (umtool) pass a spread or take the default. +// +// Plain JS so umtool's .mjs scripts and common's TS share one implementation. + +export const DEFAULT_JITTER_SPREAD = 0.25; +export const MAX_JITTER_SPREAD = 1; + +/** @param {unknown} spread */ +export function clampSpread(spread) { + const n = typeof spread === "number" && Number.isFinite(spread) ? spread : DEFAULT_JITTER_SPREAD; + return Math.min(MAX_JITTER_SPREAD, Math.max(0, n)); +} + +/** + * `value` stretched by a random share of itself in [0, spread). Never smaller + * than `value`; a non-positive or non-finite value is returned unchanged. + * @param {number} value + * @param {number} [spread] + * @param {() => number} [rand] in [0, 1) + * @returns {number} + */ +export function jitterUp(value, spread = DEFAULT_JITTER_SPREAD, rand = Math.random) { + if (!Number.isFinite(value) || value <= 0) return value; + const s = clampSpread(spread); + if (s === 0) return value; + const r = Math.min(1, Math.max(0, rand())); + return value * (1 + s * r); +} + +/** + * A STABLE draw in [0, 1) for a seed — the same seed always gives the same + * share. For a wait that is re-computed on every poll of one wait (the job gap + * re-reads its gap each pass): a fresh draw per pass would let the shortest + * draw win, which is no jitter at all. FNV-1a over the seed's UTF-16 units. + * @param {string} seed + * @returns {number} + */ +export function stableUnit(seed) { + let h = 0x811c9dc5; + for (let i = 0; i < seed.length; i++) { + h ^= seed.charCodeAt(i); + h = Math.imul(h, 0x01000193) >>> 0; + } + // Mix the low bits up so neighbouring seeds don't draw neighbouring shares. + h ^= h >>> 15; + h = Math.imul(h, 0x2c1b3c6d) >>> 0; + h ^= h >>> 12; + return (h >>> 0) / 0x100000000; +} + +/** + * `jitterUp` with the draw fixed by `seed`. + * @param {number} value + * @param {string} seed + * @param {number} [spread] + */ +export function jitterUpStable(value, seed, spread = DEFAULT_JITTER_SPREAD) { + return jitterUp(value, spread, () => stableUnit(seed)); +} + +/** + * Seconds as a yt-dlp/gallery-dl argument: at most two decimals, never rounded + * DOWN below the value (a 1.004 s pace is written 1.01, not 1). + * @param {number} seconds + */ +export function secondsArg(seconds) { + const up = Math.ceil(seconds * 100) / 100; + return String(Number.isInteger(up) ? up : Number(up.toFixed(2))); +} + +/** + * `args` with the value after each `--sleep-requests` / `--sleep-subtitles` + * (and the other fixed yt-dlp waits) stretched by `jitterUp`. Every occurrence + * is stretched because yt-dlp takes the last one. Returns a copy. + * @param {readonly string[]} args + * @param {number} [spread] + * @param {() => number} [rand] + * @returns {string[]} + */ +export function jitterSleepArgs(args, spread = DEFAULT_JITTER_SPREAD, rand = Math.random) { + const out = [...args]; + if (clampSpread(spread) === 0) return out; + for (let i = 0; i < out.length - 1; i++) { + if (!SLEEP_FLAGS.has(out[i])) continue; + const v = Number(out[i + 1]); + if (Number.isFinite(v) && v > 0) out[i + 1] = secondsArg(jitterUp(v, spread, rand)); + } + return out; +} + +// yt-dlp's FIXED waits. `--sleep-interval`/`--max-sleep-interval` are left alone: +// yt-dlp already draws that one at random between the two. +const SLEEP_FLAGS = new Set(["--sleep-requests", "--sleep-subtitles"]); diff --git a/common/lib/jitter.test.ts b/common/lib/jitter.test.ts @@ -0,0 +1,88 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + DEFAULT_JITTER_SPREAD, + clampSpread, + jitterSleepArgs, + jitterUp, + jitterUpStable, + secondsArg, + stableUnit, +} from "./jitter.mjs"; + +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/jitter.test.ts +// +// UPWARD-ONLY JITTER: every request-pacing wait is stretched by up to +// `pacing.jitter` of itself, never shortened, so a floor stays a floor. + +test("jitterUp only ever lengthens, by at most the spread", () => { + assert.equal(jitterUp(20, 0.25, () => 0), 20); + assert.equal(jitterUp(20, 0.25, () => 1), 25); + assert.equal(jitterUp(20, 0.25, () => 0.5), 22.5); + for (let i = 0; i < 200; i++) { + const v = jitterUp(120, 0.25); + assert.ok(v >= 120 && v <= 150, String(v)); + } +}); + +test("spread 0 is off; the spread is clamped to [0, 1]; a bad draw is clamped", () => { + assert.equal(jitterUp(20, 0, () => 1), 20); + assert.equal(clampSpread(-1), 0); + assert.equal(clampSpread(5), 1); + assert.equal(clampSpread(undefined), DEFAULT_JITTER_SPREAD); + assert.equal(jitterUp(20, 0.25, () => 9), 25); + assert.equal(jitterUp(20, 0.25, () => -3), 20); +}); + +test("nothing to stretch is returned as is", () => { + assert.equal(jitterUp(0, 0.25, () => 1), 0); + assert.equal(jitterUp(-5, 0.25, () => 1), -5); + assert.ok(Number.isNaN(jitterUp(Number.NaN, 0.25, () => 1))); +}); + +test("a stable draw is the same for a seed and spread across seeds", () => { + assert.equal(stableUnit("platform:youtube@1000"), stableUnit("platform:youtube@1000")); + const draws = new Set<number>(); + for (let i = 0; i < 500; i++) { + const u = stableUnit(`seed-${i}`); + assert.ok(u >= 0 && u < 1, String(u)); + draws.add(Math.floor(u * 10)); + } + // Every tenth of [0, 1) is hit — the draw is not bunched. + assert.equal(draws.size, 10); + assert.equal(jitterUpStable(20, "a", 0.25), jitterUpStable(20, "a", 0.25)); +}); + +test("secondsArg rounds UP to two decimals", () => { + assert.equal(secondsArg(1), "1"); + assert.equal(secondsArg(1.004), "1.01"); + assert.equal(secondsArg(1.25), "1.25"); + assert.equal(secondsArg(5.123), "5.13"); +}); + +test("jitterSleepArgs stretches every fixed yt-dlp wait and nothing else", () => { + const args = [ + "--sleep-requests", "1", + "--sleep-subtitles", "5", + "--sleep-interval", "10", + "--max-sleep-interval", "20", + "--retries", "3", + "--sleep-requests", "2", + ]; + const out = jitterSleepArgs(args, 0.25, () => 1); + assert.deepEqual(out, [ + "--sleep-requests", "1.25", + "--sleep-subtitles", "6.25", + // yt-dlp already draws this one between the two. + "--sleep-interval", "10", + "--max-sleep-interval", "20", + "--retries", "3", + // yt-dlp takes the last occurrence, so every one is stretched. + "--sleep-requests", "2.5", + ]); + // A copy; the input is untouched. Off is a plain copy. + assert.equal(args[1], "1"); + assert.deepEqual(jitterSleepArgs(args, 0, () => 1), args); + // A flag with no value at the end is left alone. + assert.deepEqual(jitterSleepArgs(["--sleep-requests"], 0.25, () => 1), ["--sleep-requests"]); +}); diff --git a/common/lib/jitter.ts b/common/lib/jitter.ts @@ -0,0 +1,53 @@ +// The operator's jitter (settings.json `pacing.jitter`) over ./jitter.mjs — see +// there for why every request-pacing wait is stretched, and only stretched. + +import { getSettings } from "./settings"; +import { + clampSpread, + jitterSleepArgs, + jitterUp, + jitterUpStable, +} from "./jitter.mjs"; + +export { secondsArg, stableUnit } from "./jitter.mjs"; + +// The spread in force. A settings read that throws (no settings file in a +// bare test) falls back to the default rather than to no jitter. +export function pacingJitter(): number { + // TEST-ONLY: E2E_PACING_JITTER replaces the operator's share (the unit tests + // that assert an exact gap set 0). Unset everywhere else. + const raw = process.env.E2E_PACING_JITTER; + if (raw !== undefined && raw.trim() !== "" && Number.isFinite(Number(raw))) { + return clampSpread(Number(raw)); + } + try { + return clampSpread(getSettings().pacing?.jitter); + } catch { + return clampSpread(undefined); + } +} + +// `value` (any unit) stretched by up to `pacing.jitter` of itself. +export function jitter(value: number, rand: () => number = Math.random): number { + return jitterUp(value, pacingJitter(), rand); +} + +// Milliseconds, stretched and rounded UP to a whole millisecond. +export function jitterMs(ms: number, rand: () => number = Math.random): number { + return Math.ceil(jitter(ms, rand)); +} + +// The same stretch every time for one `seed` — for a wait re-computed on each +// poll of itself (see stableUnit). +export function jitterMsStable(ms: number, seed: string): number { + return Math.ceil(jitterUpStable(ms, seed, pacingJitter())); +} + +// yt-dlp args with their fixed waits (`--sleep-requests`, `--sleep-subtitles`) +// stretched — once per spawn, since yt-dlp itself waits exactly what it is told. +export function jitterYtdlpSleeps( + args: readonly string[], + rand: () => number = Math.random, +): string[] { + return jitterSleepArgs(args, pacingJitter(), rand); +} diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -779,6 +779,9 @@ export type PacingSettingsBlock = { // keys the operator set are stored; the rest come from // JOB_GAP_DEFAULT_SECONDS at read time (jobGapSecondsFor). jobGapSeconds: Partial<Record<string, number>>; + // UPWARD-ONLY JITTER (common/lib/jitter.mjs): the largest share of itself a + // request-pacing wait is stretched by, at random. 0 = off. + jitter: number; }; export const PACING_SETTINGS_FIELD_DOCS: FieldDocs<PacingSettingsBlock> = { @@ -810,12 +813,27 @@ export const PACING_SETTINGS_FIELD_DOCS: FieldDocs<PacingSettingsBlock> = { "300, xenforo 60, bluesky 60 — only the keys set here are stored. 0 for a key: no gap on that " + "platform. At most 86400. Set on /settings beside the download sleep. " + "common/jobs/queueGap.ts.", + jitter: + "THE SHARE OF ITSELF EVERY WAIT BEFORE A REQUEST IS STRETCHED BY, AT RANDOM, so the archive " + + "does not ask a site on a fixed beat. 0.25 makes a 20 s job gap land anywhere from 20 to " + + "25 s. It only ever ADDS time: every pacing number stays a minimum (Rumble's 120 s, X's " + + "5 min, the between-downloads sleep). It stretches the gap between two downloads and two " + + "jobs on one platform, yt-dlp's `--sleep-requests` and `--sleep-subtitles` (drawn once " + + "per yt-dlp run), the archive.org, Wayback and web-fetch gaps, the rate-limit cooldowns, " + + "the download lane's metadata-scan batches and rests, and a channel's sync interval (by " + + "at most 30 minutes). 0 turns it off. Clamped 0–1; default 0.25. common/lib/jitter.mjs.", }; export const PACING_DEFAULT_SLEEP_REQUESTS_CAP_SECONDS = 16; export const PACING_DEFAULT_DECAY_AFTER_CLEAN_UNITS = 5; export const PACING_DEFAULT_HOLD_AFTER_FAILS_AT_CAP = 3; export const PACING_DEFAULT_HOLD_PROBE_MINUTES = 60; +export const PACING_DEFAULT_JITTER = 0.25; + +function clampFraction(v: unknown, dflt: number): number { + if (typeof v !== "number" || !Number.isFinite(v)) return dflt; + return Math.min(1, Math.max(0, v)); +} function clampInt(v: unknown, min: number, max: number, dflt: number): number { if (typeof v !== "number" || !Number.isFinite(v)) return dflt; @@ -850,6 +868,7 @@ export function sanitizePacing(v: unknown): PacingSettingsBlock { PACING_DEFAULT_HOLD_PROBE_MINUTES, ), jobGapSeconds: sanitizeJobGapSeconds(r.jobGapSeconds), + jitter: clampFraction(r.jitter, PACING_DEFAULT_JITTER), }; } diff --git a/common/lib/web/pacer.ts b/common/lib/web/pacer.ts @@ -9,6 +9,8 @@ // The editor's `web-search` / `web-fetch` actions and a job's agent tools // share the process's pacer (`webPacer`), so two callers in one editor never // make two streams. +import { jitterUp } from "../jitter.mjs"; +import { pacingJitter } from "../jitter"; export const WEB_MIN_GAP_MS = 3_000; export const WEB_BACKOFF_BASE_MS = 10_000; @@ -23,6 +25,7 @@ export type WebPacerDeps = { fetch?: (url: string, init: RequestInit) => Promise<Response>; now?: () => number; sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; + random?: () => number; }; export type WebPacerOpts = { @@ -31,6 +34,9 @@ export type WebPacerOpts = { backoffMaxMs?: number; maxAttempts?: number; timeoutMs?: number; + // The share of itself each gap and back-off is stretched by, at random + // (lib/jitter.mjs — only ever longer). Default: the operator's pacing.jitter. + jitter?: number; }; export class WebRequestError extends Error { @@ -79,6 +85,7 @@ export class WebPacer { fetch: deps.fetch ?? ((url, init) => fetch(url, init)), now: deps.now ?? (() => Date.now()), sleep: deps.sleep ?? defaultSleep, + random: deps.random ?? Math.random, }; this.opts = { minGapMs: opts.minGapMs ?? WEB_MIN_GAP_MS, @@ -86,6 +93,7 @@ export class WebPacer { backoffMaxMs: opts.backoffMaxMs ?? WEB_BACKOFF_MAX_MS, maxAttempts: opts.maxAttempts ?? WEB_MAX_ATTEMPTS, timeoutMs: opts.timeoutMs ?? WEB_TIMEOUT_MS, + jitter: opts.jitter ?? pacingJitter(), }; } @@ -106,7 +114,8 @@ export class WebPacer { ): Promise<T> { return this.serial(async () => { for (let attempt = 1; ; attempt++) { - const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + const gap = Math.ceil(jitterUp(this.opts.minGapMs, this.opts.jitter, this.deps.random)); + const wait = this.lastDoneAt + gap - this.deps.now(); if (wait > 0) await this.deps.sleep(wait, init.signal); this.sent.push({ url, at: this.deps.now() }); let res: Response; @@ -133,7 +142,10 @@ export class WebPacer { } const told = retryAfterMs(res.headers.get("retry-after"), this.deps.now()); const backoff = Math.min(this.opts.backoffMaxMs, told ?? this.opts.backoffBaseMs * 2 ** (attempt - 1)); - await this.deps.sleep(backoff, init.signal); + await this.deps.sleep( + Math.ceil(jitterUp(backoff, this.opts.jitter, this.deps.random)), + init.signal, + ); continue; } try { diff --git a/common/lib/web/web.test.ts b/common/lib/web/web.test.ts @@ -24,7 +24,8 @@ before(async () => { after(() => web.close()); // A pacer on a fake clock: sleeping advances it, and every sleep is recorded. -function clockPacer(opts: ConstructorParameters<typeof WebPacer>[1] = {}) { +// jitter 0 unless a test asks: the gaps below are the exact ones. +function clockPacer(opts: ConstructorParameters<typeof WebPacer>[1] = { jitter: 0 }) { let now = 1_000_000; const sleeps: number[] = []; const pacer = new WebPacer( diff --git a/common/package.json b/common/package.json @@ -42,6 +42,7 @@ "./lib/cueWiden.mjs": "./lib/cueWiden.mjs", "./lib/detectPlatform.mjs": "./lib/detectPlatform.mjs", "./lib/evidenceClip.mjs": "./lib/evidenceClip.mjs", + "./lib/jitter.mjs": "./lib/jitter.mjs", "./lib/montage/cueTextCache.mjs": "./lib/montage/cueTextCache.mjs", "./lib/montage/phraseScan.mjs": "./lib/montage/phraseScan.mjs", "./lib/montage/phraseSource.mjs": "./lib/montage/phraseSource.mjs", diff --git a/common/social/blueskyFetcher.ts b/common/social/blueskyFetcher.ts @@ -31,7 +31,12 @@ import { type SocialFetcherProbe, } from "./fetchers"; import { blueskyEndpoints } from "./blueskyEndpoints"; -import { captureBlueskyPosts, liveBlueskyCaptureDeps } from "./blueskyPostCapture"; +import { + blueskyPageGapMs, + captureBlueskyPosts, + liveBlueskyCaptureDeps, + sleepUnlessAborted, +} from "./blueskyPostCapture"; // The AppView's origin, read per call (blueskyEndpoints.ts: a test's fake). const appview = () => blueskyEndpoints().appview; @@ -419,6 +424,12 @@ export const blueskyFetcher: SocialFetcher = { for (let page = 0; page < MAX_PAGES; page++) { if (signal.aborted) break; + // A gap before every page after the first: they used to go back to back. + // The capture's own page gap, 3–6 s (blueskyPageGapMs). + if (page > 0) { + await sleepUnlessAborted(blueskyPageGapMs(Math.random), signal).catch(() => {}); + if (signal.aborted) break; + } const body = await getAuthorFeed(handle, cursor, signal); const items = body.feed ?? []; if (items.length === 0) { diff --git a/common/social/xNitterFetcher.ts b/common/social/xNitterFetcher.ts @@ -35,6 +35,7 @@ import { type SocialFetcher, type SocialFetcherProbe, } from "./fetchers"; +import { jitterMs } from "../lib/jitter"; // Ordered by preference. Override with NITTER_INSTANCES (comma-separated) — // instances die often enough that hardcoding one is a liability. @@ -55,6 +56,8 @@ export function nitterInstances(): string[] { // Bound how far back one run walks, so a huge account can't spin forever. const MAX_PAGES = 40; +// The least time between two timeline pages on one instance. +const NITTER_PAGE_GAP_MS = 4_000; // --------------------------------------------------------------------------- // Pure parsing helpers (no DOM, no network — unit-tested against real values) @@ -286,6 +289,10 @@ export const xNitterFetcher: SocialFetcher = { try { for (; pages < MAX_PAGES; pages++) { if (signal.aborted) break; + // A gap before every page after the first: they used to load back + // to back. NITTER_PAGE_GAP_MS, stretched by pacing.jitter. + if (pages > 0) await new Promise((r) => setTimeout(r, jitterMs(NITTER_PAGE_GAP_MS))); + if (signal.aborted) break; const url = `${instance}/${handle}${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ""}`; await page.goto(url, { waitUntil: "domcontentloaded", timeout: 45_000 }); // The HTTP status is NOT the success signal — poast serves 503 diff --git a/common/social/xenforoFetcher.test.ts b/common/social/xenforoFetcher.test.ts @@ -368,11 +368,11 @@ test("a bad cursor and a URL that is not a thread are refused before any load", assert.equal(loader.urls.length, 0); }); -test("pacing: jittered around the base, never below the floor", () => { - assert.equal(jitteredPause(DEFAULT_PAGE_PAUSE_MS, () => 0), Math.round(DEFAULT_PAGE_PAUSE_MS * 0.85)); - assert.ok(jitteredPause(DEFAULT_PAGE_PAUSE_MS, () => 0.999) <= 20_000); - assert.ok(jitteredPause(DEFAULT_PAGE_PAUSE_MS, () => 0) >= 10_000); - assert.equal(jitteredPause(100, () => 0), Math.round(MIN_PAGE_PAUSE_MS * 0.85)); +test("pacing: jittered above the base, never below it or the floor", () => { + assert.equal(jitteredPause(DEFAULT_PAGE_PAUSE_MS, () => 0), DEFAULT_PAGE_PAUSE_MS); + assert.ok(jitteredPause(DEFAULT_PAGE_PAUSE_MS, () => 0.999) <= DEFAULT_PAGE_PAUSE_MS * 1.8); + assert.ok(jitteredPause(DEFAULT_PAGE_PAUSE_MS, () => 0.5) > DEFAULT_PAGE_PAUSE_MS); + assert.equal(jitteredPause(100, () => 0), MIN_PAGE_PAUSE_MS); }); test("block failures: which ones ask for Connect", () => { diff --git a/common/social/xenforoFetcher.ts b/common/social/xenforoFetcher.ts @@ -90,11 +90,12 @@ export const DEFAULT_PAGE_PAUSE_MS = FORUM_DEFAULT_PAGE_PAUSE_SECONDS * 1000; // The floor a configured pause is held to. export const MIN_PAGE_PAUSE_MS = FORUM_MIN_PAGE_PAUSE_SECONDS * 1000; -// The pause before a load: `base` jittered to [0.85, 1.65) of itself — 12 s -// gives 10.2–19.8 s. +// The pause before a load: `base` (at least the floor) jittered to [1, 1.8) of +// itself — 12 s gives 12–21.6 s. Upward only (lib/jitter.mjs): it used to reach +// down to 0.85 of the base, under the floor it had just been held to. export function jitteredPause(base: number, random: () => number): number { const b = Math.max(MIN_PAGE_PAUSE_MS, base); - return Math.round(b * (0.85 + random() * 0.8)); + return Math.ceil(b * (1 + random() * 0.8)); } export function sleepUnlessAborted(ms: number, signal: AbortSignal): Promise<void> { diff --git a/common/views/schedulerStatus.ts b/common/views/schedulerStatus.ts @@ -34,6 +34,8 @@ export type SchedulerStatusInputs = { settings: { syncScheduler: SyncSchedulerSettings; channelPriority: ChannelPriority; + // `pacing.jitter`, so the next-due times shown are the scheduler's own. + pacing?: { jitter?: number }; }; now: number; state: SchedulerState; @@ -53,6 +55,7 @@ export function buildSchedulerStatusPayload( state, now, priority: settings.channelPriority, + jitter: settings.pacing?.jitter ?? 0, }); return { now, diff --git a/common/views/widgetSync.test.ts b/common/views/widgetSync.test.ts @@ -179,6 +179,8 @@ test("kinds are sorted by reachable descending, tie-broken by id", () => { test("nextRunAt and overdue come off buildScheduleView, over eligible channels only", () => { const settings = defaultSiteSettings(); + // The exact intervals: the sync jitter is pacing.jitter's (syncScheduler.test). + settings.pacing = { ...settings.pacing, jitter: 0 }; settings.syncScheduler = { ...settings.syncScheduler, enabled: true, diff --git a/common/views/widgetSync.ts b/common/views/widgetSync.ts @@ -194,6 +194,7 @@ export function buildWidgetSyncPayload( state, now, priority: settings.channelPriority, + jitter: settings.pacing?.jitter ?? 0, }); const eligible = view.filter((v) => v.autoSyncEligible); let nextRunAt: number | null = null; diff --git a/common/ytdlp/audioCheckedDownload.ts b/common/ytdlp/audioCheckedDownload.ts @@ -52,6 +52,7 @@ import { import type { StreamVerdict } from "./ffmpegStreamClassify"; import { probeAudioStream } from "./ffmpegStreamProbe"; import { DLOM_PROBE_MARKER } from "../jobs/progressParsers"; +import { jitterYtdlpSleeps } from "../lib/jitter"; const STDERR_TAIL_BYTES = 64 * 1024; const DEFAULT_SIZE_GATE_BYTES = 1024 * 1024; // 1 MiB minimum growth between checks @@ -856,8 +857,10 @@ export async function runAudioCheckedYtdlp( opts.signal.addEventListener("abort", onParentAbort, { once: true }); } - opts.onLog(`$ ${opts.paths.ytdlpBin} ${opts.ytdlpArgs.join(" ")}\n`); - const child = execa(opts.paths.ytdlpBin, opts.ytdlpArgs, { + // The fixed waits drawn once for this run (lib/jitter.mjs). + const spawned = jitterYtdlpSleeps(opts.ytdlpArgs); + opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); + const child = execa(opts.paths.ytdlpBin, spawned, { cwd: opts.channelDir, cancelSignal: launchAc.signal, all: false, diff --git a/common/ytdlp/fetchWindowStoredCut.test.ts b/common/ytdlp/fetchWindowStoredCut.test.ts @@ -26,6 +26,10 @@ import { fetchWindows } from "../controller/fetchWindows"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + const ROOT = await mkdtemp(path.join(os.tmpdir(), "storedcut-")); const FFMPEG = path.join(ROOT, "fake-ffmpeg.mjs"); await writeFile( diff --git a/common/ytdlp/managedDownloadsSleep.test.ts b/common/ytdlp/managedDownloadsSleep.test.ts @@ -10,6 +10,10 @@ import type { } from "../lib/downloadOutcome"; import type { DownloadFailureClass } from "../lib/availability"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/managedDownloadsSleep.test.ts // diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts @@ -47,6 +47,7 @@ import { type MetadataScanError, type MetadataScanRun, } from "../controller/metadataScanStore"; +import { jitterYtdlpSleeps } from "../lib/jitter"; // yt-dlp's JSON-subset print template: one JSON object per entry, so the scan // parses lines instead of whole info jsons — and so nothing is ever written to @@ -429,9 +430,11 @@ export async function runMetadataScan( batchFile, ...channelExtraArgs(channelConfig, cookies), ]; - opts.onLog(`$ ${paths.ytdlpBin} ${args.join(" ")}\n`); + // The fixed waits drawn once for this run (lib/jitter.mjs). + const spawned = jitterYtdlpSleeps(args); + opts.onLog(`$ ${paths.ytdlpBin} ${spawned.join(" ")}\n`); - const child = execa(paths.ytdlpBin, args, { + const child = execa(paths.ytdlpBin, spawned, { cwd: channelDir, cancelSignal: opts.signal, all: false, diff --git a/common/ytdlp/runOneYtdlp.ts b/common/ytdlp/runOneYtdlp.ts @@ -12,6 +12,7 @@ import { execa } from "execa"; import type { Paths } from "../lib/paths"; import { observeYtdlpServiceOutcome } from "../lib/serviceCookies-server"; +import { jitterYtdlpSleeps } from "../lib/jitter"; export const STDERR_TAIL_BYTES = 64 * 1024; @@ -56,8 +57,10 @@ export async function runOneYtdlp( cwd: string, args: string[], ): Promise<AttemptOutcome> { - opts.onLog(`$ ${opts.ytdlpBin} ${args.join(" ")}\n`); - const child = execa(opts.ytdlpBin, args, { + // The fixed waits drawn once for this run (lib/jitter.mjs). + const spawned = jitterYtdlpSleeps(args); + opts.onLog(`$ ${opts.ytdlpBin} ${spawned.join(" ")}\n`); + const child = execa(opts.ytdlpBin, spawned, { cwd, cancelSignal: opts.signal, all: false, diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -99,6 +99,7 @@ import { import type { TaskTracker } from "../jobs/taskHooks"; import type { JobProgress } from "../jobs/registry"; import { heldAudioDamage } from "../lib/audioIntegrity-server"; +import { jitterYtdlpSleeps } from "../lib/jitter"; export type YtdlpMode = | "store-playlist" @@ -526,10 +527,12 @@ async function enumeratePlaylistUrls( ), opts.channelConfig.url!, ); - opts.onLog(`$ ${opts.paths.ytdlpBin} ${args.join(" ")}\n`); + // The fixed waits drawn once for this run (lib/jitter.mjs). + const spawned = jitterYtdlpSleeps(args); + opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); if (opts.requestCounter) opts.requestCounter.n++; - const child = execa(opts.paths.ytdlpBin, args, { + const child = execa(opts.paths.ytdlpBin, spawned, { cwd: root, cancelSignal: opts.signal, all: false, @@ -627,8 +630,9 @@ export async function probeChannelMeta(opts: { ...pacedPlatformArgs(detectPlatform(url)), url, ]; - log(`$ ${paths.ytdlpBin} ${args.join(" ")}\n`); - const child = execa(paths.ytdlpBin, args, { + const spawned = jitterYtdlpSleeps(args); + log(`$ ${paths.ytdlpBin} ${spawned.join(" ")}\n`); + const child = execa(paths.ytdlpBin, spawned, { cancelSignal: opts.signal, all: false, buffer: true, @@ -2290,9 +2294,10 @@ async function runChildAndStream( cwd: string, args: string[], ): Promise<string> { - opts.onLog(`$ ${opts.paths.ytdlpBin} ${args.join(" ")}\n`); + const spawned = jitterYtdlpSleeps(args); + opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); if (opts.requestCounter) opts.requestCounter.n++; - const child = execa(opts.paths.ytdlpBin, args, { + const child = execa(opts.paths.ytdlpBin, spawned, { cwd, cancelSignal: opts.signal, all: true, diff --git a/common/ytdlp/storedUrlDownload.ts b/common/ytdlp/storedUrlDownload.ts @@ -63,6 +63,7 @@ import { backoffInterval, formatInterval, recoverInterval, type CadenceParams } import type { StreamVerdict } from "./ffmpegStreamClassify"; import { probeAudioStream } from "./ffmpegStreamProbe"; import { abortableWait, type PageOpener } from "./storedUrlPageOpen"; +import { jitterMs } from "../lib/jitter"; // One ranged read. The player asks for a few MiB at a time; 8 MiB keeps a 3 GB // file to ~400 requests of one connection each, one after another. @@ -253,7 +254,12 @@ export async function storedUrlDownload( const fetchImpl = opts.deps?.fetch ?? ((u: string, i: RequestInit) => fetch(u, i)); const chunkBytes = Math.max(1, opts.deps?.chunkBytes ?? STORED_URL_CHUNK_BYTES); const now = opts.deps?.now ?? Date.now; - const dropPauseMs = Math.max(0, opts.deps?.dropPauseMs ?? STORED_URL_DROP_PAUSE_MS); + // The default pause is stretched by up to pacing.jitter (lib/jitter.mjs); a + // pause a caller passes (the tests) is waited exactly. + const dropPauseMs = + opts.deps?.dropPauseMs !== undefined + ? Math.max(0, opts.deps.dropPauseMs) + : jitterMs(STORED_URL_DROP_PAUSE_MS); const maxDrops = Math.max(0, opts.deps?.maxDrops ?? STORED_URL_MAX_DROPS); const sleep = opts.deps?.sleep ?? ((ms: number, s?: AbortSignal) => abortableWait(ms, s ?? signal)); const knobs: Knobs = { ...resolveKnobs({ channelConfig: opts.channelConfig }), ...(opts.deps?.knobs ?? {}) }; diff --git a/common/ytdlp/storedUrlManaged.test.ts b/common/ytdlp/storedUrlManaged.test.ts @@ -20,6 +20,10 @@ import { clearPlatformGaps, platformGapRemainingMs } from "../jobs/platformGap"; import { storedUrlGapKey } from "../lib/storedMediaUrl"; import { downloadOneManaged, type ManagedDownloadOpts } from "./downloadOneManaged"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + const FF = hasFfmpeg(); const CLAIM = "FAKE-TEST-VALUEFAKE-TEST-VALUE01234567"; const FILE_PATH = `/v6/streams/${CLAIM}/a1b2c3.mp4`; diff --git a/common/ytdlp/subtitleRateLimit.test.ts b/common/ytdlp/subtitleRateLimit.test.ts @@ -8,6 +8,10 @@ import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import { downloadOneManaged } from "./downloadOneManaged"; +// The exact gaps: the jitter on them is tested in lib/jitter.test.ts and +// beside each wait (E2E_PACING_JITTER, lib/envVars.ts). +process.env.E2E_PACING_JITTER = "0"; + // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/subtitleRateLimit.test.ts // diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **Every wait before the archive asks a site now varies a little, and only ever upward.** A job every 20.0 s, a page every 3.0 s or a sync at the same minute each day is a machine's beat, so each such wait is now stretched by up to a quarter of itself at random, and never shortened: every pacing number stays a minimum (Rumble's 120 s, X's 5 min, the sleep between downloads). It covers the gap between two downloads and between two jobs on one platform, yt-dlp's `--sleep-requests` and `--sleep-subtitles` (drawn once per yt-dlp run, and shown in its logged command line), the archive.org, Wayback and web-fetch gaps, the rate-limit cooldowns and the platform hold's probe, the download lane's metadata-scan batches (60 to 75 titles) and its rests, Save Page Now's and the Kick recorder's polls, and each channel's sync interval (later by at most 30 minutes, the same on every tick until it syncs, and shown so on /operations/sync). The share is **Jitter on every wait before a request** on /settings (`pacing.jitter`, default 25 %; 0 turns it off). Three waits that already varied could come out SHORTER than their minimum and no longer do: the platform cooldown (±10 %), archive.org's back-off (±20 %) and a forum's page pause (as little as 0.85 of it, under its own 5 s floor). It now lands between the pause and 1.8 times it. Four loops that asked a site with no gap at all now wait between requests: a Bluesky feed's pages (3–6 s), a Nitter timeline's pages (4 s and up), the availability check's per-video probes (3 s and up) and umtool's network clip fetches in a build with no editor (one at a time per platform, 30 s apart, Rumble 120 s). Needs a restart of the editor and of umtool. - **The download lane's metadata scan reads 60 titles at a time and lets the downloads run in between.** A filtered channel's scan holds its platform's download queue while it runs, and the lane used to scan the whole backlog in one go: on 2026-10-25 the scan of h3-podcast's 1,163 unread titles, which started the moment the channel's download pause was lifted, held YouTube from 03:20 to 06:36 and nothing downloaded. The lane now scans 60 titles (about 10 minutes on YouTube), gives that platform 20 minutes of downloads, then scans the next 60, and its log says so: "1103 listed videos left to scan for h3-podcast; the next batch after 20 minutes of downloads." A scan that a platform stopped (a soft block, a rate limit) is still not retried until the next restart. **Run** on the metadata-scan operation still scans the whole backlog. Needs a restart of the editor. - **Download missing skips the videos the metadata scan read as members-only or private.** The download lane already skipped them; a Download missing run only skipped the ones a failed download had recorded, so on 2026-10-25 a run on h3-podcast tried each of the 277 members-only videos the scan had found that night four times (with and without cookies) and downloaded nothing. The run's log counts them: "Excluded 279 from this run (members_only=279, deleted=0, private=0; 277 as the metadata scan read them)." A video the scan reads again later comes back by itself. Needs a restart of the editor. - **A Transcribe holds the platform's queue only while it downloads.** The video page's Audio + Whisper and `pnpm ops transcribe-one` used to keep YouTube's (or any platform's) download queue for the whole transcription, so nothing else downloaded on that platform while it waited for a worker and transcribed. Now the audio download runs on the platform's queue and the transcription runs as its own job on the video's queue (`transcribe-one:<slug>:<id>`); with the audio already on disk it starts there at once. The run panel and `pnpm ops … --wait` follow both jobs to the end of the transcription, and the first job's log names the second. `pnpm ops transcribe-one` with `"file"` now runs on the video's own queue unless a download is owed, takes `"queueKey"`, and for a YouTube video whose captions are listed and that has no audio fetches the captions instead (says so, and refuses when the captions are already on disk) unless `"asr": true` is passed. Needs a restart of the editor. diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -148,6 +148,7 @@ import { handOffSlot } from "yt-dlp-transcript-common/jobs/handOff"; import { fixIncompleteTranscriptOne } from "../../lib/fixIncompleteTranscript"; import { writeFileAtomic, writeJsonAtomic } from "yt-dlp-transcript-common/lib/jsonFile-server"; import { formValues, type FormErrorState } from "../../../../lib/formState"; +import { jitterMs } from "yt-dlp-transcript-common/lib/jitter"; function videoQueueKey(config: ChannelConfig, override: string | undefined): string { return resolveQueueKey(downloadQueueKey(config), override); @@ -1828,7 +1829,7 @@ function storedFallbackGapMs(): number { const raw = Number(process.env.E2E_CLIP_WINDOW_GAP_MS); return process.env.E2E_CLIP_WINDOW_GAP_MS !== undefined && Number.isFinite(raw) && raw >= 0 ? raw - : CLIP_WINDOW_MIN_GAP_SECONDS * 1000; + : jitterMs(CLIP_WINDOW_MIN_GAP_SECONDS * 1000); } function abortableSleep(ms: number, signal: AbortSignal): Promise<void> { diff --git a/editor/app/scheduler/runTick.ts b/editor/app/scheduler/runTick.ts @@ -33,6 +33,7 @@ import { fetchPostsAction } from "../channels/[slug]/socialActions"; // outputs, the backup copies them. import { checkKeptDeletedAction } from "../channels/[slug]/whisperActions"; import { backupSavedVideosAction } from "../saved-videos/backupActions"; +import { pacingJitter } from "yt-dlp-transcript-common/lib/jitter"; export type SchedulerTickResult = { ok: boolean; @@ -134,6 +135,8 @@ export async function runSchedulerTick(): Promise<SchedulerTickResult> { activeSlugs, now, priority, + // Each channel due up to pacing.jitter of its interval later (≤ 30 min). + jitter: pacingJitter(), focusSlugs: resolveFocusSlugs( priority, siteChannels, @@ -282,6 +285,7 @@ function reconcileOutcomes( now, cs.consecutiveFailures, scheduler, + pacingJitter(), ); cs.lastOutcome = "failed"; cs.lastOutcomeAt = job.endedAt ?? now; diff --git a/editor/app/settings/actions.ts b/editor/app/settings/actions.ts @@ -163,6 +163,21 @@ export async function saveSettingsAction( const currentSettings = getSettings(); const jobGaps = parseJobGaps(formData, currentSettings.pacing.jobGapSeconds); + // pacing.jitter, edited as a whole percent (0.25 ↔ 25). A blank field keeps + // what is stored. + const jitterRaw = String(formData.get("pacingJitterPercent") ?? "").trim(); + let jitter = currentSettings.pacing.jitter; + if (jitterRaw !== "") { + const pct = Number(jitterRaw); + if (!Number.isFinite(pct) || pct < 0 || pct > 100) { + return { + ok: false, + error: "The jitter must be a percent from 0 to 100", + values, + }; + } + jitter = pct / 100; + } if (!jobGaps.ok) return { ok: false, error: jobGaps.error, values }; // 0 disables passive refresh; any other value must land in the allowed window. @@ -274,8 +289,9 @@ export async function saveSettingsAction( cookiesFromBrowser, cookieMode, sleepBetweenDownloadsSeconds: sleepParsed, - // The whole pacing block as it is, with only the job gaps this form edits. - pacing: { ...currentSettings.pacing, jobGapSeconds: jobGaps.gaps }, + // The whole pacing block as it is, with only the job gaps and the jitter + // this form edits. + pacing: { ...currentSettings.pacing, jobGapSeconds: jobGaps.gaps, jitter }, downloadFormat, sourceVideoQuality, minFreeDiskGB: minFreeDiskParsed, diff --git a/editor/app/settings/components/SettingsForm.tsx b/editor/app/settings/components/SettingsForm.tsx @@ -155,6 +155,14 @@ export function SettingsForm({ initial }: Props) { gap off. </span> </fieldset> + <Field + label="Jitter on every wait before a request (%)" + name="pacingJitterPercent" + state={state} + defaultValue={String(Math.round(initial.pacing.jitter * 100))} + type="number" + hint="Each wait before the archive asks a site — the gaps above, the sleep between downloads, yt-dlp's request sleep, the rate-limit cooldowns — is stretched by up to this share of itself at random, so requests don't come on a fixed beat. It only adds time: every gap stays a minimum. 0 turns it off. Default 25." + /> <label className="flex flex-col gap-1 text-sm"> <span className="font-medium">Default download format</span> <SeededSelect diff --git a/editor/e2e/servers.ts b/editor/e2e/servers.ts @@ -40,6 +40,7 @@ export const E2E_SERVER_ENV: Record<string, string> = { E2E_AUDIO_CHECK_RECOVER_AFTER: "2", E2E_BACKOFF_BASE_MS: "20000", E2E_CLIP_WINDOW_GAP_MS: "2000", + E2E_AVAILABILITY_PROBE_GAP_MS: "0", // The pacing guard's BUILT-IN defaults (plans/pacing-guard.md) are off on // the test server — a spec's two fake X fetches would otherwise sit five // minutes apart, and every fake X fetch would need a fresh jar. A spec that diff --git a/editor/playwright.config.ts b/editor/playwright.config.ts @@ -30,6 +30,13 @@ import { currentSlot } from "./e2e/testPaths"; // batch (30–45 s in production; 2 s here), so // fetch-window.spec sees the one it owes // (common/controller/fetchWindows.ts) +// E2E_PACING_JITTER NOT set: the e2e servers run with the real +// pacing.jitter (0.25), so every gap a spec waits is +// its floor plus up to a quarter (common/lib/jitter.ts); +// the unit tests that assert an exact gap set 0 +// E2E_AVAILABILITY_PROBE_GAP_MS 0: no pause between two availability probes +// (3 s + jitter in production; +// common/controller/checkAvailability.ts) // E2E_JOB_GAP_SECONDS, 0: the pacing guard's BUILT-IN job gap and X // E2E_X_MAX_COOKIE_AGE_MINUTES cookie-age limit are off on the test server // (common/jobs/queueGap.ts, networkGuard.ts); a diff --git a/settings.json.example b/settings.json.example @@ -14,7 +14,8 @@ "decayAfterCleanUnits": 5, "holdAfterFailsAtCap": 3, "holdProbeMinutes": 60, - "jobGapSeconds": {} + "jobGapSeconds": {}, + "jitter": 0.25 }, "downloadFormat": "auto", "sourceVideoQuality": "original", diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -35,6 +35,9 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // availability probes on one platform // (report-to-video/check-availability.mjs), in // place of the real 30–180 s, against the stub yt-dlp +// E2E_CLIP_FETCH_GAP_MS set below for the whole run: the gap between two +// network clip fetches in a build (build-video.mjs), +// in place of the real 30–120 s // The ports are common/lib/ports.mjs's (offset per worktree by // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); @@ -43,6 +46,9 @@ const PORT = portFor("UMTOOL_E2E_PORT"); // not the 30 s a real YouTube probe waits. On process.env, so the app server // and every worker (and the CLIs they spawn) inherit it. process.env.E2E_AVAILABILITY_GAP_MS ??= "50"; +// The same for a build's network clip fetches (report-to-video/build-video.mjs, +// pacedClipFetch): 0 against the stub, not the real 30 s per clip. +process.env.E2E_CLIP_FETCH_GAP_MS ??= "0"; // START MODE BY DEFAULT, as the editor suite (plans/e2e-speed.md, S1): `next // dev` compiles each route on first use and again after a change, and the diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -203,7 +203,12 @@ import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mj import { pruneChromeFrames } from "./prune-frames.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. -import { platformArgsForUrl } from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { + clipWindowMinGapSeconds, + platformArgsForUrl, +} from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs"; +import { jitterSleepArgs, jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; // The header line, the clock in it and the title cleaner live in one module // the clip bench imports too -- a preview that shows a line this renderer // would never draw is worse than no preview. @@ -1061,6 +1066,48 @@ export async function alignedClipSource(r) { }; } +// THE GAP BETWEEN TWO NETWORK CLIP FETCHES ON ONE PLATFORM. A build with no +// editor to ask (the network path below) used to spawn yt-dlp for clip after +// clip with no gap at all — a burst at the source, which nothing else here is +// allowed to do. Each platform's fetches now go one at a time, the editor's +// clip-window floor apart (clipWindowMinGapSeconds: 30 s, Rumble 120 s), +// stretched by up to a quarter at random (lib/jitter.mjs — only ever longer). +// In-process: a new build is itself a gap. +/** @type {Map<string, { chain: Promise<unknown>, lastEnd: number }>} */ +const clipFetchGates = new Map(); + +// TEST-ONLY: E2E_CLIP_FETCH_GAP_MS replaces the gap, so the e2e suite (a stub +// yt-dlp) does not wait 30 s per clip. Unset everywhere but the e2e run +// (umtool/playwright.config.ts). +function clipFetchGapMs(platform) { + const raw = Number(process.env.E2E_CLIP_FETCH_GAP_MS); + if (process.env.E2E_CLIP_FETCH_GAP_MS !== undefined && Number.isFinite(raw) && raw >= 0) return raw; + return Math.ceil(jitterUp(clipWindowMinGapSeconds(platform) * 1000)); +} + +/** + * @template T + * @param {string} url + * @param {() => Promise<T>} run + * @returns {Promise<T>} + */ +function pacedClipFetch(url, run) { + const platform = detectPlatform(url) ?? "unknown"; + const gate = clipFetchGates.get(platform) ?? { chain: Promise.resolve(), lastEnd: 0 }; + clipFetchGates.set(platform, gate); + const turn = gate.chain.then(async () => { + const wait = gate.lastEnd > 0 ? gate.lastEnd + clipFetchGapMs(platform) - Date.now() : 0; + if (wait > 0) await new Promise((r) => setTimeout(r, wait)); + try { + return await run(); + } finally { + gate.lastEnd = Date.now(); + } + }); + gate.chain = turn.catch(() => {}); + return turn; +} + async function fetchClip(entry, meta, render, local, opts) { const { rawDir } = local; const { from, to } = fetchSpan(entry, render, opts); @@ -1089,14 +1136,17 @@ async function fetchClip(entry, meta, render, local, opts) { const argsWith = (extra) => clipFetchArgs({ url: meta.webpageUrl, from, to, fmt, dest, extra }); - const attempt = async (extra) => { - try { - await execFileP(YTDLP, argsWith(extra), { maxBuffer: 1 << 26 }); - return null; - } catch (err) { - return ytdlpOk(err) ? null : err; - } - }; + // Paced per platform (pacedClipFetch), with yt-dlp's fixed waits drawn + // once per run (lib/jitter.mjs). + const attempt = (extra) => + pacedClipFetch(meta.webpageUrl, async () => { + try { + await execFileP(YTDLP, jitterSleepArgs(argsWith(extra)), { maxBuffer: 1 << 26 }); + return null; + } catch (err) { + return ytdlpOk(err) ? null : err; + } + }); EMIT("fetch", { id: entry.id, video: entry.video, from, to, cached: false, source: "network" }); let err = await attempt([]); diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs @@ -50,6 +50,7 @@ import { clipWindowMinGapSeconds, platformArgsForUrl, } from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { jitterSleepArgs } from "yt-dlp-transcript-common/lib/jitter.mjs"; import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs"; import { fetchSpan, localSources } from "./build-video.mjs"; import { SHADOW_CHANNELS, audioUse, channelsDirFor } from "./sources.mjs"; @@ -250,7 +251,8 @@ export async function checkAvailability(manifestPath, { } const checkedAt = iso(); try { - await execFileP(ytdlp, simulateArgs(meta.webpageUrl), { maxBuffer: 1 << 24 }); + // yt-dlp's fixed waits drawn once for this probe (lib/jitter.mjs). + await execFileP(ytdlp, jitterSleepArgs(simulateArgs(meta.webpageUrl)), { maxBuffer: 1 << 24 }); rows[i] = { ...w, ok: true, state: "ok", title: meta.title, url: meta.webpageUrl, checkedAt, error: null }; } catch (err) { const stderr = err?.stderr || err?.message || "";