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

measure-compact-storage.mjs

242 lines10.4 KB

1import { createHash, randomUUID } from 'node:crypto'
2import { readFile, writeFile } from 'node:fs/promises'
3import { pathToFileURL } from 'node:url'
4import pg from 'pg'
5import { createS3ChunkStorage } from '../../dist/s3.js'
6import { advanceOffset, ZERO_OFFSET } from '../../dist/offset.js'
7​
8// Run after preparing independently packed artifacts with
9// scripts/neon-test-rolling-artifacts.mjs 1ba871b2495ceb0a988676c314886384446506a2. Uses fresh random schemas and exact
10// owned keys only. No statistics resets, extension installation or VACUUM FULL.
11const env = process.env
12const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json', 'utf8'))
13if (
14 !state.name?.startsWith('ds-test-') ||
15 state.branchId !== env.NEON_TEST_BRANCH_ID ||
16 !new URL(env.TEST_DATABASE_URL_UNPOOLED).hostname.endsWith('.neon.tech')
18 throw new Error('Recorded disposable Neon environment required')
19const artifacts = JSON.parse(await readFile('.neon-test-state-rolling-artifacts.json', 'utf8')).artifacts
20if (artifacts.baseline?.commit !== '1ba871b2495ceb0a988676c314886384446506a2') throw new Error('Unexpected baseline')
21const base = createS3ChunkStorage({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, bucket: env.NEON_TEST_BUCKET })
22const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 1, connectionTimeoutMillis: 20_000, query_timeout: 60_000 })
23pool.on('error', () => {})
24let calls = 0,
25 connection
26pool.on('connect', (client) => {
27 connection = client.connection.stream
28 const original = client.query.bind(client)
29 client.query = (...args) => {
30 calls++
31 return original(...args)
32 }
33})
34const samples = [],
35 schemas = [],
36 keys = []
37const rows = 8192,
38 batchSize = 4096,
39 ordinary = 64
40const payload = (i) => String.fromCharCode(97 + (i % 26)).repeat(i < ordinary ? 32 : (i % 63) + 1)
41const expected = createHash('sha256')
42for (let i = 0; i < rows; i++) expected.update(payload(i))
43const expectedDigest = expected.digest('hex')
44let cleanupComplete = false
45try {
46 for (const [kind, framesPerChunk] of [
47 ['baseline', 128],
48 ['current', 128],
49 ['current', 1024],
50 ]) {
51 const artifact = artifacts[kind]
52 const api = await import(pathToFileURL(`${artifact.packageRoot}/dist/index.js`).href)
53 const migrations = await import(pathToFileURL(`${artifact.packageRoot}/dist/migrations.js`).href)
54 const schema = `ds_test_${randomUUID().replaceAll('-', '')}`,
55 sql = `"${schema}"`
56 schemas.push(schema)
57 const objectCounts = { gets: 0, getBytes: 0, puts: 0, putBytes: 0 }
58 const objects = {
59 ...base,
60 async get(key, max) {
61 const bytes = await base.get(key, max)
62 objectCounts.gets++
63 objectCounts.getBytes += bytes.length
64 return bytes
65 },
66 async put(key, bytes) {
67 keys.push(key)
68 objectCounts.puts++
69 objectCounts.putBytes += bytes.length
70 await base.put(key, bytes)
71 },
72 }
73 await migrations.migrate(pool, { schema, storageIdentity: objects.identity })
74 const errors = []
75 const server = api.createDurableStreams({
76 postgres: { pool, schema },
77 storage: { objects, maxChunkFrames: framesPerChunk },
78 auth: { authenticate: () => ({ tenantId: 'measure', subject: 'fixture' }), authorize: () => true },
79 onError: (error) => errors.push(error.name),
80 })
81 const request = (method, body, path = 'data') =>
82 server.fetch(
83 new Request(`https://fixture.test/v1/stream/${path}`, {
84 method,
85 headers: { 'Content-Type': 'text/plain' },
86 ...(body === undefined ? {} : { body }),
87 }),
88 )
89 try {
90 if ((await request('PUT')).status !== 201) throw new Error('Measurement stream creation failed')
91 const id = (await pool.query(`SELECT id FROM ${sql}.streams WHERE path='data'`)).rows[0].id
92 const lsn = (await pool.query('SELECT pg_current_wal_insert_lsn() AS lsn')).rows[0].lsn
93 const appendStarted = performance.now(),
94 beforeCalls = calls
95 for (let i = 0; i < ordinary; i++) if ((await request('POST', payload(i))).status !== 204) throw new Error('Ordinary append failed')
96 const appendDurationMs = performance.now() - appendStarted,
97 appendSqlCalls = calls - beforeCalls
98 const appendWalBytes = Number((await pool.query('SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),$1) AS bytes', [lsn])).rows[0].bytes)
99 await pool.query('SELECT pg_stat_force_next_flush()')
100 const headStats = (
101 await pool.query(`SELECT n_tup_upd::text,n_tup_hot_upd::text FROM pg_stat_user_tables WHERE schemaname=$1 AND relname='streams'`, [schema])
102 ).rows[0]
103 let offset = ZERO_OFFSET
104 for (let i = 0; i < ordinary; i++) offset = advanceOffset(offset, payload(i).length)
105 const sealingStarted = performance.now()
106 for (let batch = 0; batch < rows / batchSize; batch++) {
107 const from = batch === 0 ? ordinary : batch * batchSize,
108 to = (batch + 1) * batchSize,
109 frames = []
110 for (let i = from; i < to; i++) {
111 const part = Buffer.from(payload(i)),
112 start = offset
113 offset = advanceOffset(offset, part.length)
114 frames.push({ start, end: offset, bytes: part.length, payload: part.toString('hex') })
115 }
116 await pool.query('BEGIN')
117 try {
118 await pool.query(
119 `INSERT INTO ${sql}.appends(stream_id,start_offset,end_offset,payload,payload_bytes)
120 SELECT $1,x.start,x.end,decode(x.payload,'hex'),x.bytes FROM jsonb_to_recordset($2::jsonb) x(start text,"end" text,payload text,bytes integer)`,
121 [id, JSON.stringify(frames)],
122 )
123 await pool.query(`UPDATE ${sql}.streams SET tail_offset=$2,hot_frames=hot_frames+$3,hot_bytes=hot_bytes+$4 WHERE id=$1`, [
124 id,
125 offset,
126 frames.length,
127 frames.reduce((sum, f) => sum + f.bytes, 0),
128 ])
129 if (kind === 'current')
130 await pool.query(`INSERT INTO ${sql}.hot_chunks VALUES($1,clock_timestamp()+interval '1 hour') ON CONFLICT DO NOTHING`, [id])
131 await pool.query('COMMIT')
132 } catch (error) {
133 await pool.query('ROLLBACK')
134 throw error
135 }
136 await server.maintain({ maxChunks: 128, forceHot: true })
137 }
138 const sealingDurationMs = performance.now() - sealingStarted,
139 sealingObjects = { ...objectCounts }
140 const relations = []
141 for (const name of ['appends', 'chunks', 'chunk_objects']) {
142 const value = (
143 await pool.query(`SELECT count(*)::integer AS rows,COALESCE(sum(pg_column_size(t)),0)::text AS live_tuple_bytes FROM ${sql}."${name}" t`)
144 ).rows[0]
145 const sizes = (
146 await pool.query(
147 'SELECT pg_relation_size($1::regclass)::text AS heap_bytes,pg_indexes_size($1::regclass)::text AS index_bytes,pg_total_relation_size($1::regclass)::text AS total_bytes',
148 [`${sql}."${name}"`],
149 )
150 ).rows[0]
151 relations.push({
152 name,
153 rows: value.rows,
154 liveTupleBytes: Number(value.live_tuple_bytes),
155 allocatedBeforeVacuum: Object.fromEntries(Object.entries(sizes).map(([key, val]) => [key, Number(val)])),
156 })
157 await pool.query(`VACUUM (ANALYZE) ${sql}."${name}"`)
158 relations.at(-1).allocatedAfterVacuum = Number(
159 (await pool.query('SELECT pg_total_relation_size($1::regclass)::text AS bytes', [`${sql}."${name}"`])).rows[0].bytes,
160 )
161 }
162 objectCounts.gets = 0
163 objectCounts.getBytes = 0
164 const beforeReadCalls = calls,
165 beforeReadBytes = connection.bytesRead,
166 replayStarted = performance.now(),
167 hash = createHash('sha256')
168 let cursor = '-1',
169 pages = 0
170 do {
171 const response = await request('GET', undefined, `data?offset=${cursor}`)
172 if (response.status !== 200) throw new Error('Measured replay failed')
173 hash.update(Buffer.from(await response.arrayBuffer()))
174 pages++
175 cursor = response.headers.get('Stream-Next-Offset')
176 if (response.headers.has('Stream-Up-To-Date')) break
177 if (pages > rows) throw new Error('Replay did not converge')
178 } while (true)
179 if (hash.digest('hex') !== expectedDigest || errors.length) throw new Error('Measured replay digest or runtime errors differ')
180 const replay = {
181 durationMs: performance.now() - replayStarted,
182 pages,
183 objectGets: objectCounts.gets,
184 objectBytes: objectCounts.getBytes,
185 sqlCalls: calls - beforeReadCalls,
186 observedConnectionReadBytes: connection.bytesRead - beforeReadBytes,
187 }
188 samples.push({
189 kind,
190 framesPerChunk,
191 rows,
192 ordinaryAppends: ordinary,
193 ordinary: {
194 durationMs: appendDurationMs,
195 sqlCalls: appendSqlCalls,
196 observedBranchWalBytes: appendWalBytes,
197 headTupleUpdates: Number(headStats.n_tup_upd),
198 headHotUpdates: Number(headStats.n_tup_hot_upd),
199 },
200 sealingDurationMs,
201 sealingObjects,
202 relations,
203 replay,
204 })
205 console.log(
206 `Measured ${kind}/${framesPerChunk}: ${relations[0].rows} retained append rows; ${replay.objectGets} replay object reads across ${replay.pages} pages.`,
207 )
208 } finally {
209 await server.close()
210 }
211 }
212} finally {
213 try {
214 for (const schema of schemas) await pool.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`)
215 for (const key of new Set(keys)) await base.delete(key)
216 cleanupComplete = true
217 } finally {
218 await pool.end()
219 base.close()
220 }
222const sanitized = Object.fromEntries(Object.entries(artifacts).map(([kind, { packageRoot, consumer, ...artifact }]) => [kind, artifact]))
223await writeFile(
224 process.argv[2] ?? '/tmp/neon-compact-measurement.json',
225 JSON.stringify(
226 {
227 generatedAt: new Date().toISOString(),
228 harnessSha256: createHash('sha256')
229 .update(await readFile(new URL(import.meta.url)))
230 .digest('hex'),
231 artifacts: sanitized,
232 node: process.version,
233 region: env.AWS_REGION,
234 cleanupComplete,
235 scope:
236 'Actual sealing/replay on disposable Neon; two 4096-frame batches per profile; 64 ordinary API appends; remaining frames seeded transactionally. Separate live tuple bytes from allocated high-water relation sizes. Branch WAL includes background activity; connection read bytes include protocol overhead. No throughput/capacity claim.',
237 samples,
238 },
239 null,
240 2,
241 ) + '\n',