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(gate): hold the gate queue while the machine is out of memory [C7]

Corey Olsonbd300021d9e5
diff --git a/docs/api.md b/docs/api.md
index dbafe4db..9c310158 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -12,6 +12,8 @@ A successful command returns the fields listed below. `version` is always the nu
Browser-free check admission is opt-in per machine with `"gate": { "browserFreeChecks": true }` in `~/.pullboard/settings.json`; it defaults to `false`. When enabled, the reviewed test classifier can let checks use a CPU-only gate slot. An absent or false setting keeps every check browser-gated, and uncertain or unsupported test commands remain browser-gated even when enabled. The same setting controls the wider frozen-check classification introduced in 0.8.26.
+Before admitting a run, the machine gate pool reads the machine's memory: on macOS the kernel's memory pressure level and free percentage, on Linux `MemAvailable` and the pressure stall averages in `/proc/pressure/memory`. The whole queue waits in place while pressure is critical or free memory is under `"gate": { "memoryFloorMB": <n> }` in `~/.pullboard/settings.json` (default `1024`; `0` leaves only the pressure check). A held run prints one line naming why and the three biggest processes by memory, with pid, size and working directory, and starts once memory recovers. `pullboard resources` prints the same line and returns it as `memory` in JSON. Where memory cannot be read, the pool admits by slots alone and prints one warning that memory is not checked there.
+
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 9ccc8f9c..97b90dc9 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -65,7 +65,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 } from './resources.js';
+import { listResources, memoryVerdict, readMachineMemory } from './resources.js';
import { citedTestFiles, rowEvidence, rowStage } from './evidence.js';
import { exportView, serveView } from './serve.js';
import { forgetView, rememberView, runningView } from './view-session.js';
@@ -78,7 +78,7 @@ import { flowLines, flowAlertLine } from './stats-flow.js';
import { releaseHeadlinesBetween } from './changelog.js';
import { exportBoard, importBoard } from './exchange.js';
import { addSigner, assertRequiredSigners, defaultPrincipal, hasSignerFile } from './signature.js';
-import { browserFreeChecksEnabled, loadMachineSettings, setBrowserSlots, setGateSlots } from './settings.js';
+import { browserFreeChecksEnabled, 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';
@@ -1809,16 +1809,18 @@ function readCommands(io, { first, second, rest, values }) {
io.say(`imported version ${document.version} board tables: ${imported.tables.join(', ')}`);
return 0;
},
- resources: () => {
+ resources: async () => {
const ctx = context(io);
const agents = withBoard(ctx, (board) => store.listAgents(board));
const browserSlots = loadMachineSettings().browserSlots;
+ const memory = memoryVerdict(await readMachineMemory({ processes: true }), memoryFloorMB() * 1024 ** 2);
const resources = [
...listResources({ scope: 'machine' }).map((resource) => ({ ...resource, scope: 'machine' })),
...listResources({ scope: 'repo', root: ctx.info.root }).map((resource) => ({ ...resource, scope: 'repo' })),
];
- io.result?.({ resources, browserSlots });
+ io.result?.({ resources, browserSlots, memory });
io.say(`browserSlots (machine setting): ${browserSlots}`);
+ 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})`);
@@ -2835,10 +2837,25 @@ function browserAdmissionReporter(io, jsonMode = false) {
};
}
-/** 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 }) => {
+ let warned = false;
+ let held = false;
+ return ({ holders, position, memory }) => {
+ // 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) {
@@ -2852,9 +2869,10 @@ function gateWaitReporter(io) {
function settingsCommand(io, { first, second, rest }) {
if (!first && !second && !rest.length) {
const settings = loadMachineSettings();
- io.result?.({ settings });
+ io.result?.({ settings, memoryFloorMB: memoryFloorMB() });
io.say(`gateSlots: ${settings.gateSlots}`);
io.say(`browserSlots: ${settings.browserSlots}`);
+ io.say(`gate.memoryFloorMB: ${memoryFloorMB()}`);
return 0;
}
if (!['gateSlots', 'browserSlots'].includes(first) || !second || rest.length) {
diff --git a/src/gate.js b/src/gate.js
index f2154b49..cb51297e 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -12,8 +12,8 @@ import { availableParallelism } from 'node:os';
import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';
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 { GATE_SLOT_HELD_ENV, gateSlotEnvironment, inheritedGateSlot, memoryAdmission, readMachineMemory, takeResource } from './resources.js';
+import { browserFreeChecksEnabled, loadMachineSettings, memoryFloorMB } from './settings.js';
import { selectAffectedTests } from './affected-tests.js';
import { checkNeedsBrowser, testsNeedBrowser } from './browser-admission.js';
import { timingFromOutput, timingRunner } from './timing.js';
@@ -269,13 +269,14 @@ function hasPipeline(command) {
}
/** Run work under the machine queue: landings first, then every other eligible waiter in arrival order.
+ * The whole queue waits while the machine is out of memory, so a run never starts into swap.
*
* @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.
* @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, agent, item = '', kind = '', onWait } = {}) {
+export async function withGateSlot(root, action, { landing = false, itemCheck = false, diagnostic = false, browser = false, agent, item = '', kind = '', onWait, readMemory = readMachineMemory } = {}) {
const inherited = inheritedGateSlot({ root, browser });
if (inherited) {
try { return await action(inherited); }
@@ -299,6 +300,7 @@ export async function withGateSlot(root, action, { landing = false, itemCheck =
diagnostic,
browser,
allowIdleCapacityUpdate: true,
+ memory: memoryAdmission({ floorBytes: () => memoryFloorMB() * 1024 ** 2, read: readMemory }),
onWait,
});
try {
diff --git a/src/help.js b/src/help.js
index d2485849..0319cfb2 100644
--- a/src/help.js
+++ b/src/help.js
@@ -21,6 +21,7 @@ Set up
pullboard resources local resource holders and their FIFO queues
pullboard settings [gateSlots <n> | browserSlots <n>] view or set machine capacity (gate default 2; browser default 1)
browser-free check slots are opt-in: gate.browserFreeChecks in ~/.pullboard/settings.json (default false)
+ the gate queue waits while memory pressure is critical or free memory is under gate.memoryFloorMB (default 1024)
pullboard view [--project] [--port N] [--no-open] every project on this machine in your browser; default http://127.0.0.1:${DEFAULT_VIEW_PORT}
items, shouts, doctrine, agents and activity; --port 0 chooses a free port
--project limits this view to the registered project for this repository
diff --git a/src/resources.js b/src/resources.js
index 7f505336..8b07998d 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -1,6 +1,7 @@
/** Machine and repository queues persist leases; landings go first, then eligible waiters in arrival order [Q1,Q2,Q3]. */
import { mkdirSync, realpathSync } from 'node:fs';
-import { execFileSync } from 'node:child_process';
+import { execFile, execFileSync } from 'node:child_process';
+import { readFile, readlink } from 'node:fs/promises';
import { basename, dirname, join, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
@@ -211,13 +212,146 @@ function waiterPosition(db, name, ticket, { eligibleOnly = false } = {}) {
return considered.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;
}
+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} floorBytes - Free memory under which the queue is held.
+ * @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 critical = reading.pressure === 'critical';
+ const low = 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)} (floor ${memorySize(floorBytes)})`;
+ const biggest = (reading.processes ?? []).map(({ pid, name, bytes, cwd }) => `pid ${pid} ${name} ${memorySize(bytes)} in ${cwd || 'an unreadable directory'}`).join('; ');
+ const line = `memory: ${held ? `holding the gate queue because ${why}` : 'admitting'}: ${state}${biggest ? `; biggest: ${biggest}` : ''}`;
+ return { checked: true, held, line };
+}
+
+/**
+ * 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 landing-first queue; every other kind keeps its original FIFO ticket.
*
- * @param {{ name: string, capacity: number, capacityProvider?: () => number, browserCapacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.
+ * @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.
+ * 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 }>}
*/
export async function takeResource(options) {
@@ -278,7 +412,13 @@ export async function takeResource(options) {
// Retain queue metadata for older readers; admission uses landing priority and arrival only.
db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
});
+ 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 acquired = update(db, () => {
const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);
if (!waiter) {
@@ -294,6 +434,8 @@ export async function takeResource(options) {
const browserAdmissionPosition = browser ? waiterPosition(db, 'browser', waiter.ticket, { eligibleOnly: true }) : 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))) {
db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
const acquiredAt = new Date().toISOString();
diff --git a/src/settings.js b/src/settings.js
index 5c3f3542..88fa0519 100644
--- a/src/settings.js
+++ b/src/settings.js
@@ -8,6 +8,8 @@ import { Refused } from './refused.js';
const DEFAULT_GATE_SLOTS = 2;
const DEFAULT_BROWSER_SLOTS = 1;
+/** Free memory under which the machine gate queue waits; about one test run's worth of headroom. */
+export const DEFAULT_MEMORY_FLOOR_MB = 1024;
/** Resolve the separate machine settings file. */
export function machineSettingsFile() {
@@ -30,6 +32,9 @@ 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`);
}
+ 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 +51,11 @@ export function browserFreeChecksEnabled() {
return loadMachineSettings().gate?.browserFreeChecks === true;
}
+/** The free-memory floor, in megabytes, below which the machine gate pool holds its queue. */
+export function memoryFloorMB() {
+ return loadMachineSettings().gate?.memoryFloorMB ?? DEFAULT_MEMORY_FLOOR_MB;
+}
+
/** Atomically replace machine settings without exposing a partial JSON file. */
function writeMachineSettings(settings) {
const file = machineSettingsFile();
diff --git a/test/resources.test.js b/test/resources.test.js
index a1aafa5e..814acfc2 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -234,9 +234,9 @@ function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = bo
return child;
}
-/** Launch a dedicated gate-pool worker carrying browser and queue-priority metadata. */
-function poolWorker(box, { agent, browser = false, item = '', kind = '', landing = false }) {
- const workerArgs = ['--input-type=module', '-e', POOL_MODULE_WORKER, box.first, agent, String(browser), item, kind, String(landing)];
+/** 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)])];
const startedAt = performance.now();
const child = spawn(process.execPath, workerArgs, {
env: box.env, stdio: ['pipe', 'pipe', 'pipe'],
@@ -1123,6 +1123,136 @@ test('[Q2,Q3] a SIGKILLed waiter is skipped while the next live waiter advances'
await release(live);
});
+const CLI_MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/cli.js')).href;
+/** A gate run whose memory reading comes from a fixture file through the Linux reader's own parsing. */
+const MEMORY_WORKER = `
+import { readFileSync } from 'node:fs';
+import { withGateSlot } from ${JSON.stringify(GATE_MODULE)};
+import { readMachineMemory } from ${JSON.stringify(MODULE)};
+const [root, agent, source] = process.argv.slice(1);
+const ps = [' 6161 512000 /bin/zsh', ' 4242 25165824 /usr/bin/python3', ' 77 1024 /sbin/launchd',
+ ' 5151 2097152 /usr/local/bin/node', ' 4343 24117248 /opt/homebrew/bin/python3.12'].join('\\n');
+const cwds = { '/proc/4242/cwd': '/work/journal-reader', '/proc/4343/cwd': '/work/other-reader', '/proc/5151/cwd': '/work/pullboard' };
+/** Read the fixture's current machine state as Linux would present it. */
+const readMemory = (options) => source === 'win32' ? readMachineMemory({ ...options, platform: 'win32' }) : readMachineMemory({
+ ...options, platform: 'linux',
+ readText: async (file) => {
+ const reading = JSON.parse(readFileSync(source, 'utf8'));
+ if (file === '/proc/meminfo') return reading.meminfo;
+ if (file === '/proc/pressure/memory') return reading.psi;
+ throw new Error('unexpected file ' + file);
+ },
+ run: async (file) => { if (file === '/bin/ps') return ps; throw new Error('unexpected command ' + file); },
+ readLink: async (path) => { if (cwds[path]) return cwds[path]; throw new Error('EACCES'); },
+});
+let last = '';
+await withGateSlot(root, async () => {
+ console.log(JSON.stringify({ acquired: agent }));
+ for await (const line of process.stdin) if (String(line).trim() === 'release') break;
+}, { agent, kind: 'gate', readMemory, onWait: ({ position, memory }) => {
+ const state = JSON.stringify({ waiting: position, memory: memory ?? null });
+ if (state !== last) { last = state; console.log(state); }
+} });
+`;
+
+/** Write what /proc would say: total and available memory, and the pressure stall averages. */
+function writeMemoryReading(file, { availableMB, fullAvg10 = 0, someAvg10 = 0, broken = false }) {
+ const meminfo = broken ? 'MemTotal: 37748736 kB\n' : `MemTotal: 37748736 kB\nMemFree: 102400 kB\nMemAvailable: ${availableMB * 1024} kB\n`;
+ const psi = `some avg10=${someAvg10.toFixed(2)} avg60=0.00 avg300=0.00 total=1\nfull avg10=${fullAvg10.toFixed(2)} avg60=0.00 avg300=0.00 total=1\n`;
+ writeFileSync(file, JSON.stringify({ meminfo, psi }));
+}
+
+/** Launch one gate run through withGateSlot with an injected memory source. */
+function memoryWorker(box, agent, source) {
+ return poolWorker(box, { agent, script: MEMORY_WORKER, args: [box.first, agent, source] });
+}
+
+test('the pool holds work while the machine is out of memory and names the biggest process [C7]', async () => {
+ const box = fixture();
+ mkdirSync(box.home, { recursive: true });
+ writeFileSync(join(box.home, 'settings.json'), `${JSON.stringify({ gate: { memoryFloorMB: 512 } })}\n`);
+ const reading = join(box.dir, 'memory.json');
+ const biggest = 'biggest: pid 4242 python3 24.0 GB in /work/journal-reader; pid 4343 python3.12 23.0 GB in /work/other-reader; pid 5151 node 2.0 GB in /work/pullboard';
+ writeMemoryReading(reading, { availableMB: 8192, fullAvg10: 42, someAvg10: 80 });
+ const run = memoryWorker(box, 'held-run', reading);
+
+ const critical = await event(run);
+ assert.equal(critical.acquired, undefined, 'a critical reading must not admit the run');
+ assert.equal(critical.waiting, 1, 'the held run keeps its place at the head of the line');
+ assert.equal(critical.memory?.held, true, `the run is held for memory: ${JSON.stringify(critical)}`);
+ assert.equal(critical.memory.line,
+ `memory: holding the gate queue because pressure is critical: pressure critical, 8.0 GB free of 36.0 GB (floor 512 MB); ${biggest}`,
+ 'one line says why and names the three biggest processes with pid, size and working directory');
+ assert.doesNotMatch(critical.memory.line, /\n/u, 'the hold is one line');
+ const gate = privateList(box).find(({ name }) => name === 'gate');
+ assert.equal(gate.holders.length, 0, 'no run holds a slot while memory is critical, though both slots are free');
+ assert.deepEqual(gate.line.map(({ agent }) => agent), ['held-run'], 'the held run waits in the queue');
+ await delay(300);
+ assert.ok(!run.pendingLines.some((line) => JSON.parse(line).acquired), 'the run stays held while the reading stays critical');
+
+ writeMemoryReading(reading, { availableMB: 400 });
+ const low = await event(run);
+ assert.equal(low.memory?.held, true, `free memory under the settings floor still holds: ${JSON.stringify(low)}`);
+ assert.equal(low.memory.line,
+ `memory: holding the gate queue because free memory is under the floor: pressure normal, 400 MB free of 36.0 GB (floor 512 MB); ${biggest}`,
+ 'the floor comes from gate.memoryFloorMB in pullboard settings');
+
+ writeMemoryReading(reading, { availableMB: 8192 });
+ const recovered = await acquired(run).catch((error) => assert.fail(`the held run is admitted once memory recovers: ${error.message.split('\n')[0]}`));
+ assert.equal(recovered.acquired, 'held-run', 'the held run is admitted once memory recovers');
+ await release(run);
+});
+
+test('an unread machine warns once and admits as before; pullboard resources prints the memory line [C7]', async () => {
+ const { gateWaitReporter } = await import(CLI_MODULE);
+ const said = [];
+ const report = gateWaitReporter({ say: (line) => said.push(line) });
+ report({ holders: [], position: 1, memory: { checked: true, held: true, line: 'memory: holding the gate queue because pressure is critical: first' } });
+ report({ holders: [], position: 1, memory: { checked: true, held: true, line: 'memory: holding the gate queue because pressure is critical: sizes moved' } });
+ report({ holders: [], position: 1 });
+ assert.deepEqual(said, ['memory: holding the gate queue because pressure is critical: first', 'gate waiting: 0 running; place 1'],
+ 'a held run prints its line once per hold, then the ordinary queue line');
+ const warned = [];
+ const warn = gateWaitReporter({ say: (line) => warned.push(line) });
+ const unchecked = { checked: false, held: false, line: 'memory: not checked on win32', warning: 'memory: not checked on win32' };
+ warn({ holders: [], line: [], position: 0, memory: unchecked });
+ warn({ holders: [], line: [], position: 0, memory: unchecked });
+ assert.deepEqual(warned, ['memory: not checked on win32'], 'an unread machine prints one warning');
+
+ const box = fixture();
+ for (const source of ['win32', 'broken']) {
+ const file = join(box.dir, `${source}.json`);
+ writeMemoryReading(file, { availableMB: 100, fullAvg10: 99, broken: true });
+ const run = memoryWorker(box, `${source}-run`, source === 'win32' ? 'win32' : file);
+ const first = await event(run);
+ assert.equal(first.memory?.checked, false, `${source}: the run hears that memory is not checked: ${JSON.stringify(first)}`);
+ assert.match(first.memory.warning, /^memory: not checked on (win32|linux) \(.+\); the gate pool admits by slots alone$/u);
+ assert.equal((await event(run)).acquired, `${source}-run`, `${source}: an unread machine admits as today, after exactly one warning`);
+ await release(run);
+ }
+
+ const defaults = runFixtureChild(process.execPath, [BIN, 'settings', '--json'], { cwd: box.first, env: box.env, encoding: 'utf8' });
+ assert.equal(defaults.status, 0, defaults.stderr);
+ assert.equal(JSON.parse(defaults.stdout).memoryFloorMB, 1024, 'an unset machine holds under a 1 GB floor');
+ mkdirSync(box.home, { recursive: true });
+ writeFileSync(join(box.home, 'settings.json'), `${JSON.stringify({ gate: { memoryFloorMB: -1 } })}\n`);
+ const refused = runFixtureChild(process.execPath, [BIN, 'settings', '--json'], { cwd: box.first, env: box.env, encoding: 'utf8' });
+ assert.equal(refused.status, 1);
+ assert.equal(JSON.parse(refused.stdout).error.code, 'BAD_MACHINE_SETTINGS');
+ assert.match(JSON.parse(refused.stdout).error.message, /gate\.memoryFloorMB/u);
+ rmSync(join(box.home, 'settings.json'));
+
+ checkProject(box);
+ const human = runFixtureChild(process.execPath, [BIN, 'resources'], { cwd: box.first, env: box.env, encoding: 'utf8' });
+ assert.equal(human.status, 0, human.stderr);
+ const printed = human.stdout.split('\n').filter((line) => line.startsWith('memory: '));
+ assert.equal(printed.length, 1, `pullboard resources prints one machine memory line: ${human.stdout}`);
+ assert.match(printed[0], /^memory: (admitting: |holding the gate queue because |not checked on )/u);
+ const json = runFixtureChild(process.execPath, [BIN, 'resources', '--json'], { cwd: box.first, env: box.env, encoding: 'utf8' });
+ assert.equal(json.status, 0, json.stderr);
+ assert.match(JSON.parse(json.stdout).memory.line, /^memory: /u, 'the JSON result carries the same machine line');
+});
+
test('[Q4] machine capacity changes atomically refuse an occupied or queued resource', async () => {
const box = fixture();
const oldHome = process.env.PULLBOARD_HOME;