run-gates.spec.ts 36 KB

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