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 #641 63f858cf onto #697's merge head 39663e40 [C7]

Corey Olson1d4afaa4c771
diff --cc src/cli.js
index 450d2345,45d4ebbc..68062358
--- a/src/cli.js
+++ b/src/cli.js
@@@ -68,7 -65,7 +68,7 @@@ import { tour } from './tour.js'
import { commandOutput, refusalDocument } from './json.js';
import { forgetProject, listApiProjects, registerProjectAndLink } from './projects.js';
import { milestoneRoadmap } from './roadmap.js';
- import { listResources, runnerResourceStatus } from './resources.js';
-import { listResources, memoryVerdict, readMachineMemory } from './resources.js';
++import { listResources, memoryVerdict, readMachineMemory, runnerResourceStatus } from './resources.js';
import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { exportView, serveView } from './serve.js';
import { forgetView, rememberView, runningView } from './view-session.js';
@@@ -81,7 -78,7 +81,7 @@@ import { flowLines, flowAlertLine } fro
import { releaseHeadlinesBetween } from './changelog.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
- import { addRunner, browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, setBrowserSlots, setGateSlots } from './settings.js';
-import { browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, memoryFloorMB, setBrowserSlots, setGateSlots } from './settings.js';
++import { addRunner, browserFreeChecksEnabled, gateQueueSettings, loadMachineSettings, memoryFloorMB, 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';
@@@ -1881,11 -1819,11 +1883,12 @@@ function readCommands(io, { first, seco
...listResources({ scope: 'machine' }).map((resource) => ({ ...resource, scope: 'machine' })),
...listResources({ scope: 'repo', root: ctx.info.root }).map((resource) => ({ ...resource, scope: 'repo' })),
];
+ const runners = runnerResourceStatus(loadMachineSettings().runners ?? []);
const queue = gateQueueSettings();
- io.result?.({ resources, runners, browserSlots, queue });
- io.result?.({ resources, browserSlots, queue, memory });
++ io.result?.({ resources, runners, browserSlots, queue, memory });
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'}`);
+ io.say(memory.line);
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' : ''}`);
@@@ -3025,14 -2840,25 +3028,29 @@@ function browserAdmissionReporter(io, j
};
}
- /** Build a de-duplicated queue message for a gate waiting on machine capacity. */
- function gateWaitReporter(io) {
+ /** Build de-duplicated queue messages for a gate waiting on machine capacity or memory; exported so tests can read what a person sees. */
+ export function gateWaitReporter(io) {
let last = '';
- return ({ holders, position, runnerUnavailable }) => {
+ let warned = false;
+ let held = false;
- return ({ holders, position, memory }) => {
++ return ({ holders, position, memory, runnerUnavailable }) => {
+ if (runnerUnavailable) {
+ io.say(`runner ${runnerUnavailable.host} unavailable: ${runnerUnavailable.reason}; until ${runnerUnavailable.until}; requeueing the run`);
+ return;
+ }
+ // Memory speaks once per state: one warning where it cannot be read, one line per hold.
+ if (memory && !memory.checked) {
+ if (!warned) io.say(memory.warning);
+ warned = true;
+ if (!position) return;
+ }
+ if (memory?.held) {
+ if (!held) io.say(memory.line);
+ held = true;
+ last = '';
+ return;
+ }
+ held = false;
const repos = holders.map(({ repo }) => repo).filter(Boolean);
const message = `gate waiting: ${holders.length} running${repos.length ? ` in ${repos.join(', ')}` : ''}; place ${position}`;
if (message !== last) {
diff --cc src/gate.js
index d605a9a3,6e4747b8..3b73af1c
--- a/src/gate.js
+++ b/src/gate.js
@@@ -311,19 -273,19 +312,20 @@@ function hasPipeline(command)
*
* @param {string} root - Checkout used to locate the machine resource database.
* @param {(lease: { waitMs: number, token?: string, pool?: string, browser?: boolean, release: () => void }) => any | Promise<any>} action - Work to perform while holding a slot.
- * @param {{ landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, agent?: string, item?: string|number, kind?: string, onWait?: (state: object) => void }} [options] - Queue class and progress reporter.
- * @param {{ landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, agent?: string, item?: string|number, kind?: string, onWait?: (state: object) => void, readMemory?: typeof readMachineMemory }} [options] - Queue class, progress reporter and, for tests, the machine memory reader.
++ * @param {{ landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, remote?: boolean, agent?: string, item?: string|number, kind?: string, onWait?: (state: object) => void, readMemory?: typeof readMachineMemory }} [options] - Queue class, remote eligibility, progress reporter and, for tests, the machine memory reader.
* @returns {Promise<any>} The action's result after releasing its lease.
*/
- export async function withGateSlot(root, action, { landing = false, itemCheck = false, diagnostic = false, browser = false, remote = true, agent, item = '', kind = '', onWait } = {}) {
-export async function withGateSlot(root, action, { landing = false, itemCheck = false, diagnostic = false, browser = false, agent, item = '', kind = '', onWait, readMemory = readMachineMemory } = {}) {
++export async function withGateSlot(root, action, { landing = false, itemCheck = false, diagnostic = false, browser = false, remote = true, agent, item = '', kind = '', onWait, readMemory = readMachineMemory } = {}) {
const inherited = inheritedGateSlot({ root, browser });
if (inherited) {
try { return await action(inherited); }
finally { inherited.release(); }
}
const settingsProvider = () => loadMachineSettings();
+ const floorMB = memoryFloorMB();
const capacityProvider = () => settingsProvider().gateSlots;
- const lease = await takeResource({
+ const source = runnerSource(root);
+ let lease = await takeResource({
name: 'gate',
capacity: capacityProvider(),
capacityProvider,
@@@ -339,8 -301,7 +341,9 @@@
diagnostic,
browser,
allowIdleCapacityUpdate: true,
+ remote: remote && Boolean(source),
+ runnerProvider: () => loadMachineSettings().runners ?? [],
+ memory: floorMB === null ? undefined : memoryAdmission({ floorBytes: () => (memoryFloorMB() ?? floorMB) * 1024 ** 2, read: readMemory }),
onWait,
});
try {
diff --cc src/help.js
index 25eb823b,fc5da6e2..49a059ff
--- a/src/help.js
+++ b/src/help.js
@@@ -22,8 -22,7 +22,9 @@@ Set u
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)
+ memory hold is opt-in: gate.memoryFloorMB in ~/.pullboard/settings.json holds the queue under that many MB free or critical pressure (default off)
+ 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}
items, shouts, doctrine, agents and activity; --port 0 chooses a free port
--project limits this view to the registered project for this repository
diff --cc src/resources.js
index dc6c48d0,5d6b7984..3057ff88
--- a/src/resources.js
+++ b/src/resources.js
@@@ -333,140 -286,148 +334,275 @@@ 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.
+ * Local and remote slots are offered in one admission order, the rank that snapshot and
+ * waiterPosition report: landings first and then arrival by default, or, where the machine sets
+ * gate.queue.reviewsFirst, the class rank (landing, review, submit, other, aging up) FIFO by ticket
+ * within a class, back to arrival 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 {{ reviewsFirst: boolean, ageMs: number }} [order] - The pool's admission order setting.
+ * @param {number} [now] - The clock reading to age against.
+ * @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 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(); }
+}
+
+ const MEMORY_CACHE_MS = 2_000;
+ const MEMORY_COMMAND_TIMEOUT_MS = 2_000;
+ const LINUX_CRITICAL_FULL_AVG10 = 10;
+ const LINUX_WARN_SOME_AVG10 = 10;
+ const memoryCache = new Map();
+
+ /** Run a small OS utility asynchronously; a slow or missing tool rejects instead of blocking a run. */
+ function readCommand(file, args) {
+ return new Promise((resolveOutput, rejectOutput) => {
+ execFile(file, args, { encoding: 'utf8', timeout: MEMORY_COMMAND_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: 'C', LANG: 'C' } },
+ (error, stdout) => (error ? rejectOutput(error) : resolveOutput(stdout)));
+ });
+ }
+
+ /** Read macOS pressure level, free percentage and size from one sysctl call. */
+ async function readDarwinMemory(run) {
+ const [level, freePercent, total] = (await run('/usr/sbin/sysctl', ['-n', 'kern.memorystatus_vm_pressure_level', 'kern.memorystatus_level', 'hw.memsize'])).trim().split(/\s+/u).map(Number);
+ if (![level, freePercent, total].every(Number.isFinite) || total <= 0) throw new Error('sysctl did not report memory pressure');
+ // The kernel's levels are 1 normal, 2 warn and 4 critical; the free percentage is the one Activity Monitor uses.
+ const pressure = level >= 4 ? 'critical' : level >= 2 ? 'warn' : 'normal';
+ return { pressure, availableBytes: Math.round(total * freePercent / 100), totalBytes: total };
+ }
+
+ /** Read Linux MemAvailable and, where the kernel has it, pressure stall information. */
+ async function readLinuxMemory(readText) {
+ const meminfo = await readText('/proc/meminfo');
+ const field = (name) => Number(new RegExp(`^${name}:\\s+(\\d+) kB`, 'mu').exec(meminfo)?.[1]) * 1024;
+ const availableBytes = field('MemAvailable');
+ const totalBytes = field('MemTotal');
+ if (!Number.isFinite(availableBytes) || !Number.isFinite(totalBytes)) throw new Error('/proc/meminfo has no MemAvailable');
+ let pressure = 'unknown';
+ try {
+ const psi = await readText('/proc/pressure/memory');
+ const avg10 = (kind) => Number(new RegExp(`^${kind} avg10=([\\d.]+)`, 'mu').exec(psi)?.[1]);
+ const full = avg10('full');
+ const some = avg10('some');
+ if (Number.isFinite(full) || Number.isFinite(some)) {
+ pressure = full >= LINUX_CRITICAL_FULL_AVG10 ? 'critical' : some >= LINUX_WARN_SOME_AVG10 ? 'warn' : 'normal';
+ }
+ } catch { /* Kernels without PSI still report MemAvailable, which the floor checks. */ }
+ return { pressure, availableBytes, totalBytes };
+ }
+
+ /** Name the biggest processes by resident memory, with their working directories where the OS allows. */
+ async function readBiggestProcesses(platform, run, readLink, count = 3) {
+ const listed = (await run('/bin/ps', ['-e', '-o', 'pid=', '-o', 'rss=', '-o', 'comm='])).split('\n').map((line) => {
+ const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/u.exec(line);
+ // Only the executable's own name is kept: arguments can carry secrets.
+ return match ? { pid: Number(match[1]), bytes: Number(match[2]) * 1024, name: basename(match[3].trim()) } : null;
+ }).filter(Boolean).sort((left, right) => right.bytes - left.bytes).slice(0, count);
+ return Promise.all(listed.map(async (entry) => {
+ let cwd = '';
+ try {
+ if (platform === 'linux') cwd = await readLink(`/proc/${entry.pid}/cwd`);
+ else cwd = /^n(.*)$/mu.exec(await run('/usr/sbin/lsof', ['-a', '-d', 'cwd', '-p', String(entry.pid), '-Fn']))?.[1] ?? '';
+ } catch { /* Another user's process hides its directory; the pid and size still name it. */ }
+ return { ...entry, cwd };
+ }));
+ }
+
+ /**
+ * Take one reading of the machine's memory: pressure, free bytes and, when asked, the biggest
+ * processes. A platform or tool that cannot answer returns checked: false rather than throwing,
+ * so the pool falls back to counting slots.
+ *
+ * @param {{ platform?: string, processes?: boolean, run?: (file: string, args: string[]) => Promise<string>, readText?: (file: string) => Promise<string>, readLink?: (file: string) => Promise<string> }} [options]
+ * @returns {Promise<{ checked: true, pressure: string, availableBytes: number, totalBytes: number, processes?: object[] } | { checked: false, platform: string, reason: string }>}
+ */
+ export async function readMachineMemory({ platform = process.platform, processes = false, run = readCommand, readText = (file) => readFile(file, 'utf8'), readLink = readlink } = {}) {
+ try {
+ let reading;
+ if (platform === 'darwin') reading = await readDarwinMemory(run);
+ else if (platform === 'linux') reading = await readLinuxMemory(readText);
+ else return { checked: false, platform, reason: 'no memory reader for this platform' };
+ if (!processes) return { checked: true, ...reading };
+ let biggest = [];
+ try { biggest = await readBiggestProcesses(platform, run, readLink); } catch { /* The hold still stands without names. */ }
+ return { checked: true, ...reading, processes: biggest };
+ } catch (error) {
+ return { checked: false, platform, reason: String(error?.message ?? error).split('\n')[0] };
+ }
+ }
+
+ /** Format a byte count the way a person reads memory: MB under a gigabyte, GB above. */
+ function memorySize(bytes) {
+ return bytes >= 1024 ** 3 ? `${(bytes / 1024 ** 3).toFixed(1)} GB` : `${Math.round(bytes / 1024 ** 2)} MB`;
+ }
+
+ /**
+ * Decide whether a reading holds the queue and say so in one line. The same line serves a held
+ * run and pullboard resources, so a person sees one description of the machine.
+ *
+ * @param {object} reading - A readMachineMemory result.
+ * @param {number|null} floorBytes - Free memory under which the queue is held; null when the hold is off.
+ * @returns {{ checked: boolean, held: boolean, line: string, warning?: string }}
+ */
+ export function memoryVerdict(reading, floorBytes) {
+ if (!reading?.checked) {
+ const warning = `memory: not checked on ${reading?.platform ?? process.platform} (${reading?.reason ?? 'no reading'}); the gate pool admits by slots alone`;
+ return { checked: false, held: false, line: warning, warning };
+ }
+ const off = floorBytes === null;
+ const critical = !off && reading.pressure === 'critical';
+ const low = !off && reading.availableBytes < floorBytes;
+ const held = critical || low;
+ const why = [critical ? 'pressure is critical' : '', low ? 'free memory is under the floor' : ''].filter(Boolean).join(' and ');
+ const pressure = reading.pressure === 'unknown' ? 'pressure not reported' : `pressure ${reading.pressure}`;
+ const state = `${pressure}, ${memorySize(reading.availableBytes)} free of ${memorySize(reading.totalBytes)}${off ? '' : ` (floor ${memorySize(floorBytes)})`}`;
+ const biggest = (reading.processes ?? []).map(({ pid, name, bytes, cwd }) => `pid ${pid} ${name} ${memorySize(bytes)} in ${cwd || 'an unreadable directory'}`).join('; ');
+ const verdict = off ? 'hold off (set gate.memoryFloorMB to turn it on)' : held ? `holding the gate queue because ${why}` : 'admitting';
+ return { checked: true, held, line: `memory: ${verdict}: ${state}${biggest ? `; biggest: ${biggest}` : ''}` };
+ }
+
+ /**
+ * Build the gate pool's memory check: a cached reading, then the biggest processes only while the
+ * queue is held, so polling stays at one cheap call every couple of seconds.
+ *
+ * @param {{ floorBytes: () => number, read?: typeof readMachineMemory, cacheMs?: number }} options
+ * @returns {() => Promise<{ checked: boolean, held: boolean, line: string, warning?: string }>}
+ */
+ export function memoryAdmission({ floorBytes, read = readMachineMemory, cacheMs = MEMORY_CACHE_MS }) {
+ return async () => {
+ const cached = memoryCache.get(read);
+ if (cached && Date.now() - cached.at < cacheMs) return cached.verdict;
+ const floor = floorBytes();
+ let verdict = memoryVerdict(await read({ processes: false }), floor);
+ if (verdict.held) verdict = memoryVerdict(await read({ processes: true }), floor);
+ memoryCache.set(read, { at: Date.now(), verdict });
+ return verdict;
+ };
+ }
+
/** Pause briefly between durable queue checks. */
function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }
/**
* 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, 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.
- * @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, memory?: () => Promise<{ checked: boolean, held: boolean, line: string, warning?: string }> }} options - Resource identity and queue 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, remote?: boolean, runnerProvider?: () => Array<{host:string,slots:number,browser:number}>, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean, memory?: () => Promise<{ checked: boolean, held: boolean, line: string, warning?: string }>, _resume?: object }} options - Resource identity, queue class, optional remote executor pool and memory check.
+ * memory, when given, is read before each admission: a held verdict keeps the whole queue
- * waiting in place, and an unchecked one is passed to onWait once so the caller can warn.
- * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}
++ * waiting in place, local and remote slots alike, and an unchecked one is passed to onWait once
++ * so the caller can warn.
+ * @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;
@@@ -535,45 -484,39 +671,53 @@@
}
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; 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)));
+ initialTicket = Number(inserted.lastInsertRowid);
+ }
});
+ let memoryWarned = false;
while (true) {
+ const memory = options.memory ? await options.memory() : null;
+ if (memory && !memory.checked && !memoryWarned) {
+ memoryWarned = true;
+ options.onWait?.({ holders: [], line: [], position: 0, memory });
+ }
const order = queueOrder(scope);
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, 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));
+ 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, 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, order), position: waiterPosition(db, name, Number(rejoined.lastInsertRowid), { order }), 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, 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));
+ initialTicket = Number(rejoined.lastInsertRowid);
+ return { acquired: false, state: { ...snapshot(db, name, order), position: waiterPosition(db, name, initialTicket, { order }), rejoined: true } };
}
- db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);
+ // 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 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, 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;
+ // A machine short of memory holds the whole line in place; recovery admits it in order.
+ if (memory?.held) return { acquired: false, state: { ...spot, position: reportPosition, memory } };
- if (admissionPosition === 1 && spot.holders.length < limit && (!browser || (browserAdmissionPosition === 1 && browserHolders < browserLimit))) {
+ 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);
+ if (executor) {
db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
const acquiredAt = new Date().toISOString();
- db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
- return { acquired: true, state: { ...spot, position: 0 } };
+ 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: false, state: { ...spot, position: reportPosition } };
});
diff --cc src/settings.js
index b9eead48,427f32d5..b7e67c6e
--- a/src/settings.js
+++ b/src/settings.js
@@@ -21,7 -31,19 +21,10 @@@ 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}`);
- }
+ validateGateQueue(value, file);
+ if (value.gate?.memoryFloorMB !== undefined && (!Number.isSafeInteger(value.gate.memoryFloorMB) || value.gate.memoryFloorMB < 0)) {
+ throw new Refused('BAD_MACHINE_SETTINGS', `gate.memoryFloorMB in ${file} must be a whole number of megabytes, 0 or more; fix it before running Pullboard`);
+ }
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 -60,27 +49,15 @@@ export function browserFreeChecksEnable
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 };
-}
-
+ /**
+ * The free-memory floor, in megabytes, below which the machine gate pool holds its queue, or null
+ * when the hold is off. Gate and queue behavior is off by default, the person's rule, so an absent
+ * floor keeps today's admission by slots alone.
+ */
+ export function memoryFloorMB() {
+ return loadMachineSettings().gate?.memoryFloorMB ?? null;
+ }
+
/** Atomically replace machine settings without exposing a partial JSON file. */
function writeMachineSettings(settings) {
const file = machineSettingsFile();
diff --cc test/resources.test.js
index 716cae37,e6b9fe31..28d3aeee
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@@ -235,10 -234,9 +235,10 @@@ function worker(box, { name = 'gate', c
return child;
}
- /** Launch a dedicated gate-pool worker carrying browser and queue-priority metadata. */
- function poolWorker(box, { agent, browser = false, item = '', kind = '', landing = false, module = MODULE }) {
+ /** Launch a dedicated gate-pool worker carrying browser and queue-priority metadata, or another pool script. */
-function poolWorker(box, { agent, browser = false, item = '', kind = '', landing = false, script = POOL_MODULE_WORKER, args }) {
- const workerArgs = ['--input-type=module', '-e', script, ...(args ?? [box.first, agent, String(browser), item, kind, String(landing)])];
++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'],