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

fix: distinguish refused publication admission from failed writes (#10559)

[._.]/ab74381b7d5f
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 10470f2bbd..65caeed74f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -44,6 +44,18 @@ certify the old work finished. Do not delete this journal to claim readiness; pr
with the related run/job records for recovery. A backup restored on another installation
therefore starts conservatively if it contains a hold or outstanding operations.
+Publication admission keeps a maintenance reservation while waiting for a backup
+cut. A boundary-owned callback-start check retires a refused admission without
+claiming any output was saved; failures after callback entry remain unresolved.
+Legacy generic `Output publication` reservations lack destination/batch identity.
+They cannot be swept automatically. After explicit operator disposition of
+inspected evidence, an owning service may use `reconcilePublicationRefusal` with
+the exact original operation and hold. Its synchronous publisher must preserve a
+durable, replayable evidence receipt before retirement; the journal validates and
+retires that exact owner under one lock. Missing ownership can only replay the
+existing receipt, never create an owner. This does not certify a complete
+transcript, clear transcript warnings, or change the original task outcome.
+
### Explicitly abandoned duplicate agents
A local operator may reconcile a user-killed duplicate that saved no output with
@@ -66,6 +78,7 @@ lock. These machine-local recovery receipts are included in the data backup and
never federated. This deliberately narrow command does not recover nonempty output
or general failed saves; those still require the owning workflow's recovery.
+
## The Four Storage Classes
| Class | Bytes live | Searchable metadata | Use when | PortOS examples |
diff --git a/server/lib/backupSnapshotBoundary.js b/server/lib/backupSnapshotBoundary.js
index 2d38ae47a5..717139a81f 100644
--- a/server/lib/backupSnapshotBoundary.js
+++ b/server/lib/backupSnapshotBoundary.js
@@ -34,7 +34,11 @@ function releasePublications() {
/** Hold one admission across an entire file-plus-row workflow. Nested calls reuse it. */
export async function withBackupAssetPublication(work, { timeoutMs = DEFAULT_DRAIN_TIMEOUT_MS } = {}) {
- return maintenance.continueSettlement(() => withAdmittedBackupAssetPublication(work, timeoutMs));
+ let started = false;
+ return maintenance.continueSettlement(() => withAdmittedBackupAssetPublication(() => {
+ started = true;
+ return work();
+ }, timeoutMs), { hasStarted: () => started });
}
function publicationTimeoutError() {
diff --git a/server/lib/backupSnapshotBoundary.settlement.test.js b/server/lib/backupSnapshotBoundary.settlement.test.js
new file mode 100644
index 0000000000..a9e64fe64a
--- /dev/null
+++ b/server/lib/backupSnapshotBoundary.settlement.test.js
@@ -0,0 +1,50 @@
+import { expect, it, vi } from 'vitest';
+import { maintenance } from './maintenanceAdmission.js';
+import { acquireBackupSnapshotCut, withBackupAssetPublication } from './backupSnapshotBoundary.js';
+
+it('keeps waiting publication owned, retires only refused admission, and retains a started failed write', async () => {
+ vi.useFakeTimers();
+ const parent = maintenance.admit('agent', 'fixture-agent');
+ const unrelated = maintenance.admit('provider', 'fixture-other');
+ const release = await acquireBackupSnapshotCut();
+ const work = vi.fn();
+ try {
+ const pending = parent.run(() => withBackupAssetPublication(work, { timeoutMs: 50 }));
+ const rejected = expect(pending).rejects.toMatchObject({ code: 'BACKUP_SNAPSHOT_BUSY' });
+ const hold = maintenance.begin({ reason: 'Fixture drain', owner: 'Test' }).hold;
+ await parent.finish();
+ expect(maintenance.status().blockers).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: 'settlement', resource: 'Output publication' }),
+ expect.objectContaining({ resource: 'fixture-other' }),
+ ]));
+ await vi.advanceTimersByTimeAsync(50);
+ await rejected;
+ expect(work).not.toHaveBeenCalled();
+ expect(maintenance.status().blockers).toEqual([expect.objectContaining({ resource: 'fixture-other' })]);
+ release();
+ await unrelated.finish();
+ expect(maintenance.status().state).toBe('ready');
+ maintenance.resume({ id: hold.id, revision: hold.revision });
+
+ const retry = maintenance.admit('agent', 'fixture-retry');
+ await expect(retry.run(() => withBackupAssetPublication(work))).resolves.toBeUndefined();
+ expect(work).toHaveBeenCalledOnce();
+ // The code alone is never proof: a callback can fail after writing with
+ // exactly the same retryable error code as an admission timeout.
+ const failure = Object.assign(new Error('failed after write'), { code: 'BACKUP_SNAPSHOT_BUSY' });
+ let wrote = false;
+ await expect(retry.run(() => withBackupAssetPublication(() => {
+ wrote = true;
+ throw failure;
+ }))).rejects.toBe(failure);
+ await retry.finish();
+ maintenance.begin({ reason: 'Fixture final drain', owner: 'Test' });
+ expect(wrote).toBe(true);
+ expect(maintenance.status()).toMatchObject({ state: 'draining', blockers: [
+ { kind: 'settlement', resource: 'Output publication', unsettled: true },
+ ] });
+ } finally {
+ release();
+ vi.useRealTimers();
+ }
+});
diff --git a/server/lib/maintenanceAdmission.js b/server/lib/maintenanceAdmission.js
index b1117c37fd..1c212f87cd 100644
--- a/server/lib/maintenanceAdmission.js
+++ b/server/lib/maintenanceAdmission.js
@@ -163,6 +163,23 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
return true;
});
};
+ // Local owning-service recovery after explicit operator disposition of a
+ // legacy pre-admission refusal. The service must preserve inspected evidence
+ // in publish(), durably and replayably, before this exact owner is retired.
+ const reconcilePublicationRefusal = ({ hold, expected, publish, replay }) => transaction(state => {
+ if (!hold || state.hold?.id !== hold.id || state.hold?.revision !== hold.revision || state.exclusive)
+ throw error('MAINTENANCE_STALE', 'The maintenance hold changed.');
+ if (expected?.kind !== 'settlement' || expected.resource !== 'Output publication'
+ || expected.unsettled !== true || !expected.uncertaintyStamp)
+ throw error('MAINTENANCE_STALE', 'An exact uncertain publication reservation is required.');
+ const index = state.operations.findIndex(op => op.id === expected.id);
+ if (index < 0) return replay();
+ if (JSON.stringify(state.operations[index]) !== JSON.stringify(expected))
+ throw error('MAINTENANCE_STALE', 'The publication reservation changed.');
+ const receipt = publish();
+ state.operations.splice(index, 1);
+ return receipt;
+ });
const permitFor = (id, recovery) => ({
id,
run: fn => context.run(id, fn),
@@ -227,11 +244,22 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
const id = currentId();
if (id) markUnsettled(op => op.id === id);
};
- const continueSettlement = fn => currentId() ? run('settlement', 'Output publication', fn, { continuation: true }) : fn();
+ // A publication boundary may prove its callback never started. Keep the
+ // reservation while it waits, but do not mistake refused admission for an
+ // uncertain write. Callers without that proof retain the conservative default.
+ const continueSettlement = (fn, { hasStarted } = {}) => currentId()
+ ? run('settlement', 'Output publication', fn, { continuation: true, hasStarted }) : fn();
const run = async (kind, resource, fn, options) => {
const permit = admit(kind, resource, options);
try { return await permit.run(fn); }
- catch (err) { if (kind === 'settlement') permit.markUnsettled(); throw err; }
+ catch (err) {
+ if (kind === 'settlement') {
+ let started = true;
+ try { started = options?.hasStarted?.() !== false; } catch { /* Missing proof remains uncertain. */ }
+ if (started) permit.markUnsettled();
+ }
+ throw err;
+ }
finally { await permit.finish(); }
};
const begin = ({ reason, owner }) => {
@@ -270,7 +298,7 @@ export function createMaintenanceAdmission(dataDir = PATHS.data, { io = fs, asse
return receipt;
});
const { observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability } = exclusive;
- return { directory, status, held, assertOpen, admit, tryAdmit, recoverOwned, run, currentId, finish, finishResource, withResource, markResourceUnsettled, markCurrentUnsettled, continueSettlement, begin, resume, events,
+ return { directory, status, held, assertOpen, admit, tryAdmit, recoverOwned, reconcilePublicationRefusal, run, currentId, finish, finishResource, withResource, markResourceUnsettled, markCurrentUnsettled, continueSettlement, begin, resume, events,
observeIdle, claimReady, getExclusive, transitionExclusive, settleExclusive, issueExecutionCapability, reconcileAbandonedAgent };
}
diff --git a/server/lib/maintenanceAdmission.test.js b/server/lib/maintenanceAdmission.test.js
index db15edf2ea..db382835dd 100644
--- a/server/lib/maintenanceAdmission.test.js
+++ b/server/lib/maintenanceAdmission.test.js
@@ -19,6 +19,32 @@ const gate = () => {
afterEach(() => { vi.useRealTimers(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
describe('durable graceful maintenance', () => {
+ it('binds operator publication reconciliation to the exact hold and owner and publishes before retirement', async () => {
+ const { root, admission } = gate();
+ const owner = admission.admit('settlement', 'Output publication');
+ owner.markUnsettled();
+ const other = admission.admit('agent', 'unrelated');
+ const hold = admission.begin({ reason: 'Inspect refused publication', owner: 'Operator' }).hold;
+ const expected = JSON.parse(fs.readFileSync(join(root, 'workflow-maintenance', 'state.json'))).operations.find(op => op.id === owner.id);
+ let receipt;
+ const publish = vi.fn(() => {
+ expect(JSON.parse(fs.readFileSync(join(root, 'workflow-maintenance', 'state.json'))).operations)
+ .toContainEqual(expect.objectContaining({ id: owner.id, kind: 'settlement' }));
+ receipt ??= { operation: expected, disposition: 'operator-reconciled' };
+ return receipt;
+ });
+ const replay = vi.fn(() => receipt);
+ expect(() => admission.reconcilePublicationRefusal({ hold: { ...hold, revision: hold.revision + 1 }, expected, publish, replay })).toThrow('hold changed');
+ expect(() => admission.reconcilePublicationRefusal({ hold, expected: { ...expected, uncertaintyStamp: 'changed' }, publish, replay })).toThrow('reservation changed');
+ expect(publish).not.toHaveBeenCalled();
+ expect(admission.reconcilePublicationRefusal({ hold, expected, publish, replay })).toBe(receipt);
+ expect(admission.status()).toMatchObject({ hold, blockers: [{ resource: 'unrelated' }] });
+ expect(admission.reconcilePublicationRefusal({ hold, expected, publish, replay })).toBe(receipt);
+ expect(publish).toHaveBeenCalledOnce();
+ expect(replay).toHaveBeenCalledOnce();
+ await other.finish();
+ });
+
it('mints completion only when trusted recovery reuses an existing operation', () => {
const { admission } = gate();
expect(admission.admit('media', 'new')).not.toHaveProperty('completeRecovery');