Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Workers: people's runs never wait for a warm lane or a worker restart

Adarsh866c62a18109
diff --git a/bin/lib/worker/run.mjs b/bin/lib/worker/run.mjs
index 41ea8a7e..e07d190d 100644
--- a/bin/lib/worker/run.mjs
+++ b/bin/lib/worker/run.mjs
@@ -44,7 +44,7 @@ import { failure, Reach, retrying } from "./retry.mjs";
import { builtCatalogVersion, ceilingOf, ceilingWords, graphInside, laneMap, readPcAnswers, workerCatalog } from "./tickets.mjs";
import { TEXT_DRAIN_MS, TextSlot, textSlotOf, textTurn } from "./text.mjs";
import { SiteTurns, writeSite } from "./turns.mjs";
-import { CodeWatch } from "./update.mjs";
+import { CodeWatch, restartDue, UPDATE_DEFER_MAX_MS } from "./update.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(here, "../../..");
@@ -199,8 +199,9 @@ export function siteOf(answer) {
* runtimeFileList), allowed, ffmpegVersion, reencode, awake, rescanMs, comfy (OwnComfy's own options), readCounters,
* readListeners, gpuEveryMs, gpuGraceMs (MID_JOB_GRACE_MS), gpuBriefMs (BRIEF_PAUSE_MS), readGpuGen, idleClaimMs
* (IDLE_CLAIM_MS), canCleanPictures, and for job tickets: composer
- * (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, and codeWatch (update.mjs's CodeWatch: new
- * code on disk ends it with "update" once its jobs are done) }.
+ * (src/lib/ticket-compose.ts as built), catalogVersion, catalogDir, allLanes, codeWatch (update.mjs's CodeWatch: new
+ * code on disk ends it with "update" once no person's job waits for it and its jobs are done) and updateDeferMs
+ * (UPDATE_DEFER_MAX_MS) }.
*/
export async function runWorker(saved, deps) {
// One worker at a time on a worker folder: a second one would stop the first one's ComfyUI, empty its folders and
@@ -323,9 +324,13 @@ async function work(saved, deps, owner) {
let sleptSent = 0;
// Why it doesn't start the line's work now although it may (the beat's `holding`: { why, since }), or null.
let holding = null;
- // New code on disk (update.mjs): it takes no new job, finishes the one it has, and ends to start again on the new code.
+ // New code on disk (update.mjs): once no person's job waits for it (at most updateDeferMs after it found the code), it
+ // takes no new job, finishes the one it has, and ends to start again on the new code.
const codeWatch = deps.codeWatch ?? new CodeWatch({ root: ROOT, dist: path.join(here, "dist"), home: deps.home });
+ const updateDeferMs = deps.updateDeferMs ?? UPDATE_DEFER_MAX_MS;
let updating = false;
+ // When it found new code on disk (null: none yet).
+ let updateFoundAt = null;
// When its last GPU or CPU job ended while it waits to restart on new code (a text job in hand may still end).
let textDrainAt = null;
// Its ComfyUI's start, while it goes on (beats go on meanwhile), and the signal that ends a start when the worker stops.
@@ -880,9 +885,15 @@ async function work(saved, deps, owner) {
try {
while (!deps.signal?.aborted) {
const t = now();
- // New code installed: once no job is in hand (the GPU's and the CPU slot's), it ends, and starts again on it. The
- // text slot takes jobs until then; a text job in hand then gets up to TEXT_DRAIN_MS to end.
- if (!updating && codeWatch.check(t)) {
+ // New code installed: a restart never makes a person wait. While people's jobs wait that it may take (the last
+ // beat's claimableNow), it goes on taking them, for at most updateDeferMs. Then it takes no new job, and once no job
+ // is in hand (the GPU's and the CPU slot's), it ends, and starts again on it. The text slot takes jobs until then; a
+ // text job in hand then gets up to TEXT_DRAIN_MS to end.
+ if (updateFoundAt === null && codeWatch.check(t)) {
+ updateFoundAt = t;
+ if (!restartDue(t, updateFoundAt, siteOf(answer).claimable, updateDeferMs)) log(`New worker code is installed: restarting once no person's job waits for it (at most ${Math.round(updateDeferMs / 60_000)} min).`);
+ }
+ if (!updating && updateFoundAt !== null && restartDue(t, updateFoundAt, siteOf(answer).claimable, updateDeferMs)) {
updating = true;
log("New worker code is installed: restarting after this job.");
}
diff --git a/bin/lib/worker/update.mjs b/bin/lib/worker/update.mjs
index 06f924df..75d264ca 100644
--- a/bin/lib/worker/update.mjs
+++ b/bin/lib/worker/update.mjs
@@ -1,9 +1,10 @@
// New worker code on disk (docs/gpu-workers.md, "Install and update"). The worker notes the code it started with: its
// checkout's commit, the build stamp of its shared parts, and the update-ready file in its home folder (an updater
// writes it once a new build is in place). When any of them changes and the new code is whole (its parts' stamp matches
-// its checkout), the worker takes no new job, finishes the one it has, and ends with UPDATE_EXIT so that whatever
-// started it starts it again at once, on the new code. A half-done update (a checkout whose build isn't there yet)
-// never ends it: it keeps working until the parts match.
+// its checkout), the worker ends with UPDATE_EXIT so that whatever started it starts it again at once, on the new code:
+// once no person's job waits for it (restartDue; at most UPDATE_DEFER_MAX_MS after it found the new code), it takes no
+// new job, finishes the one it has, and ends. A half-done update (a checkout whose build isn't there yet) never ends it:
+// it keeps working until the parts match.
import fs from "node:fs";
import path from "node:path";
import { distProblem, STAMP_FILE } from "./stamp.mjs";
@@ -11,6 +12,19 @@ import { distProblem, STAMP_FILE } from "./stamp.mjs";
/** The exit code of `fuobe worker run` after it ended to start again on new code. */
export const UPDATE_EXIT = 75;
+/**
+ * The longest a worker puts off its restart on new code while people's jobs wait for it (ms). Past it, it restarts after
+ * the job in hand even with people's jobs waiting.
+ */
+export const UPDATE_DEFER_MAX_MS = 30 * 60_000;
+
+/**
+ * May a worker that found new code at `foundAt` begin its restart now: when no person's job waits that it may take now
+ * (`peopleWaiting`, the beat's claimableNow; null or 0 when the studio doesn't say or none waits), or once `maxMs` has
+ * gone by since it found the code. The owner's own jobs never hold a restart back.
+ */
+export const restartDue = (t, foundAt, peopleWaiting, maxMs = UPDATE_DEFER_MAX_MS) => !(Number(peopleWaiting) > 0) || t - foundAt >= maxMs;
+
/** The file in the worker's home folder that an updater writes once new code is installed and checked. */
export const UPDATE_READY_FILE = "update-ready.json";
diff --git a/docs/gpu-workers.md b/docs/gpu-workers.md
index 5ccaf090..7a41e8a3 100644
--- a/docs/gpu-workers.md
+++ b/docs/gpu-workers.md
@@ -172,9 +172,12 @@ install the worker from a zip file, from a copy that someone sends you, or from
**New code while the worker runs.** At its start, the worker notes three things: the commit of its checkout, the build
stamp of its parts (`dist/build-stamp.json`), and the file `update-ready.json` in its home folder. It looks at them
-again every 15 seconds. When one of them changes and the parts match the checkout, the worker takes no new job. It
-finishes the job that it has, writes "New worker code is installed: restarting after this job." in its log, and ends
-with exit code 75. Kept results that are not sent yet stay for its next start. Whatever starts the worker can start it
+again every 15 seconds. When one of them changes and the parts match the checkout, the worker restarts once no person's
+job waits for it: while the beat's `claimableNow` says that people's jobs wait that it may take, it goes on taking
+them on the code it runs, and its log says "New worker code is installed: restarting once no person's job waits for it
+(at most 30 min)." The owner's own jobs never hold the restart back. After 30 minutes it restarts anyway. Then it takes
+no new job, finishes the job that it has, writes "New worker code is installed: restarting after this job." in its log,
+and ends with exit code 75. Kept results that are not sent yet stay for its next start. Whatever starts the worker can start it
again at once on exit code 75. An update that is only half done (a new checkout whose build has not run yet) does not
end the worker: it works on until the parts match, and checks the stamp once a minute meanwhile. A program that
installs updates writes `update-ready.json` last, after it has checked the new build.
@@ -383,8 +386,9 @@ default). It also keeps:
- its class: `paid` or `free` for an account's run (the billing service says which; `free` without one), `owner` for
the owner's own jobs. People's runs always go first: the owner's jobs wait until no person's run waits that the
same worker could take.
-- `rank_at`: `created_at`, minus the head start the billing service gave the run inside its class (at most a day). A
- job that goes back in line keeps its `rank_at`, so it keeps its place.
+- `rank_at`: `created_at`, minus the head start the billing service gave the run inside its class (at most a day). Only
+ people's runs get a head start: the owner's own jobs keep `created_at`, so they go in the order they came. A job that
+ goes back in line keeps its `rank_at`, so it keeps its place.
- a wait limit: for an account's run, `FUOBE_POOL_WAIT_MIN` (none when it isn't set) or what the billing service set; for the
owner's own jobs, the owner's wait limit (none by default; see the queue's settings below). It applies only until a
worker first takes the job: past it, a job that no worker took fails with "The GPUs were busy".
@@ -407,9 +411,10 @@ A worker gets a job only when all of these are true, all in one SQLite transacti
it lost track of it, and nothing new.
Jobs go by class (`paid`, then `free`, then `owner`), then by the lowest `rank_at` (then the oldest). With the
-pick allowance at 0 (the default), that is the whole rule. Above 0, a worker may take a job in its warm lane (the
-models it has loaded) ahead of the best job, in the same class, while the best job has waited less than the pick
-allowance (or the worker's own `switch_after_ms`, if that is lower). With fair share on, each class goes round its
+pick allowance at 0 (the default), that is the whole rule. Above 0, a worker may take one of the owner's own jobs in its
+warm lane (the models it has loaded) ahead of the owner's best job, while that job has waited less than the pick
+allowance (or the worker's own `switch_after_ms`, if that is lower). A warm lane never makes a person wait: while a
+person's run waits that the worker can take, its next claim takes the best of them, whatever lane it has loaded. With fair share on, each class goes round its
accounts: an account's next run goes after every other account's run that is an earlier turn of its own. An account's
turns count the runs a worker holds for it now and those a worker finished for it since the oldest run still waiting
in that class came.
diff --git a/src/server/computer/pool.ts b/src/server/computer/pool.ts
index 2b3aa99e..35451cc0 100644
--- a/src/server/computer/pool.ts
+++ b/src/server/computer/pool.ts
@@ -66,6 +66,8 @@ export const runLimitMs = (p90?: number | null, lane?: string | null, loadMs?: n
* the owner's own jobs (2). A task from before classes had none: the owner's (no account) is the owner's class.
*/
const CLASS_RANK = "(CASE WHEN class = 'paid' THEN 0 WHEN class = 'owner' OR (class IS NULL AND account IS NULL) THEN 2 ELSE 1 END)";
+/** The owner's own jobs' class (classRank): after every person's run. */
+const OWNER_CLASS = 2;
export const classRank = (t: Pick<TaskRow, "class" | "account">): number => (t.class === "paid" ? 0 : t.class === "owner" || (!t.class && !t.account) ? 2 : 1);
/**
* The order workers serve waiting tasks in: by class, then by rank (a requeued task keeps its own, so it keeps its
@@ -508,8 +510,9 @@ const slotWhere = (w: Pick<WorkerRow, "cpu_slot_json">, slot: WorkerSlot) => (sl
* that slot had and lost track of; then, if the slot holds none and the worker may take work, the best waiting task that
* slot can run (its pool, its allowed lanes and their delays, the files and VRAM it needs, the retry rule, and the end of
* its hours). One task at a time in each slot: a slot that holds a task gets nothing new until that one ends or goes back
- * in line, so one worker's token never holds more than one person's GPU job and one CPU task. Sticky lanes: its warm
- * lane goes first until another lane's best task has waited longer than switch_after_ms (and is older).
+ * in line, so one worker's token never holds more than one person's GPU job and one CPU task. Sticky lanes (pick), among
+ * the owner's own jobs only: its warm lane goes first until another lane's best task has waited longer than
+ * switch_after_ms (and is older). A person's run never waits for a warm lane.
*/
export function workerClaim(w: WorkerRow, running: string[], now = Date.now(), slot: WorkerSlot = "gpu"): ClaimedTask | null {
const d = db();
@@ -656,9 +659,10 @@ function beforeWindowEnds(t: TaskRow, w: WorkerRow, now: number): boolean {
}
/**
- * The best task this worker may run, in the line's order (lineOrder). A task in the lane it has loaded may go ahead of
- * the best one, in the same class, while the best one has waited less than the pick allowance (the install's setting,
- * capped by this worker's switch_after_ms; 0: strict order).
+ * The best task this worker may run, in the line's order (lineOrder). People's runs always come first, and a warm lane
+ * never makes a person wait: while any person's run waits that this worker can take, it takes the best of them. Only
+ * among the owner's own jobs may one in the lane it has loaded go ahead of the best one, while the best one has waited
+ * less than the pick allowance (the install's setting, capped by this worker's switch_after_ms; 0: strict order).
*/
function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): { task: TaskRow | null; looked: number } {
const settings = queueSettings(now);
@@ -671,8 +675,8 @@ function pick(w: WorkerRow, now: number, slot: WorkerSlot = "gpu"): { task: Task
if (!ok.length) return { task: null, looked };
const best = ok[0];
const allowance = Math.min(w.switch_after_ms, settings.pickAllowanceMs);
- if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane) return { task: best, looked };
- const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === classRank(best));
+ if (slot === "cpu" || allowance <= 0 || !w.warm_lane || best.lane === w.warm_lane || classRank(best) !== OWNER_CLASS) return { task: best, looked };
+ const warm = ok.find((t) => t.lane === w.warm_lane && classRank(t) === OWNER_CLASS);
return { task: warm && (best.rank_at ?? best.created_at) >= now - allowance ? warm : best, looked };
}
@@ -1232,14 +1236,16 @@ export function poolFields(
const extra = { ...(o.size && { size: o.size }), ...(o.catalogVersion && { catalogVersion: o.catalogVersion }), ...(o.runtime?.length && { runtime: o.runtime }) };
const needs = found && { ...found, ...extra };
const lane = poolLane(workflowId);
+ const cls = o.class ?? (o.account ? ("free" as const) : ("owner" as const));
return {
pools: ["pool"],
// Light CPU work (the requirements index marks the workflow cpu) goes to a worker's CPU slot when it has one.
...(cpuWorkflow(workflowId) && { slot: "cpu" as const }),
account: o.account,
- class: o.class ?? (o.account ? ("free" as const) : ("owner" as const)),
- // A head start is only inside a class, and never more than a day. A later step of a run keeps the run's place (rankAt).
- rankAt: o.rankAt ?? now - Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000)),
+ class: cls,
+ // A head start is only for people's runs, only inside their class, and never more than a day: the owner's own jobs
+ // stand in line in the order they came. A later step of a run keeps the run's place (rankAt).
+ rankAt: o.rankAt ?? now - (cls === "owner" ? 0 : Math.max(0, Math.min(o.boostMs ?? 0, 24 * 60 * 60_000))),
lane,
needs: needs ?? { workflowId, files: [], packs: [], minVramBytes: 0, ...extra },
notAfter: o.waitMs ? now + o.waitMs : undefined,
diff --git a/tests/pool-line-order.test.ts b/tests/pool-line-order.test.ts
index 35a1ad6e..1983d420 100644
--- a/tests/pool-line-order.test.ts
+++ b/tests/pool-line-order.test.ts
@@ -460,7 +460,7 @@ describe("fair share", () => {
});
describe("the pick allowance", () => {
- it("0 (the default): strict order whatever the worker has loaded; set, a loaded lane goes first while the best one is young", () => {
+ it("0 (the default): strict order whatever the worker has loaded; set, a loaded lane goes first among the owner's own jobs only", () => {
const lanes = allLanes(loadIndex(), sha).map((l) => l.lane);
const w = standInWorker();
db().prepare("UPDATE relay_workers SET warm_lane = ?, switch_after_ms = ? WHERE id = ?").run(lanes[1], 60 * MIN, w.id);
@@ -473,12 +473,20 @@ describe("the pick allowance", () => {
const old2 = lineTask({ account: accountId, agoMs: 5 * MIN, lane: lanes[0] });
qs.saveQueueSettings({ ...qs.queueSettings(), pickAllowanceMs: 10 * MIN });
db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
+ // A warm lane never makes a person wait: people's runs keep their order, whatever lane is loaded.
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(old2);
+ done(old2);
+ // Never across classes: the owner's job in the loaded lane waits behind a person's run in another.
+ const ownerWarm = lineTask({ agoMs: 1 * MIN, lane: lanes[1] });
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[0], w.id);
expect(pool.workerClaim(workerRow(w), [])?.id).toBe(warm);
done(warm);
- // Never across classes: the owner's job in the loaded lane waits behind a person's run in another.
- lineTask({ agoMs: 1 * MIN, lane: lanes[1] });
+ // Among the owner's own jobs, the loaded lane goes first while the best one is young.
+ const ownerOld = lineTask({ agoMs: 5 * MIN, lane: lanes[0] });
db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(lanes[1], w.id);
- expect(pool.workerClaim(workerRow(w), [])?.id).toBe(old2);
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(ownerWarm);
+ done(ownerWarm);
+ expect(pool.workerClaim(workerRow(w), [])?.id).toBe(ownerOld);
});
});
diff --git a/tests/worker-recovery.test.ts b/tests/worker-recovery.test.ts
index b5e6e79d..5a969ad1 100644
--- a/tests/worker-recovery.test.ts
+++ b/tests/worker-recovery.test.ts
@@ -174,7 +174,7 @@ function start(
w: W,
s: Studio,
p: Pc,
- o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void>; env?: Record<string, string | undefined>; codeWatch?: unknown } = {},
+ o: { steps?: number; stepMs?: number; failNext?: string; stallMin?: number; hungMin?: number; ffmpeg?: string | null; rescanMs?: number; modelsCheckMs?: number; modelDirs?: string[]; requirements?: unknown; pins?: Record<string, string>; command?: string[]; readGpu?: () => Promise<unknown>; gpuEveryMs?: number; port?: number; now?: () => number; sleep?: (ms: number) => Promise<void>; env?: Record<string, string | undefined>; codeWatch?: unknown; updateDeferMs?: number } = {},
) {
const ctrl = new AbortController();
const cfg = {
@@ -217,6 +217,7 @@ function start(
...(o.modelsCheckMs && { modelsCheckMs: o.modelsCheckMs }),
...(o.env && { env: o.env }),
...(o.codeWatch ? { codeWatch: o.codeWatch } : {}),
+ ...(o.updateDeferMs !== undefined && { updateDeferMs: o.updateDeferMs }),
});
const r = { ctrl, done };
running.push(r);
@@ -680,6 +681,68 @@ describe("new worker code", () => {
expect(JSON.parse(fs.readFileSync(path.join(p.home, "status.json"), "utf8")).state).toBe("Finishing its job, then restarting on new code");
});
+ /**
+ * The beat's word on people's jobs (claimableNow), as `people()` says: the harness runs graph jobs, which only the
+ * owner's own jobs are, so the job that stands for a person's here is the owner's, and the beat says it is a person's.
+ */
+ function peopleSay(s: Studio, people: () => number) {
+ const api = apiAs(routes, null);
+ s.intercept = async (path, init) => {
+ if (path !== "/api/gpu/computer/beat") return undefined;
+ const res = await api(path, init);
+ if (!res.ok) return res;
+ const body = (await res.json()) as Record<string, unknown> & { worker?: { token?: { value: string } } };
+ if (body.worker?.token?.value) s.tokens.push(body.worker.token.value);
+ return Response.json({ ...body, claimableNow: people() });
+ };
+ }
+
+ it("installed while a person's job waits: it runs that job first, then restarts; the owner's own job stays for the next start", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const first = addTask();
+ const person = addTask();
+ peopleSay(s, () => (state(person.id).state === "waiting" ? 1 : 0));
+ // Each job runs longer than a beat apart (5 s while busy), so a beat while the person's job runs says none waits.
+ const r = start(w, s, p, { steps: 20, stepMs: 400, codeWatch: watch(p) });
+ await until(async () => {
+ const c = comfyOf(p);
+ return state(first.id).state !== "waiting" && c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 2;
+ });
+ installed(p);
+ await until(() => p.logs.some((l) => l.startsWith("New worker code is installed: restarting once no person's job waits for it")));
+ const owners = addTask();
+ expect(await r.done).toBe("update");
+ expect(state(first.id).state).toBe("done");
+ expect(state(person.id).state).toBe("done");
+ expect(prompts(p)).toBe(2);
+ expect(state(owners.id).state).toBe("waiting");
+ expect(p.logs.filter((l) => l === LINE)).toHaveLength(1);
+ // The restart began only once the person's job no longer waited.
+ expect(p.logs.indexOf(LINE)).toBeGreaterThan(p.logs.indexOf(`Job ${first.id} done.`));
+ }, 120_000);
+
+ it("a person's job keeps the restart back for at most the cap: past it, the worker restarts after the job in hand", async () => {
+ const w = addWorker();
+ const s = studio();
+ const p = pc();
+ const first = addTask();
+ const waiting = addTask();
+ peopleSay(s, () => 1);
+ const r = start(w, s, p, { steps: 20, stepMs: 150, codeWatch: watch(p), updateDeferMs: 0 });
+ await until(async () => {
+ const c = comfyOf(p);
+ return state(first.id).state !== "waiting" && c && ((await fakeStats(c.port).catch(() => null))?.step ?? 0) >= 2;
+ });
+ installed(p);
+ expect(await r.done).toBe("update");
+ expect(state(first.id).state).toBe("done");
+ expect(state(waiting.id).state).toBe("waiting");
+ expect(prompts(p)).toBe(1);
+ expect(p.logs.filter((l) => l === LINE)).toHaveLength(1);
+ });
+
it("installed while it waits for work: it ends at once, with its ComfyUI stopped", async () => {
const w = addWorker();
const s = studio();
diff --git a/tests/worker-update.test.ts b/tests/worker-update.test.ts
index 2789421a..d2c3a6a1 100644
--- a/tests/worker-update.test.ts
+++ b/tests/worker-update.test.ts
@@ -9,7 +9,7 @@ import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { worker } from "../bin/lib/worker/index.mjs";
import { buildStamp, STAMP_FILE } from "../bin/lib/worker/stamp.mjs";
-import { CodeWatch, codeOnDisk, headOf, UPDATE_EXIT, UPDATE_READY_FILE } from "../bin/lib/worker/update.mjs";
+import { CodeWatch, codeOnDisk, headOf, restartDue, UPDATE_DEFER_MAX_MS, UPDATE_EXIT, UPDATE_READY_FILE } from "../bin/lib/worker/update.mjs";
import { tempDir } from "./helpers/temp-dir";
// `fuobe worker run` with a loop that ends for new code at once (the loop itself is tested elsewhere).
@@ -56,6 +56,17 @@ describe("the commit a checkout is at", () => {
});
describe("new code on disk", () => {
+ it("restartDue: at once when no person's job waits (or the studio doesn't say); while one waits, only after the cap", () => {
+ expect(restartDue(1000, 1000, 0)).toBe(true);
+ expect(restartDue(1000, 1000, null)).toBe(true);
+ expect(restartDue(1000, 1000, undefined)).toBe(true);
+ expect(restartDue(1000, 1000, 2)).toBe(false);
+ expect(restartDue(1000 + UPDATE_DEFER_MAX_MS - 1, 1000, 2)).toBe(false);
+ expect(restartDue(1000 + UPDATE_DEFER_MAX_MS, 1000, 2)).toBe(true);
+ expect(restartDue(5000, 1000, 1, 4000)).toBe(true);
+ expect(UPDATE_DEFER_MAX_MS).toBe(30 * 60_000);
+ });
+
it("nothing changed: no restart", () => {
const home = tempDir("fuobe-worker-update-home-");
const w = new CodeWatch({ root: repo(A), dist: parts("s1"), home, everyMs: 0, problem: () => null });
diff --git a/tests/workers-pool.test.ts b/tests/workers-pool.test.ts
index 68ab033d..b205cebb 100644
--- a/tests/workers-pool.test.ts
+++ b/tests/workers-pool.test.ts
@@ -401,6 +401,55 @@ describe("order (checks 8, 9)", () => {
expect(state(long).state).toBe("waiting");
});
+ it("people first: every person's run goes before the owner's own jobs, even one a day older; each in the order they came", () => {
+ const w = worker("people-first");
+ const owner1 = task({ rankAgoMs: 24 * 60 * MIN });
+ const owner2 = task({ rankAgoMs: 23 * 60 * MIN });
+ const guest = task({ account: "guest", rankAgoMs: 2 * MIN });
+ const person = task({ account: "acct-a", rankAgoMs: 1 * MIN });
+ const order: string[] = [];
+ for (let i = 0; i < 4; i++) {
+ const c = claim(w);
+ order.push(c!.id);
+ db().prepare("UPDATE relay_tasks SET state = 'done' WHERE id = ?").run(c!.id);
+ }
+ expect(order).toEqual([guest, person, owner1, owner2]);
+ });
+
+ it("the owner's own jobs get no head start: a boost moves only a person's run up in its class", () => {
+ expect(pool.poolFields("wf-a", { boostMs: 60 * MIN }, clock).rankAt).toBe(clock);
+ expect(pool.poolFields("wf-a", { class: "owner", boostMs: 60 * MIN }, clock).rankAt).toBe(clock);
+ expect(pool.poolFields("wf-a", { account: "acct-a", boostMs: 60 * MIN }, clock).rankAt).toBe(clock - 60 * MIN);
+ expect(pool.poolFields("wf-a", { account: "acct-a", boostMs: 48 * 60 * MIN }, clock).rankAt).toBe(clock - 24 * 60 * MIN);
+ });
+
+ it("a warm lane never makes a person wait: with a pick allowance, a person's run in another lane goes before the warm lane", () => {
+ const w = worker("warm-people", { lanes: [LANE_A, LANE_B] });
+ db().prepare("UPDATE relay_workers SET warm_lane = ?, switch_after_ms = ? WHERE id = ?").run(LANE_A, 30 * MIN, w.id);
+ saveQueueSettings({ ...queueSettings(), pickAllowanceMs: 60 * MIN });
+ try {
+ // The owner's job in the warm lane, older than the person's run that just came in another lane.
+ const ownerWarm = task({ lane: LANE_A, rankAgoMs: 10 * MIN });
+ const person = task({ lane: LANE_B, account: "acct-a", rankAgoMs: 0 });
+ expect(claim(w)?.id).toBe(person);
+ db().prepare("UPDATE relay_tasks SET state = 'done' WHERE id = ?").run(person);
+ // Two people's runs: the older one goes first, whatever lane is warm.
+ const older = task({ lane: LANE_B, account: "acct-b", rankAgoMs: 1 * MIN });
+ const warmPerson = task({ lane: LANE_A, account: "acct-c", rankAgoMs: 0 });
+ expect(claim(w)?.id).toBe(older);
+ db().prepare("UPDATE relay_tasks SET state = 'done' WHERE id = ?").run(older);
+ expect(claim(w)?.id).toBe(warmPerson);
+ db().prepare("UPDATE relay_tasks SET state = 'done' WHERE id = ?").run(warmPerson);
+ // Among the owner's own jobs only, the warm lane still goes first while the best one is inside the allowance.
+ db().prepare("UPDATE relay_workers SET warm_lane = ? WHERE id = ?").run(LANE_B, w.id);
+ const ownerB = task({ lane: LANE_B, rankAgoMs: 0 });
+ expect(claim(w)?.id).toBe(ownerB);
+ expect(state(ownerWarm).state).toBe("waiting");
+ } finally {
+ saveQueueSettings(QUEUE_DEFAULTS);
+ }
+ });
+
it("tasks in one class go by rank_at, not by arrival", () => {
const w = worker("rank");
const later = task({ rankAgoMs: 0 });