run-gates.spec.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. import { readFileSync } from 'node:fs'
  2. import { describe, expect, it, vi, type MockInstance } from 'vitest'
  3. import {
  4. cliGateOptions,
  5. collectDescendants,
  6. defaultConcurrency,
  7. formatGateResultReason,
  8. gatesForMode,
  9. parsePidPpidLines,
  10. runGate,
  11. runGates,
  12. taskkillArgs,
  13. type Gate,
  14. type GateResult,
  15. } from './run-gates.ts'
  16. /**
  17. * Capture output a gate streams through runGate's streamOutput path.
  18. * @returns the accumulated chunks and the stdout spy to restore in finally.
  19. */
  20. function captureStreamedOutput(): { writes: string[]; write: MockInstance } {
  21. const writes: string[] = []
  22. const write = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
  23. writes.push(String(chunk))
  24. return true
  25. })
  26. return { writes, write }
  27. }
  28. /**
  29. * A process has stopped executing when its /proc entry is gone, or when it
  30. * lingers as a zombie ('Z') — an un-reaped but dead entry still answers
  31. * kill(pid, 0), so existence is not a liveness check. Non-Linux falls back to
  32. * kill(pid, 0), whose ESRCH means the process is gone.
  33. */
  34. function procStopped(pid: number): boolean {
  35. if (process.platform === 'linux') {
  36. try {
  37. const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
  38. return /\)\s+Z\s/.test(stat)
  39. } catch {
  40. return true
  41. }
  42. }
  43. try {
  44. process.kill(pid, 0)
  45. return false
  46. } catch {
  47. return true
  48. }
  49. }
  50. /**
  51. * Wait until the captured output contains `marker` and the grandchild pid the
  52. * gate printed, then return that pid.
  53. * @param writes - chunks captured from the gate's streamed stdout.
  54. * @param marker - the output line that proves the gate reached the abort point.
  55. * @param deadline - fail the wait when exceeded.
  56. * @returns the grandchild pid printed by the gate script.
  57. */
  58. async function waitForGrandchildPid(writes: string[], marker: string, deadline: number): Promise<number> {
  59. let pid: number | undefined
  60. while ((pid === undefined || !writes.join('').includes(marker)) && Date.now() < deadline) {
  61. const match = writes.join('').match(/grandchild:(\d+)/)
  62. if (match !== null) pid = Number(match[1])
  63. await new Promise(resolve => setTimeout(resolve, 50))
  64. }
  65. expect(pid ?? 0).toBeGreaterThan(0)
  66. expect(writes.join('')).toContain(marker)
  67. return pid!
  68. }
  69. /**
  70. * Abort the run and assert it settles marked aborted with the grandchild no
  71. * longer executing — the abort path must have signalled it from the captured
  72. * descendant list rather than settling over a live orphan.
  73. * @param promise - the pending `runGate` promise.
  74. * @param controller - the signal source to abort.
  75. * @param pid - the grandchild pid the gate script printed.
  76. */
  77. async function abortAndExpectTreeStopped(promise: Promise<GateResult>, controller: AbortController, pid: number): Promise<void> {
  78. controller.abort()
  79. const result = await promise
  80. expect(result.aborted).toBe(true)
  81. const stopDeadline = Date.now() + 8000
  82. while (!procStopped(pid) && Date.now() < stopDeadline) {
  83. await new Promise(resolve => setTimeout(resolve, 50))
  84. }
  85. expect(procStopped(pid)).toBe(true)
  86. }
  87. function gate(id: string, options: Partial<Gate> = {}): Gate {
  88. return {
  89. id,
  90. label: id,
  91. displayCommand: `run ${id}`,
  92. command: process.execPath,
  93. args: ['-e', ''],
  94. ...options,
  95. }
  96. }
  97. function resultFor(subject: Gate, status: GateResult['status'] = 'passed'): GateResult {
  98. return {
  99. gate: subject,
  100. status,
  101. durationMs: 10,
  102. output: [],
  103. exitCode: status === 'passed' ? 0 : 1,
  104. signalCode: null,
  105. }
  106. }
  107. function withPnpmEntrypoint<T>(action: () => T, entrypoint = '/private/pnpm.cjs'): T {
  108. const previous = process.env.npm_execpath
  109. process.env.npm_execpath = entrypoint
  110. try {
  111. return action()
  112. } finally {
  113. if (previous === undefined) Reflect.deleteProperty(process.env, 'npm_execpath')
  114. else process.env.npm_execpath = previous
  115. }
  116. }
  117. function withEnv<T>(name: string, value: string | undefined, action: () => T): T {
  118. const previous = process.env[name]
  119. if (value === undefined) Reflect.deleteProperty(process.env, name)
  120. else process.env[name] = value
  121. try {
  122. return action()
  123. } finally {
  124. if (previous === undefined) Reflect.deleteProperty(process.env, name)
  125. else process.env[name] = previous
  126. }
  127. }
  128. describe('gate graph validation', () => {
  129. it.each([
  130. 'ci-primary',
  131. 'ci-linux-primary',
  132. 'ci-static',
  133. 'ci-lint-contracts-ready',
  134. 'ci-coverage',
  135. 'ci-bench',
  136. 'ci-snapshot',
  137. 'ci-artifacts',
  138. 'ci-consumers',
  139. 'ci-windows-blocking',
  140. 'ci-windows-complete',
  141. 'ci-windows-observational',
  142. 'node-compat',
  143. 'check-all',
  144. 'hygiene',
  145. 'doc-sync',
  146. 'doc-quick',
  147. ] as const)('constructs and executes preflight for a valid non-empty %s graph', async (mode) => {
  148. const subject = withPnpmEntrypoint(() => gatesForMode(mode))
  149. const execute = vi.fn(async (item: Gate) => resultFor(item))
  150. await expect(runGates(subject, subject.length, execute)).resolves.toHaveLength(subject.length)
  151. })
  152. it('builds the native addon before benchmarks through the ci-bench script chain', () => {
  153. const subject = withPnpmEntrypoint(() => gatesForMode('ci-bench'))
  154. const { scripts } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as {
  155. scripts: Record<string, string>
  156. }
  157. expect(scripts['check:ci:bench']).toBe('tsx scripts/run-gates.ts ci-bench')
  158. expect(subject).toHaveLength(1)
  159. expect(subject[0]).toMatchObject({
  160. id: 'bench',
  161. displayCommand: 'pnpm run test:bench',
  162. args: ['/private/pnpm.cjs', 'run', 'test:bench'],
  163. })
  164. expect(scripts['test:bench']).toBe('npm run build:bench && npm run build:web && npm run test:bench:built')
  165. expect(scripts['build:bench']).toBe(
  166. 'npm run build:native-system && npm run build:lib && tsdown --config benchmarks/tsdown.config.ts',
  167. )
  168. expect(scripts['build:native-system']).toBe('tsx native/system/scripts/build.ts --host-addon-only')
  169. expect(scripts['test:bench:built']).toBe('vitest run --config vitest.bench.config.ts')
  170. })
  171. it('keeps the public repository link policy in the documentation gate', () => {
  172. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  173. expect(ids).toContain('public-repository-links')
  174. })
  175. it('keeps the concrete terminology policy in the documentation gate', () => {
  176. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  177. expect(ids).toContain('concrete-terms')
  178. })
  179. it('keeps package-group subsystem ownership in the documentation gate', () => {
  180. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  181. expect(ids).toContain('subsystem-pages')
  182. })
  183. it('keeps the package README Summary limit in the documentation gate', () => {
  184. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  185. expect(ids).toContain('package-readme-summaries')
  186. })
  187. it('derives the quick documentation aggregate from marked doc-sync leaves', () => {
  188. const full = withPnpmEntrypoint(() => gatesForMode('doc-sync'))
  189. const quick = withPnpmEntrypoint(() => gatesForMode('doc-quick'))
  190. expect(quick).toEqual(full.filter(gate => gate.quick === true))
  191. })
  192. it('keeps the hygiene aggregate aligned with the package script checks', () => {
  193. const ids = withPnpmEntrypoint(() => gatesForMode('hygiene').map(subject => subject.id))
  194. expect(ids).toEqual([
  195. 'rescope-vendor', 'publint', 'constraints', 'package-dependencies', 'application-entrypoints',
  196. 'dsh-package-licenses', 'package-invariants', 'built-package-invariants', 'node-next-types',
  197. 'optional-dependency-imports', 'client-packages', 'client-ui-i18n', 'no-bare-dispatcher', 'cordis-config',
  198. 'runtime-closure',
  199. ])
  200. expect(defaultConcurrency('hygiene', ids.length, 8)).toEqual({
  201. workers: 4,
  202. source: '8 available CPU(s), hygiene cap 4',
  203. })
  204. })
  205. it('schedules the longest documentation leaves before short checks', () => {
  206. const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
  207. expect(ids.slice(0, 10)).toEqual([
  208. 'doc-typecheck', 'docs-site-build', 'doc-graphs', 'markdown-links', 'type-equivalence',
  209. 'cordis-catalog', 'cordis-inspect-catalog', 'mermaid', 'scoped-events', 'translation-pairing',
  210. ])
  211. })
  212. it('launches a native pnpm entrypoint directly', () => {
  213. const entrypoint = String.raw`C:\Program Files\pnpm\pnpm.exe`
  214. const subject = withPnpmEntrypoint(() => gatesForMode('ci-windows-blocking')[0], entrypoint)
  215. expect(subject).toMatchObject({
  216. command: entrypoint,
  217. args: ['run', 'build'],
  218. })
  219. })
  220. it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
  221. 'keeps the DSH package license policy in %s',
  222. (mode) => {
  223. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  224. expect(ids).toContain('dsh-package-licenses')
  225. },
  226. )
  227. it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
  228. 'keeps package dependency enforcement in %s',
  229. (mode) => {
  230. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  231. expect(ids).toContain('package-dependencies')
  232. },
  233. )
  234. it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
  235. 'keeps the client dependency policy in %s',
  236. (mode) => {
  237. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  238. expect(ids).toContain('client-packages')
  239. },
  240. )
  241. it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
  242. 'keeps weighted approval policy tests in %s',
  243. (mode) => {
  244. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  245. expect(ids).toContain('approval-policy')
  246. },
  247. )
  248. it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
  249. 'keeps hard-coded Client UI copy enforcement in %s',
  250. (mode) => {
  251. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  252. expect(ids).toContain('client-ui-i18n')
  253. },
  254. )
  255. it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
  256. 'keeps application entrypoint enforcement in %s',
  257. (mode) => {
  258. const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
  259. expect(ids).toContain('application-entrypoints')
  260. },
  261. )
  262. it('keeps native Windows coverage blocking and behind the complete build', () => {
  263. const complete = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))
  264. const observational = withPnpmEntrypoint(() => gatesForMode('ci-windows-observational'))
  265. .filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
  266. const byId = new Map(complete.map(subject => [subject.id, subject]))
  267. expect(byId.get('coverage')?.allowFailure).not.toBe(true)
  268. expect(byId.get('coverage')?.needs).toContain('build')
  269. expect(byId.get('coverage-exempt-heavy')?.allowFailure).not.toBe(true)
  270. expect(byId.get('coverage')?.needs).toContain('build')
  271. expect(byId.get('coverage-exempt-heavy')?.needs).toContain('build')
  272. expect(byId.get('coverage-exempt-heavy')?.args).toContain(
  273. 'packages/experimental/webworker-packer/tests/image-loadable.spec.ts',
  274. )
  275. expect(observational).not.toHaveLength(0)
  276. for (const gate of observational) {
  277. const completeGate = byId.get(gate.id)
  278. expect(completeGate?.allowFailure).toBe(true)
  279. expect(completeGate?.after).toEqual(expect.arrayContaining([
  280. 'coverage',
  281. 'coverage-exempt-heavy',
  282. ]))
  283. expect(completeGate?.needs).toEqual(gate.needs)
  284. }
  285. })
  286. it('runs the Windows built-bin smoke after other observational gates settle', () => {
  287. const observational = withPnpmEntrypoint(() => gatesForMode('ci-windows-observational'))
  288. const builtBin = observational.find(gate => gate.id === 'built-bin-smoke')
  289. expect(builtBin?.after).toEqual(
  290. observational.filter(gate => gate.id !== 'built-bin-smoke').map(gate => gate.id),
  291. )
  292. const completeBuiltBin = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))
  293. .find(gate => gate.id === 'built-bin-smoke')
  294. expect(completeBuiltBin?.after).toContain('windows-site')
  295. expect(completeBuiltBin?.after).not.toContain('docs-site-build')
  296. })
  297. it('applies one configured test, polling, and hook timeout to both coverage gates', () => {
  298. const gates = withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', '15000', () =>
  299. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))
  300. for (const id of ['coverage', 'coverage-exempt-heavy']) {
  301. expect(gates.find(subject => subject.id === id)?.args).toEqual(expect.arrayContaining([
  302. '--testTimeout=15000',
  303. '--expect.poll.timeout=15000',
  304. '--hookTimeout=15000',
  305. ]))
  306. }
  307. })
  308. it('keeps Vitest timeout defaults when the coverage override is absent', () => {
  309. const gates = withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', undefined, () =>
  310. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))
  311. for (const id of ['coverage', 'coverage-exempt-heavy']) {
  312. expect(gates.find(subject => subject.id === id)?.args).not.toEqual(expect.arrayContaining([
  313. expect.stringMatching(/^--(?:testTimeout|expect\.poll\.timeout|hookTimeout)=/),
  314. ]))
  315. }
  316. })
  317. it('rejects an invalid coverage timeout before starting a gate', () => {
  318. expect(() => withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', '0', () =>
  319. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))))
  320. .toThrow('DSH_COVERAGE_TEST_TIMEOUT_MS must be a positive integer')
  321. })
  322. it('selects partitioned coverage only when explicitly configured', () => {
  323. const coverage = withEnv('DSH_COVERAGE_PARTITIONS', '3', () =>
  324. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete').find(subject => subject.id === 'coverage')))
  325. expect(coverage).toMatchObject({
  326. displayCommand: 'DSH_COVERAGE_PARTITIONS=3 pnpm run test:coverage:partitioned',
  327. args: ['/private/pnpm.cjs', 'run', 'test:coverage:partitioned'],
  328. env: { DSH_COVERAGE_EXEMPT_HEAVY: '1' },
  329. streamOutput: true,
  330. })
  331. })
  332. it('rejects an invalid coverage partition count before starting a gate', () => {
  333. expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '1', () =>
  334. withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))))
  335. .toThrow('DSH_COVERAGE_PARTITIONS must be an integer greater than 1')
  336. })
  337. it.each([
  338. ['empty', [], /gate graph has no gates/],
  339. ['duplicate ids', [gate('same'), gate('same')], /duplicate gate id "same"/],
  340. ['unknown dependencies', [gate('subject', { needs: ['missing'] })], /depends on unknown gate "missing"/],
  341. ['unknown ordering predecessors', [gate('subject', { after: ['missing'] })], /waits for unknown gate "missing"/],
  342. ['cycles', [gate('first', { needs: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/],
  343. ['mixed cycles', [gate('first', { after: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/],
  344. ] as const)('rejects %s before starting a child', async (_label, invalid, message) => {
  345. const execute = vi.fn(async (subject: Gate) => resultFor(subject))
  346. await expect(runGates([...invalid], 1, execute)).rejects.toThrow(message)
  347. expect(execute).not.toHaveBeenCalled()
  348. })
  349. it('rejects an invalid worker count before starting a child', async () => {
  350. const execute = vi.fn(async (subject: Gate) => resultFor(subject))
  351. await expect(runGates([gate('subject')], 0, execute)).rejects.toThrow('max concurrency must be a positive integer')
  352. expect(execute).not.toHaveBeenCalled()
  353. })
  354. it('skips dependents after their prerequisite fails', async () => {
  355. const dependent = gate('dependent', { needs: ['root'] })
  356. const root = gate('root')
  357. const execute = vi.fn(async (subject: Gate) => resultFor(subject, 'failed'))
  358. const results = await runGates([dependent, root], 1, execute)
  359. expect(execute).toHaveBeenCalledOnce()
  360. expect(execute).toHaveBeenCalledWith(root, undefined)
  361. expect(results[0]).toMatchObject({ gate: dependent, status: 'skipped', error: 'dependency failed or skipped: root' })
  362. })
  363. it('runs an ordered follower after its predecessor fails', async () => {
  364. const follower = gate('follower', { after: ['root'] })
  365. const root = gate('root')
  366. const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed'))
  367. const results = await runGates([follower, root], 2, execute)
  368. expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower'])
  369. expect(results.map(result => result.status)).toEqual(['passed', 'failed'])
  370. })
  371. it('runs an ordered follower after its predecessor is skipped', async () => {
  372. const follower = gate('follower', { after: ['dependent'] })
  373. const dependent = gate('dependent', { needs: ['root'] })
  374. const root = gate('root')
  375. const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed'))
  376. const results = await runGates([follower, dependent, root], 2, execute)
  377. expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower'])
  378. expect(results.map(result => result.status)).toEqual(['passed', 'skipped', 'failed'])
  379. })
  380. })
  381. describe('Oxlint gate', () => {
  382. it('uses the package script when no worker bound is configured', () => {
  383. const subject = withEnv('DSH_OXLINT_THREADS', undefined, () =>
  384. withPnpmEntrypoint(() => gatesForMode('ci-lint-contracts-ready')[0]))
  385. expect(subject).toMatchObject({
  386. id: 'lint',
  387. displayCommand: 'pnpm run lint:contracts-ready',
  388. command: process.execPath,
  389. args: ['/private/pnpm.cjs', 'run', 'lint:contracts-ready'],
  390. })
  391. })
  392. it('surfaces the configured worker bound on the shared package script', () => {
  393. const subject = withEnv('DSH_OXLINT_THREADS', '4', () =>
  394. withPnpmEntrypoint(() => gatesForMode('ci-lint-contracts-ready')[0]))
  395. expect(subject).toMatchObject({
  396. id: 'lint',
  397. displayCommand: 'DSH_OXLINT_THREADS=4 pnpm run lint:contracts-ready',
  398. command: process.execPath,
  399. args: ['/private/pnpm.cjs', 'run', 'lint:contracts-ready'],
  400. })
  401. })
  402. })
  403. describe('Typert contract preparation', () => {
  404. it('prepares primary source consumers once before they run', () => {
  405. const subject = withEnv('DSH_OXLINT_THREADS', undefined, () =>
  406. withPnpmEntrypoint(() => gatesForMode('ci-primary')))
  407. expect(subject.find(item => item.id === 'typert-contracts')).toMatchObject({
  408. displayCommand: 'pnpm run build:lib:host',
  409. args: ['/private/pnpm.cjs', 'run', 'build:lib:host'],
  410. })
  411. for (const [id, script] of [
  412. ['typecheck', 'typecheck:contracts-ready'],
  413. ['lint', 'lint:contracts-ready'],
  414. ['doc-typecheck', 'doc-typecheck:contracts-ready'],
  415. ] as const) {
  416. expect(subject.find(item => item.id === id)).toMatchObject({
  417. displayCommand: `pnpm run ${script}`,
  418. args: ['/private/pnpm.cjs', 'run', script],
  419. needs: ['typert-contracts'],
  420. })
  421. }
  422. expect(subject.find(item => item.id === 'build')?.needs).toEqual([
  423. 'typecheck',
  424. 'lint',
  425. 'doc-typecheck',
  426. ])
  427. })
  428. it('reuses contracts from the validated consumer build', () => {
  429. const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers'))
  430. expect(subject.find(item => item.id === 'lint-and-duplication')).toMatchObject({
  431. displayCommand: 'pnpm run check:ci:lint:contracts-ready',
  432. args: ['/private/pnpm.cjs', 'run', 'check:ci:lint:contracts-ready'],
  433. })
  434. expect(subject.find(item => item.id === 'doc-typecheck')).toMatchObject({
  435. displayCommand: 'pnpm run doc-typecheck:contracts-ready',
  436. args: ['/private/pnpm.cjs', 'run', 'doc-typecheck:contracts-ready'],
  437. })
  438. })
  439. it('keeps standalone doc sync responsible for preparation', () => {
  440. const docTypecheck = withPnpmEntrypoint(() =>
  441. gatesForMode('doc-sync').find(item => item.id === 'doc-typecheck'))
  442. expect(docTypecheck?.displayCommand).toBe('pnpm run doc-typecheck')
  443. })
  444. })
  445. describe('Node compatibility graph', () => {
  446. it('runs the jsdom environment smoke on every advertised Node line', () => {
  447. const subject = withPnpmEntrypoint(() => gatesForMode('node-compat'))
  448. expect(subject.find(item => item.id === 'vitest-jsdom-smoke')).toMatchObject({
  449. label: 'Vitest jsdom smoke',
  450. args: [
  451. '/private/pnpm.cjs',
  452. 'exec',
  453. 'vitest',
  454. 'run',
  455. 'scripts/vitest-environment.compat.spec.ts',
  456. ],
  457. })
  458. })
  459. })
  460. describe('Node 24 lane ownership', () => {
  461. it('keeps the static lane source-only', () => {
  462. const subject = withPnpmEntrypoint(() => gatesForMode('ci-static'))
  463. expect(subject.map(item => item.id)).not.toContain('build')
  464. expect(subject.map(item => item.id)).not.toContain('doc-typecheck')
  465. })
  466. it('owns the build and orders its artifact consumers', () => {
  467. const subject = withPnpmEntrypoint(() => gatesForMode('ci-consumers'))
  468. expect(defaultConcurrency('ci-consumers', subject.length, 4)).toEqual({
  469. workers: 11,
  470. source: 'ci-consumers gate count',
  471. })
  472. expect(subject.map(item => item.id)).toEqual([
  473. 'build',
  474. 'node-compat',
  475. 'publint',
  476. 'built-package-invariants',
  477. 'lint-and-duplication',
  478. 'snapshot',
  479. 'expected-output',
  480. 'web-snapshot',
  481. 'doc-typecheck',
  482. 'node-next-types',
  483. 'built-bin-smoke',
  484. ])
  485. expect(subject.find(item => item.id === 'publint')?.needs).toEqual(['build'])
  486. expect(subject.find(item => item.id === 'build')?.env).toEqual({
  487. DSH_BUILD_CLIENT_PROFILE: 'official',
  488. })
  489. expect(subject.find(item => item.id === 'node-compat')?.env).toEqual({
  490. DSH_BUILD_CLIENT_PROFILE: 'official',
  491. })
  492. expect(subject.find(item => item.id === 'built-package-invariants')?.needs).toEqual(['build'])
  493. expect(subject.find(item => item.id === 'lint-and-duplication')?.needs).toEqual(['built-package-invariants'])
  494. for (const id of [
  495. 'snapshot',
  496. 'expected-output',
  497. 'web-snapshot',
  498. 'doc-typecheck',
  499. 'node-next-types',
  500. 'built-bin-smoke',
  501. ]) {
  502. expect(subject.find(item => item.id === id)?.needs).toEqual(['built-package-invariants'])
  503. }
  504. expect(subject.find(item => item.id === 'snapshot')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' })
  505. expect(subject.find(item => item.id === 'expected-output')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' })
  506. expect(subject.find(item => item.id === 'doc-typecheck')?.env).toEqual({
  507. DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1',
  508. })
  509. expect(subject.find(item => item.id === 'built-bin-smoke')?.args).toEqual(
  510. expect.arrayContaining([
  511. 'packages/subprocess/subprocess-local/tests/spawn-runner-built.e2e.ts',
  512. 'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
  513. 'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
  514. 'packages/experimental/agent-team/tests/built-lib.e2e.ts',
  515. ]),
  516. )
  517. expect(subject.find(item => item.id === 'web-snapshot')).toMatchObject({
  518. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  519. env: { DSH_SNAPSHOT: 'replay' },
  520. after: [
  521. 'publint',
  522. 'lint-and-duplication',
  523. 'snapshot',
  524. 'expected-output',
  525. 'doc-typecheck',
  526. 'node-next-types',
  527. 'built-bin-smoke',
  528. ],
  529. })
  530. })
  531. })
  532. describe('Linux primary graph', () => {
  533. it('adds the same compare-only web gate after built client artifacts', () => {
  534. const subject = withPnpmEntrypoint(() => gatesForMode('ci-linux-primary'))
  535. const web = subject.find(item => item.id === 'web-snapshot')
  536. expect(web).toMatchObject({
  537. displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
  538. env: { DSH_SNAPSHOT: 'replay' },
  539. needs: ['built-package-invariants'],
  540. })
  541. })
  542. })
  543. describe('gate process outcomes', () => {
  544. it('streams selected gate output without retaining it', async () => {
  545. const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true)
  546. try {
  547. const result = await runGate(gate('streamed', {
  548. args: ['-e', "process.stdout.write('live output')"],
  549. streamOutput: true,
  550. }))
  551. expect(result.status).toBe('passed')
  552. expect(result.output).toEqual([])
  553. expect(write).toHaveBeenCalledWith('live output')
  554. } finally {
  555. write.mockRestore()
  556. }
  557. })
  558. it.skipIf(process.platform === 'win32')('reports signal termination independently from exit status', async () => {
  559. const result = await runGate(gate('terminated', {
  560. args: ['-e', "process.kill(process.pid, 'SIGTERM')"],
  561. }))
  562. expect(result.status).toBe('failed')
  563. expect(result.exitCode).toBeNull()
  564. expect(result.signalCode).toBe('SIGTERM')
  565. expect(formatGateResultReason(result)).toBe('signal SIGTERM')
  566. })
  567. })
  568. describe('fail-fast scheduling', () => {
  569. it('aborts the aggregate at the first blocking failure', async () => {
  570. const slow = gate('slow')
  571. const fast = gate('fast')
  572. const dependent = gate('dependent', { needs: ['slow'] })
  573. const execute = vi.fn(async (subject: Gate, signal?: AbortSignal) => {
  574. if (subject.id === 'fast') {
  575. return new Promise<GateResult>((resolve) => {
  576. signal?.addEventListener('abort', () => {
  577. // The real runGate marks a gate the abort terminated; the drain
  578. // must then record it skipped rather than keep the failure.
  579. resolve({ ...resultFor(subject, 'failed'), aborted: true })
  580. }, { once: true })
  581. })
  582. }
  583. return resultFor(subject, subject.id === 'slow' ? 'failed' : 'passed')
  584. })
  585. const results = await runGates([slow, fast, dependent], 2, execute, () => {}, { failFast: true })
  586. expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['slow', 'fast'])
  587. expect(results.map(result => result.status)).toEqual(['failed', 'skipped', 'skipped'])
  588. expect(results[1]).toMatchObject({
  589. status: 'skipped',
  590. error: 'aborted by fail-fast: slow failed',
  591. })
  592. expect(results[2]).toMatchObject({
  593. status: 'skipped',
  594. error: 'aborted by fail-fast: slow failed',
  595. })
  596. })
  597. it('does not abort on a non-blocking gate failure', async () => {
  598. const observational = gate('observational', { allowFailure: true })
  599. const root = gate('root')
  600. const execute = vi.fn(async (subject: Gate) => (
  601. resultFor(subject, subject.id === 'observational' ? 'failed' : 'passed')
  602. ))
  603. const results = await runGates([observational, root], 2, execute, () => {}, { failFast: true })
  604. expect(execute).toHaveBeenCalledTimes(2)
  605. expect(results.map(result => result.status)).toEqual(['failed', 'passed'])
  606. })
  607. it('runs independent gates to completion when fail-fast is disabled', async () => {
  608. const root = gate('root')
  609. const sibling = gate('sibling')
  610. const execute = vi.fn(async (subject: Gate) => (
  611. resultFor(subject, subject.id === 'root' ? 'failed' : 'passed')
  612. ))
  613. const results = await runGates([root, sibling], 2, execute, () => {}, { failFast: false })
  614. expect(execute).toHaveBeenCalledTimes(2)
  615. expect(results.map(result => result.status)).toEqual(['failed', 'passed'])
  616. })
  617. it('kills the child when the abort signal fires', async () => {
  618. const controller = new AbortController()
  619. const promise = runGate(gate('killable', { args: ['-e', 'setInterval(() => {}, 1000)'] }), controller.signal)
  620. controller.abort()
  621. const result = await promise
  622. expect(result.status).toBe('failed')
  623. expect(result.aborted).toBe(true)
  624. if (process.platform !== 'win32') expect(result.signalCode).toBe('SIGTERM')
  625. })
  626. it.skipIf(process.platform === 'win32')('marks a zero-exit child as aborted when the signal fired', async () => {
  627. const { writes, write } = captureStreamedOutput()
  628. try {
  629. const controller = new AbortController()
  630. const child = gate('traps-signal', {
  631. args: ['-e', "process.stdout.write('ready\\n'); process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000)"],
  632. streamOutput: true,
  633. })
  634. const promise = runGate(child, controller.signal)
  635. // Wait for the child to register its SIGTERM trap before aborting, so
  636. // the signal is caught and the child really exits zero.
  637. const deadline = Date.now() + 5000
  638. while (!writes.join('').includes('ready') && Date.now() < deadline) {
  639. await new Promise(resolve => setTimeout(resolve, 10))
  640. }
  641. controller.abort()
  642. const result = await promise
  643. // The child trapped the signal and exited zero; the drain must not
  644. // report this gate passed, so the raw outcome carries the abort mark.
  645. expect(result.status).toBe('passed')
  646. expect(result.aborted).toBe(true)
  647. } finally {
  648. write.mockRestore()
  649. }
  650. })
  651. it.skipIf(process.platform === 'win32')('kills the whole gate process tree when the abort signal fires', async () => {
  652. const { writes, write } = captureStreamedOutput()
  653. const controller = new AbortController()
  654. let promise: Promise<GateResult> | undefined
  655. try {
  656. const script = [
  657. "const { spawn } = require('node:child_process')",
  658. // Detached, so the grandchild leads its own process group: the gate
  659. // group signal cannot reach it, and only the descendant enumeration in
  660. // treeKill does — the shape of a nested run-gates' leaf gates.
  661. "const grandchild = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true })",
  662. "process.stdout.write('grandchild:' + grandchild.pid + '\\n')",
  663. 'setInterval(() => {}, 1000)',
  664. ].join(';')
  665. promise = runGate(gate('tree', { args: ['-e', script], streamOutput: true }), controller.signal)
  666. const deadline = Date.now() + 5000
  667. let pid: number | undefined
  668. while (pid === undefined && Date.now() < deadline) {
  669. const match = writes.join('').match(/grandchild:(\d+)/)
  670. if (match !== null) pid = Number(match[1])
  671. else await new Promise(resolve => setTimeout(resolve, 20))
  672. }
  673. expect(pid ?? 0).toBeGreaterThan(0)
  674. controller.abort()
  675. const result = await promise
  676. expect(result.status).toBe('failed')
  677. // The descendant enumeration signals the detached grandchild at the same
  678. // time as the group signal reaches the direct child; the direct child's
  679. // own death closes the gate pipes, so poll for the grandchild to stop
  680. // executing rather than asserting on a fixed instant.
  681. const stopDeadline = Date.now() + 5000
  682. while (!procStopped(pid!) && Date.now() < stopDeadline) {
  683. await new Promise(resolve => setTimeout(resolve, 20))
  684. }
  685. expect(procStopped(pid!)).toBe(true)
  686. } finally {
  687. // A failed wait or assertion must not leave the forever-looping detached
  688. // grandchild behind on the host: abort the gate and wait for the
  689. // process tree to settle before restoring the spy.
  690. controller.abort()
  691. await promise
  692. write.mockRestore()
  693. }
  694. })
  695. it('forwards host interruption signals to the abort path', async () => {
  696. const slow = gate('slow')
  697. const sibling = gate('sibling')
  698. const execute = vi.fn(async (subject: Gate, signal?: AbortSignal) => {
  699. if (subject.id === 'slow') {
  700. return new Promise<GateResult>((resolve) => {
  701. signal?.addEventListener('abort', () => {
  702. // A child can trap the signal and exit zero; the drain must still
  703. // record the gate skipped so the interrupted run fails.
  704. resolve({ ...resultFor(subject, 'passed'), aborted: true })
  705. }, { once: true })
  706. })
  707. }
  708. return resultFor(subject)
  709. })
  710. const promise = runGates([slow, sibling], 1, execute, () => {}, { failFast: true, forwardProcessSignals: true })
  711. // The first loop iteration starts `slow` synchronously, so its abort
  712. // listener is registered before the signal is emitted.
  713. process.emit('SIGTERM')
  714. const results = await promise
  715. expect(execute).toHaveBeenCalledOnce()
  716. expect(results.map(result => result.status)).toEqual(['skipped', 'skipped'])
  717. expect(results[0]).toMatchObject({
  718. status: 'skipped',
  719. error: 'aborted by fail-fast: host interruption',
  720. })
  721. })
  722. it('pairs host signal forwarding with fail-fast at the CLI entrypoint', () => {
  723. expect(cliGateOptions(true)).toEqual({ failFast: true, forwardProcessSignals: true })
  724. expect(cliGateOptions(false)).toEqual({ failFast: false, forwardProcessSignals: false })
  725. })
  726. it('rejects host signal forwarding without fail-fast', async () => {
  727. const execute = vi.fn(async (subject: Gate) => resultFor(subject))
  728. await expect(runGates([gate('subject')], 1, execute, () => {}, { forwardProcessSignals: true }))
  729. .rejects.toThrow('forwardProcessSignals requires failFast')
  730. expect(execute).not.toHaveBeenCalled()
  731. })
  732. it('leaves an un-aborted child running to completion', async () => {
  733. const result = await runGate(gate('settles', { args: ['-e', ''] }), new AbortController().signal)
  734. expect(result.status).toBe('passed')
  735. expect(result.aborted).toBe(false)
  736. })
  737. it.skipIf(process.platform === 'win32')('kills a detached descendant that outlived the child when the abort arrives later', async () => {
  738. const writes: string[] = []
  739. const write = vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
  740. writes.push(String(chunk))
  741. return true
  742. })
  743. const controller = new AbortController()
  744. let promise: Promise<GateResult> | undefined
  745. try {
  746. const script = [
  747. "const { spawn } = require('node:child_process')",
  748. // Detached with inherited stdio: the grandchild leads its own process
  749. // group (the gate group signal misses it) and holds the gate's
  750. // stdout write end (so `close` stays pending past the child exit).
  751. "const grandchild = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true, stdio: 'inherit' })",
  752. "process.stdout.write('grandchild:' + grandchild.pid + '\\n')",
  753. // Outlive the first descendant-sampler tick with margin so the cache
  754. // holds the grandchild even on a loaded runner, then exit normally
  755. // before the abort arrives.
  756. "setTimeout(() => { process.stdout.write('child-exit\\n'); process.exit(0) }, 8000)",
  757. ].join(';')
  758. promise = runGate(gate('late-abort', { args: ['-e', script], streamOutput: true }), controller.signal)
  759. const pid = await waitForGrandchildPid(writes, 'child-exit', Date.now() + 10000)
  760. // terminate must not re-enumerate over the sampler cache now that the
  761. // child is gone; the detached grandchild is killed from the cached list.
  762. await abortAndExpectTreeStopped(promise, controller, pid)
  763. } finally {
  764. // A failed wait or assertion must not leave the forever-looping detached
  765. // grandchild behind on the host: abort the gate and wait for the
  766. // process tree to settle before restoring the spy.
  767. controller.abort()
  768. await promise
  769. write.mockRestore()
  770. }
  771. }, 20000)
  772. it.skipIf(process.platform === 'win32')('keeps a reparented detached descendant tracked across a sampler tick', async () => {
  773. const { writes, write } = captureStreamedOutput()
  774. const controller = new AbortController()
  775. let promise: Promise<GateResult> | undefined
  776. try {
  777. const script = [
  778. "const { spawn } = require('node:child_process')",
  779. // Wrapper spawns a detached grandchild with inherited stdio (its own
  780. // process group, holding the gate's stdout write end), prints the pid,
  781. // then exits after 7 seconds — after the first sampler tick, before
  782. // the second. From then on the grandchild is reparented and
  783. // unreachable by parent id.
  784. "const wrapper = spawn(process.execPath, ['-e', \"const { spawn } = require('node:child_process'); const grandchild = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true, stdio: 'inherit' }); process.stdout.write('grandchild:' + grandchild.pid + '\\\\n'); setTimeout(() => process.exit(0), 7000)\"], { stdio: 'inherit' })",
  785. "wrapper.on('exit', () => process.stdout.write('wrapper-exited\\n'))",
  786. // Keep the root child alive past the abort with a heartbeat so the
  787. // test can abort while it is still running.
  788. "setInterval(() => process.stdout.write('hb\\n'), 1000)",
  789. ].join(';')
  790. promise = runGate(gate('sampler-merge', { args: ['-e', script], streamOutput: true }), controller.signal)
  791. const pid = await waitForGrandchildPid(writes, 'wrapper-exited', Date.now() + 15000)
  792. // Wait past the second sampler tick (t=10) with margin: a replacing tick
  793. // would drop the reparented grandchild from the cache, after which the
  794. // abort cannot reach it. The root child keeps running throughout.
  795. const tickDeadline = Date.now() + 10000
  796. const wrapperExitedAt = Date.now()
  797. while (Date.now() - wrapperExitedAt < 5000 && Date.now() < tickDeadline) {
  798. await new Promise(resolve => setTimeout(resolve, 50))
  799. }
  800. expect(Date.now() - wrapperExitedAt).toBeGreaterThanOrEqual(5000)
  801. await abortAndExpectTreeStopped(promise, controller, pid)
  802. } finally {
  803. // A failed wait or assertion must not leave the forever-looping detached
  804. // grandchild behind on the host: abort the gate and wait for the
  805. // process tree to settle before restoring the spy.
  806. controller.abort()
  807. await promise
  808. write.mockRestore()
  809. }
  810. }, 30000)
  811. })
  812. describe('process-table parsing', () => {
  813. it('excludes the root when a parent link returns to it', () => {
  814. expect(collectDescendants(100, [[200, 100], [100, 200], [300, 200]]))
  815. .toEqual([200, 300])
  816. })
  817. it('visits duplicate and cyclic descendant links only once', () => {
  818. expect(collectDescendants(100, [
  819. [200, 100], [200, 100], [300, 100], [200, 200], [400, 200], [200, 400], [500, 300], [900, 800],
  820. ])).toEqual([200, 300, 400, 500])
  821. })
  822. it('returns no descendants for an isolated or self-parented root', () => {
  823. expect(collectDescendants(100, [])).toEqual([])
  824. expect(collectDescendants(100, [[100, 100]])).toEqual([])
  825. })
  826. it('walks a wide child set without spreading it into call arguments', () => {
  827. const children = Array.from({ length: 150_000 }, (_, i): [number, number] => [i + 3, 2])
  828. const descendants = collectDescendants(1, [[2, 1], ...children])
  829. expect(descendants).toHaveLength(children.length + 1)
  830. expect(descendants[0]).toBe(2)
  831. expect(descendants.at(-1)).toBe(150_002)
  832. })
  833. it('parses `pid ppid` rows from a POSIX ps dump', () => {
  834. expect(parsePidPpidLines(' 123 1\n456 123\n 789 456\n')).toEqual([[123, 1], [456, 123], [789, 456]])
  835. })
  836. it('parses Windows PowerShell Get-CimInstance output of the same shape', () => {
  837. expect(parsePidPpidLines(' 123 1\r\n456 123\r\n')).toEqual([[123, 1], [456, 123]])
  838. })
  839. it('drops blank and malformed lines', () => {
  840. expect(parsePidPpidLines(' 123 1\n\ncommand not found\n999 abc\n')).toEqual([[123, 1]])
  841. })
  842. })
  843. describe('Windows tree termination', () => {
  844. it('targets the root first and each captured descendant after it', () => {
  845. expect(taskkillArgs(100, [201, 302, 403])).toEqual([
  846. ['/PID', '100', '/T', '/F'],
  847. ['/PID', '201', '/T', '/F'],
  848. ['/PID', '302', '/T', '/F'],
  849. ['/PID', '403', '/T', '/F'],
  850. ])
  851. })
  852. it('terminates the root alone when no descendant was captured', () => {
  853. expect(taskkillArgs(100, [])).toEqual([['/PID', '100', '/T', '/F']])
  854. })
  855. })