Open History to see the last commit
1import { createHash, randomBytes, randomUUID } from 'node:crypto'
2import { execFile } from 'node:child_process'
3import { access, mkdir, readFile, writeFile } from 'node:fs/promises'
4import { join } from 'node:path'
5import { promisify } from 'node:util'
6import { build } from 'esbuild'
7import { zipSync } from 'fflate'
8import { createNeonClient } from '@neon/sdk'
9import pg from 'pg'
10import { afterAll, beforeAll, expect, test } from 'vitest'
11import { migrate, migrationPlan, STORAGE_VERSION } from '../../src/migrations.js'
12import { beginRecovery, finishRecovery, inspectInstallation, verifyRecovery } from '../../src/operations.js'
13import { createS3ChunkStorage } from '../../src/s3.js'
14import { initializeSubscriptions, parseSubscriptionKeyring } from '../../src/subscriptions.js'
15
16const env = process.env
17if (!env.NEON_API_KEY || !env.NEON_PROJECT_ID || !env.NEON_TEST_BRANCH_ID || !env.TEST_DATABASE_URL_UNPOOLED
18 || !env.NEON_REALTIME_URL || !env.NEON_REALTIME_SECRET || !env.NEON_TEST_BUCKET || !env.DURABLE_STREAMS_KEYRING
19 || !env.AWS_ENDPOINT_URL_S3 || !env.AWS_REGION) throw new Error('Multi-instance qualification requires recorded actual Neon services')
20const projectId = env.NEON_PROJECT_ID, branchId = env.NEON_TEST_BRANCH_ID
21const coordinator = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json', 'utf8')) as { projectId: string; branchId: string; name: string }
22if (coordinator.projectId !== projectId || coordinator.branchId !== branchId || !coordinator.name.startsWith('ds-test-')) throw new Error('Unrecorded multi-instance coordinator')
23const schema = `ds_test_${randomUUID().replaceAll('-', '')}`, suffix = randomUUID().replaceAll('-', '').slice(0, 12)
24const slugs = ['a', 'b', 'c', 'd'].map((label) => `dsmix${label}${suffix}`)
25const stateFile = '.neon-test-state-rolling.json', artifactsFile = '.neon-test-state-rolling-artifacts.json'
26const testSha256 = createHash('sha256').update(await readFile(new URL(import.meta.url))).digest('hex')
27const neon = createNeonClient({ apiKey: env.NEON_API_KEY, throwOnError: true, waitForReadiness: true, wait: { timeoutMs: 180_000 } })
28const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 3, connectionTimeoutMillis: 20_000, query_timeout: 60_000 })
29pool.on('error', () => {})
30const objects = createS3ChunkStorage({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, bucket: env.NEON_TEST_BUCKET })
31const keyring = parseSubscriptionKeyring(env.DURABLE_STREAMS_KEYRING)
32const adminKey = randomBytes(32).toString('hex'), userA = randomBytes(32).toString('hex'), userB = randomBytes(32).toString('hex')
33const run = promisify(execFile)
34interface Artifact { commit: string; sourceDirty: boolean; packageRoot: string; consumer: string; sourceSnapshotSha256: string; tarballSha256: string; sourceLockSha256: string; consumerLockSha256: string }
35interface Artifacts { directory: string; artifacts: { current: Artifact } }
36interface Runtime { kind: 'current'; slug: string; url: string; revision: string; instance: string; bundleSha256: string; memoryMiB: number | undefined; runtimeNode?: string; architecture?: string }
37let prepared: Artifacts, peer: Runtime, current: Runtime, owned = false
38const bundles = new Map<string, { code: Uint8Array<ArrayBuffer>; hash: string }>()
39const runtimes: Runtime[] = []
40const liveSessions = new Set<{ close(): Promise<void> }>()
41const passed: string[] = []
42let expected = 0
43function qualify(name: string, work: () => Promise<void>, timeout = 60_000) {
44 expected++
45 test(name, async () => { await work(); passed.push(name) }, timeout)
46}
47const mask = (value: string) => { if (env.GITHUB_ACTIONS === 'true') console.log(`::add-mask::${value}`) }
48async function script(path: string) {
49 try { await run(process.execPath, [path], { env, timeout: 360_000, maxBuffer: 8 * 1024 * 1024 }) }
50 catch (error) {
51 const result = error as { stdout?: string; stderr?: string }
52 await mkdir('qualification-results', { recursive: true })
53 await writeFile('qualification-results/rolling-private.log', `${result.stdout ?? ''}\n${result.stderr ?? ''}`, { mode: 0o600 })
54 throw new Error(`Rolling fixture tooling failed: ${path}; private diagnostic log saved`)
55 }
56}
57async function deploy(kind: Runtime['kind'], slot: number): Promise<Runtime> {
58 const artifact = prepared.artifacts[kind]
59 let compiled = bundles.get(kind)
60 if (!compiled) {
61 const result = await build({ entryPoints: ['test/fixtures/rolling-function.ts'], bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false,
62 external: ['pg-native', 'bufferutil', 'utf-8-validate'], alias: {
63 '@samwillis/durable-streams-neon': join(artifact.packageRoot, 'dist/index.js'),
64 '@samwillis/durable-streams-neon/neon': join(artifact.packageRoot, 'dist/neon.js'),
65 '@samwillis/durable-streams-neon/s3': join(artifact.packageRoot, 'dist/s3.js'),
66 '@samwillis/durable-streams-neon/subscriptions': join(artifact.packageRoot, 'dist/subscriptions.js'),
67 pg: join(artifact.consumer, 'node_modules/pg/lib/index.js'),
68 }, banner: { js: 'import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);' } })
69 if (result.outputFiles.length !== 1) throw new Error('Expected one self-contained multi-instance bundle')
70 const code = new Uint8Array(result.outputFiles[0]!.contents)
71 compiled = { code, hash: createHash('sha256').update(code).digest('hex') }; bundles.set(kind, compiled)
72 }
73 const slug = slugs[slot]!, instance = randomUUID()
74 const deployed = await neon.functions.deploy({ projectId, branchId, slug, runtime: 'nodejs24',
75 zip: new File([zipSync({ 'index.mjs': compiled.code })], 'multi-instance.zip', { type: 'application/zip' }),
76 environment: JSON.stringify({ DS_SCHEMA: schema, DS_ENVIRONMENT_ID: branchId, DS_BUCKET: env.NEON_TEST_BUCKET,
77 DS_KEYRING_JSON: env.DURABLE_STREAMS_KEYRING, DS_REALTIME_URL: env.NEON_REALTIME_URL, DS_REALTIME_SECRET: env.NEON_REALTIME_SECRET,
78 DS_ADMIN_KEY: adminKey, DS_USER_A_KEY: userA, DS_USER_B_KEY: userB, DS_REVISION: artifact.commit, DS_BUILD_HASH: compiled.hash, DS_INSTANCE: instance }) })
79 const deadline = Date.now() + 180_000
80 let runtime: Runtime | undefined, consecutive = 0
81 while (Date.now() < deadline) {
82 if (!runtime) {
83 const fn = await neon.functions.get({ projectId, branchId, slug })
84 if (fn.current_deployment?.id === deployed.id && fn.current_deployment.status === 'failed') throw new Error('Multi-instance Function failed to build')
85 if (fn.active_deployment?.id === deployed.id && fn.invocation_url) runtime = { kind, slug, url: fn.invocation_url,
86 revision: artifact.commit, instance, bundleSha256: compiled.hash, memoryMiB: fn.active_deployment.memory_mib }
87 }
88 if (runtime) {
89 try {
90 const response = await fetch(new URL('_health', runtime.url), { headers: { 'x-ds-admin-key': adminKey }, signal: AbortSignal.timeout(10_000) })
91 const health = response.ok ? await response.json() as Record<string, unknown> : undefined
92 if (!response.ok) await response.arrayBuffer()
93 consecutive = health?.ready === true && health.revision === artifact.commit && health.build === compiled.hash && health.instance === instance ? consecutive + 1 : 0
94 if (consecutive >= 3) {
95 if (typeof health?.runtimeNode === 'string') runtime.runtimeNode = health.runtimeNode
96 if (typeof health?.architecture === 'string') runtime.architecture = health.architecture
97 runtimes.push(runtime); return runtime
98 }
99 } catch { consecutive = 0 }
100 }
101 await new Promise((resolve) => setTimeout(resolve, 1000))
102 }
103 throw new Error('Multi-instance Function readiness deadline exceeded')
104}
105const request = (runtime: Runtime, path: string, method = 'GET', body?: string, headers: Record<string, string> = {}, signal?: AbortSignal) => fetch(new URL(`v1/stream/${path}`, runtime.url), {
106 method, headers: { Authorization: `Bearer ${userA}`, 'Content-Type': 'text/plain', ...headers }, ...(body === undefined ? {} : { body }), signal: signal ?? AbortSignal.timeout(20_000),
107})
108async function maintain(runtime: Runtime) {
109 const response = await fetch(new URL('_maintain', runtime.url), { method: 'POST', headers: { 'x-ds-admin-key': adminKey }, signal: AbortSignal.timeout(30_000) })
110 expect(response.status).toBe(200); return response.json() as Promise<{ sealed: number }>
111}
112async function read(runtime: Runtime, path: string) {
113 let offset = '-1', data = ''
114 for (let i = 0; i < 100; i++) {
115 const response = await request(runtime, `${path}?offset=${offset}`)
116 expect(response.status).toBe(200); data += await response.text()
117 if (response.headers.get('Stream-Up-To-Date') === 'true') return data
118 const next = response.headers.get('Stream-Next-Offset')!; expect(next).not.toBe(offset); offset = next
119 }
120 throw new Error('Multi-instance replay did not reach the tail')
121}
122async function open(runtime: Runtime, path: string) {
123 const abort = new AbortController()
124 const response = await request(runtime, `${path}?live=sse&offset=now`, 'GET', undefined, {}, AbortSignal.any([abort.signal, AbortSignal.timeout(10_000)]))
125 expect(response.status).toBe(200)
126 const reader = response.body!.getReader(), decoder = new TextDecoder(); let content = ''
127 const until = async (text: string) => {
128 while (!content.includes(text)) { const part = await reader.read(); if (part.done) throw new Error(`Live session ended before ${text}`); content += decoder.decode(part.value) }
129 return content
130 }
131 await until('event: control')
132 let closed = false
133 const session = { until, reader, async close() {
134 if (closed) return
135 closed = true; liveSessions.delete(session)
136 abort.abort(); await reader.cancel().catch(() => {}); reader.releaseLock()
137 } }
138 liveSessions.add(session)
139 return session
140}
141
142beforeAll(async () => {
143 for (const path of [stateFile, artifactsFile]) { try { await access(path) } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error }; throw new Error('Clean up the prior multi-instance fixture before starting another') }
144 for (const value of [adminKey, userA, userB]) mask(value)
145 const uri = new URL(env.TEST_DATABASE_URL_UNPOOLED!)
146 await writeFile(stateFile, JSON.stringify({ projectId, branchId, branchName: coordinator.name, schema, slugs, databaseHost: uri.hostname, databaseName: uri.pathname }), { flag: 'wx', mode: 0o600 })
147 owned = true
148 await script('scripts/neon-test-rolling-artifacts.mjs')
149 prepared = JSON.parse(await readFile(artifactsFile, 'utf8')) as Artifacts
150 await migrate(pool, { schema, environmentId: branchId, storageIdentity: objects.identity, maxLiveReaders: 2 })
151 await initializeSubscriptions(pool, { schema, keyring })
152 peer = await deploy('current', 0)
153 current = await deploy('current', 1)
154}, 600_000)
155afterAll(async () => {
156 await Promise.all([...liveSessions].map((session) => session.close()))
157 await pool.end(); objects.close()
158 let cleaned = false
159 try {
160 if (owned) await script('scripts/neon-test-rolling-cleanup.mjs')
161 cleaned = true
162 } finally {
163 await mkdir('qualification-results', { recursive: true })
164 await writeFile('qualification-results/rolling-upgrade.json', JSON.stringify({ passed: cleaned && passed.length === expected && expected === 8,
165 scope: 'Eight same-candidate multi-instance checks on a fresh four-file baseline; no cross-version compatibility claim', checks: { expected, passed: passed.length, names: passed }, cleaned, generatedAt: new Date().toISOString(), testSha256,
166 node: process.version, region: env.AWS_REGION,
167 artifacts: prepared ? Object.fromEntries(Object.entries(prepared.artifacts).map(([key, { packageRoot: _root, consumer: _consumer, ...artifact }]) => [key, artifact])) : {},
168 runtimes: runtimes.map(({ url: _url, ...runtime }) => runtime), storageVersion: STORAGE_VERSION,
169 migrations: (await migrationPlan(schema)).map(({ id, checksum }) => ({ id, checksum })),
170 }, null, 2) + '\n')
171 }
172}, 180_000)
173
174qualify('two packed canonical deployments share producer deduplication, ordering, and fencing', async () => {
175 expect((await request(peer, 'producer', 'PUT', 'seed;')).status).toBe(201)
176 const tuple = { 'Producer-Id': 'mixed', 'Producer-Epoch': '0', 'Producer-Seq': '0' }
177 expect((await request(peer, 'producer', 'POST', 'peer;', tuple)).status).toBe(200)
178 expect((await request(current, 'producer', 'POST', 'ignored', tuple)).status).toBe(204)
179 expect((await request(current, 'producer', 'POST', 'new;', { ...tuple, 'Producer-Seq': '1' })).status).toBe(200)
180 expect((await request(peer, 'producer', 'POST', 'ignored', { ...tuple, 'Producer-Seq': '1' })).status).toBe(204)
181 const race = await Promise.all(Array.from({ length: 8 }, (_, i) => request(i % 2 ? peer : current, 'producer', 'POST', 'race;', { ...tuple, 'Producer-Seq': '2' })))
182 expect(race.filter((response) => response.status === 200)).toHaveLength(1)
183 expect(race.filter((response) => response.status === 204)).toHaveLength(7)
184 expect((await request(current, 'producer', 'POST', 'epoch;', { ...tuple, 'Producer-Epoch': '1' })).status).toBe(200)
185 expect((await request(peer, 'producer', 'POST', 'stale', { ...tuple, 'Producer-Seq': '3' })).status).toBe(403)
186 for (const runtime of [peer, current]) expect(await read(runtime, 'producer')).toBe('seed;peer;new;race;epoch;')
187})
188
189qualify('concurrent canonical seal workers publish mutually readable chunks and retain producer sessions', async () => {
190 expect((await request(current, 'sealing', 'PUT')).status).toBe(201)
191 const parts = Array.from({ length: 20 }, (_, i) => `part-${i.toString().padStart(2, '0')};`)
192 for (let i = 0; i < parts.length; i++) expect((await request(i % 2 ? peer : current, 'sealing', 'POST', parts[i], { 'Producer-Id': 'sealer', 'Producer-Epoch': '0', 'Producer-Seq': String(i) })).status).toBe(200)
193 await Promise.all([maintain(peer), maintain(current)])
194 expect(Number((await pool.query(`SELECT count(*) FROM "${schema}".appends a JOIN "${schema}".streams s ON s.id=a.stream_id WHERE s.path='sealing' AND a.payload IS NOT NULL`)).rows[0].count)).toBe(0)
195 for (const runtime of [peer, current]) {
196 expect(await read(runtime, 'sealing')).toBe(parts.join(''))
197 expect((await request(runtime, 'sealing', 'POST', 'duplicate', { 'Producer-Id': 'sealer', 'Producer-Epoch': '0', 'Producer-Seq': '19' })).status).toBe(204)
198 }
199})
200
201qualify('canonical deployments preserve exact-number JSON and inherited sealed fork ranges', async () => {
202 const json = '[9007199254740993,1e400,-0]'
203 expect((await request(peer, 'json', 'PUT', json, { 'Content-Type': 'application/json' })).status).toBe(201)
204 await maintain(current)
205 expect((await request(current, 'json-child', 'PUT', undefined, { 'Content-Type': 'application/json', 'Stream-Forked-From': '/v1/stream/json' })).status).toBe(201)
206 expect((await request(peer, 'json-grandchild', 'PUT', undefined, { 'Content-Type': 'application/json', 'Stream-Forked-From': '/v1/stream/json-child' })).status).toBe(201)
207 expect((await request(current, 'json-partial', 'PUT', undefined, { 'Content-Type': 'application/json', 'Stream-Forked-From': '/v1/stream/json',
208 'Stream-Fork-Offset': '0000000000000000_0000000000000000', 'Stream-Fork-Sub-Offset': '2' })).status).toBe(201)
209 await maintain(peer)
210 expect(await read(peer, 'json-partial')).toBe('[9007199254740993,1e400]')
211 expect((await request(peer, 'json-subpartial', 'PUT', undefined, { 'Content-Type': 'application/json', 'Stream-Forked-From': '/v1/stream/json-partial',
212 'Stream-Fork-Offset': '0000000000000000_0000000000000000', 'Stream-Fork-Sub-Offset': '1' })).status).toBe(201)
213 expect(await read(current, 'json-subpartial')).toBe('[9007199254740993]')
214 expect((await request(peer, 'json-child', 'POST', '[42]', { 'Content-Type': 'application/json' })).status).toBe(204)
215 expect(await read(current, 'json-grandchild')).toBe(json)
216 expect(await read(peer, 'json-child')).toBe('[9007199254740993,1e400,-0,42]')
217 expect((await request(current, 'json', 'DELETE')).status).toBe(204)
218 expect((await request(peer, 'json')).status).toBe(410)
219 expect(await read(current, 'json-grandchild')).toBe(json)
220})
221
222qualify('subscription registration, dispatch, claims, and scoped acks work across canonical deployments', async () => {
223 await request(peer, 'watched', 'PUT')
224 await request(current, 'wake', 'PUT', '[]', { 'Content-Type': 'application/json' })
225 expect((await request(peer, '__ds/subscriptions/mixed', 'PUT', JSON.stringify({ type: 'pull-wake', streams: ['watched'], wake_stream: 'wake', lease_ttl_ms: 600_000 }), { 'Content-Type': 'application/json' })).status).toBe(201)
226 const appended = await request(current, 'watched', 'POST', 'first;'); expect(appended.status).toBe(204)
227 await maintain(peer)
228 const claimed = await request(current, '__ds/subscriptions/mixed/claim', 'POST', '{"worker":"current"}', { 'Content-Type': 'application/json' })
229 expect(claimed.status).toBe(200)
230 const claim = await claimed.json() as { token: string; wake_id: string; generation: number }; mask(claim.token)
231 const ack = JSON.stringify({ wake_id: claim.wake_id, generation: claim.generation, done: true, acks: [{ stream: 'watched', offset: appended.headers.get('Stream-Next-Offset') }] })
232 expect((await request(peer, '__ds/subscriptions/mixed/ack', 'POST', ack, { Authorization: `Bearer ${claim.token}`, 'Content-Type': 'application/json' })).status).toBe(200)
233 expect((await request(current, '__ds/subscriptions/mixed/ack', 'POST', ack, { Authorization: `Bearer ${claim.token}`, 'Content-Type': 'application/json' })).status).toBe(409)
234 expect((await request(peer, 'watched', 'POST', 'second;')).status).toBe(204)
235 await maintain(current)
236 const next = await request(peer, '__ds/subscriptions/mixed/claim', 'POST', '{"worker":"peer"}', { 'Content-Type': 'application/json' })
237 expect(next.status).toBe(200)
238 const fresh = await next.json() as { token: string; wake_id: string; generation: number }; mask(fresh.token)
239 expect(fresh.generation).toBeGreaterThan(claim.generation)
240 expect((await request(current, '__ds/subscriptions/mixed/release', 'POST', JSON.stringify({ wake_id: fresh.wake_id, generation: fresh.generation }), { Authorization: `Bearer ${fresh.token}`, 'Content-Type': 'application/json' })).status).toBe(204)
241})
242
243qualify('both deployed Realtime instances deliver final contiguous bytes before EOF', async () => {
244 for (const [readerRuntime, writer, path] of [[peer, current, 'peer-live'], [current, peer, 'new-live']] as const) {
245 await request(writer, path, 'PUT')
246 const live = await open(readerRuntime, path)
247 try {
248 expect((await request(writer, path, 'POST', 'final;', { 'Stream-Closed': 'true' })).status).toBe(204)
249 const content = await live.until('"streamClosed":true')
250 expect(content).toContain('data:final;')
251 expect(content.indexOf('final;')).toBeLessThan(content.indexOf('"streamClosed":true'))
252 } finally { await live.close() }
253 }
254}, 30_000)
255
256qualify('installation-wide admission bounds both deployments and releases canceled readers', async () => {
257 await request(peer, 'capacity', 'PUT')
258 const one = await open(peer, 'capacity'), two = await open(current, 'capacity')
259 try {
260 expect((await request(current, 'capacity?live=sse&offset=now')).status).toBe(429)
261 await one.close()
262 await expect.poll(async () => Number((await pool.query(`SELECT count(*) FROM "${schema}".live_leases WHERE expires_at>clock_timestamp()`)).rows[0].count), { timeout: 5000, interval: 100 }).toBeLessThan(2)
263 const replacement = await open(current, 'capacity'); await replacement.close()
264 } finally { await one.close(); await two.close() }
265 await expect.poll(async () => Number((await pool.query(`SELECT count(*) FROM "${schema}".live_leases WHERE expires_at>clock_timestamp()`)).rows[0].count), { timeout: 5000, interval: 100 }).toBe(0)
266}, 30_000)
267
268qualify('tenant and generation isolation survive multi-instance deletion and recreation', async () => {
269 await request(peer, 'generation', 'PUT', 'peer;')
270 expect((await request(current, 'generation', 'GET', undefined, { Authorization: `Bearer ${userB}` })).status).toBe(404)
271 const live = await open(current, 'generation')
272 try {
273 expect((await request(peer, 'generation', 'DELETE')).status).toBe(204)
274 expect((await request(peer, 'generation', 'PUT', 'replacement;')).status).toBe(201)
275 let content = ''
276 for (;;) { const chunk = await live.reader.read(); if (chunk.done) break; content += new TextDecoder().decode(chunk.value) }
277 expect(content).not.toContain('replacement;')
278 } finally { await live.close() }
279 expect(await read(current, 'generation')).toBe('replacement;')
280}, 20_000)
281
282qualify('recovery fences both canonical deployments and fresh artifacts resume the installation', async () => {
283 await Promise.all([maintain(peer), maintain(current)])
284 const identity = await inspectInstallation(pool, { schema })
285 const recovery = await beginRecovery(pool, { schema, operationId: randomUUID(), expectedInstallationId: identity.id,
286 expectedServingEpoch: identity.serving_epoch, environmentId: branchId, storageIdentity: objects.identity })
287 for (const runtime of [peer, current]) expect((await request(runtime, 'producer', 'POST', 'fenced;')).status).toBe(503)
288 while (!(await verifyRecovery(pool, { schema, token: recovery.token, objects, keyring, maxChunks: 8 })).complete) {}
289 await finishRecovery(pool, { schema, token: recovery.token })
290 for (const runtime of [peer, current]) expect((await request(runtime, 'producer', 'POST', 'still fenced;')).status).toBe(503)
291 const freshCurrent = await deploy('current', 2), freshPeer = await deploy('current', 3)
292 for (const runtime of [freshCurrent, freshPeer]) expect(await read(runtime, 'producer')).toBe('seed;peer;new;race;epoch;')
293 expect((await request(freshCurrent, 'producer', 'POST', 'after recovery;', { 'Producer-Id': 'mixed', 'Producer-Epoch': '1', 'Producer-Seq': '1' })).status).toBe(200)
294 expect((await request(freshPeer, 'producer', 'POST', 'duplicate', { 'Producer-Id': 'mixed', 'Producer-Epoch': '1', 'Producer-Seq': '1' })).status).toBe(204)
295 expect(await read(freshPeer, 'producer')).toBe('seed;peer;new;race;epoch;after recovery;')
296}, 480_000)