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): normalize process identity across environments [Q3]

Corey Olson101b4da8b792
diff --git a/src/resources.js b/src/resources.js
index bcc36607..d35a8265 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -11,6 +11,8 @@ import { Refused } from './refused.js';
const LEASE_MS = 20_000;
const HEARTBEAT_MS = 3_000;
const POLL_MS = 40;
+const PROCESS_IDENTITY_CACHE_MS = 3_000;
+const processIdentities = new Map();
/** Resolve the local database for the requested scope. */
function databaseFile(scope, root) {
@@ -24,15 +26,28 @@ function databaseFile(scope, root) {
function open(file) {
mkdirSync(dirname(file), { recursive: true });
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, 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, 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 ''`);
+ db.exec('PRAGMA busy_timeout = 10000');
+ let transaction = false;
+ try {
+ db.exec('BEGIN IMMEDIATE');
+ transaction = true;
+ db.exec(`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, 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, 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 ''`);
+ }
+ db.exec('COMMIT');
+ transaction = false;
+ } catch (error) {
+ if (transaction) {
+ try { db.exec('ROLLBACK'); } catch { /* Preserve the migration error. */ }
+ }
+ db.close();
+ throw error;
}
return db;
}
@@ -42,18 +57,42 @@ 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) {
+/** Read a stable OS process identity; an unreadable identity is unknown, not proof of death. */
+function processIdentity(pid) {
+ const cached = processIdentities.get(pid);
+ if (cached && Date.now() - cached.checkedAt < PROCESS_IDENTITY_CACHE_MS) return cached.identity;
+ let identity = null;
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 ''; }
+ const output = execFileSync('/bin/ps', ['-o', 'lstart=', '-o', 'stat=', '-p', String(pid)], {
+ encoding: 'utf8',
+ env: { ...process.env, TZ: 'UTC', LC_ALL: 'C', LANG: 'C' },
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+ const fields = output.split(/\s+/u);
+ const state = fields.pop();
+ if (fields.length) identity = { started: fields.join(' '), zombie: state?.startsWith('Z') ?? false };
+ } catch { /* A live PID remains authoritative when the OS identity utility is unavailable. */ }
+ processIdentities.set(pid, { identity, checkedAt: Date.now() });
+ if (processIdentities.size > 1024) {
+ for (const [cachedPid, entry] of processIdentities) {
+ if (Date.now() - entry.checkedAt >= PROCESS_IDENTITY_CACHE_MS) processIdentities.delete(cachedPid);
+ }
+ }
+ return identity;
+}
+
+/** Read the start identity to store with a lease when the OS can provide it. */
+function processStarted(pid) {
+ return processIdentity(pid)?.started ?? '';
}
/** 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;
+ if (!alive(pid)) return false;
+ const identity = processIdentity(pid);
+ if (!identity) return true;
+ if (identity.zombie) return false;
+ return !started || identity.started === started;
}
/** Return the Git root for display when the resource caller is inside a repository. */
diff --git a/test/resources.test.js b/test/resources.test.js
index 1d07b581..4a2db3d1 100644
--- a/test/resources.test.js
+++ b/test/resources.test.js
@@ -51,6 +51,19 @@ function fixture() {
return { dir, home, first, second, env: { ...process.env, PULLBOARD_HOME: home } };
}
+/** Create the previous private queue schema so simultaneous openers exercise its migration. */
+function oldSchema(box) {
+ mkdirSync(box.home, { recursive: true });
+ const db = new DatabaseSync(join(box.home, 'resources.sqlite'));
+ try {
+ db.exec(`CREATE TABLE resource (name TEXT PRIMARY KEY, capacity INTEGER NOT NULL);
+ CREATE TABLE 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 INDEX holder_name ON holder(name);
+ CREATE TABLE 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 INDEX waiter_name_ticket ON waiter(name, ticket);`);
+ } finally { db.close(); }
+}
+
/** Force a stale private fixture row with a mismatched process start identity. */
function staleIdentity(box, table, agent) {
assert.ok(['holder', 'waiter'].includes(table));
@@ -73,9 +86,9 @@ function privateList(box, scope = 'machine', root = process.cwd()) {
}
/** 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, stallMs = 0 }) {
+function worker(box, { name = 'gate', capacity = 1, scope = 'machine', root = box.first, agent, stallMs = 0, env = {} }) {
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'],
+ env: { ...box.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'],
});
child.lines = createInterface({ input: child.stdout });
child.errors = '';
@@ -180,6 +193,24 @@ test('[Q1,Q2] capacity two admits two holders and serves the next waiter', async
await release(next);
});
+test('[Q2,Q3] a stopped head waiter keeps its place ahead of the next process', async () => {
+ const box = fixture();
+ const holder = worker(box, { agent: 'holder' });
+ assert.equal((await event(holder)).acquired, 'holder');
+ const first = worker(box, { agent: 'stopped-first' });
+ assert.equal((await event(first)).waiting, 1);
+ first.kill('SIGSTOP');
+ const second = worker(box, { agent: 'second' });
+ assert.equal((await event(second)).waiting, 2);
+ await release(holder);
+ await assert.rejects(event(second, 800), /worker timed out/u, 'the second waiter cannot jump the stopped head');
+ first.kill('SIGCONT');
+ assert.equal((await event(first)).acquired, 'stopped-first');
+ await release(first);
+ assert.equal((await event(second)).acquired, 'second');
+ await release(second);
+});
+
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' });
@@ -200,9 +231,9 @@ test('[Q2,Q3] an evicted live waiter rejoins the FIFO line after it resumes [Q2,
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 });
+ const holder = worker(box, { agent: 'stalled-holder', stallMs: 22_000, env: { TZ: 'UTC' } });
assert.equal((await event(holder)).acquired, 'stalled-holder');
- const waiter = worker(box, { agent: 'queued-behind-live-holder' });
+ const waiter = worker(box, { agent: 'queued-behind-live-holder', env: { TZ: 'Pacific/Honolulu', PATH: '/usr/bin' } });
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);
@@ -211,6 +242,15 @@ test('[Q3] a live stalled holder keeps its place beyond the lease timeout', asyn
await release(waiter);
});
+test('[Q3] concurrent openers serialize migration of a prior resource database', async () => {
+ const box = fixture();
+ oldSchema(box);
+ const workers = Array.from({ length: 8 }, (_, index) => worker(box, { name: 'legacy', capacity: 8, agent: `migrator-${index}` }));
+ const acquired = await Promise.all(workers.map((child) => event(child)));
+ assert.deepEqual(acquired.map(({ acquired: agent }) => agent).sort(), workers.map((_, index) => `migrator-${index}`).sort());
+ await Promise.all(workers.map(release));
+});
+
test('[Q3] renew refuses after an OS start-identity mismatch evicts the holder', async () => {
const box = fixture();
const holder = worker(box, { agent: 'evicted-holder' });