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(relay): seal checkpoints outside the lock; claims expire [H5]

Corey Olson8b12f3a3f993
diff --git a/src/relay-checkpoint-worker.js b/src/relay-checkpoint-worker.js
index 264da2f8..328aebba 100644
--- a/src/relay-checkpoint-worker.js
+++ b/src/relay-checkpoint-worker.js
@@ -5,8 +5,8 @@
*
* Usage (spawned by scheduleCheckpoint): node relay-checkpoint-worker.js <root> <relay link file>
*/
-import { appendFileSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { alive, checkpointFiles, checkpointQuietMs } from './relay-checkpoint.js';
+import { appendFileSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
+import { checkpointFiles, checkpointQuietMs, publisherHolding } from './relay-checkpoint.js';
import { publishLatestCheckpoint } from './relay.js';
const [root, file] = process.argv.slice(2);
@@ -23,9 +23,8 @@ function claim() {
try { writeFileSync(pid, `${process.pid}\n`, { flag: 'wx', mode: 0o600 }); return true; }
catch (error) {
if (error.code !== 'EEXIST') throw error;
- let holder = 0;
- try { holder = Number(readFileSync(pid, 'utf8')); } catch { /* Gone between the two reads: try again. */ }
- if (alive(holder) && holder !== process.pid) return false;
+ const holder = publisherHolding(pid);
+ if (holder && holder !== process.pid) return false;
rmSync(pid, { force: true });
}
}
@@ -42,6 +41,8 @@ const io = {
async function publishUntilQuiet() {
const quiet = checkpointQuietMs();
for (;;) {
+ // Refresh the claim, so a scheduler never takes this live publisher for a dead one.
+ try { utimesSync(pid, new Date(), new Date()); } catch { /* A removed claim is re-made by the next pass. */ }
const moved = lastMove();
const wait = quiet - (Date.now() - moved);
if (wait > 0) { await new Promise(next => setTimeout(next, wait)); continue; }
diff --git a/src/relay-checkpoint.js b/src/relay-checkpoint.js
index e7f59eea..1b26635d 100644
--- a/src/relay-checkpoint.js
+++ b/src/relay-checkpoint.js
@@ -8,7 +8,7 @@
* keeps one upload in flight; moves during an upload are covered by the next one.
*/
import { spawn } from 'node:child_process';
-import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { readFileSync, statSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -52,6 +52,25 @@ export function checkpointFiles(file) {
return { due: join(directory, 'relay-checkpoint.due'), pid: join(directory, 'relay-checkpoint.pid'), log: join(directory, 'relay-checkpoint.log') };
}
+// Budget: a publisher refreshes its claim on every pass, far more often than this; an older claim belongs to a
+// process that died and whose number may since have been reused.
+const CLAIM_STALE_MS = 600_000;
+
+/**
+ * The live publisher holding a board's claim, or 0: a claim counts only while its process lives and it was
+ * refreshed recently, so a reused process number never keeps the board without a publisher.
+ *
+ * @param {string} pidFile
+ * @returns {number}
+ */
+export function publisherHolding(pidFile) {
+ try {
+ if (Date.now() - statSync(pidFile).mtimeMs > CLAIM_STALE_MS) return 0;
+ const holder = Number(readFileSync(pidFile, 'utf8'));
+ return alive(holder) ? holder : 0;
+ } catch { return 0; }
+}
+
/** Whether a process is alive; a process another user owns still is. */
export function alive(pid) {
if (!Number.isSafeInteger(pid) || pid < 1) return false;
@@ -69,8 +88,7 @@ export function alive(pid) {
export function scheduleCheckpoint(root, file) {
const { due, pid } = checkpointFiles(file);
writeFileSync(due, `${Date.now()}\n`, { mode: 0o600 });
- const holder = existsSync(pid) ? Number(readFileSync(pid, 'utf8')) : 0;
- if (alive(holder)) return;
+ if (publisherHolding(pid)) return;
const child = spawn(process.execPath, [WORKER, root, file], { cwd: root, detached: true, stdio: 'ignore', env: process.env });
child.unref();
}
diff --git a/src/relay.js b/src/relay.js
index b8c3bf64..f18458c7 100644
--- a/src/relay.js
+++ b/src/relay.js
@@ -864,8 +864,26 @@ async function replayRelayRecord(board, key, state, record) {
}
}
-/** Persist the exact checkpoint before uploading, so a lost reply retries identical ciphertext. */
-async function publishCheckpoint(root, file, state, io) {
+/**
+ * Read and seal this board's checkpoint: the expensive part of publishing, which needs no relay lock.
+ *
+ * @param {string} root
+ * @param {any} state - The relay link, for the board's identity and key.
+ * @returns {Promise<{ sequence: number, digest: string, sealed: string }>}
+ */
+async function prepareCheckpoint(root, state) {
+ const document = relaySnapshot(root);
+ const sequence = Number(document.tables.board_meta.find((row) => row.meta_key === 'relay_applied_sequence')?.meta_value ?? 0);
+ return { sequence, digest: presentationDigest(document.presentation),
+ sealed: await sealedRecord(readBoardKey(state.board), document, state, 'snapshot', sequence) };
+}
+
+/**
+ * Persist the exact checkpoint before uploading, so a lost reply retries identical ciphertext. `prepared`, sealed
+ * outside the lock by the background publisher, stands in for reading the board again; an older one never replaces
+ * a newer saved checkpoint.
+ */
+async function publishCheckpoint(root, file, state, io, prepared = null) {
if (!state.token?.startsWith('pm_') || process.env.PULLBOARD_RELAY_TOKEN) return;
const resumed = Boolean(state.checkpointRefusal);
if (state.checkpointRefusal && uploadPauseType(state.checkpointRefusal)) {
@@ -875,13 +893,11 @@ async function publishCheckpoint(root, file, state, io) {
delete state.checkpointRefusal;
saveLink(file, state);
} else {
- const document = relaySnapshot(root);
- const sequence = Number(document.tables.board_meta.find((row) => row.meta_key === 'relay_applied_sequence')?.meta_value ?? 0);
- const digest = presentationDigest(document.presentation);
- if (!state.checkpoint || state.checkpoint.sequence !== sequence || state.checkpointPresentationDigest !== digest) {
+ const fresh = prepared && !(state.checkpoint?.sequence > prepared.sequence) ? prepared : await prepareCheckpoint(root, state);
+ if (!state.checkpoint || state.checkpoint.sequence !== fresh.sequence || state.checkpointPresentationDigest !== fresh.digest) {
delete state.checkpointRefusal;
- state.checkpointPresentationDigest = digest;
- state.checkpoint = { sequence, sealed: await sealedRecord(readBoardKey(state.board), document, state, 'snapshot', sequence) };
+ state.checkpointPresentationDigest = fresh.digest;
+ state.checkpoint = { sequence: fresh.sequence, sealed: fresh.sealed };
saveLink(file, state);
}
// A definitive rejection retries only a fresh image after the board changes.
@@ -905,8 +921,9 @@ async function publishCheckpoint(root, file, state, io) {
}
/**
- * Publish this board's checkpoint once, under the relay lock: the background publisher's one step (#1014). A board
- * whose link is gone or being removed publishes nothing.
+ * Publish this board's checkpoint once: the background publisher's one step (#1014). The board is read and sealed
+ * before the relay lock; only saving and uploading the sealed record hold it, since the upload may record the relay's
+ * API version and storage in the link. A board whose link is gone or being removed publishes nothing.
*
* @param {string} root
* @param {{ err: (line: string) => void, say: (line: string) => void }} io
@@ -914,10 +931,14 @@ async function publishCheckpoint(root, file, state, io) {
*/
export async function publishLatestCheckpoint(root, io) {
const file = linkFile(root);
+ const linked = loadLink(file);
+ if (!linked || linked.unlinking) return false;
+ // Reading and sealing a large board takes about a second; it happens before the lock, so moves never wait on it.
+ const prepared = await prepareCheckpoint(root, linked);
return locked(file, async () => {
const state = loadLink(file);
- if (!state || state.unlinking) return false;
- await publishCheckpoint(root, file, state, io);
+ if (!state || state.unlinking || state.board !== linked.board) return false;
+ await publishCheckpoint(root, file, state, io, prepared);
return true;
}, io);
}