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 a cutover releases mid-history-read (#8929)
[._.]/ Adam Eivye2f1143824c8
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.jsindex ba09f31c4a..13868d0320 100644--- a/server/lib/databaseMaintenanceJournal.js+++ b/server/lib/databaseMaintenanceJournal.js@@ -135,7 +135,8 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {const read = () => {if (!isFenced()) return null;try {- if (!lstatSync(activeDir).isDirectory() || !lstatSync(recordPath).isFile()) {+ const fence = lstatSync(activeDir);+ if (!fence.isDirectory() || !lstatSync(recordPath).isFile()) {throw databaseMaintenanceError();}let current = journalSchema.parse(JSON.parse(readFileSync(recordPath, 'utf8')));@@ -152,6 +153,13 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {if (JSON.stringify(next) !== JSON.stringify({ ...current, stage })) throw databaseMaintenanceError();current = next;}+ // The walk ends at the first missing publication, and a release or+ // cancellation that moves the fence mid-walk makes every later one look+ // missing. The history is complete only if the SAME fence is still in+ // place afterward: a moved fence (ENOENT) reports no operation below; a+ // different one at this path fails closed.+ const after = lstatSync(activeDir);+ if (after.ino !== fence.ino || after.dev !== fence.dev) throw databaseMaintenanceError();return current;} catch {// The fence check and the record reads are separate syscalls. A releasediff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.jsindex 92b86205fc..ad7f30741a 100644--- a/server/lib/databaseMaintenanceJournal.test.js+++ b/server/lib/databaseMaintenanceJournal.test.js@@ -6,17 +6,22 @@ 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 }));+// Pass-through fs whose readFileSync can run one hook before or after it: the+// only way to land a concurrent fence move deterministically between read()'s+// separate syscalls (fence check, record read, published-stage walk) in one+// sync call.+const fsHook = vi.hoisted(() => ({ beforeRead: null, afterRead: 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);+ const result = actual.readFileSync(...args);+ const after = fsHook.afterRead;+ fsHook.afterRead = null;+ after?.(String(args[0]));+ return result;};return { ...actual, readFileSync, default: { ...actual, readFileSync } };});@@ -238,6 +243,28 @@ describe('persistent database maintenance boundary', () => {expect(() => journal.read()).toThrowError(expect.objectContaining({ code: 'DATABASE_MAINTENANCE' }));});+ // Regression caught (#8929): a release that moved the fence after the record+ // read but before the published-stage walk truncated the history to an+ // earlier stage, so a booting server's release poll saw "the fenced+ // operation changed" and exited fenced although admission had just opened.+ it('never reports a stage history truncated by a fence move mid-walk', () => {+ const operation = journal.begin({ source, target });+ const token = journal.acquireCoordinator(operation.id);+ journal.transition(operation.id, token, 'accepted', 'quiescing');+ journal.transition(operation.id, token, 'quiescing', 'exporting');+ const active = join(data, 'database-maintenance');+ fsHook.afterRead = () => renameSync(active, join(root, 'released'));+ expect(journal.read()).toBeNull();+ expect(() => journal.assertAdmission()).not.toThrow();++ renameSync(join(root, 'released'), active);+ expect(journal.read()).toMatchObject({ id: operation.id, stage: 'exporting' });+ // A different fence now at the same path never inherits the moved one's+ // partial history; it fails closed until read again.+ fsHook.afterRead = () => { renameSync(active, join(root, 'released')); mkdirSync(active); };+ 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/services/databaseMaintenanceCutover.test.js b/server/services/databaseMaintenanceCutover.test.jsindex 8e38ed90d7..552c7657ee 100644--- a/server/services/databaseMaintenanceCutover.test.js+++ b/server/services/databaseMaintenanceCutover.test.js@@ -115,7 +115,34 @@ function successor() {const run = () => runDatabaseCutover(operation.id, token, fast);const savedMode = () => /^PGMODE=(\S+)/m.exec(readFileSync(join(root, '.env'), 'utf8'))?.[1];const serverEvents = () => stubs.events().filter(line => line.startsWith('server '));-const waitForEvent = (line) => vi.waitFor(() => expect(stubs.events()).toContain(line), { timeout: 15_000, interval: 20 });+// Bounded, synthetic-only failure evidence, read BEFORE afterEach removes the+// disposable root (#8929): every fixture event, the operation's stage and+// coordinator state, the authority record's operation, each surrogate+// server's liveness, and the tail of their timestamped stderr trace — enough+// to tell a refused boot from one still waiting (or never started).+const bounded = read => { try { return read(); } catch (err) { return 'unreadable (' + (err.code ?? 'error') + ')'; } };+function evidence() {+ const log = join(stubs.dir, 'surrogate-stderr.log');+ return [+ `events: ${JSON.stringify(stubs.events())}`,+ `fenced: ${bounded(() => journal.isFenced())}; stage: ${bounded(() => journal.read()?.stage ?? 'none')}`,+ `coordinator: ${bounded(() => JSON.stringify(journal.coordinatorStatus(operation.id)))}`,+ `authority for this operation: ${bounded(() => createDatabaseAuthority(join(root, 'data')).read()?.operationId === operation.id)}`,+ `surrogates: ${JSON.stringify((cutover?.surrogatePids() ?? []).map(pid => ({ pid, alive: alive(pid) })))}`,+ `surrogate stderr: ${existsSync(log) ? readFileSync(log, 'utf8').slice(-3_000) : ''}`,+ ].join('\n');+}+// vi.waitFor that appends the evidence above when its deadline expires.+async function waitWithEvidence(assertion) {+ try {+ await vi.waitFor(assertion, { timeout: 15_000, interval: 20 });+ } catch (err) {+ err.message += `\n--- cutover evidence ---\n${evidence()}`;+ throw err;+ }+}+const waitForEvent = (line) => waitWithEvidence(() => expect(stubs.events()).toContain(line));+const waitForProof = (pid) => waitWithEvidence(async () => expect(journal.readTargetProof(operation.id, pid, await processStart(pid))).not.toBeNull());describe.skipIf(process.platform === 'win32')('offline database cutover', () => {it.each([[native, docker], [docker, native]])('commits mode and releases only after the restarted server proves the target (%#)', async (source, target) => {@@ -200,7 +227,7 @@ describe.skipIf(process.platform === 'win32')('offline database cutover', () =>// A healthy restarted server proves the target and waits at the fence.const pid = cutover.launchServer(docker);rows.find(row => row.name === 'portos-server').pid = pid;- await vi.waitFor(async () => expect(journal.readTargetProof(operation.id, pid, await processStart(pid))).not.toBeNull(), { timeout: 15_000, interval: 20 });+ await waitForProof(pid);// A worker crashes between verification and release.successor();journal.enterCoordinatorWorker(operation.id, token);@@ -250,7 +277,7 @@ describe.skipIf(process.platform === 'win32')('offline database cutover', () =>cutover.setHealth('healthy');const pid = cutover.launchServer(docker);rows.find(row => row.name === 'portos-server').pid = pid;- await vi.waitFor(async () => expect(journal.readTargetProof(operation.id, pid, await processStart(pid))).not.toBeNull(), { timeout: 15_000, interval: 20 });+ await waitForProof(pid);successor();journal.enterCoordinatorWorker(operation.id, token);journal.transition(operation.id, token, 'verifying', 'verified');diff --git a/server/test/fixtures/databaseCutoverStubs.js b/server/test/fixtures/databaseCutoverStubs.jsindex 2eb5be21e7..5d1b91e291 100644--- a/server/test/fixtures/databaseCutoverStubs.js+++ b/server/test/fixtures/databaseCutoverStubs.js@@ -59,14 +59,20 @@ export default { Pool, types: { setTypeParser() {} } };const surrogate = join(dir, 'server-surrogate.mjs');writeFileSync(surrogate, `import { appendFileSync } from 'node:fs';const log = line => appendFileSync(${JSON.stringify(events)}, line + '\\n');+// Timestamped progress on stderr lets a failed wait tell a refusal from a+// boot that was still pending (or never started) when the test gave up.+const trace = step => console.error(new Date().toISOString() + ' surrogate ' + process.pid + ' port ' + process.env.PGPORT + ' ' + step);+trace('started');try {const { awaitDatabaseCutoverRelease } = await import(${JSON.stringify(handshakeUrl)});- await awaitDatabaseCutoverRelease({ pollMs: 20, releaseTimeoutMs: 20000 });+ const released = await awaitDatabaseCutoverRelease({ pollMs: 20, releaseTimeoutMs: 20000 });+ trace('handshake returned released=' + released.released);await import(${JSON.stringify(bootFenceUrl)});log('server booted ' + process.env.PGPORT);+ trace('booted');} catch (err) {log('server refused ' + (err.code ?? 'error'));- console.error('surrogate ' + process.pid + ' refused: ' + String(err?.message ?? err).slice(0, 300));+ trace('refused ' + (err.code ?? 'error') + ': ' + String(err?.message ?? err).slice(0, 300));process.exit(1);}setInterval(() => {}, 1000);