Open History to see the last commit
1import { createHash, randomUUID } from 'node:crypto'
2import { mkdir, writeFile, readFile } from 'node:fs/promises'
3import { execFileSync } from 'node:child_process'
4import pg from 'pg'
5import { createNeonRealtimeNotifier } from '../dist/neon.js'
6
7const env = process.env
8if (!env.TEST_FUNCTION_URL || !env.TEST_FUNCTION_API_KEY || !env.TEST_FUNCTION_MAINTENANCE_KEY || !env.TEST_FUNCTION_SCHEMA
9 || !env.TEST_FUNCTION_BUNDLE_SHA || !env.TEST_DATABASE_URL || !env.NEON_TEST_BRANCH_ID || env.TEST_FUNCTION_BRANCH_ID !== env.NEON_TEST_BRANCH_ID
10 || !/^ds_test_[a-f0-9]{32}$/.test(env.TEST_FUNCTION_SCHEMA) || !new URL(env.TEST_FUNCTION_URL).hostname.includes('.compute.')) throw new Error('Load qualification requires this run\'s isolated deployed Neon Function')
11const integer = (name, fallback, min, max) => {
12 const value = Number(env[name] ?? fallback)
13 if (!Number.isSafeInteger(value) || value < min || value > max) throw new RangeError(`Invalid ${name}`)
14 return value
15}
16const seconds = integer('DS_LOAD_SECONDS', 60, 10, 3600)
17const writers = integer('DS_LOAD_WRITERS', 4, 1, 32)
18const readers = integer('DS_LOAD_LIVE_READERS', 16, 0, 64)
19const streamCount = integer('DS_LOAD_STREAMS', 8, 1, 64)
20const writingStreams = Math.min(writers, streamCount)
21const readersOnWritingStreams = Array.from({ length: readers }, (_, index) => index % streamCount).filter((index) => index < writingStreams).length
22const recordBytes = integer('DS_LOAD_PAYLOAD_BYTES', 1024, 128, 65536)
23const realtimeProbe = env.DS_LOAD_REALTIME_PROBE === '1'
24if (realtimeProbe && (!env.NEON_REALTIME_URL || !env.NEON_REALTIME_SECRET)) throw new Error('Realtime head probe requires this branch\'s Realtime credentials')
25const maximum = 1_000_000
26const run = `qualify-${randomUUID()}`
27const paths = Array.from({ length: streamCount }, (_, i) => `${run}/${i}`)
28const expected = new Set(), ackLatency = [], liveLatency = [], errors = []
29const sent = new Map()
30const latestAcknowledged = new Map(), readerOffsets = new Map()
31const backlog = []
32const headLatency = [], headPending = new Map(), latestHead = new Map(), headWatches = []
33const liveChecks = Array.from({ length: readers }, () => ({ hash: createHash('sha256'), records: 0 }))
34let verifiedLiveReaders = 0
35let headNotifier
36const coverHead = (path, offset, at) => {
37 latestHead.set(path, { offset, at })
38 const pending = headPending.get(path) ?? []
39 headPending.set(path, pending.filter((record) => {
40 if (record.offset > offset) return true
41 headLatency.push(at - record.started)
42 return false
43 }))
44}
45let appends = 0, liveBytes = 0, rotations = 0, replayed = 0, stopping = false
46const digest = (bytes) => createHash('sha256').update(bytes).digest('hex')
47const harnessSha256 = digest(await readFile(new URL(import.meta.url)))
48const harnessCommitAtStart = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
49const request = (path, method = 'GET', body, headers = {}, signal = AbortSignal.timeout(30_000)) => fetch(new URL(path, env.TEST_FUNCTION_URL), {
50 method, headers: { Authorization: `Bearer ${env.TEST_FUNCTION_API_KEY}`, 'Content-Type': 'application/octet-stream', ...headers },
51 ...(body !== undefined ? { body } : {}), signal,
52})
53const stream = (path) => `v1/stream/${path}`
54const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL, max: 2, connectionTimeoutMillis: 10_000, query_timeout: 15_000 })
55pool.on('error', (error) => errors.push({ phase: 'database', name: error.name }))
56const liveAbort = new AbortController()
57const tasks = []
58const timings = (values) => {
59 const sorted = values.toSorted((a, b) => a - b)
60 const at = (p) => sorted.length ? Math.round(sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))] * 100) / 100 : null
61 return { samples: sorted.length, p50: at(.5), p95: at(.95), p99: at(.99), max: sorted.at(-1) ?? null }
62}
63let started, finished, connectionsBefore, connectionsAfter, frozenAfter, report, drainSeconds, replaySeconds, liveDrainSeconds
64let sampler, sampling
65const sample = async (phase = 'writing') => {
66 const row = (await pool.query(`SELECT
67 (SELECT count(*) FROM "${env.TEST_FUNCTION_SCHEMA}".chunks c JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id = c.stream_id WHERE c.state = 'frozen' AND s.path LIKE $1) AS frozen_chunks,
68 (SELECT COALESCE(sum(a.payload_bytes), 0) FROM "${env.TEST_FUNCTION_SCHEMA}".appends a JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id = a.stream_id WHERE a.payload IS NOT NULL AND s.path LIKE $1) AS local_payload_bytes,
69 (SELECT count(*) FROM "${env.TEST_FUNCTION_SCHEMA}".stream_changes c JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id = c.stream_id WHERE s.path LIKE $1) AS retained_changes,
70 (SELECT count(*) FROM pg_stat_activity WHERE datname=current_database()) AS database_connections`, [`${run}/%`])).rows[0]
71 const response = await request('health', 'GET', undefined, { 'x-ds-maintenance-key': env.TEST_FUNCTION_MAINTENANCE_KEY })
72 if (!response.ok) throw new Error(`Runtime sampling failed: HTTP ${response.status}`)
73 const health = await response.json()
74 if (health.build !== env.TEST_FUNCTION_BUNDLE_SHA) throw new Error('Runtime sampling reached a different build')
75 backlog.push({ phase, elapsedSeconds: started ? (performance.now() - started) / 1000 : 0, frozenChunks: Number(row.frozen_chunks), localPayloadBytes: Number(row.local_payload_bytes),
76 pendingChanges: Number(row.retained_changes), retainedChanges: Number(row.retained_changes), databaseConnections: Number(row.database_connections), runtime: health.runtime ?? null })
77}
78try {
79 connectionsBefore = Number((await pool.query('SELECT count(*) FROM pg_stat_activity WHERE datname = current_database()')).rows[0].count)
80 for (const path of paths) {
81 const response = await request(stream(path), 'PUT')
82 if (response.status !== 201) throw new Error(`Create failed: HTTP ${response.status}`)
83 }
84 if (realtimeProbe) {
85 headNotifier = createNeonRealtimeNotifier({ url: env.NEON_REALTIME_URL, secret: env.NEON_REALTIME_SECRET,
86 database: new URL(env.TEST_DATABASE_URL).pathname.slice(1), onError: (error) => errors.push({ phase: 'head-probe', name: error.name }) })
87 const streams = await pool.query(`SELECT id, path FROM "${env.TEST_FUNCTION_SCHEMA}".streams WHERE tenant_id='function-a' AND path=ANY($1::text[])`, [paths])
88 for (const row of streams.rows) headWatches.push(headNotifier.watch({ schema: env.TEST_FUNCTION_SCHEMA, tenantId: 'function-a', streamId: row.id },
89 (head) => { if (head) coverHead(row.path, head.offset, performance.now()) }))
90 await Promise.all(headWatches.map((watch) => watch.ready))
91 }
92 // Establish actual SSE ingress before applying write load. Each reader keeps
93 // its durable checkpoint across bounded server rotations.
94 const ready = []
95 for (let i = 0; i < readers; i++) {
96 let connected
97 ready.push(new Promise((resolve) => { connected = resolve }))
98 tasks.push((async () => {
99 let offset = '-1'
100 const decoder = new TextDecoder()
101 while (!stopping) {
102 try {
103 const response = await request(`${stream(paths[i % streamCount])}?live=sse&offset=${encodeURIComponent(offset)}`, 'GET', undefined, {}, liveAbort.signal)
104 if (!response.ok || !response.body) throw new Error(`Live admission failed: HTTP ${response.status}`)
105 connected(); let buffer = ''
106 const reader = response.body.getReader()
107 try {
108 for (;;) {
109 const part = await reader.read()
110 if (part.done) { rotations++; break }
111 buffer += decoder.decode(part.value, { stream: true })
112 if (buffer.length > 8 * 1024 * 1024) throw new Error('SSE fixture buffer bound exceeded')
113 let boundary
114 while ((boundary = buffer.indexOf('\n\n')) !== -1) {
115 const event = buffer.slice(0, boundary); buffer = buffer.slice(boundary + 2)
116 const data = event.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5)).join('\n')
117 if (event.startsWith('event: control')) { offset = JSON.parse(data).streamNextOffset; readerOffsets.set(i, offset) }
118 if (event.startsWith('event: data')) {
119 const payload = Buffer.from(data, 'base64'); liveBytes += payload.length
120 if (payload.length % recordBytes) throw new Error('SSE payload lost a record boundary')
121 liveChecks[i].hash.update(payload)
122 liveChecks[i].records += payload.length / recordBytes
123 for (let start = 0; start < payload.length; start += recordBytes) {
124 const hash = digest(payload.subarray(start, start + recordBytes)), at = sent.get(hash)
125 if (at === undefined) throw new Error('Live delivery contains an unknown record')
126 if (liveLatency.length < maximum) liveLatency.push(performance.now() - at)
127 }
128 }
129 }
130 }
131 } finally { await reader.cancel(); reader.releaseLock() }
132 } catch (error) {
133 connected()
134 if (!stopping) errors.push({ phase: 'live', name: error.name, message: error.message })
135 break
136 }
137 }
138 })())
139 }
140 await Promise.all(ready)
141 started = performance.now()
142 await sample('before-writes')
143 sampler = setInterval(() => {
144 if (sampling) return
145 sampling = sample().catch((error) => { errors.push({ phase: 'sampling', name: error.name }) }).finally(() => { sampling = undefined })
146 }, 30_000).unref()
147 const deadline = started + seconds * 1000
148 await Promise.all(Array.from({ length: writers }, async (_, writer) => {
149 for (let sequence = 0; performance.now() < deadline; sequence++) {
150 if (appends >= maximum) { errors.push({ phase: 'append', message: 'Qualification record bound reached' }); break }
151 const payload = Buffer.alloc(recordBytes, writer % 256)
152 payload.write(JSON.stringify({ run, writer, sequence }), 0, recordBytes, 'utf8')
153 const hash = digest(payload), begin = performance.now()
154 sent.set(hash, begin)
155 try {
156 const response = await request(stream(paths[writer % streamCount]), 'POST', payload, {
157 'Producer-Id': `${run}-${writer}`, 'Producer-Epoch': '0', 'Producer-Seq': String(sequence),
158 })
159 await response.arrayBuffer()
160 if (response.status !== 200 && response.status !== 204) throw new Error(`Append failed: HTTP ${response.status}`)
161 ackLatency.push(performance.now() - begin); expected.add(hash); appends++
162 const path = paths[writer % streamCount], offset = response.headers.get('stream-next-offset')
163 if (!offset) throw new Error('Append response has no checkpoint')
164 if (!latestAcknowledged.has(path) || latestAcknowledged.get(path) < offset) latestAcknowledged.set(path, offset)
165 if (realtimeProbe) {
166 const latest = latestHead.get(path)
167 if (latest && latest.offset >= offset) headLatency.push(latest.at - begin)
168 else { const pending = headPending.get(path) ?? []; pending.push({ offset, started: begin }); headPending.set(path, pending) }
169 }
170 } catch (error) { errors.push({ phase: 'append', name: error.name, message: error.message }); break }
171 }
172 }))
173 finished = performance.now()
174 clearInterval(sampler); await sampling; await sample('after-writes')
175 // Let every reader reach the final acknowledged checkpoint before measuring
176 // latency. Otherwise the last slow notifications would be censored at stop.
177 const liveDrainStarted = performance.now(), liveDeadline = liveDrainStarted + 20_000
178 const uncoveredReaders = () => Array.from({ length: readers }, (_, i) => i).filter((i) => {
179 const end = latestAcknowledged.get(paths[i % streamCount])
180 return end && (!readerOffsets.has(i) || readerOffsets.get(i) < end)
181 }).length
182 const uncoveredHeads = () => [...headPending.values()].reduce((n, pending) => n + pending.length, 0)
183 while ((uncoveredReaders() || (realtimeProbe && uncoveredHeads())) && performance.now() < liveDeadline) await new Promise((resolve) => setTimeout(resolve, 100))
184 liveDrainSeconds = (performance.now() - liveDrainStarted) / 1000
185 if (uncoveredReaders()) errors.push({ phase: 'live', message: 'Readers did not reach all acknowledged checkpoints before drain deadline', count: uncoveredReaders() })
186 if (realtimeProbe && uncoveredHeads()) errors.push({ phase: 'head-probe', message: 'Head coverage incomplete at drain deadline', count: uncoveredHeads() })
187 stopping = true; liveAbort.abort(); await Promise.allSettled(tasks)
188 const drainStarted = performance.now()
189 // Qualify sealed replay as well as delivery: bounded maintenance must recover
190 // every outstanding chunk before comparing complete immutable record sets.
191 const drainDeadline = performance.now() + 90_000
192 for (let i = 0; i < 128 && performance.now() < drainDeadline; i++) {
193 const maintenance = await request('_maintenance', 'POST', undefined, { 'x-ds-maintenance-key': env.TEST_FUNCTION_MAINTENANCE_KEY })
194 if (!maintenance.ok) throw new Error(`Maintenance failed: HTTP ${maintenance.status}`)
195 const maintenanceStats = await maintenance.json()
196 frozenAfter = Number((await pool.query(`SELECT count(*) FROM "${env.TEST_FUNCTION_SCHEMA}".appends a JOIN "${env.TEST_FUNCTION_SCHEMA}".streams s ON s.id = a.stream_id WHERE s.path LIKE $1 AND a.payload IS NOT NULL`, [`${run}/%`])).rows[0].count)
197 if (!frozenAfter) break
198 if (!maintenanceStats.sealed && !maintenanceStats.frozen) await new Promise((resolve) => setTimeout(resolve, 250))
199 }
200 const observed = new Set()
201 const sequenceByWriter = new Map()
202 drainSeconds = (performance.now() - drainStarted) / 1000
203 const replayStarted = performance.now()
204 const replayDigests = new Map()
205 async function replay(path) {
206 const ordered = createHash('sha256')
207 let offset = '-1'
208 for (let page = 0; page < maximum; page++) {
209 const response = await request(`${stream(path)}?offset=${encodeURIComponent(offset)}`)
210 if (!response.ok) throw new Error(`Replay failed: HTTP ${response.status}`)
211 const bytes = Buffer.from(await response.arrayBuffer())
212 if (bytes.length % recordBytes) throw new Error('Replay record boundary mismatch')
213 ordered.update(bytes)
214 for (let start = 0; start < bytes.length; start += recordBytes) {
215 const hash = digest(bytes.subarray(start, start + recordBytes))
216 if (observed.has(hash) || !expected.has(hash)) throw new Error('Replay contains duplicate or unacknowledged record')
217 const record = bytes.subarray(start, start + recordBytes)
218 const identity = JSON.parse(record.subarray(0, record.indexOf(125) + 1).toString('utf8'))
219 if (identity.sequence !== (sequenceByWriter.get(identity.writer) ?? -1) + 1) throw new Error('Replay reordered a producer sequence')
220 sequenceByWriter.set(identity.writer, identity.sequence)
221 observed.add(hash); replayed++
222 }
223 if (response.headers.get('stream-up-to-date') === 'true') break
224 const next = response.headers.get('stream-next-offset')
225 if (!next || next === offset) throw new Error('Replay did not advance its checkpoint')
226 offset = next
227 }
228 replayDigests.set(path, ordered.digest('hex'))
229 }
230 let nextPath = 0
231 await Promise.all(Array.from({ length: Math.min(4, paths.length) }, async () => {
232 for (;;) { const index = nextPath++; if (index >= paths.length) break; await replay(paths[index]) }
233 }))
234 replaySeconds = (performance.now() - replayStarted) / 1000
235 if (observed.size !== expected.size) throw new Error('Replay lost acknowledged records')
236 for (let i = 0; i < readers; i++) {
237 if (liveChecks[i].hash.digest('hex') !== replayDigests.get(paths[i % streamCount])) throw new Error('Live delivery differs from ordered durable replay')
238 verifiedLiveReaders++
239 }
240 if (frozenAfter) throw new Error('Maintenance did not seal all workload payloads')
241 await sample('after-replay')
242 connectionsAfter = Number((await pool.query('SELECT count(*) FROM pg_stat_activity WHERE datname = current_database()')).rows[0].count)
243} catch (error) { errors.push({ phase: 'qualification', name: error.name, message: error.message }) }
244finally {
245 clearInterval(sampler); await sampling
246 stopping = true; liveAbort.abort(); await Promise.allSettled(tasks)
247 for (const watch of headWatches) watch.close()
248 headNotifier?.close()
249 await pool.end()
250 report = { harnessSha256, harnessCommitAtStart, generatedAt: new Date().toISOString(),
251 deployedSourceCommit: env.TEST_FUNCTION_SOURCE_COMMIT ?? null, deployedSourceDirty: env.TEST_FUNCTION_SOURCE_DIRTY ?? null, deploymentId: env.TEST_FUNCTION_DEPLOYMENT_ID ?? null,
252 bundleSha256: env.TEST_FUNCTION_BUNDLE_SHA, node: process.version, profile: { seconds, writers, readers, streams: streamCount, writingStreams, readersOnWritingStreams, idleReaders: readers - readersOnWritingStreams, recordBytes, replayConcurrency: 4, realtimeProbe, maintenanceHints: env.TEST_FUNCTION_MAINTENANCE_HINTS ?? 'unknown', hasCron: env.TEST_FUNCTION_HAS_CRON ?? 'unknown', liveFallbackMs: env.TEST_FUNCTION_LIVE_FALLBACK_MS ?? null, liveValidationMs: env.TEST_FUNCTION_LIVE_VALIDATION_MS ?? null, cronChunks: env.TEST_FUNCTION_CRON_CHUNKS ?? null, cronSubscriptionWork: env.TEST_FUNCTION_CRON_SUBSCRIPTION_WORK ?? null, storage: 'actual Neon PG18/Realtime/Object Storage/Functions' },
253 elapsedSeconds: started && finished ? (finished - started) / 1000 : null, acknowledgedAppends: appends, replayedRecords: replayed,
254 appendsPerSecond: started && finished ? appends / ((finished - started) / 1000) : null,
255 appendLatencyMs: timings(ackLatency), observedLiveLatencyMs: timings(liveLatency), observedHeadCoverageMs: timings(headLatency), liveBytes, rotations,
256 liveVerification: { verifiedReaders: verifiedLiveReaders, receivedRecords: liveChecks.map((value) => value.records), orderedSha256MatchesReplay: verifiedLiveReaders === readers },
257 connectionsBefore, connectionsAfter, backlog, liveDrainSeconds, drainSeconds, replaySeconds, remainingLocalPayloads: frozenAfter, errors, passed: errors.length === 0 && appends > 0 && replayed === appends && verifiedLiveReaders === readers && (!readers || liveLatency.length > 0) }
258 await mkdir('qualification-results', { recursive: true })
259 await writeFile(`qualification-results/${run}.json`, JSON.stringify(report, null, 2) + '\n')
260}
261console.log(JSON.stringify(report, null, 2))
262if (!report.passed) process.exitCode = 1