Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Bound blocked publication waits with recovery evidence

[._.]/ Adam Eivyf14c7134e733
diff --git a/docs/BACKUP_PUBLICATION_ADMISSION.md b/docs/BACKUP_PUBLICATION_ADMISSION.md
index 87d100c8bf..8bae6524ff 100644
--- a/docs/BACKUP_PUBLICATION_ADMISSION.md
+++ b/docs/BACKUP_PUBLICATION_ADMISSION.md
@@ -10,7 +10,10 @@ separate leases while their parent remains admitted.
A snapshot or live restore atomically creates `data/backup-admission/cut/`, then
drains every registered publication before reading or replacing either store.
-New publications wait until the cut owner releases it. Readers register before
+New publications wait until the cut owner releases it, for at most two minutes
+by default (`withBackupAssetPublication(work, { timeoutMs })` can set a shorter
+caller deadline). Expiry rejects with `BACKUP_SNAPSHOT_BUSY`, the cut ownership
+and recovery path; no publication callback runs and the cut remains intact. Readers register before
checking the cut; the cut registers before checking readers. This ordering closes
the cross-process admission race. A preliminary gate check avoids registering
and deleting leases repeatedly during a long snapshot. Directory creation and
diff --git a/server/lib/backupSharedAdmission.test.js b/server/lib/backupSharedAdmission.test.js
index e596016fe7..bb26617dc3 100644
--- a/server/lib/backupSharedAdmission.test.js
+++ b/server/lib/backupSharedAdmission.test.js
@@ -29,7 +29,7 @@ const childSource = `
process.send({ type: 'entered' });
await done;
await writeFile(join(root, 'data', 'metadata.json'), JSON.stringify({ output: process.env.ADMISSION_TEST_VALUE }));
- });
+ }, { timeoutMs: Number(process.env.ADMISSION_TEST_TIMEOUT || 5000) });
} else {
const release = await acquireBackupSnapshotCut({ timeoutMs: Number(process.env.ADMISSION_TEST_TIMEOUT || 5000) });
process.send({ type: 'entered' });
@@ -38,7 +38,7 @@ const childSource = `
release(); // stale duplicate releases must be harmless
}
process.send({ type: 'finished' });
- } catch (error) { process.send({ type: 'rejected', code: error.code, message: error.message, blockers: error.blockers }); }
+ } catch (error) { process.send({ type: 'rejected', code: error.code, message: error.message, blockers: error.blockers, owner: error.owner, recoveryPath: error.recoveryPath }); }
`;
async function root() {
const path = await mkdtemp(join(tmpdir(), 'backup-shared-race-'));
@@ -161,6 +161,25 @@ describe('shared snapshot admission between real server and runner processes', (
expect(await contender.next('rejected')).toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY', message: expect.stringContaining('reconcile the interrupted backup or restore') });
const gate = JSON.parse(await readFile(join(path, 'data/backup-admission/cut/owner.json'), 'utf8'));
expect(gate.pid).toBe(owner.proc.pid);
+ const writer = worker(path, 'publication', 'must not write', 50);
+ expect(await writer.next('rejected')).toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY',
+ owner: { id: gate.id, pid: owner.proc.pid }, recoveryPath: join(path, 'data/backup-admission/cut') });
+ expect(writer.messages.some(message => message.type === 'entered')).toBe(false);
+ expect(existsSync(join(path, 'data/output.txt'))).toBe(false);
+ expect(JSON.parse(await readFile(join(path, 'data/backup-admission/cut/owner.json'), 'utf8'))).toEqual(gate);
+ });
+
+ it('refuses a child publication after bounded wait on corrupt cut ownership without changing it', async () => {
+ const path = await root();
+ const cutPath = join(path, 'data/backup-admission/cut');
+ await mkdir(cutPath, { recursive: true });
+ await writeFile(join(cutPath, 'owner.json'), '{broken');
+ const writer = worker(path, 'publication', 'must not write', 50);
+ expect(await writer.next('rejected')).toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY',
+ owner: { path: cutPath, unreadable: true }, recoveryPath: cutPath });
+ expect(writer.messages.some(message => message.type === 'entered')).toBe(false);
+ expect(existsSync(join(path, 'data/output.txt'))).toBe(false);
+ expect(await readFile(join(cutPath, 'owner.json'), 'utf8')).toBe('{broken');
});
it('fails closed on unreadable ownership and refuses a stale release', async () => {
diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.js
index 256d685e97..acea16cf18 100644
--- a/server/lib/backupSnapshotBoundary.js
+++ b/server/lib/backupSnapshotBoundary.js
@@ -8,7 +8,7 @@ import { backupSharedAdmission } from './backupSharedAdmission.js';
*
* Database maintenance shares the boundary. A cut is refused while a maintenance
* fence is up, and maintenance that must not observe or replace a half-published
- * pair takes the same cut around its own destructive step. Publication itself is
+ * pair takes the same cut around its own destructive step. Publication itself
* waits for a snapshot; unreadable ownership fails closed. Under a database
* fence the database already rejects the row write.
* Every retryable refusal carries BACKUP_SNAPSHOT_BUSY.
@@ -33,21 +33,48 @@ function releasePublications() {
}
/** Hold one admission across an entire file-plus-row workflow. Nested calls reuse it. */
-export async function withBackupAssetPublication(work) {
- return maintenance.continueSettlement(() => withAdmittedBackupAssetPublication(work));
+export async function withBackupAssetPublication(work, { timeoutMs = DEFAULT_DRAIN_TIMEOUT_MS } = {}) {
+ return maintenance.continueSettlement(() => withAdmittedBackupAssetPublication(work, timeoutMs));
}
-async function withAdmittedBackupAssetPublication(work) {
+function publicationTimeoutError() {
+ let owner;
+ try { owner = backupSharedAdmission.status().cut; }
+ catch (error) { owner = { unreadable: true, error: error.message }; }
+ return Object.assign(busyError(`Timed out waiting for backup publication admission${owner?.path ? ` at ${owner.path}` : ''}. No publication writes started. Reconcile the interrupted backup or restore before retiring its exact ownership record; do not remove it by age or PID.`), {
+ owner, ...(owner?.path ? { recoveryPath: owner.path } : {}),
+ });
+}
+
+async function waitForLocalCut(deadline) {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) throw publicationTimeoutError();
+ await new Promise((resolve, reject) => {
+ const clear = () => {
+ clearTimeout(timer);
+ publicationWaiters = publicationWaiters.filter(waiter => waiter !== resumed);
+ };
+ const resumed = () => { clear(); resolve(); };
+ const timer = setTimeout(() => { clear(); reject(publicationTimeoutError()); }, remaining);
+ publicationWaiters.push(resumed);
+ });
+}
+
+async function withAdmittedBackupAssetPublication(work, timeoutMs) {
const scope = publicationScope.getStore();
if (scope?.active) return work();
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0) throw new TypeError('Publication timeoutMs must be a non-negative finite number');
+ const deadline = Date.now() + timeoutMs;
// Work spawned by a still-admitted lease joins it: the cut already waits for that lease.
const joinsAdmitted = scope?.spawnedBy?.active === true;
while (!joinsAdmitted && (cutRequested || cutActive)) {
- await new Promise(resolve => publicationWaiters.push(resolve));
+ await waitForLocalCut(deadline);
}
let sharedLease;
while (!(sharedLease = backupSharedAdmission.tryPublication({ parent: joinsAdmitted ? scope.spawnedBy.sharedLease : null }))) {
- await new Promise(resolve => setTimeout(resolve, 25));
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) throw publicationTimeoutError();
+ await new Promise(resolve => setTimeout(resolve, Math.min(25, remaining)));
}
admitted += 1;
const lease = { active: true, sharedLease };
diff --git a/server/lib/backupSnapshotBoundary.test.js b/server/lib/backupSnapshotBoundary.test.js
index e08539d93e..745afc3612 100644
--- a/server/lib/backupSnapshotBoundary.test.js
+++ b/server/lib/backupSnapshotBoundary.test.js
@@ -73,6 +73,24 @@ describe('backup snapshot publication admission', () => {
await first;
});
+ it('bounds a local publication wait without releasing the cut or leaving a queued callback', async () => {
+ vi.useFakeTimers();
+ const release = await acquireBackupSnapshotCut();
+ const work = vi.fn();
+ try {
+ const pending = withBackupAssetPublication(work, { timeoutMs: 50 });
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY',
+ owner: expect.objectContaining({ kind: 'snapshot' }) });
+ await vi.advanceTimersByTimeAsync(50);
+ await rejected;
+ expect(work).not.toHaveBeenCalled();
+ await expect(acquireBackupSnapshotCut()).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY' });
+ } finally { release(); }
+ await Promise.resolve();
+ expect(work).not.toHaveBeenCalled();
+ await expect(withBackupAssetPublication(() => 'recovered')).resolves.toBe('recovered');
+ });
+
it('lets a listener spawned by an admitted workflow join it only while that workflow holds its lease', async () => {
const listenerWrite = deferred();
let listener;