Open History to see the last commit
1import { createHash, randomUUID } from 'node:crypto'
2import { execFileSync } from 'node:child_process'
3import { mkdir, readFile, writeFile } from 'node:fs/promises'
4import pg from 'pg'
5import { ChunkNotFoundError } from '../dist/index.js'
6import { createS3ChunkStorage } from '../dist/s3.js'
7
8// Disposable lifecycle probe. Historical recovery is provider-owned; this
9// tests current fork safety, real object deletion, and bounded maintenance.
10const env = process.env
11const state = JSON.parse(await readFile(env.NEON_TEST_STATE_FILE ?? '.neon-test-state.json', 'utf8'))
12if (state.branchId !== env.NEON_TEST_BRANCH_ID || state.projectId !== env.NEON_PROJECT_ID || state.branchId !== env.TEST_FUNCTION_BRANCH_ID
13 || !state.name.startsWith('ds-test-') || !/^ds_test_[a-f0-9]{32}$/.test(env.TEST_FUNCTION_SCHEMA ?? '')
14 || !env.TEST_FUNCTION_MAINTENANCE_KEY || !env.TEST_FUNCTION_API_KEY) throw new Error('Recorded isolated Function required')
15const seconds = Number(env.DS_RECLAMATION_SECONDS ?? 600), intervalMs = 10_000
16if (!Number.isSafeInteger(seconds) || seconds < 30 || seconds > 3600) throw new RangeError('Collection qualification needs 30–3600 seconds')
17const schema = `"${env.TEST_FUNCTION_SCHEMA}"`, run = `reclaim-${randomUUID()}`, records = [], samples = [], errors = []
18const startedAt = new Date().toISOString(), started = performance.now()
19const harnessCommit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
20const harnessSha256 = createHash('sha256').update(await readFile(new URL(import.meta.url))).digest('hex')
21const pool = new pg.Pool({ connectionString: env.TEST_DATABASE_URL_UNPOOLED, max: 2, connectionTimeoutMillis: 10_000, query_timeout: 15_000 })
22pool.on('error', (error) => errors.push({ phase: 'database', name: error.name }))
23const objects = createS3ChunkStorage({ endpoint: env.AWS_ENDPOINT_URL_S3, region: env.AWS_REGION, bucket: env.NEON_TEST_BUCKET })
24let stopped = false
25process.once('SIGINT', () => { stopped = true })
26process.once('SIGTERM', () => { stopped = true })
27const request = (path, method = 'GET', body, headers = {}) => fetch(new URL(path, env.TEST_FUNCTION_URL), {
28 method, headers: { Authorization: `Bearer ${env.TEST_FUNCTION_API_KEY}`, 'Content-Type': 'application/octet-stream', ...headers },
29 ...(body === undefined ? {} : { body }), signal: AbortSignal.timeout(30_000),
30})
31const expectStatus = async (response, status) => {
32 if (response.status !== status) { await response.arrayBuffer(); throw new Error(`Fixture HTTP ${response.status}; expected ${status}`) }
33 return response
34}
35const maintain = async () => {
36 const response = await expectStatus(await request('_maintenance', 'POST', undefined, { 'x-ds-maintenance-key': env.TEST_FUNCTION_MAINTENANCE_KEY }), 200)
37 return response.json()
38}
39const stream = (path) => `v1/stream/${path}`
40async function sample() {
41 // Check every retained key independently; ledger rows may already be pruned.
42 for (const record of records.filter((value) => !value.collectedAt)) {
43 try { await objects.get(record.objectKey, record.encodedBytes) }
44 catch (error) {
45 if (!(error instanceof ChunkNotFoundError)) throw error
46 record.collectedAt = new Date().toISOString()
47 }
48 }
49 const counts = (await pool.query(`SELECT
50 (SELECT count(*) FROM ${schema}.streams WHERE path LIKE $1) AS generations,
51 (SELECT count(*) FROM ${schema}.paths WHERE path LIKE $1) AS namespaces,
52 (SELECT count(*) FROM ${schema}.chunks WHERE stream_id=ANY($2::uuid[])) AS chunks,
53 (SELECT count(*) FROM ${schema}.chunk_objects WHERE stream_id=ANY($2::uuid[])) AS receipts`, [`${run}/%`, records.map((record) => record.streamId)])).rows[0]
54 samples.push({ elapsedSeconds: (performance.now() - started) / 1000, created: records.length,
55 verifiedMissing: records.filter((record) => record.collectedAt).length,
56 generations: Number(counts.generations), namespaces: Number(counts.namespaces), chunks: Number(counts.chunks), objectReceipts: Number(counts.receipts) })
57 return samples.at(-1)
58}
59try {
60 if (!(await pool.query(`SELECT 1 FROM ${schema}.migrations WHERE id='0004_subscriptions'`)).rowCount
61 || !(await pool.query(`SELECT enabled FROM ${schema}.reclamation_policy`)).rows[0]?.enabled) throw new Error('Current baseline with explicit collection opt-in required')
62 for (let sequence = 0; !stopped && performance.now() - started < seconds * 1000; sequence++) {
63 const cycle = performance.now(), path = `${run}/${sequence}`, child = `${path}-fork`, payload = Buffer.alloc(65536, sequence % 256)
64 payload.write(`${run}:${sequence}`)
65 await (await expectStatus(await request(stream(path), 'PUT', payload), 201)).arrayBuffer()
66 let manifest
67 for (let n = 0; n < 8; n++) {
68 await maintain()
69 manifest = (await pool.query(`SELECT c.* FROM ${schema}.chunks c JOIN ${schema}.streams s ON s.id=c.stream_id
70 WHERE s.path=$1 AND s.tenant_id='function-a' AND c.state='sealed'`, [path])).rows[0]
71 if (manifest) break
72 }
73 if (!manifest) throw new Error('Ephemeral payload did not seal')
74 await (await expectStatus(await request(stream(child), 'PUT', undefined, { 'Stream-Forked-From': `/v1/stream/${path}` }), 201)).arrayBuffer()
75 records.push({ sequence, path, streamId: manifest.stream_id, chunkId: manifest.id, objectKey: manifest.object_key, encodedBytes: manifest.encoded_bytes })
76 await (await expectStatus(await request(stream(path), 'DELETE'), 204)).arrayBuffer()
77 await maintain()
78 const replay = await expectStatus(await request(stream(child)), 200)
79 if (!Buffer.from(await replay.arrayBuffer()).equals(payload)) throw new Error('Deleted parent fork lost exact sealed bytes')
80 await (await expectStatus(await request(stream(child), 'DELETE'), 204)).arrayBuffer()
81 if (sequence % 3 === 0) console.log(JSON.stringify(await sample()))
82 await new Promise((resolve) => setTimeout(resolve, Math.max(0, intervalMs - (performance.now() - cycle))))
83 }
84 // Explicitly measure the bounded post-load drain instead of assuming a cron
85 // alone kept pace. This is a lifecycle probe, not scheduler capacity proof.
86 const drainStarted = performance.now()
87 let drained = false
88 for (let n = 0; n < 128; n++) {
89 await maintain()
90 const current = await sample()
91 if (current.verifiedMissing === records.length && !current.generations && !current.namespaces && !current.chunks && !current.objectReceipts) { drained = true; break }
92 if (performance.now() - drainStarted > 120_000) break
93 }
94 if (stopped || !records.length || !drained) throw new Error('Collection/metadata drain did not complete within the probe budget')
95} catch (error) { errors.push({ phase: 'collection-qualification', name: error.name, message: error.message }) }
96finally {
97 objects.close(); await pool.end()
98 const verifiedMissing = records.filter((record) => record.collectedAt).length
99 const report = { generatedAt: new Date().toISOString(), startedAt, harnessCommit, harnessSha256,
100 deployedSourceCommit: env.TEST_FUNCTION_SOURCE_COMMIT, deployedSourceDirty: env.TEST_FUNCTION_SOURCE_DIRTY,
101 bundleSha256: env.TEST_FUNCTION_BUNDLE_SHA, deploymentId: env.TEST_FUNCTION_DEPLOYMENT_ID,
102 profile: { seconds, intervalMs, recovery: 'provider-owned', sourceBytes: 65536, forksPerSource: 1, explicitMaintenance: true },
103 run, elapsedSeconds: (performance.now() - started) / 1000, created: records.length, verifiedMissing, records, samples, errors, passed: errors.length === 0 }
104 await mkdir('qualification-results', { recursive: true })
105 await writeFile(`qualification-results/${run}.json`, JSON.stringify(report, null, 2) + '\n')
106 console.log(JSON.stringify({ run, passed: report.passed, created: records.length, verifiedMissing, errors }))
107 if (!report.passed) process.exitCode = 1
108}