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

feat: prove detached writer quiescence before database maintenance (#8870)

[._.]/ Adam Eivydb3e9bda51bd
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index dc42d7dcfa..680305e4a9 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -120,13 +120,13 @@ Coordinator ownership and cancellation share one exclusive durable initial claim
The journal also supplies an **internal ownership-recovery foundation**, not a callable transfer workflow. `reserveCoordinatorWorker(id, token)` atomically publishes a complete, one-use `worker-<token>/` directory bound to that operation and owner. A crash while preparing its binding leaves only an unpublished temporary directory, so the same owner can retry reservation. The internal `spawnDatabaseMaintenanceWorker(id, token)` path reserves this directory and uses the shared detached launcher with `cleanup: false`, a fixed Node executable and worker entrypoint, and no caller-selected command, arguments, environment, or control directory. It verifies current ownership before setup and again before supervisor launch. The worker claims an exclusive `started.json` marker before inspecting anything; copied arguments cannot enter it twice. Ordinary `spawnDetached` calls still require normal admission, even if passed extra options or an owner token. `recoverCoordinator(id, previousToken, recoveryToken)` accepts only the recorded operation and current token, at `accepted`, `quiescing`, `exporting`, or `importing`, after the detached supervisor has published a complete numeric `exit` receipt. The caller durably records its unique recovery token before attempting recovery. An immutable successor publication chooses exactly one winner across competing recoveries and revokes the old token; retrying that same recorded request returns its published token after a crash between publication and acknowledgement. A different claimant cannot recover or reuse the winner's token. A shared per-owner/per-stage decision publication serializes ownership handoff with stage transitions. Recovery completes an already-decided forward stage before choosing its successor; a predecessor that lost the decision cannot publish a new stage. Each successor reserves a new worker directory; old logs and completion evidence remain intact. Recovery preserves the source, target, operation ID, and stage. It does not treat an interrupted import as source success or advance to committing.
-There is deliberately no PID-death, elapsed-time, or force recovery. A launch interrupted before its supervisor records an exit stays fenced, even if its PID appears dead. A worker exit does **not** prove its descendants stopped: before any export or import, the future execution coordinator must inventory and stop/drain PM2 server and CoS processes, admitted spawns, and owned detached writers, refusing unknown state. It must retain the complete source dump and re-establish quiescence before retrying the same target transaction. Those execution and transfer steps remain tracked by #8850; verified target restart, saved-mode commit, and admission release remain #8851.
+There is deliberately no PID-death, elapsed-time, or force recovery. A launch interrupted before its supervisor records an exit stays fenced, even if its PID appears dead. A worker exit does **not** prove its descendants stopped: before any export or import, the execution coordinator must stop PM2 server and CoS processes (`stopOwnedDatabaseProducers`) and reconcile admitted spawns and owned detached writers (`reconcileDetachedWriters`), refusing unknown state. It must retain the complete source dump and re-establish quiescence before retrying the same target transaction. Those execution and transfer steps remain tracked by #8850; verified target restart, saved-mode commit, and admission release remain #8851.
For local diagnostics at any stage, run `node scripts/database-maintenance.mjs status`. An owned operation adds a bounded `coordinator` result: `unregistered` means no worker reservation; `awaiting-exit` means no supervisor completion proof (either running or interrupted); `exited` includes the supervisor exit code. Neither is a transfer-success verdict. Malformed ownership, binding, or exit records fail closed. Only an **unowned accepted** operation can use `node scripts/database-maintenance.mjs cancel <operation-id>` after checking saved source configuration. There is no operator recovery command for an owned/interrupted operation yet: preserve its journal, worker records, source, and any dump; do not delete markers or call `scripts/db.sh migrate` (still refused). No public lifecycle coordinator or ownership-recovery command is exposed by this foundation.
-`data/database-writers/<launch-id>/` is machine-local, file-primary **detached launch evidence**. `spawnDetached` publishes and fsyncs a reservation before its first asynchronous setup step, then checks admission again. A launch that races fence acceptance is therefore either refused or already represented in the inventory. It checks admission again after setup; a pending Windows supervisor is still an unresolved inventoried launch, not proof that no process exists. Reservations contain only a random launch ID, timestamp, control directory, and process-group mode; active immutable records contain the observed PID; completion first records its code/signal, then compacts the entry into one durable `unreconciled-exits.json` marker before deleting that completed entry. The marker is published from fsynced bytes and its parent directory is synced before deletion, so a crash retains either the launch details or the marker (possibly both). Commands, arguments, environment variables, credentials, and application records are excluded. A partial/unreadable record fails inventory closed. Active/unresolved details and the aggregated unknown-exit history survive control-directory cleanup and caller restart. Ordinary completed jobs do not accumulate one permanent directory per launch.
+`data/database-writers/<launch-id>/` is machine-local, file-primary **detached launch evidence**. `spawnDetached` publishes and fsyncs a reservation before its first asynchronous setup step, then checks admission again. A launch that races fence acceptance is therefore either refused or already represented in the inventory. It checks admission again after setup; a launch refused before any launcher started records `abandoned.json`, the only proof that no child exists. On POSIX the detached outer `sh` is a session and process-group leader, so its PID (`launcher.json`) names the group every supervisor/job descendant inherits; `launch.json` adds the job PID and launch time. Reservations contain only a random launch ID, timestamp, control directory, and process-group mode. Commands, arguments, environment variables, credentials, and application records are excluded. A partial/unreadable record fails inventory closed. On completion, POSIX keeps the identity and retires the entry only after two consecutive process-table snapshots show the job gone and every recorded group empty (a group ID cannot be reused while it has members); a surviving descendant or slow supervisor leaves the record for maintenance reconciliation. Windows has no group proof, so its completion still compacts into the identity-free `unreconciled-exits.json` marker, published from fsynced bytes with its parent directory synced before deletion. Ordinary completed jobs do not accumulate one permanent directory per launch.
-Run `node scripts/database-maintenance.mjs writers` for bounded counts at any stage; it always reports `quiescenceVerified: false` and exposes no control paths or process identities. A malformed inventory refuses the command. The internal `createDatabaseWriterRegistry().read()` returns `unresolved`, `launched`, or `exited` observations; a `{ state: 'unresolved', kind: 'retired-exits' }` entry represents compacted completion history. An `exited` entry can remain when compaction was interrupted or failed. **None proves descendant quiescence.** Do not infer safety from a PID probe, an exit record, an empty inventory on an upgraded install, or a successful reservation read while producers still run. Legacy children have no reservation, and admitted setup can still be pending. The offline coordinator must stop/drain producers, reconcile legacy and unknown children, establish descendant termination, then read this inventory before export. Active/unresolved entries and the aggregated unknown-history marker are retained until that coordinator supplies a verified reconciliation/retirement protocol; neither the CLI nor normal completion clears the marker. Do not delete them to unblock maintenance. They are local recovery evidence included in backups, never a federated application collection or reference seed. Public transfer entrypoints remain disabled, and there is no admission bypass flag for detached launches. The fixed maintenance worker can launch while fenced, but can only inspect this bounded inventory: it reports direction, stage, counts, `quiescenceVerified: false`, and `transferReady: false`, then exits with code 78 (transfer not integrated). Empty inventory is not a successful cutover. Damaged ownership or inventory exits with code 1 and a redacted refusal. Its stdout/stderr, owner binding, one-use entry marker, and supervisor receipt remain in the reserved directory. It changes neither stage nor saved mode, stops no processes, and starts no child writers. This internal foundation is not wired to an operator launch or recovery command.
+Run `node scripts/database-maintenance.mjs writers` for bounded counts at any stage (`unresolved`, `launching`, `launched`, `exited`, `abandoned`); it always reports `quiescenceVerified: false` and exposes no control paths or process identities. A malformed inventory refuses the command. A `{ state: 'unresolved', kind: 'retired-exits' }` entry represents legacy or Windows compacted completion history. **An inventory read never proves descendant quiescence.** Only the internal `reconcileDetachedWriters(id, token)` stage (`server/services/databaseMaintenanceQuiescence.js`) can, and only for the owning coordinator worker after `stopOwnedDatabaseProducers` recorded producer shutdown at `quiescing`. It classifies each record against a POSIX process-table snapshot: a job still alive with a verified identity (its PGID is recorded and it started inside the launch window) has its recorded groups sent SIGTERM, then SIGKILL after a grace period; a group seen empty is never signalled again. It refuses, leaving the fence and every record in place, when an admitted launch has not recorded a process identity, when a record is legacy/compacted or lacks a launcher group, when a live PID does not match its recorded identity (possible reuse), when an exited job still has surviving group members, when groups do not terminate, when a detached supervisor of this install's data directory is running without a record (for example a launch from code that predates the registry), or on Windows for anything but abandoned launches. Two consecutive quiescent snapshots are required before it archives every record to `data/database-maintenance/reconciled-writers/<launch-id>/` and returns `quiescenceVerified: true, transferReady: false`. It never infers absence from a PID probe or elapsed time and has no force/skip option. It is internal: `quiesceDatabaseWriters(id, token)` runs producer shutdown then reconciliation, and no operator or public entrypoint invokes either; export/import (#8871) must re-run it before relying on its result. Limits: a descendant that deliberately leaves its session and process group (`setsid`) is not observable by group, and orphans of a pre-registry launch whose supervisor already exited cannot be identified. Records are local recovery evidence included in backups, never a federated application collection or reference seed; do not delete them to unblock maintenance. The fixed maintenance worker can launch while fenced, but can only inspect this bounded inventory: it reports direction, stage, counts, `quiescenceVerified: false`, and `transferReady: false`, then exits with code 78 (transfer not integrated). Empty inventory is not a successful cutover. Damaged ownership or inventory exits with code 1 and a redacted refusal. Its stdout/stderr, owner binding, one-use entry marker, and supervisor receipt remain in the reserved directory. It changes neither stage nor saved mode, stops no processes, and starts no child writers. This internal foundation is not wired to an operator launch or recovery command.
A cancelled unowned accepted operation moves to `data/database-maintenance-cancelled/<operation-id>/` as local recovery evidence. These records remain filesystem-backed and included in backups; they are not a growing application collection. Restoring an active journal deliberately restores its fence: do not delete it merely to make startup succeed. See [database maintenance admission](BACKUP.md#database-maintenance-admission) for the operator contract and current limitations.
@@ -290,9 +290,10 @@ stop. Missing/duplicate/foreign identities, changed live PIDs, unknown lifecycle
states, failed stops, or failed readback keep the operation fenced. Recovery
uses the same recorded operation and original identities; it never changes the
saved backend. Producer shutdown alone does **not** prove child/spawn quiescence
-or authorize a dump. Public migration and the inspection-only worker remain
-disabled for transfer until descendant reconciliation (#8870), transfer (#8871),
-and verified restart (#8851) are integrated.
+or authorize a dump. Descendant reconciliation (`reconcileDetachedWriters`, described under the
+database maintenance journal above) must follow it in the same worker. Public
+migration and the inspection-only worker remain disabled for transfer until
+transfer (#8871) and verified restart (#8851) are integrated.
For stage diagnostics, run `node scripts/database-maintenance.mjs status` and
`node scripts/database-maintenance.mjs writers`. `accepted` means no transfer
diff --git a/scripts/database-maintenance-worker.mjs b/scripts/database-maintenance-worker.mjs
index e7d01c9008..1a57e92f24 100644
--- a/scripts/database-maintenance-worker.mjs
+++ b/scripts/database-maintenance-worker.mjs
@@ -11,7 +11,7 @@ try {
const [id, token] = args;
const journal = createDatabaseMaintenanceJournal();
const operation = journal.enterCoordinatorWorker(id, token);
- const writers = { unresolved: 0, launched: 0, exited: 0 };
+ const writers = { unresolved: 0, launching: 0, launched: 0, exited: 0, abandoned: 0 };
for (const writer of createDatabaseWriterRegistry().read()) writers[writer.state] += 1;
journal.assertCoordinatorWorker(id, token);
console.log(JSON.stringify({ id: operation.id, stage: operation.stage,
diff --git a/scripts/database-maintenance.mjs b/scripts/database-maintenance.mjs
index 2a904f2e54..754cabbc93 100644
--- a/scripts/database-maintenance.mjs
+++ b/scripts/database-maintenance.mjs
@@ -21,7 +21,7 @@ function configuredEndpoints() {
function main() {
const [command, ...args] = process.argv.slice(2);
if (command === 'writers' && args.length === 0) {
- const counts = { unresolved: 0, launched: 0, exited: 0 };
+ const counts = { unresolved: 0, launching: 0, launched: 0, exited: 0, abandoned: 0 };
for (const writer of createDatabaseWriterRegistry().read()) counts[writer.state] += 1;
return { ...counts, quiescenceVerified: false };
}
diff --git a/server/lib/README.md b/server/lib/README.md
index 4a8436ff93..8342b7d28f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -392,7 +392,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. Sibling `commandOutput(cmd, args, opts)` runs the same probe but returns the trimmed stdout (or `null` when it could not run / exited non-zero), so a caller can read a `--version` banner or a `models` listing without spawning the same child twice. |
| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI AGENTS.md / CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.
| `commandSecurity.js` | Two allowlists, one parser. `validateCommand(cmd)` gates the OPERATOR-driven runner against `ALLOWED_COMMANDS` (+ `validatePm2Command(args)`, which rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateUnattendedCommand(cmd)` gates the UNATTENDED lane (Layered Intelligence `cmd` sources) against the far narrower `UNATTENDED_READONLY_COMMANDS` — read-only inspection binaries only, no `npx`/`node`/`python`/`pip`/`curl`/`wget`/`brew`, since those execute network code with no shell metacharacter — then applies a per-binary SUBCOMMAND gate to the multi-purpose survivors, so `git reset --hard` / `git commit`, `find -delete` / `-exec`, and `gh`/`glab` writes (`api -X POST`, `pr merge`) are rejected while `git log`, `find -name` and `gh pr list` pass. Both share one parse + `DANGEROUS_SHELL_CHARS` body. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
-| `detachedSpawn.js` | `spawnDatabaseMaintenanceWorker(id, token)` launches only the fixed, one-use fenced inspection worker and retains its supervisor evidence; it grants no ordinary launch bypass or transfer authority. `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
+| `detachedSpawn.js` | `spawnDatabaseMaintenanceWorker(id, token)` launches only the fixed, one-use fenced inspection worker and retains its supervisor evidence; it grants no ordinary launch bypass or transfer authority. `spawnDetached(bin, args, {controlDir,env,cwd,killProcessGroup?})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Group-kill mode persists a marker so cancel, reattach, and orphan reaping terminate a group-leader wrapper plus every runtime child together. Windows reaches the same place through a powershell supervisor started by a launcher that exits (never `detached:true`, which there means DETACHED_PROCESS and leaves a console host no console to run in), writing the same control files — so both platforms survive the restart AND take the runner's children down on cancel (`taskkill /T /F` there, the process group on POSIX). Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart, `isDetachedRunning(controlDir, expectedProcess?)` with optional executable/argument validation for fixed-command control dirs, and `reapDetached` to checkpoint-kill one when re-attach isn't possible. `snapshotProcesses()` (POSIX pid/pgid/start/command table, fails closed on unreadable rows), `signalProcessGroup(pgid, signal)` and `isDetachedSupervisorCommand(command)` back database-maintenance descendant reconciliation; completed POSIX launches retire their registry record once two snapshots prove the launcher group empty. |
| `hostShutdown.js` | Tells "PortOS was restarted out from under a running agent" apart from "the agent failed" (#3202). `markHostShuttingDown()` / `isHostShuttingDown()` are the in-process latch the SIGTERM/SIGINT handler sets first thing; `shouldAbandonForHostShutdown({sentinelPresent,terminatedByUser,paused})` keeps every spawn path on the same preserve-vs-finalize policy. `writeHostShutdownMarker({agentIds,signal})` / `readHostShutdownMarker()` / `clearHostShutdownMarker()` persist that verdict to `data/cos/host-shutdown.json` so the NEXT boot's orphan sweep can requeue those agents as *interrupted* — no orphan-retry charge, no 30-minute cooldown. All non-throwing: a missing marker degrades to the ordinary orphan path. |
| `httpDrain.js` | `createHttpDrain(servers)` tracks every ordinary request the HTTP listeners accept; `begin(windowMs)` is the synchronous shutdown step that stops intake on all of them (`server.close()` plus a 503 `Connection: close` gate for requests arriving on still-open keep-alive sockets), turns off keep-alive on in-flight responses, drops open SSE streams, and resolves `{ remaining }` once accepted requests finish or the window ends (#8323). |
| `httpCompression.js` | `httpCompression` negotiates Brotli/gzip for API and static responses while preserving streaming, ranges, existing encodings, and `no-transform`. |
@@ -768,4 +768,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `databaseMaintenanceJournal.js` | Shared `databaseMaintenanceEndpointSchema` plus durable cross-process database admission fence and operation journal with exclusive coordinator ownership, one-use detached worker reservations, exit-receipt-gated ownership recovery, and durable forward-only stages; source-only cancellation archives an unowned accepted operation. |
-| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations with completed launches compacted into a durable unresolved-history marker; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. Completion is evidence, never descendant-quiescence authority. |
+| `databaseWriterRegistry.js` | `createDatabaseWriterRegistry(dataDir?)` supplies durable detached launch reservations and inventory observations (reservation, POSIX launcher group, job PID, abandonment, completion) plus `retire(id, archiveDir?)` for proven-quiescent records; `reserveDatabaseWriter` is the mandatory `spawnDetached` admission boundary. `classifyWriterQuiescence(row, processes)` classifies a row against a process-table snapshot (quiescent / running / orphaned / pending / ambiguous) without probing PIDs. Legacy compacted history and Windows completions stay unresolved. |
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.js
index 6f040f3c68..e9ab19d1c7 100644
--- a/server/lib/databaseMaintenanceWorker.test.js
+++ b/server/lib/databaseMaintenanceWorker.test.js
@@ -54,7 +54,7 @@ describe('owned maintenance worker launch', () => {
expect(outcomes.map(value => value.status).sort((a, b) => a - b)).toEqual([1, 78]);
const inspection = JSON.parse(outcomes.find(value => value.status === 78).stdout);
expect(inspection).toEqual({ id: operation.id, stage: 'accepted', source: from.mode, target: to.mode,
- writers: { unresolved: 0, launched: 0, exited: 0 }, quiescenceVerified: false, transferReady: false });
+ writers: { unresolved: 0, launching: 0, launched: 0, exited: 0, abandoned: 0 }, quiescenceVerified: false, transferReady: false });
expect(journal.read()).toEqual(operation);
expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'exited', exitCode: 78 });
expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toEqual([]);
diff --git a/server/lib/databaseWriterRegistry.js b/server/lib/databaseWriterRegistry.js
index 48ae6196a6..173607599b 100644
--- a/server/lib/databaseWriterRegistry.js
+++ b/server/lib/databaseWriterRegistry.js
@@ -1,4 +1,4 @@
-import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, writeFileSync, linkSync, rmSync } from 'node:fs';
+import { closeSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, writeFileSync, linkSync, rmSync } from 'node:fs';
import { isAbsolute, join, resolve } from 'node:path';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
@@ -10,7 +10,15 @@ const reservationSchema = z.object({
version: z.literal(1), id: z.string().uuid(), controlDir: z.string().refine(isAbsolute),
createdAt: z.string().datetime(), processGroup: z.boolean(),
}).strict();
-const launchSchema = z.object({ pid: z.number().int().positive() }).strict();
+// `launchedAt` is absent on launches recorded before descendant
+// reconciliation existed; such a record can never prove its process identity.
+const launchSchema = z.object({
+ pid: z.number().int().positive(), launchedAt: z.string().datetime().optional(),
+}).strict();
+// POSIX only: the detached outer `sh` is a session and process-group leader,
+// so its PID names the group every supervisor/job descendant inherits.
+const launcherSchema = z.object({ pid: z.number().int().positive() }).strict();
+const abandonedSchema = z.object({ version: z.literal(1) }).strict();
const completionSchema = z.object({
code: z.number().int().nullable(), signal: z.string().nullable(),
}).strict();
@@ -44,6 +52,39 @@ function readRecord(directory, name, schema, optional = false) {
export function createDatabaseWriterRegistry(dataDir = PATHS.data) {
const directory = join(dataDir, 'database-writers');
const journal = createDatabaseMaintenanceJournal(dataDir);
+ const readEntry = (name) => {
+ if (!z.string().uuid().safeParse(name).success) throw refused();
+ const entry = join(directory, name);
+ if (!lstatSync(entry).isDirectory()) throw refused();
+ const record = readRecord(entry, 'reservation.json', reservationSchema);
+ if (record.id !== name) throw refused();
+ const launcher = readRecord(entry, 'launcher.json', launcherSchema, true);
+ const launch = readRecord(entry, 'launch.json', launchSchema, true);
+ const completion = readRecord(entry, 'completion.json', completionSchema, true);
+ const abandoned = readRecord(entry, 'abandoned.json', abandonedSchema, true);
+ // A completion needs SOME process identity to reconcile; a refusal before
+ // launch must not coexist with evidence that a launcher started.
+ if ((completion && !launch && !launcher) || (abandoned && (launcher || launch || completion))) throw refused();
+ const state = abandoned ? 'abandoned' : completion ? 'exited' : launch ? 'launched'
+ : launcher ? 'launching' : 'unresolved';
+ return { ...record, state, ...(launcher ? { launcherPid: launcher.pid } : {}),
+ ...(launch ?? {}), ...(completion ? { completion } : {}) };
+ };
+ // Retirement is only for records a caller has PROVEN quiescent (or that
+ // never launched). Archiving keeps the identity evidence with the operation.
+ const retire = (id, archiveDir = null) => {
+ assertNotRealDataWrite(directory, 'detached writer retirement');
+ readEntry(id);
+ const entry = join(directory, id);
+ if (archiveDir) {
+ mkdirSync(archiveDir, { recursive: true, mode: 0o700 });
+ renameSync(entry, join(archiveDir, id));
+ syncDirectory(archiveDir);
+ } else {
+ rmSync(entry, { recursive: true });
+ }
+ syncDirectory(directory);
+ };
const reserve = (controlDir, processGroup = false) => {
assertNotRealDataWrite(directory, 'detached writer reservation');
// Reject already-fenced callers without creating records. This check is an
@@ -65,14 +106,25 @@ export function createDatabaseWriterRegistry(dataDir = PATHS.data) {
const assertLaunchAllowed = () => journal.assertAdmission();
assertLaunchAllowed();
return {
+ id: record.id,
assertLaunchAllowed,
- launched: pid => publish(entry, 'launch.json', launchSchema.parse({ pid })),
+ // Published as soon as the launcher spawns. A crash before this write
+ // leaves the reservation unresolved, which reconciliation refuses.
+ launcher: pid => publish(entry, 'launcher.json', launcherSchema.parse({ pid })),
+ launched: pid => publish(entry, 'launch.json', launchSchema.parse({ pid, launchedAt: new Date().toISOString() })),
+ // Only for a launch refused before any launcher process was started.
+ abandoned: () => publish(entry, 'abandoned.json', { version: 1 }),
+ inspect: () => readEntry(record.id),
+ retire: () => retire(record.id),
completed: (code, signal) => {
publish(entry, 'completion.json', completionSchema.parse({ code, signal }));
+ // POSIX retains the identity so descendant reconciliation can prove the
+ // launcher group empty (the spawner retires it at once when it can).
+ if (process.platform !== 'win32') return;
+ // Windows has no process-group proof, so its identity has no use:
+ // compact into the persistent UNKNOWN-history marker (never absence).
// Missing launch identity stays unresolved and retains its details.
readRecord(entry, 'launch.json', launchSchema);
- // An exit does not prove descendant termination. Compact completed
- // details into a persistent UNKNOWN-history marker, never into absence.
// Publish fully fsynced bytes atomically, and sync the parent BEFORE
// deletion. Competing completions share one immutable marker.
publish(entry, 'retirement.json', { version: 1 });
@@ -97,23 +149,54 @@ export function createDatabaseWriterRegistry(dataDir = PATHS.data) {
const retired = names.includes(RETIRED_EXITS);
if (retired) readRecord(directory, RETIRED_EXITS, retirementSchema);
const writers = names.filter(name => name !== RETIRED_EXITS).sort().map(name => {
- if (!z.string().uuid().safeParse(name).success) throw refused();
- const entry = join(directory, name);
- if (!lstatSync(entry).isDirectory()) throw refused();
- const record = readRecord(entry, 'reservation.json', reservationSchema);
- if (record.id !== name) throw refused();
- const launch = readRecord(entry, 'launch.json', launchSchema, true);
- const completion = readRecord(entry, 'completion.json', completionSchema, true);
- if (completion && !launch) throw refused();
- return { ...record, state: completion ? 'exited' : launch ? 'launched' : 'unresolved',
- ...(launch ?? {}), ...(completion ? { completion } : {}) };
+ try { return readEntry(name); } catch { throw refused(); }
});
// Keep this in the inventory itself so a consumer cannot accidentally read
// only current launch rows and mistake a compacted history for an empty set.
if (retired) writers.push({ state: 'unresolved', kind: 'retired-exits' });
return writers;
};
- return { reserve, read };
+ return { reserve, read, retire };
}
export const reserveDatabaseWriter = (...args) => createDatabaseWriterRegistry().reserve(...args);
+
+// ps reports start time at one-second resolution, truncated.
+const START_SLACK_MS = 2000;
+
+/**
+ * Classify one inventory row against a POSIX process-table snapshot of
+ * { pid, pgid, startedAt } rows. Pure: it never probes or signals a PID.
+ *
+ * - quiescent: nothing was launched, or the job is gone AND every recorded
+ * process group is empty (a group ID cannot be reused while it has members).
+ * - running: the recorded job is alive with a verified identity (its group is
+ * recorded and it started inside this launch's window), so terminating its
+ * recorded groups reaches only this launch's tree.
+ * - orphaned: the job is gone but its groups still hold survivors.
+ * - pending: an admitted launch that recorded no process identity yet.
+ * - ambiguous: legacy/compacted history, no launcher group, or an identity
+ * mismatch (possible PID reuse). Never safe to signal or to ignore.
+ */
+export function classifyWriterQuiescence(row, processes) {
+ if (row.kind === 'retired-exits') return { verdict: 'ambiguous', groups: [] };
+ if (row.state === 'abandoned') return { verdict: 'quiescent', groups: [] };
+ if (row.state === 'unresolved') return { verdict: 'pending', groups: [] };
+ if (!row.launcherPid || (row.pid && !row.launchedAt)) return { verdict: 'ambiguous', groups: [] };
+ const groups = [...new Set([row.launcherPid, ...(row.processGroup && row.pid ? [row.pid] : [])])];
+ const earliest = Math.floor(Date.parse(row.createdAt) / 1000) * 1000 - START_SLACK_MS;
+ const latest = (row.launchedAt ? Date.parse(row.launchedAt) : Date.now()) + START_SLACK_MS;
+ const inWindow = proc => proc.startedAt >= earliest && proc.startedAt <= latest;
+ // A live process holding a recorded group's own ID must be that group's
+ // original leader; anything else is a reused ID we must not touch.
+ if (processes.some(proc => groups.includes(proc.pid) && proc.pgid === proc.pid && !inWindow(proc))) {
+ return { verdict: 'ambiguous', groups };
+ }
+ const job = row.pid ? processes.find(proc => proc.pid === row.pid) : null;
+ if (job) {
+ // The supervisor already reported this job's exit: a live PID is reuse.
+ if (row.state === 'exited' || !groups.includes(job.pgid) || !inWindow(job)) return { verdict: 'ambiguous', groups };
+ return { verdict: 'running', groups };
+ }
+ return { verdict: processes.some(proc => groups.includes(proc.pgid)) ? 'orphaned' : 'quiescent', groups };
+}
diff --git a/server/lib/databaseWriterRegistry.test.js b/server/lib/databaseWriterRegistry.test.js
index 60274ad508..a65b9a7e1c 100644
--- a/server/lib/databaseWriterRegistry.test.js
+++ b/server/lib/databaseWriterRegistry.test.js
@@ -70,44 +70,34 @@ describe('durable detached launch admission', () => {
const result = await observe(handle);
expect(result.error?.code).toBe('DATABASE_MAINTENANCE');
expect(() => readFileSync(ran)).toThrow();
- expect(registry.read()).toEqual([reserved]);
+ // A refusal before any launcher started is durable proof of no child.
+ expect(registry.read()).toEqual([{ ...reserved, state: 'abandoned' }]);
expect(() => journal.assertAdmission()).toThrow();
});
- it('compacts repeated completed launches into durable unknown history after control cleanup', async () => {
+ it.skipIf(process.platform === 'win32')('retires completed launches only once their process groups are proven empty', async () => {
for (let index = 0; index < 3; index += 1) {
const controlDir = join(root, `control-${index}`);
const handle = await spawnDetached(process.execPath, ['-e', 'process.exit(7)'], {
controlDir, cleanup: true, pollMs: 10,
});
- expect(registry.read()).toContainEqual(expect.objectContaining({ state: 'launched', pid: handle.pid, controlDir }));
+ expect(registry.read()).toContainEqual(expect.objectContaining({ state: 'launched', pid: handle.pid, controlDir,
+ launcherPid: expect.any(Number), launchedAt: expect.any(String) }));
expect(await observe(handle)).toEqual({ code: 7, signal: null });
- expect(registry.read()).toEqual([{ state: 'unresolved', kind: 'retired-exits' }]);
+ // Ordinary completed jobs leave no per-launch directory behind.
+ await vi.waitFor(() => expect(registry.read()).toEqual([]), { timeout: 5000, interval: 20 });
}
- // A fresh reader sees the same warning after restart; no per-exit files
- // accumulate and no control path or PID is inferred to be safe to kill.
- expect(createDatabaseWriterRegistry(context.data).read()).toEqual([{ state: 'unresolved', kind: 'retired-exits' }]);
- expect(readdirSync(join(context.data, 'database-writers'))).toEqual(['unreconciled-exits.json']);
+ expect(readdirSync(join(context.data, 'database-writers'))).toEqual([]);
});
- it.each(['history', 'launch'])('retains launch details when %s evidence cannot support safe compaction', async (missing) => {
- const finish = join(root, 'finish');
- const handle = await spawnDetached(process.execPath, ['-e',
- `const t=setInterval(()=>{if(require('fs').existsSync(${JSON.stringify(finish)})){clearInterval(t);}},10);`], {
- controlDir: join(root, 'control'), pollMs: 10,
- });
- const [record] = registry.read();
- // Simulate corrupt/interrupted retirement publication. It must never turn
- // the known launch into absence even though its child completes normally.
- if (missing === 'history') mkdirSync(join(context.data, 'database-writers', 'unreconciled-exits.json'));
- else unlinkSync(join(context.data, 'database-writers', record.id, 'launch.json'));
- const done = observe(handle);
- writeFileSync(finish, '');
- expect(await done).toEqual({ code: 0, signal: null });
- expect(JSON.parse(readFileSync(join(context.data, 'database-writers', record.id, 'reservation.json'), 'utf8')).id).toBe(record.id);
- expect(JSON.parse(readFileSync(join(context.data, 'database-writers', record.id, 'completion.json'), 'utf8'))).toEqual({ code: 0, signal: null });
+ it('fails closed on legacy compacted exit history and refuses to extend it when unreadable', () => {
+ mkdirSync(join(context.data, 'database-writers'), { recursive: true });
+ writeFileSync(join(context.data, 'database-writers', 'unreconciled-exits.json'), JSON.stringify({ version: 1 }));
+ expect(registry.read()).toEqual([{ state: 'unresolved', kind: 'retired-exits' }]);
+ unlinkSync(join(context.data, 'database-writers', 'unreconciled-exits.json'));
+ mkdirSync(join(context.data, 'database-writers', 'unreconciled-exits.json'));
expect(() => registry.read()).toThrow(/incomplete/);
- if (missing === 'history') expect(() => registry.reserve(join(root, 'next-control'))).toThrow(/incomplete/);
+ expect(() => registry.reserve(join(root, 'next-control'))).toThrow(/incomplete/);
});
it('rejects an already-fenced launch without touching its control directory', async () => {
@@ -128,7 +118,7 @@ describe('durable detached launch admission', () => {
encoding: 'utf8', env: { ...process.env, PORTOS_DATA_ROOT: root }, timeout: 10000,
});
expect(result.status).toBe(0);
- expect(JSON.parse(result.stdout)).toEqual({ unresolved: 1, launched: 0, exited: 0, quiescenceVerified: false });
+ expect(JSON.parse(result.stdout)).toEqual({ unresolved: 1, launching: 0, launched: 0, exited: 0, abandoned: 0, quiescenceVerified: false });
expect(result.stdout).not.toContain(root);
});
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 0bf4d4aa2f..e96444537c 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -62,7 +62,7 @@ import { ensureDir, sleep } from './fileUtils.js';
import { safeChildProcessOptions } from './processEnv.js';
import { quoteForShell } from './shellCd.js';
import { withSpawnCwdEnv } from './spawnCwd.js';
-import { reserveDatabaseWriter } from './databaseWriterRegistry.js';
+import { classifyWriterQuiescence, reserveDatabaseWriter } from './databaseWriterRegistry.js';
const execFileAsync = promisify(execFile);
@@ -514,6 +514,58 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {
return { tick, finish };
}
+const markAbandoned = (writer) => {
+ try { writer.abandoned?.(); } catch {
+ console.error('❌ Could not persist abandoned detached launch evidence');
+ }
+};
+
+// Process-table snapshot, POSIX only. `lstart` is fixed-format under LC_ALL=C;
+// an unparseable row throws rather than being skipped, because a skipped row
+// could be exactly the surviving writer a caller is looking for.
+const PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d{1,2} \d{2}:\d{2}:\d{2} \d{4})\s?(.*)$/;
+export async function snapshotProcesses() {
+ if (process.platform === 'win32') throw new Error('Process-group snapshots are unavailable on Windows');
+ const { stdout } = await execFileAsync('ps', ['-A', '-ww', '-o', 'pid=', '-o', 'pgid=', '-o', 'lstart=', '-o', 'command='],
+ safeChildProcessOptions({ timeout: 15000, maxBuffer: 32 * 1024 * 1024, env: { ...process.env, LC_ALL: 'C' } }));
+ const rows = stdout.split('\n').filter(line => line.trim()).map((line) => {
+ const match = PS_ROW.exec(line);
+ const startedAt = match ? Date.parse(match[3]) : NaN;
+ if (!match || !Number.isFinite(startedAt)) throw new Error('Unreadable process table');
+ return { pid: Number(match[1]), pgid: Number(match[2]), startedAt, command: match[4] };
+ });
+ if (!rows.some(row => row.pid === process.pid)) throw new Error('Incomplete process table');
+ return rows;
+}
+
+// The supervisor subshell of EVERY detached launch — including launches from
+// versions that predate the writer registry — runs this exact script text.
+export const isDetachedSupervisorCommand = (command) => command.includes('d="$1"; shift') && command.includes('$d/pid');
+
+// Signal a whole process group; false when it no longer exists.
+export const signalProcessGroup = (pgid, signal) => {
+ try { process.kill(-pgid, signal); return true; } catch (err) {
+ if (err.code === 'ESRCH') return false;
+ throw err;
+ }
+};
+
+// On completion, retire a POSIX record only after two consecutive snapshots
+// prove the job gone and its recorded groups empty. Survivors (or a slow
+// supervisor) leave the identity retained for maintenance reconciliation.
+const RETIRE_ATTEMPTS = 3;
+const RETIRE_INTERVAL_MS = 200;
+async function retireQuiescentWriter(writer) {
+ if (process.platform === 'win32' || !writer.inspect || !writer.retire) return;
+ let consecutive = 0;
+ for (let attempt = 0; attempt < RETIRE_ATTEMPTS + 1 && consecutive < 2; attempt += 1) {
+ if (attempt > 0) await sleep(RETIRE_INTERVAL_MS);
+ const verdict = classifyWriterQuiescence(writer.inspect(), await snapshotProcesses()).verdict;
+ consecutive = verdict === 'quiescent' ? consecutive + 1 : 0;
+ }
+ if (consecutive >= 2) writer.retire();
+}
+
/**
* Spawn a detached, pm2-restart-surviving child process.
*
@@ -587,7 +639,12 @@ async function spawnDetachedWithReservation(bin, args, {
console.error('❌ Could not persist detached writer completion evidence');
}
};
- handle.once('close', recordCompletion);
+ handle.once('close', (code, signal) => {
+ recordCompletion(code, signal);
+ retireQuiescentWriter(writer).catch(() => {
+ // Retained evidence is reconciled later; it is never treated as absence.
+ });
+ });
const pidFile = join(controlDir, 'pid');
const exitFile = join(controlDir, 'exit');
@@ -608,6 +665,7 @@ async function spawnDetachedWithReservation(bin, args, {
() => (killProcessGroup ? writeFile(groupKillFile, '1') : null),
).then(() => null, (err) => err);
if (ensureControlDir) {
+ markAbandoned(writer);
setImmediate(() => {
if (cleanup) rm(controlDir, { recursive: true, force: true }).catch(() => {});
handle.emit('error', ensureControlDir);
@@ -628,6 +686,9 @@ async function spawnDetachedWithReservation(bin, args, {
// too; route that into the same slot rather than letting it reject
// spawnDetached, for the reason ensureControlDir above spells out.
try { writer.assertLaunchAllowed(); } catch (err) {
+ // Nothing was launched, so the reservation can say so durably. Without
+ // this, an admitted launch refused by the fence would stay unresolved.
+ markAbandoned(writer);
setImmediate(() => handle.emit('error', err));
return handle;
}
@@ -643,6 +704,11 @@ async function spawnDetachedWithReservation(bin, args, {
detached: true,
stdio: 'ignore',
});
+ if (!isWindows && launcher?.pid) {
+ try { writer.launcher?.(launcher.pid); } catch {
+ console.error('❌ Could not persist detached launcher group evidence');
+ }
+ }
launcher?.on('error', (err) => { launcherSpawnError = err; });
launcher?.on('exit', (code) => { launcherExit = Number.isInteger(code) ? code : 'signal'; });
launcher?.unref();
diff --git a/server/services/README.md b/server/services/README.md
index d88ebbda25..d63f117874 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -7,6 +7,7 @@ image-generation paths below are useful entry points when tracing render jobs.
| Module | Responsibility |
| --- | --- |
| `databaseMaintenanceProducers.js` | Internal one-use coordinator stage: retain producer identity, stop this install's PM2 CoS/server, and verify fresh readback while admission remains fenced. |
+| `databaseMaintenanceQuiescence.js` | Internal coordinator stage after producer shutdown: terminate verified running detached-writer groups, prove every registry record quiescent from process-table evidence, archive it with the operation, and refuse pending, legacy, orphaned, ambiguous or unregistered writers. |
| `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. |
| `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. |
| `universeBuilderRender.js` | Universe Builder batch render jobs. |
diff --git a/server/services/databaseMaintenanceQuiescence.js b/server/services/databaseMaintenanceQuiescence.js
new file mode 100644
index 0000000000..936c5a6f1a
--- /dev/null
+++ b/server/services/databaseMaintenanceQuiescence.js
@@ -0,0 +1,110 @@
+import { join, sep } from 'node:path';
+import { PATHS } from '../lib/paths.js';
+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';
+import { classifyWriterQuiescence, createDatabaseWriterRegistry } from '../lib/databaseWriterRegistry.js';
+import { isDetachedSupervisorCommand, signalProcessGroup, snapshotProcesses } from '../lib/detachedSpawn.js';
+import { sleep } from '../lib/fileUtils.js';
+import { stopOwnedDatabaseProducers } from './databaseMaintenanceProducers.js';
+
+const TERMINATE_GRACE_MS = 12000;
+const POLL_MS = 100;
+const refused = (reason) => Object.assign(
+ new Error(`Database writer quiescence refused: ${reason}. Maintenance remains fenced.`),
+ { code: 'DATABASE_WRITER_QUIESCENCE' },
+);
+
+// Every live detached supervisor of THIS install (its control directory is
+// under the data root, and its argv carries that path) must belong to a record
+// we can account for. This catches launches with no reservation: legacy code
+// or lost state. The coordinator worker's own supervisor shares our group.
+function assertNoUnknownSupervisors(processes, knownGroups) {
+ const own = processes.find(proc => proc.pid === process.pid)?.pgid;
+ const dataRoot = PATHS.data + sep;
+ if (processes.some(proc => isDetachedSupervisorCommand(proc.command) && proc.command.includes(dataRoot)
+ && proc.pgid !== own && !knownGroups.has(proc.pgid))) {
+ throw refused('an unregistered detached supervisor is running');
+ }
+}
+
+function classifyAll(rows, processes) {
+ const results = rows.map(row => ({ row, ...classifyWriterQuiescence(row, processes) }));
+ const counts = {};
+ for (const { verdict } of results) counts[verdict] = (counts[verdict] ?? 0) + 1;
+ // Bounded diagnostics only: counts, never PIDs, paths or commands.
+ if (counts.pending) throw refused(`${counts.pending} admitted launch(es) have not recorded a process identity`);
+ if (counts.ambiguous) throw refused(`${counts.ambiguous} writer record(s) are legacy, compacted, or have an unverifiable identity`);
+ if (counts.orphaned) throw refused(`${counts.orphaned} exited writer(s) still have surviving descendants`);
+ return results;
+}
+
+/**
+ * Internal coordinator-worker stage, run AFTER producer shutdown. Terminates
+ * the process groups of verified still-running detached writers, then proves
+ * every registry record quiescent and archives it with the operation. There is
+ * no force/skip option: any unprovable state refuses and leaves the fence.
+ * `graceMs`/`pollMs` exist only so subprocess tests avoid production sleeps.
+ */
+export async function reconcileDetachedWriters(id, token, { graceMs = TERMINATE_GRACE_MS, pollMs = POLL_MS } = {}) {
+ const journal = createDatabaseMaintenanceJournal();
+ const registry = createDatabaseWriterRegistry();
+ const operation = journal.assertCoordinatorWorker(id, token);
+ if (operation.stage !== 'quiescing' || !journal.readProducerSnapshot(id, token)) {
+ throw refused('producer shutdown has not been recorded for this operation');
+ }
+ // Windows has no process-group proof and its completions are compacted into
+ // identity-free history, so only never-launched records are provable there.
+ const windows = process.platform === 'win32';
+ const rows = registry.read();
+ if (windows && rows.some(row => row.state !== 'abandoned')) {
+ throw refused('descendant termination cannot be proven on Windows');
+ }
+ let processes = windows ? [] : await snapshotProcesses();
+ let results = classifyAll(rows, processes);
+ assertNoUnknownSupervisors(processes, new Set(results.flatMap(result => result.groups)));
+
+ // Only groups of a verified live job are signalled: while a group has members
+ // its ID cannot be reused, so a group seen non-empty since verification is
+ // still this launch's tree. A group once seen empty is never signalled again.
+ let live = new Set(results.filter(result => result.verdict === 'running').flatMap(result => result.groups));
+ const terminated = results.filter(result => result.verdict === 'running').length;
+ const deadline = Date.now() + graceMs;
+ let signal = 'SIGTERM';
+ while (live.size > 0) {
+ journal.assertCoordinatorWorker(id, token);
+ for (const group of live) signalProcessGroup(group, signal);
+ await sleep(pollMs);
+ processes = await snapshotProcesses();
+ live = new Set([...live].filter(group => processes.some(proc => proc.pgid === group)));
+ if (signal === 'SIGTERM' && Date.now() >= deadline) signal = 'SIGKILL';
+ else if (signal === 'SIGKILL' && Date.now() >= deadline + graceMs) throw refused('writer process groups did not terminate');
+ }
+
+ // Two consecutive fresh snapshots must agree that everything is quiescent.
+ for (let pass = 0; pass < 2; pass += 1) {
+ journal.assertCoordinatorWorker(id, token);
+ const current = registry.read();
+ if (current.length !== rows.length || current.some((row, index) => row.id !== rows[index].id)) {
+ throw refused('the writer inventory changed during reconciliation');
+ }
+ processes = windows ? [] : await snapshotProcesses();
+ results = classifyAll(current, processes);
+ if (results.some(result => result.verdict !== 'quiescent')) throw refused('a writer is still running');
+ assertNoUnknownSupervisors(processes, new Set());
+ }
+ journal.assertCoordinatorWorker(id, token);
+ const archive = join(PATHS.data, 'database-maintenance', 'reconciled-writers');
+ for (const { row } of results) registry.retire(row.id, archive);
+ if (registry.read().length !== 0) throw refused('the writer inventory is not empty after retirement');
+ return { id, stage: 'quiescing', writersReconciled: rows.length, writersTerminated: terminated,
+ quiescenceVerified: true, transferReady: false };
+}
+
+/**
+ * The full internal quiescence stage: stop owned PM2 producers, then reconcile
+ * detached writers. Not wired to any public entrypoint; export/import (#8871)
+ * and verified restart (#8851) must re-run it before relying on its result.
+ */
+export async function quiesceDatabaseWriters(id, token, options) {
+ await stopOwnedDatabaseProducers(id, token);
+ return reconcileDetachedWriters(id, token, options);
+}
diff --git a/server/services/databaseMaintenanceQuiescence.test.js b/server/services/databaseMaintenanceQuiescence.test.js
new file mode 100644
index 0000000000..aa29b1fdc9
--- /dev/null
+++ b/server/services/databaseMaintenanceQuiescence.test.js
@@ -0,0 +1,163 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { spawn } from 'node:child_process';
+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';
+import { createDatabaseWriterRegistry } from '../lib/databaseWriterRegistry.js';
+import { spawnDetached } from '../lib/detachedSpawn.js';
+import { reconcileDetachedWriters } from './databaseMaintenanceQuiescence.js';
+
+const context = vi.hoisted(() => ({ data: undefined, setupBarrier: null }));
+vi.mock('../lib/paths.js', async original => {
+ const actual = await original();
+ return { ...actual, PATHS: new Proxy(actual.PATHS, {
+ get: (target, key) => key === 'data' ? (context.data ?? target[key]) : target[key],
+ }) };
+});
+vi.mock('../lib/fileUtils.js', async original => {
+ const actual = await original();
+ return { ...actual, ensureDir: async (...args) => {
+ if (context.setupBarrier) await context.setupBarrier;
+ return actual.ensureDir(...args);
+ } };
+});
+
+const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };
+const target = { ...source, mode: 'docker', port: 5561 };
+const producers = ['portos-cos', 'portos-server'].map((name, pmId) => ({
+ name, pmId, pid: 100 + pmId, cwd: '/example/portos', script: `${name}.js`, status: 'online',
+}));
+const fast = { graceMs: 1500, pollMs: 20 };
+const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
+let root;
+let journal;
+let registry;
+let strays;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'writer-quiescence-'));
+ writeFileSync(join(root, '.portos-disposable-root'), '');
+ context.data = join(root, 'data');
+ context.setupBarrier = null;
+ journal = createDatabaseMaintenanceJournal(context.data);
+ registry = createDatabaseWriterRegistry(context.data);
+ strays = [];
+});
+afterEach(() => {
+ context.setupBarrier = null;
+ for (const group of strays) { try { process.kill(-group, 'SIGKILL'); } catch { /* already gone */ } }
+ rmSync(root, { recursive: true, force: true });
+});
+
+// A coordinator worker that has recorded producer shutdown for this operation.
+function quiescingOperation(from = source, to = target) {
+ const operation = journal.begin({ source: from, target: to });
+ const token = journal.acquireCoordinator(operation.id);
+ journal.reserveCoordinatorWorker(operation.id, token);
+ journal.recordProducerSnapshot(operation.id, token, producers);
+ journal.transition(operation.id, token, 'accepted', 'quiescing');
+ return { id: operation.id, token };
+}
+
+const closed = handle => new Promise(resolve => {
+ handle.once('close', (code, signal) => resolve({ code, signal }));
+ handle.once('error', error => resolve({ error }));
+});
+const firstLine = handle => new Promise(resolve => {
+ let text = '';
+ handle.stdout.on('data', chunk => {
+ text += chunk;
+ if (text.includes('\n')) resolve(Number(text.split('\n')[0]));
+ });
+});
+
+// The job starts a grandchild in its own (inherited) process group and prints
+// its PID. With `exit`, the job then exits and leaves that descendant behind.
+const jobWithDescendant = exit => ['-e', `const c=require('child_process').spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});
+c.unref();console.log(c.pid);${exit ? 'setTimeout(()=>process.exit(0),50);' : 'setInterval(()=>{},1000);'}`];
+
+describe.skipIf(process.platform === 'win32')('detached writer quiescence reconciliation', () => {
+ it.each([[source, target], [target, source]])('terminates a verified running writer tree, then archives its evidence', async (from, to) => {
+ const handle = await spawnDetached(process.execPath, jobWithDescendant(false), { controlDir: join(root, 'control'), pollMs: 10 });
+ const grandchild = await firstLine(handle);
+ const [record] = registry.read();
+ strays.push(record.launcherPid);
+ const { id, token } = quiescingOperation(from, to);
+
+ const result = await reconcileDetachedWriters(id, token, fast);
+ expect(result).toEqual({ id, stage: 'quiescing', writersReconciled: 1, writersTerminated: 1,
+ quiescenceVerified: true, transferReady: false });
+ expect(alive(handle.pid)).toBe(false);
+ expect(alive(grandchild)).toBe(false);
+ expect(registry.read()).toEqual([]);
+ const archive = join(context.data, 'database-maintenance', 'reconciled-writers');
+ expect(readdirSync(archive)).toEqual([record.id]);
+ expect(JSON.parse(readFileSync(join(archive, record.id, 'launch.json'), 'utf8')).pid).toBe(handle.pid);
+ expect(() => journal.assertAdmission()).toThrow();
+ // Re-establishing quiescence after coordinator recovery is repeatable.
+ expect((await reconcileDetachedWriters(id, token, fast)).writersReconciled).toBe(0);
+ });
+
+ it('refuses an exited writer whose descendant survives, without signalling it', async () => {
+ const handle = await spawnDetached(process.execPath, jobWithDescendant(true), { controlDir: join(root, 'control'), pollMs: 10 });
+ const grandchild = await firstLine(handle);
+ expect(await closed(handle)).toEqual({ code: 0, signal: null });
+ const [record] = registry.read();
+ strays.push(record.launcherPid);
+ expect(record.state).toBe('exited');
+ const { id, token } = quiescingOperation();
+
+ await expect(reconcileDetachedWriters(id, token, fast)).rejects.toThrow(/surviving descendants/);
+ expect(alive(grandchild)).toBe(true);
+ expect(registry.read()).toEqual([record]);
+ });
+
+ it('refuses an admitted pre-fence launch until the fence refuses it durably', async () => {
+ let release;
+ context.setupBarrier = new Promise(resolve => { release = resolve; });
+ const ran = join(root, 'ran');
+ const pending = spawnDetached(process.execPath, ['-e', `require('fs').writeFileSync(${JSON.stringify(ran)},'bad')`], {
+ controlDir: join(root, 'control'), pollMs: 10,
+ });
+ const { id, token } = quiescingOperation();
+ await expect(reconcileDetachedWriters(id, token, fast)).rejects.toThrow(/admitted launch/);
+
+ release();
+ expect((await closed(await pending)).error?.code).toBe('DATABASE_MAINTENANCE');
+ const result = await reconcileDetachedWriters(id, token, fast);
+ expect(result).toMatchObject({ writersReconciled: 1, writersTerminated: 0, quiescenceVerified: true });
+ expect(() => readFileSync(ran)).toThrow();
+ });
+
+ it('refuses legacy compacted history, identity-free launches and unregistered supervisors', async () => {
+ // A launch recorded before launcher groups existed carries only a PID.
+ const legacyLaunch = registry.reserve(join(root, 'old-control'));
+ const writers = join(context.data, 'database-writers');
+ writeFileSync(join(writers, legacyLaunch.id, 'launch.json'), JSON.stringify({ pid: 999999 }) + '\n');
+ const { id, token } = quiescingOperation();
+ await expect(reconcileDetachedWriters(id, token, fast)).rejects.toThrow(/legacy, compacted/);
+ rmSync(join(writers, legacyLaunch.id), { recursive: true });
+
+ writeFileSync(join(writers, 'unreconciled-exits.json'), JSON.stringify({ version: 1 }) + '\n');
+ await expect(reconcileDetachedWriters(id, token, fast)).rejects.toThrow(/legacy, compacted/);
+ rmSync(writers, { recursive: true });
+
+ // A supervisor started by code that predates the registry has no record.
+ const controlDir = join(context.data, 'legacy-control');
+ mkdirSync(controlDir, { recursive: true });
+ const legacy = spawn('sh', ['-c', 'd="$1"; shift\n{\n "$@" > /dev/null 2>&1 &\n child=$!\n printf \'%s\' "$child" > "$d/pid"\n wait "$child"\n} &\n',
+ 'sh', controlDir, process.execPath, '-e', 'setInterval(()=>{},1000)'], { detached: true, stdio: 'ignore' });
+ strays.push(legacy.pid);
+ await vi.waitFor(() => readFileSync(join(controlDir, 'pid'), 'utf8'), { timeout: 5000, interval: 20 });
+ await expect(reconcileDetachedWriters(id, token, fast)).rejects.toThrow(/unregistered detached supervisor/);
+ });
+
+ it('requires recorded producer shutdown and live coordinator ownership', async () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ journal.reserveCoordinatorWorker(operation.id, token);
+ await expect(reconcileDetachedWriters(operation.id, token, fast)).rejects.toThrow(/producer shutdown/);
+ await expect(reconcileDetachedWriters(operation.id, '00000000-0000-4000-8000-000000000000', fast)).rejects.toThrow();
+ });
+});