The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
import { createHash, randomUUID } from 'node:crypto'
import { Readable } from 'node:stream'
import { text } from 'node:stream/consumers'
import { setTimeout as wait } from 'node:timers/promises'
import pg from 'pg'
import { MAX_ROWS, PgAppDatabase, PgPools, pgConnect, WIRE_TIMEOUT_MS } from './appdb'
import { connectUpstream, loginOf } from './dbproxy/pgwire'
import { csvHeader } from './dbtransfer'
jest.setTimeout(60000)
const describePostgres = process.env.DB_HOST ? describe : describe.skip
describePostgres('Hosted App PostgreSQL data plane', () => {
const root = new pg.Client({
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT || 5432),
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
})
const databases: string[] = []
const pools = new PgPools({ max: 1 })
const appdb = new PgAppDatabase(pools.acquire)
let source: string
async function newDatabase() {
const name = `app_test_${randomUUID().replaceAll('-', '')}`
await root.query(`CREATE DATABASE ${name}`)
databases.push(name)
const url = new URL('postgresql://localhost')
url.hostname = process.env.DB_HOST!
url.port = String(process.env.DB_PORT || 5432)
url.username = process.env.DB_USERNAME ?? ''
url.password = process.env.DB_PASSWORD ?? ''
url.pathname = name
return url.href
}
function readerUrl(owner: string) {
const url = new URL(owner)
url.searchParams.set('application_name', 'app-test-reader')
return Promise.resolve(url.href)
}
beforeAll(async () => {
await root.connect()
source = await newDatabase()
appdb.bindReaders({ urlFor: readerUrl, refresh: readerUrl })
})
afterAll(async () => {
await pools.close()
try {
for (const name of databases) await root.query(`DROP DATABASE ${name}`)
} finally {
await root.end()
}
})
const read = (sql: string) => appdb.query(source, [sql], { write: false })
const write = (sql: string) => appdb.query(source, [sql], { write: true })
it('authenticates a proxy session with the configured PostgreSQL login', async () => {
const upstream = await connectUpstream(loginOf(source), { application_name: 'app-test-proxy' })
try {
expect(upstream.pid).toBeGreaterThan(0)
expect(upstream.greeting.at(-1)?.toString('latin1', 0, 1)).toBe('Z')
} finally {
upstream.socket.destroy()
}
})
it('reuses a reset connection for each login and applies reader transaction settings', async () => {
const session =
"SELECT pg_backend_pid(), current_setting('application_name'), current_setting('transaction_read_only'), current_setting('statement_timeout')"
const reader = await read(session)
expect(reader.rows[0]).toEqual([expect.any(Number), 'app-test-reader', 'on', '15s'])
const owner = await write(session)
expect(owner.rows[0][0]).not.toEqual(reader.rows[0][0])
expect(owner.rows[0][2]).toBe('off')
await write("SET application_name = 'one-request'")
expect((await write(session)).rows).toEqual(owner.rows)
expect((await read(session)).rows).toEqual(reader.rows)
await expect(read('CREATE TABLE readonly_probe (n int)')).rejects.toMatchObject({
code: 'sql_error',
details: { sqlstate: '25006' },
})
})
it('reports the original statement error and removes an aborted session whose reset fails', async () => {
const pool = new PgPools({ idleMs: 50 })
try {
const conn = await pool.acquire(source)
let pid: unknown
try {
pid = (await conn.query('SELECT pg_backend_pid() AS pid')).rows[0].pid
await conn.query('BEGIN')
await expect(conn.query('SELECT 1 / 0')).rejects.toMatchObject({ code: '22012' })
await expect(conn.query('SELECT 1')).rejects.toMatchObject({ code: '22012' })
} finally {
await conn.end()
}
await conn.end()
const next = await pool.acquire(source)
try {
expect((await next.query('SELECT pg_backend_pid() AS pid')).rows[0].pid).not.toBe(pid)
} finally {
await next.end()
}
const deadline = Date.now() + 3000
while (pool.size && Date.now() < deadline) await wait(20)
expect(pool.size).toBe(0)
} finally {
await pool.close()
}
})
it('reprovisions a missing reader for an export and propagates a missing owner on import', async () => {
await write('CREATE TABLE catalog (label text)')
const missingLogin = new URL(source)
missingLogin.username = 'app_test_' + randomUUID().replaceAll('-', '')
const readers = { urlFor: async () => missingLogin.href, refresh: jest.fn(readerUrl) }
const transfers = new PgAppDatabase()
transfers.bindReaders(readers)
expect(await text(await transfers.exportCsv(source, 'catalog'))).toBe('label\n')
expect(readers.refresh).toHaveBeenCalledWith(source)
await expect(
transfers.importCsv(missingLogin.href, 'catalog', ['label'], Readable.from(['label\n'])),
).rejects.toMatchObject({ code: 'sql_error' })
await expect(pgConnect(missingLogin.href)).rejects.toMatchObject({ code: expect.stringMatching(/^28/) })
})
it('discards a connection whose query reaches the wire deadline', async () => {
const conn = await pools.acquire(source)
const [{ pid }] = (await conn.query('SELECT pg_backend_pid() AS pid')).rows
try {
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] })
const pending = expect(conn.query('SELECT 1')).rejects.toMatchObject({
code: 'unavailable',
message: expect.stringContaining('did not answer'),
})
jest.advanceTimersByTime(WIRE_TIMEOUT_MS)
await pending
} finally {
jest.useRealTimers()
await conn.end()
}
const replacement = await pools.acquire(source)
try {
expect((await replacement.query('SELECT pg_backend_pid() AS pid')).rows[0].pid).not.toBe(pid)
} finally {
await replacement.end()
}
})
it('returns the last result and counts all affected rows even after truncation', async () => {
await write('CREATE TABLE tally (n int)')
const inserted = await appdb.query(source, ['INSERT INTO tally SELECT generate_series(1, $1) RETURNING n'], {
write: true,
params: [MAX_ROWS + 23],
})
expect(inserted).toMatchObject({ columns: ['n'], row_count: MAX_ROWS + 23, truncated: true })
expect(inserted.rows).toHaveLength(MAX_ROWS)
expect((await read('SELECT count(*)::int FROM tally')).rows).toEqual([[MAX_ROWS + 23]])
expect(await read(`SELECT n FROM tally LIMIT ${MAX_ROWS}`)).toMatchObject({ row_count: MAX_ROWS, truncated: false })
expect(await read('SELECT n FROM tally')).toMatchObject({ row_count: MAX_ROWS, truncated: true })
const last = await appdb.query(source, ['SELECT n FROM tally', 'SELECT 42 AS result'], { write: false })
expect(last).toMatchObject({ columns: ['result'], rows: [[42]] })
const changed = await appdb.query(source, ['UPDATE tally SET n = n + 1 RETURNING n', 'DELETE FROM tally'], {
write: true,
})
expect(changed).toMatchObject({ columns: [], rows: [], row_count: MAX_ROWS + 23 })
await expect(read('SELECT FROM FROM')).rejects.toMatchObject({
code: 'sql_error',
details: { sqlstate: '42601', position: 13 },
})
})
it('atomically applies versioned files and copies their original deployment records to a new branch', async () => {
const parent = await newDatabase()
const branch = await newDatabase()
const sql = 'CREATE TABLE customers (id int PRIMARY KEY)'
const migration = { file: '0001_customers.sql', sql, sha256: createHash('sha256').update(sql).digest('hex') }
expect(await appdb.copyMigrationLedger(parent, branch)).toBe(0)
await appdb.applyMigration(parent, migration, 8)
await appdb.applyMigration(parent, migration, 9)
const ledger = await appdb.listApplied(parent)
expect(ledger).toEqual([
{ file: migration.file, sha256: migration.sha256, deployment: 8, applied_at: expect.any(String) },
])
await expect(appdb.applyMigration(parent, { ...migration, sha256: 'changed' }, 10)).rejects.toMatchObject({
code: 'invalid_manifest',
})
await expect(
appdb.applyMigration(
parent,
{
file: '0002_invalid.sql',
sql: 'CREATE TABLE orders (id int); SELECT 1 / 0',
sha256: 'invalid',
},
11,
),
).rejects.toMatchObject({ code: 'deploy_failed' })
expect((await appdb.query(parent, ["SELECT to_regclass('public.orders')"], { write: false })).rows).toEqual([
[null],
])
expect(await appdb.copyMigrationLedger(parent, branch)).toBe(1)
await appdb.copyMigrationLedger(parent, branch)
expect(await appdb.listApplied(branch)).toEqual(ledger)
})
it('streams CSV in both directions and rolls back all rows on a late constraint error', async () => {
await write('CREATE TABLE addresses ("Display name" text UNIQUE, city text)')
const csv = '"Display name",city\r\n"Friends, Inc.",Tokyo\r\n'
const input = await csvHeader(Readable.from([csv.slice(0, 5), csv.slice(5, 25), csv.slice(25)]))
expect(await appdb.importCsv(source, 'addresses', input.columns, input.stream)).toBe(1)
const invalid = Readable.from(['"Display name",city\nAnother,Kyoto\n"Friends, Inc.",Tokyo\n'])
await expect(appdb.importCsv(source, 'addresses', input.columns, invalid)).rejects.toMatchObject({
code: 'sql_error',
details: { sqlstate: '23505' },
})
expect(await text(await appdb.exportCsv(source, 'addresses'))).toBe('Display name,city\n"Friends, Inc.",Tokyo\n')
})
it('restores a full SQL stream with generated data, sequences, dependencies and views', async () => {
const original = await newDatabase()
const restored = await newDatabase()
const client = await pgConnect(original)
try {
await client.query(`
CREATE TYPE grade AS ENUM ('first', 'other');
CREATE TABLE empty_marker ();
CREATE SEQUENCE invoice_cycle CYCLE;
CREATE TABLE drafts (id int GENERATED BY DEFAULT AS IDENTITY);
ALTER TABLE drafts ENABLE ROW LEVEL SECURITY;
ALTER TABLE drafts FORCE ROW LEVEL SECURITY;
CREATE POLICY editable ON drafts FOR INSERT TO CURRENT_USER WITH CHECK (id > 0);
CREATE TABLE products (id serial PRIMARY KEY, label text NOT NULL);
INSERT INTO products (label) VALUES ('O''Brien');
CREATE TABLE sales (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product int NOT NULL REFERENCES products,
rating grade DEFAULT 'first',
total int NOT NULL CHECK (total > 0),
tax int GENERATED ALWAYS AS (total / 10) STORED
);
INSERT INTO sales (product, total) SELECT 1, n FROM generate_series(1, 101) n;
CREATE INDEX sales_total ON sales(total);
CREATE VIEW high_sales AS SELECT id FROM sales WHERE total > 99;
CREATE MATERIALIZED VIEW totals AS SELECT sum(total)::int AS n FROM sales;
CREATE FUNCTION trim_label() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN NEW.label := trim(NEW.label); RETURN NEW; END $$;
CREATE TRIGGER label BEFORE INSERT ON products FOR EACH ROW EXECUTE FUNCTION trim_label();
ALTER TABLE sales ENABLE ROW LEVEL SECURITY;
CREATE POLICY readable ON sales FOR SELECT USING (total > 0);
`)
const dump = await text(await appdb.exportSql(original, { title: 'sales' }))
const replica = await pgConnect(restored)
try {
await replica.query(dump)
expect((await replica.query('SELECT id, total, tax, rating FROM sales ORDER BY id DESC LIMIT 1')).rows).toEqual(
[{ id: 101, total: 101, tax: 10, rating: 'first' }],
)
expect((await replica.query('SELECT id FROM high_sales ORDER BY id')).rows).toEqual([{ id: 100 }, { id: 101 }])
expect((await replica.query('SELECT n FROM totals')).rows).toEqual([{ n: 5151 }])
expect((await replica.query("SELECT nextval('invoice_cycle')::int AS n")).rows).toEqual([{ n: 1 }])
expect(
(await replica.query("SELECT relforcerowsecurity FROM pg_class WHERE oid = 'drafts'::regclass")).rows,
).toEqual([{ relforcerowsecurity: true }])
expect(
(
await replica.query(
"SELECT roles::text[] = ARRAY[current_user::text] AS scoped FROM pg_policies WHERE tablename = 'drafts'",
)
).rows,
).toEqual([{ scoped: true }])
expect(
(
await replica.query(
"SELECT identity_generation FROM information_schema.columns WHERE table_name = 'drafts'",
)
).rows,
).toEqual([{ identity_generation: 'BY DEFAULT' }])
expect((await replica.query("SELECT to_regclass('empty_marker') AS name")).rows).toEqual([
{ name: 'empty_marker' },
])
expect(
(await replica.query("INSERT INTO products(label) VALUES (' new ') RETURNING id, label")).rows,
).toEqual([{ id: 2, label: 'new' }])
expect((await replica.query('INSERT INTO sales(product,total) VALUES (2,10) RETURNING id')).rows).toEqual([
{ id: 102 },
])
await expect(replica.query('INSERT INTO sales(product,total) VALUES (999,10)')).rejects.toMatchObject({
code: '23503',
})
expect((await replica.query("SELECT policyname FROM pg_policies WHERE tablename='sales'")).rows).toEqual([
{ policyname: 'readable' },
])
expect((await replica.query("SELECT to_regclass('sales_total') AS idx")).rows).toEqual([{ idx: 'sales_total' }])
} finally {
await replica.end()
}
const one = await text(await appdb.exportSql(original, { table: 'products', title: 'products' }))
expect(one).toContain('CREATE TABLE public."products"')
expect(one).not.toContain('CREATE TABLE public."sales"')
} finally {
await client.end()
}
})
})