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

test-local-performance.mjs

553 lines20.2 KB

1import assert from 'node:assert/strict'
2import { mkdir, readFile, writeFile } from 'node:fs/promises'
3import { setTimeout as delay } from 'node:timers/promises'
4import pg from 'pg'
5import {
6 Shape,
7 ShapeStream,
8 isChangeMessage,
9 isControlMessage,
10 isVisibleInSnapshot,
11} from '../packages/client/dist/index.mjs'
12​
13const base = new URL(process.env.SHAPE_URL ?? 'http://localhost:4327/api/shape')
14assert(
15 ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname),
16 'Performance acceptance requires local neon dev'
18assert(
19 process.env.DATABASE_URL,
20 'Performance acceptance requires private DATABASE_URL'
22const diagnosticsFile = process.env.NEON_SHAPE_DIAGNOSTICS_FILE
23assert(
24 diagnosticsFile,
25 'Start neon dev with NEON_SHAPE_DIAGNOSTICS=true and NEON_SHAPE_DIAGNOSTICS_FILE'
27const sizes = (process.env.BENCHMARK_ROWS ?? '1000,5000').split(',').map(Number)
28const readers = (process.env.BENCHMARK_READERS ?? '1,5').split(',').map(Number)
29const payloadChars = Number(process.env.BENCHMARK_PAYLOAD_CHARS ?? 512)
30const mutations = Number(process.env.BENCHMARK_MUTATIONS ?? 8)
31const sealBytes = Number(process.env.NEON_SHAPE_SEAL_BYTES ?? 262144)
32assert(Number.isSafeInteger(sealBytes) && sealBytes > 0)
33assert(sizes.every((n) => Number.isSafeInteger(n) && n > 0 && n <= 20_000))
34assert(readers.every((n) => Number.isSafeInteger(n) && n > 0 && n <= 20))
35assert(
36 Number.isSafeInteger(payloadChars) && payloadChars > 0 && payloadChars <= 2048
38assert(Number.isSafeInteger(mutations) && mutations >= 3 && mutations <= 100)
39const report = {
40 startedAt: new Date().toISOString(),
41 status: 'running',
42 environment: 'local neon dev, real Postgres/Realtime and Object Storage',
43 sampleIntervalMs: 100,
44 sealBytes,
45 replica: 'full',
46 sizes,
47 readers,
48 payloadChars,
49 mutations,
50 scenarios: [],
51 limits: [
52 'Local-to-service network latency is included; no deployed capacity claim.',
53 '100ms process memory samples can miss shorter peaks and include SDK/runtime overhead.',
54 'Retained rows are counted; process heap/RSS deltas are not exact per-row allocation measurements.',
55 'The fixture uses int4/text/bool and one source owner shared by readers.',
56 'Fan-out replays deliberately reread stored history; no object cache is assumed.',
57 ],
59const db = new pg.Client({
60 connectionString: process.env.DATABASE_URL,
61 connectionTimeoutMillis: 15_000,
62 query_timeout: 30_000,
63})
64const diagnostics = async () =>
65 (await readFile(diagnosticsFile, 'utf8'))
66 .split('\n')
67 .filter(Boolean)
68 .flatMap((line) => {
69 // The final line can be incomplete while the Function appends its sample.
70 try {
71 return [JSON.parse(line)]
72 } catch {
73 return []
74 }
75 })
76const summary = (values) => {
77 const sorted = [...values].sort((a, b) => a - b)
78 assert(sorted.length)
79 const quantile = (p) => sorted[Math.max(0, Math.ceil(sorted.length * p) - 1)]
80 return {
81 count: sorted.length,
82 min: sorted[0],
83 p50: quantile(0.5),
84 p95: quantile(0.95),
85 max: sorted.at(-1),
86 }
88const until = async (predicate, label, errors = []) => {
89 const end = Date.now() + 45_000
90 while (Date.now() < end) {
91 if (errors.length) throw errors[0]
92 if (await predicate()) return
93 await delay(10)
94 }
95 throw new Error(`Performance acceptance timed out: ${label}`)
97const deleteHandle = async (params, handle, allowGone = true) => {
98 const url = new URL(base)
99 for (const [key, value] of Object.entries({ ...params, handle }))
100 url.searchParams.set(
101 key,
102 typeof value === 'object' ? JSON.stringify(value) : value
103 )
104 const response = await fetch(url, {
105 method: 'DELETE',
106 signal: AbortSignal.timeout(15_000),
107 })
108 assert(
109 [204, ...(allowGone ? [409] : [])].includes(response.status),
110 'Handle cleanup must succeed'
111 )
113const output = '.artifacts/staging/local-performance.json'
114await mkdir('.artifacts/staging', { recursive: true })
115await db.connect()
116try {
117 // neon dev can evaluate the module in more than one context. Measure the
118 // serving context that actually emits samples, rather than its last boot.
119 let startEvents
120 await until(async () => {
121 startEvents = await diagnostics()
122 return startEvents.some(
123 (e) => e.event === 'function_metrics' && e.timestamp >= Date.now() - 5000
124 )
125 }, 'fresh Function memory samples')
126 const instance = startEvents.findLast(
127 (e) => e.event === 'function_metrics'
128 )?.instance
129 assert(
130 instance,
131 'No measured Function instance found; restart neon dev with diagnostics'
132 )
133 report.nodeVersion = process.version
134 report.functionNodeVersion = startEvents.findLast(
135 (e) => e.event === 'function_started' && e.instance === instance
136 )?.nodeVersion
137 for (const rowCount of sizes)
138 for (const liveSse of [false, true])
139 for (const readerCount of readers) {
140 const lower = 100_000_000 + Math.floor(Math.random() * 1_000_000_000)
141 const upper = lower + rowCount
142 const params = {
143 table: 'electric_items',
144 replica: 'full',
145 where: 'id >= $1 AND id < $2',
146 params: { 1: String(lower), 2: String(upper) },
147 }
148 const clients = []
149 const handles = new Set()
150 const errors = []
151 const requests = []
152 const times = []
153 const commitTimes = []
154 const scenario = {
155 rowCount,
156 readerCount,
157 liveSse,
158 status: 'running',
159 fixtureUtf8Bytes: rowCount * payloadChars,
160 }
161 report.scenarios.push(scenario)
162 let began
163 let timestampStart
164 const open = (options = {}) => {
165 const abort = new AbortController()
166 const receivedTxids = new Set()
167 let snapshot
168 const client = {
169 abort,
170 stream: undefined,
171 shape: undefined,
172 snapshot: () => snapshot,
173 receivedTxids,
174 firstHeadersAt: undefined,
175 bytes: 0,
176 }
177 const stream = new ShapeStream({
178 url: base.toString(),
179 params,
180 signal: abort.signal,
181 liveSse,
182 ...options,
183 onError(error) {
184 errors.push(error)
185 },
186 fetchClient: async (input, init) => {
187 const target = new URL(String(input))
188 assert.equal(target.origin, base.origin)
189 assert.equal(target.pathname, base.pathname)
190 assert.equal(init?.method ?? 'GET', 'GET')
191 requests.push({
192 at: performance.now(),
193 handle: target.searchParams.get('handle'),
194 })
195 const response = await fetch(input, init)
196 client.firstHeadersAt ??= performance.now()
197 const handle = response.headers.get('electric-handle')
198 if (handle) handles.add(handle)
199 if (!response.body) return response
200 const body = response.body.getReader()
201 return new Response(
202 new ReadableStream({
203 async pull(controller) {
204 try {
205 const chunk = await body.read()
206 if (chunk.done) controller.close()
207 else {
208 client.bytes += chunk.value.byteLength
209 controller.enqueue(chunk.value)
210 }
211 } catch (error) {
212 controller.error(error)
213 }
214 },
215 cancel(reason) {
216 return body.cancel(reason)
217 },
218 }),
219 { status: response.status, headers: response.headers }
220 )
221 },
222 })
223 client.stream = stream
224 client.shape = new Shape(stream)
225 stream.subscribe((messages) => {
226 for (const message of messages) {
227 if (isChangeMessage(message))
228 for (const txid of message.headers.txids ?? [])
229 receivedTxids.add(txid)
230 if (
231 isControlMessage(message) &&
232 message.headers.control === 'snapshot-end'
233 )
234 snapshot = message.headers
235 }
236 })
237 clients.push(client)
238 return client
239 }
240 const samples = async () =>
241 (await diagnostics()).filter(
242 (e) => e.instance === instance && e.timestamp >= timestampStart
243 )
244 try {
245 await db.query(
246 'insert into public.electric_items(id,label,enabled) select i,repeat($3,$4),true from generate_series($1::int,$2::int) i',
247 [lower, upper - 1, 'x', payloadChars]
248 )
249 const baselineMetrics = (await diagnostics()).findLast(
250 (e) => e.instance === instance && e.event === 'function_metrics'
251 )
252 assert(baselineMetrics, 'No Function memory samples')
253 scenario.beforeMemory = baselineMetrics.memory
254 timestampStart = Date.now()
255 began = performance.now()
256 const primary = open()
257 const baseline = await primary.shape.rows
258 const baselineReadyAt = Date.now()
259 scenario.firstUsableSnapshotMs = performance.now() - began
260 scenario.firstHeadersMs = primary.firstHeadersAt - began
261 assert.equal(baseline.length, rowCount)
262 assert(
263 baseline.every(
264 (row) =>
265 row.id >= lower &&
266 row.id < upper &&
267 row.label === 'x'.repeat(payloadChars) &&
268 row.enabled === true
269 )
270 )
271 const handle = primary.stream.shapeHandle
272 assert(handle)
273 const replayOffset = primary.stream.lastOffset
274 assert(replayOffset !== '-1')
275 await until(
276 async () =>
277 (await samples()).some(
278 (e) =>
279 e.event === 'function_metrics' &&
280 e.shapes.some(
281 (s) =>
282 s.handle === handle &&
283 s.retainedRows === rowCount &&
284 s.baselineComplete
285 )
286 ),
287 'owner baseline memory sample',
288 errors
289 )
290 scenario.afterBaseline = (await samples()).findLast(
291 (e) =>
292 e.event === 'function_metrics' &&
293 e.shapes.some((s) => s.handle === handle)
294 )
295 const baselineSamples = (await samples()).filter(
296 (e) =>
297 e.event === 'function_metrics' && e.timestamp <= baselineReadyAt
298 )
299 scenario.sampledBaselinePeakRss = Math.max(
300 ...[...baselineSamples, scenario.afterBaseline].map(
301 (e) => e.memory.rss
302 )
303 )
304 scenario.sampledBaselinePeakHeapUsed = Math.max(
305 ...[...baselineSamples, scenario.afterBaseline].map(
306 (e) => e.memory.heapUsed
307 )
308 )
309 const sealStart = performance.now()
310 await until(
311 async () =>
312 (await samples()).some(
313 (e) =>
314 e.event === 'function_metrics' &&
315 e.shapes.some(
316 (s) =>
317 s.handle === handle &&
318 s.sealedRanges > 0 &&
319 s.residentLogBytes < sealBytes
320 )
321 ),
322 'baseline offloaded to real storage',
323 errors
324 )
325 scenario.baselineOffloadMs = performance.now() - sealStart
326 scenario.afterSeal = (await samples()).findLast(
327 (e) =>
328 e.event === 'function_metrics' &&
329 e.shapes.some(
330 (s) => s.handle === handle && s.residentLogBytes < sealBytes
331 )
332 )
333 const getsBeforeFanout = (await samples()).filter(
334 (e) => e.event === 'object_get'
335 ).length
336 const warmStart = performance.now()
337 await Promise.all(
338 Array.from({ length: readerCount - 1 }, async () => {
339 const next = open({ handle, offset: '-1' })
340 const rows = await next.shape.rows
341 assert.deepEqual(rows, baseline)
342 })
343 )
344 scenario.fanoutReadyMs = performance.now() - warmStart
345 if (readerCount > 1)
346 assert(
347 (await samples()).filter((e) => e.event === 'object_get').length >
348 getsBeforeFanout,
349 'Warm readers must exercise stored objects'
350 )
351 for (let iteration = 0; iteration < mutations; iteration++) {
352 const label = `${iteration}:` + 'x'.repeat(payloadChars)
353 const start = performance.now()
354 const result = await db.query(
355 'update public.electric_items set label=$2 where id=$1 returning pg_current_xact_id()::text as txid',
356 [lower, label]
357 )
358 commitTimes.push(performance.now() - start)
359 const txid = result.rows[0].txid
360 const wrapped = Number(BigInt.asUintN(32, BigInt(txid)))
361 await until(
362 () =>
363 clients.every(
364 (c) =>
365 c.shape.currentRows.some(
366 (row) => row.id === lower && row.label === label
367 ) &&
368 (c.receivedTxids.has(wrapped) ||
369 (c.snapshot() && isVisibleInSnapshot(txid, c.snapshot())))
370 ),
371 'all readers observe and acknowledge committed write',
372 errors
373 )
374 times.push(performance.now() - start)
375 assert(
376 clients.every((c) => c.stream.shapeHandle === handle),
377 'Owner unexpectedly refetched during live measurement'
378 )
379 }
380 scenario.liveEndToEndMs = summary(times)
381 scenario.commitReturnMs = summary(commitTimes)
382 const liveCompletedAt = Date.now()
383 await until(
384 async () =>
385 (await samples()).some(
386 (e) =>
387 e.event === 'function_metrics' &&
388 e.timestamp >= liveCompletedAt &&
389 e.shapes.some((s) => s.handle === handle)
390 ),
391 'post-write log sample',
392 errors
393 )
394 scenario.afterLive = (await samples()).findLast(
395 (e) =>
396 e.event === 'function_metrics' &&
397 e.shapes.some((s) => s.handle === handle)
398 )
399 const logBytes = (sample) =>
400 BigInt(
401 sample.shapes
402 .find((s) => s.handle === handle)
403 .offset.split('_')[1]
404 )
405 scenario.liveLogGrowthBytes = Number(
406 logBytes(scenario.afterLive) - logBytes(scenario.afterSeal)
407 )
408 const expected = (
409 await db.query(
410 'select id,label,enabled from public.electric_items where id >= $1 and id < $2 order by id',
411 [lower, upper]
412 )
413 ).rows
414 for (const client of clients)
415 assert.deepEqual(
416 [...client.shape.currentRows].sort((a, b) => a.id - b.id),
417 expected
418 )
419 for (const client of clients) {
420 client.abort.abort()
421 client.stream.unsubscribeAll()
422 }
423 const replayStart = performance.now()
424 const replay = open({
425 handle,
426 offset: replayOffset,
427 subscribe: false,
428 })
429 const delta = await replay.shape.rows
430 scenario.deltaReplayMs = performance.now() - replayStart
431 assert.deepEqual(delta, [expected[0]])
432 assert.equal(replay.stream.shapeHandle, handle)
433 scenario.deltaReplayBytes = replay.bytes
434 replay.abort.abort()
435 await deleteHandle(params, handle, false)
436 const refetchStart = performance.now()
437 const refetch = open({
438 handle,
439 offset: replay.stream.lastOffset,
440 subscribe: false,
441 })
442 assert.deepEqual(
443 (await refetch.shape.rows).sort((a, b) => a.id - b.id),
444 expected
445 )
446 scenario.refetchMs = performance.now() - refetchStart
447 assert.notEqual(refetch.stream.shapeHandle, handle)
448 refetch.abort.abort()
449 const observed = await samples()
450 const metrics = observed.filter((e) => e.event === 'function_metrics')
451 assert(metrics.length > 0)
452 assert(
453 metrics.flatMap((e) => e.shapes).some((s) => s.sealedRanges > 0),
454 'Run this gate against an object-backed Function'
455 )
456 scenario.sampledPeakRss = Math.max(
457 ...metrics.map((e) => e.memory.rss)
458 )
459 scenario.sampledPeakHeapUsed = Math.max(
460 ...metrics.map((e) => e.memory.heapUsed)
461 )
462 scenario.totalResponseBytes = clients.reduce(
463 (total, c) => total + c.bytes,
464 0
465 )
466 scenario.getRequests = requests.length
467 scenario.elapsedMs = performance.now() - began
468 scenario.status = 'passed'
469 } catch (error) {
470 scenario.status = 'failed'
471 scenario.error = String(error)
472 throw error
473 } finally {
474 for (const client of clients) {
475 client.abort.abort()
476 client.stream.unsubscribeAll()
477 }
478 for (const handle of handles) await deleteHandle(params, handle)
479 const deletedAt = Date.now()
480 await db.query(
481 'delete from public.electric_items where id >= $1 and id < $2',
482 [lower, upper]
483 )
484 assert.equal(
485 (
486 await db.query(
487 'select count(*)::int as count from public.electric_items where id >= $1 and id < $2',
488 [lower, upper]
489 )
490 ).rows[0].count,
491 0
492 )
493 if (timestampStart) {
494 await until(async () => {
495 const events = await samples()
496 return events.some(
497 (e) =>
498 e.event === 'function_metrics' &&
499 e.timestamp >= deletedAt &&
500 e.pendingObjectCleanups === 0 &&
501 !e.shapes.some((s) => handles.has(s.handle))
502 )
503 }, 'all handle and object cleanup completed')
504 const observed = await samples()
505 const puts = observed.filter((e) => e.event === 'object_put')
506 const gets = observed.filter((e) => e.event === 'object_get')
507 scenario.objectStore = {
508 puts: puts.length,
509 gets: gets.length,
510 deletes: observed.filter((e) => e.event === 'object_delete')
511 .length,
512 putBytes: puts.reduce((n, e) => n + e.bytes, 0),
513 getBytes: gets.reduce((n, e) => n + e.bytes, 0),
514 putServiceTimeMs: puts.reduce((n, e) => n + e.elapsedMs, 0),
515 failures: observed.filter(
516 (e) =>
517 (e.event === 'object_put_failed' ||
518 e.event === 'object_get_failed') &&
519 !e.aborted
520 ).length,
521 cancelled: observed.filter(
522 (e) =>
523 (e.event === 'object_put_failed' ||
524 e.event === 'object_get_failed') &&
525 e.aborted
526 ).length,
527 }
528 assert.equal(
529 scenario.objectStore.failures,
530 0,
531 'Unexpected storage failure during performance acceptance'
532 )
533 scenario.objectStore.putBytesPerServiceSecond =
534 (scenario.objectStore.putBytes /
535 scenario.objectStore.putServiceTimeMs) *
536 1000
537 }
538 await writeFile(output, JSON.stringify(report, null, 2) + '\n')
539 }
540 console.log(
541 `Performance passed: ${rowCount} rows, ${readerCount} readers, ${liveSse ? 'SSE' : 'polling'}; snapshot=${Math.round(scenario.firstUsableSnapshotMs)}ms live p95=${Math.round(scenario.liveEndToEndMs.p95)}ms`
542 )
543 }
544 report.status = 'passed'
545} catch (error) {
546 report.status = 'failed'
547 report.error = String(error)
548 throw error
549} finally {
550 report.completedAt = new Date().toISOString()
551 await db.end()
552 await writeFile(output, JSON.stringify(report, null, 2) + '\n')