run-gates.spec.ts 38 KB

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