Skip to content

Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.

Merge origin/main 59a6e2b2 into #651 for 0.8.29 [C7,V4]

Corey Olson9c5ff95b3bd6
diff --cc src/cli.js
index e6e7b58b,062d6c58..f0dd1131
--- a/src/cli.js
+++ b/src/cli.js
@@@ -1821,10 -1886,11 +1886,11 @@@ function readCommands(io, { first, seco
io.say(`browserSlots (machine setting): ${browserSlots}`);
if (!resources.length) io.say('no resources have been used');
for (const resource of resources) {
- io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})`);
+ io.say(`${resource.name} (${resource.scope}, capacity ${resource.capacity})${resource.order === 'arrival' ? '; an older pullboard is waiting, so this line is in arrival order, landings first' : ''}`);
for (const holder of resource.holders) io.say(` held by ${agentDisplayName(agents, ctx.config, holder.agent)}${holder.repo ? ` in ${holder.repo}` : ''}${resourceRunLabel(holder)} since ${holder.since}`);
- resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${resourceRunLabel(waiter)}`));
+ resource.line.forEach((waiter, index) => io.say(` ${index + 1}. waiting: ${agentDisplayName(agents, ctx.config, waiter.agent)}${waiter.repo ? ` in ${waiter.repo}` : ''}${resourceRunLabel(waiter)}; class ${waiter.queueClass}${waiter.agedFrom ? `, aged up from ${waiter.agedFrom}` : ''}`));
}
+ for (const runner of runners) io.say(`runner ${runner.host}: ${runner.inUse}/${runner.slots} slots, ${runner.browserInUse}/${runner.browser} browser${runner.unavailable ? ' (unavailable; re-register after checking the host)' : ''}`);
return 0;
},
resume: () => resumeHere(io),
diff --cc src/resources.js
index 337a5139,f52a4931..6f487da1
--- a/src/resources.js
+++ b/src/resources.js
@@@ -86,11 -96,16 +96,20 @@@ function openQueue(file)
if (!columns.includes('browser')) db.exec(`ALTER TABLE ${table} ADD COLUMN browser INTEGER NOT NULL DEFAULT 0`);
if (!columns.includes('item')) db.exec(`ALTER TABLE ${table} ADD COLUMN item TEXT NOT NULL DEFAULT ''`);
if (!columns.includes('kind')) db.exec(`ALTER TABLE ${table} ADD COLUMN kind TEXT NOT NULL DEFAULT ''`);
+ if (table === 'holder' && !columns.includes('runner')) db.exec("ALTER TABLE holder ADD COLUMN runner TEXT NOT NULL DEFAULT ''");
+ if (table === 'waiter' && !columns.includes('remote')) db.exec('ALTER TABLE waiter ADD COLUMN remote INTEGER NOT NULL DEFAULT 0');
}
+ // Marks a waiter whose process admits by class; an older pullboard leaves it 0.
+ if (!db.prepare('PRAGMA table_info(waiter)').all().some(({ name }) => name === 'classed')) {
+ db.exec('ALTER TABLE waiter ADD COLUMN classed INTEGER NOT NULL DEFAULT 0');
+ }
+ // Older runner-aware builds stored remote leases as ordinary gate holders. Move them
+ // into their host namespace so old readers of name='gate' continue to see local use only.
+ db.exec(`INSERT INTO resource(name, capacity)
+ SELECT 'runner:' || runner, MAX(1, COUNT(*)) FROM holder
+ WHERE name = 'gate' AND runner <> '' GROUP BY runner
+ ON CONFLICT(name) DO NOTHING;
+ UPDATE holder SET name = 'runner:' || runner WHERE name = 'gate' AND runner <> '';`);
db.exec('COMMIT');
transaction = false;
} catch (error) {
@@@ -175,67 -190,22 +194,71 @@@ function update(db, action)
}
}
-/** Current holders and the landing-first line, then every other kind in arrival order. */
-function snapshot(db, name) {
+/** Admission classes, most urgent first. */
+export const QUEUE_CLASSES = ['landing', 'review', 'submit', 'other'];
+/** A waiter moves up one class for every this long it has waited, so no class starves. */
+export const QUEUE_AGE_MS = 30 * 60_000;
+
+/**
+ * A waiter's admission class: its declared class from the run it names, and the class it holds now
+ * after aging up one class per QUEUE_AGE_MS waited. Landings come first, then reviews (they unblock
+ * landing), then submits and item checks, then focused, diagnostic and every other run.
+ *
+ * @param {{ landing?: number|boolean, itemCheck?: number|boolean, diagnostic?: number|boolean, kind?: string, since?: string }} entry
+ * @param {number} [now] - The clock reading to age against; injectable so tests need not wait.
+ * @returns {{ base: number, effective: number, name: string, declared: string }}
+ */
+export function queueClass(entry, now = Date.now()) {
+ const kind = entry.kind ?? '';
+ const base = entry.landing === true || entry.landing === 1 ? 0
+ : kind === 'review' ? 1
+ : !(entry.diagnostic === true || entry.diagnostic === 1) && (entry.itemCheck === true || entry.itemCheck === 1 || kind === 'submit' || kind === 'check') ? 2
+ : 3;
+ const waited = Math.max(0, now - (Date.parse(entry.since ?? '') || now));
+ const effective = Math.max(0, base - Math.floor(waited / QUEUE_AGE_MS));
+ return { base, effective, name: QUEUE_CLASSES[effective], declared: QUEUE_CLASSES[base] };
+}
+
+/**
+ * The admission rank every process in this queue agrees on. Class order (with aging) applies only
+ * while every waiter was queued by a process that admits by class. Why: an older pullboard admits
+ * landings first and then by ticket, and two processes ranking the same line differently each
+ * wait for the other while a slot stays empty. With any older waiter queued, everyone falls back
+ * to that older order, so mixed versions on one machine never deadlock.
+ *
+ * @param {Array<{ classed?: number }>} waiters - The whole line for one resource.
+ * @param {number} now
+ * @returns {(waiter: object) => number}
+ */
+function admissionRank(waiters, now) {
+ const byClass = waiters.every((waiter) => waiter.classed === 1);
+ return byClass ? (waiter) => queueClass(waiter, now).effective : (waiter) => (waiter.landing === 1 ? 0 : 1);
+}
+
+/** Current holders and the waiting line in admission order, each waiter naming its class. */
+function snapshot(db, name, now = Date.now()) {
/** Preserve older public entries while naming diagnostics as a distinct queue class. */
- const project = ({ diagnostic, browser, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,
+ const project = ({ diagnostic, browser, remote, runner, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,
itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),
- ...(browser === 1 ? { browser: true } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });
+ ...(browser === 1 ? { browser: true } : {}), ...(remote === 1 ? { remote: true } : {}),
+ ...(runner ? { runner } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });
// Browser is an additional capability on a gate lease, not a second partially held row.
const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';
const sourceName = name === 'browser' ? 'gate' : name;
- const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);
+ const runnerHost = name.startsWith('runner:') ? name.slice('runner:'.length) : '';
+ const holderWhere = runnerHost ? 'name = ?' : where;
+ const holderValues = [sourceName];
+ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind FROM holder WHERE ${holderWhere} ORDER BY since, token`).all(...holderValues).map(project);
- const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);
- return { holders, line };
+ const queued = db.prepare('SELECT classed FROM waiter WHERE name = ?').all(sourceName);
+ const rank = admissionRank(queued, now);
- const line = db.prepare(`SELECT ticket, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind, classed FROM waiter WHERE ${where}`).all(sourceName)
++ const line = db.prepare(`SELECT ticket, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind, classed FROM waiter WHERE ${where}`).all(sourceName)
+ .sort((left, right) => rank(left) - rank(right) || left.ticket - right.ticket)
+ .map(({ ticket, classed, ...entry }) => {
+ const current = queueClass(entry, now);
+ return { ...project(entry), queueClass: current.name, ...(current.effective < current.base ? { agedFrom: current.declared } : {}) };
+ });
+ // An older pullboard in the line means everyone admits in arrival order until it leaves.
+ return { holders, line, ...(queued.some((waiter) => waiter.classed !== 1) ? { order: 'arrival' } : {}) };
}
/** Count reported or admissible queue position separately so blocked work cannot distort the visible line. */
@@@ -264,14 -234,122 +287,138 @@@ function waiterPosition(db, name, ticke
return considered.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;
}
+ /** Validate the configured remote executors before using them in a queue transaction. */
+ function validatedRunners(value) {
+ if (!Array.isArray(value)) throw new Refused('BAD_RUNNER_POOL', 'runnerProvider must return an array of runner settings');
+ const seen = new Set();
+ return value.map((runner) => {
+ if (!runner || typeof runner.host !== 'string' || !runner.host.trim() || runner.host.trim() !== runner.host
+ || !Number.isSafeInteger(runner.slots) || runner.slots < 1
+ || !Number.isSafeInteger(runner.browser) || runner.browser < 0 || runner.browser > runner.slots
+ || seen.has(runner.host)) {
+ throw new Refused('BAD_RUNNER_POOL', 'runners require unique nonempty hosts, positive slots, and browser capacity from zero through slots');
+ }
+ seen.add(runner.host);
+ return { host: runner.host, slots: runner.slots, browser: runner.browser,
+ ...(typeof runner.node === 'string' ? { node: runner.node } : {}),
+ ...(typeof runner.root === 'string' ? { root: runner.root } : {}) };
+ });
+ }
+
-/** Find the earliest compatible free executor while allowing CPU waiters past browser-only blocks. */
-function gateAdmission(db, ticket, capacity, runners) {
- const waiters = db.prepare("SELECT ticket, pid, landing, browser, remote FROM waiter WHERE name = 'gate' ORDER BY landing DESC, ticket").all();
++/**
++ * Find the earliest compatible free executor while allowing CPU waiters past browser-only blocks.
++ * Local and remote slots are offered in one admission order: the class rank that snapshot and
++ * waiterPosition report (landing, review, submit, other, aging up), FIFO by ticket within a class,
++ * or landing-first arrival order while an older pullboard waits in the line. Why one order: a
++ * second order for runners would let a focused run take a remote slot ahead of a review that
++ * could also run there.
++ *
++ * @param {import('node:sqlite').DatabaseSync} db
++ * @param {number} ticket - The waiter asking for admission.
++ * @param {number} capacity - Local gate slots.
++ * @param {Array<{host:string,slots:number,browser:number}>} runners - Validated remote executors.
++ * @param {number} [now] - The clock reading to age against.
++ * @returns {{host:string,slots:number,browser:number}|null}
++ */
++function gateAdmission(db, ticket, capacity, runners, now = Date.now()) {
++ const queued = db.prepare("SELECT ticket, pid, since, landing, item_check AS itemCheck, diagnostic, browser, remote, kind, classed FROM waiter WHERE name = 'gate'").all();
++ const rank = admissionRank(queued, now);
++ const waiters = queued.sort((left, right) => rank(left) - rank(right) || left.ticket - right.ticket);
+ const holders = db.prepare("SELECT pid, landing, browser FROM holder WHERE name = 'gate'").all();
+ const localUsed = holders.length;
+ const localBrowsers = holders.filter(holder => holder.browser === 1).length;
+ const browserCapacity = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get()?.capacity ?? 1;
+ const usage = new Map(runners.map(runner => {
+ // The reserved namespace is authoritative even for an older generic holder that
+ // predates the name guard and has no runner column value.
+ const remoteHolders = db.prepare('SELECT browser FROM holder WHERE name = ?').all(runnerResourceName(runner.host));
+ return [runner.host, {
+ slots: remoteHolders.length,
+ browsers: remoteHolders.filter(holder => holder.browser === 1).length,
+ }];
+ }));
+ const unavailable = new Set(db.prepare('SELECT host FROM runner_unavailable').all().map(row => row.host));
+ /** Keep an already holding process from taking another slot ahead of a different landing. */
+ const blockedByLanding = waiter => holders.some(holder => holder.pid === waiter.pid)
+ && waiters.some(other => other.landing === 1 && other.pid !== waiter.pid);
+ /** Find a currently free compatible slot without reserving it for later queue entries. */
+ function available(waiter) {
+ if (blockedByLanding(waiter)) return null;
+ if (localUsed < capacity && (waiter.browser !== 1 || localBrowsers < browserCapacity)) {
+ return { host: '', slots: capacity, browser: waiter.browser === 1 ? 1 : 0 };
+ }
+ if (waiter.remote === 1) {
+ for (const runner of runners) {
+ if (unavailable.has(runner.host) || (waiter.browser === 1 && runner.browser < 1)) continue;
+ const used = usage.get(runner.host);
+ if (used.slots >= runner.slots || (waiter.browser === 1 && used.browsers >= runner.browser)) continue;
+ return runner;
+ }
+ }
+ return null;
+ }
+ for (const runner of runners) {
+ const resourceName = runnerResourceName(runner.host);
+ const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(resourceName);
+ const held = usage.get(runner.host).slots;
+ if (!row) db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?)').run(resourceName, runner.slots);
+ else if (row.capacity !== runner.slots) {
+ if (held > runner.slots) throw new Refused('RUNNER_CAPACITY_MISMATCH', `runner ${runner.host} has ${held} active slot(s), more than configured capacity ${runner.slots}`);
+ db.prepare('UPDATE resource SET capacity = ? WHERE name = ?').run(runner.slots, resourceName);
+ }
+ }
+ for (const waiter of waiters) {
+ const executor = available(waiter);
+ if (executor) return waiter.ticket === ticket ? executor : null;
+ }
+ return null;
+ }
+
+ /** List configured runners with active slot usage from the same local admission database. */
+ export function runnerResourceStatus(runners) {
+ const configured = validatedRunners(runners);
+ const db = open(machineResourceFile());
+ try {
+ return update(db, () => configured.map(runner => {
+ const holders = db.prepare('SELECT agent, repo, since, browser, item, kind, runner FROM holder WHERE name = ? ORDER BY since, token')
+ .all(runnerResourceName(runner.host));
+ const unavailable = db.prepare('SELECT since, detail FROM runner_unavailable WHERE host = ?').get(runner.host);
+ return { ...runner, inUse: holders.length, browserInUse: holders.filter(holder => holder.browser === 1).length,
+ unavailable: Boolean(unavailable), ...(unavailable ? { unavailableSince: unavailable.since, unavailableReason: unavailable.detail } : {}), holders };
+ }));
+ } finally { db.close(); }
+ }
+
+ /** Serialize runner-setting changes against active remote leases and clear that host's quarantine. */
+ export function updateRunnerSettings(host, persist) {
+ if (typeof host !== 'string' || !host.trim() || host.trim() !== host || typeof persist !== 'function') {
+ throw new Refused('BAD_RUNNER_SETTINGS', 'a runner host and settings persistence callback are required');
+ }
+ const db = open(machineResourceFile());
+ try {
+ return update(db, () => {
+ const resourceName = runnerResourceName(host);
+ const held = db.prepare('SELECT COUNT(*) AS count FROM holder WHERE name = ?').get(resourceName).count;
+ if (held) throw new Refused('RUNNER_BUSY', `runner ${host} has ${held} active slot(s); wait for them to finish before changing its settings`);
+ const result = persist();
+ if (Number.isSafeInteger(result?.slots) && result.slots > 0) {
+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET capacity = excluded.capacity')
+ .run(resourceName, result.slots);
+ }
+ db.prepare('DELETE FROM runner_unavailable WHERE host = ?').run(host);
+ return result;
+ });
+ } finally { db.close(); }
+ }
+
/** Pause briefly between durable queue checks. */
function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }
/**
- * Join the landing-first queue; every other kind keeps its original FIFO ticket.
+ * Join the queue in its admission class (landing, review, submit, other), aging up over time; FIFO by ticket within a class.
*
- * @param {{ name: string, capacity: number, capacityProvider?: () => number, browserCapacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.
- * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}
+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, browserCapacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, remote?: boolean, runnerProvider?: () => Array<{host:string,slots:number,browser:number}>, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean, _resume?: object }} options - Resource identity, queue class and optional remote executor pool.
+ * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, runner?: {host:string,slots:number,browser:number}, waitMs: number, release: () => void, renew: () => void, requeueRunner?: () => Promise<object> }>}
*/
export async function takeResource(options) {
const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;
@@@ -328,16 -418,28 +487,29 @@@
}
db.prepare("INSERT INTO resource(name, capacity) VALUES ('browser', ?) ON CONFLICT(name) DO NOTHING").run(browserCapacity);
}
- // The kind and flags decide the admission class; the ticket keeps arrival order within it.
- db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
+ if (!resume) {
- // Remote eligibility is metadata on this same ticket, preserving one landing/FIFO queue.
- const inserted = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
++ // Remote eligibility is metadata on this same ticket; the kind and flags decide the
++ // admission class, and the ticket keeps arrival order within it.
++ const inserted = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
+ initialTicket = Number(inserted.lastInsertRowid);
+ }
});
while (true) {
const acquired = update(db, () => {
+ // The machine-settings provider performs a bounded local JSON read. Read it
+ // after taking the same SQLite write lock used by updateRunnerSettings so an
+ // older pre-lock snapshot cannot overwrite a newer configured capacity.
+ const runners = runnerProvider ? validatedRunners(runnerProvider()) : [];
const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);
if (!waiter) {
+ if (resume && initialTicket) {
- db.prepare('INSERT OR IGNORE INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(initialTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
++ db.prepare('INSERT OR IGNORE INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)').run(initialTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
+ return { acquired: false, state: { ...snapshot(db, name), position: waiterPosition(db, name, initialTicket), rejoined: true } };
+ }
queuedAt = new Date().toISOString();
- const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
- return { acquired: false, state: { ...snapshot(db, name), position: waiterPosition(db, name, Number(rejoined.lastInsertRowid)), rejoined: true } };
- const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
++ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
+ initialTicket = Number(rejoined.lastInsertRowid);
+ return { acquired: false, state: { ...snapshot(db, name), position: waiterPosition(db, name, initialTicket), rejoined: true } };
}
db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);
const spot = snapshot(db, name);
@@@ -384,7 -495,38 +565,39 @@@
throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);
}
};
- return { name, scope, token, pool, browser, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };
+ /** Quarantine a failed remote host and retry this exact ticket on another executor. */
+ const requeueRunner = async () => {
+ if (!acquired.runner) throw new Refused('LOCAL_RUNNER_REQUEUE', 'only a remote lease can be returned to the runner queue');
+ if (released || transferred || lost) throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);
+ transferred = true;
+ clearInterval(heartbeat);
+ let requeueTicket = acquired.ticket;
+ try {
+ update(db, () => {
+ db.prepare('INSERT INTO runner_unavailable(host, since, detail) VALUES (?, ?, ?) ON CONFLICT(host) DO UPDATE SET since = excluded.since, detail = excluded.detail')
+ .run(acquired.runner.host, new Date().toISOString(), 'TRANSPORT_LOST');
+ const holderName = runnerResourceName(acquired.runner.host);
+ const holder = db.prepare('SELECT token FROM holder WHERE token = ? AND name = ? AND runner = ?').get(token, holderName, acquired.runner.host);
+ if (!holder) throw new Refused('RESOURCE_LEASE_LOST', `remote lease for "${name}" is no longer held`);
- const minimumTicket = db.prepare("SELECT MIN(ticket) AS ticket FROM waiter WHERE name = 'gate' AND landing = ?").get(Number(landing)).ticket;
++ // Ahead of every gate ticket, so it leads its admission class (it keeps its queuedAt, so its aging too).
++ const minimumTicket = db.prepare("SELECT MIN(ticket) AS ticket FROM waiter WHERE name = 'gate'").get().ticket;
+ requeueTicket = Math.min(0, minimumTicket ?? 0) - 1;
+ db.prepare('DELETE FROM holder WHERE token = ?').run(token);
- db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
++ db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)')
+ .run(requeueTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote));
+ });
+ } catch (error) {
+ transferred = false;
+ startHeartbeat();
+ throw error;
+ }
+ db.close();
+ return takeResource({ ...options, _resume: { token, ticket: requeueTicket ?? acquired.ticket,
+ queuedAt, requestedAt, priorWaitMs: acquiredWaitMs, waitStartedAt: Date.now() } });
+ };
+ return { name, scope, token, pool, browser, ...(acquired.runner ? { runner: acquired.runner } : {}),
+ waitMs: acquiredWaitMs, release, renew,
+ ...(acquired.runner ? { requeueRunner } : {}) };
}
options.onWait?.(acquired.state);
await pause(POLL_MS);
diff --cc test/resources.test.js
index 3d2e00a7,78d4c796..27c88680
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@@ -656,105 -746,6 +747,156 @@@ test('the pool alone orders submits, re
await release(secondReview);
});
+test('the pool admits reviews before submits before focused runs, and waiting runs age up [C7,V4]', async () => {
+ const AGE_MS = 30 * 60_000;
+ const box = fixture();
+ const holders = [poolWorker(box, { agent: 'holder-one' }), poolWorker(box, { agent: 'holder-two' })];
+ for (const holder of holders) await acquired(holder);
+ const waiting = new Map();
+ const positions = {};
+ for (const [agent, options] of [
+ ['focused-one', { kind: 'focused' }],
+ ['diagnostic-one', { kind: 'diagnostic' }],
+ ['submit-one', { kind: 'submit', item: '650' }],
+ ['review-one', { kind: 'review', item: '651' }],
+ ['landing-one', { landing: true }],
+ ['focused-two', { kind: 'focused' }],
+ ]) {
+ const child = poolWorker(box, { agent, ...options });
+ waiting.set(agent, child);
+ positions[agent] = (await event(child)).queued.position;
+ }
+ assert.deepEqual(positions, { 'focused-one': 1, 'diagnostic-one': 2, 'submit-one': 1, 'review-one': 1, 'landing-one': 1, 'focused-two': 6 },
+ 'each arrival takes its place by class, behind earlier runs of its own class');
+ const line = () => privateList(box).find(({ name }) => name === 'gate').line
+ .map(({ agent, queueClass: listed, agedFrom }) => [agent, listed, agedFrom ?? '']);
+ assert.deepEqual(line(), [
+ ['landing-one', 'landing', ''],
+ ['review-one', 'review', ''],
+ ['submit-one', 'submit', ''],
+ ['focused-one', 'other', ''],
+ ['diagnostic-one', 'other', ''],
+ ['focused-two', 'other', ''],
+ ], 'landing, then reviews, then submits, then focused and other runs, first come first served within each');
+
+ // Waiting time is the only input to aging; backdating the queued time stands in for the clock.
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ try {
+ const backdate = db.prepare('UPDATE waiter SET since = ? WHERE agent = ?');
+ backdate.run(new Date(Date.now() - 2 * AGE_MS - 60_000).toISOString(), 'focused-two');
+ backdate.run(new Date(Date.now() - AGE_MS - 60_000).toISOString(), 'diagnostic-one');
+ } finally { db.close(); }
+ assert.deepEqual(line(), [
+ ['landing-one', 'landing', ''],
+ ['review-one', 'review', ''],
+ ['focused-two', 'review', 'other'],
+ ['diagnostic-one', 'submit', 'other'],
+ ['submit-one', 'submit', ''],
+ ['focused-one', 'other', ''],
+ ], 'a run waiting an hour ranks with reviews and one waiting half an hour with submits, keeping its arrival place there');
+
+ const order = [];
+ let releasing = [...holders];
+ for (const agent of ['landing-one', 'review-one', 'focused-two', 'diagnostic-one', 'submit-one', 'focused-one']) {
+ await release(releasing.shift());
+ const child = waiting.get(agent);
+ assert.equal((await acquired(child)).acquired, agent, `${agent} is admitted next`);
+ order.push(agent);
+ releasing.push(child);
+ }
+ for (const child of releasing) await release(child);
+ assert.deepEqual(order, ['landing-one', 'review-one', 'focused-two', 'diagnostic-one', 'submit-one', 'focused-one']);
+
++ // A remote run whose runner drops is requeued and keeps class order: it leads its own class,
++ // behind waiting reviews and submits, and the line stays in class order (no fallback to arrival).
++ const remoteBox = fixture();
++ const localHolders = [poolWorker(remoteBox, { agent: 'local-one' }), poolWorker(remoteBox, { agent: 'local-two' })];
++ for (const holder of localHolders) await acquired(holder);
++ const remoteWaiting = new Map();
++ for (const [agent, options] of [['focused-early', { kind: 'focused' }], ['submit-later', { kind: 'submit', item: '650' }], ['review-later', { kind: 'review', item: '651' }]]) {
++ const child = poolWorker(remoteBox, { agent, ...options });
++ remoteWaiting.set(agent, child);
++ await event(child);
++ }
++ const previousHome = process.env.PULLBOARD_HOME;
++ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;
++ process.env.PULLBOARD_HOME = remoteBox.home;
++ process.env.PULLBOARD_MACHINE_HOME = remoteBox.home;
++ let requeued;
++ try {
++ const remoteLease = await takeResource({ name: 'gate', capacity: 2, scope: 'machine', root: remoteBox.first,
++ agent: 'remote-focused', kind: 'focused', remote: true, runnerProvider: () => [{ host: 'fixture-runner', slots: 1, browser: 0 }] });
++ assert.equal(remoteLease.runner?.host, 'fixture-runner', 'the only free slot is the runner, so the remote-capable run takes it');
++ const requeue = remoteLease.requeueRunner();
++ const remoteGate = () => privateList(remoteBox).find(({ name }) => name === 'gate');
++ while (!remoteGate().line.some(({ agent }) => agent === 'remote-focused')) await new Promise((resolveTick) => setTimeout(resolveTick, 20));
++ assert.equal(remoteGate().order, undefined, 'a requeued remote waiter is marked as class-ordered, so the pool keeps class order');
++ assert.deepEqual(remoteGate().line.map(({ agent, queueClass: listed }) => [agent, listed]), [
++ ['review-later', 'review'], ['submit-later', 'submit'], ['remote-focused', 'other'], ['focused-early', 'other'],
++ ], 'the requeued remote run leads its own class, behind later reviews and submits');
++ const remoteOrder = [];
++ /** Free one slot, then record which waiter the pool admits into it. */
++ const admitNext = async (freed, agent) => {
++ await release(freed);
++ if (agent === 'remote-focused') {
++ requeued = await requeue;
++ assert.equal(requeued.runner, undefined, 'the quarantined runner is not used again');
++ } else assert.equal((await acquired(remoteWaiting.get(agent))).acquired, agent, `${agent} is admitted next`);
++ remoteOrder.push(agent);
++ };
++ await admitNext(localHolders[0], 'review-later');
++ await admitNext(localHolders[1], 'submit-later');
++ await admitNext(remoteWaiting.get('review-later'), 'remote-focused');
++ await admitNext(remoteWaiting.get('submit-later'), 'focused-early');
++ assert.deepEqual(remoteOrder, ['review-later', 'submit-later', 'remote-focused', 'focused-early']);
++ await release(remoteWaiting.get('focused-early'));
++ } finally {
++ requeued?.release();
++ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;
++ else process.env.PULLBOARD_HOME = previousHome;
++ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
++ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
++ }
++
+ // The class rule itself, against an injected clock rather than real waiting.
+ const { QUEUE_AGE_MS, queueClass } = await import('../src/resources.js');
+ const queuedAt = Date.parse('2026-10-15T19:37:00.000Z');
+ const at = (minutes) => queuedAt + minutes * 60_000;
+ const since = new Date(queuedAt).toISOString();
+ assert.equal(QUEUE_AGE_MS, 30 * 60_000, 'a waiter moves up one class every 30 minutes');
+ assert.deepEqual([0, 29, 30, 60, 90, 300].map((minutes) => queueClass({ kind: 'focused', since }, at(minutes)).name),
+ ['other', 'other', 'submit', 'review', 'landing', 'landing'], 'a focused run ages up one class per 30 minutes waited');
+ assert.equal(queueClass({ kind: 'review', since }, at(30)).name, 'landing');
+ assert.equal(queueClass({ kind: 'main-red', diagnostic: 1, itemCheck: 1, since }, at(0)).name, 'other', 'a diagnostic is optional work');
+ assert.equal(queueClass({ kind: 'check', itemCheck: 1, since }, at(0)).name, 'submit', 'an item check ranks with submits');
+ assert.equal(queueClass({ landing: 1, since }, at(0)).name, 'landing');
+});
+
+test('a line holding an older pullboard waiter keeps arrival order, so mixed versions never deadlock [C7]', async () => {
+ const box = fixture();
+ const holders = [poolWorker(box, { agent: 'mixed-holder-one' }), poolWorker(box, { agent: 'mixed-holder-two' })];
+ for (const holder of holders) await acquired(holder);
+ const older = poolWorker(box, { agent: 'older-focused', kind: 'focused' });
+ await event(older);
+ // An older pullboard writes no class marker; it admits landings first and then by ticket.
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ try { db.prepare("UPDATE waiter SET classed = 0 WHERE agent = 'older-focused'").run(); }
+ finally { db.close(); }
+ const review = poolWorker(box, { agent: 'newer-review', kind: 'review', item: '651' });
+ assert.equal((await event(review)).queued.position, 2, 'the review waits behind the older waiter\'s earlier ticket');
+ const gate = () => privateList(box).find(({ name }) => name === 'gate');
+ assert.equal(gate().order, 'arrival');
+ assert.deepEqual(gate().line.map(({ agent }) => agent), ['older-focused', 'newer-review']);
+
+ await release(holders[0]);
+ assert.equal((await acquired(older)).acquired, 'older-focused', 'both versions agree the earlier ticket goes first');
+ assert.equal(gate().order, undefined, 'class order resumes once only marked waiters remain');
+ await release(holders[1]);
+ assert.equal((await acquired(review)).acquired, 'newer-review');
+ await release(older);
+ await release(review);
+});
+
test('[Q1,Q2] a waiting landing keeps a current holder from taking the second slot [Q1,Q2]', async () => {
const box = fixture();
const firstHolder = worker(box, { capacity: 2, agent: 'same-run' });