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

qualify-replay.mjs

231 lines14.0 KB

1import assert from 'node:assert/strict'
2import { createHash, randomUUID } from 'node:crypto'
3import { mkdir, readFile, writeFile } from 'node:fs/promises'
4import pg from 'pg'
5import { replayProfiles, replayFrame, expectedReplay } from '../test/fixtures/replay-data.mjs'
6​
7const env = process.env
8const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state-replay.json', 'utf8'))
9if (state.projectId !== env.NEON_PROJECT_ID || state.branchId !== env.TEST_FUNCTION_BRANCH_ID || !state.name.startsWith('ds-test-')
10 || env.TEST_FUNCTION_BRANCH_ID !== env.NEON_TEST_BRANCH_ID || !/^ds_test_[a-f0-9]{32}$/.test(env.TEST_FUNCTION_SCHEMA ?? '')) throw new Error('Recorded replay branch and Function required')
11const run = `replay-${randomUUID()}`
12const repetitions = Number(env.REPLAY_REPETITIONS ?? 3)
13if (!Number.isSafeInteger(repetitions) || repetitions < 2 || repetitions > 10) throw new Error('Invalid replay repetitions')
14const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 1, query_timeout: 30000 })
15const request = (path, options = {}) => fetch(new URL(path, env.TEST_FUNCTION_URL), { ...options,
16 headers: { Authorization: `Bearer ${env.TEST_FUNCTION_API_KEY}`, ...options.headers }, signal: options.signal ?? AbortSignal.timeout(180000) })
17const digest = (bytes) => createHash('sha256').update(bytes).digest('hex')
18const harnessSha256 = digest(await readFile(new URL(import.meta.url)))
19const inputsSha256 = digest(await readFile(new URL('../test/fixtures/replay-data.mjs', import.meta.url)))
20const samples = []
21const datasets = []
22const errors = []
23const started = performance.now()
24const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
25const quantiles = (values) => {
26 const ordered = values.toSorted((a, b) => a - b)
27 return Object.fromEntries([['count', values.length], ...[.5, .95, .99].map((q) => [`p${q * 100}`, ordered[Math.min(ordered.length - 1, Math.floor(q * ordered.length))] ?? null])])
29let storageBefore, storageAfter
30​
31async function readPage(dataset, from, cache, mode = 'seek', extra = {}) {
32 const url = `v1/stream/${dataset.path}?offset=${encodeURIComponent(dataset.offsets[from])}`
33 const begin = performance.now()
34 const startedAt = new Date().toISOString()
35 const response = await request(url, { headers: { 'x-replay-cache': cache, ...extra.headers } })
36 const headerMs = performance.now() - begin
37 const metrics = JSON.parse(response.headers.get('x-replay-metrics') ?? 'null')
38 assert.ok(metrics, 'Missing per-request deployed metrics')
39 assert.equal(response.status, extra.status ?? 200)
40 const reader = response.body?.getReader()
41 const parts = []
42 let firstByteMs, size = 0
43 try {
44 while (reader) {
45 const part = await reader.read()
46 if (part.done) break
47 firstByteMs ??= performance.now() - begin
48 size += part.value.byteLength
49 assert.ok(size <= 3 * 1024 * 1024, 'Replay page exceeds benchmark limit')
50 parts.push(part.value)
51 if (extra.slow) await pause(10)
52 }
53 } finally { if (reader) { await reader.cancel(); reader.releaseLock() } }
54 const completeMs = performance.now() - begin
55 const next = dataset.offsets.indexOf(response.headers.get('Stream-Next-Offset'))
56 assert.ok(next >= from && next <= dataset.frames, 'Checkpoint is not an acknowledged frame boundary')
57 const bytes = Buffer.concat(parts)
58 if (response.status === 200) assert.deepEqual(bytes, expectedReplay(dataset.profile, from, next), 'Replay bytes differ from independent deterministic inputs')
59 else assert.equal(bytes.length, 0)
60 samples.push({ profile: dataset.profile, from, through: next, mode, startedAt, headerMs, firstByteMs: firstByteMs ?? headerMs, completeMs,
61 deliveredBytes: bytes.length, digest: digest(bytes), metrics })
62 return { next, response }
64​
65try {
66 const health = await (await request('_benchmark/health')).json()
67 assert.equal(health.build, env.TEST_FUNCTION_BUNDLE_SHA)
68 assert.equal(health.sourceCommit, env.TEST_FUNCTION_SOURCE_COMMIT)
69 storageBefore = await (await request('_benchmark/storage')).json()
70 for (const [profile, options] of Object.entries(replayProfiles)) {
71 const response = await request('_benchmark/seed', { method: 'POST', body: JSON.stringify({ run, profile, frames: options.frames }), headers: { 'Content-Type': 'application/json' } })
72 assert.equal(response.status, 200, `Dataset ${profile} creation failed`)
73 const dataset = await response.json()
74 assert.equal(dataset.offsets.length, dataset.frames + 1)
75 assert.equal(new Set(dataset.offsets).size, dataset.offsets.length)
76 assert.ok(dataset.offsets.every((offset, index) => !index || offset > dataset.offsets[index - 1]))
77 datasets.push(dataset)
78 console.log(`Seeded ${profile}: ${dataset.frames} public API appends`)
79 }
80 for (let index = 0; index < 8; index++) {
81 const path = `${run}/quiet-${index}`
82 const created = await request(`v1/stream/${path}`, { method: 'PUT' })
83 assert.equal(created.status, 201)
84 const appended = await request(`v1/stream/${path}`, { method: 'POST', body: replayFrame('tiny', 0), headers: { 'Content-Type': 'application/octet-stream' } })
85 assert.equal(appended.status, 204)
86 datasets.push({ path, profile: 'tiny', frames: 1, offsets: [created.headers.get('Stream-Next-Offset'), appended.headers.get('Stream-Next-Offset')] })
87 }
88 const source = datasets.find((item) => item.profile === 'binary')
89 let parent = source.path
90 for (let depth = 0; depth < 16; depth++) {
91 const path = `${run}/fork-${depth}`
92 const response = await request(`v1/stream/${path}`, { method: 'PUT', headers: { 'Stream-Forked-From': `/v1/stream/${parent}`, 'Stream-Fork-Offset': source.offsets[128] } })
93 assert.equal(response.status, 201)
94 parent = path
95 }
96 const deepFork = { path: parent, profile: 'binary', frames: 128, offsets: source.offsets.slice(0, 129) }
97 for (let pass = 0; pass < 12; pass++) {
98 const response = await request('_benchmark/maintain', { method: 'POST' })
99 assert.equal(response.status, 200)
100 await response.arrayBuffer()
101 const storage = await (await request('_benchmark/storage')).json()
102 if (Number(storage.counts.appends) === 0 && Number(storage.counts.frozen) === 0) break
103 assert.ok(pass < 11, 'Sealing did not drain')
104 }
105 await pool.query(`VACUUM (ANALYZE) "${env.TEST_FUNCTION_SCHEMA}".chunks`)
106 await pool.query(`VACUUM (ANALYZE) "${env.TEST_FUNCTION_SCHEMA}".appends`)
107 for (const dataset of datasets) {
108 for (let repetition = 0; repetition < repetitions; repetition++) {
109 const from = [Math.floor(dataset.frames / 2), Math.floor(dataset.frames / 3), Math.max(0, dataset.frames - 2)][repetition % 3]
110 await readPage(dataset, from, 'cold', 'cold-seek')
111 await readPage(dataset, from, 'shared', 'repeat-seek')
112 const { response } = await readPage(dataset, from, 'shared', 'repeat-seek')
113 await readPage(dataset, from, 'shared', 'conditional', { headers: { 'if-none-match': response.headers.get('etag') }, status: 304 })
114 }
115 for (let repetition = 0; repetition < repetitions; repetition++) {
116 let from = 0, pages = 0
117 while (from < dataset.frames) {
118 const page = await readPage(dataset, from, 'shared', 'sequential')
119 assert.ok(page.next > from, 'Replay made no progress')
120 from = page.next
121 assert.ok(++pages < 10000)
122 }
123 }
124 await readPage(dataset, 0, 'shared', 'slow-reader', { slow: true })
125 await Promise.all(Array.from({ length: 8 }, () => readPage(dataset, Math.floor(dataset.frames / 2), 'shared', 'fanout')))
126 console.log(`Verified replay bytes and checkpoints for ${dataset.profile}`)
127 }
128 for (let repetition = 0; repetition < repetitions; repetition++) {
129 await readPage(deepFork, 0, 'cold', 'deep-fork-cold')
130 await readPage(deepFork, 64, 'shared', 'deep-fork-warm')
131 }
132 const binary = datasets.find((item) => item.profile === 'binary')
133 for (let index = 0; index < 8; index++) {
134 const begin = performance.now()
135 const response = await request(`v1/stream/${binary.path}?offset=${encodeURIComponent(binary.offsets[0])}&live=sse`)
136 assert.equal(response.status, 200)
137 const reader = response.body.getReader()
138 assert.equal((await reader.read()).done, false)
139 await reader.cancel()
140 reader.releaseLock()
141 samples.push({ mode: 'canceled-sse', completeMs: performance.now() - begin, metrics: JSON.parse(response.headers.get('x-replay-metrics')) })
142 }
143 const catchup = await request(`v1/stream/${deepFork.path}?offset=${encodeURIComponent(deepFork.offsets[126])}&live=sse`)
144 assert.equal(catchup.status, 200)
145 const liveReader = catchup.body.getReader()
146 const decoder = new TextDecoder()
147 const liveDigest = createHash('sha256')
148 let pending = '', appended = false, eof = false, liveNext
149 const liveStarted = performance.now()
150 try {
151 while (!eof) {
152 const part = await liveReader.read()
153 assert.equal(part.done, false, 'SSE ended before its final checkpoint')
154 pending += decoder.decode(part.value, { stream: true })
155 assert.ok(pending.length < 4 * 1024 * 1024)
156 let end
157 while ((end = pending.indexOf('\n\n')) !== -1) {
158 const event = pending.slice(0, end)
159 pending = pending.slice(end + 2)
160 const data = event.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5)).join('\n')
161 if (event.startsWith('event: data')) liveDigest.update(Buffer.from(data, 'base64'))
162 if (event.startsWith('event: control')) {
163 const control = JSON.parse(data)
164 if (control.upToDate && !appended) {
165 const response = await request(`v1/stream/${deepFork.path}`, { method: 'POST', body: replayFrame('binary', 128),
166 headers: { 'Content-Type': 'application/octet-stream', 'Stream-Closed': 'true' } })
167 assert.equal(response.status, 204)
168 liveNext = response.headers.get('Stream-Next-Offset')
169 appended = true
170 }
171 if (control.streamClosed) { assert.equal(control.streamNextOffset, liveNext); eof = true }
172 }
173 }
174 }
175 } finally { await liveReader.cancel(); liveReader.releaseLock() }
176 assert.equal(liveDigest.digest('hex'), digest(expectedReplay('binary', 126, 129)))
177 samples.push({ mode: 'catchup-to-live', completeMs: performance.now() - liveStarted, metrics: JSON.parse(catchup.headers.get('x-replay-metrics')) })
178 // Add write pressure to a sealed stream, then repeat with separate writers.
179 for (const sameStream of [true, false]) {
180 const dataset = datasets.find((item) => item.profile === 'binary')
181 const writePath = sameStream ? dataset.path : `${run}/writer`
182 let writeStart = dataset.offsets.at(-1)
183 if (!sameStream) {
184 const created = await request(`v1/stream/${writePath}`, { method: 'PUT' })
185 assert.equal(created.status, 201)
186 writeStart = created.headers.get('Stream-Next-Offset')
187 }
188 let writeEnd
189 const writer = (async () => {
190 for (let index = 0; index < 24; index++) {
191 const begin = performance.now()
192 const response = await request(`v1/stream/${writePath}`, { method: 'POST', body: replayFrame('binary', dataset.frames + index), headers: { 'Content-Type': 'application/octet-stream' } })
193 await response.arrayBuffer()
194 assert.equal(response.status, 204)
195 writeEnd = response.headers.get('Stream-Next-Offset')
196 samples.push({ mode: sameStream ? 'writer-shared-stream' : 'writer-separate-stream', completeMs: performance.now() - begin,
197 metrics: JSON.parse(response.headers.get('x-replay-metrics')) })
198 }
199 })()
200 await Promise.all([writer, ...Array.from({ length: 4 }, async () => {
201 for (let index = 0; index < 8; index++) await readPage(dataset, 0, 'shared', sameStream ? 'reader-shared-stream' : 'reader-separate-stream')
202 })])
203 const replayed = await request(`v1/stream/${writePath}?offset=${encodeURIComponent(writeStart)}`)
204 assert.equal(replayed.status, 200)
205 assert.equal(replayed.headers.get('Stream-Next-Offset'), writeEnd)
206 assert.deepEqual(Buffer.from(await replayed.arrayBuffer()), expectedReplay('binary', dataset.frames, dataset.frames + 24))
207 }
208 storageAfter = await (await request('_benchmark/storage')).json()
209 assert.equal(Number(storageAfter.counts.replay_pins), 0, 'Replay pins remain after all readers completed')
210} catch (error) {
211 errors.push({ name: error.name, message: error.message })
212 console.error(error.name, error.message)
213} finally {
214 await pool.end()
215 const report = { sourceCommit: env.TEST_FUNCTION_SOURCE_COMMIT, bundleSha256: env.TEST_FUNCTION_BUNDLE_SHA,
216 deploymentId: env.TEST_FUNCTION_DEPLOYMENT_ID, branchId: env.NEON_TEST_BRANCH_ID, region: env.AWS_REGION,
217 harnessSha256, inputsSha256, coordinator: { node: process.version, platform: process.platform, architecture: process.arch },
218 generatedAt: new Date().toISOString(), run, seed: 20261123, repetitions,
219 settings: JSON.parse(env.REPLAY_SETTINGS), durationMs: performance.now() - started, errors,
220 scope: 'Public API appends and reads through deployed instrumented consumer. Per-request SQL/object metrics cover handler work through response headers. Disabled-cache requests create a separate server on the reached isolate. Instance IDs distinguish routed isolates. Client times include coordinator network. No open-loop capacity claim.',
221 profiles: datasets.map((dataset) => ({ profile: dataset.profile, frames: dataset.frames })), storageBefore, storageAfter, samples,
222 summary: [...new Set(samples.map((sample) => sample.mode))].map((mode) => ({ mode,
223 latencyMs: quantiles(samples.filter((sample) => sample.mode === mode).map((sample) => sample.completeMs)),
224 sqlCalls: quantiles(samples.filter((sample) => sample.mode === mode).map((sample) => sample.metrics.sqlCalls)),
225 objectGets: samples.filter((sample) => sample.mode === mode).reduce((sum, sample) => sum + sample.metrics.objectGets, 0) })) }
226 await mkdir('qualification-results', { recursive: true })
227 const output = env.REPLAY_REPORT ?? `qualification-results/${run}.json`
228 await writeFile(output, JSON.stringify(report, null, 2) + '\n')
229 console.log(JSON.stringify({ output, passed: errors.length === 0, samples: samples.length, summary: report.summary }))
231if (errors.length) process.exitCode = 1