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: launch the cutover worker only after the API response is sent (#8851)

[._.]/ Adam Eivy6592e24c9d20
diff --git a/server/routes/database.js b/server/routes/database.js
index e2eefa564c..a6139f51e9 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -30,17 +30,25 @@ router.post('/maintenance/preflight', asyncHandler(async (req, res) => {
// Accept the offline cutover. 202: the detached worker then stops PortOS,
// transfers, commits mode and restarts; progress is the status route above
// (and scripts/database-maintenance.mjs status while the server is down).
+// The worker's first act stops this server, so it launches only once the
+// response has closed; an unlaunched owner is resumable via recover.
router.post('/maintenance/cutover', asyncHandler(async (req, res) => {
const direction = validateRequest(databaseMaintenanceCutoverSchema, req.body);
+ const { accepted, launch } = await dbAdmin.acceptDatabaseCutover(direction);
+ res.once('close', launch);
res.set('Cache-Control', 'no-store');
- res.status(202).json(await dbAdmin.acceptDatabaseCutover(direction));
+ res.status(202).json(accepted);
}));
// Relaunch the worker for the SAME recorded operation after its exit receipt.
router.post('/maintenance/recover', asyncHandler(async (req, res) => {
const { id } = validateRequest(databaseMaintenanceRecoverSchema, req.body);
+ const { status, launch } = await dbAdmin.beginDatabaseCutoverRecovery(id);
+ if (launch) {
+ res.once('close', () => launch().catch(() => console.error('❌ Database cutover recovery worker could not be launched')));
+ }
res.set('Cache-Control', 'no-store');
- res.status(202).json(await dbAdmin.recoverDatabaseCutover(id));
+ res.status(202).json(status);
}));
// GET /api/database/status — current mode, connectivity, row counts, resource stats
diff --git a/server/routes/databasePreflight.test.js b/server/routes/databasePreflight.test.js
index 44c8302a2c..20067ccbbe 100644
--- a/server/routes/databasePreflight.test.js
+++ b/server/routes/databasePreflight.test.js
@@ -212,7 +212,8 @@ describe('database cutover acceptance HTTP contract', () => {
expect(operation).toMatchObject({ stage: 'accepted', source: { mode: source }, target: { mode: target } });
// Owned before launch: cancellation and a second owner are refused.
expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'unregistered' });
- expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(1);
+ // Launched only after the 202 is sent — the worker stops this server.
+ await vi.waitFor(() => expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(1));
expect(spawnDatabaseMaintenanceWorker.mock.calls[0][0]).toBe(operation.id);
expect(() => journal.acquireCoordinator(operation.id)).toThrow();
// Acceptance itself never changes the saved mode.
@@ -277,6 +278,7 @@ describe('database cutover acceptance HTTP contract', () => {
expect((await recover('not-a-uuid')).status).toBe(400);
const accepted = await accept();
const journal = createDatabaseMaintenanceJournal(PATHS.data);
+ await vi.waitFor(() => expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(1));
const [id, token] = spawnDatabaseMaintenanceWorker.mock.calls[0];
const directory = journal.reserveCoordinatorWorker(id, token);
// Still running (no receipt): recovery launches nothing.
@@ -285,8 +287,8 @@ describe('database cutover acceptance HTTP contract', () => {
expect((await recover('00000000-0000-4000-8000-000000000000')).status).toBe(503);
const recovered = await recover(id);
expect(recovered.status).toBe(202);
- expect(recovered.body).toEqual({ id: accepted.body.id, stage: 'accepted', recovery: 'launched' });
- expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(2);
+ expect(recovered.body).toEqual({ id: accepted.body.id, stage: 'accepted', recovery: 'launching' });
+ await vi.waitFor(() => expect(spawnDatabaseMaintenanceWorker).toHaveBeenCalledTimes(2));
expect(spawnDatabaseMaintenanceWorker.mock.calls[1][0]).toBe(id);
expect(spawnDatabaseMaintenanceWorker.mock.calls[1][1]).not.toBe(token);
});
diff --git a/server/services/databaseMaintenanceCutover.js b/server/services/databaseMaintenanceCutover.js
index 5c109ed442..eb583649d2 100644
--- a/server/services/databaseMaintenanceCutover.js
+++ b/server/services/databaseMaintenanceCutover.js
@@ -188,25 +188,37 @@ export async function runDatabaseCutover(id, token, options = {}) {
importCommitted: true, sourceRetained: true, restartVerified: true, cosRestarted };
}
-/**
- * Same-operation recovery for the operator CLI and the authenticated API.
- * Requires the current owner's supervisor exit receipt (or an owner whose
- * worker was never reserved); repeated calls reuse the one persisted successor
- * and never start a second worker for it. Returns bounded status only.
- */
-export async function recoverDatabaseCutover(id) {
- const journal = createDatabaseMaintenanceJournal();
- const token = journal.prepareRecovery(id);
- if (!token) return { id, stage: journal.read()?.stage ?? 'idle', recovery: 'running' };
+async function launchRecoveryWorker(journal, id, token) {
const { spawnDatabaseMaintenanceWorker } = await import('../lib/detachedSpawn.js');
let worker;
try {
worker = await spawnDatabaseMaintenanceWorker(id, token);
} catch {
// A concurrent recovery already reserved this successor's one-use worker.
- if (journal.coordinatorStatus(id).state === 'awaiting-exit') return { id, stage: journal.read()?.stage ?? 'idle', recovery: 'running' };
+ if (journal.coordinatorStatus(id).state === 'awaiting-exit') return 'running';
throw refused('the recovery worker could not be launched');
}
worker.on('error', () => console.error('❌ Database cutover recovery worker failed to launch'));
- return { id, stage: journal.read()?.stage ?? 'idle', recovery: 'launched' };
+ return 'launched';
+}
+
+/**
+ * Same-operation recovery for the operator CLI and the authenticated API.
+ * Requires the current owner's supervisor exit receipt (or an owner whose
+ * worker was never reserved); repeated calls reuse the one persisted successor
+ * and never start a second worker for it. Returns bounded status plus a
+ * `launch` step (null when the current worker is still running), so an HTTP
+ * caller can respond before the worker stops this server.
+ */
+export function beginDatabaseCutoverRecovery(id) {
+ const journal = createDatabaseMaintenanceJournal();
+ const token = journal.prepareRecovery(id);
+ const stage = journal.read()?.stage ?? 'idle';
+ if (!token) return { status: { id, stage, recovery: 'running' }, launch: null };
+ return { status: { id, stage, recovery: 'launching' }, launch: () => launchRecoveryWorker(journal, id, token) };
+}
+
+export async function recoverDatabaseCutover(id) {
+ const { status, launch } = beginDatabaseCutoverRecovery(id);
+ return launch ? { ...status, recovery: await launch() } : status;
}
diff --git a/server/services/databasePreflight.js b/server/services/databasePreflight.js
index 5eb700cd5d..07346c8cd0 100644
--- a/server/services/databasePreflight.js
+++ b/server/services/databasePreflight.js
@@ -94,9 +94,13 @@ export async function preflightDatabaseMaintenance(input) {
* operation — which closes admission synchronously — and repeats the idle and
* configuration checks UNDER the fence: work admitted just before publication
* must already be finished, and nothing new can be admitted. Only then does a
- * coordinator take ownership and the detached worker launch. A failed final
- * check cancels the still-unowned operation — but only while the saved source
- * still equals the recorded one; otherwise the fence stays for the operator.
+ * coordinator take ownership. A failed final check cancels the still-unowned
+ * operation — but only while the saved source still equals the recorded one;
+ * otherwise the fence stays for the operator.
+ *
+ * Returns `{ accepted, launch }`. The caller runs `launch()` only after its
+ * response is sent: the worker's first act is stopping this server. An owner
+ * whose worker never launched is resumable with same-operation recovery.
*/
export async function acceptDatabaseMaintenance(input) {
const direction = databaseMaintenancePreflightSchema.parse(input);
@@ -127,7 +131,13 @@ export async function acceptDatabaseMaintenance(input) {
}
const token = journal.acquireCoordinator(operation.id);
const { spawnDatabaseMaintenanceWorker } = await import('../lib/detachedSpawn.js');
- const worker = await spawnDatabaseMaintenanceWorker(operation.id, token);
- worker.on('error', () => console.error('❌ Database cutover worker failed to launch; inspect scripts/database-maintenance.mjs status'));
- return { id: operation.id, stage: 'accepted', source: direction.source, target: direction.target, accepted: true };
+ const launch = async () => {
+ try {
+ const worker = await spawnDatabaseMaintenanceWorker(operation.id, token);
+ worker.on('error', () => console.error('❌ Database cutover worker failed to launch; run scripts/database-maintenance.mjs recover'));
+ } catch {
+ console.error('❌ Database cutover worker failed to launch; run scripts/database-maintenance.mjs recover');
+ }
+ };
+ return { accepted: { id: operation.id, stage: 'accepted', source: direction.source, target: direction.target, accepted: true }, launch };
}
diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.js
index cf7e570f50..ec67a38d71 100644
--- a/server/services/dbAdmin.js
+++ b/server/services/dbAdmin.js
@@ -65,16 +65,19 @@ export function getMaintenanceStatus() {
}
/**
- * Accept an offline cutover (202). Serialized with every other database admin
- * mutation; the worker then stops PortOS, so the response is the last thing
- * this server process sends before its restart.
+ * Accept an offline cutover. Serialized with every other database admin
+ * mutation. Returns `{ accepted, launch }`: the route sends its 202 first and
+ * launches the worker afterward, because the worker then stops PortOS.
*/
export const acceptDatabaseCutover = (direction) => withDatabaseOperation(() => acceptDatabaseMaintenance(direction));
-/** Same-operation recovery. Runs while fenced, so it bypasses the admin lock. */
-export async function recoverDatabaseCutover(id) {
- const { recoverDatabaseCutover: recover } = await import('./databaseMaintenanceCutover.js');
- return recover(id);
+/**
+ * Same-operation recovery: `{ status, launch }`, launch deferred like
+ * acceptance. Runs while fenced, so it bypasses the admin lock.
+ */
+export async function beginDatabaseCutoverRecovery(id) {
+ const { beginDatabaseCutoverRecovery: begin } = await import('./databaseMaintenanceCutover.js');
+ return begin(id);
}
/**