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: bind cutover target proofs to the proving process's start time (#8851)

[._.]/ Adam Eivyf74e83e96d59
diff --git a/server/lib/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.js
index d57f3e930a..000529dbcc 100644
--- a/server/lib/databaseMaintenanceJournal.js
+++ b/server/lib/databaseMaintenanceJournal.js
@@ -56,10 +56,13 @@ const transferImportSchema = z.object({
}).strict();
// A restarted ordinary server proved ITS OWN pool reaches the recorded target.
// Evidence, not authority: the coordinator accepts it only for the PM2 pid it
-// reads back itself, and every booting process still proves its own pool.
+// reads back itself AND that process's start time (a reused pid cannot inherit
+// an earlier process's proof), and every booting process proves its own pool.
+// startedAt is null only on Windows, which has no process-table start time.
const targetProofSchema = z.object({
id: z.string().uuid(),
pid: z.number().int().positive(),
+ startedAt: z.number().int().nullable(),
target: databaseMaintenanceEndpointSchema,
}).strict();
const recoveryIntentSchema = z.object({
@@ -605,11 +608,11 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
// Published by a booting ordinary server AFTER its own pool passed the
// read-only target verification. Only verifying/verified may carry one.
- const recordTargetProof = (id, pid) => {
+ const recordTargetProof = (id, pid, startedAt) => {
assertNotRealDataWrite(activeDir, 'database maintenance target proof');
const current = read();
if (!current || current.id !== id || !['verifying', 'verified'].includes(current.stage)) throw databaseMaintenanceError();
- publishImmutable(targetProofPath(pid), targetProofSchema.parse({ id, pid, target: current.target }));
+ publishImmutable(targetProofPath(pid), targetProofSchema.parse({ id, pid, startedAt, target: current.target }));
return readTargetProof(id, pid);
};
diff --git a/server/services/databaseCutoverHandshake.js b/server/services/databaseCutoverHandshake.js
index bdcae6b921..23463f7adf 100644
--- a/server/services/databaseCutoverHandshake.js
+++ b/server/services/databaseCutoverHandshake.js
@@ -32,7 +32,14 @@ export async function awaitDatabaseCutoverRelease({ releaseTimeoutMs = RELEASE_T
await verifyDatabaseMaintenanceTarget(operation.id).catch(() => {
throw refused('this process could not prove the recorded target backend');
});
- journal.recordTargetProof(operation.id, process.pid);
+ // Bind the proof to this process's start time so a reused pid cannot inherit it.
+ let startedAt = null;
+ if (process.platform !== 'win32') {
+ const { snapshotProcesses } = await import('../lib/detachedSpawn.js');
+ startedAt = (await snapshotProcesses().catch(() => [])).find(row => row.pid === process.pid)?.startedAt;
+ if (!Number.isSafeInteger(startedAt)) throw refused('this process\'s start time is unknown');
+ }
+ journal.recordTargetProof(operation.id, process.pid, startedAt);
console.log(`🗄️ Database cutover target verified by pid ${process.pid}; waiting for admission release`);
const deadline = Date.now() + releaseTimeoutMs;
diff --git a/server/services/databaseMaintenanceCutover.js b/server/services/databaseMaintenanceCutover.js
index eb583649d2..64a5dbc16f 100644
--- a/server/services/databaseMaintenanceCutover.js
+++ b/server/services/databaseMaintenanceCutover.js
@@ -10,6 +10,7 @@ import { isDisposableRoot } from '../lib/dataRoot.js';
import { runDatabaseTransfer } from './databaseMaintenanceTransfer.js';
import { readRecordedProducers } from './databaseMaintenanceProducers.js';
import { restartMaintenanceProducer } from './pm2.js';
+import { snapshotProcesses } from '../lib/detachedSpawn.js';
const TRANSFER_STAGES = ['accepted', 'quiescing', 'exporting', 'importing'];
const PROOF_TIMEOUT_MS = 180_000;
@@ -110,11 +111,20 @@ async function commitSavedMode(operation) {
await assertSavedTarget(operation);
}
+// A proof counts only for the process that wrote it: same pid AND the start
+// time the process table reports for that pid now.
+async function proofMatchesProcess(proof, pid) {
+ if (!proof) return false;
+ if (process.platform === 'win32') return proof.startedAt === null;
+ const row = (await snapshotProcesses().catch(() => [])).find(value => value.pid === pid);
+ return Number.isSafeInteger(proof.startedAt) && row?.startedAt === proof.startedAt;
+}
+
/**
* Restart the recorded server with the committed configuration and wait for
* THAT restarted process — the one PM2 reports now — to publish proof that its
* own pool reached the recorded target. PM2 `online`, the saved mode, or a
- * proof from an earlier pid is not success. The server is restarted at most
+ * proof from an earlier process (even one with a reused pid) is not success. The server is restarted at most
* once per attempt; a crash-looping or wrong-pool server times out fenced.
*/
async function awaitRestartedTarget(journal, operation, token, saved, { proofTimeoutMs = PROOF_TIMEOUT_MS, pollMs = POLL_MS }) {
@@ -124,7 +134,8 @@ async function awaitRestartedTarget(journal, operation, token, saved, { proofTim
while (true) {
journal.assertEnteredCoordinatorWorker(id, token);
const server = (await readRecordedProducers(saved)).find(row => row.name === 'portos-server');
- if (server.status === 'online' && server.pid > 0 && journal.readTargetProof(id, server.pid)) return server.pid;
+ if (server.status === 'online' && server.pid > 0
+ && await proofMatchesProcess(journal.readTargetProof(id, server.pid), server.pid)) return server.pid;
if (server.status !== 'online' && !restarted) {
journal.assertEnteredCoordinatorWorker(id, token);
const result = await restartMaintenanceProducer('portos-server', recordedEndpointEnv(operation)).catch(() => null);
diff --git a/server/services/databaseMaintenanceCutover.test.js b/server/services/databaseMaintenanceCutover.test.js
index 3323431a54..178da186ec 100644
--- a/server/services/databaseMaintenanceCutover.test.js
+++ b/server/services/databaseMaintenanceCutover.test.js
@@ -7,6 +7,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
+import { spawn } from 'node:child_process';
import { join } from 'node:path';
import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';
import { installCutoverStubs, restartedServerEndpoint } from '../test/fixtures/databaseCutoverStubs.js';
@@ -213,6 +214,27 @@ describe.skipIf(process.platform === 'win32')('offline database cutover', () =>
expect(() => journal.prepareRecovery(operation.id)).toThrow();
}, 60_000);
+ it('never accepts a proof written by an earlier process whose pid was reused', async () => {
+ begin();
+ cutover.setHealth('unhealthy');
+ await expect(run()).rejects.toThrow(/did not prove/);
+ // PM2 now reports a process that never verified anything, holding a pid for
+ // which an earlier (verified) process left a proof with its own start time.
+ const impostor = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore', detached: true });
+ impostor.unref();
+ try {
+ const server = rows.find(row => row.name === 'portos-server');
+ Object.assign(server, { pid: impostor.pid, status: 'online', surrogate: true });
+ journal.recordTargetProof(operation.id, impostor.pid, Date.now() - 3_600_000);
+ successor();
+ await expect(run()).rejects.toThrow(/did not prove the target backend/);
+ expect(journal.read().stage).toBe('verifying');
+ expect(() => journal.assertAdmission()).toThrow();
+ } finally {
+ impostor.kill('SIGKILL');
+ }
+ }, 60_000);
+
it('refuses to release onto a saved configuration edited away from the target', async () => {
begin();
cutover.setHealth('unhealthy');