Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit be101061b60b285cd13d0178ee8d4edc60e2ea98
parent 13e15280c73ab762c5e8987701b4e48481824904
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 18 Nov 2026 23:04:22 -0500

x: review 3 M3/S4 -- the count is rebuilt only from records shown to cover the day, retention keeps X's records, and a future start never hides the real ones

M3: pruneJobLogs (retention by count, by age, and Clear logs) never deletes
the record of an X job that may still count -- an X-queue record (or one
carrying xStarts) with a start, a counted start or its queueing in the last
day, or a young record that cannot be read -- and writes once, in
.jobs/x-records-kept.json, since when it has kept them. rebuildXJobStarts
counts X jobs of the day only when that is over a day old, or a finished
job that ended over a day ago is still on disk (retention deletes the
oldest finished first). Otherwise it refuses and writes nothing; the
refusal itself starts the day, so it ends by itself within 24 hours.

S4: the windows are every start later than now minus their length: a start
stamped in the future counts in both and never prunes the real ones, and a
start is recorded at the clock's time.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/jobs/listJobs.test.ts | 45+++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/listJobs.ts | 22++++++++++++++++++++++
Mcommon/jobs/xJobCap.test.ts | 75++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/jobs/xJobCap.ts | 72+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/xJobRule.test.ts | 12++++++++++++
Mcommon/lib/xJobRule.ts | 20+++++++++-----------
6 files changed, 225 insertions(+), 21 deletions(-)

