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: transfer the recorded offline database operation with durable dump recovery (#8871)

[._.]/ Adam Eivy99e4aada6d6c
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 1de159656e..9a259b4273 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -260,7 +260,7 @@ node scripts/database-maintenance.mjs cancel <operation-id>
Cancellation supports only the initial accepted stage, preserves the journal in the machine-local cancelled archive, and never switches mode or reverses direction. Restart managed processes through the existing PM2 ecosystem workflow after cancellation if their normal boot was refused. CLI configuration follows the ecosystem's environment precedence; run from the same configured operator environment. Changed source configuration, a different operation ID, an unknown stage/version, and a competing operation are refused.
-An incomplete publication or interrupted cancellation remains fenced. Do not remove the active directory, steal its cancellation claim, or guess a backend from `.env`: retain the journal for recovery. This first boundary deliberately supplies no transfer-stage resume/rollback command; the detached coordinator and verified restart protocol are tracked in #8810, and Settings recovery feedback in #8811. Normal startup and migration must not be re-enabled by treating this preparatory operation as a completed cutover.
+An incomplete publication or interrupted cancellation remains fenced. Do not remove the active directory, steal its cancellation claim, or guess a backend from `.env`: retain the journal for recovery. There is still no operator transfer-stage launch, resume or rollback command. The internal offline transfer, its retained `data/db-dumps/portos-maintenance-<operation-id>.sql` recovery dump, and the stage-specific `status` fields are described in [offline transfer](STORAGE.md#offline-transfer); verified restart is tracked in #8851, and Settings recovery feedback in #8811. Normal startup and migration must not be re-enabled by treating this preparatory operation as a completed cutover.
Coordinator stage publication uses immutable, atomically linked records. A same-operation retry with the existing owner token can confirm its last transition after a lost response; abandoned temporary files do not advance the stage, and a delayed retry cannot overwrite later progress. Interrupted claims from the older publication protocol still fail closed. This does not permit replacing a coordinator, reopening admission, or retrying SQL import: those require the offline recovery protocol.
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 2acdde9e4b..fa90898a7f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -118,18 +118,29 @@ recorded endpoints, and the running pool before cutover.
Coordinator ownership and cancellation share one exclusive durable initial claim. Once owned, an operation advances only through `accepted → quiescing → exporting → importing → committing → verifying → verified`; each transition requires the same operation, current ownership token, and expected previous stage. Immutable stage publications tolerate a retry of the same transition. Every stage (including `verified`) retains the admission fence. Stage names record coordinator progress; they do not independently prove quiescence, transfer, or healthy target startup. Verification-only server startup can read the recorded target through its actual pool at the `verifying` or `verified` stage; its bounded result is transient, creates no new store, and never advances the journal or reopens admission.
-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.
+The journal also supplies **internal ownership recovery** for the transfer worker; neither is an operator command. `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 doing anything else; copied arguments cannot enter it twice. On POSIX it then records its process group in `group.json` before starting any database child. 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 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.
+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, so every transfer attempt — including each recovered successor — repeats quiescence before any export or import (see [offline transfer](#offline-transfer) below). 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.
+For local diagnostics at any stage, run `node scripts/database-maintenance.mjs status`. From `exporting` onward it adds `transfer: { dump: "absent" | "recorded", import: "pending" | "committed" }`; malformed transfer records fail closed. 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 launch, resume, force or skip command for an owned operation; the worker and its recovery are internal until verified restart (#8851) wires them. Preserve the journal, worker records, `transfer-*.json`, the source database and the `portos-maintenance-<operation-id>.sql` dump; do not delete markers, edit or replace the dump, or call `scripts/db.sh migrate` (still refused). Stage-specific meaning: `accepted` — nothing stopped; `quiescing` — producers may be stopped, no dump yet; `exporting` + `dump: absent` — the next attempt re-exports from the quiesced source; `exporting`/`importing` + `dump: recorded` — the source copy is fixed and only it may be imported; `importing` + `import: pending` — the target transaction did not commit, retry imports the same dump; `import: committed` — only restart verification remains. If a successor refuses because an earlier coordinator's process is still running, inspect this install's process table (`ps -A -o pid,pgid,command`) and stop that leftover dump/import yourself before the next recovery.
`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 (`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, lacks a launcher group, or is a process-group job whose own PID was never recorded, 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.
+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, lacks a launcher group, or is a process-group job whose own PID was never recorded, 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, the predecessor-coordinator proof, then reconciliation inside the entered transfer worker, which repeats it on every attempt. 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. Damaged ownership or inventory makes the transfer worker exit with code 1 and a redacted refusal. Its stdout/stderr, owner binding, one-use entry marker, group record and supervisor receipt remain in the reserved directory.
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.
+#### Offline transfer
+
+The fixed worker (`scripts/database-maintenance-worker.mjs` → `runDatabaseTransfer(id, token)` in `server/services/databaseMaintenanceTransfer.js`) is the only code that transfers data. In order it: claims its one-use entry and records its process group; stops PM2 CoS then server (`stopOwnedDatabaseProducers`, which moves `accepted` → `quiescing` and, on recovery, re-reads the ORIGINAL identities); proves no earlier coordinator of this operation still has a live process group (`assertPredecessorCoordinatorsStopped`); reconciles admitted spawns and detached writers (`reconcileDetachedWriters`); and only then transfers:
+
+- **`quiescing` → `exporting`**: `scripts/db.sh export --endpoint` with the journal's recorded source host, port, user and database. The worker builds the child environment from an allowlist (the password is the only libpq variable passed), and `db.sh` strips every other inherited `PG*` variable again, so `PGHOST`, `PGHOSTADDR`, `PGSERVICE`, `PGOPTIONS` and the like cannot redirect it. The dump is `data/db-dumps/portos-maintenance-<operation-id>.sql`. A failed `pg_dump`, missing completion trailer, or unexpected output path is never recorded. A complete dump and its directory are fsynced, then `transfer-dump.json` publishes its operation, source identity, size and SHA-256, immutably, before `exporting` → `importing`.
+- **`importing`**: the recorded dump must still match its size and digest (a changed or missing dump refuses). `db.sh import --endpoint` loads it into the recorded target in one `psql --single-transaction` with `ON_ERROR_STOP`; a failed import commits nothing. Success publishes `transfer-import.json`, binding that digest to the target.
+
+The worker then exits `78` with `{ stage: "importing", importCommitted: true, sourceRetained: true, restartVerified: false }`: saved mode is unchanged, producers stay stopped, the source database and dump are retained, and admission stays fenced until verified target restart (#8851) exists. Ordinary pooled writes and detached spawns refuse throughout. A refusal exits `1` with a bounded reason (counts and stage only; no hosts, paths, tokens or PIDs); `db.sh` output stays internal.
+
+Recovery is same-operation only and never reverses direction. A successor (`recoverCoordinator` after the predecessor's supervisor exit receipt, then a new `spawnDatabaseMaintenanceWorker`) repeats the whole quiescence sequence, then: at `exporting` with no recorded dump it exports again (an interrupted or failed export is never reused); at `exporting` with a recorded dump it verifies the bytes and advances; at `importing` it retries the same recorded dump into the same recorded target; with an import receipt it reports the committed import without importing again. A killed worker can leave its `pg_dump`/`psql` running after its supervisor records an exit: while any recorded predecessor group still has members, the successor refuses (`a previous coordinator's dump or import process is still running`) and signals nothing, because a group ID seen empty could have been reused. A predecessor with no group record never started a database child. Windows has no group proof, so a successor there refuses once any predecessor had entered. Descendants that leave their process group (`setsid`) are not observable.
+
### Calendar daily-review recovery
Daily reviews remain in the existing `data/calendar/daily-reviews/<date>.json`
@@ -290,19 +301,19 @@ 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. 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.
+or authorize a dump. The internal transfer worker follows it with predecessor
+and descendant reconciliation, then exports the recorded source and imports the
+recorded dump into the recorded target (see [offline transfer](#offline-transfer)).
+Public migration stays disabled until verified restart (#8851) is integrated.
For stage diagnostics, run `node scripts/database-maintenance.mjs status` and
`node scripts/database-maintenance.mjs writers`. `accepted` means no transfer
has begun; `quiescing` requires retained producer and child reconciliation
-evidence. Do not remove the fence, erase `producers.json`, probe a PID to infer
+evidence; `exporting`/`importing` report `transfer` dump/import state. Do not remove the fence, erase `producers.json`, probe a PID to infer
ownership, or reverse source/target. There is no user-callable resume or bypass
-for the unfinished transfer stages. A same-operation internal successor requires
-the prior detached supervisor's durable exit receipt and must repeat shutdown
-readback before any subsequent transfer stage.
+for the transfer stages. A same-operation internal successor requires
+the prior detached supervisor's durable exit receipt and repeats shutdown
+readback, predecessor and writer reconciliation before any export or import.
Keep the existing backend selected and use backups until the coordinated
offline cutover is available (tracked in #8797 / #8805). A safe cutover requires
diff --git a/scripts/database-maintenance-worker.mjs b/scripts/database-maintenance-worker.mjs
index 1a57e92f24..c62c8bdb6d 100644
--- a/scripts/database-maintenance-worker.mjs
+++ b/scripts/database-maintenance-worker.mjs
@@ -1,28 +1,26 @@
#!/usr/bin/env node
// Fixed internal worker entrypoint. No command, endpoint, environment, or
-// control-directory arguments are accepted. This slice inspects prerequisites;
-// it never stops writers, exports/imports data, commits mode, or opens admission.
-import { createDatabaseMaintenanceJournal } from '../server/lib/databaseMaintenanceJournal.js';
-import { createDatabaseWriterRegistry } from '../server/lib/databaseWriterRegistry.js';
+// control-directory arguments are accepted. It quiesces every owned writer and
+// transfers the RECORDED operation (source dump → one target transaction). It
+// never changes saved mode, restarts producers, or reopens admission: a
+// committed import still awaits verified target restart (#8851).
+import { runDatabaseTransfer } from '../server/services/databaseMaintenanceTransfer.js';
try {
const args = process.argv.slice(2);
if (args.length !== 2) throw new Error('Invalid worker identity');
const [id, token] = args;
- const journal = createDatabaseMaintenanceJournal();
- const operation = journal.enterCoordinatorWorker(id, token);
- 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,
- source: operation.source.mode, target: operation.target.mode, writers,
- quiescenceVerified: false, transferReady: false }));
- // Successful inspection is NOT a successful cutover. Even an empty registry
- // cannot exclude legacy children or an admitted producer still starting one.
- console.error('⛔ Database transfer refused: writer shutdown and descendant reconciliation are not yet integrated.');
+ const result = await runDatabaseTransfer(id, token);
+ console.log(JSON.stringify(result));
+ // A committed import is NOT a successful cutover: saved mode, restart and
+ // admission release belong to the verified-restart stage.
+ console.error('⚠️ Database transfer imported; target restart verification is not yet integrated. Maintenance remains fenced.');
process.exitCode = 78;
-} catch {
+} catch (err) {
// Never print tokens, paths, endpoints, or raw parser/OS exception messages.
- console.error('⛔ Database maintenance worker refused: ownership or inventory evidence is incomplete.');
+ // Transfer and quiescence refusals carry only bounded, redacted reasons.
+ console.error(['DATABASE_TRANSFER', 'DATABASE_WRITER_QUIESCENCE'].includes(err?.code)
+ ? `⛔ ${err.message}`
+ : '⛔ Database maintenance worker refused: ownership, writer, or transfer evidence is incomplete.');
process.exitCode = 1;
}
diff --git a/scripts/database-maintenance.mjs b/scripts/database-maintenance.mjs
index 754cabbc93..3b0587b738 100644
--- a/scripts/database-maintenance.mjs
+++ b/scripts/database-maintenance.mjs
@@ -1,6 +1,8 @@
#!/usr/bin/env node
// Operator interface for the admission boundary. This does NOT transfer data,
// stop existing writers, change mode, or authorize invoking db.sh migrate.
+// Transfer runs only inside the owned internal worker; there is no command
+// here that starts, resumes, forces, or skips it.
import { createRequire } from 'node:module';
import { join } from 'node:path';
import { PATHS } from '../server/lib/paths.js';
@@ -31,7 +33,8 @@ function main() {
if (!record) return { stage: 'idle' };
const coordinator = journal.coordinatorStatus(record.id);
return { id: record.id, stage: record.stage, source: record.source.mode, target: record.target.mode,
- ...(coordinator.state === 'unclaimed' ? {} : { coordinator }) };
+ ...(coordinator.state === 'unclaimed' ? {} : { coordinator }),
+ ...(['accepted', 'quiescing'].includes(record.stage) ? {} : { transfer: journal.transferStatus(record.id) }) };
}
if (command === 'begin' && args.length === 2) {
const [sourceMode, targetMode] = args;
diff --git a/scripts/db-migrate.test.js b/scripts/db-migrate.test.js
index 5f4a1de7ec..3d2045a67b 100644
--- a/scripts/db-migrate.test.js
+++ b/scripts/db-migrate.test.js
@@ -40,7 +40,7 @@ exit 0
const PSQL_STUB = `#!/bin/sh
echo "psql $*" >> "$STUB_LOG"
-echo "endpoint-env \${PGHOSTADDR-unset}|\${PGSERVICE-unset}|\${PGSERVICEFILE-unset}" >> "$STUB_LOG"
+echo "endpoint-env \${PGHOSTADDR-unset}|\${PGSERVICE-unset}|\${PGSERVICEFILE-unset}|\${PGOPTIONS-unset}" >> "$STUB_LOG"
case "$*" in *--single-transaction*) cat >> "$IMPORT_LOG"; exit "\${IMPORT_EXIT:-0}" ;; esac
case "$*" in *count*) echo 3 ;; esac
exit 0
@@ -48,7 +48,7 @@ exit 0
const PG_DUMP_STUB = `#!/bin/sh
echo "pg_dump $*" >> "$STUB_LOG"
-echo "endpoint-env \${PGHOSTADDR-unset}|\${PGSERVICE-unset}|\${PGSERVICEFILE-unset}" >> "$STUB_LOG"
+echo "endpoint-env \${PGHOSTADDR-unset}|\${PGSERVICE-unset}|\${PGSERVICEFILE-unset}|\${PGOPTIONS-unset}" >> "$STUB_LOG"
case "$DUMP_MODE" in
partial) printf 'DROP TABLE example_record;\\n'; exit 1 ;;
empty) exit 1 ;;
@@ -154,7 +154,7 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
writeFileSync(envFile, `PGMODE=${mode}\n`);
const source = ['--endpoint', 'source.example.invalid', '6543', 'example_user', 'example source'];
const target = ['--endpoint', 'target.example.invalid', '6544', 'example_user', 'example target'];
- const inherited = { PGPORT: '9999', PGHOSTADDR: '192.0.2.10', PGSERVICE: 'other', PGSERVICEFILE: '/example/service.conf' };
+ const inherited = { PGPORT: '9999', PGHOSTADDR: '192.0.2.10', PGSERVICE: 'other', PGSERVICEFILE: '/example/service.conf', PGOPTIONS: '-c search_path=other' };
const exported = run(['export', ...source, 'explicit'], 'ok', inherited);
expect(exported.status, exported.stderr).toBe(0);
const dump = join(dumpDir, 'portos-explicit.sql');
@@ -168,7 +168,7 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',
expect(log).toContain('pg_dump -h source.example.invalid -p 6543 -U example_user -d example source');
expect(log).toContain('psql -h target.example.invalid -p 6544 -U example_user -d example target -v ON_ERROR_STOP=1 --single-transaction');
expect(log).not.toMatch(/docker|SOURCE_STOP|test-only/);
- expect(log.match(/endpoint-env unset\|unset\|unset/g)).toHaveLength(2);
+ expect(log.match(/endpoint-env unset\|unset\|unset\|unset/g)).toHaveLength(2);
expect(log).not.toContain('192.0.2.10');
expect(readFileSync(envFile, 'utf8')).toBe(`PGMODE=${mode}\n`);
});
diff --git a/scripts/db.sh b/scripts/db.sh
index 0327ddd18a..087cc6567f 100755
--- a/scripts/db.sh
+++ b/scripts/db.sh
@@ -30,7 +30,9 @@ PGUSER="${PGUSER:-portos}"
PGDATABASE="${PGDATABASE:-portos}"
PGPASSWORD="${PGPASSWORD:-portos}"
PGHOST="${PGHOST:-localhost}"
-DUMP_DIR="$ROOT_DIR/data/db-dumps"
+# The maintenance coordinator names its install's dump directory explicitly
+# (its data root can differ from this checkout); otherwise use this checkout.
+DUMP_DIR="${PORTOS_DUMP_DIR:-$ROOT_DIR/data/db-dumps}"
ENV_FILE="$ROOT_DIR/.env"
# Colors
@@ -524,13 +526,18 @@ cmd_setup_native() {
info "Coordinated backend migration is not yet available. Keep using the current backend."
}
-# Scope inherited libpq endpoint overrides out of explicit transfers. In
-# particular PGHOSTADDR takes precedence over -h's network destination.
+# Scope inherited libpq settings out of explicit transfers. PGHOSTADDR takes
+# precedence over -h's network destination, PGSERVICE can supply another
+# endpoint, and PGOPTIONS can redirect statements (search_path). Only the
+# password crosses; every connection parameter is an explicit argument.
run_explicit_pg() (
- unset PGHOSTADDR PGSERVICE PGSERVICEFILE
- local binary="$1"
+ local binary="$1" host="$PGHOST" port="$PGPORT" user="$PGUSER" database="$PGDATABASE" password="$PGPASSWORD"
shift
- PGPASSWORD="$PGPASSWORD" "$binary" -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"
+ local name
+ for name in $(compgen -e); do
+ case "$name" in PG*) unset "$name" ;; esac
+ done
+ PGPASSWORD="$password" "$binary" -h "$host" -p "$port" -U "$user" -d "$database" "$@"
)
# Run psql command, using Docker exec in Docker mode if host psql is unavailable
diff --git a/server/lib/README.md b/server/lib/README.md
index 8342b7d28f..408282c24c 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. `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. |
+| `detachedSpawn.js` | `spawnDatabaseMaintenanceWorker(id, token)` launches only the fixed, one-use fenced offline-transfer worker and retains its supervisor evidence; it grants no ordinary launch bypass. `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`. |
@@ -766,6 +766,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `messageBrowserIdentity.js` | Shared Outlook row extraction and identity-safe browser action scripts; exact unique targets and confirmed row removal. |
-| `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. |
+| `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, worker process-group records, immutable recovery-dump and import receipts, 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 (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/databaseMaintenanceJournal.js b/server/lib/databaseMaintenanceJournal.js
index c7f1bc5a58..519ccac266 100644
--- a/server/lib/databaseMaintenanceJournal.js
+++ b/server/lib/databaseMaintenanceJournal.js
@@ -38,6 +38,22 @@ const producerSnapshotSchema = z.object({
status: z.enum(['online', 'stopped']),
}).strict()).length(2),
}).strict();
+const sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
+// Transfer evidence. The dump name is derived from the operation, never a path
+// chosen by a caller, so a manifest cannot point the import anywhere else.
+const transferDumpSchema = z.object({
+ id: z.string().uuid(),
+ source: databaseMaintenanceEndpointSchema,
+ file: z.string().regex(/^portos-maintenance-[0-9a-f-]{36}\.sql$/),
+ bytes: z.number().int().positive(),
+ sha256: sha256Schema,
+}).strict();
+const transferImportSchema = z.object({
+ id: z.string().uuid(),
+ target: databaseMaintenanceEndpointSchema,
+ sha256: sha256Schema,
+}).strict();
+const workerGroupSchema = coordinatorSchema.extend({ pgid: z.number().int().positive() }).strict();
const decisionSchema = coordinatorSchema.extend({
stage: z.enum(stages),
action: z.discriminatedUnion('kind', [
@@ -164,24 +180,25 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
// Recovery appends an immutable successor instead of overwriting ownership.
// Each predecessor admits exactly one successor, even across processes. A
// missing/partial worker receipt never authorizes reclaiming an owner.
- const readCoordinator = (id, rejectedPredecessor = null) => {
+ // The ordered ownership chain, oldest first; empty when never claimed.
+ const readCoordinatorChain = (id, rejectedPredecessor = null) => {
const current = read();
if (!current || current.id !== id) throw databaseMaintenanceError();
const ownerPath = join(activeDir, 'cancel-' + id + '.claim');
try { lstatSync(ownerPath); } catch (err) {
- if (err.code === 'ENOENT') return null;
+ if (err.code === 'ENOENT') return [];
throw databaseMaintenanceError();
}
if (!lstatSync(ownerPath).isFile()) throw databaseMaintenanceError();
let owner = coordinatorSchema.parse(JSON.parse(readFileSync(ownerPath, 'utf8')));
if (owner.id !== id) throw databaseMaintenanceError();
- const visited = new Set();
+ const chain = [];
while (true) {
- if (visited.has(owner.token)) throw databaseMaintenanceError();
- visited.add(owner.token);
+ if (chain.some(value => value.token === owner.token)) throw databaseMaintenanceError();
+ chain.push(owner);
const nextPath = join(activeDir, 'coordinator-after-' + owner.token + '.json');
try { lstatSync(nextPath); } catch (err) {
- if (err.code === 'ENOENT') return owner;
+ if (err.code === 'ENOENT') return chain;
throw databaseMaintenanceError();
}
if (!lstatSync(nextPath).isFile()) throw databaseMaintenanceError();
@@ -190,6 +207,7 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
owner = { id, token: next.token };
}
};
+ const readCoordinator = (id, rejectedPredecessor = null) => readCoordinatorChain(id, rejectedPredecessor).at(-1) ?? null;
const assertCoordinator = (id, token) => {
const owner = readCoordinator(id);
@@ -268,6 +286,129 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
return current;
};
+ // Optional JSON record: null when absent, fenced when present but invalid.
+ const readRecord = (path, schema) => {
+ try { lstatSync(path); } catch (err) {
+ if (err.code === 'ENOENT') return null;
+ throw databaseMaintenanceError();
+ }
+ try {
+ if (!lstatSync(path).isFile()) throw databaseMaintenanceError();
+ return schema.parse(JSON.parse(readFileSync(path, 'utf8')));
+ } catch {
+ throw databaseMaintenanceError();
+ }
+ };
+
+ // For stages that run inside the one entered worker process. Entry itself
+ // stays one-use; this only proves the caller is that entered owner.
+ const assertEnteredCoordinatorWorker = (id, token) => {
+ const current = assertCoordinatorWorker(id, token);
+ const started = readRecord(join(workerDirectory(token), 'started.json'), coordinatorSchema);
+ if (!started || started.id !== id || started.token !== token) throw databaseMaintenanceError();
+ return current;
+ };
+
+ // The entered worker's POSIX process group. Every database child it starts
+ // (dump/import) inherits this group, so a successor can prove none survive.
+ const recordCoordinatorGroup = (id, token, pgid) => {
+ assertNotRealDataWrite(activeDir, 'database maintenance worker group');
+ assertEnteredCoordinatorWorker(id, token);
+ const value = workerGroupSchema.parse({ id, token, pgid });
+ writeDurableExclusive(join(workerDirectory(token), 'group.json'), value);
+ syncDirectory(workerDirectory(token));
+ assertEnteredCoordinatorWorker(id, token);
+ return value;
+ };
+
+ // Earlier owners of this operation. Recovery requires each one's supervisor
+ // exit receipt, but that says nothing about descendants it may have left.
+ // A worker records its group before starting any database child, so a
+ // predecessor without a group record (never entered, crashed before that
+ // point, or an inspection-only legacy worker) started no dump or import.
+ const readPredecessorWorkers = (id, token) => {
+ assertEnteredCoordinatorWorker(id, token);
+ const chain = readCoordinatorChain(id);
+ if (chain.at(-1)?.token !== token) throw databaseMaintenanceError();
+ return chain.slice(0, -1).map(({ token: previous }) => {
+ const directory = workerDirectory(previous);
+ const started = readRecord(join(directory, 'started.json'), coordinatorSchema);
+ const group = readRecord(join(directory, 'group.json'), workerGroupSchema);
+ if ((started && (started.id !== id || started.token !== previous))
+ || (group && (!started || group.id !== id || group.token !== previous))) throw databaseMaintenanceError();
+ return { started: Boolean(started), pgid: group?.pgid ?? null };
+ });
+ };
+
+ const transferDumpPath = id => join(dataDir, 'db-dumps', 'portos-maintenance-' + z.string().uuid().parse(id) + '.sql');
+ const transferDumpRecordPath = join(activeDir, 'transfer-dump.json');
+ const transferImportRecordPath = join(activeDir, 'transfer-import.json');
+
+ const readTransferDump = (id) => {
+ const current = read();
+ if (!current || current.id !== id) throw databaseMaintenanceError();
+ const dump = readRecord(transferDumpRecordPath, transferDumpSchema);
+ if (dump && (dump.id !== id || JSON.stringify(dump.source) !== JSON.stringify(current.source)
+ || dump.file !== 'portos-maintenance-' + id + '.sql')) throw databaseMaintenanceError();
+ return dump;
+ };
+
+ const readTransferImport = (id) => {
+ const current = read();
+ if (!current || current.id !== id) throw databaseMaintenanceError();
+ const receipt = readRecord(transferImportRecordPath, transferImportSchema);
+ if (!receipt) return null;
+ const dump = readTransferDump(id);
+ if (!dump || receipt.id !== id || receipt.sha256 !== dump.sha256
+ || JSON.stringify(receipt.target) !== JSON.stringify(current.target)) throw databaseMaintenanceError();
+ return receipt;
+ };
+
+ // Immutable no-replace publication of already-fsynced bytes. A retry of the
+ // identical record is accepted; a different record is never substituted.
+ const publishImmutable = (destination, value) => {
+ const pending = join(activeDir, 'record-' + randomUUID() + '.pending');
+ writeDurableExclusive(pending, value);
+ try {
+ linkSync(pending, destination);
+ } catch (err) {
+ if (err.code !== 'EEXIST') throw err;
+ } finally {
+ unlinkSync(pending);
+ }
+ syncDirectory(activeDir);
+ if (readFileSync(destination, 'utf8') !== JSON.stringify(value, null, 2) + '\n') throw databaseMaintenanceError();
+ };
+
+ // Publish the COMPLETE recovery dump's identity. The caller has already
+ // fsynced the dump and its directory; the import may use only these bytes.
+ const recordTransferDump = (id, token, dump) => {
+ assertNotRealDataWrite(activeDir, 'database maintenance dump publication');
+ const current = assertEnteredCoordinatorWorker(id, token);
+ const value = transferDumpSchema.parse(dump);
+ if (current.stage !== 'exporting' || value.id !== id) throw databaseMaintenanceError();
+ publishImmutable(transferDumpRecordPath, value);
+ assertEnteredCoordinatorWorker(id, token);
+ return readTransferDump(id);
+ };
+
+ // A committed single-transaction import into the recorded target.
+ const recordTransferImport = (id, token, receipt) => {
+ assertNotRealDataWrite(activeDir, 'database maintenance import receipt');
+ const current = assertEnteredCoordinatorWorker(id, token);
+ const value = transferImportSchema.parse(receipt);
+ if (current.stage !== 'importing' || value.id !== id) throw databaseMaintenanceError();
+ publishImmutable(transferImportRecordPath, value);
+ assertEnteredCoordinatorWorker(id, token);
+ return readTransferImport(id);
+ };
+
+ // Bounded operator status: never paths, digests, endpoints or tokens.
+ const transferStatus = (id) => ({
+ dump: readTransferDump(id) ? 'recorded' : 'absent',
+ import: readTransferImport(id) ? 'committed' : 'pending',
+ });
+
// Retain the pre-stop producer identities across same-operation recovery.
// Partial publication is never interpreted as an empty producer set.
const readProducerSnapshot = (id, token) => {
@@ -440,7 +581,9 @@ export function createDatabaseMaintenanceJournal(dataDir = PATHS.data) {
return { isFenced, assertAdmission, read, begin, cancel, acquireCoordinator, transition, reconciledWritersDirectory,
reserveCoordinatorWorker, coordinatorStatus, recoverCoordinator, assertCoordinatorWorker, enterCoordinatorWorker,
- readProducerSnapshot, recordProducerSnapshot };
+ readProducerSnapshot, recordProducerSnapshot, assertEnteredCoordinatorWorker, recordCoordinatorGroup,
+ readPredecessorWorkers, transferDumpPath, readTransferDump, readTransferImport, recordTransferDump,
+ recordTransferImport, transferStatus };
}
const journal = createDatabaseMaintenanceJournal();
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.js
index e9ab19d1c7..b1388aeb12 100644
--- a/server/lib/databaseMaintenanceWorker.test.js
+++ b/server/lib/databaseMaintenanceWorker.test.js
@@ -1,26 +1,75 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { spawn } from 'node:child_process';
+// The real detached worker, end to end: supervisor launch, producer stop,
+// writer reconciliation, db.sh dump/import. PM2 is replaced at its module
+// boundary by a loader hook in the worker process only, and pg_dump/psql are
+// disposable stubs; no live daemon, database or install data is touched.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { spawn, spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import { delimiter, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';
import { createDatabaseWriterRegistry } from './databaseWriterRegistry.js';
+import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';
const detachedUrl = new URL('./detachedSpawn.js', import.meta.url).href;
-const source = { mode: 'native', host: 'localhost', port: 5432, database: 'example_test', user: 'example' };
-const target = { ...source, mode: 'docker', port: 5561 };
+const source = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };
+const target = { ...source, mode: 'docker', host: 'docker.example.invalid', port: 5561 };
let root;
let journal;
let env;
+let stubs;
+let strays;
+
+// Writes a PM2 module stand-in with file-backed state and a loader hook that
+// substitutes it for server/services/pm2.js.
+function installPm2Stub() {
+ const state = join(stubs.dir, 'pm2.json');
+ writeFileSync(state, JSON.stringify([
+ { name: 'portos-cos', pmId: 12, pid: 1012, status: 'online', cwd: root, script: 'server/cos-runner/index.js' },
+ { name: 'portos-server', pmId: 13, pid: 1013, status: 'online', cwd: root, script: 'server/start.js' },
+ ]));
+ const stubModule = join(stubs.dir, 'pm2.mjs');
+ writeFileSync(stubModule, `import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
+const state = ${JSON.stringify(state)};
+export async function listMaintenanceProcesses() { return JSON.parse(readFileSync(state, 'utf8')); }
+export async function stopApp(id) {
+ const rows = JSON.parse(readFileSync(state, 'utf8'));
+ const row = rows.find(value => value.pmId === id);
+ row.status = 'stopped'; row.pid = 0;
+ writeFileSync(state, JSON.stringify(rows));
+ appendFileSync(${JSON.stringify(join(stubs.dir, 'events.log'))}, 'stop ' + row.name + '\\n');
+ return { success: true };
+}\n`);
+ const hooks = join(stubs.dir, 'hooks.mjs');
+ writeFileSync(hooks, `export async function resolve(specifier, context, next) {
+ const result = await next(specifier, context);
+ return result.url.endsWith('/server/services/pm2.js') ? { url: ${JSON.stringify(pathToFileURL(stubModule).href)}, format: 'module', shortCircuit: true } : result;
+}\n`);
+ const register = join(stubs.dir, 'register.mjs');
+ writeFileSync(register, `import { register } from 'node:module';\nregister(${JSON.stringify(pathToFileURL(hooks).href)});\n`);
+ return pathToFileURL(register).href;
+}
+
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'maintenance-worker-'));
writeFileSync(join(root, '.portos-disposable-root'), '');
+ mkdirSync(join(root, 'server', 'cos-runner'), { recursive: true });
+ writeFileSync(join(root, 'server', 'start.js'), '');
+ writeFileSync(join(root, 'server', 'cos-runner', 'index.js'), '');
journal = createDatabaseMaintenanceJournal(join(root, 'data'));
- env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root };
+ stubs = installDatabaseStubs(root);
+ strays = [];
+ env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root, PATH: `${stubs.bin}${delimiter}${process.env.PATH}`,
+ PGPASSWORD: 'example-password', PGHOST: 'inherited.example.invalid', PGHOSTADDR: '192.0.2.10',
+ NODE_OPTIONS: `--import=${installPm2Stub()}` };
delete env.VITEST;
});
-afterEach(() => rmSync(root, { recursive: true, force: true }));
+afterEach(() => {
+ for (const group of strays) { try { process.kill(-group, 'SIGKILL'); } catch { /* already gone */ } }
+ rmSync(root, { recursive: true, force: true });
+});
function run(code) {
return new Promise((resolve, reject) => {
@@ -46,22 +95,38 @@ function launch(id, token) {
} catch { process.exitCode=1; }`);
}
-describe('owned maintenance worker launch', () => {
- it.each([[source, target], [target, source]])('runs one fixed inspection while ordinary launches remain fenced', async (from, to) => {
+// Operator status: bounded stage evidence, never endpoints, paths or tokens.
+const status = () => {
+ const result = spawnSync(process.execPath, [fileURLToPath(new URL('../../scripts/database-maintenance.mjs', import.meta.url)), 'status'],
+ { env, encoding: 'utf8' });
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).not.toMatch(/example\.invalid|example-password|maintenance-worker-/);
+ return JSON.parse(result.stdout);
+};
+const controlDirFor = token => join(root, 'data', 'database-maintenance', 'worker-' + token);
+const importsStarted = () => stubs.events().filter(line => line === 'import-start').length;
+
+describe.skipIf(process.platform === 'win32')('owned maintenance worker', () => {
+ it.each([[source, target], [target, source]])('transfers the recorded operation once while ordinary launches remain fenced (%#)', async (from, to) => {
const operation = journal.begin({ source: from, target: to });
const token = journal.acquireCoordinator(operation.id);
const outcomes = await Promise.all([launch(operation.id, token), launch(operation.id, token)]);
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, launching: 0, launched: 0, exited: 0, abandoned: 0 }, quiescenceVerified: false, transferReady: false });
- expect(journal.read()).toEqual(operation);
+ const transferred = JSON.parse(outcomes.find(value => value.status === 78).stdout);
+ expect(transferred).toEqual({ id: operation.id, stage: 'importing', source: from.mode, target: to.mode,
+ imported: true, importCommitted: true, sourceRetained: true, restartVerified: false });
+ expect(stubs.events()).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=none', 'import-start', 'import-commit']);
+ expect(stubs.invocations('pg_dump')).toEqual([`pg_dump -h ${from.host} -p ${from.port} -U ${from.user} -d ${from.database} --no-owner --no-privileges --if-exists --clean`]);
+ expect(stubs.invocations('psql')).toEqual([`psql -h ${to.host} -p ${to.port} -U ${to.user} -d ${to.database} -v ON_ERROR_STOP=1 --single-transaction`]);
+ expect(stubs.receivedVariables()).toEqual(['PGPASSWORD']);
+ expect(stubs.imported()).toBe(STUB_DUMP_COMPLETE);
+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });
expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'exited', exitCode: 78 });
expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toEqual([]);
expect(() => journal.assertAdmission()).toThrow();
- const controlDir = join(root, 'data', 'database-maintenance', 'worker-' + token);
+ const controlDir = controlDirFor(token);
const before = readdirSync(controlDir).sort();
- expect(before).toEqual(expect.arrayContaining(['owner.json', 'started.json', 'stdout.log', 'stderr.log', 'pid', 'exit']));
+ expect(before).toEqual(expect.arrayContaining(['owner.json', 'started.json', 'group.json', 'stdout.log', 'stderr.log', 'pid', 'exit']));
expect((await launch(operation.id, token)).status).toBe(1);
expect(readdirSync(controlDir).sort()).toEqual(before);
expect(readFileSync(join(controlDir, 'exit'), 'utf8').trim()).toBe('78');
@@ -75,13 +140,69 @@ describe('owned maintenance worker launch', () => {
child.on('error',()=>{process.exitCode=1;}); child.on('close',()=>{process.exitCode=2;});`);
expect(ordinary.status).toBe(1);
expect(existsSync(ran)).toBe(false);
+ // A recovered owner re-proves quiescence but never re-imports a committed transfer.
const successor = journal.recoverCoordinator(operation.id, token, randomUUID());
expect((await launch(operation.id, token)).status).toBe(1);
- expect((await launch(operation.id, successor)).status).toBe(78);
+ const resumed = await launch(operation.id, successor);
+ expect(resumed.status).toBe(78);
+ expect(JSON.parse(resumed.stdout)).toMatchObject({ imported: false, importCommitted: true });
+ expect(stubs.invocations('pg_dump')).toHaveLength(1);
+ expect(importsStarted()).toBe(1);
expect(readFileSync(join(controlDir, 'exit'), 'utf8').trim()).toBe('78');
- expect(journal.read()).toEqual(operation);
- }, 60_000);
+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });
+ }, 90_000);
+
+ // Regression caught: a successor importing while an import started by a
+ // killed predecessor (whose supervisor already published an exit) still runs.
+ it('never lets a recovered coordinator import while a killed predecessor\'s import still runs', async () => {
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ stubs.setMode('import', 'pause');
+ const first = launch(operation.id, token);
+ await vi.waitFor(() => expect(stubs.started('import')).toBe(true), { timeout: 30_000, interval: 50 });
+ const { pgid } = JSON.parse(readFileSync(join(controlDirFor(token), 'group.json'), 'utf8'));
+ strays.push(pgid);
+ process.kill(Number(readFileSync(join(controlDirFor(token), 'pid'), 'utf8')), 'SIGKILL');
+ expect((await first).status).not.toBe(78);
+ await vi.waitFor(() => expect(journal.coordinatorStatus(operation.id).state).toBe('exited'), { timeout: 10_000, interval: 50 });
+
+ const second = journal.recoverCoordinator(operation.id, token, randomUUID());
+ const refused = await launch(operation.id, second);
+ expect(refused.status).toBe(1);
+ expect(refused.stderr).toMatch(/previous coordinator's dump or import process is still running/);
+ expect(importsStarted()).toBe(1);
+ expect(status()).toEqual({ id: operation.id, stage: 'importing', source: 'native', target: 'docker',
+ coordinator: { state: 'exited', exitCode: 1 }, transfer: { dump: 'recorded', import: 'pending' } });
+
+ process.kill(-pgid, 'SIGKILL');
+ stubs.setMode('import', 'ok');
+ const third = journal.recoverCoordinator(operation.id, second, randomUUID());
+ const done = await launch(operation.id, third);
+ expect(done.status).toBe(78);
+ expect(stubs.invocations('pg_dump')).toHaveLength(1);
+ expect(importsStarted()).toBe(2);
+ expect(status()).toMatchObject({ stage: 'importing', transfer: { dump: 'recorded', import: 'committed' } });
+ expect(stubs.imported()).toBe(STUB_DUMP_COMPLETE);
+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });
+ }, 90_000);
+
+ it('retains unresolved inventory and refuses to export', async () => {
+ createDatabaseWriterRegistry(join(root, 'data')).reserve(join(root, 'pending-writer'));
+ const operation = journal.begin({ source, target });
+ const token = journal.acquireCoordinator(operation.id);
+ const outcome = await launch(operation.id, token);
+ expect(outcome.status).toBe(1);
+ expect(outcome.stdout).toBe('');
+ expect(outcome.stderr).toMatch(/1 admitted launch\(es\) have not recorded a process identity/);
+ expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toHaveLength(1);
+ expect(journal.read()).toEqual({ ...operation, stage: 'quiescing' });
+ expect(stubs.invocations('pg_dump')).toEqual([]);
+ }, 40_000);
+
+});
+// Ownership and entry refusals happen before any platform-specific transfer step.
+describe('owned maintenance worker entry', () => {
it('rejects a foreign owner and cannot relaunch an interrupted reservation', async () => {
const operation = journal.begin({ source, target });
const token = journal.acquireCoordinator(operation.id);
@@ -93,17 +214,7 @@ describe('owned maintenance worker launch', () => {
expect(readFileSync(join(controlDir, 'stdout.log'), 'utf8')).toBe('retained evidence');
expect(journal.coordinatorStatus(operation.id)).toEqual({ state: 'awaiting-exit' });
expect(() => journal.recoverCoordinator(operation.id, token, randomUUID())).toThrow();
- }, 40_000);
-
- it('retains unresolved inventory and refuses transfer after inspecting it', async () => {
- createDatabaseWriterRegistry(join(root, 'data')).reserve(join(root, 'pending-writer'));
- const operation = journal.begin({ source, target });
- const token = journal.acquireCoordinator(operation.id);
- const outcome = await launch(operation.id, token);
- expect(outcome.status).toBe(78);
- expect(JSON.parse(outcome.stdout)).toMatchObject({ writers: { unresolved: 1 }, transferReady: false });
- expect(createDatabaseWriterRegistry(join(root, 'data')).read()).toHaveLength(1);
- expect(journal.read()).toEqual(operation);
+ expect(stubs.events()).toEqual([]);
}, 40_000);
it('refuses damaged inventory without printing local evidence', async () => {
@@ -116,11 +227,12 @@ describe('owned maintenance worker launch', () => {
const outcome = await launch(operation.id, token);
expect(outcome.status).toBe(1);
expect(outcome.stdout).toBe('');
- expect(outcome.stderr).toContain('ownership or inventory evidence is incomplete');
+ expect(outcome.stderr).toContain('ownership, writer, or transfer evidence is incomplete');
expect(outcome.stderr).not.toContain('private-example-marker');
expect(outcome.stderr).not.toContain(root);
expect(outcome.stderr).not.toContain(token);
- expect(journal.read()).toEqual(operation);
+ expect(journal.read()).toEqual({ ...operation, stage: 'quiescing' });
+ expect(stubs.invocations('pg_dump')).toEqual([]);
expect(() => journal.assertAdmission()).toThrow();
}, 40_000);
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index e96444537c..440d437689 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -594,10 +594,10 @@ export async function spawnDetached(bin, args = [], options = {}) {
}
/**
- * Internal, one-use launch of the fixed maintenance inspection worker. There
- * is no bin/argv/env/controlDir override and no ordinary-writer bypass option.
- * It retains the supervisor receipt even when the caller exits. Transfer and
- * PM2 lifecycle execution remain disabled pending proven writer quiescence.
+ * Internal, one-use launch of the fixed offline-transfer worker. There is no
+ * bin/argv/env/controlDir override and no ordinary-writer bypass option. It
+ * retains the supervisor receipt even when the caller exits; a successor needs
+ * that receipt before recovery (see databaseMaintenanceTransfer.js).
*/
export async function spawnDatabaseMaintenanceWorker(id, token) {
const [{ createDatabaseMaintenanceJournal }, { PATHS }] = await Promise.all([
diff --git a/server/services/databaseMaintenanceProducers.js b/server/services/databaseMaintenanceProducers.js
index a976ed22eb..400a3a2ae4 100644
--- a/server/services/databaseMaintenanceProducers.js
+++ b/server/services/databaseMaintenanceProducers.js
@@ -41,12 +41,15 @@ function sameIdentities(current, saved) {
/**
* Internal one-use coordinator worker stage. Stops producers only; descendants
* and pre-fence admitted spawns still require reconciliation before any dump.
- * No public entrypoint invokes this workflow until the transfer stages ship.
+ * A recovered worker at `exporting`/`importing` repeats the same readback and
+ * stop against the ORIGINAL identities before retrying its transfer step.
+ * `entered` is for the transfer worker, which has already claimed its one-use
+ * entry; standalone calls claim it here.
*/
-export async function stopOwnedDatabaseProducers(id, token) {
+export async function stopOwnedDatabaseProducers(id, token, { entered = false } = {}) {
const journal = createDatabaseMaintenanceJournal();
- const operation = journal.enterCoordinatorWorker(id, token);
- if (!['accepted', 'quiescing'].includes(operation.stage)) throw refused();
+ const operation = entered ? journal.assertEnteredCoordinatorWorker(id, token) : journal.enterCoordinatorWorker(id, token);
+ if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(operation.stage)) throw refused();
const inventory = async () => {
journal.assertCoordinatorWorker(id, token);
const rows = await listMaintenanceProcesses();
@@ -77,5 +80,5 @@ export async function stopOwnedDatabaseProducers(id, token) {
const final = await inventory();
sameIdentities(final, saved);
if (final.some(row => row.status !== 'stopped')) throw refused();
- return { id, stage: 'quiescing', producersStopped: true, quiescenceVerified: false, transferReady: false };
+ return { id, stage: journal.read().stage, producersStopped: true, quiescenceVerified: false, transferReady: false };
}
diff --git a/server/services/databaseMaintenanceQuiescence.js b/server/services/databaseMaintenanceQuiescence.js
index 8ccc78503b..8e7d682885 100644
--- a/server/services/databaseMaintenanceQuiescence.js
+++ b/server/services/databaseMaintenanceQuiescence.js
@@ -8,6 +8,7 @@ import { stopOwnedDatabaseProducers } from './databaseMaintenanceProducers.js';
const TERMINATE_GRACE_MS = 12000;
const POLL_MS = 100;
+const PREDECESSOR_GRACE_MS = 5000;
const refused = (reason) => Object.assign(
new Error(`Database writer quiescence refused: ${reason}. Maintenance remains fenced.`),
{ code: 'DATABASE_WRITER_QUIESCENCE' },
@@ -48,7 +49,7 @@ export async function reconcileDetachedWriters(id, token, { graceMs = TERMINATE_
const journal = createDatabaseMaintenanceJournal();
const registry = createDatabaseWriterRegistry();
const operation = journal.assertCoordinatorWorker(id, token);
- if (operation.stage !== 'quiescing' || !journal.readProducerSnapshot(id, token)) {
+ if (!['quiescing', 'exporting', 'importing'].includes(operation.stage) || !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
@@ -94,16 +95,49 @@ export async function reconcileDetachedWriters(id, token, { graceMs = TERMINATE_
journal.assertCoordinatorWorker(id, token);
for (const { row } of results) registry.retire(row.id, journal.reconciledWritersDirectory);
if (registry.read().length !== 0) throw refused('the writer inventory is not empty after retirement');
- return { id, stage: 'quiescing', writersReconciled: rows.length, writersTerminated: terminated,
+ return { id, stage: journal.read().stage, 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.
+ * Earlier coordinator workers of this operation ran dump/import children in
+ * their own process group. Their supervisor's exit receipt (which recovery
+ * requires) does not prove those children stopped: a killed worker can leave
+ * an import running. Refuse while any recorded predecessor group has members.
+ * Nothing is signalled: the group may have emptied and its ID been reused, so
+ * the operator must inspect and stop it. Windows has no group proof at all.
*/
-export async function quiesceDatabaseWriters(id, token, options) {
- await stopOwnedDatabaseProducers(id, token);
+export async function assertPredecessorCoordinatorsStopped(id, token, { graceMs = PREDECESSOR_GRACE_MS, pollMs = POLL_MS } = {}) {
+ const journal = createDatabaseMaintenanceJournal();
+ const predecessors = journal.readPredecessorWorkers(id, token);
+ if (!predecessors.some(worker => worker.started)) return { predecessorsVerified: predecessors.length };
+ if (process.platform === 'win32') throw refused('a previous coordinator\'s children cannot be proven stopped on Windows');
+ const groups = new Set(predecessors.filter(worker => worker.pgid !== null).map(worker => worker.pgid));
+ const deadline = Date.now() + graceMs;
+ let consecutive = 0;
+ // Two consecutive empty snapshots; the predecessor supervisor may still be
+ // exiting just after publishing its receipt.
+ while (consecutive < 2) {
+ journal.assertCoordinatorWorker(id, token);
+ const processes = await snapshotProcesses();
+ const own = processes.find(proc => proc.pid === process.pid)?.pgid;
+ // A recorded ID equal to our own group was empty when ours was created.
+ const occupied = processes.some(proc => proc.pgid !== own && groups.has(proc.pgid));
+ consecutive = occupied ? 0 : consecutive + 1;
+ if (occupied && Date.now() >= deadline) throw refused('a previous coordinator\'s dump or import process is still running');
+ if (consecutive < 2) await sleep(pollMs);
+ }
+ return { predecessorsVerified: predecessors.length };
+}
+
+/**
+ * The full internal quiescence stage for the entered transfer worker: stop
+ * owned PM2 producers, prove earlier coordinator children stopped, then
+ * reconcile detached writers. Every transfer attempt repeats it before any
+ * dump or import; a recovered worker never relies on a predecessor's result.
+ */
+export async function quiesceDatabaseWriters(id, token, options = {}) {
+ await stopOwnedDatabaseProducers(id, token, { entered: true });
+ await assertPredecessorCoordinatorsStopped(id, token, options);
return reconcileDetachedWriters(id, token, options);
}
diff --git a/server/services/databaseMaintenanceTransfer.js b/server/services/databaseMaintenanceTransfer.js
new file mode 100644
index 0000000000..3af58eb30c
--- /dev/null
+++ b/server/services/databaseMaintenanceTransfer.js
@@ -0,0 +1,152 @@
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import { closeSync, createReadStream, fsyncSync, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
+import { basename, dirname, join } from 'node:path';
+import { PATHS } from '../lib/paths.js';
+import { createDatabaseMaintenanceJournal } from '../lib/databaseMaintenanceJournal.js';
+import { snapshotProcesses } from '../lib/detachedSpawn.js';
+import { quiesceDatabaseWriters } from './databaseMaintenanceQuiescence.js';
+
+const refused = (reason) => Object.assign(
+ new Error(`Database transfer refused: ${reason}. Maintenance remains fenced.`),
+ { code: 'DATABASE_TRANSFER' },
+);
+
+// pg_dump's plain-format completion marker. Newer releases may append an
+// `\unrestrict` line after it, so only the tail is searched.
+const DUMP_COMPLETE = '-- PostgreSQL database dump complete';
+const TAIL_BYTES = 4096;
+
+function syncPath(path) {
+ if (process.platform === 'win32') return;
+ const fd = openSync(path, 'r');
+ try { fsyncSync(fd); } finally { closeSync(fd); }
+}
+
+async function digest(path) {
+ const hash = createHash('sha256');
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
+ return hash.digest('hex');
+}
+
+// Regular file only (never a symlink), with the bytes the manifest recorded.
+async function dumpIdentity(path) {
+ const stat = lstatSync(path);
+ if (!stat.isFile()) throw refused('the recovery dump is not a regular file');
+ return { bytes: stat.size, sha256: await digest(path) };
+}
+
+function hasCompletionMarker(path) {
+ const fd = openSync(path, 'r');
+ try {
+ const { size } = fstatSync(fd);
+ const length = Math.min(size, TAIL_BYTES);
+ const buffer = Buffer.alloc(length);
+ readSync(fd, buffer, 0, length, size - length);
+ return buffer.toString('utf8').includes(DUMP_COMPLETE);
+ } finally {
+ closeSync(fd);
+ }
+}
+
+/**
+ * Run scripts/db.sh bound to ONE recorded endpoint. The environment is built
+ * from an allowlist: inherited libpq variables (PGHOST, PGHOSTADDR, PGSERVICE,
+ * PGOPTIONS, …) never reach it, and db.sh strips them again for explicit
+ * endpoints. Children stay in this worker's process group so a successor can
+ * prove none survive (assertPredecessorCoordinatorsStopped). Output is kept
+ * internal: it can name hosts and paths.
+ */
+function runDbScript(action, endpoint, argument, dumpDir) {
+ const env = { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? PATHS.installRoot,
+ PGPASSWORD: process.env.PGPASSWORD || 'portos', PORTOS_DUMP_DIR: dumpDir, LC_ALL: 'C' };
+ const args = [join(PATHS.root, 'scripts', 'db.sh'), action, '--endpoint',
+ endpoint.host, String(endpoint.port), endpoint.user, endpoint.database, argument];
+ return new Promise((resolve) => {
+ const child = spawn('bash', args, { cwd: PATHS.root, env, stdio: ['ignore', 'pipe', 'ignore'] });
+ let stdout = '';
+ child.stdout.on('data', chunk => { if (stdout.length < 65536) stdout += chunk; });
+ child.once('error', () => resolve({ code: null, stdout: '' }));
+ child.once('close', code => resolve({ code, stdout }));
+ });
+}
+
+async function recordOwnGroup(journal, id, token) {
+ if (process.platform === 'win32') return;
+ const own = (await snapshotProcesses()).find(proc => proc.pid === process.pid)?.pgid;
+ if (!Number.isSafeInteger(own) || own <= 0) throw refused('the coordinator process group is unknown');
+ journal.recordCoordinatorGroup(id, token, own);
+}
+
+async function exportRecoveryDump(journal, id, token, operation) {
+ const path = journal.transferDumpPath(id);
+ journal.assertCoordinatorWorker(id, token);
+ const result = await runDbScript('export', operation.source, basename(path, '.sql').slice('portos-'.length), dirname(path));
+ journal.assertCoordinatorWorker(id, token);
+ // A failed or incomplete export is never recorded, so it can never be
+ // imported; the next attempt exports again after renewed quiescence.
+ if (result.code !== 0) throw refused(`the source export failed (exit ${result.code ?? 'spawn'})`);
+ if (result.stdout.trim().split('\n').at(-1) !== path) throw refused('the source export did not publish the recorded dump');
+ if (!lstatSync(path).isFile() || !hasCompletionMarker(path)) throw refused('the source export is incomplete');
+ syncPath(path);
+ syncPath(dirname(path));
+ const identity = await dumpIdentity(path);
+ return journal.recordTransferDump(id, token, { id, source: operation.source, file: basename(path), ...identity });
+}
+
+async function assertRecordedDump(journal, id, dump) {
+ const path = journal.transferDumpPath(id);
+ let identity;
+ try { identity = await dumpIdentity(path); } catch {
+ throw refused('the recorded recovery dump is missing');
+ }
+ if (identity.bytes !== dump.bytes || identity.sha256 !== dump.sha256) {
+ throw refused('the recovery dump no longer matches its recorded digest');
+ }
+ return path;
+}
+
+/**
+ * Internal offline transfer for the one entered coordinator worker. It never
+ * changes saved mode, restarts producers, or reopens admission: the result is
+ * a committed target import at `importing`, awaiting verified restart (#8851).
+ *
+ * Every attempt (including a recovered successor) first repeats quiescence.
+ * `exporting` without a recorded dump re-exports; a recorded dump is reused
+ * only when its bytes still match. `importing` retries only the recorded dump
+ * into the recorded target, in one transaction. Direction never changes.
+ * `options` only shortens reconciliation waits for subprocess tests.
+ */
+export async function runDatabaseTransfer(id, token, options = {}) {
+ const journal = createDatabaseMaintenanceJournal();
+ const entered = journal.enterCoordinatorWorker(id, token);
+ if (!['accepted', 'quiescing', 'exporting', 'importing'].includes(entered.stage)) {
+ throw refused(`stage ${entered.stage} is not a transfer stage`);
+ }
+ await recordOwnGroup(journal, id, token);
+ await quiesceDatabaseWriters(id, token, options);
+
+ let operation = journal.assertEnteredCoordinatorWorker(id, token);
+ if (operation.stage === 'quiescing') operation = journal.transition(id, token, 'quiescing', 'exporting');
+ if (operation.stage === 'exporting') {
+ const dump = journal.readTransferDump(id) ?? await exportRecoveryDump(journal, id, token, operation);
+ await assertRecordedDump(journal, id, dump);
+ operation = journal.transition(id, token, 'exporting', 'importing');
+ }
+ if (operation.stage !== 'importing') throw refused('the operation left the transfer stages');
+
+ const dump = journal.readTransferDump(id);
+ if (!dump) throw refused('no complete recovery dump is recorded');
+ let imported = false;
+ if (!journal.readTransferImport(id)) {
+ const path = await assertRecordedDump(journal, id, dump);
+ journal.assertCoordinatorWorker(id, token);
+ const result = await runDbScript('import', operation.target, path, dirname(path));
+ journal.assertCoordinatorWorker(id, token);
+ if (result.code !== 0) throw refused(`the target import failed and was rolled back (exit ${result.code ?? 'spawn'})`);
+ journal.recordTransferImport(id, token, { id, target: operation.target, sha256: dump.sha256 });
+ imported = true;
+ }
+ return { id, stage: 'importing', source: operation.source.mode, target: operation.target.mode,
+ imported, importCommitted: true, sourceRetained: true, restartVerified: false };
+}
diff --git a/server/services/databaseMaintenanceTransfer.test.js b/server/services/databaseMaintenanceTransfer.test.js
new file mode 100644
index 0000000000..b5a91844d8
--- /dev/null
+++ b/server/services/databaseMaintenanceTransfer.test.js
@@ -0,0 +1,239 @@
+// Offline transfer workflow against the REAL journal, writer reconciliation
+// (live process table) and scripts/db.sh, with PM2 mocked at its module
+// boundary and pg_dump/psql replaced by disposable stubs. No live database,
+// PM2 daemon or install data is touched.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { spawn } from 'node:child_process';
+import { createHash, randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';
+
+const context = vi.hoisted(() => ({ root: undefined, list: null, stop: null }));
+vi.mock('../lib/paths.js', async original => {
+ const actual = await original();
+ return { ...actual, PATHS: new Proxy(actual.PATHS, {
+ get: (target, key) => {
+ if (key === 'data' && context.root) return context.root + '/data';
+ if (key === 'installRoot' && context.root) return context.root;
+ return target[key];
+ },
+ }) };
+});
+vi.mock('./pm2.js', () => ({
+ listMaintenanceProcesses: (...args) => context.list(...args),
+ stopApp: (...args) => context.stop(...args),
+}));
+const { createDatabaseMaintenanceJournal } = await import('../lib/databaseMaintenanceJournal.js');
+const { spawnDetached } = await import('../lib/detachedSpawn.js');
+const { runDatabaseTransfer } = await import('./databaseMaintenanceTransfer.js');
+
+const native = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };
+const docker = { mode: 'docker', host: 'docker.example.invalid', port: 5561, database: 'example_test', user: 'example' };
+const fast = { graceMs: 1500, pollMs: 20 };
+const endpointArgs = endpoint => `-h ${endpoint.host} -p ${endpoint.port} -U ${endpoint.user} -d ${endpoint.database}`;
+const sha256 = text => createHash('sha256').update(text).digest('hex');
+const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
+const savedEnv = { ...process.env };
+
+let root;
+let journal;
+let stubs;
+let rows;
+let operation;
+let token;
+let strays;
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'database-transfer-'));
+ writeFileSync(join(root, '.portos-disposable-root'), '');
+ mkdirSync(join(root, 'server', 'cos-runner'), { recursive: true });
+ writeFileSync(join(root, 'server', 'start.js'), '');
+ writeFileSync(join(root, 'server', 'cos-runner', 'index.js'), '');
+ context.root = root;
+ journal = createDatabaseMaintenanceJournal(join(root, 'data'));
+ stubs = installDatabaseStubs(root);
+ strays = [];
+ rows = [
+ { name: 'portos-cos', pmId: 12, pid: 1012, status: 'online', cwd: root, script: 'server/cos-runner/index.js' },
+ { name: 'portos-server', pmId: 13, pid: 1013, status: 'online', cwd: root, script: 'server/start.js' },
+ ];
+ context.list = vi.fn(async () => rows.map(row => ({ ...row })));
+ context.stop = vi.fn(async id => {
+ const row = rows.find(value => value.pmId === id);
+ stubs.event('stop ' + row.name);
+ row.status = 'stopped'; row.pid = 0;
+ return { success: true };
+ });
+ // Inherited libpq settings that must never redirect the transfer.
+ Object.assign(process.env, {
+ PATH: `${stubs.bin}:${savedEnv.PATH}`, PGPASSWORD: 'example-password',
+ PGHOST: 'inherited.example.invalid', PGPORT: '1', PGUSER: 'inherited', PGDATABASE: 'inherited',
+ PGHOSTADDR: '192.0.2.10', PGSERVICE: 'inherited', PGSERVICEFILE: '/example/pg_service.conf',
+ PGOPTIONS: '-c search_path=inherited',
+ });
+});
+afterEach(() => {
+ for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key];
+ Object.assign(process.env, savedEnv);
+ for (const group of strays) { try { process.kill(-group, 'SIGKILL'); } catch { /* already gone */ } }
+ context.root = undefined;
+ rmSync(root, { recursive: true, force: true });
+});
+
+function begin(source = native, target = docker) {
+ operation = journal.begin({ source, target });
+ token = journal.acquireCoordinator(operation.id);
+ journal.reserveCoordinatorWorker(operation.id, token);
+}
+
+// Same-operation recovery exactly as a detached supervisor receipt permits it.
+function successor() {
+ const previous = token;
+ writeFileSync(join(root, 'data', 'database-maintenance', 'worker-' + previous, 'exit'), '1\n');
+ token = journal.recoverCoordinator(operation.id, previous, randomUUID());
+ journal.reserveCoordinatorWorker(operation.id, token);
+ return previous;
+}
+
+const transfer = () => runDatabaseTransfer(operation.id, token, fast);
+const dumpPath = () => join(root, 'data', 'db-dumps', `portos-maintenance-${operation.id}.sql`);
+
+// An ordinary process of this install: a pooled write and a detached spawn.
+function ordinaryWriter() {
+ const dbUrl = new URL('../lib/db.js', import.meta.url).href;
+ const detachedUrl = new URL('../lib/detachedSpawn.js', import.meta.url).href;
+ const ran = join(root, 'ordinary-ran');
+ const code = `import { query } from ${JSON.stringify(dbUrl)};
+ import { spawnDetached } from ${JSON.stringify(detachedUrl)};
+ const out = {};
+ try { await query('INSERT INTO example_record VALUES (1)'); out.query = 'allowed'; } catch (err) { out.query = err.code ?? 'failed'; }
+ const child = await spawnDetached(process.execPath, ['-e', ${JSON.stringify(`require('fs').writeFileSync(${JSON.stringify(ran)},'x')`)}],
+ { controlDir: ${JSON.stringify(join(root, 'ordinary-control'))} });
+ out.spawn = await new Promise(resolve => { child.once('error', err => resolve(err.code)); child.once('close', () => resolve('ran')); });
+ console.log(JSON.stringify(out)); process.exit(0);`;
+ const env = { ...savedEnv, NODE_ENV: 'test', PORTOS_DATA_ROOT: root,
+ PGHOST: 'ordinary.example.invalid', PGPORT: '1', PGDATABASE: 'example_test' };
+ delete env.VITEST;
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, ['--input-type=module', '-e', code], { env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '';
+ child.stdout.on('data', chunk => { stdout += chunk; });
+ child.once('error', reject);
+ child.once('close', () => resolve({ ...JSON.parse(stdout || '{}'), ran: existsSync(ran) }));
+ });
+}
+
+describe.skipIf(process.platform === 'win32')('offline database transfer', () => {
+ it.each([[native, docker], [docker, native]])('exports only after every writer stops, then imports the recorded dump into the recorded target (%#)', async (source, target) => {
+ const writer = await spawnDetached(process.execPath, ['-e', 'setInterval(()=>{},1000)'], { controlDir: join(root, 'writer'), pollMs: 10 });
+ strays.push(writer.pid);
+ stubs.writerPid(writer.pid);
+ begin(source, target);
+
+ const result = await transfer();
+ expect(result).toEqual({ id: operation.id, stage: 'importing', source: source.mode, target: target.mode,
+ imported: true, importCommitted: true, sourceRetained: true, restartVerified: false });
+ // Regression caught: a dump taken while a producer or detached writer still ran.
+ expect(stubs.events()).toEqual(['stop portos-cos', 'stop portos-server', 'dump writer=dead', 'import-start', 'import-commit']);
+ expect(alive(writer.pid)).toBe(false);
+ const [dump] = stubs.invocations('pg_dump');
+ const [load] = stubs.invocations('psql');
+ expect(dump).toBe(`pg_dump ${endpointArgs(source)} --no-owner --no-privileges --if-exists --clean`);
+ expect(load).toBe(`psql ${endpointArgs(target)} -v ON_ERROR_STOP=1 --single-transaction`);
+ // Inherited libpq endpoint/option variables never reach the client tools.
+ expect(stubs.receivedVariables()).toEqual(['PGPASSWORD']);
+ expect(stubs.calls()).not.toMatch(/inherited|192\.0\.2\.10/);
+ expect(stubs.imported()).toBe(STUB_DUMP_COMPLETE);
+ // The source recovery dump is retained, recorded, and bound to this operation.
+ expect(readFileSync(dumpPath(), 'utf8')).toBe(STUB_DUMP_COMPLETE);
+ const manifest = JSON.parse(readFileSync(join(root, 'data', 'database-maintenance', 'transfer-dump.json'), 'utf8'));
+ expect(manifest).toEqual({ id: operation.id, source, file: `portos-maintenance-${operation.id}.sql`,
+ bytes: Buffer.byteLength(STUB_DUMP_COMPLETE), sha256: sha256(STUB_DUMP_COMPLETE) });
+ // Direction, mode and the fence are unchanged; restart is #8851's.
+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });
+ expect(journal.transferStatus(operation.id)).toEqual({ dump: 'recorded', import: 'committed' });
+ expect(existsSync(join(root, '.env'))).toBe(false);
+ expect(() => journal.assertAdmission()).toThrow();
+ // One-use worker entry: the same owner cannot transfer twice.
+ await expect(transfer()).rejects.toThrow();
+ expect(stubs.invocations('psql')).toHaveLength(1);
+ }, 30_000);
+
+ it('refuses ordinary writes and spawns while export and import are paused', async () => {
+ begin();
+ stubs.setMode('dump', 'pause');
+ stubs.setMode('import', 'pause');
+ const pending = transfer();
+ await vi.waitFor(() => expect(stubs.started('dump')).toBe(true), { timeout: 10_000, interval: 20 });
+ expect(journal.read().stage).toBe('exporting');
+ expect(await ordinaryWriter()).toEqual({ query: 'DATABASE_MAINTENANCE', spawn: 'DATABASE_MAINTENANCE', ran: false });
+ stubs.release('dump');
+ await vi.waitFor(() => expect(stubs.started('import')).toBe(true), { timeout: 10_000, interval: 20 });
+ expect(journal.read().stage).toBe('importing');
+ expect(await ordinaryWriter()).toEqual({ query: 'DATABASE_MAINTENANCE', spawn: 'DATABASE_MAINTENANCE', ran: false });
+ stubs.release('import');
+ expect(await pending).toMatchObject({ importCommitted: true });
+ }, 30_000);
+
+ it.each(['fail', 'incomplete'])('never records a %s export; a recovered owner re-quiesces and exports again', async mode => {
+ begin();
+ stubs.setMode('dump', mode);
+ await expect(transfer()).rejects.toThrow(mode === 'fail' ? /source export failed/ : /incomplete/);
+ expect(journal.read().stage).toBe('exporting');
+ expect(journal.transferStatus(operation.id)).toEqual({ dump: 'absent', import: 'pending' });
+ expect(stubs.invocations('psql')).toEqual([]);
+
+ const retired = successor();
+ await expect(runDatabaseTransfer(operation.id, retired, fast)).rejects.toThrow();
+ stubs.setMode('dump', 'ok');
+ const listed = context.list.mock.calls.length;
+ expect(await transfer()).toMatchObject({ stage: 'importing', imported: true });
+ // Renewed producer readback precedes the retried export.
+ expect(context.list.mock.calls.length).toBeGreaterThan(listed);
+ expect(stubs.invocations('pg_dump')).toHaveLength(2);
+ expect(stubs.imported()).toBe(STUB_DUMP_COMPLETE);
+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });
+ }, 30_000);
+
+ it.each([[native, docker], [docker, native]])('retries a failed import only from the same recorded dump into the same target (%#)', async (source, target) => {
+ begin(source, target);
+ stubs.setMode('import', 'fail');
+ await expect(transfer()).rejects.toThrow(/target import failed/);
+ expect(journal.read()).toEqual({ ...operation, stage: 'importing' });
+ expect(journal.transferStatus(operation.id)).toEqual({ dump: 'recorded', import: 'pending' });
+ const recorded = readFileSync(dumpPath(), 'utf8');
+
+ successor();
+ stubs.setMode('import', 'ok');
+ expect(await transfer()).toMatchObject({ source: source.mode, target: target.mode, imported: true });
+ // No second export: the retry cannot pick up post-fence source state.
+ expect(stubs.invocations('pg_dump')).toHaveLength(1);
+ expect(stubs.invocations('psql')).toEqual([
+ `psql ${endpointArgs(target)} -v ON_ERROR_STOP=1 --single-transaction`,
+ `psql ${endpointArgs(target)} -v ON_ERROR_STOP=1 --single-transaction`,
+ ]);
+ expect(readFileSync(dumpPath(), 'utf8')).toBe(recorded);
+ expect(journal.transferStatus(operation.id)).toEqual({ dump: 'recorded', import: 'committed' });
+
+ // A later recovery never imports a committed transfer again.
+ successor();
+ expect(await transfer()).toMatchObject({ imported: false, importCommitted: true });
+ expect(stubs.invocations('psql')).toHaveLength(2);
+ }, 30_000);
+
+ it.each(['changed', 'missing'])('refuses to import a recovery dump whose recorded bytes are %s', async fault => {
+ begin();
+ stubs.setMode('import', 'fail');
+ await expect(transfer()).rejects.toThrow(/target import failed/);
+ if (fault === 'changed') writeFileSync(dumpPath(), STUB_DUMP_COMPLETE.replace('id int', 'id text'));
+ else rmSync(dumpPath());
+ successor();
+ stubs.setMode('import', 'ok');
+ await expect(transfer()).rejects.toThrow(fault === 'changed' ? /no longer matches/ : /missing/);
+ expect(stubs.invocations('psql')).toHaveLength(1);
+ expect(stubs.invocations('pg_dump')).toHaveLength(1);
+ expect(journal.read().stage).toBe('importing');
+ }, 30_000);
+});
diff --git a/server/test/fixtures/databaseTransferStubs.js b/server/test/fixtures/databaseTransferStubs.js
new file mode 100644
index 0000000000..f0078a6188
--- /dev/null
+++ b/server/test/fixtures/databaseTransferStubs.js
@@ -0,0 +1,78 @@
+// Disposable stand-ins for the PostgreSQL client tools scripts/db.sh runs
+// during an offline transfer. No real database is ever reached: pg_dump and
+// psql are shell stubs placed first on PATH, and a `uname` stub keeps db.sh
+// from prepending Homebrew's real PostgreSQL on macOS. Test endpoints use
+// `.invalid` hosts so even an unexpected real client could not connect.
+//
+// Each stub logs its argv and every PG* variable it received, and its behavior
+// is switched by mode files: dump-mode (ok | fail | incomplete | pause) and
+// import-mode (ok | fail | pause). A paused stub publishes `<kind>-started`
+// and waits for `<kind>-release`. events.log orders stops, dumps and imports.
+import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+export const STUB_DUMP_BODY = 'CREATE TABLE example_record (id int);\n';
+export const STUB_DUMP_COMPLETE = `${STUB_DUMP_BODY}--\n-- PostgreSQL database dump complete\n--\n\n`;
+
+const quote = value => `'${value.replaceAll("'", "'\\''")}'`;
+
+function writeStub(path, body) {
+ writeFileSync(path, body);
+ chmodSync(path, 0o755);
+}
+
+export function installDatabaseStubs(root) {
+ const dir = join(root, 'stubs');
+ const bin = join(dir, 'bin');
+ mkdirSync(bin, { recursive: true });
+ const R = quote(dir);
+ const logInvocation = name => `{ echo "${name} $*"; env | grep '^PG' | sort | sed 's/^/env /'; } >> "$R/calls.log"`;
+ const pause = kind => `: > "$R/${kind}-started"; while [ ! -e "$R/${kind}-release" ]; do sleep 0.05; done`;
+ writeStub(join(bin, 'uname'), '#!/bin/sh\necho Linux\n');
+ writeStub(join(bin, 'pg_dump'), `#!/bin/sh
+R=${R}
+mode=$(cat "$R/dump-mode" 2>/dev/null || echo ok)
+${logInvocation('pg_dump')}
+writer=none
+if [ -s "$R/writer.pid" ]; then
+ if kill -0 "$(cat "$R/writer.pid")" 2>/dev/null; then writer=alive; else writer=dead; fi
+fi
+echo "dump writer=$writer" >> "$R/events.log"
+if [ "$mode" = pause ]; then ${pause('dump')}; fi
+case "$mode" in
+ fail) printf 'DROP TABLE example_record;\\n'; exit 1 ;;
+ incomplete) printf '%s' ${quote(STUB_DUMP_BODY)}; exit 0 ;;
+esac
+printf '%s' ${quote(STUB_DUMP_COMPLETE)}
+`);
+ writeStub(join(bin, 'psql'), `#!/bin/sh
+R=${R}
+case "$*" in *--single-transaction*) ;; *) echo "psql-other $*" >> "$R/calls.log"; exit 0 ;; esac
+mode=$(cat "$R/import-mode" 2>/dev/null || echo ok)
+${logInvocation('psql')}
+echo "import-start" >> "$R/events.log"
+if [ "$mode" = pause ]; then ${pause('import')}; fi
+cat > "$R/import.pending"
+if [ "$mode" = fail ]; then rm -f "$R/import.pending"; exit 3; fi
+mv "$R/import.pending" "$R/imported.sql"
+echo "import-commit" >> "$R/events.log"
+`);
+ const read = name => (existsSync(join(dir, name)) ? readFileSync(join(dir, name), 'utf8') : '');
+ return {
+ dir,
+ bin,
+ setMode: (kind, mode) => writeFileSync(join(dir, `${kind}-mode`), mode),
+ release: kind => writeFileSync(join(dir, `${kind}-release`), ''),
+ started: kind => existsSync(join(dir, `${kind}-started`)),
+ event: line => appendFileSync(join(dir, 'events.log'), line + '\n'),
+ events: () => read('events.log').split('\n').filter(Boolean),
+ calls: () => read('calls.log'),
+ imported: () => read('imported.sql'),
+ // argv lines only (env lines are separate)
+ invocations: name => read('calls.log').split('\n').filter(line => line.startsWith(name + ' ')),
+ // PG* variable names each stub received
+ receivedVariables: () => [...new Set(read('calls.log').split('\n')
+ .filter(line => line.startsWith('env ')).map(line => line.slice(4).split('=')[0]))].sort(),
+ writerPid: pid => writeFileSync(join(dir, 'writer.pid'), String(pid)),
+ };
+}