commit ab4d9dba9b001a834ba8f4aaeb2f6efa9324c2f5
parent 7755c58e89259cd24a35e42720ebf122d675b46b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 15:30:27 -0500
common: every X run stop path defers what has not run; one queueing at a time; runs pruned to 100
Cancel before a channel, cancel or drain in X's gap and a thrown error left
channels queued/running, so Resume said nothing to resume. One stop() now
defers every unfinished channel on every path (a throw marks the run failed,
saves, rethrows), and the view counts an unfinished channel of any run that
is not live as deferred. A process-wide flag around plan -> enqueue refuses a
second concurrent start (two clicks on Resume). The wait's save logs its
failure. A new run prunes .x-runs/ to the newest 100. Tests for each path.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
2 files changed, 230 insertions(+), 94 deletions(-)
diff --git a/common/controller/xRun.test.ts b/common/controller/xRun.test.ts
@@ -294,3 +294,99 @@ test("a stale jar at the start refuses the new run before a job; its file is def
assert.equal(view.status, "deferred");
assert.equal(view.summary, "0 done, 1 deferred until the next refresh");
});
+
+test("every stop path defers what has not run, and Resume takes it: cancel before a channel, cancel or drain in X's gap, a thrown error", async () => {
+ const resumable = async (id: string) => (await xr.readXRunView(paths, id))!.resumable;
+ const run = async (deps: import("./xRun").XRunDeps, signal = never(), drain = never()) => {
+ const plan = await xr.planXRun(paths, { channels: ["xa", "xb", "xc"] });
+ assert.ok(plan.ok);
+ let threw: Error | null = null;
+ const r = await xr
+ .runXRun({ paths, state: plan.state, deps, onLog: () => {}, signal, drain })
+ .catch((e: Error) => ((threw = e), null));
+ const disk = (await xr.readXRun(paths, plan.state.id))!;
+ return { id: plan.state.id, r, threw: threw as Error | null, disk };
+ };
+ const statuses = (d: import("./xRun").XRunState) => d.channels.map((c) => c.status);
+
+ // Cancelled before the first channel.
+ const pre = new AbortController();
+ pre.abort();
+ const a = await run(stubDeps({ calls: [] }), pre.signal);
+ assert.equal(a.disk.status, "cancelled");
+ assert.deepEqual(statuses(a.disk), ["deferred", "deferred", "deferred"]);
+ assert.equal(await resumable(a.id), 3);
+
+ // Cancelled while waiting X's gap after the first channel.
+ const b = await run({ ...stubDeps({ calls: [] }), waitGap: async () => "aborted" });
+ assert.equal(b.disk.status, "cancelled");
+ assert.deepEqual(statuses(b.disk), ["done", "deferred", "deferred"]);
+ assert.equal(await resumable(b.id), 2);
+
+ // Drained while waiting X's gap.
+ const c = await run({ ...stubDeps({ calls: [] }), waitGap: async () => "drained" });
+ assert.equal(c.disk.status, "drained");
+ assert.deepEqual(statuses(c.disk), ["done", "deferred", "deferred"]);
+
+ // The guard throws on the second channel: the run fails, nothing is lost.
+ let n = 0;
+ const d = await run({
+ ...stubDeps({ calls: [] }),
+ guard: async () => {
+ if (++n === 2) throw new Error("settings unreadable");
+ return { ok: true, notes: [] };
+ },
+ });
+ assert.equal(d.threw?.message, "settings unreadable");
+ assert.equal(d.disk.status, "failed");
+ assert.equal(d.disk.stopped, "settings unreadable");
+ assert.deepEqual(statuses(d.disk), ["done", "deferred", "deferred"]);
+ assert.equal(await resumable(d.id), 2);
+ const again = await xr.planXRun(paths, { resume: d.id });
+ assert.ok(again.ok);
+ assert.deepEqual(again.state.channels.map((ch) => ch.status), ["done", "queued", "queued"]);
+
+ // A file left with queued/running channels by a stopped run (a crash, an
+ // older build) still reads them as resumable.
+ const e = await xr.planXRun(paths, { channels: ["xa", "xb"] });
+ assert.ok(e.ok);
+ e.state.status = "cancelled";
+ e.state.channels[0].status = "running";
+ await xr.writeXRun(paths, e.state);
+ assert.equal(await resumable(e.state.id), 2);
+});
+
+test("two clicks at once queue one run: the second is refused while the first is being queued", async () => {
+ jar(0);
+ const gate: { open?: () => void } = {};
+ const opened = new Promise<void>((r) => (gate.open = r));
+ const deps = (jobId: string) => ({
+ ...xr.defaultXRunDeps(paths, jobId),
+ fetch: async () => {
+ await opened;
+ return { ok: true, written: 0 };
+ },
+ });
+ const [one, two] = await Promise.all([
+ xr.queueXRun({ paths, req: { channels: ["xa"] }, deps }),
+ xr.queueXRun({ paths, req: { channels: ["xb"] }, deps }),
+ ]);
+ const oks = [one, two].filter((r) => r.ok);
+ assert.equal(oks.length, 1);
+ const refused = [one, two].find((r) => !r.ok) as { error: string };
+ assert.match(refused.error, /one at a time/);
+ // And while the first runs, a third is refused by the registry check.
+ const three = await xr.queueXRun({ paths, req: { channels: ["xc"] }, deps });
+ assert.equal(three.ok, false);
+ assert.match((three as { error: string }).error, /already queued or running/);
+ gate.open!();
+ assert.equal((await (oks[0] as { done: Promise<{ status: string }> }).done).status, "done");
+});
+
+test("runs are pruned to the newest X_RUN_KEEP when a new one is made", async () => {
+ const before = await xr.listXRunIds(paths);
+ const removed = await xr.pruneXRuns(paths, 2);
+ assert.equal(removed.length, Math.max(0, before.length - 2));
+ assert.deepEqual(await xr.listXRunIds(paths), before.slice(0, 2));
+ assert.equal(xr.X_RUN_KEEP, 100);
+});
diff --git a/common/controller/xRun.ts b/common/controller/xRun.ts
@@ -35,7 +35,7 @@
// says so.
import path from "node:path";
-import { readdir } from "node:fs/promises";
+import { readdir, rm } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import { readJsonFile, writeJsonAtomic } from "../lib/jsonFile-server";
import { getSettings } from "../lib/settings";
@@ -173,6 +173,17 @@ export async function listXRunIds(paths: Pick<Paths, "jobsDir">): Promise<string
.reverse();
}
+// The run files kept: the newest X_RUN_KEEP; older ones are removed when a
+// new run is made (a run's file is its console row and its Resume, nothing
+// else reads it).
+export const X_RUN_KEEP = 100;
+
+export async function pruneXRuns(paths: Pick<Paths, "jobsDir">, keep = X_RUN_KEEP): Promise<string[]> {
+ const old = (await listXRunIds(paths)).slice(keep);
+ for (const id of old) await rm(xRunPath(paths, id), { force: true }).catch(() => {});
+ return old;
+}
+
export async function latestXRun(paths: Pick<Paths, "jobsDir">): Promise<XRunState | null> {
for (const id of await listXRunIds(paths)) {
const run = await readXRun(paths, id);
@@ -231,7 +242,10 @@ export function xRunView(state: XRunState, liveJob: { id: string; status: string
const live = !!liveJob && (liveJob.status === "queued" || liveJob.status === "running");
const jobId = live ? liveJob!.id : (state.jobIds.at(-1) ?? null);
const interrupted = !live && (state.status === "queued" || state.status === "running");
- const channels = interrupted
+ // A run that is not live has nothing running: an unfinished channel in a
+ // file written before every stop path deferred (or by a crash) reads as
+ // deferred, so Resume counts it.
+ const channels = !live
? state.channels.map((c) =>
c.status === "queued" || c.status === "running" ? { ...c, status: "deferred" as const } : c,
)
@@ -440,6 +454,7 @@ export async function planXRun(paths: Paths, req: XRunRequest, now = Date.now())
channels: slugs.map((slug) => ({ slug, status: "queued" })),
};
await writeXRun(paths, state, now);
+ await pruneXRuns(paths);
return { ok: true, state, resumed: false };
}
@@ -504,109 +519,109 @@ export async function runXRun(opts: {
`X's queue gap between them; the cookie jar is checked before each.`,
);
opts.onProgress?.({ done: settled(), total });
- const deferRest = (reason: string) => {
- for (const c of state.channels) if (c.status === "queued") c.status = "deferred";
- state.status = "deferred";
+ // EVERY STOP PATH ENDS HERE: what has not run (queued, and one cut while
+ // running) is deferred — a Resume takes exactly those — and the run says why.
+ const stop = (status: XRunStatus, reason: string) => {
+ for (const c of state.channels) if (c.status === "queued" || c.status === "running") c.status = "deferred";
+ state.status = status;
state.stopped = reason;
};
let stoppedEarly = false;
let first = true;
- for (const ch of todo) {
- if (signal.aborted) {
- state.status = "cancelled";
- state.stopped = "Cancelled.";
- stoppedEarly = true;
- break;
- }
- if (drain.aborted) {
- state.status = "drained";
- state.stopped = "Drained: the channels not yet fetched stay queued for a Resume.";
- for (const c of state.channels) if (c.status === "queued") c.status = "deferred";
- stoppedEarly = true;
- break;
- }
- // The run's first channel follows the job's own gap (runManagedFunction
- // waited it); every later one waits X's gap after the one before.
- if (!first) {
- const waited = await deps.waitGap({
- signal,
- drain,
- onLog,
- onWait: (until) => {
- if (until === null) delete state.waitingUntil;
- else state.waitingUntil = new Date(until).toISOString();
- void save();
- },
- });
- delete state.waitingUntil;
- if (waited === "aborted") {
- state.status = "cancelled";
- state.stopped = "Cancelled.";
+ try {
+ for (const ch of todo) {
+ if (signal.aborted) {
+ stop("cancelled", "Cancelled.");
stoppedEarly = true;
break;
}
- if (waited === "drained") {
- state.status = "drained";
- state.stopped = "Drained while waiting for X's gap: the channels not yet fetched stay for a Resume.";
- for (const c of state.channels) if (c.status === "queued") c.status = "deferred";
+ if (drain.aborted) {
+ stop("drained", "Drained: the channels not yet fetched stay for a Resume.");
+ stoppedEarly = true;
+ break;
+ }
+ // The run's first channel follows the job's own gap (runManagedFunction
+ // waited it); every later one waits X's gap after the one before.
+ if (!first) {
+ const waited = await deps.waitGap({
+ signal,
+ drain,
+ onLog,
+ onWait: (until) => {
+ if (until === null) delete state.waitingUntil;
+ else state.waitingUntil = new Date(until).toISOString();
+ save().catch((err) => onLog(`[warn] could not save the run's wait: ${(err as Error).message}`));
+ },
+ });
+ delete state.waitingUntil;
+ if (waited === "aborted") {
+ stop("cancelled", "Cancelled while waiting for X's gap.");
+ stoppedEarly = true;
+ break;
+ }
+ if (waited === "drained") {
+ stop("drained", "Drained while waiting for X's gap: the channels not yet fetched stay for a Resume.");
+ stoppedEarly = true;
+ break;
+ }
+ }
+ // THE JAR, BEFORE EACH CHANNEL. A refusal stops the run: this channel and
+ // every one after it wait for the next refresh.
+ const g = await deps.guard(ch.slug);
+ if (!g.ok) {
+ onLog(`Stopped before ${ch.slug}: ${g.error}`);
+ stop("deferred", g.error);
+ stoppedEarly = true;
+ break;
+ }
+ for (const note of g.notes) onLog(note);
+ first = false;
+ ch.status = "running";
+ ch.startedAt = iso();
+ delete ch.error;
+ await save();
+ onLog(`── ${ch.slug} (${state.channels.indexOf(ch) + 1}/${total}) ──`);
+ let r: XRunFetchResult;
+ try {
+ r = await deps.fetch(ch.slug, { limit: state.limit, onLog, signal, drain });
+ } catch (err) {
+ r = { ok: false, written: 0, error: (err as Error).message };
+ }
+ deps.noteEnd();
+ deps.channelDone?.(ch.slug);
+ ch.endedAt = iso();
+ if (signal.aborted) {
+ // Cancelled mid-fetch: what it checkpointed is on disk; the channel
+ // runs again on a Resume.
+ if (r.written > 0) ch.posts = r.written;
+ stop("cancelled", "Cancelled.");
+ stoppedEarly = true;
+ break;
+ }
+ ch.posts = r.written;
+ if (r.ok) {
+ ch.status = "done";
+ onLog(`${ch.slug}: ${r.written} new post(s).`);
+ } else {
+ ch.status = "failed";
+ ch.error = r.error ?? "Post fetch failed";
+ onLog(`${ch.slug} failed: ${ch.error}`);
+ }
+ await save();
+ opts.onProgress?.({ done: settled(), total });
+ if (r.drained) {
+ stop("drained", "Drained: the channels not yet fetched stay for a Resume.");
stoppedEarly = true;
break;
}
}
- // THE JAR, BEFORE EACH CHANNEL. A refusal stops the run: this channel and
- // every one after it wait for the next refresh.
- const g = await deps.guard(ch.slug);
- if (!g.ok) {
- onLog(`Stopped before ${ch.slug}: ${g.error}`);
- deferRest(g.error);
- stoppedEarly = true;
- break;
- }
- for (const note of g.notes) onLog(note);
- first = false;
- ch.status = "running";
- ch.startedAt = iso();
- delete ch.error;
- await save();
- onLog(`── ${ch.slug} (${state.channels.indexOf(ch) + 1}/${total}) ──`);
- let r: XRunFetchResult;
- try {
- r = await deps.fetch(ch.slug, { limit: state.limit, onLog, signal, drain });
- } catch (err) {
- r = { ok: false, written: 0, error: (err as Error).message };
- }
- deps.noteEnd();
- deps.channelDone?.(ch.slug);
- ch.endedAt = iso();
- if (signal.aborted) {
- // Cancelled mid-fetch: what it checkpointed is on disk; the channel
- // runs again on a Resume.
- ch.status = "deferred";
- if (r.written > 0) ch.posts = r.written;
- state.status = "cancelled";
- state.stopped = "Cancelled.";
- for (const c of state.channels) if (c.status === "queued") c.status = "deferred";
- stoppedEarly = true;
- break;
- }
- ch.posts = r.written;
- if (r.ok) {
- ch.status = "done";
- onLog(`${ch.slug}: ${r.written} new post(s).`);
- } else {
- ch.status = "failed";
- ch.error = r.error ?? "Post fetch failed";
- onLog(`${ch.slug} failed: ${ch.error}`);
- }
- await save();
- opts.onProgress?.({ done: settled(), total });
- if (r.drained) {
- state.status = "drained";
- state.stopped = "Drained: the channels not yet fetched stay for a Resume.";
- for (const c of state.channels) if (c.status === "queued") c.status = "deferred";
- stoppedEarly = true;
- break;
- }
+ } catch (err) {
+ // The run itself broke (a state write, the guard): nothing unfinished is
+ // lost — it is deferred, and Resume takes it.
+ stop("failed", (err as Error).message);
+ delete state.waitingUntil;
+ await save().catch(() => {});
+ throw err;
}
if (!stoppedEarly) {
const left = state.channels.some((c) => c.status === "deferred");
@@ -680,6 +695,28 @@ export async function queueXRun(opts: {
onChannelDone?: (slug: string) => void;
now?: number;
}): Promise<StreamActionResult & { run?: string }> {
+ // ONE AT A TIME, ALSO BETWEEN THE CHECK AND THE ENQUEUE: planXRun asks the
+ // registry for a live x-run, but awaits file I/O before the job exists, so
+ // two clicks on Resume could both pass it. A process-wide flag (globalThis:
+ // a server action and a route are separate module graphs) closes the gap;
+ // once runManagedFunction returns, the job is in the registry.
+ if (globalThis.__yttXRunStarting__) {
+ return { ok: false, error: "An X run is being queued right now: one at a time." };
+ }
+ globalThis.__yttXRunStarting__ = true;
+ try {
+ return await queueXRunNow(opts);
+ } finally {
+ globalThis.__yttXRunStarting__ = false;
+ }
+}
+
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttXRunStarting__: boolean | undefined;
+}
+
+async function queueXRunNow(opts: Parameters<typeof queueXRun>[0]): Promise<StreamActionResult & { run?: string }> {
const planned = await planXRun(opts.paths, opts.req, opts.now);
if (!planned.ok) return { ok: false, error: planned.error };
const { state } = planned;
@@ -712,6 +749,9 @@ export async function queueXRun(opts: {
onProgress: (p) => setProgress({ metric: "channels", initial: 0, target: p.total, current: p.done }),
});
} catch (err) {
+ // runXRun has deferred the unfinished channels; make sure the file
+ // says so even when the break came before it began.
+ for (const c of fresh.channels) if (c.status === "queued" || c.status === "running") c.status = "deferred";
fresh.status = "failed";
fresh.stopped = (err as Error).message;
await writeXRun(opts.paths, fresh).catch(() => {});