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.

test(relay): preserve traced checkpoint load proof [H16,C7]

Corey Olsona6f17376744c
diff --git a/test/chrome-fixture.js b/test/chrome-fixture.js
index 399c9e08..9eec3697 100644
--- a/test/chrome-fixture.js
+++ b/test/chrome-fixture.js
@@ -71,6 +71,9 @@ async function stopProcessGroup(child, stopped, timeoutMs = CLEANUP_TIMEOUT_MS)
try { process.kill(-pid, 'SIGKILL'); } catch { /* The owned process group already exited. */ }
if (!await waitForProcessGroupExit(pid, timeoutMs)) throw new Error('Isolated Chrome process group did not exit after cleanup.');
}
+ // Crash reporters/updaters may inherit stderr outside Chrome's detached group.
+ // Once every owned process is gone, stop owning that pipe rather than their lifetime.
+ child.stderr?.destroy();
if (!await waitForLeaderExit(stopped, timeoutMs)) throw new Error('Isolated Chrome did not close after its process group exited.');
}
@@ -108,6 +111,7 @@ export async function startChrome({
profileDirectory,
startupTimeoutMs = STARTUP_TIMEOUT_MS,
commandTimeoutMs = COMMAND_TIMEOUT_MS,
+ taskTimeoutMs = 25_000,
cleanupTimeoutMs = CLEANUP_TIMEOUT_MS,
env = process.env,
} = {}) {
@@ -149,6 +153,19 @@ export async function startChrome({
}
throw new Error(`Browser condition "${label}" did not arrive within ${timeoutMs}ms.`);
}
+ /** Wait for non-stream relay traffic to finish before an idle-network assertion. */
+ async function waitForRelayIdle(timeoutMs = commandTimeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ let quietSince = null;
+ while (Date.now() < deadline) {
+ if (relayRequests.size === 0) {
+ quietSince ??= Date.now();
+ if (Date.now() - quietSince >= 100) return;
+ } else quietSince = null;
+ await pause(20);
+ }
+ throw new Error(`Relay requests did not become idle within ${timeoutMs}ms.`);
+ }
/** Start asynchronous page work without holding a CDP Runtime.evaluate command open. */
async function startTask(expression, label) {
const taskId = '__pullboardFixtureTask' + ++taskSequence;
@@ -158,7 +175,7 @@ export async function startChrome({
return taskId;
}
/** Poll asynchronous page work while each DevTools command stays short. */
- async function pollTask(taskId, timeoutMs = 25_000, label = 'poll page operation') {
+ async function pollTask(taskId, timeoutMs = taskTimeoutMs, label = 'poll page operation') {
const key = JSON.stringify(taskId);
await waitFor(`window[${key}] !== null && window[${key}] !== undefined`, timeoutMs, label);
const result = await evaluate(`window[${key}]`, label + ' result');
@@ -192,6 +209,7 @@ export async function startChrome({
navigate,
evaluate,
waitFor,
+ waitForRelayIdle,
startTask,
pollTask,
send,
diff --git a/test/chrome-fixture.test.js b/test/chrome-fixture.test.js
index 6a5fbf02..b3e80db7 100644
--- a/test/chrome-fixture.test.js
+++ b/test/chrome-fixture.test.js
@@ -108,3 +108,27 @@ test('a missing DevTools port fails once with stderr and elapsed launch time [C7
});
assert.equal(readFileSync(launches, 'utf8'), 'launch\n', 'the shared launcher never retries');
});
+
+
+/** Prove an unrelated process inheriting stderr cannot keep an exited owned Chrome open. */
+test('Chrome close releases inherited stderr after its owned process group exits [C7]', async t => {
+ const directory = mkdtempSync(join(tmpdir(), 'pullboard-chrome-inherited-pipe-'));
+ const ready = join(directory, 'holder-ready');
+ const holder = `const fs = require('node:fs'); fs.writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000);`;
+ const leader = `const { spawn } = require('node:child_process');
+ const child = spawn(process.execPath, ['-e', process.argv[1], process.argv[2]], { detached: true, stdio: ['ignore', 'ignore', 'inherit'] });
+ child.unref(); process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000);`;
+ const chrome = launchChromeProcess({ executable: process.execPath, args: ['-e', leader, holder, ready] });
+ let holderPid;
+ t.after(async () => {
+ if (holderPid) { try { process.kill(holderPid, 'SIGKILL'); } catch { /* The private stand-in already stopped. */ } }
+ try { await chrome.close(); } catch { /* Retain the original close assertion on a broken implementation. */ }
+ rmSync(directory, { recursive: true, force: true });
+ });
+ await waitForFile(ready);
+ holderPid = Number(readFileSync(ready, 'utf8'));
+ const failure = await chrome.close().then(() => null, error => error);
+ assert.equal(failure, null, 'an inherited stderr holder must not prevent owned Chrome cleanup');
+ assert.doesNotThrow(() => process.kill(holderPid, 0), 'cleanup closes its pipe without killing an independent process');
+ assert.ok(chrome.child.exitCode !== null || chrome.child.signalCode !== null, 'the owned leader exited before close resolved');
+});
diff --git a/test/relay-browser-fixture.js b/test/relay-browser-fixture.js
index 36e82240..647462db 100644
--- a/test/relay-browser-fixture.js
+++ b/test/relay-browser-fixture.js
@@ -1,2 +1,11 @@
-/** Keep relay tests on the shared launcher while preserving their established local import path [C7]. */
-export { findChromeExecutable, startChrome } from './chrome-fixture.js';
+/** Relay Chrome operations share the native/network work budget [H16,C7]. */
+import { startChrome as launchChrome } from './chrome-fixture.js';
+import { relayWorkBudgetMs } from './relay-budget.js';
+export { findChromeExecutable } from './chrome-fixture.js';
+export { relayWorkBudgetMs } from './relay-budget.js';
+
+/** Give ordinary relay page work its declared native and transport allowance. */
+export async function startChrome(options = {}) {
+ return launchChrome({ startupTimeoutMs: relayWorkBudgetMs(2),
+ commandTimeoutMs: relayWorkBudgetMs(), taskTimeoutMs: relayWorkBudgetMs(), ...options });
+}
diff --git a/test/relay-browser-fixture.test.js b/test/relay-browser-fixture.test.js
index 0f42b3e0..cb919888 100644
--- a/test/relay-browser-fixture.test.js
+++ b/test/relay-browser-fixture.test.js
@@ -4,7 +4,7 @@ import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import { ENGINE_VERSION } from '../src/machine.js';
import { relayClientFixture } from './relay-client-fixture.js';
-import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
+import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';
/** Assert the fixed CDP bound reports its command context and relay-request state. */
async function stalledCommand(chrome, label, pending) {
@@ -24,7 +24,7 @@ async function stalledCommand(chrome, label, pending) {
test('real Chrome names the stalled command when a 16-second page promise exceeds the CDP bound [H16,C7]', {
skip: !findChromeExecutable() && 'Chrome is not installed',
}, async t => {
- const chrome = await startChrome();
+ const chrome = await startChrome({ commandTimeoutMs: 15000 });
t.after(() => chrome.close());
await stalledCommand(chrome, '16-second stalled-command probe', false);
const task = await chrome.startTask('new Promise(resolve => setTimeout(resolve, 16000))', 'navigation cleanup probe');
@@ -41,21 +41,22 @@ test('paired Chrome excludes idle event streams and reports only held state requ
await box.link();
const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
const key = readFileSync(box.keyFile, 'utf8').trim();
- const chrome = await startChrome();
+ const chrome = await startChrome({ commandTimeoutMs: 15000 });
t.after(() => chrome.close());
const cookie = await chrome.send('Network.setCookie', {
name: 'pb_session', value: link.token, url: box.origin, httpOnly: true, sameSite: 'Lax',
});
assert.equal(cookie.success, true);
await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);
- await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');
+ await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')', relayWorkBudgetMs());
+ await chrome.waitForRelayIdle();
await stalledCommand(chrome, 'idle paired stream probe', false);
const before = box.stateReadStarted();
box.delayStateReads(30000);
const stateTask = await chrome.startTask(`fetch(${JSON.stringify('/api/v1/boards/' + link.board + '/state')}, { credentials: 'same-origin', headers: { 'x-pullboard-engine': ${ENGINE_VERSION} } })
.then(response => response.status)`, 'held paired state read');
- const deadline = Date.now() + 5000;
+ const deadline = Date.now() + relayWorkBudgetMs(1);
while (box.stateReadStarted() === before && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));
assert.ok(box.stateReadStarted() > before, 'the authenticated state request reached the private relay');
await stalledCommand(chrome, 'held paired state probe', true);
@@ -64,3 +65,30 @@ test('paired Chrome excludes idle event streams and reports only held state requ
await stalledCommand(chrome, 'navigation-cleared paired request probe', false);
await assert.rejects(chrome.pollTask(stateTask, 250, 'state task lost to navigation'), /did not arrive within 250ms/);
});
+
+
+test('relay idle readiness waits for a real held request and then observes its completion [H16,C7]', {
+ skip: !findChromeExecutable() && 'Chrome is not installed',
+}, async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const chrome = await startChrome();
+ t.after(() => chrome.close());
+ await chrome.navigate(box.origin);
+ await chrome.waitFor('document.readyState === "complete"');
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const release = box.holdStateReads();
+ t.after(release);
+ const before = box.stateReadStarted();
+ const task = await chrome.startTask(`fetch(${JSON.stringify('/api/v1/boards/')} + ${JSON.stringify(link.board)} + '/state', {
+ headers: { authorization: 'Bearer ' + ${JSON.stringify(link.token)}, 'x-pullboard-engine': ${ENGINE_VERSION} }
+ }).then(async response => { await response.arrayBuffer(); return response.status; })`, 'idle readiness held request');
+ await chrome.waitFor('true');
+ const deadline = Date.now() + relayWorkBudgetMs(1);
+ while (box.stateReadStarted() === before && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20));
+ assert.ok(box.stateReadStarted() > before);
+ await assert.rejects(chrome.waitForRelayIdle(200), /did not become idle within 200ms/);
+ release();
+ assert.equal(await chrome.pollTask(task), 200);
+ await chrome.waitForRelayIdle();
+});
diff --git a/test/relay-budget.js b/test/relay-budget.js
new file mode 100644
index 00000000..f31928ae
--- /dev/null
+++ b/test/relay-budget.js
@@ -0,0 +1,10 @@
+/** Shared relay fixture work allowances, based on real product request bounds [H16,C7]. */
+export const RELAY_REQUEST_BOUND_MS = 10_000;
+export const NATIVE_COMMAND_BOUND_MS = 15_000;
+export const FIXTURE_SCHEDULING_MARGIN_MS = 10_000;
+export const MAX_SNAPSHOT_ATTEMPTS = 6;
+
+/** Allow native work, its declared sequential network attempts, and scheduling headroom. */
+export function relayWorkBudgetMs(requests = MAX_SNAPSHOT_ATTEMPTS) {
+ return NATIVE_COMMAND_BOUND_MS + requests * RELAY_REQUEST_BOUND_MS + FIXTURE_SCHEDULING_MARGIN_MS;
+}
diff --git a/test/relay-client-fixture.js b/test/relay-client-fixture.js
index 086d1e56..12de7f37 100644
--- a/test/relay-client-fixture.js
+++ b/test/relay-client-fixture.js
@@ -14,12 +14,13 @@ import { createRelayAuth } from '../relay/auth.js';
import { createRelayHandler } from '../relay/service.js';
import { createGitHubClient } from '../relay/github.js';
import { githubFixture } from './relay-fixture.js';
+import { RELAY_REQUEST_BOUND_MS, NATIVE_COMMAND_BOUND_MS, FIXTURE_SCHEDULING_MARGIN_MS, MAX_SNAPSHOT_ATTEMPTS } from './relay-budget.js';
const CLI = resolve(import.meta.dirname, '../bin/pullboard.js');
-const CLI_PRODUCT_DEADLINE_MS = 15_000;
-const SNAPSHOT_UPLOAD_BOUND_MS = 10_000;
-const CLI_DEADLINE_MARGIN_MS = 10_000;
-const MAX_OBSERVED_SNAPSHOT_UPLOADS = 6;
+const CLI_PRODUCT_DEADLINE_MS = NATIVE_COMMAND_BOUND_MS;
+const SNAPSHOT_UPLOAD_BOUND_MS = RELAY_REQUEST_BOUND_MS;
+const CLI_DEADLINE_MARGIN_MS = FIXTURE_SCHEDULING_MARGIN_MS;
+const MAX_OBSERVED_SNAPSHOT_UPLOADS = MAX_SNAPSHOT_ATTEMPTS;
const DEFAULT_SNAPSHOT_UPLOADS = 3;
/** Derive a private CLI child deadline from observed uploads, with a finite runaway guard. */
@@ -29,6 +30,24 @@ export function cliChildDeadlineMs(observedUploads) {
return Math.max(CLI_PRODUCT_DEADLINE_MS, observedUploads * SNAPSHOT_UPLOAD_BOUND_MS) + CLI_DEADLINE_MARGIN_MS;
}
+/** Count durable checkpoints, permitting only byte-identical retries of aborted PUTs. */
+export function assertSnapshotCheckpoints(trace, expected) {
+ const checkpoints = new Map();
+ for (const write of trace) {
+ assert.ok(Number.isSafeInteger(write.sequence) && /^[0-9a-f]{64}$/u.test(write.ciphertext ?? ''), 'checkpoint metadata is complete');
+ const previous = checkpoints.get(write.sequence);
+ if (previous) {
+ assert.equal(write.ciphertext, previous.ciphertext, 'a retried sequence preserves its exact ciphertext');
+ assert.equal(previous.abort?.name, 'TimeoutError', 'only a timed-out PUT can add a transport attempt');
+ assert.ok(write.callers.some(caller => caller.includes('async [email protected]:')), 'syncRelay retries the persisted checkpoint');
+ }
+ checkpoints.set(write.sequence, write);
+ }
+ assert.equal(checkpoints.size, expected, 'the flow publishes its exact number of distinct checkpoints');
+ assert.ok([...checkpoints.values()].every(write => write.status === 200), 'every checkpoint eventually receives an acknowledgement');
+ return checkpoints.size;
+}
+
/** Capture a real child result without exposing its private output in failure diagnostics. */
function childResult(root, env, argv, observedSnapshotUploads, initialSnapshotUploads = DEFAULT_SNAPSHOT_UPLOADS) {
return new Promise((resolveResult, reject) => {
@@ -149,10 +168,12 @@ globalThis.fetch = function tracedFetch(input, init) {
assert.ok(Number.isSafeInteger(injectedSnapshotWriteDelayMs) && injectedSnapshotWriteDelayMs >= 0 && injectedSnapshotWriteDelayMs <= 15000,
'injected snapshot delay is within the product wait bound');
let snapshotWriteDelayMs = 0;
+ let oneSnapshotDelay = null;
let snapshotWriteCount = 0;
const snapshotWriteDelays = [];
const snapshotWriteRecords = [];
let stateReadDelayMs = 0;
+ let stateReadHold = null;
let stateReadStarted = 0;
let refuseSnapshotWrites = false;
let refuseRequestWrites = false;
@@ -244,15 +265,16 @@ globalThis.fetch = function tracedFetch(input, init) {
return;
}
const stateSnapshotDelayMs = Math.max(snapshotWriteDelayMs, injectedSnapshotWriteDelayMs);
- if (stateSnapshotDelayMs && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
- const delay = stateSnapshotDelayMs;
+ if ((stateSnapshotDelayMs || oneSnapshotDelay?.count === snapshotWriteCount) && req.method === 'PUT' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
+ const delay = oneSnapshotDelay?.count === snapshotWriteCount ? oneSnapshotDelay.ms : stateSnapshotDelayMs;
const delayedAt = Date.now();
await new Promise(resolveDelay => setTimeout(resolveDelay, delay));
snapshotWriteDelays.push(Date.now() - delayedAt);
}
- if (stateReadDelayMs && req.method === 'GET' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
+ if ((stateReadDelayMs || stateReadHold) && req.method === 'GET' && /\/api\/v1\/boards\/[0-9a-f]{32}\/state$/.test(req.url ?? '')) {
stateReadStarted += 1;
- await new Promise(resolveDelay => setTimeout(resolveDelay, stateReadDelayMs));
+ if (stateReadHold) await stateReadHold;
+ else await new Promise(resolveDelay => setTimeout(resolveDelay, stateReadDelayMs));
}
if (await signIn(request, res)) return;
await api(request, res);
@@ -331,8 +353,13 @@ globalThis.fetch = function tracedFetch(input, init) {
const observedUploads = snapshotWriteCount - writesBefore;
const observedWrites = snapshotWriteRecords.slice(writesBefore);
const safeTrace = result.snapshotTrace ?? [];
- assert.equal(observedUploads, snapshotUploads,
- `private CLI child ${cliChildIndex} uploads its declared number of snapshots; client fetches: ${JSON.stringify(safeTrace)}; relay receives: ${JSON.stringify(observedWrites)}`);
+ try {
+ if (traceSnapshotWrites) assertSnapshotCheckpoints(safeTrace, snapshotUploads);
+ else assert.equal(observedUploads, snapshotUploads, 'untraced setup uploads match the plan');
+ } catch (error) {
+ error.message += `; private CLI child ${cliChildIndex}; client fetches: ${JSON.stringify(safeTrace)}; relay receives: ${JSON.stringify(observedWrites)}`;
+ throw error;
+ }
}
if (cliChildren && requestedUploads !== undefined) {
assert.equal(requestedUploads, snapshotUploads, `private CLI child ${cliChildIndex} uses its declared upload count`);
@@ -465,6 +492,11 @@ globalThis.fetch = function tracedFetch(input, init) {
assert.ok(Number.isSafeInteger(ms) && ms >= 0 && ms <= 15000, 'snapshot delay is within the product wait bound');
snapshotWriteDelayMs = ms;
},
+ /** Delay exactly one upcoming PUT to exercise the real product abort and persisted retry. */
+ delaySnapshotWriteOnce(offset, ms) {
+ assert.ok(Number.isSafeInteger(offset) && offset > 0 && Number.isSafeInteger(ms) && ms > 10000 && ms <= 15000);
+ oneSnapshotDelay = { count: snapshotWriteCount + offset, ms };
+ },
/** Return observed delays for the fixture's real snapshot endpoint. */
snapshotWriteDelays() { return [...snapshotWriteDelays]; },
/** Return sanitized per-child transport callsites and checkpoint fingerprints. */
@@ -474,6 +506,12 @@ globalThis.fetch = function tracedFetch(input, init) {
assert.ok(Number.isSafeInteger(ms) && ms >= 0 && ms <= 30000, 'state read hold is bounded');
stateReadDelayMs = ms;
},
+ /** Hold reads until the test explicitly releases them, avoiding load-sensitive short sleeps. */
+ holdStateReads() {
+ let release;
+ stateReadHold = new Promise(resolveHold => { release = resolveHold; });
+ return () => { stateReadHold = null; release(); };
+ },
/** Return how many state reads reached the private relay. */
stateReadStarted() { return stateReadStarted; },
refuseRequestWrites(value) { refuseRequestWrites = value; },
diff --git a/test/relay-person-actions.test.js b/test/relay-person-actions.test.js
index b9446e14..db2a1db5 100644
--- a/test/relay-person-actions.test.js
+++ b/test/relay-person-actions.test.js
@@ -9,8 +9,8 @@ import { executeMove } from '../src/api.js';
import { main } from '../src/cli.js';
import { decodeBoardKey, seal } from '../src/seal.js';
import { ENGINE_VERSION } from '../src/machine.js';
-import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
-import { relayClientFixture } from './relay-client-fixture.js';
+import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';
+import { assertSnapshotCheckpoints, relayClientFixture } from './relay-client-fixture.js';
/** Install only the private fixture's person cookie in the real browser. */
async function signIn(chrome, box) {
@@ -28,12 +28,10 @@ async function pairedTransport(chrome, box, title) {
await signIn(chrome, box);
await chrome.navigate(box.origin + '/#board=' + link.board + '&key=' + key);
await chrome.waitFor("document.querySelector('#chain')?.textContent.includes(" + JSON.stringify(title) + ')');
- const task = await chrome.startTask(`(async () => {
- const { createTransport } = await import('/relay/client.js');
- window.__personActionTransport = await createTransport({ onUpdate: () => {} });
- return true;
- })()`, 'initialize paired person transport');
- await chrome.pollTask(task, 25000, 'initialize paired person transport');
+ await chrome.waitFor('typeof transport?.request === "function"', relayWorkBudgetMs(), 'real page transport ready');
+ assert.equal(await chrome.evaluate(`(() => { window.__personActionTransport = transport;
+ return window.__personActionTransport === transport; })()`, 'use real paired person transport'), true,
+ 'fixture commands use the page-owned transport and its single stream queue');
return link;
}
@@ -41,7 +39,7 @@ async function pairedTransport(chrome, box, title) {
async function personAction(chrome, board, move) {
const task = await chrome.startTask('window.__personActionTransport.request('
+ JSON.stringify('/api/v1/boards/' + board + '/moves') + ',' + JSON.stringify(move) + ')', 'send person action');
- return chrome.pollTask(task, 25000, 'send person action');
+ return chrome.pollTask(task, relayWorkBudgetMs(), 'send person action');
}
/** Poll checkpoint completion separately from CDP's bounded evaluation deadline. */
@@ -50,7 +48,7 @@ async function waitRequest(chrome, board, id, status) {
const predicate = `value.state?.personRequests?.some(entry => entry.id === ${JSON.stringify(id)} && entry.status === ${JSON.stringify(status)})`;
// Product checkpoint work is bounded at 15 seconds; ten seconds remain for scheduling and polling.
const task = await chrome.startTask(`(async () => {
- const deadline = Date.now() + 25000;
+ const deadline = Date.now() + ${relayWorkBudgetMs()};
while (Date.now() < deadline) {
try {
const value = await window.__personActionTransport.request(${JSON.stringify(path)});
@@ -60,14 +58,14 @@ async function waitRequest(chrome, board, id, status) {
}
throw new Error('The native request status did not reach the paired browser.');
})()`, 'wait for native person request status');
- return chrome.pollTask(task, 30000, 'wait for native person request status');
+ return chrome.pollTask(task, relayWorkBudgetMs() + relayWorkBudgetMs(0), 'wait for native person request status');
}
/** Read the final relay state without holding Runtime.evaluate open across network work. */
async function finalState(chrome, board) {
const task = await chrome.startTask('window.__personActionTransport.request('
+ JSON.stringify('/api/v1/boards/' + board + '/state') + ')', 'read final person-action state');
- return chrome.pollTask(task, 25000, 'read final person-action state');
+ return chrome.pollTask(task, relayWorkBudgetMs(), 'read final person-action state');
}
test('real paired person adds, answers a person decision, and holds then releases a lane [H12,H16,B26]', {
@@ -177,7 +175,7 @@ test('a person action completes with late native snapshots after 8 seconds [H12,
assert.equal(status.error, undefined, 'the real native CLI completes within its product deadline plus margin');
assert.equal(status.result.code, 0, 'the real native CLI reports success');
const delays = box.snapshotWriteDelays().slice(delayedBefore);
- assert.equal(delays.length, 3, 'this three-upload status flow uploads exactly three snapshots');
+ assertSnapshotCheckpoints(status.result.snapshotTrace, 3);
assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');
const completed = await waitRequest(chrome, link.board, action.result.request.id, 'done');
assert.equal(completed.state.personRequests.find(row => row.id === action.result.request.id).status, 'done');
diff --git a/test/relay-person-outbox.test.js b/test/relay-person-outbox.test.js
index a1356b9d..92739e52 100644
--- a/test/relay-person-outbox.test.js
+++ b/test/relay-person-outbox.test.js
@@ -2,8 +2,8 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
-import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
-import { cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';
+import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';
+import { assertSnapshotCheckpoints, cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';
/** Install only the private fixture's person cookie in the real browser. */
async function signIn(chrome, box) {
@@ -27,26 +27,24 @@ async function pairedTransport(chrome, box, title) {
/** Initialize the real transport on the currently loaded document. */
async function installTransport(chrome) {
- const task = await chrome.startTask(`(async () => {
- const { createTransport } = await import('/relay/client.js');
- window.__personOutboxTransport = await createTransport({ onUpdate: () => {} });
- return true;
- })()`, 'initialize person outbox transport');
- await chrome.pollTask(task, 25000, 'initialize person outbox transport');
+ await chrome.waitFor('typeof transport?.request === "function"', relayWorkBudgetMs(), 'real page transport ready');
+ assert.equal(await chrome.evaluate(`(() => { window.__personOutboxTransport = transport;
+ return window.__personOutboxTransport === transport; })()`, 'use real person outbox transport'), true,
+ 'fixture commands use the page-owned transport and its single stream queue');
}
/** Read a final state without keeping a single DevTools evaluation open during relay work. */
async function finalState(chrome, board) {
const task = await chrome.startTask('window.__personOutboxTransport.request('
+ JSON.stringify('/api/v1/boards/' + board + '/state') + ')', 'read person outbox state');
- return chrome.pollTask(task, 25000, 'read person outbox state');
+ return chrome.pollTask(task, relayWorkBudgetMs(), 'read person outbox state');
}
/** Poll the device-decrypted outbox receipt while native status publishes its snapshot. */
async function waitForRequest(chrome, board, id, status) {
const path = '/api/v1/boards/' + board + '/state';
const task = await chrome.startTask(`(async () => {
- const deadline = Date.now() + 25000;
+ const deadline = Date.now() + ${relayWorkBudgetMs()};
while (Date.now() < deadline) {
try {
const state = await window.__personOutboxTransport.request(${JSON.stringify(path)});
@@ -56,7 +54,7 @@ async function waitForRequest(chrome, board, id, status) {
}
throw new Error('The person outbox receipt did not reach its expected status.');
})()`, 'wait for person outbox receipt');
- return chrome.pollTask(task, 30000, 'wait for person outbox receipt');
+ return chrome.pollTask(task, relayWorkBudgetMs() + relayWorkBudgetMs(0), 'wait for person outbox receipt');
}
test('real Chrome keeps an interrupted person request sealed and retries it once after reload [H12,H16,H17]', {
@@ -78,7 +76,7 @@ test('real Chrome keeps an interrupted person request sealed and retries it once
${JSON.stringify({ verb: 'shout', args: { to: 'coordinator', text } })}
)`, 'submit interrupted person request');
let interrupted;
- try { interrupted = await chrome.pollTask(interruptedTask, 25000, 'submit interrupted person request'); }
+ try { interrupted = await chrome.pollTask(interruptedTask, relayWorkBudgetMs(), 'submit interrupted person request'); }
catch (error) { interrupted = { code: error.code }; }
assert.equal(interrupted.code, 'RELAY_UNAVAILABLE');
let outbox = await chrome.evaluate(`(() => {
@@ -129,7 +127,7 @@ test('real Chrome keeps an interrupted person request sealed and retries it once
assert.ok(trace.every(write => write.callers.some(line => line.includes('publishCheckpoint'))), 'each traced upload came from checkpoint publication');
assert.equal(status.result.snapshotUploads, trace.length);
assert.equal(status.result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length), 'the child deadline follows this run’s observed upload count');
- assert.equal(delays.length, 3, 'this three-upload status flow uploads exactly three snapshots');
+ assertSnapshotCheckpoints(trace, 3);
assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');
const completed = await waitForRequest(chrome, link.board, requestId, 'done');
const exported = (await box.cli('export')).document;
diff --git a/test/relay-person-requests.test.js b/test/relay-person-requests.test.js
index ec9b6207..fcdf4823 100644
--- a/test/relay-person-requests.test.js
+++ b/test/relay-person-requests.test.js
@@ -6,11 +6,11 @@ import { join } from 'node:path';
import { test } from 'node:test';
import { decodeBoardKey, seal } from '../src/seal.js';
import { ENGINE_VERSION } from '../src/machine.js';
-import { findChromeExecutable, startChrome } from './relay-browser-fixture.js';
-import { cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';
+import { findChromeExecutable, relayWorkBudgetMs, startChrome } from './relay-browser-fixture.js';
+import { assertSnapshotCheckpoints, cliChildDeadlineMs, relayClientFixture } from './relay-client-fixture.js';
-const CHROME_START_BUDGET_MS = 30_000;
-const CLI_SETUP_MARGIN_MS = 20_000;
+const CHROME_START_BUDGET_MS = relayWorkBudgetMs(2);
+const CLI_SETUP_MARGIN_MS = relayWorkBudgetMs(0);
const FIXTURE_SETUP_CLI_CHILDREN = [
{ command: ['init'], snapshotUploads: 0 },
{ command: ['add'], snapshotUploads: 0 },
@@ -68,12 +68,10 @@ async function pairedTransport(chrome, box, title) {
/** Attach a transport handle for the existing test actions after either pairing or a reload. */
async function installRequestTransport(chrome) {
- const task = await chrome.startTask(`(async () => {
- const { createTransport } = await import('/relay/client.js');
- window.__personRequestTransport = await createTransport({ onUpdate: () => {} });
- return true;
- })()`, 'initialize person request transport');
- await chrome.pollTask(task, 25000, 'initialize person request transport');
+ await chrome.waitFor('typeof transport?.request === "function"', relayWorkBudgetMs(), 'real page transport ready');
+ assert.equal(await chrome.evaluate(`(() => { window.__personRequestTransport = transport;
+ return window.__personRequestTransport === transport; })()`, 'use real person request transport'), true,
+ 'fixture commands use the page-owned transport and its single stream queue');
}
/** Send one exact person intent through the browser transport rather than constructing a move. */
@@ -81,16 +79,16 @@ async function sendPersonIntent(chrome, board, move) {
const path = '/api/v1/boards/' + board + '/moves';
const task = await chrome.startTask('window.__personRequestTransport.request('
+ JSON.stringify(path) + ',' + JSON.stringify(move) + ')', 'send person request');
- return chrome.pollTask(task, 25000, 'send person request');
+ return chrome.pollTask(task, relayWorkBudgetMs(), 'send person request');
}
/** Poll the browser's authenticated, device-decrypted presentation for one durable receipt. */
async function waitForRequest(chrome, board, id, status, requireCoordinatorRequest = false) {
const path = '/api/v1/boards/' + board + '/state';
const predicate = `(() => { const row = documentValue.state?.personRequests?.find(entry => entry.id === ${JSON.stringify(id)}); return row?.status === ${JSON.stringify(status)}${requireCoordinatorRequest ? ' && Number.isSafeInteger(row.coordinatorRequest)' : ''}; })()`;
- // Native processing can take 15 seconds; allow ten seconds for relay transport and polling.
+ // Share the native command, bounded snapshot attempts and scheduling allowance.
const task = await chrome.startTask(`(async () => {
- const deadline = Date.now() + 25000;
+ const deadline = Date.now() + ${relayWorkBudgetMs()};
while (Date.now() < deadline) {
try {
const documentValue = await window.__personRequestTransport.request(${JSON.stringify(path)});
@@ -100,14 +98,14 @@ async function waitForRequest(chrome, board, id, status, requireCoordinatorReque
}
throw new Error('The native person request did not reach the expected status.');
})()`, 'wait for person request status');
- return chrome.pollTask(task, 30000, 'wait for person request status');
+ return chrome.pollTask(task, relayWorkBudgetMs() + relayWorkBudgetMs(0), 'wait for person request status');
}
/** Read final request state by starting the fetch in the page and polling its completion. */
async function finalState(chrome, board) {
const task = await chrome.startTask('window.__personRequestTransport.request('
+ JSON.stringify('/api/v1/boards/' + board + '/state') + ')', 'read final person request state');
- return chrome.pollTask(task, 25000, 'read final person request state');
+ return chrome.pollTask(task, relayWorkBudgetMs(), 'read final person request state');
}
/** Add a private pending spec row without changing shared or submitted repository files. */
@@ -178,7 +176,7 @@ test('real paired Chrome transports a person shout while its native snapshot is
assert.ok(trace.every(write => write.callers.some(line => line.includes('publishCheckpoint'))), 'each traced upload came from checkpoint publication');
assert.equal(status.result.snapshotUploads, trace.length);
assert.equal(status.result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length), 'the child deadline follows this run’s observed upload count');
- assert.equal(delays.length, 3, 'this three-upload status flow uploads exactly three snapshots');
+ assertSnapshotCheckpoints(trace, 3);
assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every native snapshot by 8 seconds');
const latest = await waitForRequest(chrome, link.board, receipt.result.request.id, 'done');
assert.equal(await chrome.evaluate("document.querySelector('#relay-notice').textContent"), '',
@@ -214,7 +212,7 @@ test('real paired Chrome approval remains pending until coordinator applies and
assert.equal(native.error, undefined, 'the four-upload approval status fits its derived deadline');
assert.equal(native.result.code, 0);
const delays = box.snapshotWriteDelays().slice(delayedBefore);
- assert.equal(delays.length, 4, 'the approval status flow uploads exactly four snapshots');
+ assertSnapshotCheckpoints(native.result.snapshotTrace, 4);
assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every approval snapshot by 8 seconds');
const pendingState = await waitForRequest(chrome, link.board, approval.result.request.id, 'waiting', true);
assert.equal(readFileSync(row.path, 'utf8'), before, 'the received approval records a row decision but does not edit SPEC.md');
@@ -328,7 +326,7 @@ test('coordinator decline resolves a paired approval request with a reason and l
assert.equal(native.result.snapshotUploads, trace.length);
assert.equal(native.result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length),
'the decline status deadline follows its observed uploads');
- assert.equal(delays.length, 4, 'the decline status flow uploads exactly four snapshots');
+ assertSnapshotCheckpoints(trace, 4);
assert.ok(delays.every(delay => delay >= 7900), 'the relay delayed every decline snapshot by 8 seconds');
const pending = (await finalState(chrome, link.board)).state.personRequests.find(record => record.id === queued.result.request.id);
assert.equal(pending.status, 'waiting');
@@ -345,3 +343,41 @@ test('coordinator decline resolves a paired approval request with a reason and l
assert.deepEqual((await box.cli('resume')).document.requests, [], 'the declined request leaves the open coordinator queue');
box.assertCliChildrenComplete();
});
+
+
+test('a timed-out checkpoint PUT retries identical ciphertext through the native status flow [H16,C7]', async t => {
+ const box = await relayClientFixture(t);
+ await box.link();
+ const link = JSON.parse(readFileSync(box.linkFile, 'utf8'));
+ const key = decodeBoardKey(readFileSync(box.keyFile, 'utf8').trim());
+ const intent = { version: 1, type: 'person-request', id: randomUUID(),
+ move: { verb: 'shout', args: { to: 'coordinator', text: 'RETRY_CHECKPOINT_CONTROL' } } };
+ const sealed = Buffer.from(await seal(key, new TextEncoder().encode(JSON.stringify(intent)), {
+ boardId: link.board, kind: 'request', sequence: 1,
+ })).toString('base64url');
+ const response = await fetch(box.origin + '/api/v1/boards/' + link.board + '/requests', {
+ method: 'POST', headers: { authorization: 'Bearer ' + link.token,
+ 'x-pullboard-engine': String(ENGINE_VERSION), 'content-type': 'application/json' },
+ body: JSON.stringify({ sequence: 1, sealed }),
+ });
+ assert.equal(response.status, 200);
+ const before = box.snapshotWriteRecords().length;
+ // The claim receipt times out; the nested CLI sync must resend its persisted bytes.
+ box.delaySnapshotWriteOnce(2, 10100);
+ const result = await box.cliWithSnapshotTrace(3, 'status');
+ assert.equal(result.code, 0);
+ const trace = result.snapshotTrace;
+ t.diagnostic('controlled checkpoint abort/retry: ' + JSON.stringify({ fetches: trace,
+ relayReceives: box.snapshotWriteRecords().slice(before) }));
+ assertSnapshotCheckpoints(trace, 3);
+ assert.equal(trace.length, 4, 'one product abort adds exactly one transport attempt');
+ assert.equal(trace[1].abort?.name, 'TimeoutError');
+ assert.ok(trace[1].elapsedMs >= 9900, 'the actual ten-second product request bound expired');
+ assert.equal(trace[2].sequence, trace[1].sequence);
+ assert.equal(trace[2].ciphertext, trace[1].ciphertext);
+ assert.equal(trace[2].status, 200);
+ assert.equal(result.snapshotDeadlineMs, cliChildDeadlineMs(trace.length));
+ const exported = (await box.cli('export')).document;
+ assert.equal(exported.tables.shout.filter(row => row.shout_text === 'RETRY_CHECKPOINT_CONTROL').length, 1,
+ 'the identical checkpoint retry does not execute the person intent twice');
+});