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.

feat(settings): reviews-first queue order is a machine opt-in [C7,O5]

Corey Olson2237cf1f5852
diff --git a/docs/api.md b/docs/api.md
index dbafe4db..abe42911 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -12,6 +12,8 @@ A successful command returns the fields listed below. `version` is always the nu
Browser-free check admission is opt-in per machine with `"gate": { "browserFreeChecks": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the reviewed test classifier can let checks use a CPU-only gate slot. An absent or false setting keeps every check browser-gated, and uncertain or unsupported test commands remain browser-gated even when enabled. The same setting controls the wider frozen-check classification introduced in 0.8.26.
+The machine gate pool admits landings first and then everything else in arrival order. A machine opts in to reviews first with `"gate": { "queue": { "reviewsFirst": true } }` in `~/.pullboard/settings.json`: the pool then admits landing runs, then reviews, then submits and item checks, then focused and other runs, first come first served within each class. `gate.queue.agingMinutes` (a positive whole number, default `30`) is how long a waiting run waits before it moves up one class, so no class starves; it is used only while `reviewsFirst` is true. `pullboard settings` prints both values, and `pullboard resources` names the order in effect.
+
When `add` or `edit` supplies a new nonempty check, it records the item before measuring that check in a background temporary checkout of the captured `main` commit. Use `--wait` to wait for the measurement before returning, or `args.wait: true` for an HTTP add/edit move. The item returned by `add`, `edit`, `show`, and `next --verify` may include `item_check_baseline`: `{command, main, result, request?, seconds?, reason?, warning?}`. `main` is the commit id or `null`, and `result` is `pending`, `green`, `red`, or `unavailable`. A background request carries an opaque `request` identity; an older completion cannot overwrite a newly edited or cleared check.
An item's HTTP detail, and each item in the full board state, include `check` and, when recorded, `checkBaseline` with the same observation fields. A green result carries `warning: "CRITERION_PROVES_NOTHING"`; text output names that warning when showing or reserving the item for review, and when filing it with `--wait`. An exact match with the project gate configured at that main commit records green with `reason: "repo gate"` without running it again. A missing main records unavailable with `reason: "no main"` and still files the item. Changing the check replaces this observation; clearing it removes the observation. Captured observations and completions travel through ordered board moves, so replicas store results without executing commands. A completed result awaiting relay delivery stays on the measuring device and is retried by the next normal CLI command.
diff --git a/src/cli.js b/src/cli.js
index 5d7e9300..d7916cd8 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -78,7 +78,7 @@ import { flowLines, flowAlertLine } from './stats-flow.js';
import { releaseHeadlinesBetween } from './changelog.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
-import { browserFreeChecksEnabled, loadMachineSettings, setBrowserSlots, setGateSlots } from './settings.js';
+import { browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, setBrowserSlots, setGateSlots } from './settings.js';
import { formatSnapshotLimit, pendingSnapshotSize, pendingCheckpointProblem, relayCommandReceipt, relayCommandReceiptReported, relayLinked, relayOff, relayOn, relayOperation, relayRecover, relayRecovered, relayRevoke, relayStatus, relayTokens, syncRelay } from './relay.js';
import { autoLinkProject, relayOnAll, revokeRelayDevice, unlinkedRelayProjects } from './relay-setup.js';
import { readRelayMachine } from './relay-machine.js';
@@ -1817,8 +1817,10 @@ function readCommands(io, { first, second, rest, values }) {
...listResources({ scope: 'machine' }).map((resource) => ({ ...resource, scope: 'machine' })),
...listResources({ scope: 'repo', root: ctx.info.root }).map((resource) => ({ ...resource, scope: 'repo' })),
];
- io.result?.({ resources, browserSlots });
+ const queue = gateQueueSettings();
+ io.result?.({ resources, browserSlots, queue });
io.say(`browserSlots (machine setting): ${browserSlots}`);
+ io.say(`machine queue order (gate.queue.reviewsFirst ${queue.reviewsFirst}): ${queue.reviewsFirst ? `landing, review, submit, other; a waiting run moves up one class every ${queue.agingMinutes} minutes` : 'landings first, then arrival'}`);
if (!resources.length) io.say('no resources have been used');
for (const resource of resources) {
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' : ''}`);
@@ -2852,9 +2854,13 @@ function gateWaitReporter(io) {
function settingsCommand(io, { first, second, rest }) {
if (!first && !second && !rest.length) {
const settings = loadMachineSettings();
- io.result?.({ settings });
+ const queue = gateQueueSettings();
+ // The result names the queue order in effect, defaults included; the file keeps only what was set.
+ io.result?.({ settings: { ...settings, gate: { ...settings.gate, queue: { ...settings.gate?.queue, ...queue } } } });
io.say(`gateSlots: ${settings.gateSlots}`);
io.say(`browserSlots: ${settings.browserSlots}`);
+ io.say(`gate.queue.reviewsFirst: ${queue.reviewsFirst}${queue.reviewsFirst ? '' : ' (landings first, then arrival order)'}`);
+ io.say(`gate.queue.agingMinutes: ${queue.agingMinutes}${queue.reviewsFirst ? '' : ' (used only while reviewsFirst is true)'}`);
return 0;
}
if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {
diff --git a/src/help.js b/src/help.js
index d2485849..4e2fbe0e 100644
--- a/src/help.js
+++ b/src/help.js
@@ -21,6 +21,7 @@ Set up
pullboard resources local resource holders and their FIFO queues
pullboard settings [gateSlots <n> | browserSlots <n>] view or set machine capacity (gate default 2; browser default 1)
browser-free check slots are opt-in: gate.browserFreeChecks in ~/.pullboard/settings.json (default false)
+ reviews-first queue order is opt-in: gate.queue.reviewsFirst (default false), gate.queue.agingMinutes (default 30)
pullboard view [--project] [--port N] [--no-open] every project on this machine in your browser; default http://127.0.0.1:${DEFAULT_VIEW_PORT}
items, shouts, doctrine, agents and activity; --port 0 chooses a free port
--project limits this view to the registered project for this repository
diff --git a/src/resources.js b/src/resources.js
index 337a5139..b2fdb2be 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -1,4 +1,4 @@
-/** Machine and repository queues persist leases; waiters are admitted by class (landing, review, submit, other), aging up over time, then in arrival order [Q1,Q2,Q3]. */
+/** Machine and repository queues persist leases; landings first, then arrival order, or by class (landing, review, submit, other) aging up over time where the machine opts in [Q1,Q2,Q3]. */
import { mkdirSync, realpathSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { basename, dirname, join, resolve } from 'node:path';
@@ -7,6 +7,7 @@ import { DatabaseSync } from 'node:sqlite';
import { repoInfo } from './git.js';
import { machineHome } from './machine-home.js';
import { Refused } from './refused.js';
+import { gateQueueSettings } from './settings.js';
const LEASE_MS = 20_000;
const HEARTBEAT_MS = 3_000;
@@ -177,47 +178,66 @@ function update(db, action) {
/** 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. */
+/** By default 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;
+/** Landings first, then arrival: the order every pool keeps unless the machine opts in to reviews first. */
+const ARRIVAL_ORDER = Object.freeze({ reviewsFirst: false, ageMs: QUEUE_AGE_MS });
+
+/**
+ * The admission order a pool uses now. Only the machine pool follows the machine settings
+ * (gate.queue.reviewsFirst and gate.queue.agingMinutes); it is read on every poll so each process
+ * sharing the pool ranks the line the same way, even right after the setting changes.
+ *
+ * @param {'machine'|'repo'|'board'} scope
+ * @returns {{ reviewsFirst: boolean, ageMs: number }}
+ */
+function queueOrder(scope) {
+ if (scope !== 'machine') return ARRIVAL_ORDER;
+ const { reviewsFirst, agingMinutes } = gateQueueSettings();
+ return { reviewsFirst, ageMs: agingMinutes * 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
+ * after aging up one class per ageMs waited (QUEUE_AGE_MS unless the machine sets agingMinutes). 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.
+ * @param {number} [ageMs] - How long a waiter waits before it moves up one class.
* @returns {{ base: number, effective: number, name: string, declared: string }}
*/
-export function queueClass(entry, now = Date.now()) {
+export function queueClass(entry, now = Date.now(), ageMs = QUEUE_AGE_MS) {
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));
+ const effective = Math.max(0, base - Math.floor(waited / ageMs));
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
+ * while the machine opts in to reviews first and every waiter was queued by a process that admits
+ * by class; otherwise landings come first and then arrival. 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
+ * @param {{ reviewsFirst: boolean, ageMs: number }} order - The pool's admission order setting.
* @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);
+function admissionRank(waiters, now, order) {
+ const byClass = order.reviewsFirst && waiters.every((waiter) => waiter.classed === 1);
+ return byClass ? (waiter) => queueClass(waiter, now, order.ageMs).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()) {
+/** Current holders and the waiting line in admission order, each waiter naming its class (aged only while class order is on). */
+function snapshot(db, name, order = ARRIVAL_ORDER, 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,
itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),
@@ -227,19 +247,20 @@ function snapshot(db, name, now = Date.now()) {
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 queued = db.prepare('SELECT classed FROM waiter WHERE name = ?').all(sourceName);
- const rank = admissionRank(queued, now);
+ const rank = admissionRank(queued, now, order);
+ const ageMs = order.reviewsFirst ? order.ageMs : Infinity;
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)
.sort((left, right) => rank(left) - rank(right) || left.ticket - right.ticket)
.map(({ ticket, classed, ...entry }) => {
- const current = queueClass(entry, now);
+ const current = queueClass(entry, now, ageMs);
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' } : {}) };
+ // With reviews first on, an older pullboard in the line means everyone admits in arrival order until it leaves.
+ return { holders, line, ...(order.reviewsFirst && queued.some((waiter) => waiter.classed !== 1) ? { order: 'arrival' } : {}) };
}
/** Count reported or admissible queue position separately so blocked work cannot distort the visible line. */
-function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now() } = {}) {
+function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now(), order = ARRIVAL_ORDER } = {}) {
const queueName = name === 'browser' ? 'gate' : name;
const waiters = db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, kind, classed FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);
const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(queueName);
@@ -251,7 +272,7 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now
const blockedByLanding = (waiter) => holdsSlot(waiter)
&& waiters.some((other) => other.landing === 1 && other.pid !== waiter.pid);
/** Map queue entries to the admission rank every process in this line agrees on. */
- const rank = admissionRank(waiters, now);
+ const rank = admissionRank(waiters, now, order);
const line = name === 'browser' ? waiters.filter((waiter) => waiter.browser === 1) : waiters;
const considered = line.filter((waiter) => !blockedByLanding(waiter)
// Browser availability affects admission only; reported positions retain every browser waiter.
@@ -332,19 +353,20 @@ export async function takeResource(options) {
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);
});
while (true) {
+ const order = queueOrder(scope);
const acquired = update(db, () => {
const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);
if (!waiter) {
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 } };
+ return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, Number(rejoined.lastInsertRowid), { order }), rejoined: true } };
}
db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);
- const spot = snapshot(db, name);
- const reportPosition = waiterPosition(db, name, waiter.ticket);
- const admissionPosition = waiterPosition(db, name, waiter.ticket, { eligibleOnly: true });
+ const spot = snapshot(db, name, order);
+ const reportPosition = waiterPosition(db, name, waiter.ticket, { order });
+ const admissionPosition = waiterPosition(db, name, waiter.ticket, { eligibleOnly: true, order });
const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;
- const browserAdmissionPosition = browser ? waiterPosition(db, 'browser', waiter.ticket, { eligibleOnly: true }) : 0;
+ const browserAdmissionPosition = browser ? waiterPosition(db, 'browser', waiter.ticket, { eligibleOnly: true, order }) : 0;
const browserHolders = browser ? db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count : 0;
const browserLimit = browser ? db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get().capacity : 0;
if (admissionPosition === 1 && spot.holders.length < limit && (!browser || (browserAdmissionPosition === 1 && browserHolders < browserLimit))) {
@@ -442,8 +464,9 @@ export function setResourceCapacity({ name, capacity, scope = 'machine', root =
/** List resources and prune leases whose process died or lease expired. */
export function listResources({ scope = 'machine', root = process.cwd() } = {}) {
+ const order = queueOrder(scope);
const db = open(databaseFile(scope, root));
try {
- return update(db, () => db.prepare('SELECT name, capacity FROM resource ORDER BY name').all().map(({ name, capacity }) => ({ name, capacity, ...snapshot(db, name) })));
+ return update(db, () => db.prepare('SELECT name, capacity FROM resource ORDER BY name').all().map(({ name, capacity }) => ({ name, capacity, ...snapshot(db, name, order) })));
} finally { db.close(); }
}
diff --git a/src/settings.js b/src/settings.js
index 5c3f3542..9948416c 100644
--- a/src/settings.js
+++ b/src/settings.js
@@ -8,6 +8,7 @@ import { Refused } from './refused.js';
const DEFAULT_GATE_SLOTS = 2;
const DEFAULT_BROWSER_SLOTS = 1;
+const DEFAULT_QUEUE_AGING_MINUTES = 30;
/** Resolve the separate machine settings file. */
export function machineSettingsFile() {
@@ -30,6 +31,16 @@ export function loadMachineSettings() {
if (value.gate?.browserFreeChecks !== undefined && typeof value.gate.browserFreeChecks !== 'boolean') {
throw new Refused('BAD_MACHINE_SETTINGS', `gate.browserFreeChecks in ${file} must be true or false`);
}
+ const queue = value.gate?.queue;
+ if (queue !== undefined && (!queue || typeof queue !== 'object' || Array.isArray(queue))) {
+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue in ${file} must be an object; fix it before running Pullboard`);
+ }
+ if (queue?.reviewsFirst !== undefined && typeof queue.reviewsFirst !== 'boolean') {
+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue.reviewsFirst in ${file} must be true or false`);
+ }
+ if (queue?.agingMinutes !== undefined && (!Number.isSafeInteger(queue.agingMinutes) || queue.agingMinutes < 1)) {
+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue.agingMinutes in ${file} must be a positive whole number of minutes; fix it or remove it for the default ${DEFAULT_QUEUE_AGING_MINUTES}`);
+ }
const gateSlots = value.gateSlots ?? DEFAULT_GATE_SLOTS;
if (!Number.isSafeInteger(gateSlots) || gateSlots < 1) {
throw new Refused('BAD_GATE_SLOTS', `gateSlots in ${file} must be a positive integer; run pullboard settings gateSlots <n>`);
@@ -46,6 +57,18 @@ export function browserFreeChecksEnabled() {
return loadMachineSettings().gate?.browserFreeChecks === true;
}
+/**
+ * The gate pool's admission order. Reviews-first class order is opt-in per machine because it
+ * changes who waits for whom on every board sharing the pool; absent or false keeps landings
+ * first, then arrival. agingMinutes only matters while class order is on.
+ *
+ * @returns {{ reviewsFirst: boolean, agingMinutes: number }}
+ */
+export function gateQueueSettings() {
+ const queue = loadMachineSettings().gate?.queue;
+ return { reviewsFirst: queue?.reviewsFirst === true, agingMinutes: queue?.agingMinutes ?? DEFAULT_QUEUE_AGING_MINUTES };
+}
+
/** Atomically replace machine settings without exposing a partial JSON file. */
function writeMachineSettings(settings) {
const file = machineSettingsFile();
diff --git a/test/resources.test.js b/test/resources.test.js
index 410f6fbb..6c869478 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -291,6 +291,14 @@ function setBrowserFreeChecks(box, value) {
writeFileSync(file, `${JSON.stringify({ gate: { browserFreeChecks: value } }, null, 2)}\n`);
}
+/** Write a fixture's machine queue-order settings (gate.queue); undefined removes the settings file. */
+function setQueueOrder(box, queue) {
+ const file = join(box.home, 'settings.json');
+ if (queue === undefined) { rmSync(file, { force: true }); return; }
+ mkdirSync(box.home, { recursive: true });
+ writeFileSync(file, `${JSON.stringify({ gate: { queue } }, null, 2)}\n`);
+}
+
/** Read the next worker event, failing promptly with its stderr if it exits unexpectedly. */
async function event(child, timeoutMs = 10_000) {
if (child.pendingLines.length) return JSON.parse(child.pendingLines.shift());
@@ -649,8 +657,7 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
const diagnosticOne = poolWorker(orderBox, { agent: 'diagnostic-one', kind: 'diagnostic' });
assert.equal((await event(diagnosticOne)).queued.position, 2);
const laterReview = poolWorker(orderBox, { agent: 'later-review', item: '621', kind: 'review' });
- // #651: a review joins ahead of the older focused and diagnostic runs, in its own class.
- assert.equal((await event(laterReview)).queued.position, 1);
+ assert.equal((await event(laterReview)).queued.position, 3);
const diagnosticTwo = poolWorker(orderBox, { agent: 'diagnostic-two', kind: 'diagnostic' });
assert.equal((await event(diagnosticTwo)).queued.position, 4);
const laterGate = poolWorker(orderBox, { agent: 'later-gate', kind: 'focused' });
@@ -661,12 +668,12 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
assert.deepEqual(orderedGate.line.map(({ agent, landing, diagnostic, itemCheck, kind }) =>
[agent, landing, diagnostic === true, itemCheck, kind ?? '']), [
['later-landing', true, false, false, ''],
- ['later-review', false, false, true, 'review'],
['later-focused', false, false, false, 'focused'],
['diagnostic-one', false, true, false, 'diagnostic'],
+ ['later-review', false, false, true, 'review'],
['diagnostic-two', false, true, false, 'diagnostic'],
['later-gate', false, false, false, 'focused'],
- ], 'landing, then the review, then focused and diagnostic runs in their arrival order (#651)');
+ ], 'landing moves ahead while all other kinds retain their arrival order');
await release(otherHolder);
assert.equal((await acquired(laterLanding)).acquired, 'later-landing',
@@ -675,16 +682,16 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
assert.ok(orderedGate.holders.some(({ agent, landing }) => agent === 'later-landing' && landing));
await release(laterLanding);
- assert.equal((await acquired(laterReview)).acquired, 'later-review',
- 'a later review is admitted ahead of older focused and diagnostic runs (#651)');
- await release(laterReview);
assert.equal((await acquired(laterFocused)).acquired, 'later-focused',
- 'the oldest focused or diagnostic waiter acquires after the review');
+ 'the oldest eligible non-landing waiter acquires next');
await release(laterFocused);
assert.equal((await acquired(diagnosticOne)).acquired, 'diagnostic-one');
await release(diagnosticOne);
+ assert.equal((await acquired(laterReview)).acquired, 'later-review',
+ 'a diagnostic does not yield its older ticket to a later item check');
+ await release(laterReview);
assert.equal((await acquired(diagnosticTwo)).acquired, 'diagnostic-two',
- 'diagnostics keep their FIFO place among focused runs');
+ 'diagnostics keep their FIFO place around a later item check');
await release(diagnosticTwo);
assert.equal((await acquired(laterGate)).acquired, 'later-gate',
'a diagnostic does not yield its older ticket to later ordinary gate work');
@@ -746,6 +753,7 @@ test('the pool alone orders submits, reviews and browser runs [C7]', async () =>
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();
+ setQueueOrder(box, { reviewsFirst: true }); // #697: class order is a machine opt-in.
const holders = [poolWorker(box, { agent: 'holder-one' }), poolWorker(box, { agent: 'holder-two' })];
for (const holder of holders) await acquired(holder);
const waiting = new Map();
@@ -819,6 +827,7 @@ test('the pool admits reviews before submits before focused runs, and waiting ru
test('a line holding an older pullboard waiter keeps arrival order, so mixed versions never deadlock [C7]', async () => {
const box = fixture();
+ setQueueOrder(box, { reviewsFirst: true }); // #697: class order is a machine opt-in.
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' });
@@ -842,6 +851,107 @@ test('a line holding an older pullboard waiter keeps arrival order, so mixed ver
await release(review);
});
+test('queue order follows the machine settings [C7,O5]', async () => {
+ const gate = (box) => privateList(box).find(({ name }) => name === 'gate');
+ const line = (box) => gate(box).line.map(({ agent, queueClass: listed, agedFrom }) => [agent, listed, agedFrom ?? '']);
+ /** Backdate a waiter's queued time: the test clock that stands in for real waiting. */
+ const backdate = (box, agent, ms) => {
+ const queuedAt = new Date(Date.now() - ms).toISOString();
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ let changed;
+ try { changed = db.prepare('UPDATE waiter SET since = ? WHERE agent = ?').run(queuedAt, agent).changes; }
+ finally { db.close(); }
+ assert.equal(changed, 1, `${agent} has a private waiter row`);
+ };
+ /** Run pullboard settings against the fixture's private machine home. */
+ const settingsCli = (box, ...flags) => runFixtureChild(process.execPath, [BIN, 'settings', ...flags], { cwd: box.first, env: box.env, encoding: 'utf8' });
+
+ // No settings: landings first, then arrival, so a review waits behind an earlier focused run.
+ const plain = fixture();
+ const plainHolders = [poolWorker(plain, { agent: 'plain-holder-one' }), poolWorker(plain, { agent: 'plain-holder-two' })];
+ for (const holder of plainHolders) await acquired(holder);
+ const plainFocused = poolWorker(plain, { agent: 'plain-focused', kind: 'focused' });
+ assert.equal((await event(plainFocused)).queued.position, 1);
+ const plainReview = poolWorker(plain, { agent: 'plain-review', kind: 'review', item: '697' });
+ assert.equal((await event(plainReview)).queued.position, 2, 'with no settings a review waits its arrival turn');
+ assert.deepEqual(gate(plain).line.map(({ agent }) => agent), ['plain-focused', 'plain-review'], 'with no settings the line is in arrival order');
+ // agingMinutes alone does nothing: aging is used only while a class order is on.
+ setQueueOrder(plain, { agingMinutes: 1 });
+ backdate(plain, 'plain-review', 5 * 60_000);
+ assert.deepEqual(line(plain), [['plain-focused', 'other', ''], ['plain-review', 'review', '']],
+ 'with reviewsFirst off no waiter ages up, even with a short agingMinutes');
+ setQueueOrder(plain, undefined);
+ const plainPrinted = settingsCli(plain);
+ assert.equal(plainPrinted.status, 0, plainPrinted.stderr);
+ assert.match(plainPrinted.stdout, /^gate\.queue\.reviewsFirst: false\b/mu, 'pullboard settings prints reviewsFirst, default false');
+ assert.match(plainPrinted.stdout, /^gate\.queue\.agingMinutes: 30\b/mu, 'pullboard settings prints agingMinutes, default 30');
+ await release(plainHolders[0]);
+ assert.equal((await acquired(plainFocused)).acquired, 'plain-focused', 'with no settings the earlier focused run is admitted first');
+ await release(plainHolders[1]);
+ assert.equal((await acquired(plainReview)).acquired, 'plain-review');
+ await release(plainFocused);
+ await release(plainReview);
+
+ // reviewsFirst true: the same review is admitted ahead of the earlier focused run.
+ const classed = fixture();
+ setQueueOrder(classed, { reviewsFirst: true });
+ const classedHolders = [poolWorker(classed, { agent: 'classed-holder-one' }), poolWorker(classed, { agent: 'classed-holder-two' })];
+ for (const holder of classedHolders) await acquired(holder);
+ const classedFocused = poolWorker(classed, { agent: 'classed-focused', kind: 'focused' });
+ assert.equal((await event(classedFocused)).queued.position, 1);
+ const classedReview = poolWorker(classed, { agent: 'classed-review', kind: 'review', item: '697' });
+ assert.equal((await event(classedReview)).queued.position, 1, 'with reviewsFirst true a review joins ahead of focused runs');
+ assert.deepEqual(gate(classed).line.map(({ agent }) => agent), ['classed-review', 'classed-focused'], 'with reviewsFirst true the line is in class order');
+ await release(classedHolders[0]);
+ assert.equal((await acquired(classedReview)).acquired, 'classed-review', 'with reviewsFirst true the review is admitted first');
+ await release(classedHolders[1]);
+ assert.equal((await acquired(classedFocused)).acquired, 'classed-focused');
+ await release(classedReview);
+ await release(classedFocused);
+
+ // agingMinutes 1: a focused run waiting just over a minute moves up one class, ahead of a later submit.
+ const aging = fixture();
+ setQueueOrder(aging, { reviewsFirst: true, agingMinutes: 1 });
+ const agingHolders = [poolWorker(aging, { agent: 'aging-holder-one' }), poolWorker(aging, { agent: 'aging-holder-two' })];
+ for (const holder of agingHolders) await acquired(holder);
+ const agingFocused = poolWorker(aging, { agent: 'aging-focused', kind: 'focused' });
+ await event(agingFocused);
+ const agingSubmit = poolWorker(aging, { agent: 'aging-submit', kind: 'submit', item: '697' });
+ assert.equal((await event(agingSubmit)).queued.position, 1, 'a fresh submit goes ahead of a fresh focused run');
+ assert.deepEqual(line(aging), [['aging-submit', 'submit', ''], ['aging-focused', 'other', '']]);
+ backdate(aging, 'aging-focused', 61_000);
+ assert.deepEqual(line(aging), [['aging-focused', 'submit', 'other'], ['aging-submit', 'submit', '']],
+ 'after agingMinutes 1 the focused run ranks with submits and keeps its earlier ticket there');
+ const agingPrinted = settingsCli(aging);
+ assert.equal(agingPrinted.status, 0, agingPrinted.stderr);
+ assert.match(agingPrinted.stdout, /^gate\.queue\.reviewsFirst: true$/mu, 'pullboard settings prints the reviewsFirst set on this machine');
+ assert.match(agingPrinted.stdout, /^gate\.queue\.agingMinutes: 1$/mu, 'pullboard settings prints the agingMinutes set on this machine');
+ assert.deepEqual(JSON.parse(settingsCli(aging, '--json').stdout).settings.gate.queue, { reviewsFirst: true, agingMinutes: 1 });
+ await release(agingHolders[0]);
+ assert.equal((await acquired(agingFocused)).acquired, 'aging-focused', 'the aged focused run is admitted before the later submit');
+ await release(agingHolders[1]);
+ assert.equal((await acquired(agingSubmit)).acquired, 'aging-submit');
+ await release(agingFocused);
+ await release(agingSubmit);
+ // The class rule against an injected clock: one class per agingMinutes waited.
+ const { queueClass } = await import('../src/resources.js');
+ const queuedAt = Date.parse('2026-10-16T16:00:00.000Z');
+ const since = new Date(queuedAt).toISOString();
+ assert.deepEqual([0, 0.99, 1, 2, 3].map((minutes) => queueClass({ kind: 'focused', since }, queuedAt + minutes * 60_000, 60_000).name),
+ ['other', 'other', 'submit', 'review', 'landing'], 'a one-minute aging moves a waiting run up one class per minute');
+
+ // An unusable value is refused by name, with the fix.
+ setQueueOrder(aging, { reviewsFirst: 'yes' });
+ const badFlag = settingsCli(aging, '--json');
+ assert.equal(badFlag.status, 1);
+ assert.equal(JSON.parse(badFlag.stdout).error.code, 'BAD_MACHINE_SETTINGS');
+ assert.match(JSON.parse(badFlag.stdout).error.message, /gate\.queue\.reviewsFirst .* must be true or false/u);
+ setQueueOrder(aging, { reviewsFirst: true, agingMinutes: 0 });
+ const badAging = settingsCli(aging, '--json');
+ assert.equal(badAging.status, 1);
+ assert.match(JSON.parse(badAging.stdout).error.message, /gate\.queue\.agingMinutes .* must be a positive whole number/u);
+});
+
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' });