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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep a booting server from refusing when maintenance releases mid-poll (#8904)
[._.]/ Adam Eivy6c2817c5c034
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsindex c9d6075a59..ba09f31c4a 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -154,6 +154,11 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {}return current;} catch {+ // The fence check and the record reads are separate syscalls. A release+ // or cancellation that renames the fence between them is not damage:+ // once the directory itself is gone, no operation is active. Anything+ // still fenced (partial publication, damaged record) fails closed.+ if (!isFenced()) return null;throw databaseMaintenanceError();}};@@ -443,7 +448,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {|| new Set(snapshot.producers.map(p => p.pmId)).size !== 2) throw databaseMaintenanceError();return snapshot.producers;} catch (err) {- if (err.code === 'ENOENT' && read().stage === 'accepted') return null;+ if (err.code === 'ENOENT' && read()?.stage === 'accepted') return null;throw databaseMaintenanceError();}};@@ -451,7 +456,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {const recordProducerSnapshot = (id, token, producers) => {assertNotRealDataWrite(activeDir, 'database maintenance producer inventory');assertCoordinatorWorker(id, token);- if (read().stage !== 'accepted' || readProducerSnapshot(id, token)) throw databaseMaintenanceError();+ if (read()?.stage !== 'accepted' || readProducerSnapshot(id, token)) throw databaseMaintenanceError();const snapshot = producerSnapshotSchema.parse({ id, producers });writeDurableExclusive(join(activeDir, 'producers.json'), snapshot);syncDirectory(activeDir);@@ -508,13 +513,13 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {// or a committed mode back to the source.while (true) {const current = read();- if (!stages.includes(current.stage)) throw databaseMaintenanceError();+ if (!stages.includes(current?.stage)) throw databaseMaintenanceError();const decision = decide(id, previousToken, current.stage, { kind: 'recovery', recoveryToken });if (decision.kind === 'recovery') {if (decision.recoveryToken !== recoveryToken) throw databaseMaintenanceError();break;}- if (read().stage === current.stage) transition(id, previousToken, current.stage, decision.nextStage);+ if (read()?.stage === current.stage) transition(id, previousToken, current.stage, decision.nextStage);}const directory = workerDirectory(previousToken);const fd = openSync(join(directory, 'exit'), 'r+');@@ -588,7 +593,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {}writeDurableExclusive(join(activeDir, 'cancel-' + id + '.claim'), { id });const current = read();- if (current.id !== id || current.stage !== 'accepted') throw databaseMaintenanceError();+ if (current?.id !== id || current.stage !== 'accepted') throw databaseMaintenanceError();const archiveDir = join(dataDir, 'database-maintenance-cancelled');mkdirSync(archiveDir, { recursive: true, mode: 0o700 });// Archive before reopening admission; retain the operation's direction asdiff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.jsindex 9a5eb61df1..92b86205fc 100644--- a/server/lib/databaseMaintenanceJournal.test.js+++ b/server/lib/databaseMaintenanceJournal.test.js@@ -1,11 +1,26 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { spawn, spawnSync } from 'node:child_process';-import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';+import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';+// Pass-through fs whose readFileSync can run one hook first: the only way to+// land a concurrent fence move deterministically between read()'s fence check+// and its record read (the two are separate syscalls in one sync call).+const fsHook = vi.hoisted(() => ({ beforeRead: null }));+vi.mock('node:fs', async (importOriginal) => {+ const actual = await importOriginal();+ const readFileSync = (...args) => {+ const hook = fsHook.beforeRead;+ fsHook.beforeRead = null;+ hook?.(String(args[0]));+ return actual.readFileSync(...args);+ };+ return { ...actual, readFileSync, default: { ...actual, readFileSync } };+});+const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };const target = { ...source, mode: 'docker', port: 5561 };const moduleUrl = new URL('./databaseMaintenanceJournal.js', import.meta.url).href;@@ -207,6 +222,22 @@ describe('persistent database maintenance boundary', () => {}});+ // Regression caught (#8904): a coordinator releasing admission between the+ // fence check and the record read made a booting server's release poll+ // throw DATABASE_MAINTENANCE and exit fenced although admission was open.+ it('reports no operation when the fence moves mid-read, but fails closed while still fenced', () => {+ const operation = journal.begin({ source, target });+ const active = join(data, 'database-maintenance');+ fsHook.beforeRead = () => renameSync(active, join(root, 'archived'));+ expect(journal.read()).toBeNull();+ expect(() => journal.assertAdmission()).not.toThrow();++ renameSync(join(root, 'archived'), active);+ expect(journal.read()).toMatchObject({ id: operation.id });+ fsHook.beforeRead = () => rmSync(join(active, 'operation.json'));+ expect(() => journal.read()).toThrowError(expect.objectContaining({ code: 'DATABASE_MAINTENANCE' }));+ });+it('cancels only an accepted matching source and retains the immutable operation as local evidence', () => {const operation = journal.begin({ source, target });expect(() => journal.cancel('00000000-0000-4000-8000-000000000000', source)).toThrow();diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.jsindex aa9d1b110c..805e512d18 100644--- a/server/lib/databaseMaintenanceWorker.test.js+++ b/server/lib/databaseMaintenanceWorker.test.js@@ -150,6 +150,36 @@ const recover = id => new Promise((resolve, reject) => {});const importsStarted = () => stubs.events().filter(line => line === 'import-start').length;+// Bounded, synthetic-only failure evidence, read BEFORE afterEach removes the+// disposable root (#8904): every fixture event, the operator's bounded stage+// and coordinator state, and the stderr tail of each owned worker (active or+// archived) and each surrogate server.+const tail = path => (existsSync(path) ? readFileSync(path, 'utf8').slice(-1_500) : '');+function evidence() {+ const operator = spawnSync(process.execPath, [fileURLToPath(new URL('../../scripts/database-maintenance.mjs', import.meta.url)), 'status'],+ { env, encoding: 'utf8', timeout: 10_000 });+ const completed = join(root, 'data', 'database-maintenance-completed');+ const controlParents = [join(root, 'data', 'database-maintenance'),+ ...(existsSync(completed) ? readdirSync(completed).map(id => join(completed, id)) : [])];+ const workers = controlParents.flatMap(parent => (existsSync(parent) ? readdirSync(parent) : [])+ .filter(name => name.startsWith('worker-')).map(name => join(parent, name, 'stderr.log')));+ return [+ `events: ${JSON.stringify(stubs.events())}`,+ `status (exit ${operator.status}): ${(operator.stdout || operator.stderr).trim().slice(0, 1_500)}`,+ ...workers.map((path, index) => `worker ${index} stderr: ${tail(path)}`),+ `surrogate stderr: ${tail(join(stubs.dir, 'surrogate-stderr.log'))}`,+ ].join('\n');+}+// vi.waitFor that appends the evidence above when its deadline expires.+async function waitWithEvidence(assertion, timeout) {+ try {+ await vi.waitFor(assertion, { timeout, interval: 50 });+ } catch (err) {+ err.message += `\n--- maintenance evidence ---\n${evidence()}`;+ throw err;+ }+}+describe.skipIf(process.platform === 'win32')('owned maintenance worker', () => {it.each([[source, target], [target, source]])('cuts over the recorded operation once and releases only after the restarted server proves the target (%#)', async (from, to) => {writeFileSync(join(root, '.env'), `PGMODE=${from.mode}\n`);@@ -161,7 +191,7 @@ describe.skipIf(process.platform === 'win32')('owned maintenance worker', () =>expect(outcomes.filter(value => value.status === 1)).toHaveLength(1);expect(releasedResult(released[0])).toEqual({ id: operation.id, stage: 'released', source: from.mode, target: to.mode,importCommitted: true, sourceRetained: true, restartVerified: true, cosRestarted: true });- await vi.waitFor(() => expect(stubs.events()).toContain(`server booted ${to.port}`), { timeout: 15_000, interval: 50 });+ await waitWithEvidence(() => expect(stubs.events()).toContain(`server booted ${to.port}`), 15_000);expect(stubs.events().slice(0, 6)).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=none','import-start', 'import-commit', 'restart portos-server']);expect(stubs.events()).toContain('restart portos-cos');@@ -189,8 +219,8 @@ describe.skipIf(process.platform === 'win32')('owned maintenance worker', () =>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']);- await vi.waitFor(() => expect(stubs.events()).toContain(`server booted ${target.port}`), { timeout: 30_000, interval: 50 });- await vi.waitFor(() => expect(journal.read()).toBeNull(), { timeout: 10_000, interval: 50 });+ 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.expect(stubs.invocations('pg_dump')).toHaveLength(2);expect(importsStarted()).toBe(1);diff --git a/server/test/fixtures/databaseCutoverStubs.js b/server/test/fixtures/databaseCutoverStubs.jsindex ec862cdea1..2eb5be21e7 100644--- a/server/test/fixtures/databaseCutoverStubs.js+++ b/server/test/fixtures/databaseCutoverStubs.js@@ -10,7 +10,8 @@// - `launchServer(endpoint)` starts a surrogate ordinary server: the REAL// databaseCutoverHandshake + databaseBootFence against a pool configured// from its environment, then records `server booted` (or `server refused`).-import { appendFileSync, chmodSync, copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';+// Its stderr is kept in `surrogate-stderr.log` as failure evidence.+import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, openSync, readFileSync, writeFileSync } from 'node:fs';import { spawn } from '../../lib/childProcess.js';import { join } from 'node:path';import { pathToFileURL } from 'node:url';@@ -65,6 +66,7 @@ try {log('server booted ' + process.env.PGPORT);} catch (err) {log('server refused ' + (err.code ?? 'error'));+ console.error('surrogate ' + process.pid + ' refused: ' + String(err?.message ?? err).slice(0, 300));process.exit(1);}setInterval(() => {}, 1000);@@ -100,7 +102,9 @@ export function launchSurrogateServer(root, dir, endpoint) {PGHOST: endpoint.host, PGPORT: String(endpoint.port), PGDATABASE: endpoint.database, PGUSER: endpoint.user,PGPASSWORD: 'example-password', NODE_OPTIONS: `--import=${pathToFileURL(join(dir, 'pg-register.mjs')).href}` };delete env.VITEST;- const child = spawn(process.execPath, [join(dir, 'server-surrogate.mjs')], { env, stdio: 'ignore', detached: true });+ const stderr = openSync(join(dir, 'surrogate-stderr.log'), 'a');+ const child = spawn(process.execPath, [join(dir, 'server-surrogate.mjs')], { env, stdio: ['ignore', 'ignore', stderr], detached: true });+ closeSync(stderr);child.unref();appendFileSync(join(dir, 'surrogates'), `${child.pid}\n`);return child.pid;