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

refactor([issue-1050]): share pg_dump version-resolution between backup and DB export

Adam Eivy4870698da78b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f21226322f..e9ffe768a5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,3 +10,4 @@
- **[issue-1027] Songs: vocal takes remember their pitch analysis** — a recorded take now saves its tuner trace and color-match score so your accuracy isn't recomputed every time you reopen the song.
- **[issue-1060] Cleaner test runs** — browser-dependent tests now run only under their own test environment, so the server test run no longer reports spurious failures from double-running them.
+- **[issue-1050] More reliable database exports** — manual database exports now pick a PostgreSQL dump tool that matches the database being exported, so an export no longer fails on machines with several Postgres versions installed.
diff --git a/server/lib/README.md b/server/lib/README.md
index a4b48f0304..145b9d2dc4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -189,6 +189,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `browserConfig.js` | Shared custom browser path helpers for deriving macOS app bundles, detecting configured browser choices, normalizing browser config, and validating Chrome-compatible binary paths. |
| `db.js` | PostgreSQL connection pool. |
| `pgTimestamp.js` | `mirrorTimestamp(value, fallback)` — coerce a hand-editable timestamp into a value Postgres TIMESTAMPTZ always accepts (or fall back), guarding boot-time binds against `Date.parse` rollover + out-of-range years. |
+| `pgTools.js` | `pg_dump` binary resolution shared by the backup snapshot path and the native↔Docker export path: `resolvePgDumpBinary(serverMajor)` (PORTOS_PGDUMP override → version-aware auto-select → bare `pg_dump`), plus the lower-level `pickPgDump` / `discoverPgDumpCandidates` / `resolvePgDump`. Picks the closest installed `pg_dump` whose major is ≥ the running server's. |
| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |
| `platform.js` | Platform/OS detection helpers. |
| `timezone.js` | Timezone utilities for scheduling. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 030ccf669b..f5bc2d90e2 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -160,6 +160,7 @@ export * from './browserConfig.js';
export * from './buildId.js';
export * from './db.js';
export * from './pgTimestamp.js';
+export * from './pgTools.js';
export * from './platform.js';
export * from './ports.js';
export * from './timezone.js';
diff --git a/server/lib/pgTools.js b/server/lib/pgTools.js
new file mode 100644
index 0000000000..7aa37eb069
--- /dev/null
+++ b/server/lib/pgTools.js
@@ -0,0 +1,135 @@
+/**
+ * pg_dump binary resolution.
+ *
+ * `pg_dump` REFUSES to dump a server newer than itself ("server version
+ * mismatch"), but a newer `pg_dump` dumps an older server fine. On machines
+ * with multiple Postgres installs (the common Homebrew case: an old
+ * `postgresql@NN` keg shadowing a newer running server in PATH) the bare
+ * `pg_dump` is often the wrong one, so these helpers discover the installed
+ * binaries and select the closest whose major is >= the running server's.
+ *
+ * Shared by both pg_dump consumers — the backup snapshot path
+ * (`server/services/backup.js`) and the native↔Docker backend-copy / export
+ * path (`server/routes/database.js`) — so the version-aware selection and the
+ * `PORTOS_PGDUMP` override behave identically in both. Self-contained: no
+ * imports out to other PortOS services.
+ */
+
+import { readdir } from 'fs/promises';
+import { join } from 'path';
+import { execFileAsync } from './fileUtils.js';
+
+/**
+ * Choose which discovered pg_dump binary to run, given the server's major
+ * version. pg_dump REFUSES to dump a server newer than itself ("server version
+ * mismatch"), but a newer pg_dump dumps an older server fine — so the rule is:
+ * pick the closest binary whose major is >= the server's.
+ *
+ * Pure + exported for unit testing (the IO-bound discovery lives in
+ * resolvePgDump, which feeds this the runnable candidates it found).
+ *
+ * @param {number|null} serverMajor - server's PG major version (null = unknown)
+ * @param {Array<{binary: string, major: number}>} candidates - runnable pg_dumps
+ * @returns {string|null} chosen binary path, or null if none discovered
+ */
+export function pickPgDump(serverMajor, candidates) {
+ if (!candidates?.length) return null;
+ // Unknown server version: keep prior behavior — trust the first (PATH) entry.
+ if (!Number.isFinite(serverMajor)) return candidates[0].binary;
+ // Prefer the smallest major that still satisfies >= server (closest match,
+ // avoids reaching for a wildly newer keg when an exact one is installed).
+ const viable = candidates.filter(c => c.major >= serverMajor).sort((a, b) => a.major - b.major);
+ if (viable.length) return viable[0].binary;
+ // Nothing is new enough. Return the newest we have so the resulting error is a
+ // clear "still too old" instead of an arbitrary pick — and so the version
+ // detection in dumpPostgres can flag it as version_mismatch.
+ return [...candidates].sort((a, b) => b.major - a.major)[0].binary;
+}
+
+/**
+ * Read a pg_dump binary's major version, or null if it isn't runnable.
+ * `pg_dump --version` prints e.g. "pg_dump (PostgreSQL) 17.10 (Homebrew)".
+ */
+async function pgDumpMajor(binary) {
+ const { stdout } = await execFileAsync(binary, ['--version']).catch(() => ({ stdout: '' }));
+ const m = stdout.match(/PostgreSQL\)\s+(\d+)/i);
+ return m ? parseInt(m[1], 10) : null;
+}
+
+/**
+ * Enumerate candidate pg_dump locations: the bare PATH binary, then versioned
+ * Homebrew kegs and Postgres.app bundles (where multiple majors coexist and
+ * PATH order silently picks the wrong one).
+ */
+export async function discoverPgDumpCandidates() {
+ // Note: the PORTOS_PGDUMP override is NOT a candidate here — resolvePgDumpBinary
+ // honors it outright before discovery runs, so it's never subject to the
+ // closest-major auto-selection below.
+ const paths = ['pg_dump']; // whatever PATH resolves — preserves the old default
+ const kegDirs = ['/opt/homebrew/opt', '/usr/local/opt', '/Applications/Postgres.app/Contents/Versions'];
+ for (const dir of kegDirs) {
+ const entries = await readdir(dir).catch(() => []);
+ for (const entry of entries) {
+ if (dir.endsWith('Versions') || entry.startsWith('postgresql')) {
+ paths.push(join(dir, entry, 'bin', 'pg_dump'));
+ }
+ }
+ }
+ // Probe versions concurrently (each `pg_dump --version` is an independent
+ // spawn); [...new Set(paths)] de-dups while preserving priority order, which
+ // Promise.all keeps — so pickPgDump still sees PATH > kegs.
+ const probed = await Promise.all(
+ [...new Set(paths)].map(async (binary) => ({ binary, major: await pgDumpMajor(binary) }))
+ );
+ return probed.filter(c => c.major != null);
+}
+
+/**
+ * Auto-select a pg_dump binary for a server at `serverMajor` by discovering
+ * installed binaries and picking the closest whose major is >= the server's.
+ * Returns the chosen path and whether it satisfies the server's version
+ * (false ⇒ the dump will fail with a version mismatch and there's nothing
+ * newer installed).
+ *
+ * The explicit `PORTOS_PGDUMP` override is NOT handled here — the caller
+ * (`resolvePgDumpBinary`) honors it before reaching this resolver, so the
+ * override works even when the server version is unknown and this resolver
+ * is skipped.
+ *
+ * @param {number} serverMajor - known server major (caller guards on isFinite)
+ * @returns {Promise<{binary: string, satisfies: boolean}>}
+ */
+export async function resolvePgDump(serverMajor) {
+ const candidates = await discoverPgDumpCandidates();
+ const binary = pickPgDump(serverMajor, candidates) || 'pg_dump';
+ const chosen = candidates.find(c => c.binary === binary);
+ const satisfies = !Number.isFinite(serverMajor) || !chosen || chosen.major >= serverMajor;
+ return { binary, satisfies };
+}
+
+/**
+ * The full pg_dump-binary decision shared by every consumer:
+ * - an explicit PORTOS_PGDUMP override always wins — the escape hatch must
+ * work even when version detection failed (its main use case);
+ * - else, when we know the server version, auto-select a binary whose major
+ * is >= it (resolvePgDump scans Homebrew kegs / Postgres.app);
+ * - else keep the prior behavior (bare `pg_dump` off PATH) without paying for
+ * discovery I/O we couldn't act on.
+ *
+ * `satisfies` is false only when a known server version has no new-enough
+ * installed binary — the caller can warn before the dump fails with a clear
+ * "server version mismatch".
+ *
+ * @param {number|null} serverMajor - server's PG major (null/NaN = unknown)
+ * @returns {Promise<{binary: string, satisfies: boolean}>}
+ */
+export async function resolvePgDumpBinary(serverMajor) {
+ if (process.env.PORTOS_PGDUMP) {
+ // user forced it; the stderr classifier still catches a too-old pick
+ return { binary: process.env.PORTOS_PGDUMP, satisfies: true };
+ }
+ if (Number.isFinite(serverMajor)) {
+ return resolvePgDump(serverMajor);
+ }
+ return { binary: 'pg_dump', satisfies: true };
+}
diff --git a/server/lib/pgTools.test.js b/server/lib/pgTools.test.js
new file mode 100644
index 0000000000..1263371b5a
--- /dev/null
+++ b/server/lib/pgTools.test.js
@@ -0,0 +1,172 @@
+/**
+ * Unit tests for the shared pg_dump resolver (server/lib/pgTools.js).
+ *
+ * - pickPgDump — the pure closest-major selection (server-version-aware).
+ * - discoverPgDumpCandidates — enumerates PATH + Homebrew/Postgres.app kegs and
+ * probes each binary's `--version`.
+ * - resolvePgDump — discovery + pick + the `satisfies` verdict.
+ * - resolvePgDumpBinary — the full override-or-auto decision both consumers
+ * (backup.js, routes/database.js) share: PORTOS_PGDUMP wins, else auto-select
+ * when the server version is known, else bare `pg_dump`.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Mock readdir (keg enumeration) and execFileAsync (version probe) so discovery
+// runs against a controlled filesystem/version map instead of the host.
+vi.mock('fs/promises', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, readdir: vi.fn(async () => []) };
+});
+vi.mock('./fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, execFileAsync: vi.fn(async () => ({ stdout: '' })) };
+});
+
+import { readdir } from 'fs/promises';
+import { execFileAsync } from './fileUtils.js';
+import {
+ pickPgDump,
+ discoverPgDumpCandidates,
+ resolvePgDump,
+ resolvePgDumpBinary,
+} from './pgTools.js';
+
+describe('pickPgDump', () => {
+ const c = (major, binary = `pg_dump@${major}`) => ({ binary, major });
+
+ it('returns null when no candidates were discovered', () => {
+ expect(pickPgDump(17, [])).toBeNull();
+ expect(pickPgDump(17, undefined)).toBeNull();
+ });
+
+ it('picks the exact-major binary when one is installed', () => {
+ const chosen = pickPgDump(17, [c(15), c(17), c(16)]);
+ expect(chosen).toBe('pg_dump@17');
+ });
+
+ it('picks the closest binary that is >= the server (newer is fine, never older)', () => {
+ // server 16: 15 is too old, choose 17 (smallest qualifying), not 18.
+ expect(pickPgDump(16, [c(15), c(17), c(18)])).toBe('pg_dump@17');
+ });
+
+ it('falls back to the newest available when nothing is new enough (forces a clear mismatch error)', () => {
+ // This is the reported bug: server 17, only pg_dump 15 installed.
+ expect(pickPgDump(17, [c(15)])).toBe('pg_dump@15');
+ expect(pickPgDump(17, [c(14), c(15)])).toBe('pg_dump@15');
+ });
+
+ it('trusts the first (PATH) candidate when the server version is unknown', () => {
+ expect(pickPgDump(null, [c(15, 'pg_dump'), c(17)])).toBe('pg_dump');
+ expect(pickPgDump(NaN, [c(15, 'pg_dump'), c(17)])).toBe('pg_dump');
+ });
+});
+
+describe('discoverPgDumpCandidates', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readdir.mockResolvedValue([]);
+ });
+
+ it('always probes the bare PATH pg_dump and filters out non-runnable binaries', async () => {
+ // No kegs on disk; only PATH pg_dump exists at major 16.
+ execFileAsync.mockImplementation(async (binary) =>
+ binary === 'pg_dump' ? { stdout: 'pg_dump (PostgreSQL) 16.4 (Homebrew)' } : { stdout: '' }
+ );
+ const candidates = await discoverPgDumpCandidates();
+ expect(candidates).toEqual([{ binary: 'pg_dump', major: 16 }]);
+ });
+
+ it('enumerates Homebrew kegs and keeps PATH ahead of them (priority order)', async () => {
+ // /opt/homebrew/opt has postgresql@15 and postgresql@17 kegs.
+ readdir.mockImplementation(async (dir) =>
+ dir === '/opt/homebrew/opt' ? ['postgresql@15', 'postgresql@17', 'somethingelse'] : []
+ );
+ const versions = {
+ 'pg_dump': '15.10',
+ '/opt/homebrew/opt/postgresql@15/bin/pg_dump': '15.10',
+ '/opt/homebrew/opt/postgresql@17/bin/pg_dump': '17.2',
+ };
+ execFileAsync.mockImplementation(async (binary) => ({
+ stdout: versions[binary] ? `pg_dump (PostgreSQL) ${versions[binary]}` : '',
+ }));
+ const candidates = await discoverPgDumpCandidates();
+ // PATH binary first, then the kegs; the non-postgresql entry is ignored.
+ expect(candidates[0]).toEqual({ binary: 'pg_dump', major: 15 });
+ expect(candidates.map(c => c.binary)).toContain('/opt/homebrew/opt/postgresql@17/bin/pg_dump');
+ expect(candidates.find(c => c.binary.includes('postgresql@17')).major).toBe(17);
+ });
+});
+
+describe('resolvePgDump', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readdir.mockResolvedValue([]);
+ });
+
+ it('selects a satisfying binary and reports satisfies=true', async () => {
+ readdir.mockImplementation(async (dir) =>
+ dir === '/opt/homebrew/opt' ? ['postgresql@17'] : []
+ );
+ const versions = {
+ 'pg_dump': '15.10',
+ '/opt/homebrew/opt/postgresql@17/bin/pg_dump': '17.2',
+ };
+ execFileAsync.mockImplementation(async (binary) => ({
+ stdout: versions[binary] ? `pg_dump (PostgreSQL) ${versions[binary]}` : '',
+ }));
+ const { binary, satisfies } = await resolvePgDump(17);
+ expect(binary).toBe('/opt/homebrew/opt/postgresql@17/bin/pg_dump');
+ expect(satisfies).toBe(true);
+ });
+
+ it('reports satisfies=false when nothing installed is new enough', async () => {
+ // Only an old PATH pg_dump 15 against a server 17.
+ execFileAsync.mockImplementation(async (binary) =>
+ binary === 'pg_dump' ? { stdout: 'pg_dump (PostgreSQL) 15.10' } : { stdout: '' }
+ );
+ const { binary, satisfies } = await resolvePgDump(17);
+ expect(binary).toBe('pg_dump');
+ expect(satisfies).toBe(false);
+ });
+});
+
+describe('resolvePgDumpBinary', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readdir.mockResolvedValue([]);
+ });
+ afterEach(() => {
+ delete process.env.PORTOS_PGDUMP;
+ });
+
+ it('honors the PORTOS_PGDUMP override outright, even when the server version is known', async () => {
+ process.env.PORTOS_PGDUMP = '/custom/bin/pg_dump';
+ const result = await resolvePgDumpBinary(17);
+ expect(result).toEqual({ binary: '/custom/bin/pg_dump', satisfies: true });
+ // Override short-circuits before discovery — no version probing.
+ expect(execFileAsync).not.toHaveBeenCalled();
+ });
+
+ it('honors the PORTOS_PGDUMP override even when the server version is unknown', async () => {
+ process.env.PORTOS_PGDUMP = '/custom/bin/pg_dump';
+ const result = await resolvePgDumpBinary(null);
+ expect(result).toEqual({ binary: '/custom/bin/pg_dump', satisfies: true });
+ });
+
+ it('auto-selects via resolvePgDump when the server version is known and no override is set', async () => {
+ execFileAsync.mockImplementation(async (binary) =>
+ binary === 'pg_dump' ? { stdout: 'pg_dump (PostgreSQL) 17.2' } : { stdout: '' }
+ );
+ const result = await resolvePgDumpBinary(17);
+ expect(result.binary).toBe('pg_dump');
+ expect(result.satisfies).toBe(true);
+ });
+
+ it('falls back to bare pg_dump (no discovery) when the server version is unknown', async () => {
+ const result = await resolvePgDumpBinary(null);
+ expect(result).toEqual({ binary: 'pg_dump', satisfies: true });
+ // Unknown version + no override ⇒ skip discovery I/O entirely.
+ expect(execFileAsync).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/database.js b/server/routes/database.js
index b821f6ffe5..511919ca11 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -5,6 +5,7 @@ import { join } from 'path';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { checkHealth, query } from '../lib/db.js';
import { PATHS } from '../lib/fileUtils.js';
+import { resolvePgDumpBinary } from '../lib/pgTools.js';
const rootDir = PATHS.root;
const dbScript = join(rootDir, 'scripts', 'db.sh');
@@ -289,6 +290,23 @@ const pgEnv = (port) => ({
PGDATABASE: pgDb
});
+/**
+ * Read a specific backend's PostgreSQL major version by probing it on its own
+ * port (native 5432 / Docker 5561 can run different majors, so the connection
+ * pool's version isn't authoritative for the export target). `server_version_num`
+ * is an integer like 170010 → major = floor(n / 10000). Returns null when the
+ * probe fails — the shared resolver then falls back to bare `pg_dump`.
+ */
+async function probeServerMajor(port, env) {
+ const result = await runCmd('psql', [
+ '-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,
+ '-tAc', 'SHOW server_version_num'
+ ], 5_000, env);
+ const num = parseInt(result.stdout.trim(), 10);
+ if (!Number.isFinite(num)) return null;
+ return Math.floor(num / 10000);
+}
+
// POST /api/database/sync — copy data from active to non-active backend
// Since native (5432) and Docker (5561) use different ports, both can be
// running simultaneously. No need to stop the active backend.
@@ -468,8 +486,16 @@ router.post('/export', asyncHandler(async (req, res) => {
const dumpDir = join(rootDir, 'data', 'db-dumps');
await runCmd('mkdir', ['-p', dumpDir], 5_000);
const dumpFile = join(dumpDir, `portos-${backend}-${label}.sql`);
- // Use -f flag to write output directly — no shell redirect needed, avoids shell injection
- const pgDumpBin = pg17Bin ? `${pg17Bin}/pg_dump` : 'pg_dump';
+ // Use -f flag to write output directly — no shell redirect needed, avoids shell injection.
+ // Resolve a pg_dump whose major is >= the TARGET backend's server (probed
+ // against this port, not the pool's 5432) via the shared resolver, which
+ // also honors PORTOS_PGDUMP. Falls back to bare `pg_dump` when the probe
+ // can't determine the version. (Shared with backup.js — server/lib/pgTools.js.)
+ const targetMajor = await probeServerMajor(port, env);
+ const { binary: pgDumpBin, satisfies } = await resolvePgDumpBinary(targetMajor);
+ if (!satisfies) {
+ console.warn(`🗄️ No installed pg_dump satisfies ${backend} server major ${targetMajor} (using ${pgDumpBin})`);
+ }
const result = await runCmd(pgDumpBin, [
'-h', 'localhost', '-p', String(port), '-U', pgUser, '-d', pgDb,
'--no-owner', '--no-privileges', '--if-exists', '--clean', '-f', dumpFile
diff --git a/server/services/backup.js b/server/services/backup.js
index df22bc0ea3..15395e500e 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -10,9 +10,10 @@ import { spawn } from 'child_process';
import { access, readdir, readFile, stat, unlink, writeFile } from 'fs/promises';
import { hostname } from 'os';
import { join, resolve, relative, isAbsolute } from 'path';
-import { PATHS, ensureDir, execFileAsync, readJSONFile, sha256File } from '../lib/fileUtils.js';
+import { PATHS, ensureDir, readJSONFile, sha256File } from '../lib/fileUtils.js';
import { getEvent } from './eventScheduler.js';
import { checkHealth, getServerMajorVersion } from '../lib/db.js';
+import { resolvePgDumpBinary } from '../lib/pgTools.js';
import { getBackendName } from './memoryBackend.js';
import { emitErrorEvent, ServerError } from '../lib/errorHandler.js';
import { getIo } from './socket.js';
@@ -238,93 +239,6 @@ export async function runBackup(destPath, io = null, { excludePaths = [], disabl
return complete({ snapshotId, filesChanged: changedFiles.length, status, lastRun, manifest, pgBackup: pgResult });
}
-/**
- * Choose which discovered pg_dump binary to run, given the server's major
- * version. pg_dump REFUSES to dump a server newer than itself ("server version
- * mismatch"), but a newer pg_dump dumps an older server fine — so the rule is:
- * pick the closest binary whose major is >= the server's.
- *
- * Pure + exported for unit testing (the IO-bound discovery lives in
- * resolvePgDump, which feeds this the runnable candidates it found).
- *
- * @param {number|null} serverMajor - server's PG major version (null = unknown)
- * @param {Array<{binary: string, major: number}>} candidates - runnable pg_dumps
- * @returns {string|null} chosen binary path, or null if none discovered
- */
-export function pickPgDump(serverMajor, candidates) {
- if (!candidates?.length) return null;
- // Unknown server version: keep prior behavior — trust the first (PATH) entry.
- if (!Number.isFinite(serverMajor)) return candidates[0].binary;
- // Prefer the smallest major that still satisfies >= server (closest match,
- // avoids reaching for a wildly newer keg when an exact one is installed).
- const viable = candidates.filter(c => c.major >= serverMajor).sort((a, b) => a.major - b.major);
- if (viable.length) return viable[0].binary;
- // Nothing is new enough. Return the newest we have so the resulting error is a
- // clear "still too old" instead of an arbitrary pick — and so the version
- // detection in dumpPostgres can flag it as version_mismatch.
- return [...candidates].sort((a, b) => b.major - a.major)[0].binary;
-}
-
-/**
- * Read a pg_dump binary's major version, or null if it isn't runnable.
- * `pg_dump --version` prints e.g. "pg_dump (PostgreSQL) 17.10 (Homebrew)".
- */
-async function pgDumpMajor(binary) {
- const { stdout } = await execFileAsync(binary, ['--version']).catch(() => ({ stdout: '' }));
- const m = stdout.match(/PostgreSQL\)\s+(\d+)/i);
- return m ? parseInt(m[1], 10) : null;
-}
-
-/**
- * Enumerate candidate pg_dump locations: an explicit override, the bare PATH
- * binary, then versioned Homebrew kegs and Postgres.app bundles (where multiple
- * majors coexist and PATH order silently picks the wrong one).
- */
-async function discoverPgDumpCandidates() {
- // Note: the PORTOS_PGDUMP override is NOT a candidate here — dumpPostgres
- // honors it outright before discovery runs, so it's never subject to the
- // closest-major auto-selection below.
- const paths = ['pg_dump']; // whatever PATH resolves — preserves the old default
- const kegDirs = ['/opt/homebrew/opt', '/usr/local/opt', '/Applications/Postgres.app/Contents/Versions'];
- for (const dir of kegDirs) {
- const entries = await readdir(dir).catch(() => []);
- for (const entry of entries) {
- if (dir.endsWith('Versions') || entry.startsWith('postgresql')) {
- paths.push(join(dir, entry, 'bin', 'pg_dump'));
- }
- }
- }
- // Probe versions concurrently (each `pg_dump --version` is an independent
- // spawn); [...new Set(paths)] de-dups while preserving priority order, which
- // Promise.all keeps — so pickPgDump still sees PATH > kegs.
- const probed = await Promise.all(
- [...new Set(paths)].map(async (binary) => ({ binary, major: await pgDumpMajor(binary) }))
- );
- return probed.filter(c => c.major != null);
-}
-
-/**
- * Auto-select a pg_dump binary for a server at `serverMajor` by discovering
- * installed binaries and picking the closest whose major is >= the server's.
- * Returns the chosen path and whether it satisfies the server's version
- * (false ⇒ the dump will fail with a version mismatch and there's nothing
- * newer installed).
- *
- * The explicit `PORTOS_PGDUMP` override is NOT handled here — the caller
- * (`dumpPostgres`) honors it before reaching this resolver, so the override
- * works even when the server version is unknown and this resolver is skipped.
- *
- * @param {number} serverMajor - known server major (caller guards on isFinite)
- * @returns {Promise<{binary: string, satisfies: boolean}>}
- */
-async function resolvePgDump(serverMajor) {
- const candidates = await discoverPgDumpCandidates();
- const binary = pickPgDump(serverMajor, candidates) || 'pg_dump';
- const chosen = candidates.find(c => c.binary === binary);
- const satisfies = !Number.isFinite(serverMajor) || !chosen || chosen.major >= serverMajor;
- return { binary, satisfies };
-}
-
/**
* Run pg_dump to create a PostgreSQL backup alongside the rsync snapshot.
* Returns an explicit status so the caller can distinguish the benign file
@@ -373,23 +287,10 @@ export async function dumpPostgres(outputPath) {
// PATH) the bare `pg_dump` is often the wrong one, so select a matching binary
// instead of trusting PATH order.
const serverMajor = await getServerMajorVersion();
- // Choose the pg_dump binary:
- // - an explicit PORTOS_PGDUMP override always wins — the escape hatch must
- // work even when version detection failed (its main use case);
- // - else, when we know the server version, auto-select a binary whose major
- // is >= it (resolvePgDump scans Homebrew kegs / Postgres.app);
- // - else keep the prior behavior (bare `pg_dump` off PATH) without paying
- // for discovery I/O we couldn't act on.
- let pgDumpBin, satisfies;
- if (process.env.PORTOS_PGDUMP) {
- pgDumpBin = process.env.PORTOS_PGDUMP;
- satisfies = true; // user forced it; the stderr classifier still catches a too-old pick
- } else if (Number.isFinite(serverMajor)) {
- ({ binary: pgDumpBin, satisfies } = await resolvePgDump(serverMajor));
- } else {
- pgDumpBin = 'pg_dump';
- satisfies = true;
- }
+ // Shared resolver (server/lib/pgTools.js): PORTOS_PGDUMP override wins, else
+ // auto-select a binary whose major is >= the server when we know the version,
+ // else fall back to bare `pg_dump` off PATH.
+ const { binary: pgDumpBin, satisfies } = await resolvePgDumpBinary(serverMajor);
if (!satisfies) {
console.warn(`⚠️ No installed pg_dump satisfies server major ${serverMajor} (using ${pgDumpBin})`);
}
diff --git a/server/services/backup.test.js b/server/services/backup.test.js
index 914e3cdb4b..6ed32949ba 100644
--- a/server/services/backup.test.js
+++ b/server/services/backup.test.js
@@ -48,7 +48,7 @@ vi.mock('fs/promises', async (importOriginal) => {
import { checkHealth, getServerMajorVersion } from '../lib/db.js';
import { getBackendName } from './memoryBackend.js';
import * as fs from 'fs/promises';
-import { DEFAULT_EXCLUDES, computeEffectiveExcludes, pickPgDump, listSnapshots } from './backup.js';
+import { DEFAULT_EXCLUDES, computeEffectiveExcludes, listSnapshots } from './backup.js';
// Helper: build a fake child process whose close/error we can drive.
function fakeProc() {
@@ -170,36 +170,6 @@ describe('computeEffectiveExcludes', () => {
});
});
-describe('pickPgDump', () => {
- const c = (major, binary = `pg_dump@${major}`) => ({ binary, major });
-
- it('returns null when no candidates were discovered', () => {
- expect(pickPgDump(17, [])).toBeNull();
- expect(pickPgDump(17, undefined)).toBeNull();
- });
-
- it('picks the exact-major binary when one is installed', () => {
- const chosen = pickPgDump(17, [c(15), c(17), c(16)]);
- expect(chosen).toBe('pg_dump@17');
- });
-
- it('picks the closest binary that is >= the server (newer is fine, never older)', () => {
- // server 16: 15 is too old, choose 17 (smallest qualifying), not 18.
- expect(pickPgDump(16, [c(15), c(17), c(18)])).toBe('pg_dump@17');
- });
-
- it('falls back to the newest available when nothing is new enough (forces a clear mismatch error)', () => {
- // This is the reported bug: server 17, only pg_dump 15 installed.
- expect(pickPgDump(17, [c(15)])).toBe('pg_dump@15');
- expect(pickPgDump(17, [c(14), c(15)])).toBe('pg_dump@15');
- });
-
- it('trusts the first (PATH) candidate when the server version is unknown', () => {
- expect(pickPgDump(null, [c(15, 'pg_dump'), c(17)])).toBe('pg_dump');
- expect(pickPgDump(NaN, [c(15, 'pg_dump'), c(17)])).toBe('pg_dump');
- });
-});
-
describe('listSnapshots', () => {
beforeEach(() => vi.clearAllMocks());
const dirent = (name, isDir) => ({ name, isDirectory: () => isDir });