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

test: stabilize concurrent database recovery under load (#9236)

Adam Eivy61f736d7debf
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index a74175c653..8998374a7d 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -156,6 +156,14 @@ After a committed import the same worker (`runDatabaseCutover` in `server/servic
**Recovery commands.** Inspect with `node scripts/database-maintenance.mjs status`. If `coordinator.state` is `exited`, repair the reported cause (for example start the target backend, or fix `.env`) and run `node scripts/database-maintenance.mjs recover <operation-id>`; repeat as needed — each run resumes the recorded stage. `verifying` with a server that keeps exiting usually means the target is unreachable or `.env`/the launch environment points elsewhere; `pm2 logs portos-server` shows the bounded refusal. `verified` with no release (a crash between them) is completed by the same `recover`. Never delete the fence, the proofs, or the authority record to force startup.
+Concurrent operator recoveries still launch at most one worker for the recorded
+successor. A competing command can report `running`, or exit 1 with
+`Database maintenance is fenced; journal recovery is required.` if ownership
+changes between its checks. Inspect `status` and retry the same operation;
+while its worker is running, the retry reports `running`. Once release finishes,
+there is no active operation left to recover. A fenced refusal never authorizes
+removing the fence or launching another operation.
+
### Calendar daily-review recovery
Daily reviews remain in the existing `data/calendar/daily-reviews/<date>.json`
diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.js
index 5dcd3729d9..bc4da95945 100644
--- a/server/lib/databaseMaintenanceJournal.test.js
+++ b/server/lib/databaseMaintenanceJournal.test.js
@@ -97,6 +97,37 @@ describe('persistent database maintenance boundary', () => {
expect(() => journal.assertAdmission()).toThrow();
});
+ // Regression: ownership can change after recoverCoordinator reads the old
+ // owner but before it asserts that owner. Refusal is safe; retry adopts the
+ // persisted successor instead of publishing another one (#9236).
+ it('fences a contended recovery and lets an operator retry adopt the one successor', () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const directory = journal.reserveCoordinatorWorker(operation.id, token);
+ writeFileSync(join(directory, 'exit'), '1\n');
+ let ownerReads = 0;
+ let successor;
+ const interleave = path => {
+ if (path.endsWith('cancel-' + operation.id + '.claim') && ++ownerReads === 3) {
+ successor = journal.prepareRecovery(operation.id);
+ } else {
+ fsHook.beforeRead = interleave;
+ }
+ };
+ fsHook.beforeRead = interleave;
+ try {
+ expect(() => journal.prepareRecovery(operation.id)).toThrow(expect.objectContaining({ code: 'DATABASE_MAINTENANCE' }));
+ } finally {
+ fsHook.beforeRead = null;
+ }
+ expect(successor).toBeTruthy();
+ expect(journal.prepareRecovery(operation.id)).toBe(successor);
+ journal.reserveCoordinatorWorker(operation.id, successor);
+ expect(journal.prepareRecovery(operation.id)).toBeNull();
+ expect(() => journal.reserveCoordinatorWorker(operation.id, successor)).toThrow();
+ expect(() => journal.assertAdmission()).toThrow();
+ });
+
it('fences cancellation and competing coordinators through every durable stage', () => {
const operation = journal.begin({ source, target });
const token = journal.acquireCoordinator(operation.id);
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.js
index 4733049a1f..edc5329b8c 100644
--- a/server/lib/databaseMaintenanceWorker.test.js
+++ b/server/lib/databaseMaintenanceWorker.test.js
@@ -217,16 +217,37 @@ describe.skipIf(process.platform === 'win32')('owned maintenance worker', () =>
.toEqual(expect.arrayContaining(['owner.json', 'started.json', 'group.json', 'stdout.log', 'stderr.log', 'pid']));
}, 90_000);
- it('relaunches only the recorded operation once across repeated operator recovery', async () => {
+ it('relaunches the recorded operation once; a contended operator recovery reports running or fenced, retry', async () => {
const operation = journal.begin({ source, target });
const token = journal.acquireCoordinator(operation.id);
stubs.setMode('dump', 'fail');
expect((await launch(operation.id, token)).status).toBe(1);
expect(status()).toMatchObject({ stage: 'exporting', coordinator: { state: 'exited', exitCode: 1 } });
- stubs.setMode('dump', 'ok');
- const outcomes = await Promise.all([recover(operation.id), recover(operation.id)]);
- expect(outcomes.map(value => value.status), outcomes.map(value => value.stderr).join('\n')).toEqual([0, 0]);
- expect(outcomes.map(value => JSON.parse(value.stdout).recovery).sort()).toEqual(['launched', 'running']);
+ // Hold the successor at export so a slow competing CLI cannot arrive
+ // after release. Ownership changes between checks deliberately fail
+ // closed: that contender must retry, not assume both calls exit zero.
+ stubs.setMode('dump', 'pause');
+ try {
+ const outcomes = await Promise.all([recover(operation.id), recover(operation.id)]);
+ const successful = outcomes.filter(value => value.status === 0);
+ expect(successful.filter(value => JSON.parse(value.stdout).recovery === 'launched'),
+ outcomes.map(value => value.stderr).join('\n')).toHaveLength(1);
+ for (const outcome of outcomes) {
+ if (outcome.status === 0) {
+ expect(JSON.parse(outcome.stdout)).toMatchObject({ id: operation.id, recovery: expect.stringMatching(/^(launched|running)$/) });
+ } else {
+ expect(outcome.status).toBe(1);
+ expect(outcome.stdout).toBe('');
+ expect(outcome.stderr.trim()).toBe('Database maintenance is fenced; journal recovery is required.');
+ }
+ }
+ await waitWithEvidence(() => expect(stubs.started('dump')).toBe(true), 30_000);
+ const retry = await recover(operation.id);
+ expect(retry.status, retry.stderr).toBe(0);
+ expect(JSON.parse(retry.stdout)).toMatchObject({ id: operation.id, recovery: 'running' });
+ } finally {
+ stubs.release('dump');
+ }
await waitWithEvidence(() => expect(stubs.events()).toContain(`server booted ${target.port}`), 30_000);
await waitWithEvidence(() => expect(journal.read()).toBeNull(), 10_000);
// One recovered worker: one export retry, one import, one server restart.