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
test: keep a timed-out database restore case from overlapping the next (#10272)
Adam Eivydefbb1b6fa3d
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.mdindex 58055530cf..d4dec67ba4 100644--- a/docs/CONTRIBUTING.md+++ b/docs/CONTRIBUTING.md@@ -149,6 +149,13 @@ npm run setup:db:testnpm run test:db```+For release validation, run `npm run test:db` after the server and client+suites finish rather than alongside them. A concurrent run is supported —+the database restore suite drains a timed-out case before the next one touches+`portos_test` — but its per-case budgets assume an+unloaded machine, so a concurrent run can time out cases a sequential run+passes.+For server watch mode, run this alternative from the repository root:```bashdiff --git a/scripts/backupDbCaseBoundary.test.js b/scripts/backupDbCaseBoundary.test.jsnew file mode 100644index 0000000000..7bece7bfba--- /dev/null+++ b/scripts/backupDbCaseBoundary.test.js@@ -0,0 +1,89 @@+import { expect, it } from 'vitest';+import { spawnSync } from 'node:child_process';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { createVitestTempFixture } from './lib/vitestTempRootFixture.js';++const ownTestBodiesUrl = new URL('../server/lib/mockPathsDataRoot.js', import.meta.url).href;++// Pins the regression uniquely (#10272): a case that TIMES OUT while it is+// between restores — after one settled, before its next one starts — must not+// overlap the following case. Draining only in-flight restore promises (the+// former server/services/backup.db.test.js lifecycle) finds nothing pending at+// that moment and lets the next case in; owning the whole body does not. The+// timed-out body is held at that gap deterministically: it resumes only when+// the next case's body releases it, or on a fallback timer when that body is+// (correctly) still gated.+it('keeps a timed-out case between restores from overlapping the next case', () => {+ const host = mkdtempSync(join(tmpdir(), 'restore-boundary-'));+ try {+ const fixture = join(host, 'fixture');+ const resultsPath = join(fixture, 'results.json');+ const { args, options } = createVitestTempFixture(host, 'server', '');+ writeFileSync(join(fixture, 'boundary.test.js'), `+ import { afterAll, beforeEach, describe, it as vitestIt } from 'vitest';+ import { writeFileSync } from 'node:fs';+ import { ownTestBodies } from ${JSON.stringify(ownTestBodiesUrl)};++ const results = {};+ afterAll(() => writeFileSync(${JSON.stringify(resultsPath)}, JSON.stringify(results)));+ const wait = ms => new Promise(resolve => setTimeout(resolve, ms));++ function lifecycleCases(label, caseIt, track = work => work) {+ const state = { settled: false, restoreActive: false, overlapped: false };+ let release;+ const released = new Promise(resolve => { release = resolve; });+ const restore = () => track((async () => {+ state.restoreActive = true;+ await wait(20);+ state.restoreActive = false;+ })());+ caseIt('times out between restores', async ({ signal }) => {+ await restore();+ if (!signal.aborted) await new Promise(resolve => signal.addEventListener('abort', resolve, { once: true }));+ await Promise.race([released, wait(300)]);+ await restore();+ state.settled = true;+ }, 50);+ caseIt('next case', async () => {+ results[label] = { previousSettledAtStart: state.settled };+ release();+ for (let i = 0; i < 10; i += 1) {+ if (state.restoreActive) state.overlapped = true;+ await wait(10);+ }+ results[label].overlapped = state.overlapped;+ });+ }++ describe('restore-promise drain', () => {+ const pendingRestores = new Set();+ const track = async pending => {+ pendingRestores.add(pending);+ try { return await pending; } finally { pendingRestores.delete(pending); }+ };+ beforeEach(() => Promise.all([...pendingRestores]));+ lifecycleCases('restoreSet', vitestIt, track);+ });++ describe('owned body drain', () => {+ const owned = ownTestBodies(vitestIt);+ beforeEach(() => owned.drain());+ lifecycleCases('owned', owned.it);+ });+ `);+ const result = spawnSync(process.execPath, args, options);+ const output = `${result.stdout}\n${result.stderr}`;+ expect(result.error).toBeUndefined();+ expect(result.status, output).toBe(1);+ expect(output.match(/Test timed out in 50ms/g), output).toHaveLength(2);+ const results = JSON.parse(readFileSync(resultsPath, 'utf8'));+ // Negative control: the restore-only drain admits the next case early.+ expect(results.restoreSet).toEqual({ previousSettledAtStart: false, overlapped: true });+ expect(results.owned).toEqual({ previousSettledAtStart: true, overlapped: false });+ expect(output).not.toMatch(/Unhandled|Cancelled test body failed/);+ } finally {+ rmSync(host, { recursive: true, force: true });+ }+}, 25000);diff --git a/server/lib/mockPathsDataRoot.js b/server/lib/mockPathsDataRoot.jsindex 33bf1adc5c..b48c6fff19 100644--- a/server/lib/mockPathsDataRoot.js+++ b/server/lib/mockPathsDataRoot.js@@ -151,6 +151,9 @@ export async function sweepStrayTempRoots(prefix) {* fixture, and `await drain()` in teardown BEFORE removing it. A body that* failed after cancellation (vitest is no longer listening) is rethrown from* `drain()` rather than dropped; a failure vitest already reported is not.+ * A test TIMEOUT leaves its body running the same way, so a suite whose cases+ * share external state also awaits `drain()` in `beforeEach` (#10272,+ * `services/backup.db.test.js`).** const owned = ownTestBodies(vitestIt);* const it = owned.it;diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.jsindex dcb0025bce..fc7af19843 100644--- a/server/services/backup.db.test.js+++ b/server/services/backup.db.test.js@@ -1,11 +1,12 @@/** Real clean-dump restore regressions. Only guarded test databases. */-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterAll, beforeAll, beforeEach, describe, expect, it as vitestIt, vi } from 'vitest';import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { basename, join } from 'node:path';import { spawnSync } from 'node:child_process';import { checkHealth, ensureSchema, query, close, getServerMajorVersion, POOL_CONFIG } from '../lib/db.js';import { requireDbOrSkip } from '../lib/dbTestGate.js';+import { ownTestBodies } from '../lib/mockPathsDataRoot.js';import { resolvePgDumpBinary } from '../lib/pgTools.js';import { runDbMigrations } from '../scripts/run-db-migrations.js';import { listFolders } from './writersRoom/db.js';@@ -41,7 +42,13 @@ vi.mock('../scripts/run-db-migrations.js', async (importOriginal) => {// Load the service before timing restore assertions, as other integration// suites do. A cold module graph is setup, not database replay time.const { restorePostgres } = await import('./backup.js');-const pendingRestores = new Set();+// Vitest's timeout settles a case while its body keeps running: it can still be+// between queries and start its next restore (or arm the migration fault)+// after the following case began. Own each WHOLE body, not just its restore+// promises, so case boundaries and teardown wait for every continuation (#10272).+const owned = ownTestBodies(vitestIt);+const it = owned.it;+let fixtureSetup;const feedSequenceValues = async () => Object.fromEntries((await query('SELECT sequencename, last_value::text AS v FROM pg_sequences WHERE sequencename = ANY($1::text[])',@@ -63,9 +70,12 @@ const childEnv = { ...process.env, PGPASSWORD: POOL_CONFIG.password };const DUMP_COMPLETE = '\n--\n-- PostgreSQL database dump complete';afterAll(async () => {- // Vitest timing out an assertion does not cancel the real restore. Drain it- // before cleanup queries, which otherwise race its maintenance fence.- await Promise.allSettled([...pendingRestores]);+ // Vitest timing out a case or hook does not cancel its real restore or+ // queries. Drain them before cleanup queries, which otherwise race the+ // restore's maintenance fence; a late body failure is rethrown afterwards.+ await Promise.allSettled([fixtureSetup]);+ const drained = owned.drain();+ await drained.catch(() => {});runDbMigrationsFault.next = null;try {if (ready) {@@ -86,19 +96,11 @@ afterAll(async () => {dataRoot.path && rm(dataRoot.path, { recursive: true, force: true }),]);}+ await drained;});-async function trackRestore(pending) {- pendingRestores.add(pending);- try {- return await pending;- } finally {- pendingRestores.delete(pending);- }-}-function restore(dryRun = false, snapshotId = 'old-schema') {- return trackRestore(restorePostgres(dest, snapshotId, { source: 'fixture-source', dryRun }));+ return restorePostgres(dest, snapshotId, { source: 'fixture-source', dryRun });}describe.skipIf(!ready)('restore older database schema', () => {@@ -106,16 +108,24 @@ describe.skipIf(!ready)('restore older database schema', () => {let feedBefore;const folder = { id: folderId, name: 'Recovered folder' };- // A timed-out test keeps running. Gate every following case before it can- // query the shared database; a failed drain hook skips that case's body.+ // A timed-out test keeps running. Gate every following case on the previous+ // body's full settlement before it can query the shared database or arm the+ // fault; a failed or timed-out drain hook skips that case's body, and a body+ // that failed after its timeout is reported here rather than dropped.beforeEach(async () => {- await Promise.all([...pendingRestores]);- runDbMigrationsFault.next = null;+ try {+ await owned.drain();+ } finally {+ runDbMigrationsFault.next = null;+ }});// Prepare the shared snapshot in a hook so setup failures stop dependent// cases and the first test's budget measures restore and its assertions.- beforeAll(async () => {+ // Teardown drains it too: a timed-out hook keeps running like a case does.+ beforeAll(() => (fixtureSetup = prepareFixture()));++ async function prepareFixture() {await ensureSchema({ force: true });await runDbMigrations();appliedBefore = await query('SELECT id, applied_at FROM schema_migrations WHERE id <> $1 ORDER BY id', [pendingMigration]);@@ -149,7 +159,7 @@ describe.skipIf(!ready)('restore older database schema', () => {// Feed positions handed out after the dump must never be reissued (#8710).await query("SELECT nextval('memories_sync_feed_seq') FROM generate_series(1, 5)");feedBefore = await feedSequenceValues();- });+ }it('restores a real pre-FK dump, discards newer rows, and runs schema repair and ordered migrations', async () => {expect(await restore()).toMatchObject({ status: 'ok', dryRun: false });@@ -206,8 +216,8 @@ describe.skipIf(!ready)('restore older database schema', () => {expect(await restore(true)).toMatchObject({ status: 'failed', reason: 'restore_recovery_pending' });// Recovery owns the same maintenance fence and pool as replay. If this- // assertion times out, later cases and teardown must drain it too.- expect(await trackRestore(resumeDatabaseRestore(journal.id))).toMatchObject({ status: 'ok', outcome: 'repaired' });+ // assertion times out, later cases and teardown drain it with the body.+ expect(await resumeDatabaseRestore(journal.id)).toMatchObject({ status: 'ok', outcome: 'repaired' });expect(databaseRestoreRecovery.read()).toBeNull();// The receipt committed with the replay, inside its transaction.expect((await query('SELECT dump_sha256 FROM restore_receipts WHERE operation_id = $1', [journal.id])).rows)@@ -236,10 +246,10 @@ describe.skipIf(!ready)('restore older database schema', () => {// #8782: a legacy dump without a checksum that parses cleanly but stops early// must be refused before the full reset, or it commits an empty database.- it.each([+ for (const [name, truncate] of [['header-only', sql => sql.slice(0, sql.indexOf('SET '))],['truncated between complete statements', sql => sql.slice(0, sql.indexOf('\nCOPY ') + 1)],- ])('refuses a %s legacy dump in preview and execution and keeps existing rows', async (name, truncate) => {+ ]) it(`refuses a ${name} legacy dump in preview and execution and keeps existing rows`, async () => {const dir = join(dest, 'snapshots', 'fixture-source', `truncated-${name.split(' ')[0]}`);await mkdir(dir);await writeFile(join(dir, 'portos-db.sql'), truncate(await readFile(dumpPath, 'utf8')));