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.

fix(resources): preserve live leases and queue order [Q1,Q2,Q3]

Corey Olson4c5871d89c92
diff --git a/src/resources.js b/src/resources.js
index 5c5811cd..bcc36607 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -1,7 +1,8 @@
/** Local machine and repository resource queues with SQLite-backed leases [Q1,Q2,Q3]. */
import { mkdirSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
import { homedir } from 'node:os';
-import { dirname, join, resolve } from 'node:path';
+import { dirname, join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { DatabaseSync } from 'node:sqlite';
import { repoInfo } from './git.js';
@@ -25,28 +26,55 @@ function open(file) {
const db = new DatabaseSync(file);
db.exec(`PRAGMA busy_timeout = 10000;
CREATE TABLE IF NOT EXISTS resource (name TEXT PRIMARY KEY, capacity INTEGER NOT NULL);
- CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS holder_name ON holder(name);
- CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);
+ for (const table of ['holder', 'waiter']) {
+ const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(({ name }) => name);
+ if (!columns.includes('started')) db.exec(`ALTER TABLE ${table} ADD COLUMN started TEXT NOT NULL DEFAULT ''`);
+ }
return db;
}
-/** Treat a process as alive unless the operating system confirms that its PID is gone. */
+/** Check whether the operating system still recognizes this process ID. */
function alive(pid) {
try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
}
+/** Read the OS process start identity so a reused PID cannot inherit an old lease. */
+function processStarted(pid) {
+ try {
+ const identity = execFileSync('ps', ['-o', 'lstart=', '-o', 'stat=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim().split(/\s+/u);
+ const state = identity.pop();
+ return state?.startsWith('Z') ? '' : identity.join(' ');
+ } catch { return ''; }
+}
+
+/** Confirm that a live PID still belongs to the process recorded in the lease. */
+function sameProcess(pid, started) {
+ return Boolean(started) && alive(pid) && processStarted(pid) === started;
+}
+
+/** Return the Git root for display when the resource caller is inside a repository. */
+function repoRoot(root) {
+ try { return repoInfo(root).root; } catch { return ''; }
+}
+
/** Run a short serialized database update and discard dead or expired leases. */
function update(db, action) {
db.exec('BEGIN IMMEDIATE');
try {
const cutoff = Date.now() - LEASE_MS;
- for (const row of db.prepare('SELECT token, pid, heartbeat FROM holder').all()) {
- if (row.heartbeat < cutoff || !alive(row.pid)) db.prepare('DELETE FROM holder WHERE token = ?').run(row.token);
+ for (const row of db.prepare('SELECT token, pid, started, heartbeat FROM holder').all()) {
+ if (!alive(row.pid) || (row.heartbeat < cutoff && !sameProcess(row.pid, row.started))) {
+ db.prepare('DELETE FROM holder WHERE token = ?').run(row.token);
+ }
}
- for (const row of db.prepare('SELECT token, pid, heartbeat FROM waiter').all()) {
- if (row.heartbeat < cutoff || !alive(row.pid)) db.prepare('DELETE FROM waiter WHERE token = ?').run(row.token);
+ for (const row of db.prepare('SELECT token, pid, started, heartbeat FROM waiter').all()) {
+ if (!alive(row.pid) || (row.heartbeat < cutoff && !sameProcess(row.pid, row.started))) {
+ db.prepare('DELETE FROM waiter WHERE token = ?').run(row.token);
+ }
}
const result = action();
db.exec('COMMIT');
@@ -82,43 +110,66 @@ export async function takeResource(options) {
const token = randomUUID();
const pid = process.pid;
const agent = options.agent ?? process.env.PULLBOARD_AGENT ?? `pid-${pid}`;
- const repo = options.repo ?? (scope === 'repo' ? repoInfo(root).root : '');
- const since = new Date().toISOString();
+ const started = processStarted(pid);
+ const repo = options.repo ?? repoRoot(root);
+ let queuedAt = new Date().toISOString();
try {
update(db, () => {
const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name);
if (row && row.capacity !== capacity) throw new Refused('RESOURCE_CAPACITY_MISMATCH', `resource "${name}" already has capacity ${row.capacity}`);
db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO NOTHING').run(name, capacity);
- db.prepare('INSERT INTO waiter(token, name, pid, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, agent, repo, since, Date.now());
+ db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now());
});
while (true) {
const acquired = update(db, () => {
+ const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);
+ if (!waiter) {
+ queuedAt = new Date().toISOString();
+ db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now());
+ return { acquired: false, state: { ...snapshot(db, name), position: db.prepare('SELECT count(*) AS count FROM waiter WHERE name = ?').get(name).count, rejoined: true } };
+ }
db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);
const spot = snapshot(db, name);
- const position = db.prepare('SELECT count(*) AS count FROM waiter WHERE name = ? AND ticket <= (SELECT ticket FROM waiter WHERE token = ?)').get(name, token).count;
+ const position = db.prepare('SELECT count(*) AS count FROM waiter WHERE name = ? AND ticket <= ?').get(name, waiter.ticket).count;
const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;
if (position === 1 && spot.holders.length < limit) {
db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
- db.prepare('INSERT INTO holder(token, name, pid, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, agent, repo, since, Date.now());
+ const acquiredAt = new Date().toISOString();
+ db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now());
return { acquired: true, state: { ...spot, position: 0 } };
}
return { acquired: false, state: { ...spot, position } };
});
if (acquired.acquired) {
let released = false;
+ let lost = false;
const heartbeat = setInterval(() => {
- if (released) return;
- try { update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token)); } catch { /* Lease expiry remains the crash fallback. */ }
+ if (released || lost) return;
+ try {
+ const changed = update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token).changes);
+ if (!changed) { lost = true; clearInterval(heartbeat); }
+ } catch { /* Lease expiry remains the crash fallback. */ }
}, HEARTBEAT_MS);
heartbeat.unref();
+ /** Release the resource and close its SQLite handle. */
const release = () => {
if (released) return;
released = true;
clearInterval(heartbeat);
- update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token));
- db.close();
+ try { update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token)); }
+ finally { db.close(); }
+ };
+ /** Refresh this lease, or refuse if another process already evicted it. */
+ const renew = () => {
+ if (released || lost) throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);
+ const changed = update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token).changes);
+ if (!changed) {
+ lost = true;
+ clearInterval(heartbeat);
+ throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);
+ }
};
- return { name, scope, token, release, renew: () => update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token)) };
+ return { name, scope, token, release, renew };
}
options.onWait?.(acquired.state);
await pause(POLL_MS);
diff --git a/test/resources.test.js b/test/resources.test.js
index d7e51a3f..1d07b581 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -1,23 +1,39 @@
/** Real-process resource queue and lease coverage [Q1,Q2,Q3]. */
import assert from 'node:assert/strict';
import { spawn, spawnSync } from 'node:child_process';
-import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, realpathSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { createInterface } from 'node:readline';
-import { once } from 'node:events';
import { after, test } from 'node:test';
+import { DatabaseSync } from 'node:sqlite';
+import { listResources } from '../src/resources.js';
const TEMP = [];
+const CHILDREN = new Set();
const MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;
const WORKER = `
import { takeResource } from ${JSON.stringify(MODULE)};
-const [name, capacity, scope, root, agent] = process.argv.slice(1);
-const lease = await takeResource({ name, capacity: Number(capacity), scope, root, agent, onWait: ({position, holders}) => console.log(JSON.stringify({waiting:position, holders})) });
+const [name, capacity, scope, root, agent, stallMs] = process.argv.slice(1);
+let lastWait = '';
+const lease = await takeResource({ name, capacity: Number(capacity), scope, root, agent, onWait: ({position, holders, line, rejoined}) => {
+ const state = JSON.stringify({waiting:position, holders, line, rejoined:rejoined ?? false});
+ if (!lastWait || rejoined) { lastWait = state; console.log(state); }
+} });
console.log(JSON.stringify({acquired:agent}));
+if (Number(stallMs) > 0) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Number(stallMs));
+ console.log(JSON.stringify({resumed:true}));
+}
process.stdin.setEncoding('utf8');
-for await (const line of process.stdin) { if (line.trim() === 'release') { lease.release(); break; } }
+for await (const line of process.stdin) {
+ if (line.trim() === 'renew') {
+ try { lease.renew(); console.log(JSON.stringify({renewed:true})); }
+ catch (error) { console.log(JSON.stringify({renewError:error.code})); }
+ }
+ if (line.trim() === 'release') { lease.release(); break; }
+}
`;
/** Create isolated machine storage and a pair of real Git repositories. */
@@ -35,25 +51,66 @@ function fixture() {
return { dir, home, first, second, env: { ...process.env, PULLBOARD_HOME: home } };
}
+/** Force a stale private fixture row with a mismatched process start identity. */
+function staleIdentity(box, table, agent) {
+ assert.ok(['holder', 'waiter'].includes(table));
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ try {
+ const result = db.prepare(`UPDATE ${table} SET started = ?, heartbeat = 0 WHERE agent = ?`).run('old-process-start', agent);
+ assert.equal(result.changes, 1, `${agent} has a private ${table} row`);
+ } finally { db.close(); }
+}
+
+/** Read a private machine database without changing the process environment for other fixtures. */
+function privateList(box, scope = 'machine', root = process.cwd()) {
+ const previous = process.env.PULLBOARD_HOME;
+ process.env.PULLBOARD_HOME = box.home;
+ try { return listResources({ scope, root }); }
+ finally {
+ if (previous === undefined) delete process.env.PULLBOARD_HOME;
+ else process.env.PULLBOARD_HOME = previous;
+ }
+}
+
/** Launch one independent process that takes a resource and waits for a release command. */
-function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = box.first, agent }) {
- const child = spawn(process.execPath, ['--input-type=module', '-e', WORKER, name, String(capacity), scope, root, agent], {
+function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = box.first, agent, stallMs = 0 }) {
+ const child = spawn(process.execPath, ['--input-type=module', '-e', WORKER, name, String(capacity), scope, root, agent, String(stallMs)], {
env: box.env, stdio: ['pipe', 'pipe', 'pipe'],
});
child.lines = createInterface({ input: child.stdout });
child.errors = '';
+ child.pendingLines = [];
+ child.lineWaiters = [];
+ child.exitResult = null;
+ child.finished = new Promise((resolveExit) => child.once('exit', (code, signal) => {
+ child.exitResult = { code, signal };
+ CHILDREN.delete(child);
+ for (const waiter of child.lineWaiters.splice(0)) {
+ clearTimeout(waiter.timer);
+ waiter.reject(new Error(`worker exited ${code}/${signal}: ${child.errors}`));
+ }
+ resolveExit(child.exitResult);
+ }));
child.stderr.setEncoding('utf8').on('data', (chunk) => { child.errors += chunk; });
+ child.lines.on('line', (line) => {
+ const waiter = child.lineWaiters.shift();
+ if (waiter) { clearTimeout(waiter.timer); waiter.resolve(line); }
+ else child.pendingLines.push(line);
+ });
+ CHILDREN.add(child);
return child;
}
/** Read the next worker event, failing promptly with its stderr if it exits unexpectedly. */
-async function event(child) {
+async function event(child, timeoutMs = 10_000) {
+ if (child.pendingLines.length) return JSON.parse(child.pendingLines.shift());
+ if (child.exitResult) throw new Error(`worker exited ${child.exitResult.code}/${child.exitResult.signal}: ${child.errors}`);
const line = await new Promise((resolveLine, reject) => {
- const onLine = (value) => { clearTimeout(timer); child.removeListener('exit', onExit); resolveLine(value); };
- const onExit = (code, signal) => { clearTimeout(timer); child.lines.removeListener('line', onLine); reject(new Error(`worker exited ${code}/${signal}: ${child.errors}`)); };
- const timer = setTimeout(() => { child.lines.removeListener('line', onLine); child.removeListener('exit', onExit); reject(new Error(`worker timed out: ${child.errors}`)); }, 10_000);
- child.lines.once('line', onLine);
- child.once('exit', onExit);
+ const waiter = { resolve: resolveLine, reject, timer: setTimeout(() => {
+ child.lineWaiters.splice(child.lineWaiters.indexOf(waiter), 1);
+ reject(new Error(`worker timed out: ${child.errors}`));
+ }, timeoutMs) };
+ child.lineWaiters.push(waiter);
});
return JSON.parse(line);
}
@@ -61,30 +118,47 @@ async function event(child) {
/** Ask a holder to release and wait for clean process exit. */
async function release(child) {
child.stdin.end('release\n');
- const [code] = await once(child, 'exit');
+ const { code } = await child.finished;
child.lines.close();
assert.equal(code, 0, child.errors);
}
-after(() => TEMP.forEach((dir) => rmSync(dir, { recursive: true, force: true })));
+/** Kill and reap every fixture worker before deleting its private files. */
+after(async () => {
+ const running = [...CHILDREN];
+ for (const child of running) if (!child.exitResult) child.kill('SIGKILL');
+ await Promise.all(running.map((child) => child.finished));
+ for (const child of running) child.lines.close();
+ TEMP.forEach((dir) => rmSync(dir, { recursive: true, force: true }));
+});
test('[Q1,Q2] capacity-one takers acquire in strict FIFO arrival order', async () => {
const box = fixture();
const holder = worker(box, { agent: 'holder' });
assert.equal((await event(holder)).acquired, 'holder');
const waiting = [];
+ let firstQueuedAt = 0;
for (const agent of ['first', 'second', 'third']) {
const child = worker(box, { agent });
waiting.push(child);
const state = await event(child);
assert.equal(state.waiting, waiting.length, `${agent} reports its FIFO place`);
assert.equal(state.holders[0].agent, 'holder', `${agent} says who holds the place`);
+ if (agent === 'first') {
+ assert.equal(state.holders[0].repo, realpathSync(box.first), 'machine-scope listings still identify the Git root');
+ firstQueuedAt = Date.parse(state.line[0].since);
+ assert.ok(Number.isFinite(firstQueuedAt));
+ }
}
const order = [];
let current = holder;
for (const [index, child] of waiting.entries()) {
await release(current);
assert.equal((await event(child)).acquired, ['first', 'second', 'third'][index]);
+ if (index === 0) {
+ const displayed = privateList(box).find((resource) => resource.name === 'gate').holders[0];
+ assert.ok(Date.parse(displayed.since) > firstQueuedAt, 'holder since is when capacity was acquired, not when it joined the queue');
+ }
order.push(['first', 'second', 'third'][index]);
current = child;
}
@@ -92,6 +166,63 @@ test('[Q1,Q2] capacity-one takers acquire in strict FIFO arrival order', async (
assert.deepEqual(order, ['first', 'second', 'third']);
});
+test('[Q1,Q2] capacity two admits two holders and serves the next waiter', async () => {
+ const box = fixture();
+ const first = worker(box, { name: 'two-slots', capacity: 2, agent: 'first-holder' });
+ const second = worker(box, { name: 'two-slots', capacity: 2, agent: 'second-holder' });
+ assert.equal((await event(first)).acquired, 'first-holder');
+ assert.equal((await event(second)).acquired, 'second-holder');
+ const next = worker(box, { name: 'two-slots', capacity: 2, agent: 'next-waiter' });
+ assert.equal((await event(next)).waiting, 1);
+ await release(first);
+ assert.equal((await event(next)).acquired, 'next-waiter');
+ await release(second);
+ await release(next);
+});
+
+test('[Q2,Q3] an evicted live waiter rejoins the FIFO line after it resumes [Q2,Q3]', async () => {
+ const box = fixture();
+ const holder = worker(box, { agent: 'holder' });
+ assert.equal((await event(holder)).acquired, 'holder');
+ const waiter = worker(box, { agent: 'resumed-waiter' });
+ assert.equal((await event(waiter)).waiting, 1);
+ waiter.kill('SIGSTOP');
+ staleIdentity(box, 'waiter', 'resumed-waiter');
+ assert.deepEqual(privateList(box)[0].line, []);
+ waiter.kill('SIGCONT');
+ const rejoined = await event(waiter);
+ assert.equal(rejoined.rejoined, true);
+ assert.equal(rejoined.waiting, 1);
+ await release(holder);
+ assert.equal((await event(waiter)).acquired, 'resumed-waiter');
+ await release(waiter);
+});
+
+test('[Q3] a live stalled holder keeps its place beyond the lease timeout', async () => {
+ const box = fixture();
+ const holder = worker(box, { agent: 'stalled-holder', stallMs: 22_000 });
+ assert.equal((await event(holder)).acquired, 'stalled-holder');
+ const waiter = worker(box, { agent: 'queued-behind-live-holder' });
+ assert.equal((await event(waiter)).waiting, 1);
+ await assert.rejects(event(waiter, 20_500), /worker timed out/u, 'a live OS process must not be evicted when its heartbeat pauses');
+ assert.equal((await event(holder, 5_000)).resumed, true);
+ await release(holder);
+ assert.equal((await event(waiter)).acquired, 'queued-behind-live-holder');
+ await release(waiter);
+});
+
+test('[Q3] renew refuses after an OS start-identity mismatch evicts the holder', async () => {
+ const box = fixture();
+ const holder = worker(box, { agent: 'evicted-holder' });
+ assert.equal((await event(holder)).acquired, 'evicted-holder');
+ staleIdentity(box, 'holder', 'evicted-holder');
+ assert.deepEqual(privateList(box)[0].holders, []);
+ holder.stdin.write('renew\n');
+ assert.equal((await event(holder)).renewError, 'RESOURCE_LEASE_LOST');
+ holder.stdin.end('release\n');
+ assert.equal((await holder.finished).code, 0, holder.errors);
+});
+
test('[Q3] SIGKILL of a holder frees its lease for the next process', async () => {
const box = fixture();
const holder = worker(box, { agent: 'doomed-holder' });
@@ -100,7 +231,7 @@ test('[Q3] SIGKILL of a holder frees its lease for the next process', async () =
const waiting = await event(next);
assert.equal(waiting.waiting, 1);
holder.kill('SIGKILL');
- await once(holder, 'exit');
+ await holder.finished;
assert.equal((await event(next)).acquired, 'successor');
await release(next);
});
@@ -114,7 +245,7 @@ test('[Q2,Q3] a SIGKILLed waiter is skipped while the next live waiter advances'
const live = worker(box, { agent: 'live-waiter' });
assert.equal((await event(live)).waiting, 2);
dead.kill('SIGKILL');
- await once(dead, 'exit');
+ await dead.finished;
await release(holder);
assert.equal((await event(live)).acquired, 'live-waiter');
await release(live);