diff --git a/common/jobs/listJobs.test.ts b/common/jobs/listJobs.test.ts @@ -195,3 +195,48 @@ test("readLogTail returns the last N lines, read from the end, never a half line await rm(dir, { recursive: true, force: true }); } }); + +// Review 3 M3: X's job count is rebuilt from the job records when its file is +// gone (jobs/xJobCap.ts), so retention never deletes the record of an X job +// that may still count — by count, by age, or "Clear logs → all". +test("review 3 M3: pruning keeps every X-queue record that may still count, and says since when it has", async () => { + await withJobs(async (paths, seed) => { + const DAY = 24 * 60 * 60 * 1000; + const now = BASE + 40 * DAY; + const xRecord = async (t: number, extra: Record<string, unknown>) => { + const id = ulid(t); + await writeFile(path.join(paths.jobsDir, `${id}.log`), "x\n"); + await writeFile(path.join(paths.jobsDir, `${id}.meta.json`), JSON.stringify({ id, kind: "fetch-posts", queueKey: "platform:twitter", status: "done", queuedAt: t, ...extra })); + return id; + }; + // Counted an hour ago; queued two days ago and counted an hour ago (it waited); started an hour ago (a record from before xStarts). + const young = await xRecord(now - 60 * 60 * 1000, { startedAt: now - 60 * 60 * 1000, xStarts: [now - 60 * 60 * 1000] }); + const waited = await xRecord(now - 2 * DAY, { startedAt: now - 60 * 60 * 1000, xStarts: [now - 60 * 60 * 1000] }); + const legacy = await xRecord(now - 2 * 60 * 60 * 1000, { startedAt: now - 2 * 60 * 60 * 1000 }); + // Counted 25 hours ago: it cannot count any more, so it goes. + const old = await xRecord(now - 25 * 60 * 60 * 1000, { startedAt: now - 25 * 60 * 60 * 1000, xStarts: [now - 25 * 60 * 60 * 1000] }); + // A young record that cannot be read: it may be an X job's. + const tornId = ulid(now - 60_000); + await writeFile(path.join(paths.jobsDir, `${tornId}.log`), "x\n"); + await writeFile(path.join(paths.jobsDir, `${tornId}.meta.json`), "{torn"); + const other = await seed(9, now - 60_000); + const { deleted } = await pruneJobLogs(paths, { all: true, now }); + const left = await readdir(paths.jobsDir); + for (const id of [young, waited, legacy, tornId]) { + assert.ok(left.includes(`${id}.log`) && left.includes(`${id}.meta.json`), `kept ${id}`); + } + for (const id of [old, other]) assert.ok(!left.includes(`${id}.meta.json`), `deleted ${id}`); + assert.equal(deleted, 2); + // By count and by age the same. + assert.equal((await pruneJobLogs(paths, { keepLast: 0, now })).deleted, 0); + assert.equal((await pruneJobLogs(paths, { olderThanMs: 1, now })).deleted, 0); + // The pruner says since when it has kept them (jobs/xJobCap.ts reads it). + const kept = JSON.parse(await (await import("node:fs/promises")).readFile(path.join(paths.jobsDir, "x-records-kept.json"), "utf8")); + assert.equal(kept.since, now); + // A day later the same records can no longer count: they go. + assert.equal((await pruneJobLogs(paths, { all: true, now: now + DAY })).deleted, 4); + // The first "since" is kept. + const again = JSON.parse(await (await import("node:fs/promises")).readFile(path.join(paths.jobsDir, "x-records-kept.json"), "utf8")); + assert.equal(again.since, now); + }); +}); diff --git a/common/jobs/listJobs.ts b/common/jobs/listJobs.ts @@ -9,6 +9,7 @@ const ENTRY_READ_CONCURRENCY = 32; import { metaPath, readJobMeta } from "./jobMeta"; import { jobSpecDetail } from "./jobDetail"; import { jobIdTime } from "./ulid"; +import { noteXRecordsKept, xRecordMayCount } from "./xJobCap"; export type JobListEntry = { id: string; @@ -320,6 +321,7 @@ export async function pruneJobLogs( const cutoff = opts.olderThanMs != null ? now - opts.olderThanMs : null; let deleted = 0; + let keepingNoted = false; for (let i = 0; i < items.length; i++) { const { id, t } = items[i]; if (protectedIds.has(id)) continue; @@ -330,6 +332,26 @@ export async function pruneJobLogs( // keepLast so we never delete something whose age we can't establish. if (!doDelete && cutoff != null && t > 0 && t < cutoff) doDelete = true; if (!doDelete) continue; + // NEVER THE RECORD OF AN X JOB THAT MAY STILL COUNT (review 3 M3): X's + // job count is rebuilt from these records when its file is gone + // (jobs/xJobCap.ts). Kept until it cannot count — a day after its last + // start — by count, by age and by "Clear logs" alike. + if (!keepingNoted) { + await noteXRecordsKept(paths, now).catch(() => {}); + keepingNoted = true; + } + const meta = await readFile(metaPath(paths, id), "utf8").then( + (text) => { + try { + const v = JSON.parse(text) as unknown; + return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : null; + } catch { + return null; + } + }, + (err: NodeJS.ErrnoException) => (err?.code === "ENOENT" ? ({} as Record<string, unknown>) : null), + ); + if (xRecordMayCount(id, meta, now)) continue; await rm(path.join(paths.jobsDir, `${id}.log`), { force: true }); await rm(metaPath(paths, id), { force: true }); diff --git a/common/jobs/xJobCap.test.ts b/common/jobs/xJobCap.test.ts @@ -9,7 +9,7 @@ import assert from "node:assert/strict"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { rebuildXJobStarts, recordXJobStart, xJobCapStatus, xJobStartsFile } from "./xJobCap"; +import { X_RECORDS_KEPT_FILE, rebuildXJobStarts, recordXJobStart, xJobCapStatus, xJobStartsFile } from "./xJobCap"; import { ulid } from "./ulid"; const TMP = mkdtempSync(path.join(tmpdir(), "x-job-cap-")); @@ -29,6 +29,12 @@ const meta = (paths: ReturnType<typeof corpus>, m: Record<string, unknown>, at: return id; }; +// The pruner's word that it keeps every X record that may still count, since `since` (review 3 M3). +const keptSince = (paths: ReturnType<typeof corpus>, since: number) => { + mkdirSync(paths.jobsDir, { recursive: true }); + writeFileSync(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), JSON.stringify({ version: 1, since })); +}; + test("M1: ONE count for the machine — checked and recorded in one step, kept across a restart", async () => { const paths = corpus("disk"); for (let i = 0; i < 12; i++) assert.equal((await recordXJobStart(paths, T0 + i * MIN)).ok, true); @@ -42,11 +48,12 @@ test("M1: ONE count for the machine — checked and recorded in one step, kept a // "Restart": nothing is in memory; the file is the count. const again = await xJobCapStatus(paths, T0 + 13 * MIN); assert.deepEqual([again.ok, again.lastHour, again.lastDay, again.nextAt], [false, 12, 12, T0 + 60 * MIN]); - // A start recorded with the clock set back is recorded no earlier than the latest on record. + // A start recorded with the clock set back is recorded at the clock's time + // (review 3 S4); the later start on record still counts, and is kept. const p2 = corpus("disk-back"); await recordXJobStart(p2, T0); await recordXJobStart(p2, T0 - 600 * MIN); - assert.deepEqual(fileOf(p2).starts, [T0, T0]); + assert.deepEqual(fileOf(p2).starts, [T0, T0 - 600 * MIN]); // Starts older than a day are dropped when the next is recorded. await recordXJobStart(p2, T0 + 25 * HOUR); assert.deepEqual(fileOf(p2).starts, [T0 + 25 * HOUR]); @@ -104,6 +111,7 @@ test("R-c: a fresh corpus where no X job ever ran starts at zero", async () => { test("R-c: deleting job-starts.json does not reset the count — the last day is rebuilt from the job records", async () => { const paths = corpus("rebuild"); + keptSince(paths, T0 - 25 * HOUR); // Jobs that ran through the funnel: each meta says the starts it was counted for. for (let i = 0; i < 10; i++) meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - i * MIN, xStarts: [T0 - i * MIN] }, T0 - i * MIN); // An X run's channels: one start each. @@ -126,6 +134,7 @@ test("R-c: deleting job-starts.json does not reset the count — the last day is test("R-c: a record from before `xStarts` counts once at its start when its kind counts", async () => { const paths = corpus("legacy"); + keptSince(paths, T0 - 25 * HOUR); meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - MIN }, T0 - MIN); meta(paths, { kind: "read-x-trending", queueKey: "platform:twitter", startedAt: T0 - 2 * MIN }, T0 - 2 * MIN); // A library's media-only capture of that time: its channel is not read, so it counts (more rather than fewer). @@ -186,3 +195,63 @@ test("R-c: X activity whose records cannot be read is refused — fail closed", } } }); + +test("review 3 S4: a start in the future counts in both windows and never prunes the real ones", async () => { + const paths = corpus("future"); + mkdirSync(path.dirname(xJobStartsFile(paths)), { recursive: true }); + // Ten real starts and one stamped a year ahead (a clock that jumped forward, then back). + const real = Array.from({ length: 10 }, (_, i) => T0 + i * MIN); + writeFileSync(xJobStartsFile(paths), JSON.stringify({ version: 2, starts: [...real, T0 + 365 * 24 * HOUR] })); + const status = await xJobCapStatus(paths, T0 + 10 * MIN); + assert.deepEqual([status.ok, status.lastHour, status.lastDay], [true, 11, 11]); + const r = await recordXJobStart(paths, T0 + 10 * MIN); + assert.deepEqual([r.ok, r.at, r.lastHour], [true, T0 + 10 * MIN, 12]); + // The real starts are kept beside the future one. + assert.deepEqual(fileOf(paths).starts, [...real, T0 + 365 * 24 * HOUR, T0 + 10 * MIN]); + assert.equal((await recordXJobStart(paths, T0 + 11 * MIN)).ok, false, "the hour holds twelve"); +}); + +test("review 3 M3: a rebuild that cannot show its records cover the last day refuses, writes nothing, and ends by itself", async () => { + const xs = (paths: ReturnType<typeof corpus>) => { + for (let i = 0; i < 5; i++) meta(paths, { kind: "fetch-posts", queueKey: "platform:twitter", startedAt: T0 - i * MIN, endedAt: T0 - i * MIN + 1000, xStarts: [T0 - i * MIN] }, T0 - i * MIN); + }; + // X jobs ran today; nothing says the records of the day are all there. + const paths = corpus("m3-unshown"); + xs(paths); + const refused = await xJobCapStatus(paths, T0 + MIN); + assert.equal(refused.ok, false); + assert.equal(refused.unreadable, true); + assert.match(refused.sentence ?? "", /cannot be rebuilt from the job records: records of the last 24 hours may have been deleted .* at the latest until 2026-11-19 12:01 UTC/); + assert.equal((await recordXJobStart(paths, T0 + MIN)).ok, false); + assert.throws(() => readFileSync(xJobStartsFile(paths)), "nothing is written on a guess"); + // The refusal itself starts the day after which the records are known kept. + assert.equal(JSON.parse(readFileSync(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), "utf8")).since, T0 + MIN); + // A day later the count is rebuilt (the five can no longer count). + const later = await xJobCapStatus(paths, T0 + MIN + 24 * HOUR); + assert.deepEqual([later.ok, later.lastDay], [true, 0]); + + // SHOWN BY A RECORD: a finished job that ended over a day ago is still on + // disk, so no retention ever deleted a newer one. + const shown = corpus("m3-shown-by-old"); + xs(shown); + meta(shown, { kind: "sync", queueKey: "platform:youtube", status: "done", startedAt: T0 - 26 * HOUR, endedAt: T0 - 25 * HOUR }, T0 - 26 * HOUR); + const s = await xJobCapStatus(shown, T0 + MIN); + assert.deepEqual([s.ok, s.lastDay], [true, 5]); + // …but an old job still running (or queued) is no such proof: it was kept because it ran. + const running = corpus("m3-old-running"); + xs(running); + meta(running, { kind: "sync", queueKey: "platform:youtube", status: "running", startedAt: T0 - 26 * HOUR }, T0 - 26 * HOUR); + assert.equal((await xJobCapStatus(running, T0 + MIN)).ok, false); + // SHOWN BY THE PRUNER: it has kept X's records for over a day. + const pruner = corpus("m3-shown-by-pruner"); + xs(pruner); + keptSince(pruner, T0 - 25 * HOUR); + assert.deepEqual([(await xJobCapStatus(pruner, T0 + MIN)).ok, (await xJobCapStatus(pruner, T0 + MIN)).lastDay], [true, 5]); + // …for less than a day: not yet. + const recent = corpus("m3-pruner-recent"); + xs(recent); + keptSince(recent, T0 - 2 * HOUR); + const r = await xJobCapStatus(recent, T0 + MIN); + assert.equal(r.ok, false); + assert.match(r.sentence ?? "", /at the latest until 2026-11-19 10:00 UTC/); +}); diff --git a/common/jobs/xJobCap.ts b/common/jobs/xJobCap.ts @@ -27,7 +27,6 @@ import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile import { X_JOB_CAP, X_QUEUE_KEY, - xCapClock, xJobCapSentence, xJobCapUnreadableSentence, xJobCapUnrebuildableSentence, @@ -74,6 +73,45 @@ async function readStartsFile(paths: CapPaths): Promise<{ state: "absent" } | { return { state: "bad" }; } +// ── the records are kept (review 3 M3) ───────────────────────────────────── + +// RETENTION NEVER DELETES THE RECORD OF AN X JOB THAT MAY STILL COUNT +// (jobs/listJobs.ts pruneJobLogs asks xRecordMayCount), and says since when it +// has kept them: `<jobsDir>/x-records-kept.json`, {version: 1, since: <ms>}, +// written once, by the first prune (or rebuild) of code that keeps them. A +// rebuild trusts the records of the last day only when that is over a day +// old — or when a finished job that ended over a day ago is still on disk +// (retention deletes the oldest finished first, so nothing newer was +// deleted). +export const X_RECORDS_KEPT_FILE = "x-records-kept.json"; + +export async function readXRecordsKeptSince(paths: Pick<Paths, "jobsDir">): Promise<number | undefined> { + const read = await readJsonFile(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE)); + const since = read.ok ? (read.value as { since?: unknown } | null)?.since : undefined; + return finite(since) ? since : undefined; +} + +// Said once: a "since" already on disk is never moved later. +export async function noteXRecordsKept(paths: Pick<Paths, "jobsDir">, now: number): Promise<number> { + const had = await readXRecordsKeptSince(paths); + if (had !== undefined) return had; + await writeJsonAtomic(path.join(paths.jobsDir, X_RECORDS_KEPT_FILE), { version: 1, since: now }, { mkdir: true }); + return now; +} + +// MAY THIS RECORD STILL COUNT AGAINST X'S CAP? An X-queue record (or one that +// says it was counted) with a start, a counted start or its queueing inside +// the last day — or after `now`; and a record that cannot be read whose id +// is of the last day (or of no known day). Kept by retention while it may. +export function xRecordMayCount(id: string, meta: Record<string, unknown> | null, now: number): boolean { + const since = now - X_JOB_CAP.dayMs; + const born = jobIdTime(id); + if (!meta) return born === 0 || born > since; + const xStarts = Array.isArray(meta.xStarts) ? meta.xStarts.filter(finite) : []; + if (meta.queueKey !== X_QUEUE_KEY && xStarts.length === 0) return false; + return [...xStarts, meta.startedAt, born].some((t) => finite(t) && t > since); +} + // ── the rebuild (ruling R-c) ─────────────────────────────────────────────── export type XJobStartsRebuild = @@ -104,6 +142,7 @@ export async function rebuildXJobStarts(paths: Pick<Paths, "jobsDir">, now: numb } const starts: number[] = []; let records = 0; + let oldFinished = false; for (const name of names) { if (!name.endsWith(".meta.json")) continue; const id = name.slice(0, -".meta.json".length); @@ -121,6 +160,9 @@ export async function rebuildXJobStarts(paths: Pick<Paths, "jobsDir">, now: numb if (born === 0 || born > since) return { ok: false, why: `the job record ${name} cannot be read`, ...(until ? { until } : {}) }; continue; } + // A finished job that ended over a day ago, still on disk: retention + // deletes the oldest finished jobs first, so no newer one was deleted. + if ((m.status === "done" || m.status === "failed" || m.status === "cancelled") && finite(m.endedAt) && m.endedAt <= since) oldFinished = true; if (m.queueKey !== X_QUEUE_KEY) continue; if (Array.isArray(m.xStarts)) { records++; @@ -141,6 +183,22 @@ export async function rebuildXJobStarts(paths: Pick<Paths, "jobsDir">, now: numb if (lastXEnd !== undefined && records === 0) { return { ok: false, why: "X's queue ended a job within the last 24 hours and no record of an X job is left", ...(until ? { until } : {}) }; } + // X JOBS RAN TODAY: THE RECORDS MUST BE SHOWN TO COVER THE DAY (review 3 + // M3). A count from records retention may have thinned is a guess, and + // nothing is counted on a guess. + if (lastXEnd !== undefined || starts.length > 0) { + const kept = await noteXRecordsKept(paths, now); + if (!(kept <= since || oldFinished)) { + const ends = [kept + X_JOB_CAP.dayMs, ...(until !== undefined ? [until] : [])]; + return { + ok: false, + why: + "records of the last 24 hours may have been deleted (by the jobs list's retention or Clear logs, before it kept X's): " + + "nothing shows they are all there", + until: Math.min(...ends), + }; + } + } return { ok: true, starts: starts.sort((a, b) => a - b), records }; } @@ -164,10 +222,10 @@ function closed(sentence: string): XJobCapStatus { return { ok: false, lastHour: 0, lastDay: 0, perHour: X_JOB_CAP.perHour, perDay: X_JOB_CAP.perDay, unreadable: true, sentence }; } -// What a day can still count (the longer window), as of `now`. +// What a day can still count (the longer window), as of `now`: a start in +// the future is kept, and never a reason to drop the real ones (review 3 S4). function keptOf(starts: ReadonlyArray<number>, now: number): number[] { - const clock = xCapClock(starts, now); - return starts.filter((t) => t > clock - X_JOB_CAP.dayMs); + return starts.filter((t) => t > now - X_JOB_CAP.dayMs); } async function writeStarts(paths: CapPaths, starts: number[]): Promise<void> { @@ -202,15 +260,15 @@ export async function xJobCapStatus(paths: CapPaths, now: number = Date.now()): // ONE X JOB STARTS: checked and recorded in one step, under the file's lock. // `ok: false` — the cap is reached, or the count cannot be read — records -// nothing, and the job does not start. `at` is the time recorded, never -// earlier than the latest start on record (xCapClock). +// nothing, and the job does not start. `at` is the time recorded: the +// clock's (a start already on record later than it still counts — S4). export async function recordXJobStart(paths: CapPaths, now: number = Date.now()): Promise<XJobCapStatus & { at?: number }> { return withJsonFileLock(xJobStartsFile(paths), async () => { const loaded = await loadLocked(paths, now); if (!loaded.ok) return closed(loaded.sentence); const before = statusOf(loaded.starts, now); if (!before.ok) return before; - const at = xCapClock(loaded.starts, now); + const at = now; const starts = [...keptOf(loaded.starts, now), at]; await writeStarts(paths, starts); // This start was within the cap: said so, with the count it leaves. diff --git a/common/lib/xJobRule.test.ts b/common/lib/xJobRule.test.ts @@ -208,3 +208,15 @@ test("review 3 S6: a t.co short link is X's", () => { assert.equal(isXUrl("https://x.com/a/status/1"), true); assert.equal(isXUrl("https://twitter.com/a/status/1"), true); }); + +test("review 3 S4: a start in the future counts in both windows, and never moves the windows off the real starts", () => { + const real = Array.from({ length: 11 }, (_, i) => T0 + i * MIN); + const future = T0 + 365 * 24 * 60 * MIN; + const v = xJobCapVerdict([...real, future], T0 + 11 * MIN); + assert.deepEqual([v.ok, v.lastHour, v.lastDay], [false, 12, 12]); + // The next may start when the oldest of the newest twelve has left: the real 12:00 start, at 13:00. + assert.equal(v.nextAt, T0 + 60 * MIN); + // The future start alone keeps counting until the clock has passed it by the window. + assert.deepEqual([xJobCapVerdict([future], T0).lastHour, xJobCapVerdict([future], T0).lastDay], [1, 1]); + assert.equal(xJobCapVerdict([future], future + 60 * MIN).lastHour, 0); +}); diff --git a/common/lib/xJobRule.ts b/common/lib/xJobRule.ts @@ -85,19 +85,17 @@ export type XJobCapVerdict = { window?: "hour" | "day"; }; -// THE CLOCK NEVER FREES A START EARLY. The windows end at the LATER of now -// and the latest recorded start: a machine clock set back (by a person, by a -// time sync) leaves every recorded start inside its window until the clock -// has passed it again. -export function xCapClock(starts: ReadonlyArray<number>, now: number): number { - return starts.reduce((a, t) => (t > a ? t : a), now); -} - +// THE CLOCK NEVER FREES A START EARLY, AND A START IN THE FUTURE NEVER HIDES +// THE REAL ONES (review 3 S4). A window is every start later than `now` minus +// its length — a start stamped after `now` included: a machine clock set back +// (by a person, by a time sync) leaves every recorded start inside its window +// until the clock has passed it again, and one stamped far ahead (a clock that +// jumped forward) counts in both windows without pushing the windows past the +// starts around it. export function xJobCapVerdict(starts: ReadonlyArray<number>, now: number): XJobCapVerdict { - const at = xCapClock(starts, now); const recent = [...starts].filter((t) => Number.isFinite(t)).sort((a, b) => b - a); - const hour = recent.filter((t) => t > at - X_JOB_CAP.hourMs); - const day = recent.filter((t) => t > at - X_JOB_CAP.dayMs); + const hour = recent.filter((t) => t > now - X_JOB_CAP.hourMs); + const day = recent.filter((t) => t > now - X_JOB_CAP.dayMs); const out = { lastHour: hour.length, lastDay: day.length }; // The next may start once the oldest of the newest <cap> starts has left its window. const hourFree = hour.length >= X_JOB_CAP.perHour ? hour[X_JOB_CAP.perHour - 1] + X_JOB_CAP.hourMs : null;