Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

release-history-oracle.property.test.js

413 lines14.4 KB

1/**
2 * An RC release is a sequence, not an isolated version-string calculation.
3 * The shared independent ledger states the authority and finite grammar.
4 * This receiver runs real Changesets pre entry/exit and the production version
5 * functions in disposable workspaces. After every action it compares package
6 * versions, dependency protocols, consumed IDs and changelog attribution.
7 *
8 * The first/9-counter boundaries, independent stable work, maximum bump type,
9 * direct versus peer edges and insertion order form a finite exhaustive set.
10 * Unknown packages, reused IDs and release types outside the grammar are not
11 * legal histories. Failure histories inject one seed write/pre-entry/changelog
12 * failure and demand exact restoration before a successful retry. These are
13 * initial seeding boundaries, not an atomicity promise for every later tool.
14 * Direct finite replay uses the shared PROPERTY/SEED/PATH interface. Property
15 * scripts.release-version or scripts.release-seed-failure selects the family;
16 * PATH is one finite case index. The required SEED is inert for enumeration.
17 * Replay selects that input immediately and keeps every applicable local cut.
18 * No install, tarball, registry HTTP, or installed-consumer behavior is claimed.
19 */
20import assert from 'node:assert/strict'
21import { existsSync, readFileSync, writeFileSync } from 'node:fs'
22import { join } from 'node:path'
23import { afterAll, expect, test, vi } from 'vitest'
24import { declareOracle } from '../packages/db/tests/oracle-declaration.js'
25import { createOracleReach } from '../packages/db/tests/oracle-reach.js'
26import {
27 oracleReplayRequested,
28 oracleReplaySkips,
29 oracleReplayTest,
30 readOracleRunConfig,
31} from '../packages/db/tests/oracle-config.js'
32import { recordOracleFiniteReplay } from '../packages/db/tests/oracle-replay-witness.js'
33import { withFiniteComparison } from './finite-comparison.js'
34import {
35 applyReleaseVersion,
36 checkReleaseObservation,
37 createReleaseModel,
38 queueRelease,
39 releaseHistories,
40 seedFailureHistories,
41} from './release-history-oracle.js'
42import {
43 addFixtureChangeset,
44 enterRealPreMode,
45 exitRealPreMode,
46 observeRelease,
47 repeatStableVersion,
48 withReleaseWorkspace,
49 workspaceBytes,
50} from './release-fixture.js'
51import {
52 seedFirstCandidate,
53 versionDuringRc,
54 versionOnRcExit,
55} from './version-packages.mjs'
56​
57// Faults affect only seedFirstCandidate's synchronous write boundary. A single
58// failure disarms itself so restoration can proceed. Fixture writes occur while
59// disarmed; CJS Changesets writes are not counted as intercepted seed writes.
60const fault = vi.hoisted(() => ({
61 remaining: undefined,
62 reached: false,
63 afterApply: false,
64 appliedToken: false,
65}))
66vi.mock('node:fs', async (importOriginal) => {
67 const actual = await importOriginal()
68 return {
69 ...actual,
70 writeFileSync(...args) {
71 if (fault.remaining !== undefined) {
72 if (fault.remaining-- === 0) {
73 fault.remaining = undefined
74 fault.reached = true
75 throw new Error('injected seed write failure')
76 }
77 }
78 return actual.writeFileSync(...args)
79 },
80 }
81})
82vi.mock('@changesets/apply-release-plan', async (importOriginal) => {
83 const actual = await importOriginal()
84 const apply =
85 typeof actual.default === 'function'
86 ? actual.default
87 : actual.default.default
88 return {
89 ...actual,
90 default: async (...args) => {
91 const result = await apply(...args)
92 if (fault.afterApply) {
93 fault.afterApply = false
94 fault.reached = true
95 const fs = await vi.importActual('node:fs')
96 const path = join(args[4], 'packages', 'db', 'CHANGELOG.md')
97 fault.appliedToken = fs
98 .readFileSync(path, 'utf8')
99 .includes('release-token:first-rc')
100 throw new Error('injected failure after release files applied')
101 }
102 return result
103 },
104 }
105})
106​
107const first = { db: 'major', react: 'major', query: 'minor', offline: 'minor' }
108const VERSION = 'scripts.release-version'
109const FAILURE = 'scripts.release-seed-failure'
110const replay = readOracleRunConfig()
111const selected = oracleReplayRequested() && !oracleReplaySkips(VERSION, FAILURE)
112const caseIndex = selected ? Number(replay.replayPath) : 0
113if (
114 selected &&
115 (!/^\d+$/.test(replay.replayPath) ||
116 !Number.isSafeInteger(caseIndex) ||
117 caseIndex >=
118 (replay.replayProperty === VERSION
119 ? releaseHistories
120 : seedFailureHistories
121 ).length)
123 throw new Error('Finite release replay PATH must be one existing case index')
124async function recordFiniteComparison(property, action) {
125 return withFiniteComparison(action, ({ failed }) => {
126 if (selected && replay.replayProperty === property)
127 recordOracleFiniteReplay(property, {
128 seed: replay.replaySeed,
129 path: replay.replayPath,
130 failed,
131 })
132 })
134const versionReach = createOracleReach(
135 'release.version-history',
136 [
137 'first-candidate',
138 'candidate-nine-to-ten',
139 'patch-nine-to-ten',
140 'mixed-work',
141 'stable-only-work',
142 'bump-precedence',
143 'no-op',
144 'consumed-minor-pending-patch-exit',
145 'dependent-stable-exit',
146 'stable-no-op',
147 'exit-no-pending',
148 'exit-stable-only',
149 'exit-candidate-pending',
150 ],
151 { replaying: false },
153const failureReach = createOracleReach(
154 'release.seed-failure',
155 seedFailureHistories.map(
156 ({ failure, stableDependency }) => `${failure}/${stableDependency}`,
157 ),
158 { replaying: false },
160afterAll(() => {
161 // Direct finite replay keeps its local required cuts. The normal campaign
162 // additionally requires all axes. Generic -t slicing is not finite replay.
163 if (!oracleReplayRequested()) {
164 versionReach.assertReached()
165 failureReach.assertReached()
166 }
167 if (process.env.TANSTACK_DB_ORACLE_STATISTICS === '1')
168 console.info('release history reach', {
169 version: Object.fromEntries(versionReach.counts()),
170 failure: Object.fromEntries(failureReach.counts()),
171 })
172})
173​
174declareOracle({
175 check: [checkReleaseObservation],
176 model: [createReleaseModel, applyReleaseVersion, queueRelease],
177 grammar: [releaseHistories, seedFailureHistories],
178})
179​
180oracleReplayTest(test, VERSION).each(
181 oracleReplayRequested() ? [releaseHistories[caseIndex]] : releaseHistories,
182)(
183 'release version history %j',
184 async (history) => {
185 versionReach.beginHistory()
186 const local = createOracleReach(
187 'one release version history',
188 [
189 'first-candidate',
190 'mixed-work',
191 'stable-only-work',
192 'bump-precedence',
193 'no-op',
194 'stable-no-op',
195 ...(history.boundary === 'candidate-nine'
196 ? ['candidate-nine-to-ten']
197 : []),
198 ...(history.boundary === 'patch-nine' ? ['patch-nine-to-ten'] : []),
199 ...(history.stableDependency ? ['dependent-stable-exit'] : []),
200 ...(history.exitWork !== 'none' && history.strongest === 'minor'
201 ? ['consumed-minor-pending-patch-exit']
202 : []),
203 history.exitWork === 'none'
204 ? 'exit-no-pending'
205 : history.exitWork === 'stable-only'
206 ? 'exit-stable-only'
207 : 'exit-candidate-pending',
208 ],
209 { replaying: false },
210 )
211 local.beginHistory()
212 const reached = (state) => {
213 versionReach.reach(state)
214 local.reach(state)
215 }
216 await recordFiniteComparison(VERSION, (comparison) =>
217 withReleaseWorkspace(async (fixture) => {
218 const { root } = fixture
219 let model = createReleaseModel(history.stableDependency)
220 const queue = (id, releases) => {
221 addFixtureChangeset(root, id, releases)
222 queueRelease(model, id, releases)
223 }
224 const compare = (checkpoint) => {
225 comparison()
226 checkReleaseObservation(observeRelease(fixture), model, checkpoint)
227 }
228 const version = async (checkpoint) => {
229 await versionDuringRc(root)
230 model = applyReleaseVersion(model)
231 compare(checkpoint)
232 }
233 queue('first-rc', first)
234 await seedFirstCandidate(root, () => enterRealPreMode(root))
235 model = applyReleaseVersion(model)
236 compare('first candidate')
237 reached('first-candidate')
238​
239 if (history.boundary === 'candidate-nine') {
240 for (let index = 1; index <= 8; index++) {
241 queue(`warm-minor-${index}`, { db: 'minor' })
242 await version(`candidate warmup ${index}`)
243 }
244 } else if (history.boundary === 'patch-nine') {
245 for (let index = 1; index <= 9; index++) {
246 queue(`warm-patch-${index}`, { db: 'patch' })
247 await version(`patch warmup ${index}`)
248 }
249 }
250 queue('isolated-stable', { offline: 'patch' })
251 await version('stable work without any candidate release')
252 reached('stable-only-work')
253 const mixed = [
254 ['mixed-patch', { db: 'patch', query: 'patch' }],
255 ['stable-only', { offline: 'patch' }],
256 ]
257 if (history.reverse) mixed.reverse()
258 for (const [id, releases] of mixed) queue(id, releases)
259 await version('mixed and stable-only work')
260 reached('mixed-work')
261 if (history.boundary === 'patch-nine') reached('patch-nine-to-ten')
262 const beforeNoop = workspaceBytes(root)
263 await version('repeat without pending work')
264 assert.deepEqual(
265 workspaceBytes(root),
266 beforeNoop,
267 'no-op preserves workspace bytes',
268 )
269 reached('no-op')
270​
271 const precedence = [
272 ['weaker', { db: 'patch', query: 'patch' }],
273 ['stronger', { db: history.strongest, query: history.strongest }],
274 ]
275 if (history.reverse) precedence.reverse()
276 for (const [id, releases] of precedence) queue(id, releases)
277 await version('strongest pending bump wins')
278 reached('bump-precedence')
279 if (history.boundary === 'candidate-nine')
280 reached('candidate-nine-to-ten')
281 queue('independent-candidate', { react: 'patch' })
282 await version('independent candidate patch')
283 if (history.exitWork !== 'none')
284 queue('pending-at-exit', {
285 ...(history.exitWork === 'candidate-and-stable'
286 ? { db: 'patch' }
287 : {}),
288 query: 'patch',
289 })
290 exitRealPreMode(root)
291 await versionOnRcExit(root)
292 model = applyReleaseVersion(model, { exit: true })
293 compare('exit applies pending IDs once')
294 if (history.exitWork !== 'none' && history.strongest === 'minor')
295 reached('consumed-minor-pending-patch-exit')
296 reached(
297 history.exitWork === 'none'
298 ? 'exit-no-pending'
299 : history.exitWork === 'stable-only'
300 ? 'exit-stable-only'
301 : 'exit-candidate-pending',
302 )
303 if (history.stableDependency) reached('dependent-stable-exit')
304 const afterExit = workspaceBytes(root)
305 repeatStableVersion(root)
306 compare('stable no-op after exit')
307 assert.deepEqual(
308 workspaceBytes(root),
309 afterExit,
310 'stable no-op preserves bytes',
311 )
312 reached('stable-no-op')
313 local.assertReached()
314 }, history.stableDependency),
315 )
316 },
317 20_000,
319​
320oracleReplayTest(test, FAILURE).each(
321 oracleReplayRequested()
322 ? [seedFailureHistories[caseIndex]]
323 : seedFailureHistories,
324)(
325 'first candidate failure and retry %j',
326 async (history) => {
327 failureReach.beginHistory()
328 const local = createOracleReach(
329 'one seed failure history',
330 ['restored', 'retried'],
331 { replaying: false },
332 )
333 local.beginHistory()
334 await recordFiniteComparison(FAILURE, (comparison) =>
335 withReleaseWorkspace(async (fixture) => {
336 const { root } = fixture
337 const model = createReleaseModel(history.stableDependency)
338 addFixtureChangeset(root, 'first-rc', first)
339 queueRelease(model, 'first-rc', first)
340 // Existing changelog bytes and the absence of others both require restore.
341 writeFileSync(
342 join(root, 'packages', 'db', 'CHANGELOG.md'),
343 '# Existing\n',
344 )
345 const before = workspaceBytes(root)
346 const writeIndex = [
347 'first-manifest',
348 'second-manifest',
349 'release-config',
350 ].indexOf(history.failure)
351 fault.remaining = writeIndex < 0 ? undefined : writeIndex
352 fault.reached = false
353 fault.afterApply = history.failure === 'after-apply'
354 fault.appliedToken = false
355 if (history.failure === 'changelog')
356 process.env.RELEASE_ORACLE_CHANGELOG_FAIL = root
357 try {
358 await expect(
359 seedFirstCandidate(root, () => {
360 if (history.failure === 'before-pre') {
361 fault.reached = true
362 throw new Error('injected pre-entry failure')
363 }
364 enterRealPreMode(root)
365 if (history.failure === 'after-pre') {
366 fault.reached = true
367 throw new Error('injected post-entry failure')
368 }
369 }),
370 ).rejects.toThrow(/injected/)
371 if (history.failure === 'changelog') fault.reached = true
372 } finally {
373 fault.remaining = undefined
374 fault.afterApply = false
375 delete process.env.RELEASE_ORACLE_CHANGELOG_FAIL
376 }
377 assert.equal(fault.reached, true, 'the intended failure boundary ran')
378 if (history.failure === 'after-apply')
379 assert.equal(
380 fault.appliedToken,
381 true,
382 'generated changelog write precedes the fault',
383 )
384 comparison()
385 assert.deepEqual(
386 workspaceBytes(root),
387 before,
388 'failed first candidate restores every fixture byte',
389 )
390 assert.equal(existsSync(join(root, '.changeset', 'pre.json')), false)
391 local.reach('restored')
392 failureReach.reach(`${history.failure}/${history.stableDependency}`)
393 await seedFirstCandidate(root, () => enterRealPreMode(root))
394 const expected = applyReleaseVersion(model)
395 checkReleaseObservation(
396 observeRelease(fixture),
397 expected,
398 'retry after seed failure',
399 )
400 local.reach('retried')
401 assert.equal(
402 readFileSync(
403 join(root, 'packages', 'db', 'CHANGELOG.md'),
404 'utf8',
405 ).match(/release-token:first-rc/g).length,
406 expected.tokens.db.length,
407 )
408 local.assertReached()
409 }, history.stableDependency),
410 )
411 },
412 20_000,