From c918f27eff8d4d1305ee572b1e8c6bb9c9942ffc Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:27:38 +0100 Subject: [PATCH 01/43] test-postgres: the package's skeleton and the PostgreSQL its tests start An empty @plexus-ms/test-postgres, with the conda:postgresql pin its own tests need and POSTGRES_MAJOR, the major they ask for, as an input of its test task. Co-Authored-By: Claude Fable 5.2 --- mise.toml | 5 ++++ packages/test-postgres/package.json | 36 ++++++++++++++++++++++++++++ packages/test-postgres/src/index.ts | 4 ++++ packages/test-postgres/tsconfig.json | 20 ++++++++++++++++ packages/test-postgres/turbo.json | 10 ++++++++ pnpm-lock.yaml | 9 +++++++ 6 files changed, 84 insertions(+) create mode 100644 packages/test-postgres/package.json create mode 100644 packages/test-postgres/src/index.ts create mode 100644 packages/test-postgres/tsconfig.json create mode 100644 packages/test-postgres/turbo.json diff --git a/mise.toml b/mise.toml index 4d7b493..622e181 100644 --- a/mise.toml +++ b/mise.toml @@ -9,6 +9,8 @@ hk = "latest" # The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates); # allow_low_downloads only waives npm's young-package heuristics. "npm:@plexus-ms/cli" = { version = "0.133.0", allow_low_downloads = true } +# The server @plexus-ms/test-postgres starts in its own tests; POSTGRES_MAJOR below names its major. +"conda:postgresql" = "18.6" [settings] # Not a version source: it lets config_roots match a project without a mise config of its own, @@ -21,6 +23,9 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co [env] _.path = ["{{config_root}}/node_modules/.bin"] +# The major the tests ask the server for: that of the conda:postgresql pin, which a wrong one fails. +# Declared in turbo.json, so a new major runs the tests again. +POSTGRES_MAJOR = "18" [tasks.dev] description = "No-op: a package repo has no development environment to start; build builds its packages and test exercises them" diff --git a/packages/test-postgres/package.json b/packages/test-postgres/package.json new file mode 100644 index 0000000..f539605 --- /dev/null +++ b/packages/test-postgres/package.json @@ -0,0 +1,36 @@ +{ + "name": "@plexus-ms/test-postgres", + "version": "0.0.0", + "description": "A throwaway PostgreSQL server for tests, from the binary on the PATH", + "license": "GPL-3.0-or-later", + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + }, + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/plexus-ms/libraries.git", + "directory": "packages/test-postgres" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org", + "access": "public" + }, + "scripts": { + "build": "tsc", + "check": "tsc --noEmit", + "test": "node --test", + "prepack": "tsc" + }, + "devDependencies": { + "@types/node": "^24.19.4", + "typescript": "catalog:" + } +} diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts new file mode 100644 index 0000000..1da056e --- /dev/null +++ b/packages/test-postgres/src/index.ts @@ -0,0 +1,4 @@ +// @plexus-ms/test-postgres: a throwaway PostgreSQL server for tests, started +// from the binary on the PATH and removed afterwards. + +export {}; diff --git a/packages/test-postgres/tsconfig.json b/packages/test-postgres/tsconfig.json new file mode 100644 index 0000000..94828e9 --- /dev/null +++ b/packages/test-postgres/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2022", + "lib": ["ES2022"], + "types": ["node"], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "outDir": "dist", + "rootDir": "src", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "strict": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true, + "noUncheckedIndexedAccess": true + }, + "include": ["src"], + "exclude": ["dist", "node_modules", "**/*.test.ts", "src/fixtures"] +} diff --git a/packages/test-postgres/turbo.json b/packages/test-postgres/turbo.json new file mode 100644 index 0000000..7860099 --- /dev/null +++ b/packages/test-postgres/turbo.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://turborepo.com/schema.json", + "extends": ["//"], + "tasks": { + "test": { + "env": ["$TURBO_EXTENDS$", "POSTGRES_MAJOR"], + "passThroughEnv": ["$TURBO_EXTENDS$", "HOME", "DOCKER_HOST", "DOCKER_CONTEXT"] + } + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d6bb691..b535c07 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -222,6 +222,15 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/test-postgres: + devDependencies: + '@types/node': + specifier: ^24.19.4 + version: 24.19.4 + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages: '@biomejs/biome@2.6.9': From 133234666f99972d09d7d07a99803d8103da1306 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:27:59 +0100 Subject: [PATCH 02/43] test-postgres: a test that starts, uses and stops a server (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/fixtures/psql.ts | 17 ++++++++++ packages/test-postgres/src/start.test.ts | 37 +++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 packages/test-postgres/src/fixtures/psql.ts create mode 100644 packages/test-postgres/src/start.test.ts diff --git a/packages/test-postgres/src/fixtures/psql.ts b/packages/test-postgres/src/fixtures/psql.ts new file mode 100644 index 0000000..51246b8 --- /dev/null +++ b/packages/test-postgres/src/fixtures/psql.ts @@ -0,0 +1,17 @@ +// What the tests share: the major they ask for and a way to ask a server +// something, with the psql on the PATH, so that the tests need no driver. +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +/** The major of the repo's PostgreSQL pin, which mise puts in POSTGRES_MAJOR. */ +export function askedMajor(): number { + const major = Number(process.env.POSTGRES_MAJOR); + if (!Number.isInteger(major)) throw new Error('POSTGRES_MAJOR names no major: run the tests through mise'); + return major; +} + +/** Runs `sql` against the database `url` names and returns psql's unaligned, tuples-only output. */ +export async function query(url: string, sql: string): Promise { + const { stdout } = await promisify(execFile)('psql', ['-X', '-At', '-v', 'ON_ERROR_STOP=1', '-d', url, '-c', sql]); + return stdout.trim(); +} diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts new file mode 100644 index 0000000..ebfa420 --- /dev/null +++ b/packages/test-postgres/src/start.test.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; +import path from 'node:path'; +import { test } from 'node:test'; +import { askedMajor, query } from './fixtures/psql.ts'; +import { startPostgres } from './index.ts'; + +test('starts a server on a loopback port that answers, and stop() takes it down with its directory', async () => { + const major = askedMajor(); + const server = await startPostgres({ major }); + let dataDirectory = ''; + try { + assert.equal(new URL(server.url).hostname, '127.0.0.1'); + assert.equal(await query(server.url, 'select 1 + 1'), '2'); + assert.equal(await query(server.url, "select current_setting('server_version_num')::int / 10000"), String(major)); + dataDirectory = await query(server.url, 'show data_directory'); + assert.ok(existsSync(dataDirectory)); + } finally { + await server.stop(); + } + assert.equal(existsSync(path.dirname(dataDirectory)), false, 'the temporary directory is removed'); + await assert.rejects(query(server.url, 'select 1'), 'the server is down'); +}); + +test('the cluster is UTF-8 with the builtin C.UTF-8 locale, the same on every machine', async () => { + const server = await startPostgres({ major: askedMajor() }); + try { + assert.equal(await query(server.url, 'show server_encoding'), 'UTF8'); + assert.equal( + await query(server.url, 'select datlocale from pg_database where datname = current_database()'), + 'C.UTF-8', + ); + assert.equal(await query(server.url, "select upper('äb')"), 'ÄB'); + } finally { + await server.stop(); + } +}); From 8f67a439625c32794d328d305d3e3993227dfdc6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:28:37 +0100 Subject: [PATCH 03/43] test-postgres: start a cluster with initdb and pg_ctl, stop and remove it Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 116 +++++++++++++++++++++++++++- 1 file changed, 115 insertions(+), 1 deletion(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 1da056e..3540b6f 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -1,4 +1,118 @@ // @plexus-ms/test-postgres: a throwaway PostgreSQL server for tests, started // from the binary on the PATH and removed afterwards. +// +// startPostgres() initialises a cluster in a new temporary directory with +// initdb, owned by the postgres role with trust authentication, UTF-8 with +// the builtin C.UTF-8 locale so that text sorts and cases alike on every +// machine, and without fsync, since the data lives for one run. It starts the +// server with pg_ctl on a free port on 127.0.0.1, its socket in that +// directory, and returns the URL of the `postgres` database. stop() shuts the +// server down at once and removes the directory. -export {}; +import { spawn } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { appendFile, mkdtemp, rm } from 'node:fs/promises'; +import { createServer } from 'node:net'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; + +export interface StartOptions { + /** The major version the server must have, as in 18. */ + major: number; +} + +export interface Postgres { + /** The URL of the server's `postgres` database, as the `postgres` role. */ + url: string; + /** Shuts the server down and removes its directory. */ + stop(): Promise; +} + +export async function startPostgres(options: StartOptions): Promise { + void options; + const bin = findInstall(); + const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); + const data = path.join(dir, 'data'); + const pgCtl = path.join(bin, 'pg_ctl'); + try { + const port = await freePort(); + await run(path.join(bin, 'initdb'), [ + '-D', + data, + '-U', + 'postgres', + '-A', + 'trust', + '--no-sync', + '-E', + 'UTF8', + '--locale=C', + '--locale-provider=builtin', + '--builtin-locale=C.UTF-8', + ]); + await appendFile( + path.join(data, 'postgresql.conf'), + configuration({ port, listen_addresses: '127.0.0.1', unix_socket_directories: dir, fsync: 'off' }), + ); + await run(pgCtl, ['-D', data, '-l', path.join(dir, 'server.log'), '-w', 'start']); + return { + url: `postgres://postgres@127.0.0.1:${port}/postgres`, + async stop() { + try { + await run(pgCtl, ['-D', data, '-m', 'immediate', '-w', 'stop']); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }, + }; + } catch (error) { + await rm(dir, { recursive: true, force: true }); + throw error; + } +} + +// The directory of the first initdb on the PATH. +function findInstall(): string { + for (const dir of (process.env.PATH ?? '').split(path.delimiter)) { + if (dir && existsSync(path.join(dir, 'initdb'))) return dir; + } + throw new Error('No initdb on the PATH'); +} + +// Lines for postgresql.conf, where a later line wins over the defaults above it. +function configuration(settings: Record): string { + return Object.entries(settings) + .map(([name, value]) => `${name} = '${String(value).replaceAll("'", "''")}'\n`) + .join(''); +} + +// A loopback port nothing listens on right now. +function freePort(): Promise { + return new Promise((resolve, reject) => { + const probe = createServer(); + probe.once('error', reject); + probe.listen(0, '127.0.0.1', () => { + const address = probe.address(); + probe.close(() => + typeof address === 'object' && address ? resolve(address.port) : reject(new Error('No free port')), + ); + }); + }); +} + +// Runs a tool to its end and rejects with its stderr when it fails. pg_ctl +// sends the server's output to the log file, so the started server holds no +// pipe of ours. +function run(file: string, args: string[]): Promise { + return new Promise((resolve, reject) => { + const child = spawn(file, args, { stdio: ['ignore', 'ignore', 'pipe'] }); + let stderr = ''; + child.stderr.on('data', (chunk) => { + stderr += chunk; + }); + child.once('error', reject); + child.once('close', (code) => + code === 0 ? resolve() : reject(new Error(`${path.basename(file)} exited with ${code}: ${stderr.trim()}`)), + ); + }); +} From 414492c9455fe99400f71464ea845539d2adf443 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:28:57 +0100 Subject: [PATCH 04/43] test-postgres: tests of a database per caller, from a template, and its drop (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/databases.test.ts | 50 ++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 packages/test-postgres/src/databases.test.ts diff --git a/packages/test-postgres/src/databases.test.ts b/packages/test-postgres/src/databases.test.ts new file mode 100644 index 0000000..334bfdb --- /dev/null +++ b/packages/test-postgres/src/databases.test.ts @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { after, before, test } from 'node:test'; +import { promisify } from 'node:util'; +import { askedMajor, query } from './fixtures/psql.ts'; +import { createDatabase, dropDatabase, type Postgres, startPostgres } from './index.ts'; + +let server: Postgres; +before(async () => { + server = await startPostgres({ major: askedMajor() }); +}); +after(() => server.stop()); + +const nameOf = (url: string) => new URL(url).pathname.slice(1); + +test('createDatabase() gives each caller an empty database of its own, in parallel', async () => { + const [a, b] = await Promise.all([createDatabase(server.url), createDatabase(server.url)]); + assert.notEqual(nameOf(a), nameOf(b)); + await Promise.all([ + query(a, "create table t (v text); insert into t values ('a')"), + query(b, "create table t (v text); insert into t values ('b')"), + ]); + assert.equal(await query(a, 'select v from t'), 'a'); + assert.equal(await query(b, 'select v from t'), 'b'); +}); + +test('a database made from a template starts with its contents, even while a session holds the template', async () => { + const template = await createDatabase(server.url); + await query(template, "create table t (v text); insert into t values ('seed')"); + // A session still connected to the template, as a migration's pool can be + // for a moment after it ends: PostgreSQL refuses to copy the template meanwhile. + const lingering = promisify(execFile)('psql', ['-X', '-d', template, '-c', 'select pg_sleep(1)']); + await new Promise((resolve) => setTimeout(resolve, 200)); + const copies = await Promise.all( + Array.from({ length: 4 }, () => createDatabase(server.url, { template: nameOf(template) })), + ); + await lingering; + for (const copy of copies) assert.equal(await query(copy, 'select v from t'), 'seed'); + await query(copies[0] ?? '', "insert into t values ('only here')"); + assert.equal(await query(copies[1] ?? '', 'select count(*) from t'), '1'); +}); + +test('dropDatabase() drops the database its URL names, even with a session connected', async () => { + const url = await createDatabase(server.url); + const lingering = promisify(execFile)('psql', ['-X', '-d', url, '-c', 'select pg_sleep(5)']).catch(() => {}); + await new Promise((resolve) => setTimeout(resolve, 200)); + await dropDatabase(url); + await lingering; + assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(url)}'`), '0'); +}); From 506365727e9e37a85cd71b867e8ab5c69ba82030 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:29:24 +0100 Subject: [PATCH 05/43] test-postgres: createDatabase() and dropDatabase(), a database per caller Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 78 ++++++++++++++++++++++++++--- 1 file changed, 70 insertions(+), 8 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 3540b6f..204bd4e 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -8,8 +8,18 @@ // server with pg_ctl on a free port on 127.0.0.1, its socket in that // directory, and returns the URL of the `postgres` database. stop() shuts the // server down at once and removes the directory. +// +// createDatabase() makes a database of its own for each caller, so that test +// files running in parallel share no state: an empty one, or a copy of a +// template, such as a database the run migrated once, which PostgreSQL makes +// in well under a second. PostgreSQL refuses the copy while a session is +// connected to the template, so the copy is tried again for half a minute. +// dropDatabase() drops one, closing the sessions still connected to it. Both +// speak to the server with the psql beside the server's binaries, and need no +// driver. -import { spawn } from 'node:child_process'; +import { type SpawnOptions, spawn } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; import { existsSync } from 'node:fs'; import { appendFile, mkdtemp, rm } from 'node:fs/promises'; import { createServer } from 'node:net'; @@ -71,6 +81,54 @@ export async function startPostgres(options: StartOptions): Promise { } } +/** + * Creates a database on the server of `url` and returns its URL: an empty one, + * or a copy of the database named `template` on that server. + */ +export async function createDatabase(url: string, options: { template?: string } = {}): Promise { + const name = `test_${randomBytes(4).toString('hex')}`; + const template = options.template === undefined ? '' : ` template ${identifier(options.template)}`; + const deadline = Date.now() + 30_000; + for (;;) { + try { + await sql(withDatabase(url, 'postgres'), `create database ${name}${template}`); + return withDatabase(url, name); + } catch (error) { + // 55006: the template is in use. + if (!(error instanceof Error && /ERROR:\s+55006:/.test(error.message)) || Date.now() > deadline) throw error; + await new Promise((resolve) => setTimeout(resolve, 100 + Math.random() * 200)); + } + } +} + +/** Drops the database `url` names, closing the sessions connected to it. */ +export async function dropDatabase(url: string): Promise { + const name = new URL(url).pathname.slice(1); + await sql(withDatabase(url, 'postgres'), `drop database if exists ${identifier(name)} with (force)`); +} + +function withDatabase(url: string, name: string): string { + const parsed = new URL(url); + parsed.pathname = `/${name}`; + return parsed.toString(); +} + +function identifier(name: string): string { + return `"${name.replaceAll('"', '""')}"`; +} + +// One statement through psql, which names the SQLSTATE of an error in its +// message. The environment's PG variables are left out, so that only the URL +// says where and how to connect. +function sql(url: string, statement: string): Promise { + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('PG'))); + return run( + path.join(findInstall(), 'psql'), + ['-X', '-q', '-v', 'ON_ERROR_STOP=1', '-v', 'VERBOSITY=verbose', '-d', url, '-c', statement], + { env }, + ); +} + // The directory of the first initdb on the PATH. function findInstall(): string { for (const dir of (process.env.PATH ?? '').split(path.delimiter)) { @@ -100,19 +158,23 @@ function freePort(): Promise { }); } -// Runs a tool to its end and rejects with its stderr when it fails. pg_ctl -// sends the server's output to the log file, so the started server holds no -// pipe of ours. -function run(file: string, args: string[]): Promise { +// Runs a tool to its end and resolves with its stdout, or rejects with its +// stderr. pg_ctl sends the server's output to the log file, so the started +// server holds no pipe of ours. +function run(file: string, args: string[], options: SpawnOptions = {}): Promise { return new Promise((resolve, reject) => { - const child = spawn(file, args, { stdio: ['ignore', 'ignore', 'pipe'] }); + const child = spawn(file, args, { ...options, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; let stderr = ''; - child.stderr.on('data', (chunk) => { + child.stdout?.on('data', (chunk) => { + stdout += chunk; + }); + child.stderr?.on('data', (chunk) => { stderr += chunk; }); child.once('error', reject); child.once('close', (code) => - code === 0 ? resolve() : reject(new Error(`${path.basename(file)} exited with ${code}: ${stderr.trim()}`)), + code === 0 ? resolve(stdout) : reject(new Error(`${path.basename(file)} exited with ${code}: ${stderr.trim()}`)), ); }); } From e6ead735a4f9f86beece86b01ec964e5042f8c1b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:29:46 +0100 Subject: [PATCH 06/43] test-postgres: tests of missing binaries, a client-only install and no fallback (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/binaries.test.ts | 72 +++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 packages/test-postgres/src/binaries.test.ts diff --git a/packages/test-postgres/src/binaries.test.ts b/packages/test-postgres/src/binaries.test.ts new file mode 100644 index 0000000..e23f2d7 --- /dev/null +++ b/packages/test-postgres/src/binaries.test.ts @@ -0,0 +1,72 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterEach, test } from 'node:test'; +import { askedMajor } from './fixtures/psql.ts'; +import { startPostgres } from './index.ts'; + +const originalPath = process.env.PATH; +const made: string[] = []; +afterEach(async () => { + process.env.PATH = originalPath; + delete process.env.DATABASE_URL; + for (const dir of made.splice(0)) await rm(dir, { recursive: true, force: true }); +}); + +// A directory on its own as the PATH, holding stand-ins for the tools named. +async function pathWith(...tools: string[]) { + const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-path-')); + made.push(dir); + for (const tool of tools) await writeFile(path.join(dir, tool), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + process.env.PATH = dir; + return dir; +} + +const namesThePin = (major: number) => (error: Error) => { + assert.match(error.message, new RegExp(`"conda:postgresql" = "${major}\\.`)); + assert.match(error.message, /mise\.toml/); + return true; +}; + +test('without PostgreSQL on the PATH it fails naming the mise pin to add', async () => { + const major = askedMajor(); + await pathWith(); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /initdb/); + return namesThePin(major)(error); + }); +}); + +test('with a client-only install on the PATH it says so and names the mise pin', async () => { + const major = askedMajor(); + const dir = await pathWith('psql', 'pg_dump'); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /client/); + assert.ok(error.message.includes(dir), 'names where the client is'); + return namesThePin(major)(error); + }); +}); + +test('with initdb but no server beside it it names what is missing and the mise pin', async () => { + const major = askedMajor(); + await pathWith('initdb', 'psql'); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /pg_ctl/); + assert.match(error.message, /\bpostgres\b/); + return namesThePin(major)(error); + }); +}); + +test('it never falls back to a database from the environment', async () => { + const major = askedMajor(); + const running = await startPostgres({ major }); + try { + process.env.DATABASE_URL = running.url; + await pathWith(); + await assert.rejects(startPostgres({ major }), namesThePin(major)); + } finally { + process.env.PATH = originalPath; + await running.stop(); + } +}); From 34b50ecac7f49346e9d28cd8b41ef353114595b8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:30:11 +0100 Subject: [PATCH 07/43] test-postgres: find the install on the PATH, or name the mise pin to add Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 44 +++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 204bd4e..dc0ff06 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -17,10 +17,18 @@ // dropDatabase() drops one, closing the sessions still connected to it. Both // speak to the server with the psql beside the server's binaries, and need no // driver. +// +// The binaries are the first initdb on the PATH and the pg_ctl, postgres and +// psql beside it: in a Plexus repo, the conda:postgresql pin of its +// mise.toml. The package installs nothing. When the PATH holds no initdb, or +// only a client, or an initdb without the rest, it fails with a message that +// names the pin to add. It never falls back to a container, to a database +// named by the environment (DATABASE_URL, the PG variables), or to an +// emulation: a pass must be the same evidence on every machine. import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; -import { existsSync } from 'node:fs'; +import { accessSync, constants } from 'node:fs'; import { appendFile, mkdtemp, rm } from 'node:fs/promises'; import { createServer } from 'node:net'; import { tmpdir } from 'node:os'; @@ -39,8 +47,7 @@ export interface Postgres { } export async function startPostgres(options: StartOptions): Promise { - void options; - const bin = findInstall(); + const bin = findInstall(options.major); const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); const data = path.join(dir, 'data'); const pgCtl = path.join(bin, 'pg_ctl'); @@ -129,12 +136,33 @@ function sql(url: string, statement: string): Promise { ); } -// The directory of the first initdb on the PATH. -function findInstall(): string { - for (const dir of (process.env.PATH ?? '').split(path.delimiter)) { - if (dir && existsSync(path.join(dir, 'initdb'))) return dir; +// The directory of the first initdb on the PATH, which must hold the rest of +// the install beside it, or an error that names the pin to add. +function findInstall(major?: number): string { + const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean); + const pin = `Pin a server in the repo's mise.toml, as "conda:postgresql" = "${major ?? ''}." under [tools], and run mise install.`; + const dir = dirs.find((candidate) => isExecutable(path.join(candidate, 'initdb'))); + if (!dir) { + const client = dirs.find((candidate) => isExecutable(path.join(candidate, 'psql'))); + const found = client ? `, and the psql in ${client} is a client-only install` : ''; + throw new Error(`No PostgreSQL server on the PATH: no initdb${found}. ${pin}`); + } + const missing = TOOLS.filter((tool) => !isExecutable(path.join(dir, tool))); + if (missing.length > 0) { + throw new Error(`The PostgreSQL install in ${dir} has no ${missing.join(', ')} beside initdb. ${pin}`); + } + return dir; +} + +const TOOLS = ['initdb', 'pg_ctl', 'postgres', 'psql']; + +function isExecutable(file: string): boolean { + try { + accessSync(file, constants.X_OK); + return true; + } catch { + return false; } - throw new Error('No initdb on the PATH'); } // Lines for postgresql.conf, where a later line wins over the defaults above it. From 9ea7f19adb50d8f9ef449da660fd482b91fdd09b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:30:37 +0100 Subject: [PATCH 08/43] test-postgres: a test of a server of another major than asked for (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/major.test.ts | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 packages/test-postgres/src/major.test.ts diff --git a/packages/test-postgres/src/major.test.ts b/packages/test-postgres/src/major.test.ts new file mode 100644 index 0000000..6569bc0 --- /dev/null +++ b/packages/test-postgres/src/major.test.ts @@ -0,0 +1,34 @@ +import assert from 'node:assert/strict'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { askedMajor } from './fixtures/psql.ts'; +import { startPostgres } from './index.ts'; + +test('it fails when the server on the PATH is of another major than the one asked for', async () => { + const installed = askedMajor(); + const asked = installed + 1; + // A temporary directory of this test's own, to see that nothing was initialised in it. + const scratch = await mkdtemp(path.join(tmpdir(), 'test-postgres-major-')); + const original = process.env.TMPDIR; + process.env.TMPDIR = scratch; + try { + // A server that starts anyway is stopped, and the test fails on the missing rejection. + const started = startPostgres({ major: asked }).then(async (server) => { + await server.stop(); + return server; + }); + await assert.rejects(started, (error: Error) => { + assert.match(error.message, new RegExp(`PostgreSQL ${installed}\\.\\d+`), 'names the version found'); + assert.match(error.message, new RegExp(`\\b${asked}\\b`), 'names the major asked for'); + assert.match(error.message, /mise\.toml/); + return true; + }); + assert.deepEqual(await readdir(scratch), [], 'nothing was initialised'); + } finally { + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + await rm(scratch, { recursive: true, force: true }); + } +}); From 5aeee48ee9a67ef105187c8b1e4c495ff9eda306 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:30:55 +0100 Subject: [PATCH 09/43] test-postgres: refuse a server of another major than the one asked for Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index dc0ff06..177d058 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -25,6 +25,11 @@ // names the pin to add. It never falls back to a container, to a database // named by the environment (DATABASE_URL, the PG variables), or to an // emulation: a pass must be the same evidence on every machine. +// +// The caller names the major it expects, and a server of another major on +// the PATH fails the start before anything is initialised, so that a test +// never passes against a version nobody pinned. It needs PostgreSQL 17 or +// later, the first with the builtin locale. import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; @@ -48,6 +53,12 @@ export interface Postgres { export async function startPostgres(options: StartOptions): Promise { const bin = findInstall(options.major); + const version = (await run(path.join(bin, 'postgres'), ['--version'])).match(/\(PostgreSQL\) (\S+)/)?.[1]; + if (Number.parseInt(version ?? '', 10) !== options.major) { + throw new Error( + `The server on the PATH is PostgreSQL ${version} (${bin}), but ${options.major} was asked for. ${pin(options.major)}`, + ); + } const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); const data = path.join(dir, 'data'); const pgCtl = path.join(bin, 'pg_ctl'); @@ -140,22 +151,26 @@ function sql(url: string, statement: string): Promise { // the install beside it, or an error that names the pin to add. function findInstall(major?: number): string { const dirs = (process.env.PATH ?? '').split(path.delimiter).filter(Boolean); - const pin = `Pin a server in the repo's mise.toml, as "conda:postgresql" = "${major ?? ''}." under [tools], and run mise install.`; const dir = dirs.find((candidate) => isExecutable(path.join(candidate, 'initdb'))); if (!dir) { const client = dirs.find((candidate) => isExecutable(path.join(candidate, 'psql'))); const found = client ? `, and the psql in ${client} is a client-only install` : ''; - throw new Error(`No PostgreSQL server on the PATH: no initdb${found}. ${pin}`); + throw new Error(`No PostgreSQL server on the PATH: no initdb${found}. ${pin(major)}`); } const missing = TOOLS.filter((tool) => !isExecutable(path.join(dir, tool))); if (missing.length > 0) { - throw new Error(`The PostgreSQL install in ${dir} has no ${missing.join(', ')} beside initdb. ${pin}`); + throw new Error(`The PostgreSQL install in ${dir} has no ${missing.join(', ')} beside initdb. ${pin(major)}`); } return dir; } const TOOLS = ['initdb', 'pg_ctl', 'postgres', 'psql']; +function pin(major: number | undefined): string { + const version = `${major ?? ''}.`; + return `Pin the server in the repo's mise.toml, as "conda:postgresql" = "${version}" under [tools], and run mise install.`; +} + function isExecutable(file: string): boolean { try { accessSync(file, constants.X_OK); From 35266f148a283752ebfb6da10ebf3f9536da790a Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:31:46 +0100 Subject: [PATCH 10/43] test-postgres: a test that kills the starting process with SIGKILL (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/killed.test.ts | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 packages/test-postgres/src/killed.test.ts diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts new file mode 100644 index 0000000..e460971 --- /dev/null +++ b/packages/test-postgres/src/killed.test.ts @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { rm } from 'node:fs/promises'; +import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { test } from 'node:test'; +import { askedMajor, query } from './fixtures/psql.ts'; + +// The processes whose command line names the data directory: the server's +// postmaster, as pg_ctl starts it. +function serverProcesses(dataDirectory: string): number[] { + return execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'command='], { encoding: 'utf8' }) + .split('\n') + .filter((line) => line.includes(`-D ${dataDirectory}`)) + .map((line) => Number.parseInt(line, 10)); +} + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +test('it leaves no server running when the process that started it is killed with SIGKILL', async () => { + const entry = new URL('./index.ts', import.meta.url).href; + const script = [ + `import { startPostgres } from ${JSON.stringify(entry)};`, + `const server = await startPostgres({ major: ${askedMajor()} });`, + 'console.log(server.url);', + 'setInterval(() => {}, 60_000);', + ].join('\n'); + const parent = spawn(process.execPath, ['--input-type=module', '-e', script], { + stdio: ['ignore', 'pipe', 'inherit'], + }); + const [url] = (await once(createInterface({ input: parent.stdout }), 'line')) as [string]; + const dataDirectory = await query(url, 'show data_directory'); + assert.notDeepEqual(serverProcesses(dataDirectory), [], 'the server runs'); + + parent.kill('SIGKILL'); + const [, signal] = await once(parent, 'exit'); + assert.equal(signal, 'SIGKILL'); + + const deadline = Date.now() + 15_000; + while ((serverProcesses(dataDirectory).length > 0 || existsSync(dataDirectory)) && Date.now() < deadline) { + await sleep(100); + } + const left = serverProcesses(dataDirectory); + try { + assert.deepEqual(left, [], 'no server process is left'); + assert.equal(existsSync(path.dirname(dataDirectory)), false, 'its directory is removed'); + } finally { + // A failing run takes down what it found, so that it leaves nothing behind. + for (const pid of left) process.kill(pid, 'SIGQUIT'); + while (serverProcesses(dataDirectory).length > 0 && Date.now() < deadline + 15_000) await sleep(100); + await rm(path.dirname(dataDirectory), { recursive: true, force: true }); + } +}); From 42172951820c845d0f99676578f0ff1f6f421c3b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:32:44 +0100 Subject: [PATCH 11/43] test-postgres: a detached supervisor owns the cluster and outlives its caller The supervisor waits for the end of its stdin, which the caller's stop() closes and the kernel closes when the caller dies, SIGKILL included. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 93 ++++++++++++++++++++++++++++- 1 file changed, 92 insertions(+), 1 deletion(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 177d058..8c3252f 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -9,6 +9,16 @@ // directory, and returns the URL of the `postgres` database. stop() shuts the // server down at once and removes the directory. // +// The cluster belongs to a supervisor, this file run as a detached Node +// process, and not to the caller: the supervisor starts the cluster, reports +// its URL on its stdout, and waits for the end of its stdin, whose other end +// the caller holds. stop() closes that end; so does the kernel when the +// caller exits or is killed, SIGKILL included, which no exit handler sees. +// Either way the supervisor shuts the server down and removes the directory. +// It runs in a session of its own, so that a Ctrl-C meant for the tests does +// not take it down before it has cleaned up. The caller may exit without +// calling stop(): nothing of the server keeps its event loop alive. +// // createDatabase() makes a database of its own for each caller, so that test // files running in parallel share no state: an empty one, or a copy of a // template, such as a database the run migrated once, which PostgreSQL makes @@ -33,11 +43,14 @@ import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; +import { once } from 'node:events'; import { accessSync, constants } from 'node:fs'; import { appendFile, mkdtemp, rm } from 'node:fs/promises'; -import { createServer } from 'node:net'; +import { createServer, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; import path from 'node:path'; +import { createInterface } from 'node:readline'; +import { fileURLToPath } from 'node:url'; export interface StartOptions { /** The major version the server must have, as in 18. */ @@ -59,6 +72,80 @@ export async function startPostgres(options: StartOptions): Promise { `The server on the PATH is PostgreSQL ${version} (${bin}), but ${options.major} was asked for. ${pin(options.major)}`, ); } + const supervisor = spawn(process.execPath, [fileURLToPath(import.meta.url), SUPERVISE, bin], { + detached: true, + stdio: ['pipe', 'pipe', 'ignore'], + }); + const reports = createInterface({ input: supervisor.stdout })[Symbol.asyncIterator](); + const exited = once(supervisor, 'exit'); + const next = async (): Promise => { + const line = await reports.next(); + if (line.done) { + const [code, signal] = await exited; + return { error: `The supervisor of the server exited with ${signal ?? code} before it reported` }; + } + return JSON.parse(line.value) as Report; + }; + const ready = await next(); + if (!('url' in ready)) throw new Error('error' in ready ? ready.error : 'The supervisor reported no URL'); + // The supervisor lives on its own now: this process may exit without + // waiting for it, and the end of its stdin, however it comes, stops it. + const pipes = [supervisor.stdin, supervisor.stdout] as Socket[]; + supervisor.unref(); + for (const pipe of pipes) pipe.unref(); + let stopped: Promise | undefined; + return { + url: ready.url, + stop() { + stopped ??= (async () => { + supervisor.ref(); + for (const pipe of pipes) pipe.ref(); + supervisor.stdin.end(); + const [report] = await Promise.all([next(), exited]); + if ('error' in report) throw new Error(report.error); + })(); + return stopped; + }, + }; +} + +// What the supervisor writes to its stdout, one JSON line each: the server's +// URL once it runs, and whether it stopped. +type Report = { url: string } | { stopped: true } | { error: string }; + +const SUPERVISE = '--supervise'; + +// The supervisor: this file run on its own with SUPERVISE and the install's +// directory. It starts the cluster and reports its URL, then waits for the +// end of its stdin, and stops the cluster and removes its directory. +async function supervise(bin: string) { + process.stdout.on('error', () => {}); + const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); + let cluster: Cluster; + try { + cluster = await startCluster(bin); + } catch (error) { + report({ error: error instanceof Error ? error.message : String(error) }); + process.exitCode = 1; + return; + } + report({ url: cluster.url }); + for await (const _ of process.stdin); + try { + await cluster.stop(); + report({ stopped: true }); + } catch (error) { + report({ error: error instanceof Error ? error.message : String(error) }); + process.exitCode = 1; + } +} + +interface Cluster { + url: string; + stop(): Promise; +} + +async function startCluster(bin: string): Promise { const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); const data = path.join(dir, 'data'); const pgCtl = path.join(bin, 'pg_ctl'); @@ -221,3 +308,7 @@ function run(file: string, args: string[], options: SpawnOptions = {}): Promise< ); }); } + +if (process.argv[2] === SUPERVISE && process.argv[1] === fileURLToPath(import.meta.url)) { + void supervise(process.argv[3] ?? ''); +} From 7d6aacde1ef6fd08f81cd914e37a8675c5b25b52 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:33:27 +0100 Subject: [PATCH 12/43] test-postgres: a test of the root case, as root or in a container (red) Co-Authored-By: Claude Fable 5.2 --- .../test-postgres/src/fixtures/as-root.ts | 47 +++++++++++++++ packages/test-postgres/src/root.test.ts | 59 +++++++++++++++++++ 2 files changed, 106 insertions(+) create mode 100644 packages/test-postgres/src/fixtures/as-root.ts create mode 100644 packages/test-postgres/src/root.test.ts diff --git a/packages/test-postgres/src/fixtures/as-root.ts b/packages/test-postgres/src/fixtures/as-root.ts new file mode 100644 index 0000000..bb2df7e --- /dev/null +++ b/packages/test-postgres/src/fixtures/as-root.ts @@ -0,0 +1,47 @@ +// The root case, run by root.test.ts as root: directly where the tests run +// as root, in a container elsewhere. It starts a server, uses it and stops +// it, then tries an install that the unprivileged user cannot reach, and +// prints what it saw as one JSON line for the test to judge. +import { execFileSync } from 'node:child_process'; +import { existsSync, statSync } from 'node:fs'; +import { mkdtemp, rm, symlink } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { createDatabase, startPostgres } from '../index.ts'; +import { askedMajor, query } from './psql.ts'; + +const major = askedMajor(); +const seen: Record = { uid: process.getuid?.() }; + +const server = await startPostgres({ major }); +let dataDirectory = ''; +try { + dataDirectory = await query(server.url, 'show data_directory'); + const backend = await query(server.url, 'select pg_backend_pid()'); + seen.serverUser = execFileSync('ps', ['-o', 'user=', '-p', backend], { encoding: 'utf8' }).trim(); + seen.directoryOwner = statSync(dataDirectory).uid; + seen.query = await query(await createDatabase(server.url), 'select 1'); +} finally { + await server.stop(); +} +seen.removed = !existsSync(path.dirname(dataDirectory)); + +// The same install behind a directory that only root may enter, as an +// install under /root is. +const hidden = await mkdtemp(path.join(tmpdir(), 'test-postgres-hidden-')); +for (const tool of ['initdb', 'pg_ctl', 'postgres', 'psql']) { + const target = execFileSync('sh', ['-c', `command -v ${tool}`], { encoding: 'utf8' }).trim(); + await symlink(target, path.join(hidden, tool)); +} +process.env.PATH = `${hidden}${path.delimiter}${process.env.PATH}`; +try { + const unexpected = await startPostgres({ major }); + await unexpected.stop(); + seen.unreachable = 'started'; +} catch (error) { + seen.unreachable = error instanceof Error ? error.message : String(error); +} finally { + await rm(hidden, { recursive: true, force: true }); +} + +console.log(JSON.stringify(seen)); diff --git a/packages/test-postgres/src/root.test.ts b/packages/test-postgres/src/root.test.ts new file mode 100644 index 0000000..b1c2a4c --- /dev/null +++ b/packages/test-postgres/src/root.test.ts @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { test } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; +import { askedMajor } from './fixtures/psql.ts'; + +const run = promisify(execFile); +const fixture = fileURLToPath(new URL('./fixtures/as-root.ts', import.meta.url)); +const packageDirectory = fileURLToPath(new URL('..', import.meta.url)); + +// Where the tests run as root, the fixture runs here. Elsewhere it runs as +// root in a container, from an image of the official postgres image of the +// major asked for with this Node beside it, and this package mounted: the +// root case is exercised on every machine, and never passes by not running. +async function asRoot(major: number): Promise { + if (process.getuid?.() === 0) { + return (await run(process.execPath, [fixture], { env: { ...process.env, POSTGRES_MAJOR: String(major) } })).stdout; + } + const image = `test-postgres-root:${major}-node${process.versions.node}`; + const dockerfile = [ + `FROM node:${process.versions.node}-trixie-slim AS node`, + `FROM postgres:${major}-trixie`, + 'COPY --from=node /usr/local/bin/node /usr/local/bin/node', + ].join('\n'); + const build = execFile('docker', ['build', '--quiet', '--tag', image, '-']); + build.stdin?.end(dockerfile); + await new Promise((resolve, reject) => { + build.once('error', reject); + build.once('exit', (code) => (code === 0 ? resolve() : reject(new Error(`docker build exited with ${code}`)))); + }); + const { stdout } = await run('docker', [ + 'run', + '--rm', + '--name', + `test-postgres-root-${randomBytes(4).toString('hex')}`, + '--volume', + `${packageDirectory}:/pkg:ro`, + '--env', + `POSTGRES_MAJOR=${major}`, + '--entrypoint', + 'node', + image, + '/pkg/src/fixtures/as-root.ts', + ]); + return stdout; +} + +test('as root it runs the server as nobody, and fails clearly when nobody cannot run the install', async () => { + const seen = JSON.parse((await asRoot(askedMajor())).trim().split('\n').at(-1) ?? '{}'); + assert.equal(seen.uid, 0, 'the fixture ran as root'); + assert.equal(seen.serverUser, 'nobody'); + assert.notEqual(seen.directoryOwner, 0); + assert.equal(seen.query, '1'); + assert.equal(seen.removed, true, 'stop() removed the directory'); + assert.match(seen.unreachable, /nobody/); + assert.match(seen.unreachable, /cannot run/); +}); From 0505edd77fe9be7312ae8b2b450acd19f6d40ce4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:34:11 +0100 Subject: [PATCH 13/43] test-postgres: as root, run the cluster as nobody, or say why it cannot The root fixture reads the postmaster's pid from postmaster.pid: the backend of the query that asked for it has gone by the time ps looks. Co-Authored-By: Claude Fable 5.2 --- .../test-postgres/src/fixtures/as-root.ts | 6 +- packages/test-postgres/src/index.ts | 102 +++++++++++++----- 2 files changed, 77 insertions(+), 31 deletions(-) diff --git a/packages/test-postgres/src/fixtures/as-root.ts b/packages/test-postgres/src/fixtures/as-root.ts index bb2df7e..2e4fb10 100644 --- a/packages/test-postgres/src/fixtures/as-root.ts +++ b/packages/test-postgres/src/fixtures/as-root.ts @@ -3,7 +3,7 @@ // it, then tries an install that the unprivileged user cannot reach, and // prints what it saw as one JSON line for the test to judge. import { execFileSync } from 'node:child_process'; -import { existsSync, statSync } from 'node:fs'; +import { existsSync, readFileSync, statSync } from 'node:fs'; import { mkdtemp, rm, symlink } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; @@ -17,8 +17,8 @@ const server = await startPostgres({ major }); let dataDirectory = ''; try { dataDirectory = await query(server.url, 'show data_directory'); - const backend = await query(server.url, 'select pg_backend_pid()'); - seen.serverUser = execFileSync('ps', ['-o', 'user=', '-p', backend], { encoding: 'utf8' }).trim(); + const postmaster = readFileSync(path.join(dataDirectory, 'postmaster.pid'), 'utf8').split('\n')[0] ?? ''; + seen.serverUser = execFileSync('ps', ['-o', 'user=', '-p', postmaster], { encoding: 'utf8' }).trim(); seen.directoryOwner = statSync(dataDirectory).uid; seen.query = await query(await createDatabase(server.url), 'select 1'); } finally { diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 8c3252f..3ea4316 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -40,12 +40,20 @@ // the PATH fails the start before anything is initialised, so that a test // never passes against a version nobody pinned. It needs PostgreSQL 17 or // later, the first with the builtin locale. +// +// PostgreSQL refuses to run as root. Where this process is root, as in a +// container or a cloud session, the cluster's directory belongs to nobody and +// initdb, pg_ctl and the server run as nobody. That needs the install to be +// readable by nobody, which one under /root (mode 0700) is not; the start +// then fails with a message that says so, as it does when there is no user +// nobody. It never runs the server as root and never changes the +// permissions of the install. import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { once } from 'node:events'; import { accessSync, constants } from 'node:fs'; -import { appendFile, mkdtemp, rm } from 'node:fs/promises'; +import { appendFile, chown, mkdtemp, rm } from 'node:fs/promises'; import { createServer, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; import path from 'node:path'; @@ -66,16 +74,29 @@ export interface Postgres { export async function startPostgres(options: StartOptions): Promise { const bin = findInstall(options.major); - const version = (await run(path.join(bin, 'postgres'), ['--version'])).match(/\(PostgreSQL\) (\S+)/)?.[1]; + const owner = process.getuid?.() === 0 ? await unprivilegedUser() : undefined; + const postgres = path.join(bin, 'postgres'); + const version = ( + await run(postgres, ['--version'], owner).catch((error: Error) => { + if (!owner) throw error; + throw new Error( + `The process runs as root, so the server runs as nobody (uid ${owner.uid}), and nobody cannot run ${postgres}: ${error.message}. Make the install and every directory above it readable and searchable by all users, or install it where they are, as with a MISE_DATA_DIR outside /root.`, + ); + }) + ).match(/\(PostgreSQL\) (\S+)/)?.[1]; if (Number.parseInt(version ?? '', 10) !== options.major) { throw new Error( `The server on the PATH is PostgreSQL ${version} (${bin}), but ${options.major} was asked for. ${pin(options.major)}`, ); } - const supervisor = spawn(process.execPath, [fileURLToPath(import.meta.url), SUPERVISE, bin], { - detached: true, - stdio: ['pipe', 'pipe', 'ignore'], - }); + const supervisor = spawn( + process.execPath, + [fileURLToPath(import.meta.url), SUPERVISE, JSON.stringify({ bin, owner })], + { + detached: true, + stdio: ['pipe', 'pipe', 'ignore'], + }, + ); const reports = createInterface({ input: supervisor.stdout })[Symbol.asyncIterator](); const exited = once(supervisor, 'exit'); const next = async (): Promise => { @@ -116,14 +137,14 @@ type Report = { url: string } | { stopped: true } | { error: string }; const SUPERVISE = '--supervise'; // The supervisor: this file run on its own with SUPERVISE and the install's -// directory. It starts the cluster and reports its URL, then waits for the -// end of its stdin, and stops the cluster and removes its directory. -async function supervise(bin: string) { +// directory and owner. It starts the cluster and reports its URL, then waits +// for the end of its stdin, and stops the cluster and removes its directory. +async function supervise({ bin, owner }: { bin: string; owner?: Owner }) { process.stdout.on('error', () => {}); const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); let cluster: Cluster; try { - cluster = await startCluster(bin); + cluster = await startCluster(bin, owner); } catch (error) { report({ error: error instanceof Error ? error.message : String(error) }); process.exitCode = 1; @@ -140,41 +161,66 @@ async function supervise(bin: string) { } } +// The user the server runs as when this process is root. +interface Owner { + uid: number; + gid: number; +} + +// PostgreSQL refuses to run as root, so as root the server runs as nobody, +// the one unprivileged user that Linux and macOS systems have, containers +// with neither a postgres user nor sudo among them. +async function unprivilegedUser(): Promise { + try { + const [uid, gid] = await Promise.all([run('id', ['-u', 'nobody']), run('id', ['-g', 'nobody'])]); + return { uid: Number(uid), gid: Number(gid) }; + } catch (error) { + throw new Error( + `The process runs as root, where PostgreSQL refuses to run, and there is no user nobody to run the server as: ${error instanceof Error ? error.message : error}`, + ); + } +} + interface Cluster { url: string; stop(): Promise; } -async function startCluster(bin: string): Promise { +async function startCluster(bin: string, owner: Owner | undefined): Promise { const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); + if (owner) await chown(dir, owner.uid, owner.gid); const data = path.join(dir, 'data'); const pgCtl = path.join(bin, 'pg_ctl'); try { const port = await freePort(); - await run(path.join(bin, 'initdb'), [ - '-D', - data, - '-U', - 'postgres', - '-A', - 'trust', - '--no-sync', - '-E', - 'UTF8', - '--locale=C', - '--locale-provider=builtin', - '--builtin-locale=C.UTF-8', - ]); + await run( + path.join(bin, 'initdb'), + [ + '-D', + data, + '-U', + 'postgres', + '-A', + 'trust', + '--no-sync', + '-E', + 'UTF8', + '--locale=C', + '--locale-provider=builtin', + '--builtin-locale=C.UTF-8', + ], + owner, + ); await appendFile( path.join(data, 'postgresql.conf'), configuration({ port, listen_addresses: '127.0.0.1', unix_socket_directories: dir, fsync: 'off' }), ); - await run(pgCtl, ['-D', data, '-l', path.join(dir, 'server.log'), '-w', 'start']); + await run(pgCtl, ['-D', data, '-l', path.join(dir, 'server.log'), '-w', 'start'], owner); return { url: `postgres://postgres@127.0.0.1:${port}/postgres`, async stop() { try { - await run(pgCtl, ['-D', data, '-m', 'immediate', '-w', 'stop']); + await run(pgCtl, ['-D', data, '-m', 'immediate', '-w', 'stop'], owner); } finally { await rm(dir, { recursive: true, force: true }); } @@ -310,5 +356,5 @@ function run(file: string, args: string[], options: SpawnOptions = {}): Promise< } if (process.argv[2] === SUPERVISE && process.argv[1] === fileURLToPath(import.meta.url)) { - void supervise(process.argv[3] ?? ''); + void supervise(JSON.parse(process.argv[3] ?? '{}')); } From 0014f5f506903a1078ba8780b4f93c33a776d4dc Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:34:24 +0100 Subject: [PATCH 14/43] test-postgres: a test of server settings such as max_connections (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/start.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts index ebfa420..68ed700 100644 --- a/packages/test-postgres/src/start.test.ts +++ b/packages/test-postgres/src/start.test.ts @@ -35,3 +35,13 @@ test('the cluster is UTF-8 with the builtin C.UTF-8 locale, the same on every ma await server.stop(); } }); + +test('settings are passed to the server', async () => { + const server = await startPostgres({ major: askedMajor(), settings: { max_connections: 250, cluster_name: "it's" } }); + try { + assert.equal(await query(server.url, 'show max_connections'), '250'); + assert.equal(await query(server.url, 'show cluster_name'), "it's"); + } finally { + await server.stop(); + } +}); From e904929cd9b07f6f44d95feb8179a2b4d17e7074 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:34:41 +0100 Subject: [PATCH 15/43] test-postgres: the caller's server settings, in postgresql.conf Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 36 +++++++++++++++++++---------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 3ea4316..e3c81b7 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -4,10 +4,12 @@ // startPostgres() initialises a cluster in a new temporary directory with // initdb, owned by the postgres role with trust authentication, UTF-8 with // the builtin C.UTF-8 locale so that text sorts and cases alike on every -// machine, and without fsync, since the data lives for one run. It starts the -// server with pg_ctl on a free port on 127.0.0.1, its socket in that -// directory, and returns the URL of the `postgres` database. stop() shuts the -// server down at once and removes the directory. +// machine, and without fsync, since the data lives for one run. The caller's +// settings, such as max_connections for many test workers, go into its +// postgresql.conf; the port, the address and the socket directory are the +// package's. It starts the server with pg_ctl on a free port on 127.0.0.1, +// its socket in that directory, and returns the URL of the `postgres` +// database. stop() shuts the server down at once and removes the directory. // // The cluster belongs to a supervisor, this file run as a detached Node // process, and not to the caller: the supervisor starts the cluster, reports @@ -63,6 +65,8 @@ import { fileURLToPath } from 'node:url'; export interface StartOptions { /** The major version the server must have, as in 18. */ major: number; + /** Server parameters for postgresql.conf, as in `{ max_connections: 400 }`. */ + settings?: Record; } export interface Postgres { @@ -91,7 +95,7 @@ export async function startPostgres(options: StartOptions): Promise { } const supervisor = spawn( process.execPath, - [fileURLToPath(import.meta.url), SUPERVISE, JSON.stringify({ bin, owner })], + [fileURLToPath(import.meta.url), SUPERVISE, JSON.stringify({ bin, owner, settings: options.settings ?? {} })], { detached: true, stdio: ['pipe', 'pipe', 'ignore'], @@ -139,12 +143,12 @@ const SUPERVISE = '--supervise'; // The supervisor: this file run on its own with SUPERVISE and the install's // directory and owner. It starts the cluster and reports its URL, then waits // for the end of its stdin, and stops the cluster and removes its directory. -async function supervise({ bin, owner }: { bin: string; owner?: Owner }) { +async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; settings: Settings }) { process.stdout.on('error', () => {}); const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); let cluster: Cluster; try { - cluster = await startCluster(bin, owner); + cluster = await startCluster(bin, owner, settings); } catch (error) { report({ error: error instanceof Error ? error.message : String(error) }); process.exitCode = 1; @@ -186,7 +190,7 @@ interface Cluster { stop(): Promise; } -async function startCluster(bin: string, owner: Owner | undefined): Promise { +async function startCluster(bin: string, owner: Owner | undefined, settings: Settings): Promise { const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-')); if (owner) await chown(dir, owner.uid, owner.gid); const data = path.join(dir, 'data'); @@ -213,7 +217,7 @@ async function startCluster(bin: string, owner: Owner | undefined): Promise): string { +type Settings = Record; + +// Lines for postgresql.conf, where a later line wins over the defaults above +// it: no shell and no command line sees a value. +function configuration(settings: Settings): string { return Object.entries(settings) - .map(([name, value]) => `${name} = '${String(value).replaceAll("'", "''")}'\n`) + .map(([name, value]) => { + if (!/^[a-z_][a-z0-9_.]*$/i.test(name) || /[\r\n]/.test(String(value))) { + throw new Error(`Not a server setting: ${name} = ${value}`); + } + return `${name} = '${String(value).replaceAll("'", "''")}'\n`; + }) .join(''); } From d3f04b3bc75b3dc7aa793d190c4a7c59caac9c51 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 14:36:37 +0100 Subject: [PATCH 16/43] test-postgres: the changeset that releases it as 0.1.0 Co-Authored-By: Claude Fable 5.2 --- .changeset/test-postgres.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .changeset/test-postgres.md diff --git a/.changeset/test-postgres.md b/.changeset/test-postgres.md new file mode 100644 index 0000000..5aaf5f1 --- /dev/null +++ b/.changeset/test-postgres.md @@ -0,0 +1,8 @@ +--- +"@plexus-ms/test-postgres": minor +--- + +A new package: a throwaway PostgreSQL server for tests, started from the binary on the PATH and removed afterwards. +`startPostgres({ major })` initialises a cluster in a temporary directory and starts it on a free loopback port; `createDatabase()` gives each test file a database of its own, empty or copied from a template, and `dropDatabase()` drops one. +It fails with a message naming the mise pin to add when no server is on the PATH, and when the server is of another major than the one asked for. +As root it runs the server as `nobody`, and no server outlives the process that started it, even one killed with SIGKILL. From cd489e7c7b1171bc8524be6c603b497364c1a31b Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:25:39 +0100 Subject: [PATCH 17/43] test-postgres: drop the root test; the fixture stays as a script run by hand The maintainer's decision: nothing in test may need Docker. The root path stays and the header says that no test covers it; the Docker variables leave the package's turbo.json. Co-Authored-By: Claude Fable 5.2 --- .../test-postgres/src/fixtures/as-root.ts | 10 ++-- packages/test-postgres/src/index.ts | 3 +- packages/test-postgres/src/root.test.ts | 59 ------------------- packages/test-postgres/turbo.json | 3 +- 4 files changed, 9 insertions(+), 66 deletions(-) delete mode 100644 packages/test-postgres/src/root.test.ts diff --git a/packages/test-postgres/src/fixtures/as-root.ts b/packages/test-postgres/src/fixtures/as-root.ts index 2e4fb10..207878a 100644 --- a/packages/test-postgres/src/fixtures/as-root.ts +++ b/packages/test-postgres/src/fixtures/as-root.ts @@ -1,7 +1,9 @@ -// The root case, run by root.test.ts as root: directly where the tests run -// as root, in a container elsewhere. It starts a server, uses it and stops -// it, then tries an install that the unprivileged user cannot reach, and -// prints what it saw as one JSON line for the test to judge. +// The root case, which no test covers: a script run by hand as root. It +// starts a server, uses it and stops it, then tries an install that the +// unprivileged user cannot reach, and prints what it saw as one JSON line: +// the server's user is nobody, the directory is removed, and the second start +// fails naming nobody. +// In a container, from this package's directory: docker run --rm --cpus 2 --memory 2g --pids-limit 300 -v "$PWD":/pkg:ro -e POSTGRES_MAJOR=18 --entrypoint node /pkg/src/fixtures/as-root.ts import { execFileSync } from 'node:child_process'; import { existsSync, readFileSync, statSync } from 'node:fs'; import { mkdtemp, rm, symlink } from 'node:fs/promises'; diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index e3c81b7..cfefe61 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -49,7 +49,8 @@ // readable by nobody, which one under /root (mode 0700) is not; the start // then fails with a message that says so, as it does when there is no user // nobody. It never runs the server as root and never changes the -// permissions of the install. +// permissions of the install. No test covers this path; it is tried by hand +// with src/fixtures/as-root.ts. import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; diff --git a/packages/test-postgres/src/root.test.ts b/packages/test-postgres/src/root.test.ts deleted file mode 100644 index b1c2a4c..0000000 --- a/packages/test-postgres/src/root.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import assert from 'node:assert/strict'; -import { execFile } from 'node:child_process'; -import { randomBytes } from 'node:crypto'; -import { test } from 'node:test'; -import { fileURLToPath } from 'node:url'; -import { promisify } from 'node:util'; -import { askedMajor } from './fixtures/psql.ts'; - -const run = promisify(execFile); -const fixture = fileURLToPath(new URL('./fixtures/as-root.ts', import.meta.url)); -const packageDirectory = fileURLToPath(new URL('..', import.meta.url)); - -// Where the tests run as root, the fixture runs here. Elsewhere it runs as -// root in a container, from an image of the official postgres image of the -// major asked for with this Node beside it, and this package mounted: the -// root case is exercised on every machine, and never passes by not running. -async function asRoot(major: number): Promise { - if (process.getuid?.() === 0) { - return (await run(process.execPath, [fixture], { env: { ...process.env, POSTGRES_MAJOR: String(major) } })).stdout; - } - const image = `test-postgres-root:${major}-node${process.versions.node}`; - const dockerfile = [ - `FROM node:${process.versions.node}-trixie-slim AS node`, - `FROM postgres:${major}-trixie`, - 'COPY --from=node /usr/local/bin/node /usr/local/bin/node', - ].join('\n'); - const build = execFile('docker', ['build', '--quiet', '--tag', image, '-']); - build.stdin?.end(dockerfile); - await new Promise((resolve, reject) => { - build.once('error', reject); - build.once('exit', (code) => (code === 0 ? resolve() : reject(new Error(`docker build exited with ${code}`)))); - }); - const { stdout } = await run('docker', [ - 'run', - '--rm', - '--name', - `test-postgres-root-${randomBytes(4).toString('hex')}`, - '--volume', - `${packageDirectory}:/pkg:ro`, - '--env', - `POSTGRES_MAJOR=${major}`, - '--entrypoint', - 'node', - image, - '/pkg/src/fixtures/as-root.ts', - ]); - return stdout; -} - -test('as root it runs the server as nobody, and fails clearly when nobody cannot run the install', async () => { - const seen = JSON.parse((await asRoot(askedMajor())).trim().split('\n').at(-1) ?? '{}'); - assert.equal(seen.uid, 0, 'the fixture ran as root'); - assert.equal(seen.serverUser, 'nobody'); - assert.notEqual(seen.directoryOwner, 0); - assert.equal(seen.query, '1'); - assert.equal(seen.removed, true, 'stop() removed the directory'); - assert.match(seen.unreachable, /nobody/); - assert.match(seen.unreachable, /cannot run/); -}); diff --git a/packages/test-postgres/turbo.json b/packages/test-postgres/turbo.json index 7860099..35c9361 100644 --- a/packages/test-postgres/turbo.json +++ b/packages/test-postgres/turbo.json @@ -3,8 +3,7 @@ "extends": ["//"], "tasks": { "test": { - "env": ["$TURBO_EXTENDS$", "POSTGRES_MAJOR"], - "passThroughEnv": ["$TURBO_EXTENDS$", "HOME", "DOCKER_HOST", "DOCKER_CONTEXT"] + "env": ["$TURBO_EXTENDS$", "POSTGRES_MAJOR"] } } } From 931c7745a1ecd4a7d6c8144233a87e86a0cb0ca6 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:26:37 +0100 Subject: [PATCH 18/43] test-postgres: no retry of a template copy; PostgreSQL waits on its own Measured with 18.6 and the loop removed: eight copies at once from one template all succeed (25 ms), and a session on the template is waited for about five seconds before the copy fails with 55006 (a 3 s session: the copy succeeds after 2.7 s; a 9 s session: it fails after 5.0 s). Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index cfefe61..7713580 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -24,8 +24,10 @@ // createDatabase() makes a database of its own for each caller, so that test // files running in parallel share no state: an empty one, or a copy of a // template, such as a database the run migrated once, which PostgreSQL makes -// in well under a second. PostgreSQL refuses the copy while a session is -// connected to the template, so the copy is tried again for half a minute. +// in well under a second. Copies made at once from one template do not wait +// on each other; a session connected to the template makes PostgreSQL wait +// for it to leave, about five seconds, and then refuse the copy with SQLSTATE +// 55006, which the call passes on. // dropDatabase() drops one, closing the sessions still connected to it. Both // speak to the server with the psql beside the server's binaries, and need no // driver. @@ -244,17 +246,8 @@ async function startCluster(bin: string, owner: Owner | undefined, settings: Set export async function createDatabase(url: string, options: { template?: string } = {}): Promise { const name = `test_${randomBytes(4).toString('hex')}`; const template = options.template === undefined ? '' : ` template ${identifier(options.template)}`; - const deadline = Date.now() + 30_000; - for (;;) { - try { - await sql(withDatabase(url, 'postgres'), `create database ${name}${template}`); - return withDatabase(url, name); - } catch (error) { - // 55006: the template is in use. - if (!(error instanceof Error && /ERROR:\s+55006:/.test(error.message)) || Date.now() > deadline) throw error; - await new Promise((resolve) => setTimeout(resolve, 100 + Math.random() * 200)); - } - } + await sql(withDatabase(url, 'postgres'), `create database ${name}${template}`); + return withDatabase(url, name); } /** Drops the database `url` names, closing the sessions connected to it. */ From b01cc1199e0a035a813b9fba369965b728bd952d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:27:52 +0100 Subject: [PATCH 19/43] test-postgres: a test of the package bundled into its caller's file (red) The package's source and a caller in one file, as a bundler makes it. The caller logs every process that runs the file and stops three levels down, so that the chain this reproduces stays small; the test removes what it left. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/bundled.test.ts | 66 ++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 packages/test-postgres/src/bundled.test.ts diff --git a/packages/test-postgres/src/bundled.test.ts b/packages/test-postgres/src/bundled.test.ts new file mode 100644 index 0000000..a66a1eb --- /dev/null +++ b/packages/test-postgres/src/bundled.test.ts @@ -0,0 +1,66 @@ +import assert from 'node:assert/strict'; +import { execFileSync, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { test } from 'node:test'; +import { askedMajor } from './fixtures/psql.ts'; + +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +const processesNaming = (text: string) => + execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'command='], { encoding: 'utf8' }) + .split('\n') + .filter((line) => line.includes(text)) + .map((line) => Number.parseInt(line, 10)); + +// A bundler puts the package's code and the caller's into one file, as here +// by hand: the package's source with a caller after it, in an app of its own. +// Every process that runs the file logs itself, and a process three levels +// down exits at once, so that a regression stays small. +test('bundled into the file of its caller it refuses to start, and starts nothing', { timeout: 60_000 }, async () => { + const app = await mkdtemp(path.join(tmpdir(), 'test-postgres-bundle-')); + const clusters = path.join(app, 'tmp'); + const log = path.join(app, 'processes.log'); + const file = path.join(app, 'app.ts'); + try { + await mkdir(clusters); + await writeFile(path.join(app, 'package.json'), '{ "name": "app", "type": "module" }\n'); + const caller = [ + "import { appendFileSync } from 'node:fs';", + 'const depth = Number(process.env.TEST_BUNDLE_DEPTH ?? 0);', + `appendFileSync(${JSON.stringify(log)}, \`\${depth}\\n\`);`, + 'process.env.TEST_BUNDLE_DEPTH = String(depth + 1);', + 'if (depth >= 2) process.exit(0);', + `const server = await startPostgres({ major: ${askedMajor()} });`, + 'await server.stop();', + ].join('\n'); + await writeFile(file, `${await readFile(new URL('./index.ts', import.meta.url), 'utf8')}\n${caller}\n`); + + const run = spawn(process.execPath, [file], { + env: { ...process.env, TMPDIR: clusters }, + stdio: ['ignore', 'ignore', 'pipe'], + }); + let stderr = ''; + run.stderr.on('data', (chunk) => { + stderr += chunk; + }); + const exited = once(run, 'exit'); + const [code] = (await Promise.race([exited, sleep(20_000).then(() => ['timeout'])])) as [number | string]; + await sleep(1_000); + + const depths = (await readFile(log, 'utf8')).trim().split('\n').map(Number); + assert.ok(depths.filter((depth) => depth > 0).length <= 1, `at most one supervisor ever existed: ${depths}`); + assert.notEqual(code, 0); + assert.match(stderr, /bundled/); + assert.match(stderr, /external/); + assert.deepEqual(processesNaming(clusters), [], 'no server runs'); + assert.deepEqual(await readdir(clusters), [], 'no cluster directory is left'); + } finally { + // What a regression left: its processes, then its servers, then the files. + for (const pid of processesNaming(file)) process.kill(pid, 'SIGKILL'); + for (const pid of processesNaming(clusters)) process.kill(pid, 'SIGQUIT'); + for (let i = 0; i < 50 && processesNaming(clusters).length > 0; i++) await sleep(100); + await rm(app, { recursive: true, force: true }); + } +}); From 616b55112573de8d3c8621c2fb40871f7d8045db Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:29:37 +0100 Subject: [PATCH 20/43] test-postgres: refuse to start bundled; mark the supervisor by its environment The supervisor is the package's own file run on its own. Bundled into the caller's file, that file is the caller's program, so each supervisor ran the caller again and started the next. startPostgres now refuses unless its file is the package's own (the nearest package.json names it), and the entry guard tests an environment variable the package sets on the supervisor, not the command line. A marker alone was not enough: tried by hand, the bundle's supervisor began its cluster directory before the bundle's caller code failed, and the directory was left. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 58 +++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 7713580..e3fe223 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -21,6 +21,13 @@ // not take it down before it has cleaned up. The caller may exit without // calling stop(): nothing of the server keeps its event loop alive. // +// So the package must stay a file of its own, external to any bundle: a +// bundle that holds the caller's code too would run the caller again as the +// supervisor. It refuses to start when its file is not the package's own (the +// nearest package.json names another package). The supervisor is marked by +// the environment variable PLEXUS_TEST_POSTGRES_SUPERVISOR, which the package +// sets on it, and not by its command line, which a bundle may change. +// // createDatabase() makes a database of its own for each caller, so that test // files running in parallel share no state: an empty one, or a copy of a // template, such as a database the run migrated once, which PostgreSQL makes @@ -57,7 +64,7 @@ import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { once } from 'node:events'; -import { accessSync, constants } from 'node:fs'; +import { accessSync, constants, readFileSync } from 'node:fs'; import { appendFile, chown, mkdtemp, rm } from 'node:fs/promises'; import { createServer, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; @@ -80,6 +87,7 @@ export interface Postgres { } export async function startPostgres(options: StartOptions): Promise { + const file = ownFile(); const bin = findInstall(options.major); const owner = process.getuid?.() === 0 ? await unprivilegedUser() : undefined; const postgres = path.join(bin, 'postgres'); @@ -96,14 +104,11 @@ export async function startPostgres(options: StartOptions): Promise { `The server on the PATH is PostgreSQL ${version} (${bin}), but ${options.major} was asked for. ${pin(options.major)}`, ); } - const supervisor = spawn( - process.execPath, - [fileURLToPath(import.meta.url), SUPERVISE, JSON.stringify({ bin, owner, settings: options.settings ?? {} })], - { - detached: true, - stdio: ['pipe', 'pipe', 'ignore'], - }, - ); + const supervisor = spawn(process.execPath, [file, '--supervise'], { + env: { ...process.env, [SUPERVISOR]: JSON.stringify({ bin, owner, settings: options.settings ?? {} }) }, + detached: true, + stdio: ['pipe', 'pipe', 'ignore'], + }); const reports = createInterface({ input: supervisor.stdout })[Symbol.asyncIterator](); const exited = once(supervisor, 'exit'); const next = async (): Promise => { @@ -141,10 +146,34 @@ export async function startPostgres(options: StartOptions): Promise { // URL once it runs, and whether it stopped. type Report = { url: string } | { stopped: true } | { error: string }; -const SUPERVISE = '--supervise'; +// The variable that marks the supervisor and carries what it needs: the +// install's directory, the owner and the settings. `--supervise` on its +// command line only names it in a process list. +const SUPERVISOR = 'PLEXUS_TEST_POSTGRES_SUPERVISOR'; + +const BUNDLED = + '@plexus-ms/test-postgres cannot run bundled into another file, since it runs its own file as the supervisor of the server: keep it external to the bundle (for esbuild, --external:@plexus-ms/test-postgres).'; -// The supervisor: this file run on its own with SUPERVISE and the install's -// directory and owner. It starts the cluster and reports its URL, then waits +// This file, when it is the package's own: the file whose nearest +// package.json is this package's. A bundle that holds the caller's code too +// would run the caller again as the supervisor, and each such supervisor +// would start the next. +function ownFile(): string { + const file = fileURLToPath(import.meta.url); + for (let dir = path.dirname(file); dir !== path.dirname(dir); dir = path.dirname(dir)) { + let manifest: string; + try { + manifest = readFileSync(path.join(dir, 'package.json'), 'utf8'); + } catch { + continue; + } + if (JSON.parse(manifest).name === '@plexus-ms/test-postgres') return file; + break; + } + throw new Error(BUNDLED); +} + +// The supervisor: this file run on its own, marked by SUPERVISOR. It starts the cluster and reports its URL, then waits // for the end of its stdin, and stops the cluster and removes its directory. async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; settings: Settings }) { process.stdout.on('error', () => {}); @@ -361,6 +390,5 @@ function run(file: string, args: string[], options: SpawnOptions = {}): Promise< }); } -if (process.argv[2] === SUPERVISE && process.argv[1] === fileURLToPath(import.meta.url)) { - void supervise(JSON.parse(process.argv[3] ?? '{}')); -} +const supervisorConfiguration = process.env[SUPERVISOR]; +if (supervisorConfiguration !== undefined) void supervise(JSON.parse(supervisorConfiguration)); From 6329790579d9848e4cd2e979b9b2745a1dc8396d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:30:12 +0100 Subject: [PATCH 21/43] test-postgres: a test that a marked supervisor starts no server (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/bundled.test.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/packages/test-postgres/src/bundled.test.ts b/packages/test-postgres/src/bundled.test.ts index a66a1eb..19b7ca1 100644 --- a/packages/test-postgres/src/bundled.test.ts +++ b/packages/test-postgres/src/bundled.test.ts @@ -6,6 +6,7 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; import { askedMajor } from './fixtures/psql.ts'; +import { startPostgres } from './index.ts'; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); const processesNaming = (text: string) => @@ -64,3 +65,24 @@ test('bundled into the file of its caller it refuses to start, and starts nothin await rm(app, { recursive: true, force: true }); } }); + +test('a process the package marked as a supervisor refuses to start another server', async () => { + const clusters = await mkdtemp(path.join(tmpdir(), 'test-postgres-marked-')); + const original = process.env.TMPDIR; + process.env.TMPDIR = clusters; + process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR = '{}'; + try { + // A server that starts anyway is stopped, and the test fails on the missing rejection. + const started = startPostgres({ major: askedMajor() }).then(async (server) => { + await server.stop(); + return server; + }); + await assert.rejects(started, /bundled/); + assert.deepEqual(await readdir(clusters), [], 'nothing was started'); + } finally { + delete process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR; + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + await rm(clusters, { recursive: true, force: true }); + } +}); From d49a533ff31f2e0f91b3dac29da67c699201f704 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:30:32 +0100 Subject: [PATCH 22/43] test-postgres: a marked supervisor refuses to start another server Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index e3fe223..317a188 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -26,7 +26,8 @@ // supervisor. It refuses to start when its file is not the package's own (the // nearest package.json names another package). The supervisor is marked by // the environment variable PLEXUS_TEST_POSTGRES_SUPERVISOR, which the package -// sets on it, and not by its command line, which a bundle may change. +// sets on it, and not by its command line, which a bundle may change; a +// process so marked refuses to start another server. // // createDatabase() makes a database of its own for each caller, so that test // files running in parallel share no state: an empty one, or a copy of a @@ -87,6 +88,7 @@ export interface Postgres { } export async function startPostgres(options: StartOptions): Promise { + if (process.env[SUPERVISOR] !== undefined) throw new Error(BUNDLED); const file = ownFile(); const bin = findInstall(options.major); const owner = process.getuid?.() === 0 ? await unprivilegedUser() : undefined; From c0aea26cce80a1dcd9714a732a6267f9ac54773f Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:31:45 +0100 Subject: [PATCH 23/43] test-postgres: the tests share a way to watch a start that must fail fixtures/psql.ts becomes fixtures/support.ts, with startThatFails(): the start under a TMPDIR of its own, its error and what it left there. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/binaries.test.ts | 2 +- packages/test-postgres/src/bundled.test.ts | 18 ++----- packages/test-postgres/src/databases.test.ts | 2 +- .../test-postgres/src/fixtures/as-root.ts | 2 +- packages/test-postgres/src/fixtures/psql.ts | 17 ------- .../test-postgres/src/fixtures/support.ts | 47 +++++++++++++++++++ packages/test-postgres/src/killed.test.ts | 2 +- packages/test-postgres/src/major.test.ts | 33 +++---------- packages/test-postgres/src/start.test.ts | 2 +- 9 files changed, 63 insertions(+), 62 deletions(-) delete mode 100644 packages/test-postgres/src/fixtures/psql.ts create mode 100644 packages/test-postgres/src/fixtures/support.ts diff --git a/packages/test-postgres/src/binaries.test.ts b/packages/test-postgres/src/binaries.test.ts index e23f2d7..6c7cb23 100644 --- a/packages/test-postgres/src/binaries.test.ts +++ b/packages/test-postgres/src/binaries.test.ts @@ -3,7 +3,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, test } from 'node:test'; -import { askedMajor } from './fixtures/psql.ts'; +import { askedMajor } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; const originalPath = process.env.PATH; diff --git a/packages/test-postgres/src/bundled.test.ts b/packages/test-postgres/src/bundled.test.ts index 19b7ca1..7f14f57 100644 --- a/packages/test-postgres/src/bundled.test.ts +++ b/packages/test-postgres/src/bundled.test.ts @@ -5,7 +5,7 @@ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promis import { tmpdir } from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; -import { askedMajor } from './fixtures/psql.ts'; +import { askedMajor, startThatFails } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -67,22 +67,12 @@ test('bundled into the file of its caller it refuses to start, and starts nothin }); test('a process the package marked as a supervisor refuses to start another server', async () => { - const clusters = await mkdtemp(path.join(tmpdir(), 'test-postgres-marked-')); - const original = process.env.TMPDIR; - process.env.TMPDIR = clusters; process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR = '{}'; try { - // A server that starts anyway is stopped, and the test fails on the missing rejection. - const started = startPostgres({ major: askedMajor() }).then(async (server) => { - await server.stop(); - return server; - }); - await assert.rejects(started, /bundled/); - assert.deepEqual(await readdir(clusters), [], 'nothing was started'); + const { error, left } = await startThatFails(() => startPostgres({ major: askedMajor() })); + assert.match(error?.message ?? 'it started', /bundled/); + assert.deepEqual(left, [], 'nothing was started'); } finally { delete process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR; - if (original === undefined) delete process.env.TMPDIR; - else process.env.TMPDIR = original; - await rm(clusters, { recursive: true, force: true }); } }); diff --git a/packages/test-postgres/src/databases.test.ts b/packages/test-postgres/src/databases.test.ts index 334bfdb..78f4505 100644 --- a/packages/test-postgres/src/databases.test.ts +++ b/packages/test-postgres/src/databases.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { execFile } from 'node:child_process'; import { after, before, test } from 'node:test'; import { promisify } from 'node:util'; -import { askedMajor, query } from './fixtures/psql.ts'; +import { askedMajor, query } from './fixtures/support.ts'; import { createDatabase, dropDatabase, type Postgres, startPostgres } from './index.ts'; let server: Postgres; diff --git a/packages/test-postgres/src/fixtures/as-root.ts b/packages/test-postgres/src/fixtures/as-root.ts index 207878a..4848db2 100644 --- a/packages/test-postgres/src/fixtures/as-root.ts +++ b/packages/test-postgres/src/fixtures/as-root.ts @@ -10,7 +10,7 @@ import { mkdtemp, rm, symlink } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { createDatabase, startPostgres } from '../index.ts'; -import { askedMajor, query } from './psql.ts'; +import { askedMajor, query } from './support.ts'; const major = askedMajor(); const seen: Record = { uid: process.getuid?.() }; diff --git a/packages/test-postgres/src/fixtures/psql.ts b/packages/test-postgres/src/fixtures/psql.ts deleted file mode 100644 index 51246b8..0000000 --- a/packages/test-postgres/src/fixtures/psql.ts +++ /dev/null @@ -1,17 +0,0 @@ -// What the tests share: the major they ask for and a way to ask a server -// something, with the psql on the PATH, so that the tests need no driver. -import { execFile } from 'node:child_process'; -import { promisify } from 'node:util'; - -/** The major of the repo's PostgreSQL pin, which mise puts in POSTGRES_MAJOR. */ -export function askedMajor(): number { - const major = Number(process.env.POSTGRES_MAJOR); - if (!Number.isInteger(major)) throw new Error('POSTGRES_MAJOR names no major: run the tests through mise'); - return major; -} - -/** Runs `sql` against the database `url` names and returns psql's unaligned, tuples-only output. */ -export async function query(url: string, sql: string): Promise { - const { stdout } = await promisify(execFile)('psql', ['-X', '-At', '-v', 'ON_ERROR_STOP=1', '-d', url, '-c', sql]); - return stdout.trim(); -} diff --git a/packages/test-postgres/src/fixtures/support.ts b/packages/test-postgres/src/fixtures/support.ts new file mode 100644 index 0000000..5e4ed14 --- /dev/null +++ b/packages/test-postgres/src/fixtures/support.ts @@ -0,0 +1,47 @@ +// What the tests share: the major they ask for, a way to ask a server +// something with the psql on the PATH, so that the tests need no driver, and +// a way to watch a start that must fail. +import { execFile } from 'node:child_process'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { promisify } from 'node:util'; + +/** The major of the repo's PostgreSQL pin, which mise puts in POSTGRES_MAJOR. */ +export function askedMajor(): number { + const major = Number(process.env.POSTGRES_MAJOR); + if (!Number.isInteger(major)) throw new Error('POSTGRES_MAJOR names no major: run the tests through mise'); + return major; +} + +/** Runs `sql` against the database `url` names and returns psql's unaligned, tuples-only output. */ +export async function query(url: string, sql: string): Promise { + const { stdout } = await promisify(execFile)('psql', ['-X', '-At', '-v', 'ON_ERROR_STOP=1', '-d', url, '-c', sql]); + return stdout.trim(); +} + +/** + * Runs a start that must fail, with TMPDIR set to a directory of its own, and + * returns its error and what it left in that directory. A server that starts + * anyway is stopped, and the error is then undefined. + */ +export async function startThatFails( + start: () => Promise<{ stop(): Promise }>, +): Promise<{ error: Error | undefined; left: string[] }> { + const scratch = await mkdtemp(path.join(tmpdir(), 'test-postgres-scratch-')); + const original = process.env.TMPDIR; + process.env.TMPDIR = scratch; + try { + let error: Error | undefined; + try { + await (await start()).stop(); + } catch (caught) { + error = caught as Error; + } + return { error, left: await readdir(scratch) }; + } finally { + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + await rm(scratch, { recursive: true, force: true }); + } +} diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts index e460971..c7673bc 100644 --- a/packages/test-postgres/src/killed.test.ts +++ b/packages/test-postgres/src/killed.test.ts @@ -6,7 +6,7 @@ import { rm } from 'node:fs/promises'; import path from 'node:path'; import { createInterface } from 'node:readline'; import { test } from 'node:test'; -import { askedMajor, query } from './fixtures/psql.ts'; +import { askedMajor, query } from './fixtures/support.ts'; // The processes whose command line names the data directory: the server's // postmaster, as pg_ctl starts it. diff --git a/packages/test-postgres/src/major.test.ts b/packages/test-postgres/src/major.test.ts index 6569bc0..9456bbf 100644 --- a/packages/test-postgres/src/major.test.ts +++ b/packages/test-postgres/src/major.test.ts @@ -1,34 +1,15 @@ import assert from 'node:assert/strict'; -import { mkdtemp, readdir, rm } from 'node:fs/promises'; -import { tmpdir } from 'node:os'; -import path from 'node:path'; import { test } from 'node:test'; -import { askedMajor } from './fixtures/psql.ts'; +import { askedMajor, startThatFails } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; test('it fails when the server on the PATH is of another major than the one asked for', async () => { const installed = askedMajor(); const asked = installed + 1; - // A temporary directory of this test's own, to see that nothing was initialised in it. - const scratch = await mkdtemp(path.join(tmpdir(), 'test-postgres-major-')); - const original = process.env.TMPDIR; - process.env.TMPDIR = scratch; - try { - // A server that starts anyway is stopped, and the test fails on the missing rejection. - const started = startPostgres({ major: asked }).then(async (server) => { - await server.stop(); - return server; - }); - await assert.rejects(started, (error: Error) => { - assert.match(error.message, new RegExp(`PostgreSQL ${installed}\\.\\d+`), 'names the version found'); - assert.match(error.message, new RegExp(`\\b${asked}\\b`), 'names the major asked for'); - assert.match(error.message, /mise\.toml/); - return true; - }); - assert.deepEqual(await readdir(scratch), [], 'nothing was initialised'); - } finally { - if (original === undefined) delete process.env.TMPDIR; - else process.env.TMPDIR = original; - await rm(scratch, { recursive: true, force: true }); - } + const { error, left } = await startThatFails(() => startPostgres({ major: asked })); + assert.ok(error, 'the start fails'); + assert.match(error.message, new RegExp(`PostgreSQL ${installed}\\.\\d+`), 'names the version found'); + assert.match(error.message, new RegExp(`\\b${asked}\\b`), 'names the major asked for'); + assert.match(error.message, /mise\.toml/); + assert.deepEqual(left, [], 'nothing was initialised'); }); diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts index 68ed700..0163acc 100644 --- a/packages/test-postgres/src/start.test.ts +++ b/packages/test-postgres/src/start.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { existsSync } from 'node:fs'; import path from 'node:path'; import { test } from 'node:test'; -import { askedMajor, query } from './fixtures/psql.ts'; +import { askedMajor, query } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; test('starts a server on a loopback port that answers, and stop() takes it down with its directory', async () => { From b2e011065124efb108ac55288597970d3671e251 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:31:45 +0100 Subject: [PATCH 24/43] test-postgres: a test that a failed start says what PostgreSQL said (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/start.test.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts index 0163acc..5d01777 100644 --- a/packages/test-postgres/src/start.test.ts +++ b/packages/test-postgres/src/start.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { existsSync } from 'node:fs'; import path from 'node:path'; import { test } from 'node:test'; -import { askedMajor, query } from './fixtures/support.ts'; +import { askedMajor, query, startThatFails } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; test('starts a server on a loopback port that answers, and stop() takes it down with its directory', async () => { @@ -45,3 +45,11 @@ test('settings are passed to the server', async () => { await server.stop(); } }); + +test('a start that fails says what PostgreSQL said, and leaves no directory', async () => { + const { error, left } = await startThatFails(() => + startPostgres({ major: askedMajor(), settings: { max_connections: 'many' } }), + ); + assert.match(error?.message ?? 'it started', /invalid value for parameter "max_connections"/); + assert.deepEqual(left, []); +}); From 3ff3bb581079729571e8592330242db07e38c7a7 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:32:35 +0100 Subject: [PATCH 25/43] test-postgres: a failed start carries the end of server.log Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 317a188..28825f3 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -10,6 +10,8 @@ // package's. It starts the server with pg_ctl on a free port on 127.0.0.1, // its socket in that directory, and returns the URL of the `postgres` // database. stop() shuts the server down at once and removes the directory. +// A start that fails removes the directory too, and its error carries the end +// of the server's log, where PostgreSQL says why. // // The cluster belongs to a supervisor, this file run as a detached Node // process, and not to the caller: the supervisor starts the cluster, reports @@ -66,7 +68,7 @@ import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { once } from 'node:events'; import { accessSync, constants, readFileSync } from 'node:fs'; -import { appendFile, chown, mkdtemp, rm } from 'node:fs/promises'; +import { appendFile, chown, mkdtemp, readFile, rm } from 'node:fs/promises'; import { createServer, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; import path from 'node:path'; @@ -253,7 +255,13 @@ async function startCluster(bin: string, owner: Owner | undefined, settings: Set path.join(data, 'postgresql.conf'), configuration({ fsync: 'off', ...settings, port, listen_addresses: '127.0.0.1', unix_socket_directories: dir }), ); - await run(pgCtl, ['-D', data, '-l', path.join(dir, 'server.log'), '-w', 'start'], owner); + const log = path.join(dir, 'server.log'); + await run(pgCtl, ['-D', data, '-l', log, '-w', 'start'], owner).catch(async (error: Error) => { + // pg_ctl says only that the server did not start; why is in the log, + // which goes with the directory. + const tail = (await readFile(log, 'utf8').catch(() => '')).trim().split('\n').slice(-20).join('\n'); + throw new Error(`${error.message}\nThe end of server.log:\n${tail}`); + }); return { url: `postgres://postgres@127.0.0.1:${port}/postgres`, async stop() { From eca23069e10c5f2f9fa2b375ea013479d11c68dc Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:34:00 +0100 Subject: [PATCH 26/43] test-postgres: tests of SIGTERM, SIGINT and SIGHUP to the supervisor (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/killed.test.ts | 63 ++++++++++++++++------- 1 file changed, 44 insertions(+), 19 deletions(-) diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts index c7673bc..231dbc6 100644 --- a/packages/test-postgres/src/killed.test.ts +++ b/packages/test-postgres/src/killed.test.ts @@ -7,18 +7,45 @@ import path from 'node:path'; import { createInterface } from 'node:readline'; import { test } from 'node:test'; import { askedMajor, query } from './fixtures/support.ts'; +import { startPostgres } from './index.ts'; + +function processes(): { pid: number; ppid: number; command: string }[] { + return execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'ppid=', '-o', 'command='], { encoding: 'utf8' }) + .split('\n') + .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)) + .filter((match) => match !== null) + .map(([, pid, ppid, command]) => ({ pid: Number(pid), ppid: Number(ppid), command: command ?? '' })); +} // The processes whose command line names the data directory: the server's // postmaster, as pg_ctl starts it. function serverProcesses(dataDirectory: string): number[] { - return execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'command='], { encoding: 'utf8' }) - .split('\n') - .filter((line) => line.includes(`-D ${dataDirectory}`)) - .map((line) => Number.parseInt(line, 10)); + return processes() + .filter(({ command }) => command.includes(`-D ${dataDirectory}`)) + .map(({ pid }) => pid); } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); +// Waits for the server of `dataDirectory` and its directory to go, and +// asserts that they went. A failing run takes down what it found, so that it +// leaves nothing behind. +async function assertGone(dataDirectory: string) { + const deadline = Date.now() + 15_000; + while ((serverProcesses(dataDirectory).length > 0 || existsSync(dataDirectory)) && Date.now() < deadline) { + await sleep(100); + } + const left = serverProcesses(dataDirectory); + try { + assert.deepEqual(left, [], 'no server process is left'); + assert.equal(existsSync(path.dirname(dataDirectory)), false, 'its directory is removed'); + } finally { + for (const pid of left) process.kill(pid, 'SIGQUIT'); + while (serverProcesses(dataDirectory).length > 0 && Date.now() < deadline + 15_000) await sleep(100); + await rm(path.dirname(dataDirectory), { recursive: true, force: true }); + } +} + test('it leaves no server running when the process that started it is killed with SIGKILL', async () => { const entry = new URL('./index.ts', import.meta.url).href; const script = [ @@ -37,19 +64,17 @@ test('it leaves no server running when the process that started it is killed wit parent.kill('SIGKILL'); const [, signal] = await once(parent, 'exit'); assert.equal(signal, 'SIGKILL'); - - const deadline = Date.now() + 15_000; - while ((serverProcesses(dataDirectory).length > 0 || existsSync(dataDirectory)) && Date.now() < deadline) { - await sleep(100); - } - const left = serverProcesses(dataDirectory); - try { - assert.deepEqual(left, [], 'no server process is left'); - assert.equal(existsSync(path.dirname(dataDirectory)), false, 'its directory is removed'); - } finally { - // A failing run takes down what it found, so that it leaves nothing behind. - for (const pid of left) process.kill(pid, 'SIGQUIT'); - while (serverProcesses(dataDirectory).length > 0 && Date.now() < deadline + 15_000) await sleep(100); - await rm(path.dirname(dataDirectory), { recursive: true, force: true }); - } + await assertGone(dataDirectory); }); + +for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) { + test(`a ${signal} to the supervisor stops the server and removes its directory`, async () => { + const server = await startPostgres({ major: askedMajor() }); + const dataDirectory = await query(server.url, 'show data_directory'); + const supervisor = processes().find(({ ppid, command }) => ppid === process.pid && command.includes('--supervise')); + assert.ok(supervisor, 'the supervisor is a child of this process, named by --supervise'); + process.kill(supervisor.pid, signal); + await assertGone(dataDirectory); + await server.stop().catch(() => {}); + }); +} From adad59aaf96285470491e7fa6aa6026ca2c3361d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:34:39 +0100 Subject: [PATCH 27/43] test-postgres: the supervisor stops on SIGTERM, SIGINT and SIGHUP too A supervisor whose start failed also lets go of its stdin, so that it exits rather than wait for a caller that will not close it. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 28825f3..2df32b6 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -18,7 +18,9 @@ // its URL on its stdout, and waits for the end of its stdin, whose other end // the caller holds. stop() closes that end; so does the kernel when the // caller exits or is killed, SIGKILL included, which no exit handler sees. -// Either way the supervisor shuts the server down and removes the directory. +// Either way the supervisor shuts the server down and removes the directory, +// and so it does on a SIGTERM, SIGINT or SIGHUP of its own. A SIGKILL of the +// supervisor itself cannot be handled and leaves the server running. // It runs in a session of its own, so that a Ctrl-C meant for the tests does // not take it down before it has cleaned up. The caller may exit without // calling stop(): nothing of the server keeps its event loop alive. @@ -182,16 +184,23 @@ function ownFile(): string { async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; settings: Settings }) { process.stdout.on('error', () => {}); const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); + // The end of stdin or one of these signals asks for the stop; one that + // comes during the start is answered once the start is over. + const stopAsked = new Promise((resolve) => { + process.stdin.on('end', resolve).on('error', resolve).resume(); + for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => resolve()); + }); let cluster: Cluster; try { cluster = await startCluster(bin, owner, settings); } catch (error) { report({ error: error instanceof Error ? error.message : String(error) }); process.exitCode = 1; + process.stdin.destroy(); return; } report({ url: cluster.url }); - for await (const _ of process.stdin); + await stopAsked; try { await cluster.stop(); report({ stopped: true }); From 3e0061a4bc697d55801c6210c9175ec4ea767473 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:34:57 +0100 Subject: [PATCH 28/43] test-postgres: a test of a database name that needs quoting and encoding (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/databases.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/packages/test-postgres/src/databases.test.ts b/packages/test-postgres/src/databases.test.ts index 78f4505..e79dd07 100644 --- a/packages/test-postgres/src/databases.test.ts +++ b/packages/test-postgres/src/databases.test.ts @@ -48,3 +48,15 @@ test('dropDatabase() drops the database its URL names, even with a session conne await lingering; assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(url)}'`), '0'); }); + +test('a name with a space and a double quote works as a template, and its URL drops it', async () => { + const name = 'odd "name" here'; + await query(server.url, `create database "odd ""name"" here"`); + const url = new URL(server.url); + url.pathname = `/${encodeURIComponent(name)}`; + await query(url.toString(), "create table t (v text); insert into t values ('from the odd one')"); + const copy = await createDatabase(server.url, { template: name }); + assert.equal(await query(copy, 'select v from t'), 'from the odd one'); + await dropDatabase(url.toString()); + assert.equal(await query(server.url, `select count(*) from pg_database where datname = 'odd "name" here'`), '0'); +}); From 62552d08be5ee7ca050fe5f9a7a234a6e43bb4a5 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:35:17 +0100 Subject: [PATCH 29/43] test-postgres: dropDatabase() decodes the name in the URL's path Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 2df32b6..57b2570 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -300,7 +300,7 @@ export async function createDatabase(url: string, options: { template?: string } /** Drops the database `url` names, closing the sessions connected to it. */ export async function dropDatabase(url: string): Promise { - const name = new URL(url).pathname.slice(1); + const name = decodeURIComponent(new URL(url).pathname.slice(1)); await sql(withDatabase(url, 'postgres'), `drop database if exists ${identifier(name)} with (force)`); } From 11fe26f8532a2d78e7355d68f7aeebed25b59837 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:35:41 +0100 Subject: [PATCH 30/43] test-postgres: a test of a server older than 17, with stand-in binaries (red) The stand-ins on the PATH now answer postgres --version with a version of the test's choosing, and initdb leaves a file when it runs. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/binaries.test.ts | 35 ++++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/packages/test-postgres/src/binaries.test.ts b/packages/test-postgres/src/binaries.test.ts index 6c7cb23..eed3a75 100644 --- a/packages/test-postgres/src/binaries.test.ts +++ b/packages/test-postgres/src/binaries.test.ts @@ -1,9 +1,10 @@ import assert from 'node:assert/strict'; +import { existsSync } from 'node:fs'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; import { afterEach, test } from 'node:test'; -import { askedMajor } from './fixtures/support.ts'; +import { askedMajor, startThatFails } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; const originalPath = process.env.PATH; @@ -14,15 +15,25 @@ afterEach(async () => { for (const dir of made.splice(0)) await rm(dir, { recursive: true, force: true }); }); -// A directory on its own as the PATH, holding stand-ins for the tools named. -async function pathWith(...tools: string[]) { +// A directory on its own as the PATH, holding stand-ins for the tools named: +// postgres answers --version with `version`, initdb leaves a file initdb-ran +// beside them, and the others do nothing. +async function pathWith(tools: string[], version = `${askedMajor()}.6`) { const dir = await mkdtemp(path.join(tmpdir(), 'test-postgres-path-')); made.push(dir); - for (const tool of tools) await writeFile(path.join(dir, tool), '#!/bin/sh\nexit 0\n', { mode: 0o755 }); + const scripts: Record = { + postgres: `echo "postgres (PostgreSQL) ${version}"`, + initdb: `touch "${dir}/initdb-ran"`, + }; + for (const tool of tools) { + await writeFile(path.join(dir, tool), `#!/bin/sh\n${scripts[tool] ?? 'exit 0'}\n`, { mode: 0o755 }); + } process.env.PATH = dir; return dir; } +const SERVER = ['initdb', 'pg_ctl', 'postgres', 'psql']; + const namesThePin = (major: number) => (error: Error) => { assert.match(error.message, new RegExp(`"conda:postgresql" = "${major}\\.`)); assert.match(error.message, /mise\.toml/); @@ -31,7 +42,7 @@ const namesThePin = (major: number) => (error: Error) => { test('without PostgreSQL on the PATH it fails naming the mise pin to add', async () => { const major = askedMajor(); - await pathWith(); + await pathWith([]); await assert.rejects(startPostgres({ major }), (error: Error) => { assert.match(error.message, /initdb/); return namesThePin(major)(error); @@ -40,7 +51,7 @@ test('without PostgreSQL on the PATH it fails naming the mise pin to add', async test('with a client-only install on the PATH it says so and names the mise pin', async () => { const major = askedMajor(); - const dir = await pathWith('psql', 'pg_dump'); + const dir = await pathWith(['psql', 'pg_dump']); await assert.rejects(startPostgres({ major }), (error: Error) => { assert.match(error.message, /client/); assert.ok(error.message.includes(dir), 'names where the client is'); @@ -50,7 +61,7 @@ test('with a client-only install on the PATH it says so and names the mise pin', test('with initdb but no server beside it it names what is missing and the mise pin', async () => { const major = askedMajor(); - await pathWith('initdb', 'psql'); + await pathWith(['initdb', 'psql']); await assert.rejects(startPostgres({ major }), (error: Error) => { assert.match(error.message, /pg_ctl/); assert.match(error.message, /\bpostgres\b/); @@ -63,10 +74,18 @@ test('it never falls back to a database from the environment', async () => { const running = await startPostgres({ major }); try { process.env.DATABASE_URL = running.url; - await pathWith(); + await pathWith([]); await assert.rejects(startPostgres({ major }), namesThePin(major)); } finally { process.env.PATH = originalPath; await running.stop(); } }); + +test('a server older than 17 fails before initdb, naming the version found', async () => { + const dir = await pathWith(SERVER, '16.9'); + const { error } = await startThatFails(() => startPostgres({ major: 16 })); + assert.match(error?.message ?? 'it started', /PostgreSQL 17 or later/); + assert.match(error?.message ?? '', /16\.9/); + assert.equal(existsSync(path.join(dir, 'initdb-ran')), false, 'initdb did not run'); +}); From f9e0bea10f38cd71fd7cd9d6b7f31f8c3955cbb0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:36:09 +0100 Subject: [PATCH 31/43] test-postgres: refuse a server older than 17 before initdb runs Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 57b2570..e953a4f 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -55,7 +55,8 @@ // The caller names the major it expects, and a server of another major on // the PATH fails the start before anything is initialised, so that a test // never passes against a version nobody pinned. It needs PostgreSQL 17 or -// later, the first with the builtin locale. +// later, the first with the builtin locale, and refuses an older server +// before initdb runs. // // PostgreSQL refuses to run as root. Where this process is root, as in a // container or a cloud session, the cluster's directory belongs to nobody and @@ -105,7 +106,13 @@ export async function startPostgres(options: StartOptions): Promise { ); }) ).match(/\(PostgreSQL\) (\S+)/)?.[1]; - if (Number.parseInt(version ?? '', 10) !== options.major) { + const found = Number.parseInt(version ?? '', 10); + if (found < 17 || options.major < 17) { + throw new Error( + `@plexus-ms/test-postgres needs PostgreSQL 17 or later, for the builtin locale; the server on the PATH is PostgreSQL ${version} (${bin}). ${pin(Math.max(options.major, 17))}`, + ); + } + if (found !== options.major) { throw new Error( `The server on the PATH is PostgreSQL ${version} (${bin}), but ${options.major} was asked for. ${pin(options.major)}`, ); From 147ce0ff1038244fc99069b7f95d98394f8ce489 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:36:26 +0100 Subject: [PATCH 32/43] test-postgres: a test of the settings that are refused (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/start.test.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts index 5d01777..344786e 100644 --- a/packages/test-postgres/src/start.test.ts +++ b/packages/test-postgres/src/start.test.ts @@ -53,3 +53,23 @@ test('a start that fails says what PostgreSQL said, and leaves no directory', as assert.match(error?.message ?? 'it started', /invalid value for parameter "max_connections"/); assert.deepEqual(left, []); }); + +test('settings the package sets itself, odd names, and values that are not a string or a number are refused', async () => { + const refused: Record[] = [ + { port: 5432 }, + { listen_addresses: '*' }, + { unix_socket_directories: '/tmp' }, + { cluster_name: undefined }, + { cluster_name: true }, + { cluster_name: ['a'] }, + { 'cluster name': 'a' }, + { cluster_name: 'a\nport = 1' }, + ]; + for (const settings of refused) { + const { error, left } = await startThatFails(() => + startPostgres({ major: askedMajor(), settings: settings as Record }), + ); + assert.match(error?.message ?? `it started with ${JSON.stringify(settings)}`, /setting/); + assert.deepEqual(left, []); + } +}); From 973573bb929e764144ed43b206ce641bfd623434 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:37:00 +0100 Subject: [PATCH 33/43] test-postgres: refuse the package's own settings and values of other types The settings are checked in the caller's process, before anything starts. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index e953a4f..b69b6e4 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -7,7 +7,7 @@ // machine, and without fsync, since the data lives for one run. The caller's // settings, such as max_connections for many test workers, go into its // postgresql.conf; the port, the address and the socket directory are the -// package's. It starts the server with pg_ctl on a free port on 127.0.0.1, +// package's, and a caller's setting of them is refused. It starts the server with pg_ctl on a free port on 127.0.0.1, // its socket in that directory, and returns the URL of the `postgres` // database. stop() shuts the server down at once and removes the directory. // A start that fails removes the directory too, and its error carries the end @@ -95,6 +95,7 @@ export interface Postgres { export async function startPostgres(options: StartOptions): Promise { if (process.env[SUPERVISOR] !== undefined) throw new Error(BUNDLED); const file = ownFile(); + const settings = checkSettings(options.settings ?? {}); const bin = findInstall(options.major); const owner = process.getuid?.() === 0 ? await unprivilegedUser() : undefined; const postgres = path.join(bin, 'postgres'); @@ -118,7 +119,7 @@ export async function startPostgres(options: StartOptions): Promise { ); } const supervisor = spawn(process.execPath, [file, '--supervise'], { - env: { ...process.env, [SUPERVISOR]: JSON.stringify({ bin, owner, settings: options.settings ?? {} }) }, + env: { ...process.env, [SUPERVISOR]: JSON.stringify({ bin, owner, settings }) }, detached: true, stdio: ['pipe', 'pipe', 'ignore'], }); @@ -368,16 +369,27 @@ function isExecutable(file: string): boolean { type Settings = Record; +// The settings the package writes itself, which a caller cannot change. +const OWN_SETTINGS = ['port', 'listen_addresses', 'unix_socket_directories']; + +// Refuses a caller's setting that the package sets itself, a name that is no +// parameter's, and a value that is not a string or a number on one line. +function checkSettings(settings: Record): Settings { + for (const [name, value] of Object.entries(settings)) { + if (OWN_SETTINGS.includes(name)) throw new Error(`The setting ${name} is the package's own`); + if (!/^[a-z_][a-z0-9_.]*$/i.test(name)) throw new Error(`Not a server setting: ${name}`); + if (!(typeof value === 'string' || typeof value === 'number') || /[\r\n]/.test(String(value))) { + throw new Error(`The setting ${name} needs a string or a number on one line, not ${JSON.stringify(value)}`); + } + } + return settings as Settings; +} + // Lines for postgresql.conf, where a later line wins over the defaults above // it: no shell and no command line sees a value. function configuration(settings: Settings): string { return Object.entries(settings) - .map(([name, value]) => { - if (!/^[a-z_][a-z0-9_.]*$/i.test(name) || /[\r\n]/.test(String(value))) { - throw new Error(`Not a server setting: ${name} = ${value}`); - } - return `${name} = '${String(value).replaceAll("'", "''")}'\n`; - }) + .map(([name, value]) => `${name} = '${String(value).replaceAll("'", "''")}'\n`) .join(''); } From d8778de0bba9d6915d55f66ec3c595ba0ed74535 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:38:29 +0100 Subject: [PATCH 34/43] test-postgres: tests of conditions the header states and no test held The server listens on 127.0.0.1 only with its socket in its own directory; a caller that ends without stop() is not held up and leaves nothing; a SIGINT or a SIGKILL to the caller's process group leaves nothing; the drop test's session outlasts the five seconds PostgreSQL waits; the environment's PG variables do not change where the calls connect; an install without psql fails with the pin; a lower and a higher major both fail. These pass as they are; each was seen to fail with its condition broken. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/binaries.test.ts | 21 ++++++++++ packages/test-postgres/src/databases.test.ts | 30 +++++++++++++- packages/test-postgres/src/killed.test.ts | 43 +++++++++++++++++--- packages/test-postgres/src/start.test.ts | 11 +++++ 4 files changed, 98 insertions(+), 7 deletions(-) diff --git a/packages/test-postgres/src/binaries.test.ts b/packages/test-postgres/src/binaries.test.ts index eed3a75..f1a608e 100644 --- a/packages/test-postgres/src/binaries.test.ts +++ b/packages/test-postgres/src/binaries.test.ts @@ -89,3 +89,24 @@ test('a server older than 17 fails before initdb, naming the version found', asy assert.match(error?.message ?? '', /16\.9/); assert.equal(existsSync(path.join(dir, 'initdb-ran')), false, 'initdb did not run'); }); + +test('an install without psql beside initdb fails naming psql and the mise pin', async () => { + const major = askedMajor(); + await pathWith(['initdb', 'pg_ctl', 'postgres']); + await assert.rejects(startPostgres({ major }), (error: Error) => { + assert.match(error.message, /psql/); + return namesThePin(major)(error); + }); +}); + +test('a server of a lower and one of a higher major than asked for both fail', async () => { + for (const version of ['17.4', '19.1']) { + await pathWith(SERVER, version); + const { error } = await startThatFails(() => startPostgres({ major: 18 })); + assert.match( + error?.message ?? `it started with ${version}`, + new RegExp(`PostgreSQL ${version.replace('.', '\\.')}`), + ); + assert.match(error?.message ?? '', /"conda:postgresql" = "18\./); + } +}); diff --git a/packages/test-postgres/src/databases.test.ts b/packages/test-postgres/src/databases.test.ts index e79dd07..20c7d2a 100644 --- a/packages/test-postgres/src/databases.test.ts +++ b/packages/test-postgres/src/databases.test.ts @@ -42,7 +42,8 @@ test('a database made from a template starts with its contents, even while a ses test('dropDatabase() drops the database its URL names, even with a session connected', async () => { const url = await createDatabase(server.url); - const lingering = promisify(execFile)('psql', ['-X', '-d', url, '-c', 'select pg_sleep(5)']).catch(() => {}); + // Longer than the five seconds PostgreSQL waits for a session to leave. + const lingering = promisify(execFile)('psql', ['-X', '-d', url, '-c', 'select pg_sleep(30)']).catch(() => {}); await new Promise((resolve) => setTimeout(resolve, 200)); await dropDatabase(url); await lingering; @@ -60,3 +61,30 @@ test('a name with a space and a double quote works as a template, and its URL dr await dropDatabase(url.toString()); assert.equal(await query(server.url, `select count(*) from pg_database where datname = 'odd "name" here'`), '0'); }); + +test('the PG variables of the environment do not change where the calls connect', async () => { + const variables = { + PGHOSTADDR: '127.0.0.2', + PGPORT: '1', + PGDATABASE: 'nowhere', + PGUSER: 'nobody_here', + PGSSLMODE: 'require', + PGCONNECT_TIMEOUT: '2', + }; + Object.assign(process.env, variables); + let made: string; + let other: Postgres; + try { + other = await startPostgres({ major: askedMajor() }); + made = await createDatabase(server.url); + await dropDatabase(made); + } finally { + for (const name of Object.keys(variables)) delete process.env[name]; + } + try { + assert.equal(await query(other.url, 'select 1'), '1'); + assert.equal(await query(server.url, `select count(*) from pg_database where datname = '${nameOf(made)}'`), '0'); + } finally { + await other.stop(); + } +}); diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts index 231dbc6..0e54db8 100644 --- a/packages/test-postgres/src/killed.test.ts +++ b/packages/test-postgres/src/killed.test.ts @@ -46,27 +46,58 @@ async function assertGone(dataDirectory: string) { } } -test('it leaves no server running when the process that started it is killed with SIGKILL', async () => { +// A caller in a process of its own: it starts a server, prints its data +// directory and then, unless told to end, waits. With `group` it leads a process group of +// its own, as a shell's foreground job does. +async function caller(options: { end?: boolean; group?: boolean } = {}) { const entry = new URL('./index.ts', import.meta.url).href; const script = [ + "import { execFileSync } from 'node:child_process';", `import { startPostgres } from ${JSON.stringify(entry)};`, `const server = await startPostgres({ major: ${askedMajor()} });`, - 'console.log(server.url);', - 'setInterval(() => {}, 60_000);', + "const show = ['-X', '-At', '-d', server.url, '-c', 'show data_directory'];", + "console.log(execFileSync('psql', show, { encoding: 'utf8' }).trim());", + options.end ? '' : 'setInterval(() => {}, 60_000);', ].join('\n'); const parent = spawn(process.execPath, ['--input-type=module', '-e', script], { stdio: ['ignore', 'pipe', 'inherit'], + detached: options.group ?? false, }); - const [url] = (await once(createInterface({ input: parent.stdout }), 'line')) as [string]; - const dataDirectory = await query(url, 'show data_directory'); + const exited = once(parent, 'exit'); + const [dataDirectory] = (await once(createInterface({ input: parent.stdout }), 'line')) as [string]; + return { parent, exited, dataDirectory }; +} + +test('it leaves no server running when the process that started it is killed with SIGKILL', async () => { + const { parent, exited, dataDirectory } = await caller(); assert.notDeepEqual(serverProcesses(dataDirectory), [], 'the server runs'); parent.kill('SIGKILL'); - const [, signal] = await once(parent, 'exit'); + const [, signal] = await exited; assert.equal(signal, 'SIGKILL'); await assertGone(dataDirectory); }); +test('a caller that ends without stop() is not held up, and leaves nothing', async () => { + const started = Date.now(); + const { exited, dataDirectory } = await caller({ end: true }); + const [code] = await Promise.race([exited, sleep(5_000).then(() => ['still running'])]); + assert.equal(code, 0, 'the caller ended by itself'); + assert.ok(Date.now() - started < 5_000); + await assertGone(dataDirectory); +}); + +// SIGINT is what a Ctrl-C sends to the foreground group; SIGKILL to a group is +// how a runner may end a job. +for (const signal of ['SIGINT', 'SIGKILL'] as const) { + test(`a ${signal} to the caller's process group leaves nothing`, async () => { + const { parent, exited, dataDirectory } = await caller({ group: true }); + process.kill(-(parent.pid ?? 0), signal); + await exited; + await assertGone(dataDirectory); + }); +} + for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) { test(`a ${signal} to the supervisor stops the server and removes its directory`, async () => { const server = await startPostgres({ major: askedMajor() }); diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts index 344786e..67a676a 100644 --- a/packages/test-postgres/src/start.test.ts +++ b/packages/test-postgres/src/start.test.ts @@ -73,3 +73,14 @@ test('settings the package sets itself, odd names, and values that are not a str assert.deepEqual(left, []); } }); + +test('the server listens on 127.0.0.1 only, its socket in its own directory', async () => { + const server = await startPostgres({ major: askedMajor() }); + try { + assert.equal(await query(server.url, 'show listen_addresses'), '127.0.0.1'); + const dataDirectory = await query(server.url, 'show data_directory'); + assert.equal(await query(server.url, 'show unix_socket_directories'), path.dirname(dataDirectory)); + } finally { + await server.stop(); + } +}); From 39781828144d8a2ac46835b5344d303ef0244fb4 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:58:19 +0100 Subject: [PATCH 35/43] test-postgres: a failed start's supervisor exits; held-up processes are ended The failed-start test now also asserts that the supervisor exits, and the test of a caller ending without stop() ends a caller that is held up, so that both fail cleanly with their condition broken instead of hanging the run. The process list moves into the shared fixtures. Co-Authored-By: Claude Fable 5.2 --- .../test-postgres/src/fixtures/support.ts | 20 ++++++++++++++++--- packages/test-postgres/src/killed.test.ts | 18 ++++++----------- packages/test-postgres/src/start.test.ts | 9 ++++++++- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/packages/test-postgres/src/fixtures/support.ts b/packages/test-postgres/src/fixtures/support.ts index 5e4ed14..f2bc0b3 100644 --- a/packages/test-postgres/src/fixtures/support.ts +++ b/packages/test-postgres/src/fixtures/support.ts @@ -1,7 +1,7 @@ // What the tests share: the major they ask for, a way to ask a server -// something with the psql on the PATH, so that the tests need no driver, and -// a way to watch a start that must fail. -import { execFile } from 'node:child_process'; +// something with the psql on the PATH, so that the tests need no driver, a +// way to watch a start that must fail, and the process list. +import { execFile, execFileSync } from 'node:child_process'; import { mkdtemp, readdir, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import path from 'node:path'; @@ -45,3 +45,17 @@ export async function startThatFails( await rm(scratch, { recursive: true, force: true }); } } + +/** The machine's processes, from ps. */ +export function processes(): { pid: number; ppid: number; command: string }[] { + return execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'ppid=', '-o', 'command='], { encoding: 'utf8' }) + .split('\n') + .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)) + .filter((match) => match !== null) + .map(([, pid, ppid, command]) => ({ pid: Number(pid), ppid: Number(ppid), command: command ?? '' })); +} + +/** The supervisors this process started, which --supervise names in the process list. */ +export function supervisors(): { pid: number; ppid: number; command: string }[] { + return processes().filter(({ ppid, command }) => ppid === process.pid && command.includes('--supervise')); +} diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts index 0e54db8..b58d465 100644 --- a/packages/test-postgres/src/killed.test.ts +++ b/packages/test-postgres/src/killed.test.ts @@ -1,22 +1,14 @@ import assert from 'node:assert/strict'; -import { execFileSync, spawn } from 'node:child_process'; +import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { existsSync } from 'node:fs'; import { rm } from 'node:fs/promises'; import path from 'node:path'; import { createInterface } from 'node:readline'; import { test } from 'node:test'; -import { askedMajor, query } from './fixtures/support.ts'; +import { askedMajor, processes, query, supervisors } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; -function processes(): { pid: number; ppid: number; command: string }[] { - return execFileSync('ps', ['-A', '-o', 'pid=', '-o', 'ppid=', '-o', 'command='], { encoding: 'utf8' }) - .split('\n') - .map((line) => line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)) - .filter((match) => match !== null) - .map(([, pid, ppid, command]) => ({ pid: Number(pid), ppid: Number(ppid), command: command ?? '' })); -} - // The processes whose command line names the data directory: the server's // postmaster, as pg_ctl starts it. function serverProcesses(dataDirectory: string): number[] { @@ -80,8 +72,10 @@ test('it leaves no server running when the process that started it is killed wit test('a caller that ends without stop() is not held up, and leaves nothing', async () => { const started = Date.now(); - const { exited, dataDirectory } = await caller({ end: true }); + const { parent, exited, dataDirectory } = await caller({ end: true }); const [code] = await Promise.race([exited, sleep(5_000).then(() => ['still running'])]); + // A caller held up is ended here, so that this process can end. + if (code === 'still running') parent.kill('SIGKILL'); assert.equal(code, 0, 'the caller ended by itself'); assert.ok(Date.now() - started < 5_000); await assertGone(dataDirectory); @@ -102,7 +96,7 @@ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) { test(`a ${signal} to the supervisor stops the server and removes its directory`, async () => { const server = await startPostgres({ major: askedMajor() }); const dataDirectory = await query(server.url, 'show data_directory'); - const supervisor = processes().find(({ ppid, command }) => ppid === process.pid && command.includes('--supervise')); + const [supervisor] = supervisors(); assert.ok(supervisor, 'the supervisor is a child of this process, named by --supervise'); process.kill(supervisor.pid, signal); await assertGone(dataDirectory); diff --git a/packages/test-postgres/src/start.test.ts b/packages/test-postgres/src/start.test.ts index 67a676a..642701b 100644 --- a/packages/test-postgres/src/start.test.ts +++ b/packages/test-postgres/src/start.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { existsSync } from 'node:fs'; import path from 'node:path'; import { test } from 'node:test'; -import { askedMajor, query, startThatFails } from './fixtures/support.ts'; +import { askedMajor, query, startThatFails, supervisors } from './fixtures/support.ts'; import { startPostgres } from './index.ts'; test('starts a server on a loopback port that answers, and stop() takes it down with its directory', async () => { @@ -52,6 +52,13 @@ test('a start that fails says what PostgreSQL said, and leaves no directory', as ); assert.match(error?.message ?? 'it started', /invalid value for parameter "max_connections"/); assert.deepEqual(left, []); + // Its supervisor exits too, rather than wait for this process to end. One + // that stays is ended here, so that this process can end. + const deadline = Date.now() + 5_000; + while (supervisors().length > 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 100)); + const lingering = supervisors(); + for (const { pid } of lingering) process.kill(pid, 'SIGKILL'); + assert.deepEqual(lingering, [], 'the supervisor exited'); }); test('settings the package sets itself, odd names, and values that are not a string or a number are refused', async () => { From 655562b620cbdd2789aa88043fed6ab11b6403fa Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 15:58:35 +0100 Subject: [PATCH 36/43] test-postgres: the header and the changeset say what the package does now Co-Authored-By: Claude Fable 5.2 --- .changeset/test-postgres.md | 3 ++- packages/test-postgres/src/index.ts | 11 ++++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/.changeset/test-postgres.md b/.changeset/test-postgres.md index 5aaf5f1..d208ace 100644 --- a/.changeset/test-postgres.md +++ b/.changeset/test-postgres.md @@ -4,5 +4,6 @@ A new package: a throwaway PostgreSQL server for tests, started from the binary on the PATH and removed afterwards. `startPostgres({ major })` initialises a cluster in a temporary directory and starts it on a free loopback port; `createDatabase()` gives each test file a database of its own, empty or copied from a template, and `dropDatabase()` drops one. -It fails with a message naming the mise pin to add when no server is on the PATH, and when the server is of another major than the one asked for. +It fails with a message naming the mise pin to add when no server is on the PATH, and when the server is of another major than the one asked for; it needs PostgreSQL 17 or later. As root it runs the server as `nobody`, and no server outlives the process that started it, even one killed with SIGKILL. +It must stay external to a bundle, and refuses to start when it is bundled into its caller's file. diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index b69b6e4..cce1b5a 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -7,9 +7,9 @@ // machine, and without fsync, since the data lives for one run. The caller's // settings, such as max_connections for many test workers, go into its // postgresql.conf; the port, the address and the socket directory are the -// package's, and a caller's setting of them is refused. It starts the server with pg_ctl on a free port on 127.0.0.1, -// its socket in that directory, and returns the URL of the `postgres` -// database. stop() shuts the server down at once and removes the directory. +// package's, and a caller's setting of them is refused. It starts the server +// with pg_ctl on a free port on 127.0.0.1, its socket in that directory, and +// returns the URL of the `postgres` database. stop() shuts the server down at once and removes the directory. // A start that fails removes the directory too, and its error carries the end // of the server's log, where PostgreSQL says why. // @@ -36,12 +36,13 @@ // createDatabase() makes a database of its own for each caller, so that test // files running in parallel share no state: an empty one, or a copy of a // template, such as a database the run migrated once, which PostgreSQL makes -// in well under a second. Copies made at once from one template do not wait +// in milliseconds. Copies made at once from one template do not wait // on each other; a session connected to the template makes PostgreSQL wait // for it to leave, about five seconds, and then refuse the copy with SQLSTATE // 55006, which the call passes on. // dropDatabase() drops one, closing the sessions still connected to it. Both -// speak to the server with the psql beside the server's binaries, and need no +// speak to the server with the psql beside the first initdb on the PATH when +// they are called, without the environment's PG variables, and need no // driver. // // The binaries are the first initdb on the PATH and the pg_ctl, postgres and From ca1e66f7e384eaa1890f16dbfaaf3bdf032f6e28 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:33:32 +0100 Subject: [PATCH 37/43] test-postgres: the major the tests ask for is PLX_POSTGRES_MAJOR The name the repo-turbo template sets, by the maintainer's decision. Co-Authored-By: Claude Fable 5.2 --- mise.toml | 4 ++-- packages/test-postgres/src/fixtures/as-root.ts | 2 +- packages/test-postgres/src/fixtures/support.ts | 6 +++--- packages/test-postgres/turbo.json | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/mise.toml b/mise.toml index 622e181..b9bc22e 100644 --- a/mise.toml +++ b/mise.toml @@ -9,7 +9,7 @@ hk = "latest" # The plx pins are written with each Plexus version, never by the update bot (§ 1 PLX-Updates); # allow_low_downloads only waives npm's young-package heuristics. "npm:@plexus-ms/cli" = { version = "0.133.0", allow_low_downloads = true } -# The server @plexus-ms/test-postgres starts in its own tests; POSTGRES_MAJOR below names its major. +# The server @plexus-ms/test-postgres starts in its own tests; PLX_POSTGRES_MAJOR below names its major. "conda:postgresql" = "18.6" [settings] @@ -25,7 +25,7 @@ postinstall = "if command -v hk >/dev/null; then hk install --mise; fi && npx co _.path = ["{{config_root}}/node_modules/.bin"] # The major the tests ask the server for: that of the conda:postgresql pin, which a wrong one fails. # Declared in turbo.json, so a new major runs the tests again. -POSTGRES_MAJOR = "18" +PLX_POSTGRES_MAJOR = "18" [tasks.dev] description = "No-op: a package repo has no development environment to start; build builds its packages and test exercises them" diff --git a/packages/test-postgres/src/fixtures/as-root.ts b/packages/test-postgres/src/fixtures/as-root.ts index 4848db2..21f3491 100644 --- a/packages/test-postgres/src/fixtures/as-root.ts +++ b/packages/test-postgres/src/fixtures/as-root.ts @@ -3,7 +3,7 @@ // unprivileged user cannot reach, and prints what it saw as one JSON line: // the server's user is nobody, the directory is removed, and the second start // fails naming nobody. -// In a container, from this package's directory: docker run --rm --cpus 2 --memory 2g --pids-limit 300 -v "$PWD":/pkg:ro -e POSTGRES_MAJOR=18 --entrypoint node /pkg/src/fixtures/as-root.ts +// In a container, from this package's directory: docker run --rm --cpus 2 --memory 2g --pids-limit 300 -v "$PWD":/pkg:ro -e PLX_POSTGRES_MAJOR=18 --entrypoint node /pkg/src/fixtures/as-root.ts import { execFileSync } from 'node:child_process'; import { existsSync, readFileSync, statSync } from 'node:fs'; import { mkdtemp, rm, symlink } from 'node:fs/promises'; diff --git a/packages/test-postgres/src/fixtures/support.ts b/packages/test-postgres/src/fixtures/support.ts index f2bc0b3..e07e0d6 100644 --- a/packages/test-postgres/src/fixtures/support.ts +++ b/packages/test-postgres/src/fixtures/support.ts @@ -7,10 +7,10 @@ import { tmpdir } from 'node:os'; import path from 'node:path'; import { promisify } from 'node:util'; -/** The major of the repo's PostgreSQL pin, which mise puts in POSTGRES_MAJOR. */ +/** The major of the repo's PostgreSQL pin, which mise puts in PLX_POSTGRES_MAJOR. */ export function askedMajor(): number { - const major = Number(process.env.POSTGRES_MAJOR); - if (!Number.isInteger(major)) throw new Error('POSTGRES_MAJOR names no major: run the tests through mise'); + const major = Number(process.env.PLX_POSTGRES_MAJOR); + if (!Number.isInteger(major)) throw new Error('PLX_POSTGRES_MAJOR names no major: run the tests through mise'); return major; } diff --git a/packages/test-postgres/turbo.json b/packages/test-postgres/turbo.json index 35c9361..6c0e160 100644 --- a/packages/test-postgres/turbo.json +++ b/packages/test-postgres/turbo.json @@ -3,7 +3,7 @@ "extends": ["//"], "tasks": { "test": { - "env": ["$TURBO_EXTENDS$", "POSTGRES_MAJOR"] + "env": ["$TURBO_EXTENDS$", "PLX_POSTGRES_MAJOR"] } } } From 134f1a117ceeaef34d2d2f8d8a3b5678d1d345e8 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:33:58 +0100 Subject: [PATCH 38/43] test-postgres: a test of a signal to the supervisor during the start (red) Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/killed.test.ts | 35 ++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts index b58d465..0643233 100644 --- a/packages/test-postgres/src/killed.test.ts +++ b/packages/test-postgres/src/killed.test.ts @@ -2,7 +2,8 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; import { existsSync } from 'node:fs'; -import { rm } from 'node:fs/promises'; +import { mkdtemp, readdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; import path from 'node:path'; import { createInterface } from 'node:readline'; import { test } from 'node:test'; @@ -103,3 +104,35 @@ for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP'] as const) { await server.stop().catch(() => {}); }); } + +test('a signal to the supervisor during the start fails the start and leaves nothing', async () => { + const scratch = await mkdtemp(path.join(tmpdir(), 'test-postgres-signal-')); + const original = process.env.TMPDIR; + process.env.TMPDIR = scratch; + const running = () => + processes() + .filter(({ command }) => command.includes(`-D ${scratch}`)) + .map(({ pid }) => pid); + try { + const started = startPostgres({ major: askedMajor() }).then(async (server) => { + await server.stop(); + return server.url; + }); + // The supervisor has begun the cluster: its directory exists, initdb runs. + const deadline = Date.now() + 15_000; + while ((await readdir(scratch)).length === 0 && Date.now() < deadline) await sleep(10); + const [supervisor] = supervisors(); + assert.ok(supervisor, 'the supervisor runs'); + process.kill(supervisor.pid, 'SIGTERM'); + await assert.rejects(started, /signal/); + while ((running().length > 0 || (await readdir(scratch)).length > 0) && Date.now() < deadline) await sleep(100); + assert.deepEqual(running(), [], 'no server process is left'); + assert.deepEqual(await readdir(scratch), [], 'no directory is left'); + } finally { + if (original === undefined) delete process.env.TMPDIR; + else process.env.TMPDIR = original; + for (const pid of running()) process.kill(pid, 'SIGQUIT'); + for (let i = 0; i < 100 && running().length > 0; i++) await sleep(100); + await rm(scratch, { recursive: true, force: true }); + } +}); From 5b5ec9cb5cca4bbc1980808e48bfc1cf40196077 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:39:54 +0100 Subject: [PATCH 39/43] test-postgres: a stop asked during the start fails the start A signal that reaches the supervisor while the cluster starts used to give the caller the URL of a server that was already going. The supervisor now stops the cluster once it is up, reports an error that names the signal, and lets go of its stdin so that it exits. The test also asserts that the supervisor exits, so that a supervisor left waiting fails it rather than hanging the run. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 27 ++++++++++++++++++----- packages/test-postgres/src/killed.test.ts | 11 ++++++++- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index cce1b5a..f3305fe 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -19,7 +19,8 @@ // the caller holds. stop() closes that end; so does the kernel when the // caller exits or is killed, SIGKILL included, which no exit handler sees. // Either way the supervisor shuts the server down and removes the directory, -// and so it does on a SIGTERM, SIGINT or SIGHUP of its own. A SIGKILL of the +// and so it does on a SIGTERM, SIGINT or SIGHUP of its own; one that comes +// during the start fails the start once the cluster is up and gone again. A SIGKILL of the // supervisor itself cannot be handled and leaves the server running. // It runs in a session of its own, so that a Ctrl-C meant for the tests does // not take it down before it has cleaned up. The caller may exit without @@ -193,11 +194,20 @@ function ownFile(): string { async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; settings: Settings }) { process.stdout.on('error', () => {}); const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); - // The end of stdin or one of these signals asks for the stop; one that - // comes during the start is answered once the start is over. + // The end of stdin or one of these signals asks for the stop. One that + // comes during the start is answered once the start is over, and the start + // then fails rather than hand out the URL of a server that is going. + let asked: string | undefined; const stopAsked = new Promise((resolve) => { - process.stdin.on('end', resolve).on('error', resolve).resume(); - for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => resolve()); + const ask = (reason: string) => { + asked ??= reason; + resolve(); + }; + process.stdin + .on('end', () => ask('the end of its stdin')) + .on('error', () => ask('an error on its stdin')) + .resume(); + for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => ask(`signal ${signal}`)); }); let cluster: Cluster; try { @@ -208,6 +218,13 @@ async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; process.stdin.destroy(); return; } + if (asked !== undefined) { + await cluster.stop().catch(() => {}); + report({ error: `The supervisor of the server was stopped by ${asked} during the start` }); + process.exitCode = 1; + process.stdin.destroy(); + return; + } report({ url: cluster.url }); await stopAsked; try { diff --git a/packages/test-postgres/src/killed.test.ts b/packages/test-postgres/src/killed.test.ts index 0643233..8650e76 100644 --- a/packages/test-postgres/src/killed.test.ts +++ b/packages/test-postgres/src/killed.test.ts @@ -125,9 +125,18 @@ test('a signal to the supervisor during the start fails the start and leaves not assert.ok(supervisor, 'the supervisor runs'); process.kill(supervisor.pid, 'SIGTERM'); await assert.rejects(started, /signal/); - while ((running().length > 0 || (await readdir(scratch)).length > 0) && Date.now() < deadline) await sleep(100); + while ( + (running().length > 0 || (await readdir(scratch)).length > 0 || supervisors().length > 0) && + Date.now() < deadline + ) { + await sleep(100); + } + // A supervisor that stays is ended here, so that this process can end. + const lingering = supervisors(); + for (const { pid } of lingering) process.kill(pid, 'SIGKILL'); assert.deepEqual(running(), [], 'no server process is left'); assert.deepEqual(await readdir(scratch), [], 'no directory is left'); + assert.deepEqual(lingering, [], 'the supervisor exited'); } finally { if (original === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = original; From 64a6911e8dde199f01226119e35e5808582301f0 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:40:45 +0100 Subject: [PATCH 40/43] test-postgres: a test of a bundle inside the package directory (red) The bundled test runs twice: in an app of its own, and in a directory whose package.json names this package, where the own-file check passes. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/bundled.test.ts | 23 ++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/packages/test-postgres/src/bundled.test.ts b/packages/test-postgres/src/bundled.test.ts index 7f14f57..f488b8d 100644 --- a/packages/test-postgres/src/bundled.test.ts +++ b/packages/test-postgres/src/bundled.test.ts @@ -16,17 +16,18 @@ const processesNaming = (text: string) => .map((line) => Number.parseInt(line, 10)); // A bundler puts the package's code and the caller's into one file, as here -// by hand: the package's source with a caller after it, in an app of its own. -// Every process that runs the file logs itself, and a process three levels -// down exits at once, so that a regression stays small. -test('bundled into the file of its caller it refuses to start, and starts nothing', { timeout: 60_000 }, async () => { +// by hand: the package's source with a caller after it, in a directory whose +// package.json names `owner`. Every process that runs the file logs itself, +// and a process three levels down exits at once, so that a regression stays +// small. +async function assertBundleRefused(owner: string) { const app = await mkdtemp(path.join(tmpdir(), 'test-postgres-bundle-')); const clusters = path.join(app, 'tmp'); const log = path.join(app, 'processes.log'); const file = path.join(app, 'app.ts'); try { await mkdir(clusters); - await writeFile(path.join(app, 'package.json'), '{ "name": "app", "type": "module" }\n'); + await writeFile(path.join(app, 'package.json'), `{ "name": "${owner}", "type": "module" }\n`); const caller = [ "import { appendFileSync } from 'node:fs';", 'const depth = Number(process.env.TEST_BUNDLE_DEPTH ?? 0);', @@ -64,7 +65,17 @@ test('bundled into the file of its caller it refuses to start, and starts nothin for (let i = 0; i < 50 && processesNaming(clusters).length > 0; i++) await sleep(100); await rm(app, { recursive: true, force: true }); } -}); +} + +test('bundled into the file of its caller it refuses to start, and starts nothing', { timeout: 60_000 }, () => + assertBundleRefused('app'), +); + +// The own-file check passes there, so the supervisor starts and has to find +// out for itself. +test('bundled into a file inside the package directory it refuses too, and leaves nothing', { timeout: 60_000 }, () => + assertBundleRefused('@plexus-ms/test-postgres'), +); test('a process the package marked as a supervisor refuses to start another server', async () => { process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR = '{}'; From 53da2bccb152621dffea0fcfdebf19d460f0934d Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:41:35 +0100 Subject: [PATCH 41/43] test-postgres: a bundle inside the package directory is refused and leaves nothing The own-file check is not widened. The supervisor lets a caller bundled into its file run first; that caller's startPostgres() writes the bundled message to the supervisor's stdout before it throws, and the supervisor, seeing the refusal, creates nothing. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index f3305fe..3b628af 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -32,7 +32,10 @@ // nearest package.json names another package). The supervisor is marked by // the environment variable PLEXUS_TEST_POSTGRES_SUPERVISOR, which the package // sets on it, and not by its command line, which a bundle may change; a -// process so marked refuses to start another server. +// process so marked refuses to start another server. A bundle placed inside +// the package's own directory gets past the own-file check; its supervisor +// lets the bundled caller run first, and when that caller is refused it +// reports the refusal and starts nothing. // // createDatabase() makes a database of its own for each caller, so that test // files running in parallel share no state: an empty one, or a copy of a @@ -72,7 +75,7 @@ import { type SpawnOptions, spawn } from 'node:child_process'; import { randomBytes } from 'node:crypto'; import { once } from 'node:events'; -import { accessSync, constants, readFileSync } from 'node:fs'; +import { accessSync, constants, readFileSync, writeSync } from 'node:fs'; import { appendFile, chown, mkdtemp, readFile, rm } from 'node:fs/promises'; import { createServer, type Socket } from 'node:net'; import { tmpdir } from 'node:os'; @@ -95,7 +98,13 @@ export interface Postgres { } export async function startPostgres(options: StartOptions): Promise { - if (process.env[SUPERVISOR] !== undefined) throw new Error(BUNDLED); + if (process.env[SUPERVISOR] !== undefined) { + // A supervisor whose file holds a caller too, a bundle the own-file check + // let through: its own caller hears why before this process dies of it. + if (supervising && !refused) writeSync(1, `${JSON.stringify({ error: BUNDLED })}\n`); + refused = true; + throw new Error(BUNDLED); + } const file = ownFile(); const settings = checkSettings(options.settings ?? {}); const bin = findInstall(options.major); @@ -191,7 +200,19 @@ function ownFile(): string { // The supervisor: this file run on its own, marked by SUPERVISOR. It starts the cluster and reports its URL, then waits // for the end of its stdin, and stops the cluster and removes its directory. +// Whether this process is a supervisor, and whether a startPostgres() in it +// refused to start. +let supervising = false; +let refused = false; + async function supervise({ bin, owner, settings }: { bin: string; owner?: Owner; settings: Settings }) { + supervising = true; + // A caller bundled into this file runs now, before anything is created. + await new Promise((resolve) => setImmediate(resolve)); + if (refused) { + process.exitCode = 1; + return; + } process.stdout.on('error', () => {}); const report = (line: Report) => process.stdout.write(`${JSON.stringify(line)}\n`); // The end of stdin or one of these signals asks for the stop. One that From 0425943f4e69fca9c2469fd08add13604a036465 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:41:50 +0100 Subject: [PATCH 42/43] test-postgres: the header's lines wrapped, and what the session of its own is for The supervisor's own session keeps a SIGKILL to the caller's process group from reaching it; a Ctrl-C would not take it down without the session, since it handles SIGINT itself. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/index.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/test-postgres/src/index.ts b/packages/test-postgres/src/index.ts index 3b628af..09d1a35 100644 --- a/packages/test-postgres/src/index.ts +++ b/packages/test-postgres/src/index.ts @@ -9,9 +9,10 @@ // postgresql.conf; the port, the address and the socket directory are the // package's, and a caller's setting of them is refused. It starts the server // with pg_ctl on a free port on 127.0.0.1, its socket in that directory, and -// returns the URL of the `postgres` database. stop() shuts the server down at once and removes the directory. -// A start that fails removes the directory too, and its error carries the end -// of the server's log, where PostgreSQL says why. +// returns the URL of the `postgres` database. stop() shuts the server down at +// once and removes the directory. A start that fails removes the directory +// too, and its error carries the end of the server's log, where PostgreSQL +// says why. // // The cluster belongs to a supervisor, this file run as a detached Node // process, and not to the caller: the supervisor starts the cluster, reports @@ -20,11 +21,12 @@ // caller exits or is killed, SIGKILL included, which no exit handler sees. // Either way the supervisor shuts the server down and removes the directory, // and so it does on a SIGTERM, SIGINT or SIGHUP of its own; one that comes -// during the start fails the start once the cluster is up and gone again. A SIGKILL of the -// supervisor itself cannot be handled and leaves the server running. -// It runs in a session of its own, so that a Ctrl-C meant for the tests does -// not take it down before it has cleaned up. The caller may exit without -// calling stop(): nothing of the server keeps its event loop alive. +// during the start fails the start once the cluster is up and gone again. A +// SIGKILL of the supervisor itself cannot be handled and leaves the server +// running. It runs in a session of its own, so that a SIGKILL to the caller's +// process group, as a runner may send to end a job, does not reach it. The +// caller may exit without calling stop(): nothing of the server keeps its +// event loop alive. // // So the package must stay a file of its own, external to any bundle: a // bundle that holds the caller's code too would run the caller again as the From c46c5e81e17f02af03c95299a34951554220ce80 Mon Sep 17 00:00:00 2001 From: David Julian Albers Date: Mon, 30 Nov 2026 16:46:37 +0100 Subject: [PATCH 43/43] test-postgres: a test of a bundled caller that catches the refusal With the refusal check in the supervisor removed, the suite passed: a caller that lets the error end its process ends the supervisor before the check matters. A caller that catches it and lives on is where the check counts; the test watches the cluster directory while the bundle runs. Co-Authored-By: Claude Fable 5.2 --- packages/test-postgres/src/bundled.test.ts | 28 +++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/test-postgres/src/bundled.test.ts b/packages/test-postgres/src/bundled.test.ts index f488b8d..9c990a8 100644 --- a/packages/test-postgres/src/bundled.test.ts +++ b/packages/test-postgres/src/bundled.test.ts @@ -19,8 +19,9 @@ const processesNaming = (text: string) => // by hand: the package's source with a caller after it, in a directory whose // package.json names `owner`. Every process that runs the file logs itself, // and a process three levels down exits at once, so that a regression stays -// small. -async function assertBundleRefused(owner: string) { +// small. With `caught`, the caller catches the refusal and lives on for two +// seconds, during which nothing may be created. +async function assertBundleRefused(owner: string, caught = false) { const app = await mkdtemp(path.join(tmpdir(), 'test-postgres-bundle-')); const clusters = path.join(app, 'tmp'); const log = path.join(app, 'processes.log'); @@ -34,8 +35,12 @@ async function assertBundleRefused(owner: string) { `appendFileSync(${JSON.stringify(log)}, \`\${depth}\\n\`);`, 'process.env.TEST_BUNDLE_DEPTH = String(depth + 1);', 'if (depth >= 2) process.exit(0);', + caught ? 'try {' : '', `const server = await startPostgres({ major: ${askedMajor()} });`, 'await server.stop();', + caught + ? '} catch (error) { console.error(String(error)); await new Promise((r) => setTimeout(r, 2_000)); process.exit(1); }' + : '', ].join('\n'); await writeFile(file, `${await readFile(new URL('./index.ts', import.meta.url), 'utf8')}\n${caller}\n`); @@ -47,8 +52,20 @@ async function assertBundleRefused(owner: string) { run.stderr.on('data', (chunk) => { stderr += chunk; }); - const exited = once(run, 'exit'); + let created = false; + let ended = false; + const exited = once(run, 'exit').finally(() => { + ended = true; + }); + const watched = (async () => { + while (!ended) { + created ||= (await readdir(clusters)).length > 0; + await sleep(50); + } + })(); const [code] = (await Promise.race([exited, sleep(20_000).then(() => ['timeout'])])) as [number | string]; + ended = true; + await watched; await sleep(1_000); const depths = (await readFile(log, 'utf8')).trim().split('\n').map(Number); @@ -58,6 +75,7 @@ async function assertBundleRefused(owner: string) { assert.match(stderr, /external/); assert.deepEqual(processesNaming(clusters), [], 'no server runs'); assert.deepEqual(await readdir(clusters), [], 'no cluster directory is left'); + assert.equal(created, false, 'no cluster directory was ever made'); } finally { // What a regression left: its processes, then its servers, then the files. for (const pid of processesNaming(file)) process.kill(pid, 'SIGKILL'); @@ -77,6 +95,10 @@ test('bundled into a file inside the package directory it refuses too, and leave assertBundleRefused('@plexus-ms/test-postgres'), ); +test('a caller in such a bundle that catches the refusal and lives on starts nothing either', { timeout: 60_000 }, () => + assertBundleRefused('@plexus-ms/test-postgres', true), +); + test('a process the package marked as a supervisor refuses to start another server', async () => { process.env.PLEXUS_TEST_POSTGRES_SUPERVISOR = '{}'; try {