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

qualify-replay-dense.mjs

103 lines7.2 KB

1import assert from 'node:assert/strict'
2import { randomUUID, createHash } from 'node:crypto'
3import { readFile, writeFile } from 'node:fs/promises'
4import pg from 'pg'
5​
6const env = process.env
7const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state-replay.json', 'utf8'))
8const schema = env.TEST_FUNCTION_SCHEMA
9if (!state.name.startsWith('ds-test-') || state.branchId !== env.NEON_TEST_BRANCH_ID || state.branchId !== env.TEST_FUNCTION_BRANCH_ID || !/^ds_test_[a-f0-9]{32}$/.test(schema)) throw new Error('Recorded isolated replay Function required')
10const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 1, query_timeout: 120000 })
11const path = `replay-${randomUUID()}/dense`
12let count
13const payload = Buffer.alloc(32, 120)
14const request = (suffix, options = {}) => fetch(new URL(suffix, env.TEST_FUNCTION_URL), { ...options,
15 headers: { Authorization: `Bearer ${env.TEST_FUNCTION_API_KEY}`, ...options.headers }, signal: AbortSignal.timeout(180000) })
16const samples = []
17let result
18try {
19 const health = await (await request('_benchmark/health')).json()
20 assert.equal(health.build, env.TEST_FUNCTION_BUNDLE_SHA)
21 count = health.settings.maxChunkFrames
22 assert.ok([8192, 32768, 131072].includes(count))
23 assert.equal(health.settings.targetChunkBytes, 4194304)
24 const created = await request(`v1/stream/${path}`, { method: 'PUT', headers: { 'Content-Type': 'application/octet-stream' } })
25 assert.equal(created.status, 201)
26 const zero = created.headers.get('Stream-Next-Offset')
27 const stream = (await pool.query(`SELECT id FROM "${schema}".streams WHERE tenant_id='replay' AND path=$1`, [path])).rows[0].id
28 const history = stream.replaceAll('-', '')
29 const footprint = async () => {
30 const relations = []
31 for (const name of ['appends', 'chunks', 'chunk_objects']) {
32 const sizes = (await pool.query('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', [`"${schema}".${name}`])).rows[0]
33 relations.push({ name, ...Object.fromEntries(Object.entries(sizes).map(([key, value]) => [key, Number(value)])) })
34 }
35 return relations
36 }
37 const before = (await pool.query('SELECT pg_current_wal_insert_lsn() AS lsn')).rows[0].lsn
38 const seedStarted = performance.now()
39 // Bulk setup is not append throughput: the final append, freeze, seal and
40 // every replay use the deployed public consumer against actual Neon.
41 await pool.query('BEGIN')
42 try {
43 await pool.query(`SET LOCAL statement_timeout='90s'`)
44 await pool.query(`INSERT INTO "${schema}".appends(stream_id,start_offset,end_offset,payload,payload_bytes)
45 SELECT $1::uuid,CASE WHEN n=0 THEN $2 ELSE lpad(n::text,16,'0')||'_'||$3 END,lpad((n+1)::text,16,'0')||'_'||$3,$4,32
46 FROM generate_series(0,$5::integer-2) n`, [stream, zero, history, payload, count])
47 await pool.query(`UPDATE "${schema}".streams SET tail_offset=$2,hot_frames=$3::integer,hot_bytes=$3::integer*32 WHERE id=$1`, [stream, `${String(count - 1).padStart(16, '0')}_${history}`, count - 1])
48 await pool.query(`INSERT INTO "${schema}".hot_chunks VALUES($1,clock_timestamp()+interval '1 hour')`, [stream])
49 await pool.query('COMMIT')
50 } catch (error) { await pool.query('ROLLBACK'); throw error }
51 const seedMs = performance.now() - seedStarted
52 const stagingFootprint = await footprint()
53 const appendStarted = performance.now()
54 const append = await request(`v1/stream/${path}`, { method: 'POST', body: payload, headers: { 'Content-Type': 'application/octet-stream' } })
55 assert.equal(append.status, 204)
56 const tail = append.headers.get('Stream-Next-Offset')
57 const appendMs = performance.now() - appendStarted
58 const freezeMetrics = JSON.parse(append.headers.get('x-replay-metrics'))
59 assert.equal(tail, `${String(count).padStart(16, '0')}_${history}`)
60 console.log(`The public final append froze all ${count} frames`)
61 const sealStarted = performance.now()
62 const maintenance = await request('_benchmark/maintain', { method: 'POST' })
63 assert.equal(maintenance.status, 200)
64 const sealed = await maintenance.json()
65 assert.equal(sealed.sealed, 1)
66 const sealMs = performance.now() - sealStarted
67 assert.equal((await pool.query(`SELECT count(*) FROM "${schema}".appends WHERE stream_id=$1`, [stream])).rows[0].count, '0')
68 const manifests = (await pool.query(`SELECT frame_count,payload_bytes,encoded_bytes,octet_length(block_directory) AS directory_bytes FROM "${schema}".chunks WHERE stream_id=$1`, [stream])).rows
69 assert.equal(manifests.length, 1)
70 assert.equal(manifests[0].frame_count, count)
71 const sealedFootprint = await footprint()
72 for (const name of ['appends', 'chunks', 'chunk_objects']) await pool.query(`VACUUM (ANALYZE) "${schema}".${name}`)
73 const vacuumedFootprint = await footprint()
74 const digest = createHash('sha256')
75 let cursor = zero, bytes = 0
76 const replayStarted = performance.now()
77 while (cursor !== tail) {
78 const started = performance.now()
79 const response = await request(`v1/stream/${path}?offset=${encodeURIComponent(cursor)}`)
80 assert.equal(response.status, 200)
81 const body = Buffer.from(await response.arrayBuffer())
82 assert.deepEqual(body, Buffer.alloc(body.length, 120))
83 assert.ok(body.length > 0)
84 bytes += body.length; digest.update(body)
85 const next = response.headers.get('Stream-Next-Offset')
86 assert.ok(next > cursor)
87 samples.push({ bytes: body.length, durationMs: performance.now() - started, metrics: JSON.parse(response.headers.get('x-replay-metrics')) })
88 cursor = next
89 assert.ok(samples.length <= Math.ceil(count / 8192))
90 }
91 assert.equal(samples.length, Math.ceil(count / 8192))
92 assert.equal(bytes, count * 32)
93 assert.equal(digest.digest('hex'), createHash('sha256').update(Buffer.alloc(count * 32, 120)).digest('hex'))
94 assert.equal((await pool.query(`SELECT count(*) FROM "${schema}".replay_pins`)).rows[0].count, '0')
95 result = { passed: true, count, stagingFootprint, sealedFootprint, vacuumedFootprint, seedMs, appendMs, freezeMetrics, sealMs, maintenance: sealed, manifests, replayMs: performance.now() - replayStarted,
96 deliveredBytes: bytes, samples, observedBranchWalBytes: Number((await pool.query('SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),$1) AS bytes', [before])).rows[0].bytes) }
97} finally { await pool.end() }
98await writeFile(env.REPLAY_REPORT ?? 'qualification-results/replay-dense.json', JSON.stringify({
99 ...result, sourceCommit: env.TEST_FUNCTION_SOURCE_COMMIT, bundleSha256: env.TEST_FUNCTION_BUNDLE_SHA, branchId: state.branchId,
100 harnessSha256: createHash('sha256').update(await readFile(new URL(import.meta.url))).digest('hex'),
101 scope: 'Actual configured-full-chunk qualification. Bulk seed count-1 constrained hot rows; final ordinary public append triggers freeze, deployed maintenance uploads/read-back-verifies/deletes staging, and default public pages verify exact bytes and final checkpoint. This is not append throughput. Lifetime RSS is the reached sealer process high-water, not fleet memory; branch WAL includes setup and background work.',
102}, null, 2) + '\n')
103console.log(JSON.stringify({ passed: result.passed, appendMs: result.appendMs, sealMs: result.sealMs, replayMs: result.replayMs, pages: result.samples.length, memory: result.maintenance.benchmark }))