From c678b67b8a8121eaf09e11c77ab4b64328979c6f Mon Sep 17 00:00:00 2001 From: Jack Herrington Date: Thu, 3 Dec 2026 08:36:56 -0800 Subject: [PATCH 1/3] fix(store-postgres): close the embedded PGlite pool so one-shot processes exit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `createPgliteStorage` creates its own PGlite pool and hands it to `createPostgresStorage` as both the main and migration pool. But `createPostgresStorage.close()` deliberately leaves a *caller-supplied* pool open — a server app (and the shared-pool test harness) owns its own `pg.Pool` lifecycle. The migration-pool local is likewise only assigned for an internally built pool, so for the embedded engine neither `.end()` ran: the PGlite instance was never closed. An un-closed PGlite leaves the Emscripten `setitimer` timers its WASM arms for Postgres transaction timeouts ref'd on the Node event loop. A long-running server never notices, but a one-shot process — the `tanstack-cms` CLI (migrate/seed/export), a seed/export script, or the packed-consumer smoke — finishes its work and then hangs forever. In CI that surfaced as the Packed Consumer job wedging until the 6-hour GitHub Actions ceiling, blocking the PR. `createPgliteStorage` owns its pool, so it now ends it when the storage closes. Scope is exact: `createPostgresStorage` is unchanged, so server pools and the deliberately-shared test VM (`testing.ts`) still stay open across `close()`. - tests/pglite-teardown.test.ts spawns a one-shot child that runs two open→write→close cycles (the real app shape) and asserts it EXITS; without the fix the child hangs and the spawn times out. - pr.yml: every PR job gets `timeout-minutes` so any future hang fails in minutes instead of burning the 6-hour default and blocking the PR. Co-Authored-By: Claude Opus 4.8 (1M context) --- .github/workflows/pr.yml | 9 +++ packages/store-postgres/src/pglite.ts | 16 ++++- .../tests/pglite-teardown.test.ts | 59 +++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 packages/store-postgres/tests/pglite-teardown.test.ts diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index e66fb6f3..bc5b5d67 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -17,6 +17,7 @@ jobs: test: name: Test runs-on: ubuntu-latest + timeout-minutes: 30 services: postgres: image: postgres:16 @@ -50,6 +51,7 @@ jobs: coverage: name: Coverage runs-on: ubuntu-latest + timeout-minutes: 30 services: postgres: image: postgres:16 @@ -148,6 +150,7 @@ jobs: e2e: name: E2E runs-on: ubuntu-latest + timeout-minutes: 25 steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -179,6 +182,7 @@ jobs: min-node: name: Minimum Node (22.13) runs-on: ubuntu-latest + timeout-minutes: 20 steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -203,6 +207,10 @@ jobs: pack: name: Packed Consumer runs-on: ubuntu-latest + # A hard ceiling so a hung consumer process (e.g. a store that never closes, + # leaving the Node event loop pinned) fails in minutes instead of running to + # the 6-hour GitHub Actions default and blocking the whole PR. + timeout-minutes: 20 steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -218,6 +226,7 @@ jobs: # the GitHub App installed on the repo it publishes from). if: github.repository == 'TanStack/cms' runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: read pull-requests: write diff --git a/packages/store-postgres/src/pglite.ts b/packages/store-postgres/src/pglite.ts index e8f668e7..ad126aac 100644 --- a/packages/store-postgres/src/pglite.ts +++ b/packages/store-postgres/src/pglite.ts @@ -124,10 +124,24 @@ export function createPgliteStorage( const pool = createPglitePool( options.dataDir ? { dataDir: options.dataDir } : {}, ) - return createPostgresStorage({ + const storage = createPostgresStorage({ pool, migrationPool: pool, acquisitionTimeoutMs: options.acquisitionTimeoutMs ?? 30_000, ...(options.prefix ? { prefix: options.prefix } : {}), }) + // `createPostgresStorage` deliberately leaves a *caller-supplied* pool open on + // `close()` — a server app (and the shared-pool test harness) owns its own + // `pg.Pool` lifecycle. Here the pool is ours: created just above and passed as + // both the main and migration pool, so we own its teardown and must end it. + // Without this the embedded PGlite instance is never closed, and the Emscripten + // `setitimer` timers its WASM arms for Postgres transaction timeouts stay + // ref'd on the Node event loop — so a one-shot process (the CLI, a seed/export + // script, the packed-consumer smoke) runs to completion but then never exits. + const closeStorage = storage.close + storage.close = async () => { + await closeStorage() + await pool.end() + } + return storage } diff --git a/packages/store-postgres/tests/pglite-teardown.test.ts b/packages/store-postgres/tests/pglite-teardown.test.ts new file mode 100644 index 00000000..83a37b93 --- /dev/null +++ b/packages/store-postgres/tests/pglite-teardown.test.ts @@ -0,0 +1,59 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +// Regression guard for the "packed consumer hangs for 6 hours" bug: an embedded +// PGlite store that runs a transactional workload (migrations + a write) and +// then `close()`s must let its process EXIT. PGlite's WASM arms Emscripten +// `setitimer` timers for Postgres transaction timeouts; those stay ref'd on the +// Node event loop unless the underlying PGlite instance is actually closed. +// `createPgliteStorage` owns its pool, so its `close()` must end it. +// +// This spawns a one-shot child so the assertion is the real thing we care about +// — the process terminating on its own — rather than an indirect handle count +// (vitest's own runtime keeps timers alive, so `getActiveResourcesInfo()` in- +// process can't distinguish the leak). If the bug returns, the child hangs and +// `execFileSync`'s timeout kills it, throwing here. +describe('createPgliteStorage process teardown', () => { + it('lets a one-shot process exit after close()', () => { + const dir = mkdtempSync(join(tmpdir(), 'pglite-teardown-')) + const pgliteSrc = fileURLToPath(new URL('../src/pglite.ts', import.meta.url)) + const script = join(dir, 'exit.mts') + // Two open→write→close cycles on the same dataDir — the shape a real app + // (and the packed-consumer smoke's runtime.mjs) exercises. One un-closed + // instance only *delays* exit; the second leaves a self-re-arming WASM timer + // that pins the loop forever, which is the true 6-hour wedge. + const idx = (t: string) => + `{ published: true, locale: 'en', slug: ${JSON.stringify(t)}, title: ${JSON.stringify(t)}, publishAt: null, unpublishAt: null, deletedAt: null }` + writeFileSync( + script, + `import { createPgliteStorage } from ${JSON.stringify(pgliteSrc)} +const dataDir = ${JSON.stringify(join(dir, 'data'))} +for (const id of ['a', 'b']) { + const s = createPgliteStorage({ dataDir }) + await s.init() + await s.putDocument( + { collection: 'post', id, doc: { title: id, published: true }, updatedAt: new Date().toISOString() }, + ${idx('t')}, + ) + await s.close() +} +console.log('exited-clean') +`, + ) + const tsx = fileURLToPath( + new URL('../../../node_modules/.bin/tsx', import.meta.url), + ) + // If close() leaves PGlite's timers armed, the child never exits; the + // timeout then kills it and execFileSync throws, failing the test. + const out = execFileSync(tsx, [script], { + timeout: 30_000, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }) + expect(out).toContain('exited-clean') + }, 40_000) +}) From 6f34871f04a63f977e3712c6ee41098bc9dedc0a Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:40:23 +0000 Subject: [PATCH 2/3] ci: apply automated fixes --- packages/store-postgres/tests/pglite-teardown.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/store-postgres/tests/pglite-teardown.test.ts b/packages/store-postgres/tests/pglite-teardown.test.ts index 83a37b93..a37e36d5 100644 --- a/packages/store-postgres/tests/pglite-teardown.test.ts +++ b/packages/store-postgres/tests/pglite-teardown.test.ts @@ -20,7 +20,9 @@ import { describe, expect, it } from 'vitest' describe('createPgliteStorage process teardown', () => { it('lets a one-shot process exit after close()', () => { const dir = mkdtempSync(join(tmpdir(), 'pglite-teardown-')) - const pgliteSrc = fileURLToPath(new URL('../src/pglite.ts', import.meta.url)) + const pgliteSrc = fileURLToPath( + new URL('../src/pglite.ts', import.meta.url), + ) const script = join(dir, 'exit.mts') // Two open→write→close cycles on the same dataDir — the shape a real app // (and the packed-consumer smoke's runtime.mjs) exercises. One un-closed From bce7574c0669da770ff5805d31083568c35c2adf Mon Sep 17 00:00:00 2001 From: Jack Herrington Date: Thu, 3 Dec 2026 09:04:52 -0800 Subject: [PATCH 3/3] fix(ci): ship PGlite assets in the packed-consumer prod build; bound smoke fetches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With the PGlite close-on-teardown fix, the packed-consumer smoke now gets past runtime.mjs and the CLI (which previously wedged) and reaches the production server boot — exposing two latent problems: 1. The generated consumer `vite.config.ts` used a bare `nitro()`, so the embedded PGlite engine got bundled and its runtime assets (pglite.data, pg_trgm.tar.gz) were dropped from `.output`. The server booted, then threw "Extension bundle not found" / ENOENT on first request and never became healthy. Mirror the documented production pattern (app/prm/vite.config.ts): externalize `@electric-sql/pglite` and pass `nitro({ traceDeps: ['@electric-sql/pglite*'] })` so Nitro traces the assets into `.output`. 2. The smoke's `fetch` calls had no timeout, so a server that accepts the connection but never responds hung `fetch` forever — turning a broken build into a silent wedge (the readiness probe never advanced past its first attempt). Every request is now bounded by an `AbortSignal.timeout`, so a broken build fails promptly instead of running to the job's time cap. Co-Authored-By: Claude Opus 4.8 (1M context) --- scripts/pack-consumer.mjs | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/scripts/pack-consumer.mjs b/scripts/pack-consumer.mjs index 7d014eb8..6e8ff613 100644 --- a/scripts/pack-consumer.mjs +++ b/scripts/pack-consumer.mjs @@ -380,7 +380,16 @@ import tailwindcss from '@tailwindcss/vite' import { createRoutes } from '@tanstack/cms-ui-react/virtual-routes' import { tanstackCms } from '@tanstack/cms-ui-react/vite' import { definition } from './src/cms.definition' -export default defineConfig({ plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro(), react()] }) +export default defineConfig({ + // Keep the embedded PGlite store external so Nitro traces its adjacent WASM / + // data / extension assets (pglite.data, pg_trgm.tar.gz) into .output. Bundling + // it drops those runtime binaries and the store can't open — the server boots + // then throws "Extension bundle not found" / ENOENT on first request. This is + // the documented production pattern for a TanStack Start app using the + // embedded engine (see app/prm/vite.config.ts). + ssr: { external: ['@electric-sql/pglite'] }, + plugins: [tanstackCms(), tailwindcss(), tanstackStart({ router: { virtualRouteConfig: createRoutes(definition) } }), nitro({ traceDeps: ['@electric-sql/pglite*'] }), react()], +}) `, ) run('pnpm', ['exec', 'vite', 'build'], app, { @@ -411,13 +420,19 @@ const server = spawn(process.execPath, ['.output/server/index.mjs'], { stdio: ['ignore', 'ignore', 'inherit'], }) const origin = `http://127.0.0.1:${port}` +// Every request is bounded: a server that boots but can't serve (e.g. a store +// that accepts the connection but never responds) would otherwise hang `fetch` +// forever — Node's fetch has no default timeout — turning a broken build into a +// silent wedge instead of a prompt failure. +const fetchT = (url, init = {}) => + fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(10_000) }) try { let ready = false for (let attempt = 0; attempt < 100; attempt++) { if (server.exitCode !== null) throw new Error('Packed production server exited before readiness') try { - if ((await fetch(origin)).ok) { + if ((await fetchT(origin, { signal: AbortSignal.timeout(3_000) })).ok) { ready = true break } @@ -425,7 +440,7 @@ try { await new Promise((resolve) => setTimeout(resolve, 300)) } assert.ok(ready, 'Packed production Start app did not become ready') - assert.equal((await fetch(`${origin}/api/cms/v1/health`)).status, 200) + assert.equal((await fetchT(`${origin}/api/cms/v1/health`)).status, 200) const input = { collection: 'post', id: 'production', @@ -433,7 +448,7 @@ try { create: true, } const write = (cookie) => - fetch(`${origin}/api/cms/v1/ops/save`, { + fetchT(`${origin}/api/cms/v1/ops/save`, { method: 'POST', headers: { 'content-type': 'application/json', @@ -445,7 +460,7 @@ try { assert.equal((await write('cms_consumer=admin')).status, 200) let automated = false for (let attempt = 0; attempt < 50; attempt++) { - const response = await fetch( + const response = await fetchT( `${origin}/api/cms/v1/ops/list?collection=post`, ) assert.equal(response.status, 200) @@ -464,7 +479,7 @@ try { automated, 'Automatic event dispatch must survive the packed production build', ) - const page = await fetch(`${origin}/post/production`) + const page = await fetchT(`${origin}/post/production`) assert.equal(page.status, 200) assert.ok((await page.text()).includes('Packed production')) console.log(