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(queue): prefer current release within each board [C7,V4]

Corey Olsona29fb0aea297
diff --git a/docs/api.md b/docs/api.md
index 75ddc138..0f8a927b 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -14,6 +14,8 @@ Browser-free check admission is opt-in per machine with `"gate": { "browserFreeC
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.
+Release priority is separately opt-in with `"gate": { "queue": { "currentReleaseFirst": true } }`. Before queueing, a gate run captures its board identity and its item's roadmap rank. The first unfinished milestone is current, counting only this board's own items as verified out of total; `repo#id` references are left out and never opened. Later milestones follow in roadmap order, then already completed earlier milestones, then unplanned work. Within otherwise-tied positions belonging to one board, current-release work goes first: `A-later, B, A-current` becomes `A-current, B, A-later`. Different boards retain their opportunity positions. Global admission classes and landings retain their existing precedence, and a waiter older than `agingMinutes` keeps its position against release reordering. Queued ranks do not change if the roadmap changes. With the setting off, no board is read for release priority. Unknown board identities keep their positions; while any older client is waiting, all clients fall back together to landings then arrival. `pullboard settings` prints `gate.queue.currentReleaseFirst`, default `false`.
+
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 7c289e1f..094d1a1a 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -3178,6 +3178,7 @@ function settingsCommand(io, { first, second, rest }) {
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.currentReleaseFirst: ${queue.currentReleaseFirst}${queue.currentReleaseFirst ? '' : ' (release priority is off)'}`);
io.say(`gate.queue.agingMinutes: ${queue.agingMinutes}${queue.reviewsFirst ? '' : ' (used only while reviewsFirst is true)'}`);
return 0;
}
diff --git a/src/gate.js b/src/gate.js
index 6b0a99e3..eaf7a672 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -14,7 +14,7 @@ import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked
import { secretsIn } from './hooks.js';
import { Refused } from './refused.js';
import { GATE_SLOT_HELD_ENV, gateSlotEnvironment, inheritedGateSlot, takeResource } from './resources.js';
-import { browserFreeChecksEnabled, loadMachineSettings } from './settings.js';
+import { browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings } from './settings.js';
import { selectAffectedTests } from './affected-tests.js';
import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';
import { timingFromOutput, timingRunner } from './timing.js';
@@ -511,6 +511,9 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =
const settingsProvider = () => loadMachineSettings();
const capacityProvider = () => settingsProvider().gateSlots;
const source = runnerSource(root);
+ // Read the board once before queueing, never inside the machine admission transaction.
+ const releaseContext = gateQueueSettings().currentReleaseFirst
+ ? (await import('./release-queue.js')).captureReleaseQueue(root, item) : undefined;
let lease = await takeResource({
name: 'gate',
capacity: capacityProvider(),
@@ -529,6 +532,7 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =
allowIdleCapacityUpdate: true,
remote: remote && Boolean(source),
runnerProvider: () => loadMachineSettings().runners ?? [],
+ releaseContext,
onWait,
});
try {
diff --git a/src/help.js b/src/help.js
index a1185b07..d6d3d936 100644
--- a/src/help.js
+++ b/src/help.js
@@ -24,6 +24,7 @@ Set up
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)
+ release priority is opt-in: gate.queue.currentReleaseFirst (default false), within each board's otherwise-tied positions
pullboard runner add <ssh-host> --slots <n> --browser <n> [--node <remote-path>] [--root <remote-path>]
register SSH test capacity; no runner sign-in; root defaults to ~/.pullboard-runner
pullboard view [--project] [--port N] [--no-open] every project on this machine in your browser; default http://127.0.0.1:${DEFAULT_VIEW_PORT}
diff --git a/src/queue-order.js b/src/queue-order.js
new file mode 100644
index 00000000..2f216976
--- /dev/null
+++ b/src/queue-order.js
@@ -0,0 +1,113 @@
+/** Pure ordering shared by every machine gate client, including shipped runner runtimes [C7,V4]. */
+/** Admission classes, most urgent first. */
+export const QUEUE_CLASSES = ['landing', 'review', 'submit', 'other'];
+/** 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. */
+export const ARRIVAL_ORDER = Object.freeze({ reviewsFirst: false, ageMs: QUEUE_AGE_MS });
+
+/**
+ * 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 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(), 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 / ageMs));
+ return { base, effective, name: QUEUE_CLASSES[effective], declared: QUEUE_CLASSES[base] };
+}
+
+/**
+ * Whether a line admits by class: only while the machine opts in to reviews first and every
+ * waiter in it was queued by a process that admits by class (see admissionRank for why).
+ *
+ * @param {Array<{ classed?: number }>} waiters - The whole line for one resource.
+ * @param {{ reviewsFirst: boolean }} order - The pool's admission order setting.
+ * @returns {boolean}
+ */
+export function classOrderInEffect(waiters, order) {
+ return order.reviewsFirst && (releaseOrderInEffect(waiters, order) || waiters.every((waiter) => waiter.classed === 1));
+}
+
+/**
+ * The compatibility marker understood by class-only clients. Release-aware clients write 0
+ * while release ordering is enabled: older clients must fall back to arrival until they leave.
+ * New clients may then use class and release order together only when all waiters are aware.
+ * Why not always 1: a #651-only process reads classed=1 on every waiter as "everyone admits by
+ * class" and ranks by class, while a process with reviewsFirst off ranks by arrival; the two would
+ * disagree and a free slot could stay empty. Writing 0 with the setting off makes every process,
+ * old or new, fall back to arrival order together.
+ *
+ * @param {{ reviewsFirst: boolean, currentReleaseFirst?: boolean }} order - This poll's settings.
+ * @returns {0|1}
+ */
+export function classedMarker(order) {
+ return order.reviewsFirst && !order.currentReleaseFirst ? 1 : 0;
+}
+
+/**
+ * The admission rank every process in this queue agrees on. Class order (with aging) applies only
+ * 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, order) {
+ return classOrderInEffect(waiters, order) ? (waiter) => queueClass(waiter, now, order.ageMs).effective : (waiter) => (waiter.landing === 1 ? 0 : 1);
+}
+
+/** All waiters must understand release ordering, or old and new clients use arrival together. */
+export function releaseOrderInEffect(waiters, order) {
+ return order.currentReleaseFirst && waiters.every((waiter) => waiter.release_aware === 1);
+}
+
+/**
+ * One admission order for display, reported position and local/remote execution. Begin with the
+ * existing class/arrival order, then exchange only otherwise-tied positions belonging to one
+ * board. Aged entries keep their positions, so continuing current-release arrivals cannot
+ * displace them. Unknown board identities keep their original positions too.
+ *
+ * @param {object[]} waiters - The complete resource line, before capability filtering.
+ * @param {number} now - One clock reading for the whole order.
+ * @param {{ reviewsFirst: boolean, currentReleaseFirst?: boolean, ageMs: number }} order
+ * @returns {object[]}
+ */
+export function orderedWaiters(waiters, now, order) {
+ const rank = admissionRank(waiters, now, order);
+ const releaseOrder = releaseOrderInEffect(waiters, order);
+ /** Opportunity positions are consumed separately from immutable waiter identity tickets. */
+ const opportunity = waiter => releaseOrder ? waiter.queue_ticket ?? waiter.ticket : waiter.ticket;
+ const line = [...waiters].sort((left, right) => rank(left) - rank(right) || opportunity(left) - opportunity(right) || left.ticket - right.ticket);
+ if (!releaseOrder) return line;
+ const positions = new Map();
+ line.forEach((waiter, index) => {
+ const waited = Math.max(0, now - (Date.parse(waiter.since ?? '') || now));
+ if (!waiter.board_key || waited >= order.ageMs) return;
+ const key = JSON.stringify([waiter.board_key, rank(waiter)]);
+ const group = positions.get(key) ?? [];
+ group.push(index);
+ positions.set(key, group);
+ });
+ for (const group of positions.values()) {
+ const tickets = group.map(index => opportunity(line[index]));
+ const entries = group.map(index => line[index]).sort((left, right) => left.release_rank - right.release_rank || opportunity(left) - opportunity(right) || left.ticket - right.ticket);
+ group.forEach((index, at) => { line[index] = { ...entries[at], queue_ticket: tickets[at] }; });
+ }
+ return line;
+}
diff --git a/src/queue-settings.js b/src/queue-settings.js
index 17bc7a96..2e803c00 100644
--- a/src/queue-settings.js
+++ b/src/queue-settings.js
@@ -48,6 +48,9 @@ export function validateGateQueue(value, file) {
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?.currentReleaseFirst !== undefined && typeof queue.currentReleaseFirst !== 'boolean') {
+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.queue.currentReleaseFirst 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}`);
}
@@ -58,12 +61,12 @@ export function validateGateQueue(value, file) {
* 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 }}
+ * @returns {{ reviewsFirst: boolean, currentReleaseFirst: boolean, agingMinutes: number }}
*/
export function gateQueueSettings() {
const file = machineSettingsFile();
const value = readMachineSettingsFile(file) ?? {};
validateGateQueue(value, file);
const queue = value.gate?.queue;
- return { reviewsFirst: queue?.reviewsFirst === true, agingMinutes: queue?.agingMinutes ?? DEFAULT_QUEUE_AGING_MINUTES };
+ return { reviewsFirst: queue?.reviewsFirst === true, currentReleaseFirst: queue?.currentReleaseFirst === true, agingMinutes: queue?.agingMinutes ?? DEFAULT_QUEUE_AGING_MINUTES };
}
diff --git a/src/release-queue.js b/src/release-queue.js
new file mode 100644
index 00000000..1afc9cf5
--- /dev/null
+++ b/src/release-queue.js
@@ -0,0 +1,45 @@
+/** Capture one board's release priority before joining the machine resource transaction [C7,V4]. */
+import { existsSync } from 'node:fs';
+import { join } from 'node:path';
+import { boardId, openBoardReadOnly, roadmap } from './board.js';
+import { repoInfo } from './git.js';
+
+/**
+ * Capture the item's roadmap rank once, without opening or migrating a board for writing.
+ * The first unfinished local milestone is current; later milestones follow, then completed earlier
+ * milestones, then unplanned work. External references are neither counted nor opened. Board identity joins worktrees and local relay replicas of
+ * the same board. A checkout with no board has no release identity and keeps its queue position.
+ * Why outside resources.js: remote workers ship only its small trusted runtime, not the board.
+ *
+ * @param {string} root - The gate caller's checkout.
+ * @param {string|number} item - The local item id, or empty for an unplanned run.
+ * @returns {{ board: string, rank: number }|undefined}
+ */
+export function captureReleaseQueue(root, item) {
+ let info;
+ try { info = repoInfo(root); } catch { return undefined; }
+ const file = join(info.commonDir, 'pullboard', 'board.sqlite');
+ if (!existsSync(file)) return undefined;
+ const db = openBoardReadOnly(file);
+ try {
+ const board = { db, clock: { now: () => new Date() } };
+ return { board: boardId(board), rank: localReleaseRank(roadmap(board), item) };
+ } finally { db.close(); }
+}
+
+/**
+ * Rank local work using the board's own verified-item completion. A repo-qualified reference
+ * cannot pin this board to an old milestone: its state belongs to another board and is not read.
+ *
+ * @param {{ items: { id: number|string, status: string }[] }[]} releases - Public roadmap projection.
+ * @param {string|number} item - The local item id.
+ * @returns {number} Current, later, completed earlier, then unplanned.
+ */
+export function localReleaseRank(releases, item) {
+ const local = releases.map(release => release.items.filter(entry => typeof entry.id === 'number'));
+ const first = local.findIndex(items => items.some(entry => entry.status !== 'verified'));
+ const current = first < 0 ? 0 : first;
+ const ranks = local.flatMap((items, index) => items.some(entry => String(entry.id) === String(item))
+ ? [index >= current ? index - current : releases.length + index] : []);
+ return ranks.length ? Math.min(...ranks) : Number.MAX_SAFE_INTEGER;
+}
diff --git a/src/resources.js b/src/resources.js
index dc6c48d0..ca4792b6 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -8,6 +8,8 @@ import { repoInfo } from './git.js';
import { machineHome, withMachineHomeWrite } from './machine-home.js';
import { Refused } from './refused.js';
import { gateQueueSettings } from './queue-settings.js';
+import { ARRIVAL_ORDER, classedMarker, classOrderInEffect, orderedWaiters, queueClass, releaseOrderInEffect } from './queue-order.js';
+export { QUEUE_CLASSES, QUEUE_AGE_MS, queueClass } from './queue-order.js';
const LEASE_MS = 20_000;
const HEARTBEAT_MS = 3_000;
@@ -104,6 +106,11 @@ function openQueue(file) {
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');
}
+ for (const [column, definition] of [['release_aware', 'INTEGER NOT NULL DEFAULT 0'], ['board_key', "TEXT NOT NULL DEFAULT ''"], ['release_rank', 'INTEGER NOT NULL DEFAULT 9007199254740991'], ['queue_ticket', 'INTEGER']]) {
+ if (!db.prepare('PRAGMA table_info(waiter)').all().some(({ name }) => name === column)) {
+ db.exec(`ALTER TABLE waiter ADD COLUMN ${column} ${definition}`);
+ }
+ }
// 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)
@@ -195,89 +202,23 @@ function update(db, action) {
}
}
-/** Admission classes, most urgent first. */
-export const QUEUE_CLASSES = ['landing', 'review', 'submit', 'other'];
-/** 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
+ * (gate.queue.reviewsFirst, currentReleaseFirst and 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 }}
+ * @returns {{ reviewsFirst: boolean, currentReleaseFirst?: 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 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(), 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 / ageMs));
- return { base, effective, name: QUEUE_CLASSES[effective], declared: QUEUE_CLASSES[base] };
+ const { reviewsFirst, currentReleaseFirst, agingMinutes } = gateQueueSettings();
+ return { reviewsFirst, currentReleaseFirst, ageMs: agingMinutes * 60_000 };
}
-/**
- * Whether a line admits by class: only while the machine opts in to reviews first and every
- * waiter in it was queued by a process that admits by class (see admissionRank for why).
- *
- * @param {Array<{ classed?: number }>} waiters - The whole line for one resource.
- * @param {{ reviewsFirst: boolean }} order - The pool's admission order setting.
- * @returns {boolean}
- */
-function classOrderInEffect(waiters, order) {
- return order.reviewsFirst && waiters.every((waiter) => waiter.classed === 1);
-}
-
-/**
- * The classed marker this process writes on its waiter: 1 only while it admits by class order.
- * Why not always 1: a #651-only process reads classed=1 on every waiter as "everyone admits by
- * class" and ranks by class, while a process with reviewsFirst off ranks by arrival; the two would
- * disagree and a free slot could stay empty. Writing 0 with the setting off makes every process,
- * old or new, fall back to arrival order together.
- *
- * @param {{ reviewsFirst: boolean }} order - This process's admission order setting, read this poll.
- * @returns {0|1}
- */
-function classedMarker(order) {
- return order.reviewsFirst ? 1 : 0;
-}
-
-/**
- * The admission rank every process in this queue agrees on. Class order (with aging) applies only
- * 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, order) {
- return classOrderInEffect(waiters, order) ? (waiter) => queueClass(waiter, now, order.ageMs).effective : (waiter) => (waiter.landing === 1 ? 0 : 1);
+/** Read the complete resource line with the metadata every admission view orders identically. */
+function queuedWaiters(db, name) {
+ return db.prepare('SELECT ticket, pid, agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind, classed, release_aware, board_key, release_rank, queue_ticket FROM waiter WHERE name = ?').all(name);
}
/** Current holders and the waiting line in admission order, each waiter naming its class (aged only while class order is on). */
@@ -294,23 +235,22 @@ function snapshot(db, name, order = ARRIVAL_ORDER, now = Date.now()) {
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 queued = db.prepare('SELECT classed FROM waiter WHERE name = ?').all(sourceName);
- const rank = admissionRank(queued, now, order);
+ const queued = queuedWaiters(db, sourceName);
const ageMs = order.reviewsFirst ? order.ageMs : Infinity;
- 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 line = orderedWaiters(queued, now, order)
+ .filter(entry => name !== 'browser' || entry.browser === 1)
+ .map(({ ticket, pid, classed, release_aware, board_key, release_rank, queue_ticket, ...entry }) => {
const current = queueClass(entry, now, ageMs);
return { ...project(entry), queueClass: current.name, ...(current.effective < current.base ? { agedFrom: current.declared } : {}) };
});
// 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' } : {}) };
+ return { holders, line, ...((order.reviewsFirst || order.currentReleaseFirst) && !classOrderInEffect(queued, order) && queued.some((waiter) => waiter.release_aware !== 1 || (!order.currentReleaseFirst && 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(), 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 waiters = orderedWaiters(queuedWaiters(db, queueName), now, order);
const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(queueName);
const browserCapacity = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get()?.capacity ?? 1;
const browserBusy = db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count >= browserCapacity;
@@ -319,8 +259,6 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now
/** Leave a waiting independent landing a slot before a holder takes another lease. */
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, 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.
@@ -329,8 +267,23 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false, now = Date.now
if (!current) return eligibleOnly ? Number.MAX_SAFE_INTEGER : line.length + 1;
const currentIndex = considered.findIndex((waiter) => waiter.ticket === ticket);
if (currentIndex < 0) return eligibleOnly ? Number.MAX_SAFE_INTEGER : Math.max(2, considered.length + 1);
- const currentRank = rank(current);
- return considered.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;
+ return currentIndex + 1;
+}
+
+/**
+ * Consume the selected run's opportunity, not its original identity ticket. Persist every
+ * exchange before deleting that run, or another run from its board could consume the same
+ * early position again and jump a different board. Called inside the admission transaction.
+ */
+function consumeOpportunity(db, name, ticket, order, now) {
+ const queued = queuedWaiters(db, name);
+ if (!releaseOrderInEffect(queued, order)) return ticket;
+ const line = orderedWaiters(queued, now, order);
+ for (const entry of line) {
+ db.prepare('UPDATE waiter SET queue_ticket = ? WHERE ticket = ?').run(entry.queue_ticket ?? entry.ticket, entry.ticket);
+ }
+ const selected = line.find(entry => entry.ticket === ticket);
+ return selected?.queue_ticket ?? ticket;
}
/** Validate the configured remote executors before using them in a queue transaction. */
@@ -369,9 +322,7 @@ function validatedRunners(value) {
* @returns {{host:string,slots:number,browser:number}|null}
*/
function gateAdmission(db, ticket, capacity, runners, order = ARRIVAL_ORDER, 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, order);
- const waiters = queued.sort((left, right) => rank(left) - rank(right) || left.ticket - right.ticket);
+ const waiters = orderedWaiters(queuedWaiters(db, 'gate'), now, order);
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;
@@ -483,6 +434,9 @@ export async function takeResource(options) {
const runnerProvider = options.runnerProvider;
const item = options.item ?? '';
const kind = options.kind ?? '';
+ // withGateSlot supplies a once-captured board rank; raw resource clients may leave it unknown.
+ const boardKey = typeof options.releaseContext?.board === 'string' ? options.releaseContext.board : '';
+ const releaseRank = Number.isSafeInteger(options.releaseContext?.rank) && options.releaseContext.rank >= 0 ? options.releaseContext.rank : Number.MAX_SAFE_INTEGER;
if (browser && name !== 'gate') throw new Refused('BAD_BROWSER_RESOURCE', 'browser capacity can only be acquired together with the machine gate; request name "gate" with browser: true');
if ((remote || runnerProvider !== undefined) && name !== 'gate') throw new Refused('BAD_REMOTE_RESOURCE', 'remote executors can only be acquired together with the machine gate');
if (runnerProvider !== undefined && typeof runnerProvider !== 'function') throw new Refused('BAD_RUNNER_POOL', 'runnerProvider must be a function returning configured runners');
@@ -538,13 +492,14 @@ export async function takeResource(options) {
if (!resume) {
// 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(queueOrder(scope)));
+ const inserted = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, release_aware, board_key, release_rank, queue_ticket) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(queueOrder(scope)), 1, boardKey, releaseRank, resume?.queueTicket ?? null);
initialTicket = Number(inserted.lastInsertRowid);
}
});
while (true) {
const order = queueOrder(scope);
const acquired = update(db, () => {
+ const now = Date.now();
// 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.
@@ -552,28 +507,29 @@ export async function takeResource(options) {
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, classed) 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), classedMarker(order));
+ 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, release_aware, board_key, release_rank, queue_ticket) 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), classedMarker(order), 1, boardKey, releaseRank, resume?.queueTicket ?? null);
return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order }), 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, remote, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(order));
+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, release_aware, board_key, release_rank, queue_ticket) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), classedMarker(order), 1, boardKey, releaseRank, resume?.queueTicket ?? null);
initialTicket = Number(rejoined.lastInsertRowid);
return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order }), rejoined: true } };
}
// The marker follows this poll's setting, so a change mid-wait reaches every process's ranking.
db.prepare('UPDATE waiter SET heartbeat = ?, classed = ? WHERE token = ?').run(Date.now(), classedMarker(order), token);
- const spot = snapshot(db, name, order);
- const reportPosition = waiterPosition(db, name, waiter.ticket, { order });
+ const spot = snapshot(db, name, order, now);
+ const reportPosition = waiterPosition(db, name, waiter.ticket, { order, now });
const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;
const executor = name === 'gate'
- ? gateAdmission(db, waiter.ticket, limit, runners, order)
- : (waiterPosition(db, name, waiter.ticket, { eligibleOnly: true, order }) === 1 && spot.holders.length < limit ? { host: '' } : null);
+ ? gateAdmission(db, waiter.ticket, limit, runners, order, now)
+ : (waiterPosition(db, name, waiter.ticket, { eligibleOnly: true, order, now }) === 1 && spot.holders.length < limit ? { host: '' } : null);
if (executor) {
+ const queueTicket = consumeOpportunity(db, name, waiter.ticket, order, now);
db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
const acquiredAt = new Date().toISOString();
const holderName = executor.host ? runnerResourceName(executor.host) : name;
db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, runner) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, holderName, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, executor.host);
- return { acquired: true, state: { ...spot, position: 0 }, ticket: waiter.ticket, runner: executor.host ? executor : undefined };
+ return { acquired: true, state: { ...spot, position: 0 }, ticket: waiter.ticket, queueTicket, runner: executor.host ? executor : undefined };
}
return { acquired: false, state: { ...spot, position: reportPosition } };
});
@@ -622,6 +578,7 @@ export async function takeResource(options) {
transferred = true;
clearInterval(heartbeat);
let requeueTicket = acquired.ticket;
+ let requeueOpportunity = acquired.queueTicket;
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')
@@ -635,14 +592,18 @@ export async function takeResource(options) {
// ticket ahead of its landing tier, as on main.
const requeueOrder = queueOrder(scope);
const marker = classedMarker(requeueOrder);
- if (classOrderInEffect([...db.prepare("SELECT classed FROM waiter WHERE name = 'gate'").all(), { classed: marker }], requeueOrder)) requeueTicket = acquired.ticket;
+ if (classOrderInEffect([...db.prepare("SELECT classed, release_aware FROM waiter WHERE name = 'gate'").all(), { classed: marker, release_aware: 1 }], requeueOrder)) {
+ requeueTicket = acquired.ticket;
+ requeueOpportunity = acquired.queueTicket;
+ }
else {
const minimumTicket = db.prepare("SELECT MIN(ticket) AS ticket FROM waiter WHERE name = 'gate' AND landing = ?").get(Number(landing)).ticket;
requeueTicket = Math.min(0, minimumTicket ?? 0) - 1;
+ requeueOpportunity = requeueTicket;
}
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, classed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
- .run(requeueTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), marker);
+ db.prepare('INSERT INTO waiter(ticket, token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, remote, classed, release_aware, board_key, release_rank, queue_ticket) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
+ .run(requeueTicket, token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, Number(remote), marker, 1, boardKey, releaseRank, requeueOpportunity);
});
} catch (error) {
transferred = false;
@@ -650,7 +611,7 @@ export async function takeResource(options) {
throw error;
}
db.close();
- return takeResource({ ...options, _resume: { token, ticket: requeueTicket ?? acquired.ticket,
+ return takeResource({ ...options, _resume: { token, ticket: requeueTicket ?? acquired.ticket, queueTicket: requeueOpportunity,
queuedAt, requestedAt, priorWaitMs: acquiredWaitMs, waitStartedAt: Date.now() } });
};
return { name, scope, token, pool, browser, ...(acquired.runner ? { runner: acquired.runner } : {}),
diff --git a/src/runner-worker.js b/src/runner-worker.js
index 43fc5b50..e5d5e3d1 100644
--- a/src/runner-worker.js
+++ b/src/runner-worker.js
@@ -131,7 +131,7 @@ async function readSpec() {
tagNames.add(tag.name);
if (tag.chain.length ? tag.chain[0] !== tag.object : tag.object !== tag.peeledCommit) throw new Error('invalid tag manifest');
}
- const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js'];
+ const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js'];
if (Object.keys(value.runtime.files).length !== runtimeNames.length
|| runtimeNames.some(name => typeof value.runtime.files[name] !== 'string')) throw new Error('invalid work specification');
if (createHash('sha256').update(JSON.stringify(value.runtime.files)).digest('hex') !== value.runtime.sha256) throw new Error('invalid trusted runtime');
diff --git a/src/runners.js b/src/runners.js
index 0b59fe6d..8fd88844 100644
--- a/src/runners.js
+++ b/src/runners.js
@@ -18,7 +18,7 @@ const MAX_BLOB_BYTES = 8 * 1024 ** 2;
const MAX_HISTORY_TAGS = 1_024;
const MAX_TAG_CHAIN = 8;
const TOOL_ROOT = fileURLToPath(new URL('../', import.meta.url));
-const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js'];
+const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js', 'process-census.js', 'queue-settings.js', 'queue-order.js'];
/** Validate an SSH destination as one argument, never a command or an SSH option. */
export function validateRunner(value) {
diff --git a/test/queue-order.test.js b/test/queue-order.test.js
new file mode 100644
index 00000000..80f4f4cb
--- /dev/null
+++ b/test/queue-order.test.js
@@ -0,0 +1,32 @@
+/** Local release completion and deterministic ordering boundaries [C7,V4]. */
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { localReleaseRank } from '../src/release-queue.js';
+import { orderedWaiters } from '../src/queue-order.js';
+
+test('release priority uses only local verified work, leaving external references alone [C7,V4]', () => {
+ const releases = [
+ { items: [{ id: 'elsewhere#1', status: 'unavailable' }, { id: 1, status: 'verified' }] },
+ { items: [{ id: 2, status: 'claimed' }] },
+ { items: [{ id: 3, status: 'open' }] },
+ ];
+ assert.deepEqual([1, 2, 3, 4].sort((a, b) => localReleaseRank(releases, a) - localReleaseRank(releases, b)), [2, 3, 1, 4],
+ 'an unknown external reference cannot make completed local work outrank the current release');
+ const localOnly = releases.map(release => ({ items: release.items.filter(entry => typeof entry.id === 'number') }));
+ assert.deepEqual([1, 2, 3, 4].map(id => localReleaseRank(releases, id)), [1, 2, 3, 4].map(id => localReleaseRank(localOnly, id)));
+});
+
+test('release ordering preserves opportunity positions and already aged arrivals [C7,V4]', () => {
+ const now = Date.UTC(2026, 9, 17, 2);
+ const order = { reviewsFirst: false, currentReleaseFirst: true, ageMs: 60_000 };
+ /** Build one otherwise-tied waiter with a captured board rank and controlled age. */
+ const row = (ticket, board, rank, waited = 0) => ({ ticket, board_key: board, release_rank: rank, release_aware: 1, since: new Date(now - waited).toISOString() });
+ const line = [row(1, 'A', 2), row(2, 'B', 0), row(3, 'A', 0)];
+ const ordered = orderedWaiters(line, now, order);
+ assert.deepEqual(ordered.map(entry => entry.ticket), [3, 2, 1]);
+ assert.deepEqual(ordered.map(entry => entry.queue_ticket ?? entry.ticket), [1, 2, 3]);
+ const remaining = ordered.filter(entry => entry.ticket !== 3);
+ assert.deepEqual(orderedWaiters(remaining, now, order).map(entry => entry.ticket), [2, 1], 'consumed opportunities cannot be reused');
+ assert.deepEqual(orderedWaiters([row(1, 'A', 2, 61_000), row(2, 'A', 0)], now, order).map(entry => entry.ticket), [1, 2],
+ 'release-only admission also protects an aged unplanned run');
+});
diff --git a/test/resources-release-fixture.js b/test/resources-release-fixture.js
new file mode 100644
index 00000000..13adc5de
--- /dev/null
+++ b/test/resources-release-fixture.js
@@ -0,0 +1,149 @@
+/** Real board, roadmap and queue scenarios for release admission [C7,V4]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { DatabaseSync } from 'node:sqlite';
+import { runFixtureChild } from './fixture-child.js';
+
+const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
+const GATE_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/gate.js')).href;
+const RELEASE_WORKER = `
+import { withGateSlot } from ${JSON.stringify(GATE_MODULE)};
+const [root, agent, item, kind, landing] = process.argv.slice(1);
+let said = false;
+await withGateSlot(root, async () => {
+ console.log(JSON.stringify({ acquired: agent }));
+ for await (const line of process.stdin) if (String(line).trim() === 'release') break;
+}, { agent, item, kind, landing: landing === 'true', remote: false, onWait: state => {
+ if (!said || state.rejoined) { said = true; console.log(JSON.stringify({ queued: state })); }
+} });
+`;
+
+/** Run the actual CLI in a private board and preserve its named refusal on failure. */
+function command(box, root, ...args) {
+ const result = runFixtureChild(process.execPath, [BIN, ...args], { cwd: root, env: box.env, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ return result.stdout;
+}
+
+/** Initialize a real private board with current, later and unplanned work through public commands. */
+function board(box, root) {
+ command(box, root, 'init');
+ for (const title of ['Current work', 'Later work', 'Unplanned work']) command(box, root, 'add', 'coordinator', title);
+ command(box, root, 'milestone', 'add', 'current', '--items', '1');
+ command(box, root, 'milestone', 'add', 'later', '--items', '2');
+}
+
+/** Change only this test's private machine settings, preserving both gate slots. */
+function settings(box, queue) {
+ mkdirSync(box.home, { recursive: true });
+ writeFileSync(join(box.home, 'settings.json'), JSON.stringify({ gateSlots: 2, gate: { queue } }) + '\n');
+}
+
+/** Move one private waiter's clock back; no live board or shared machine database is changed. */
+function age(box, agent) {
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ try {
+ db.exec('PRAGMA busy_timeout = 5000');
+ assert.equal(db.prepare('UPDATE waiter SET since = ? WHERE agent = ?').run(new Date(Date.now() - 61_000).toISOString(), agent).changes, 1); // budget: derived from the declared one-minute queue age, injecting a private clock without elapsed waiting.
+ } finally { db.close(); }
+}
+
+/**
+ * Exercise release ordering through withGateSlot, real private boards and child processes.
+ * The named test stays in resources.test.js; its scenarios live here so the already large queue
+ * test file does not grow another block of fixture code. The outer native runner owns the real
+ * machine lease; these child queues use only the fixture's separate machine home.
+ *
+ * @param {{ fixture: Function, poolWorker: Function, privateList: Function, event: Function, acquired: Function, release: Function, legacyModule: string }} helpers
+ * @returns {Promise<void>}
+ */
+export async function releaseQueueProof({ fixture, poolWorker, privateList, event, acquired, release, legacyModule }) {
+ const line = box => privateList(box).find(row => row.name === 'gate').line.map(row => row.agent);
+ /** Launch a real gate action that captures its board and item when joining the pool. */
+ const run = (box, root, agent, item, kind = 'submit', landing = false) => {
+ const child = poolWorker(box, { agent, script: RELEASE_WORKER, args: [root, agent, String(item), kind, String(landing)] });
+ child.releaseAgent = agent;
+ return child;
+ };
+ /** Fill both slots, so all later runs demonstrably join the waiting line. */
+ const hold = async box => {
+ const holders = [poolWorker(box, { agent: 'holder-one' }), poolWorker(box, { agent: 'holder-two' })];
+ for (const holder of holders) await acquired(holder);
+ return holders;
+ };
+ /** Queue one run and wait until its admission metadata has been stored. */
+ const queue = async (...args) => {
+ const child = run(...args);
+ assert.ok((await event(child)).queued, 'a full pool keeps this run queued');
+ return child;
+ };
+ /** Release exactly one holder and prove the remaining runs execute in the reported order. */
+ const drain = async (box, holders, children) => {
+ await release(holders[0]);
+ for (const [index, child] of children.entries()) {
+ assert.equal((await acquired(child)).acquired, child.releaseAgent);
+ assert.deepEqual(line(box), children.slice(index + 1).map(entry => entry.releaseAgent),
+ 'consuming one opportunity leaves every other board in its remaining positions');
+ await release(child);
+ }
+ await release(holders[1]);
+ };
+
+ const off = fixture();
+ board(off, off.first);
+ const offHolders = await hold(off);
+ const offLater = await queue(off, off.first, 'off-later', 2);
+ const offCurrent = await queue(off, off.first, 'off-current', 1);
+ assert.deepEqual(line(off), ['off-later', 'off-current'], 'absent release setting preserves arrival');
+ await drain(off, offHolders, [offLater, offCurrent]);
+
+ const on = fixture();
+ board(on, on.first);
+ board(on, on.second);
+ settings(on, { currentReleaseFirst: true });
+ const onHolders = await hold(on);
+ const unplanned = await queue(on, on.first, 'A-unplanned', 3, 'focused');
+ const foreign = await queue(on, on.second, 'B-current', 1);
+ const later = await queue(on, on.first, 'A-later', 2);
+ const current = await queue(on, on.first, 'A-current', 1);
+ const landing = await queue(on, on.first, 'A-landing', 3, 'landing', true);
+ assert.deepEqual(line(on), ['A-landing', 'A-current', 'B-current', 'A-later', 'A-unplanned'],
+ 'landing stays first and each board retains its opportunity positions');
+ assert.match(command(off, off.first, 'settings'), /^gate\.queue\.currentReleaseFirst: false\b/mu);
+ command(on, on.first, 'milestone', 'move', 'later', '--before', 'current');
+ assert.deepEqual(line(on), ['A-landing', 'A-current', 'B-current', 'A-later', 'A-unplanned'],
+ 'queued ranks remain captured despite a roadmap reorder');
+ await drain(on, onHolders, [landing, current, foreign, later, unplanned]);
+ assert.match(command(on, on.first, 'settings'), /^gate\.queue\.currentReleaseFirst: true$/mu);
+
+ const aging = fixture();
+ board(aging, aging.first);
+ settings(aging, { reviewsFirst: true, currentReleaseFirst: true, agingMinutes: 1 });
+ const agingHolders = await hold(aging);
+ const aged = await queue(aging, aging.first, 'aged-unplanned', 3, 'focused');
+ age(aging, 'aged-unplanned');
+ const young = await queue(aging, aging.first, 'young-current', 1);
+ const review = await queue(aging, aging.first, 'review-later', 2, 'review');
+ assert.deepEqual(line(aging), ['review-later', 'aged-unplanned', 'young-current'],
+ 'release priority cannot displace global review class or an aged waiter');
+ await drain(aging, agingHolders, [review, aged, young]);
+
+ const mixed = fixture();
+ board(mixed, mixed.first);
+ settings(mixed, { reviewsFirst: true, currentReleaseFirst: true });
+ const mixedHolders = await hold(mixed);
+ const old = poolWorker(mixed, { agent: 'legacy-focused', kind: 'focused', module: legacyModule });
+ old.releaseAgent = 'legacy-focused';
+ assert.ok((await event(old)).queued);
+ const newReview = await queue(mixed, mixed.first, 'new-current-review', 1, 'review');
+ assert.deepEqual(line(mixed), ['legacy-focused', 'new-current-review'], 'all clients agree on arrival while a legacy client waits');
+ assert.equal(privateList(mixed).find(row => row.name === 'gate').order, 'arrival');
+ await drain(mixed, mixedHolders, [old, newReview]);
+
+ settings(aging, { currentReleaseFirst: 'yes' });
+ const bad = runFixtureChild(process.execPath, [BIN, 'settings', '--json'], { cwd: aging.first, env: aging.env, encoding: 'utf8' });
+ assert.equal(bad.status, 1);
+ assert.match(JSON.parse(bad.stdout).error.message, /gate\.queue\.currentReleaseFirst/u);
+}
diff --git a/test/resources.test.js b/test/resources.test.js
index 544c12ef..dbd52d44 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -1,3 +1,4 @@
+/** @pullboard-test-input source-tree */
/** Real-process resource queue and lease coverage [Q1,Q2,Q3]. */
import assert from 'node:assert/strict';
import { startFixtureChild as spawn, runFixtureChild as spawnSync, reportFixtureChildFailure, runFixtureChild, runFixtureChildAsync, runFixtureGit } from './fixture-child.js';
@@ -12,6 +13,7 @@ import { after, test } from 'node:test';
import { DatabaseSync } from 'node:sqlite';
import { listResources, setResourceCapacity, takeResource } from '../src/resources.js';
import { checkNeedsBrowser } from '../src/browser-admission.js';
+import { releaseQueueProof } from './resources-release-fixture.js';
const TEMP = [];
const CHILDREN = new Set();
@@ -236,9 +238,9 @@ function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = bo
}
/** Launch a dedicated gate-pool worker carrying browser and queue-priority metadata. */
-function poolWorker(box, { agent, browser = false, item = '', kind = '', landing = false, module = MODULE }) {
+function poolWorker(box, { agent, browser = false, item = '', kind = '', landing = false, module = MODULE, script = POOL_MODULE_WORKER, args }) {
// module swaps in another resources implementation, such as an older pullboard's, for mixed-version tests.
- const workerArgs = ['--input-type=module', '-e', POOL_MODULE_WORKER.replace(JSON.stringify(MODULE), JSON.stringify(module)), box.first, agent, String(browser), item, kind, String(landing)];
+ const workerArgs = ['--input-type=module', '-e', script.replace(JSON.stringify(MODULE), JSON.stringify(module)), ...(args ?? [box.first, agent, String(browser), item, kind, String(landing)])];
const startedAt = performance.now();
const child = spawn(process.execPath, workerArgs, {
env: box.env, stdio: ['pipe', 'pipe', 'pipe'],
@@ -942,6 +944,8 @@ test('a line holding an older pullboard waiter keeps arrival order, so mixed ver
await release(review);
});
+test('the gate pool serves the current release first [C7,V4]', () => releaseQueueProof({ fixture, poolWorker, privateList, event, acquired, release, legacyModule: PRE_RUNNER_MODULE }));
+
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 ?? '']);
@@ -1019,7 +1023,7 @@ test('queue order follows the machine settings [C7,O5]', async () => {
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 });
+ assert.deepEqual(JSON.parse(settingsCli(aging, '--json').stdout).settings.gate.queue, { reviewsFirst: true, currentReleaseFirst: false, 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]);