Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: block database migration that can strand accepted writes (#8804)
[._.]/ Adam Eivy65e2b21464a1
diff --git a/client/src/components/settings/DatabaseTab.jsx b/client/src/components/settings/DatabaseTab.jsxindex 77e658b23c..416bd429e8 100644--- a/client/src/components/settings/DatabaseTab.jsx+++ b/client/src/components/settings/DatabaseTab.jsx@@ -99,21 +99,6 @@ function BackendCard({ label, icon: Icon, backend, isActive, dbStatus, runAction{/* Non-active backend actions */}{!isActive && (data?.installed || data?.configured) && (<>- {/* Migrate & switch to this backend */}- <button- onClick={() => setConfirmAction({- type: 'migrate',- label: `Migrate to ${displayLabel} and switch?`,- detail: `Exports data from ${activeLabel}, imports into ${displayLabel}, and makes ${displayLabel} the active backend.`,- action: () => runAction(`migrate-${backend}`, () => switchDatabase(backend, true), `Migrated to ${displayLabel}`)- })}- disabled={busy}- className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}- >- <ArrowRightLeft size={12} />- Migrate to {displayLabel}- </button>-{/* Switch without migration */}<buttononClick={() => setConfirmAction({@@ -276,6 +261,12 @@ export function DatabaseTab() {/></div>+ <p className="text-sm text-port-warning">+ Database migration is temporarily unavailable to protect writes made while PortOS is running.+ Keep using the current backend until a coordinated shutdown and restart is available.+ Backups remain available.+ </p>+{/* Progress indicator */}{progressMsg && (<div className="flex items-center gap-2 text-sm text-port-accent bg-port-accent/10 border border-port-accent/20 rounded-lg px-3 py-2">diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 7d3f17f8cc..2d6c4585d9 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -11,6 +11,24 @@ The dump includes the machine-local `cos_pending_agent_feedback` reference indexImplementation: `server/services/backup.js` (snapshot/dump/restore), `server/services/backupScheduler.js` (cron), `server/routes/backup.js` (API), and `server/routes/database.js` (DB export/sync).+## Database backend migration++Migration between Docker and native PostgreSQL is temporarily unavailable in+Settings and `scripts/db.sh migrate`. Copying a live database and switching+mode can strand writes accepted after the snapshot. Backups and standalone+exports remain available; they do not make a new backend authoritative.++Keep using the current backend until the coordinated offline cutover ships+(#8797 / #8805). It must stop/drain every PortOS writer, including the CoS+runner, then verify the restarted server's target connection before declaring+success. Expect downtime. Do not substitute Sync followed by Switch.++If a previous migration left records missing, preserve both backend databases+and the migration dump. The source may hold accepted writes absent from the+target; overwriting or deleting it can destroy that recovery copy. Compare and+recover the missing records before choosing an authoritative backend.+See [storage mode guidance](STORAGE.md#moving-between-docker-and-native).+## What gets backed upA backup run (`runBackup` in `server/services/backup.js`) writes to:diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 9e963cc07c..49e069da4a 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -203,22 +203,25 @@ The escape hatch is **guarded from bitrot by the test suite** (tests boot with `### Moving between Docker and native-`scripts/db.sh migrate` exports the mode selected in the repository-root `.env`-and imports into the other mode. The dump uses `--clean`: it **replaces the-destination's database objects and records**, rather than merging records.-Back up both databases and stop PortOS processes before an intentional move.--`scripts/db.sh setup-native` selects **native** mode after provisioning; it does-not copy Docker data. Running `scripts/db.sh migrate` immediately afterward-therefore copies **native → Docker**, potentially overwriting your existing-Docker records with a fresh database. For **Docker → native**, first select the-Docker source with `scripts/db.sh use-docker`, ensure that source is running,-then run `scripts/db.sh migrate`. Check `scripts/db.sh status` before migrating.-The migration switches to the destination mode after a successful import.--The migration command assumes the standard native `:5432` and Docker `:5561`-destination ports. For custom ports, use an explicitly targeted dump/restore-instead. See [Backup & Restore](./BACKUP.md) for backup and restore semantics.+Automatic backend migration is temporarily unavailable. Both the Settings+migration request and `scripts/db.sh migrate` refuse before copying data or+changing mode. The former path could accept writes after its dump snapshot+and strand them on the source; changing `.env` also leaves the running server+connected to its original pool.++Keep the existing backend selected and use backups until the coordinated+offline cutover is available (tracked in #8797 / #8805). A safe cutover requires+downtime for **all** PortOS writers, including the CoS runner, and verification+that the restarted server actually uses the target. A server-only restart or+a saved-mode change is not that verification. Do not use Sync followed by Switch+as a migration workaround.++`scripts/db.sh setup-native` selects native mode after provisioning; it does+not copy Docker data. Preserve the backend holding your records. If an earlier+migration already ran, keep both databases and its dump intact: the old source+may contain writes missing from the target. Do not destroy either backend or+reverse the migration before comparing and recovering those records.+See [Backup & Restore](./BACKUP.md) for backup and restore semantics.### Boot schema upgrades & lock windowsdiff --git a/scripts/db-migrate.test.js b/scripts/db-migrate.test.jsindex cf58fe766e..6cfffa3692 100644--- a/scripts/db-migrate.test.js+++ b/scripts/db-migrate.test.js@@ -1,6 +1,6 @@// Runs the real scripts/db.sh control flow against stubbed executables in a-// temporary root, so a failed pg_dump is proven to stop `migrate` before any-// import, mode change, or source shutdown (#8781). No real database is touched:+// temporary root. Migration refuses before side effects; failed pg_dump never+// publishes a partial export (#8781). No real database is touched:// every host command db.sh reaches (docker, psql, pg_dump, pg_isready, uname)// is a stub placed ahead of the system directories on PATH.import { describe, it, expect, beforeEach, afterEach } from 'vitest';@@ -98,8 +98,8 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',const tempArtifacts = () => (existsSync(dumpDir) ? readdirSync(dumpDir).filter(f => f.startsWith('portos-export.')) : []);const dumps = () => (existsSync(dumpDir) ? readdirSync(dumpDir).filter(f => f.endsWith('.sql')) : []);- it.each(['partial', 'empty'])('aborts migrate on a %s failed dump before import, mode change, or shutdown', (mode) => {- const result = run(['migrate'], mode);+ it.each(['partial', 'empty'])('refuses to publish a %s failed export', (mode) => {+ const result = run(['export', 'failed'], mode);expect(result.status).not.toBe(0);const log = readFileSync(stubLog, 'utf8');@@ -124,17 +124,25 @@ describe.skipIf(process.platform === 'win32')('scripts/db.sh export + migrate',expect(tempArtifacts()).toEqual([]);});- it('imports the complete dump and switches mode once on success', () => {- const result = run(['migrate'], 'ok');-+ it('publishes a complete export without switching mode or stopping the source', () => {+ const result = run(['export', 'complete'], 'ok');expect(result.status).toBe(0);- expect(readFileSync(importLog, 'utf8')).toBe(FULL_DUMP);- const log = readFileSync(stubLog, 'utf8');- expect(log.match(/^IMPORT$/gm)).toHaveLength(1);- expect(log.match(/^SOURCE_STOP$/gm)).toHaveLength(1);- expect(readFileSync(envFile, 'utf8')).toBe('PGMODE=native\n');- const [dump] = dumps();- expect(readFileSync(join(dumpDir, dump), 'utf8')).toBe(FULL_DUMP);+ expect(readFileSync(join(dumpDir, 'portos-complete.sql'), 'utf8')).toBe(FULL_DUMP);+ expect(readFileSync(envFile, 'utf8')).toBe('PGMODE=docker\n');+ expect(readFileSync(stubLog, 'utf8')).not.toMatch(/IMPORT|SOURCE_STOP/);expect(tempArtifacts()).toEqual([]);});++ it.each(['docker', 'native'])('refuses repeated %s migrations before any database command', (mode) => {+ writeFileSync(envFile, `PGMODE=${mode}\n`);+ for (let attempt = 0; attempt < 2; attempt++) {+ const result = run(['migrate'], 'ok');+ expect(result.status).not.toBe(0);+ expect(result.stderr).toMatch(/migration is temporarily unavailable/);+ expect(readFileSync(stubLog, 'utf8')).toBe('');+ expect(existsSync(importLog)).toBe(false);+ expect(existsSync(dumpDir)).toBe(false);+ expect(readFileSync(envFile, 'utf8')).toBe(`PGMODE=${mode}\n`);+ }+ });});diff --git a/scripts/db.sh b/scripts/db.shindex a3a51f10b0..a0956f84a0 100755--- a/scripts/db.sh+++ b/scripts/db.sh@@ -17,7 +17,7 @@# setup-native Install and configure native PostgreSQL via Homebrew# use-docker Switch to Docker mode# use-native Switch to native mode-# migrate Export from current mode, import to the other+# migrate Unavailable pending coordinated offline cutover# export Export database to a SQL dump file# import Import a SQL dump file into the database# logs Show database logs@@ -607,118 +607,13 @@ cmd_import() {log "Import complete"}-# Import a dump into a specific target using Docker's pg17 psql when available.-# This avoids version-mismatch issues when the host psql is older than the dump format.-import_to_target() {- local dumpfile="$1"- local target_port="$2"-- # Strip pg17-only features for compat with older psql- local filtered- filtered="$(sed -e '/^\\restrict /d' -e '/^\\unrestrict /d' -e '/^SET transaction_timeout/d' "$dumpfile")"-- # Prefer Docker's pg17 psql to avoid version mismatch with host psql- if docker_running; then- echo "$filtered" | docker exec -i -e PGPASSWORD="$PGPASSWORD" portos-db \- psql -h host.docker.internal -p "$target_port" -U "$PGUSER" -d "$PGDATABASE" \- -v ON_ERROR_STOP=1 --single-transaction- else- echo "$filtered" | PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$target_port" -U "$PGUSER" -d "$PGDATABASE" \- -v ON_ERROR_STOP=1 --single-transaction- fi-}--# Migrate data between Docker and native+# Do not snapshot and change mode while PortOS can still accept writes.+# A process-list probe is not a writer fence. The recoverable coordinator in+# #8805 must own admission, explicit endpoints and verified restart first.cmd_migrate() {- local current_mode- current_mode=$(get_mode)- local target_mode-- if [ "$current_mode" = "docker" ]; then- target_mode="native"- else- target_mode="docker"- fi-- info "Migrating data from $current_mode to $target_mode..."-- # Verify source is running- if ! run_psql -c "SELECT 1" >/dev/null 2>&1; then- err "Source database ($current_mode) is not running on port $PGPORT"- echo " Start it first: scripts/db.sh start"- exit 1- fi-- # Count source records- local count- count=$(run_psql -tAc "SELECT count(*) FROM memories" 2>/dev/null || echo "0")- info "Source has $count memories"-- # Export from source- # Abort before touching the target or the mode when the export fails (#8781)- local dumpfile- if ! dumpfile=$(cmd_export "migrate-$(date +%Y%m%d-%H%M%S)") || [ ! -f "$dumpfile" ]; then- err "Export from $current_mode failed — migration aborted; $target_mode was not modified and mode remains $current_mode"- exit 1- fi-- # Determine target port- local target_port- target_port=$([ "$target_mode" = "native" ] && echo "5432" || echo "5561")-- # Ensure target is running (keep source running too — they use different ports)- if [ "$target_mode" = "native" ]; then- # Ensure native pg is up (don't stop Docker — we need its pg17 psql)- if ! pg_isready -h "$PGHOST" -p "$target_port" >/dev/null 2>&1; then- start_native- fi- else- # Start Docker if not running- if ! docker_running; then- require_docker_compose- cd "$ROOT_DIR"- docker compose up -d db- info "Waiting for Docker PostgreSQL..."- for i in $(seq 1 30); do- if docker compose exec -T db pg_isready -U "$PGUSER" >/dev/null 2>&1; then break; fi- sleep 1- done- fi- fi-- # Restore mode on failure or interruption- _migrate_cleanup() {- warn "Migration aborted — restoring mode to $current_mode"- set_mode "$current_mode"- }- trap '_migrate_cleanup' ERR INT TERM-- # Import into target- info "Importing into $target_mode (port $target_port)..."- import_to_target "$dumpfile" "$target_port"-- # Switch mode to target- set_mode "$target_mode"- PGPORT=$(get_port)-- # Clear traps after successful import- trap - ERR INT TERM-- # Stop the old source if desired (both can coexist, but stop to save resources)- if [ "$current_mode" = "docker" ]; then- info "Stopping Docker..."- stop_docker- fi-- # Verify- local new_count- new_count=$(run_psql -tAc "SELECT count(*) FROM memories" 2>/dev/null || echo "0")-- echo ""- log "Migration complete!"- info "Source ($current_mode): $count memories"- info "Target ($target_mode): $new_count memories"- info "Dump saved: $dumpfile"+ err "Database migration is temporarily unavailable: coordinated shutdown and restart are required to preserve writes." >&2+ echo "Keep using the current backend. Backups remain available via scripts/db.sh export." >&2+ return 1}# Use Docker mode@@ -790,7 +685,7 @@ Commands:use-docker Switch to Docker mode (port 5561)use-native Switch to native/system mode (port 5432)- migrate Export from current mode, import to the other+ migrate Unavailable pending coordinated offline cutoverexport [label] Export database to data/db-dumps/import <file> Import a SQL dump filediff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex 4b03008b70..76ade47910 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -55,7 +55,7 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {};});-import { POOL_CONFIG } from '../lib/db.js';+import { POOL_CONFIG, query, checkHealth } from '../lib/db.js';import { execFile, spawn } from '../lib/childProcess.js';import { EventEmitter } from 'events';import { PassThrough, Readable } from 'stream';@@ -103,6 +103,28 @@ describe('database route boundary', () => {});});+// Regression: an API migration must not start the unfenced snapshot/cutover,+// even for an older client that still exposes the migration button.+describe('database migration admission', () => {+ it.each(['docker', 'native'])('refuses repeated migrations to %s without side effects', async (target) => {+ vi.clearAllMocks();+ const app = makeApp();+ const io = { emit: vi.fn() };+ app.set('io', io);+ for (let attempt = 0; attempt < 2; attempt++) {+ const res = await request(app).post('/api/database/switch').send({ target, migrate: true });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('DATABASE_CUTOVER_UNAVAILABLE');+ expect(res.body.error).toMatch(/coordinated shutdown and restart/);+ }+ expect(execFile).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(query).not.toHaveBeenCalled();+ expect(checkHealth).not.toHaveBeenCalled();+ expect(io.emit).not.toHaveBeenCalled();+ });+});+describe('isPg17OnlyDirective (sed-replacement line filter)', () => {it('matches the pg17-only directives the legacy sed stripped', () => {expect(isPg17OnlyDirective('\\restrict abc123')).toBe(true);diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex 574b643c04..70c6fa8744 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -231,17 +231,12 @@ async function switchDatabaseImpl({ target, migrate }, io) {const emit = (event, data) => io?.emit('database:progress', { event, ...data });if (migrate) {- emit('start', { message: `Migrating data to ${target}...` });- const result = await runDbScript(['migrate']);- if (result.exitCode !== 0) {- emit('error', { message: 'Migration failed' });- throw new ServerError('Migration failed', {- status: 500,- context: { details: result.stderr || result.stdout }- });- }- emit('complete', { message: `Migration to ${target} complete` });- return { success: true, output: result.stdout };+ // A shell child cannot fence the CoS runner or rebind this server's pool.+ // Re-enable only with the durable, verified offline cutover in #8805.+ throw new ServerError(+ 'Database migration is temporarily unavailable: a coordinated shutdown and restart is required to preserve writes. Keep using the current backend; backups remain available.',+ { status: 409, code: 'DATABASE_CUTOVER_UNAVAILABLE' }+ );}// Just switch mode without migrating