coverage-partitions.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /** Coordinate single-worker Vitest coverage partitions and one merged report. */
  2. import { spawn } from 'node:child_process'
  3. import { lstat, mkdir, readdir, rm, unlink } from 'node:fs/promises'
  4. import { join, relative, sep } from 'node:path'
  5. import { pnpmInvocation } from './pnpm-invocation.ts'
  6. /** Environment variable selecting the number of instrumented coverage processes. */
  7. export const COVERAGE_PARTITIONS_ENV = 'DSH_COVERAGE_PARTITIONS'
  8. /** Internal marker that suppresses reports and thresholds inside a partition process. */
  9. export const COVERAGE_PARTITION_MODE_ENV = 'DSH_COVERAGE_PARTITION_MODE'
  10. /** Environment variable overriding instrumented test and polling timeouts. */
  11. export const COVERAGE_TEST_TIMEOUT_ENV = 'DSH_COVERAGE_TEST_TIMEOUT_MS'
  12. /** One child command owned by the coverage coordinator. */
  13. export interface CoverageCommand {
  14. /** Diagnostic identity. */
  15. label: string
  16. /** Executable launched without a platform shell. */
  17. command: string
  18. /** Arguments passed to the executable. */
  19. args: string[]
  20. /** Environment additions for the child. */
  21. env: Record<string, string | undefined>
  22. /** Working directory for the child. */
  23. cwd: string
  24. /** Blob the partition must produce; absent for the merge command. */
  25. blobPath?: string
  26. }
  27. /** Observable child-process completion. */
  28. export interface CoverageCommandResult {
  29. /** Numeric process status, or `null` when a signal ended the child. */
  30. exitCode: number | null
  31. /** Terminating signal, or `null` after an ordinary exit. */
  32. signalCode: NodeJS.Signals | null
  33. /** Spawn failure recorded independently from process completion. */
  34. error?: string
  35. /** Bounded combined stdout/stderr tail repeated when the command fails. */
  36. outputTail?: string
  37. }
  38. /** Execute one coordinator command with inherited output. */
  39. export type CoverageCommandRunner = (command: CoverageCommand) => Promise<CoverageCommandResult>
  40. /** Construction inputs for {@link CoveragePartitionCoordinator}. */
  41. export interface CoveragePartitionCoordinatorOptions {
  42. /** Repository root that owns coverage output. */
  43. root: string
  44. /** Number of concurrent single-worker Vitest processes. */
  45. partitions: number
  46. /** pnpm JavaScript or executable entrypoint from `npm_execpath`. */
  47. pnpmEntrypoint: string
  48. /** Additional arguments shared by every partition. */
  49. vitestArgs?: string[]
  50. /** Child executor, injectable for scheduler tests. */
  51. runCommand?: CoverageCommandRunner
  52. }
  53. /** Parse an optional coverage partition count. */
  54. export function parseCoveragePartitionCount(raw: string | undefined): number | undefined {
  55. if (raw === undefined || raw === '') return undefined
  56. const parsed = Number.parseInt(raw, 10)
  57. if (!Number.isSafeInteger(parsed) || parsed < 2 || String(parsed) !== raw) {
  58. throw new Error(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1, got ${JSON.stringify(raw)}.`)
  59. }
  60. return parsed
  61. }
  62. /** Resolve the paired Vitest timeout arguments used by coverage partitions. */
  63. export function coverageTestTimeoutArgs(raw: string | undefined): string[] {
  64. if (raw === undefined || raw === '') return []
  65. const parsed = Number.parseInt(raw, 10)
  66. if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
  67. throw new Error(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer, got ${JSON.stringify(raw)}.`)
  68. }
  69. return [`--testTimeout=${raw}`, `--expect.poll.timeout=${raw}`]
  70. }
  71. /** Remove pnpm's package-script separator before forwarding Vitest arguments. */
  72. export function forwardedCoverageArgs(args: readonly string[]): string[] {
  73. return [...args.slice(args[0] === '--' ? 1 : 0)]
  74. }
  75. /** Run instrumented partitions, validate their blobs, and merge once. */
  76. export class CoveragePartitionCoordinator {
  77. private readonly root: string
  78. private readonly partitions: number
  79. private readonly pnpmEntrypoint: string
  80. private readonly vitestArgs: string[]
  81. private readonly runCommand: CoverageCommandRunner
  82. private readonly temporaryRoot: string
  83. private readonly blobsRoot: string
  84. /** Create a coordinator from validated process-independent inputs. */
  85. public constructor(options: CoveragePartitionCoordinatorOptions) {
  86. if (!Number.isSafeInteger(options.partitions) || options.partitions < 2) {
  87. throw new Error(`coverage partitions must be an integer greater than 1, got ${String(options.partitions)}.`)
  88. }
  89. this.root = options.root
  90. this.partitions = options.partitions
  91. this.pnpmEntrypoint = options.pnpmEntrypoint
  92. this.vitestArgs = options.vitestArgs ?? []
  93. this.runCommand = options.runCommand ?? runCoverageCommand
  94. this.temporaryRoot = join(this.root, 'coverage', '.partitioned')
  95. this.blobsRoot = join(this.temporaryRoot, 'blobs')
  96. }
  97. /**
  98. * Run every partition before one merged threshold check.
  99. * @returns zero only when every partition and the merge command succeed.
  100. */
  101. public async run(): Promise<number> {
  102. await removeOwnedTree(join(this.root, 'coverage'))
  103. await mkdir(this.blobsRoot, { recursive: true })
  104. try {
  105. const commands = Array.from(
  106. { length: this.partitions },
  107. (_, index) => this.partitionCommand(index + 1),
  108. )
  109. const results = await Promise.all(commands.map(async (command) => {
  110. console.log(`coverage-partitions: start ${command.label}`)
  111. const result = await this.runCommand(command)
  112. if (commandFailed(result)) {
  113. console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`)
  114. if (result.outputTail !== undefined && result.outputTail !== '') {
  115. console.error(`coverage-partitions: output tail for ${command.label}:\n${result.outputTail}`)
  116. }
  117. }
  118. return result
  119. }))
  120. await this.assertCompleteBlobSet(commands)
  121. const mergeCommand = this.mergeCommand()
  122. console.log(`coverage-partitions: start ${mergeCommand.label}`)
  123. const mergeResult = await this.runCommand(mergeCommand)
  124. return results.some(commandFailed) || commandFailed(mergeResult) ? 1 : 0
  125. } finally {
  126. await removeOwnedTree(this.temporaryRoot)
  127. }
  128. }
  129. private partitionCommand(index: number): CoverageCommand {
  130. const blobPath = join(this.blobsRoot, `partition-${index}.json`)
  131. const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`)
  132. const invocation = pnpmInvocation([
  133. 'exec',
  134. 'vitest',
  135. 'run',
  136. '--coverage',
  137. '--coverage.reportOnFailure',
  138. '--maxWorkers=1',
  139. `--shard=${index}/${this.partitions}`,
  140. '--reporter=default',
  141. '--reporter=blob',
  142. `--outputFile.blob=${this.relativePath(blobPath)}`,
  143. `--coverage.reportsDirectory=${this.relativePath(reportsDirectory)}`,
  144. ...this.vitestArgs,
  145. ], { npm_execpath: this.pnpmEntrypoint })
  146. return {
  147. label: `partition ${index}/${this.partitions}`,
  148. ...invocation,
  149. env: {
  150. [COVERAGE_PARTITIONS_ENV]: undefined,
  151. [COVERAGE_PARTITION_MODE_ENV]: '1',
  152. },
  153. cwd: this.root,
  154. blobPath,
  155. }
  156. }
  157. private mergeCommand(): CoverageCommand {
  158. const invocation = pnpmInvocation([
  159. 'exec',
  160. 'vitest',
  161. `--merge-reports=${this.relativePath(this.blobsRoot)}`,
  162. '--coverage',
  163. ], { npm_execpath: this.pnpmEntrypoint })
  164. return {
  165. label: 'merged coverage report',
  166. ...invocation,
  167. env: {
  168. [COVERAGE_PARTITIONS_ENV]: undefined,
  169. [COVERAGE_PARTITION_MODE_ENV]: undefined,
  170. },
  171. cwd: this.root,
  172. }
  173. }
  174. private relativePath(path: string): string {
  175. return relative(this.root, path).split(sep).join('/')
  176. }
  177. private async assertCompleteBlobSet(commands: CoverageCommand[]): Promise<void> {
  178. const expected = commands.map((command) => {
  179. if (command.blobPath === undefined) throw new Error(`${command.label} has no blob path.`)
  180. return this.relativePath(command.blobPath)
  181. }).sort()
  182. const actual = (await readdir(this.blobsRoot))
  183. .map(name => this.relativePath(join(this.blobsRoot, name)))
  184. .sort()
  185. if (actual.length !== expected.length || actual.some((name, index) => name !== expected[index])) {
  186. throw new Error(`coverage partitions produced ${JSON.stringify(actual)}; expected ${JSON.stringify(expected)}.`)
  187. }
  188. }
  189. }
  190. /** Spawn one pnpm-backed command without a platform shell. */
  191. function runCoverageCommand(command: CoverageCommand): Promise<CoverageCommandResult> {
  192. return new Promise((resolveCommand) => {
  193. let outputTail = ''
  194. const env = { ...process.env }
  195. for (const [name, value] of Object.entries(command.env)) {
  196. if (value === undefined) Reflect.deleteProperty(env, name)
  197. else env[name] = value
  198. }
  199. const child = spawn(command.command, command.args, {
  200. cwd: command.cwd,
  201. env,
  202. stdio: ['ignore', 'pipe', 'pipe'],
  203. })
  204. child.stdout.setEncoding('utf8')
  205. child.stderr.setEncoding('utf8')
  206. child.stdout.on('data', (chunk: string) => {
  207. process.stdout.write(chunk)
  208. outputTail = appendOutputTail(outputTail, chunk)
  209. })
  210. child.stderr.on('data', (chunk: string) => {
  211. process.stderr.write(chunk)
  212. outputTail = appendOutputTail(outputTail, chunk)
  213. })
  214. child.once('error', (error: Error) => {
  215. resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail })
  216. })
  217. child.once('close', (exitCode, signalCode) => {
  218. resolveCommand({ exitCode, signalCode, outputTail })
  219. })
  220. })
  221. }
  222. function appendOutputTail(previous: string, chunk: string): string {
  223. const combined = previous + chunk
  224. return combined.length <= 65_536 ? combined : combined.slice(-65_536)
  225. }
  226. function commandFailed(result: CoverageCommandResult): boolean {
  227. return result.exitCode !== 0 || result.signalCode !== null || result.error !== undefined
  228. }
  229. function commandFailureReason(result: CoverageCommandResult): string {
  230. const facts = [
  231. result.error,
  232. result.exitCode === null ? undefined : `exit ${result.exitCode}`,
  233. result.signalCode === null ? undefined : `signal ${result.signalCode}`,
  234. ].filter((fact): fact is string => fact !== undefined)
  235. return facts.join(', ') || 'no exit code or signal'
  236. }
  237. async function removeOwnedTree(path: string): Promise<void> {
  238. const metadata = await lstat(path).catch((error: unknown) => {
  239. if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
  240. throw error
  241. })
  242. if (metadata === undefined) return
  243. if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
  244. await unlink(path)
  245. return
  246. }
  247. await rm(path, { recursive: true, force: true })
  248. }