Skip to content
Source
Sign inSign up
samwillis/neon-durable-streams
Open History to see the last commit

measure-postgres-metadata.mjs

94 lines8.1 KB

1import { createHash, randomUUID } from 'node:crypto'
2import { execFileSync } from 'node:child_process'
3import { mkdir, readFile, writeFile } from 'node:fs/promises'
4import { createRequire } from 'node:module'
5import { dirname, join } from 'node:path'
6import { fileURLToPath, pathToFileURL } from 'node:url'
7​
8// Research only: no objects are uploaded. All SQL uses a fresh disposable
9// schema on the recorded Neon test branch; existing data/stats are untouched.
10const root = fileURLToPath(new URL('../../', import.meta.url))
11const require = createRequire(join(root, 'package.json'))
12const pg = require('pg')
13// This experiment measures the archived per-append layout, not today's schema.
14const artifacts = JSON.parse(await readFile(join(root, '.neon-test-state-rolling-artifacts.json'), 'utf8')).artifacts
15if (artifacts.baseline?.commit !== '1ba871b2495ceb0a988676c314886384446506a2') throw new Error('Prepare archived package artifacts as documented in docs/experiments/README.md')
16const { migrate } = await import(pathToFileURL(join(artifacts.baseline.packageRoot, 'dist/migrations.js')).href)
17const env = process.env
18if (!env.TEST_DATABASE_URL_UNPOOLED || !env.NEON_TEST_BRANCH_ID) throw new Error('Recorded disposable Neon test environment required')
19const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? join(root, '.neon-test-state-smoke.json'), 'utf8'))
20if (state.branchId !== env.NEON_TEST_BRANCH_ID || !state.name?.startsWith('ds-test-')
21 || !new URL(env.TEST_DATABASE_URL_UNPOOLED).hostname.endsWith('.neon.tech')) throw new Error('Refusing measurement outside the recorded Neon test branch')
22const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 1, connectionTimeoutMillis: 20_000, query_timeout: 60_000 })
23pool.on('error', () => {})
24const schemas = [], samples = []
25let cleanupComplete = false
26const rows = 65_536, payloadBytes = 32, stride = payloadBytes + 5
27const column = '0000000000000000_' // The existing wire-offset representation.
28const quote = (name) => { if (!/^ds_test_[a-f0-9]{32}$/.test(name)) throw new Error('Invalid owned schema'); return `"${name}"` }
29try {
30 const version = (await pool.query("SELECT current_setting('server_version_num') AS version")).rows[0].version
31 if (Number(version) < 180000) throw new Error('Neon Postgres 18 required')
32 for (const framesPerChunk of [128, 1024]) {
33 const schema = `ds_test_${randomUUID().replaceAll('-', '')}`, sql = quote(schema), streamId = randomUUID()
34 schemas.push(schema)
35 await migrate(pool, { schema, storageIdentity: 'synthetic-metadata-measurement', environmentId: env.NEON_TEST_BRANCH_ID })
36 await pool.query('BEGIN')
37 try {
38 await pool.query("SET LOCAL statement_timeout='60s'; SET LOCAL lock_timeout='5s'; SET LOCAL transaction_timeout='120s'")
39 await pool.query(`INSERT INTO ${sql}.paths (tenant_id,path) VALUES ('measurement','stream')`)
40 await pool.query(`INSERT INTO ${sql}.streams (id,tenant_id,path,content_type,tail_offset)
41 VALUES ($1,'measurement','stream','application/octet-stream',$2)`, [streamId, column + String(rows * stride).padStart(16, '0')])
42 await pool.query(`UPDATE ${sql}.paths SET active_stream_id=$1`, [streamId])
43 await pool.query(`INSERT INTO ${sql}.chunks (id,stream_id,start_offset,end_offset,state,frame_count,payload_bytes,object_key,sha256,encoded_bytes,sealed_at)
44 SELECT md5($1::text||':'||n::text)::uuid,$1::uuid,$2||lpad((n*$3*$4)::text,16,'0'),$2||lpad(((n+1)*$3*$4)::text,16,'0'),
45 'sealed',$3,$3*$5,'v1/'||i.id::text||'/'||$1::text||'/'||md5($1::text||':'||n::text)::uuid::text||'/'||repeat('0',64)||'.ndsc',repeat('0',64),60+$3*(74+$5),clock_timestamp()
46 FROM generate_series(0,$6::int-1) AS n CROSS JOIN ${sql}.installation i`, [streamId, column, framesPerChunk, stride, payloadBytes, rows / framesPerChunk])
47 await pool.query(`INSERT INTO ${sql}.appends (stream_id,start_offset,end_offset,payload,payload_bytes,chunk_id)
48 SELECT $1::uuid,$2||lpad((n*$3)::text,16,'0'),$2||lpad(((n+1)*$3)::text,16,'0'),NULL,$4,md5($1::text||':'||(n/$5)::text)::uuid
49 FROM generate_series(0,$6::int-1) AS n`, [streamId, column, stride, payloadBytes, framesPerChunk, rows])
50 await pool.query(`INSERT INTO ${sql}.chunk_objects (object_key,stream_id,chunk_id,sha256,encoded_bytes)
51 SELECT object_key,stream_id,id,sha256,encoded_bytes FROM ${sql}.chunks`)
52 // Alternative research layout: one exact cumulative end-delta directory
53 // per manifest. This array is not used by the implementation today.
54 await pool.query(`CREATE TABLE ${sql}.directories (chunk_id uuid PRIMARY KEY REFERENCES ${sql}.chunks(id), end_deltas integer[] NOT NULL)`)
55 await pool.query(`INSERT INTO ${sql}.directories SELECT id,ARRAY(SELECT n*$1 FROM generate_series(1,$2) n) FROM ${sql}.chunks`, [stride, framesPerChunk])
56 // Copy the actual manifest columns/indexes so the proposed embedded
57 // layout is measured too. LIKE does not copy foreign keys; those do not
58 // add a relation/index here and are not part of this footprint comparison.
59 await pool.query(`CREATE TABLE ${sql}.packed_chunks (LIKE ${sql}.chunks INCLUDING ALL)`)
60 await pool.query(`ALTER TABLE ${sql}.packed_chunks ADD COLUMN end_deltas integer[] NOT NULL`)
61 await pool.query(`INSERT INTO ${sql}.packed_chunks SELECT c.*,ARRAY(SELECT n*$1 FROM generate_series(1,$2) n) FROM ${sql}.chunks c`, [stride, framesPerChunk])
62 await pool.query('COMMIT')
63 } catch (error) { await pool.query('ROLLBACK'); throw error }
64 const relations = []
65 for (const name of ['appends', 'chunks', 'chunk_objects', 'directories', 'packed_chunks']) {
66 const relation = `${sql}."${name}"`
67 const counts = (await pool.query(`SELECT count(*)::int AS rows,COALESCE(sum(pg_column_size(t)),0)::bigint AS tuple_bytes FROM ${relation} t`)).rows[0]
68 const sizes = (await pool.query('SELECT pg_relation_size($1::regclass)::bigint AS heap_bytes,pg_indexes_size($1::regclass)::bigint AS index_bytes,pg_total_relation_size($1::regclass)::bigint AS total_bytes', [relation])).rows[0]
69 relations.push({ relation: name, rows: counts.rows, tupleBytes: Number(counts.tuple_bytes), heapBytes: Number(sizes.heap_bytes), indexBytes: Number(sizes.index_bytes), totalBytes: Number(sizes.total_bytes) })
70 }
71 const byName = Object.fromEntries(relations.map((value) => [value.relation, value]))
72 const current = byName.appends.totalBytes + byName.chunks.totalBytes + byName.chunk_objects.totalBytes
73 const manifests = byName.chunks.totalBytes + byName.chunk_objects.totalBytes
74 // Keep the separate-table comparison, but use the measured embedded layout
75 // for the recommendation: TOAST/page effects are not strictly monotonic.
76 samples.push({ framesPerChunk, sealedAppendRows: rows, chunks: rows / framesPerChunk, payloadBytes,
77 relations, currentMetadataBytes: current, manifestsAndLedgerBytes: manifests,
78 manifestsLedgerAndSeparateDirectoriesBytes: manifests + byName.directories.totalBytes,
79 packedManifestsAndLedgerBytes: byName.packed_chunks.totalBytes + byName.chunk_objects.totalBytes,
80 idealPackedBoundaryBytes: rows * 4,
81 excludes: ['payload bytes in Object Storage', 'other fixed/producer/subscription tables', 'prior MVCC versions, vacuum overhead, WAL and provider history', 'new-reader or write-throughput benchmark'] })
82 }
83} finally {
84 try { for (const schema of schemas) await pool.query(`DROP SCHEMA IF EXISTS ${quote(schema)} CASCADE`); cleanupComplete = true }
85 finally { await pool.end() }
87const output = process.argv[2] ?? '/tmp/neon-postgres-metadata-baseline.json'
88await mkdir(dirname(output), { recursive: true })
89const report = { generatedAt: new Date().toISOString(), sourceCommit: execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(),
90 harnessSha256: createHash('sha256').update(await readFile(fileURLToPath(import.meta.url))).digest('hex'),
91 node: process.version, region: env.AWS_REGION, storage: 'Synthetic sealed baseline in pinned schema 0007 on actual Neon Postgres 18',
92 objectUploads: 0, cleanupComplete, samples }
93await writeFile(output, JSON.stringify(report, null, 2)+'\n')
94console.log(JSON.stringify(report))