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: abort the database transaction when dump streaming fails (#7213) (#7218)
Louis Deconinckc35cd59efb79
diff --git a/server/routes/database.test.js b/server/routes/database.test.jsindex fa539caa7f..d9d0cd6a6c 100644--- a/server/routes/database.test.js+++ b/server/routes/database.test.js@@ -33,6 +33,17 @@ vi.mock('../lib/db.js', () => ({query: vi.fn(async () => ({ rows: [] })),}));+// Wrap fs so a test can substitute a dump source that fails mid-stream — the+// mid-import read error the abort path exists for. Everything else delegates+// to the real module (the suite writes real temp dumps).+vi.mock('fs', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ createReadStream: vi.fn(actual.createReadStream),+ };+});+// Mock child_process.execFile + spawn at the module level.vi.mock('../lib/childProcess.js', async (importOriginal) => {const actual = await importOriginal();@@ -45,8 +56,8 @@ vi.mock('../lib/childProcess.js', async (importOriginal) => {import { execFile, spawn } from '../lib/childProcess.js';import { EventEmitter } from 'events';-import { PassThrough } from 'stream';-import { writeFileSync, mkdtempSync, readFileSync } from 'fs';+import { PassThrough, Readable } from 'stream';+import { writeFileSync, mkdtempSync, readFileSync, createReadStream } from 'fs';import { tmpdir } from 'os';import { join as pathJoin } from 'path';import databaseRoutes from './database.js';@@ -111,8 +122,10 @@ describe('importDumpFile (no-shell streaming import)', () => {vi.clearAllMocks();});- // Build a fake psql child process backed by real streams.- function makeFakePsql() {+ // Build a fake psql child process backed by real streams. `closeOnKill`+ // models a terminated psql emitting 'close' asynchronously; tests that must+ // control exactly when the close lands pass false and emit it themselves.+ function makeFakePsql({ closeOnKill = true } = {}) {const child = new EventEmitter();child.stdout = new PassThrough();child.stderr = new PassThrough();@@ -123,13 +136,25 @@ describe('importDumpFile (no-shell streaming import)', () => {// Emulate psql exiting cleanly once stdin closes.child.emit('close', 0);});- child.kill = vi.fn();+ child.kill = vi.fn((signal) => {+ if (closeOnKill) process.nextTick(() => child.emit('close', null, signal));+ return true;+ });// Raw bytes piped to psql stdin, concatenated.child.__pipedBuffer = () => Buffer.concat(writes);child.__piped = (encoding = 'latin1') => Buffer.concat(writes).toString(encoding);return child;}+ // A dump source that delivers `prefix` (complete SQL statements), then fails+ // the read — the mid-import error that must abort the child, not EOF it.+ function makeFailingSource(prefix, message = 'dump read failed mid-stream') {+ return Readable.from((async function* () {+ yield prefix;+ throw new Error(message);+ })(), { encoding: 'latin1' });+ }+it('spawns psql via argv without a shell and pipes filtered dump to stdin', async () => {const child = makeFakePsql();spawn.mockReturnValue(child);@@ -222,6 +247,129 @@ describe('importDumpFile (no-shell streaming import)', () => {const result = await importDumpFile('/nonexistent/dump.sql', '5432', {});expect(result.exitCode).not.toBe(0);});++ it('aborts psql without a normal EOF when the dump read fails after a complete SQL prefix', async () => {+ // closeOnKill: false — the test owns when the child's 'close' lands, so it+ // can prove the promise stays unsettled until then.+ const child = makeFakePsql({ closeOnKill: false });+ spawn.mockReturnValue(child);+ const stdinEnd = vi.spyOn(child.stdin, 'end');+ createReadStream.mockImplementationOnce(() => makeFailingSource(+ 'DROP TABLE memories;\nINSERT INTO memories VALUES (1);\n'+ ));++ let settled = false;+ const promise = importDumpFile('/fake/dump.sql', '5561', {})+ .then((r) => { settled = true; return r; });++ // The destructive prefix reached psql's stdin, the read failed, and the+ // child was told to terminate — before the promise resolves.+ await vi.waitFor(() => {+ expect(child.__piped()).toContain('DROP TABLE memories;');+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ });++ // No end-of-script EOF: stdin.end() is what would let psql commit the+ // already-delivered statements under --single-transaction.+ expect(stdinEnd).not.toHaveBeenCalled();+ // The caller is NOT told the import finished while the child could still+ // be alive — settlement waits on the confirmed close.+ await new Promise((resolve) => setImmediate(resolve));+ expect(settled).toBe(false);++ child.emit('close', null, 'SIGTERM');+ const result = await promise;+ expect(result.exitCode).not.toBe(0);+ // The original read error is preserved in the returned diagnostic.+ expect(result.stderr).toContain('dump read failed mid-stream');+ expect(stdinEnd).not.toHaveBeenCalled();+ });++ it('escalates a stalled abort to SIGKILL and still resolves the failure bounded', async () => {+ vi.useFakeTimers();+ try {+ const child = makeFakePsql({ closeOnKill: false }); // wedged: never closes+ spawn.mockReturnValue(child);+ createReadStream.mockImplementationOnce(() => makeFailingSource(+ 'DROP TABLE memories;\n'+ ));++ const promise = importDumpFile('/fake/dump.sql', '5561', {});+ // Under fake timers the stream's internal setImmediate is faked too;+ // advancing the clock by 0 pumps it plus the generator microtasks, so+ // the yield→data→throw→error chain runs and abort() fires SIGTERM.+ await vi.advanceTimersByTimeAsync(0);+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');+ expect(child.kill).not.toHaveBeenCalledWith('SIGKILL');++ // SIGTERM grace, then SIGKILL grace — both bounds elapse with no close,+ // so the import reports failure rather than hanging the sync request.+ const result = await Promise.race([+ promise,+ vi.advanceTimersByTimeAsync(10_000).then(() => 'still pending'),+ ]);+ const signals = child.kill.mock.calls.map((c) => c[0]);+ expect(signals).toEqual(['SIGTERM', 'SIGKILL']);+ expect(result).not.toBe('still pending');+ expect(result.exitCode).not.toBe(0);+ expect(result.stderr).toContain('dump read failed mid-stream');+ } finally {+ vi.useRealTimers();+ }+ });++ it('bounds escalation when both termination signals synchronously emit errors', async () => {+ vi.useFakeTimers();+ try {+ const child = makeFakePsql({ closeOnKill: false });+ const failKill = () => {+ child.emit('error', Object.assign(new Error('kill EPERM'), { code: 'EPERM' }));+ return false;+ };+ // Two consecutive failures reproduce Node's synchronous error delivery;+ // the fallback prevents a regressed implementation overflowing the test runner.+ child.kill.mockImplementation(() => false)+ .mockImplementationOnce(failKill).mockImplementationOnce(failKill);+ spawn.mockReturnValue(child);+ const stdinEnd = vi.spyOn(child.stdin, 'end');+ createReadStream.mockImplementationOnce(() => makeFailingSource('SELECT 1;\n'));++ const promise = importDumpFile('/fake/dump.sql', '5561', {});+ await vi.advanceTimersByTimeAsync(10_000);+ const result = await promise;+ expect(child.kill.mock.calls.map(([signal]) => signal)).toEqual(['SIGTERM', 'SIGKILL']);+ expect(stdinEnd).not.toHaveBeenCalled();+ expect(result.exitCode).toBe(1);+ expect(result.stderr).toContain('dump read failed mid-stream');+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps waiting for close when the child errors mid-abort and settles once', async () => {+ const child = makeFakePsql({ closeOnKill: false });+ spawn.mockReturnValue(child);+ createReadStream.mockImplementationOnce(() => makeFailingSource(+ 'DROP TABLE memories;\n'+ ));++ const promise = importDumpFile('/fake/dump.sql', '5561', {});+ await vi.waitFor(() => expect(child.kill).toHaveBeenCalledWith('SIGTERM'));++ // A failed termination surfaces as 'error' — the child may still be+ // running, so the abort escalates instead of resolving early.+ child.emit('error', new Error('kill failed'));+ expect(child.kill).toHaveBeenCalledWith('SIGKILL');++ // The confirmed close settles the promise; a duplicate lifecycle event is+ // a no-op.+ child.emit('close', null, 'SIGKILL');+ child.emit('close', null, 'SIGKILL');+ const result = await promise;+ expect(result.exitCode).not.toBe(0);+ expect(result.stderr).toContain('dump read failed mid-stream');+ });});describe('POST /api/database/destroy', () => {diff --git a/server/services/dbAdmin.db.test.js b/server/services/dbAdmin.db.test.jsnew file mode 100644index 0000000000..32cb46507b--- /dev/null+++ b/server/services/dbAdmin.db.test.js@@ -0,0 +1,110 @@+/**+ * DB-backed coverage for the importDumpFile abort path (#7213): a dump read+ * failure after complete destructive SQL must terminate the psql child so the+ * interrupted --single-transaction rolls back — preexisting rows in the target+ * database survive.+ *+ * The psql child is REAL — the spawn spy delegates to the real process.+ * Only the dump source is synthetic: createReadStream is wrapped so the test can substitute a Readable+ * that delivers a complete destructive prefix and then fails the read. Runs+ * only under `npm run test:db` against the throwaway portos_test database.+ */+import { afterAll, describe, expect, it, vi } from 'vitest';+import { Readable } from 'stream';+import { createReadStream } from 'fs';+import { spawn, spawnSync } from '../lib/childProcess.js';+import { checkHealth, close, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';++vi.mock('fs', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, createReadStream: vi.fn(actual.createReadStream) };+});++vi.mock('../lib/childProcess.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, spawn: vi.fn(actual.spawn) };+});++import { importDumpFile } from './dbAdmin.js';++const TABLE = 'import_abort_probe';+const PORT = process.env.PGPORT || '5432';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((error) => ({ connected: false, error: error?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else if (spawnSync('psql', ['--version']).status !== 0) {+ // The import path drives the real psql client binary — without it there is+ // nothing to abort and nothing to prove.+ skipReason = 'psql client binary not on PATH';+ } else {+ dbReady = true;+ }+}+const runDb = requireDbOrSkip('services/dbAdmin.db.test', dbReady, skipReason);++afterAll(async () => {+ if (dbReady) {+ await query(`DROP TABLE IF EXISTS ${TABLE}`).catch(() => {});+ await close();+ }+});++describe.skipIf(!runDb)('importDumpFile abort rolls back the interrupted import (#7213)', () => {+ it('preserves preexisting target rows when the dump read fails mid-import', async () => {+ // The target's pre-sync "recovery copy": a table with a row the dump would+ // destroy and repopulate.+ await query(`DROP TABLE IF EXISTS ${TABLE}`);+ await query(`CREATE TABLE ${TABLE} (id int)`);+ await query(`INSERT INTO ${TABLE} VALUES (1)`);++ // Wait for psql to acknowledge execution, so slow startup cannot turn this+ // into a passing test that killed the child before any destructive SQL ran.+ const marker = 'IMPORT_ABORT_PREFIX_EXECUTED';+ let acknowledge;+ const prefixExecuted = new Promise((resolve) => { acknowledge = resolve; });+ let markerSeen = false;+ createReadStream.mockImplementationOnce(() => Readable.from((async function* () {+ yield `DROP TABLE IF EXISTS ${TABLE};\n` ++ `CREATE TABLE ${TABLE} (id int);\n` ++ `INSERT INTO ${TABLE} VALUES (2);\n` ++ `\\echo ${marker}\n`;+ let deadline;+ try {+ await Promise.race([+ prefixExecuted,+ new Promise((_, reject) => {+ deadline = setTimeout(() => reject(new Error('psql did not execute prefix')), 5_000);+ }),+ ]);+ } finally {+ clearTimeout(deadline);+ }+ throw new Error('simulated dump read failure');+ })(), { encoding: 'latin1' }));++ const importing = importDumpFile('/unused/dump.sql', PORT, { ...process.env }, 15_000);+ const child = spawn.mock.results.at(-1).value;+ let output = '';+ child.stdout.on('data', (chunk) => {+ output += chunk.toString();+ if (output.includes(marker)) {+ markerSeen = true;+ acknowledge();+ }+ });+ const result = await importing;++ expect(markerSeen).toBe(true);+ expect(result.exitCode).not.toBe(0);+ expect(result.stderr).toContain('simulated dump read failure');++ // The DROP + INSERT prefix never committed — the preexisting row survived.+ const rows = await query(`SELECT id FROM ${TABLE} ORDER BY id`);+ expect(rows.rows.map((r) => r.id)).toEqual([1]);+ });+});diff --git a/server/services/dbAdmin.js b/server/services/dbAdmin.jsindex b6b6b46abf..4637c4b18a 100644--- a/server/services/dbAdmin.js+++ b/server/services/dbAdmin.js@@ -309,6 +309,13 @@ const pgEnv = (port) => ({const PG17_ONLY_DIRECTIVES = [/^\\restrict /, /^\\unrestrict /, /^SET transaction_timeout/];export const isPg17OnlyDirective = (line) => PG17_ONLY_DIRECTIVES.some((re) => re.test(line));+// Abort escalation bounds for importDumpFile's read-failure path: after+// SIGTERM, wait this long for the child's 'close' before escalating to+// SIGKILL, then this much longer before reporting failure without a confirmed+// close. The final bound reports failure without claiming termination was confirmed.+const ABORT_TERM_GRACE_MS = 2_000;+const ABORT_KILL_GRACE_MS = 2_000;+/*** Import a pg_dump SQL file into the target database WITHOUT invoking a shell.*@@ -324,6 +331,11 @@ export const isPg17OnlyDirective = (line) => PG17_ONLY_DIRECTIVES.some((re) => r* async boundary resolves rather than throws — an uncaught throw here would* crash the Node process (there is no next(err) to bubble to). Returns the same* { stdout, stderr, exitCode } shape as runCmd().+ *+ * A dump READ failure leaves the import half-delivered, so the child is+ * aborted (SIGTERM, escalating to SIGKILL) WITHOUT the normal-EOF stdin end+ * that psql would commit as a finished --single-transaction script, and the+ * promise waits for 'close' or the bounded abort deadline (see abort()).*/export function importDumpFile(dumpFile, port, env, timeout = 120_000) {return new Promise((resolve) => {@@ -352,17 +364,36 @@ export function importDumpFile(dumpFile, port, env, timeout = 120_000) {let stderr = '';const capture = (buf, chunk) => (buf.length >= CAPTURE_LIMIT ? buf : buf + chunk);let finished = false;+ // Set once a dump read failure starts tearing the child down. While an+ // abort is in flight the promise stays unsettled — it resolves only on a+ // confirmed 'close' or when the bounded escalation gives up.+ let aborting = false;+ let abortDetail = null;+ let abortTimer = null;+ let killRequested = false;const finish = (exitCode, extraDetail) => {if (finished) return;finished = true;clearTimeout(timer);+ clearTimeout(abortTimer);src.destroy();- if (psql.stdin.writable) psql.stdin.end();+ // Only a normal completion ends stdin — that EOF is what psql reads as+ // end-of-script and commits under --single-transaction. An abort never+ // sends it, including when termination could not be confirmed.+ if (!aborting && psql.stdin.writable) psql.stdin.end();if (exitCode !== 0) {const detail = stripAnsi(stderr || stdout || extraDetail || '').replace(/\s+/g, ' ').trim();console.error(`🗄️ psql import exited ${exitCode}: ${detail}`);}- resolve({ stdout: stripAnsi(stdout), stderr: stripAnsi(stderr), exitCode });+ // Keep the triggering detail (read error, spawn failure, timeout) in the+ // diagnostic the caller surfaces — psql is usually killed before it can+ // write anything, so its stderr alone would report a bare failure.+ const stderrText = stripAnsi(stderr);+ const detailText = stripAnsi(extraDetail || '');+ const stderrOut = detailText && !stderrText.includes(detailText)+ ? [stderrText, detailText].filter(Boolean).join('\n')+ : stderrText;+ resolve({ stdout: stripAnsi(stdout), stderr: stderrOut, exitCode });};const timer = setTimeout(() => {@@ -370,10 +401,48 @@ export function importDumpFile(dumpFile, port, env, timeout = 120_000) {finish(1, `import timed out after ${timeout}ms`);}, timeout);+ // A dump read failure must NOT end stdin: end-of-script is a successful+ // run to psql, so --single-transaction would commit whatever complete+ // statements already arrived — the export's leading DROPs included+ // (scripts/db.sh --clean). Abort instead: stop pumping, leave stdin open,+ // and terminate the child so its open transaction rolls back with the+ // connection. Settlement then waits on the child's 'close' — bounded by+ // SIGTERM → SIGKILL escalation below. Even if neither signal succeeds,+ // stdin stays open so the partial prefix cannot commit on normal EOF.+ const escalateAbort = () => {+ if (finished || killRequested) return;+ // kill() can synchronously emit 'error'; arm the guard and deadline first.+ killRequested = true;+ clearTimeout(abortTimer);+ abortTimer = setTimeout(() => finish(1, abortDetail), ABORT_KILL_GRACE_MS);+ psql.kill('SIGKILL');+ };+ const abort = (detail) => {+ if (finished || aborting) return;+ aborting = true;+ abortDetail = detail;+ clearTimeout(timer); // the import timeout's bound is superseded by the abort bound+ src.destroy();+ abortTimer = setTimeout(escalateAbort, ABORT_TERM_GRACE_MS);+ psql.kill('SIGTERM');+ };+psql.stdout.on('data', (d) => { stdout = capture(stdout, d.toString()); });psql.stderr.on('data', (d) => { stderr = capture(stderr, d.toString()); });- psql.on('error', (err) => finish(1, err.message));- psql.on('close', (code) => finish(typeof code === 'number' ? code : 1));+ psql.on('error', (err) => {+ if (aborting) {+ // A failed kill during teardown — the child may still be running.+ // Escalate and keep waiting on close rather than reporting failure+ // while it can still commit.+ escalateAbort();+ return;+ }+ finish(1, err.message);+ });+ psql.on('close', (code) => {+ if (aborting) finish(1, abortDetail);+ else finish(typeof code === 'number' ? code : 1);+ });// psql may exit early (e.g. ON_ERROR_STOP) while we're still writing — the// resulting EPIPE would otherwise crash the process.psql.stdin.on('error', () => {});@@ -394,19 +463,24 @@ export function importDumpFile(dumpFile, port, env, timeout = 120_000) {pending = pending.slice(nl + 1);if (!writeLine(line)) {src.pause();- psql.stdin.once('drain', () => { src.resume(); pump(); });+ psql.stdin.once('drain', () => {+ if (finished || aborting) return;+ src.resume();+ pump();+ });return;}}};src.on('data', (chunk) => {- if (finished) return;+ if (finished || aborting) return; // a queued chunk must not pump after abortpending += chunk;pump();});- src.on('error', (err) => finish(1, err.message));+ src.on('error', (err) => abort(err.message));src.on('end', () => {+ if (finished || aborting) return; // the success EOF must never follow an abort// Flush a final line that lacked a trailing newline, then close stdin so// psql runs the script and emits 'close'.if (pending.length) { writeLine(pending); pending = ''; }diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex d6818e3eaf..f0ad00130b 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -17,6 +17,7 @@ process.env.NODE_ENV = 'test';export const DB_TEST_INCLUDE = ['services/appQuality.db.test.js','**/db.test.js',+ 'services/dbAdmin.db.test.js','services/catalogDB.test.js','services/catalogDB.facets.db.test.js','services/humanActivity.db.test.js',