python-runtime-selfhosted.spec.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import { spawnSync } from 'node:child_process'
  2. import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
  3. import { tmpdir } from 'node:os'
  4. import { resolve } from 'node:path'
  5. import { runInNewContext } from 'node:vm'
  6. import * as yaml from 'js-yaml'
  7. import { describe, expect, it } from 'vitest'
  8. const root = resolve(import.meta.dirname, '..')
  9. const workflow = yaml.load(readFileSync(resolve(root, '.github/workflows/build-exe-for-python-sdk.yml'), 'utf8')) as {
  10. jobs: Record<string, { 'runs-on': string; steps: Array<{ name?: string; id?: string; uses?: string; if?: string; shell?: string; run?: string; with?: Record<string, unknown> }> }>
  11. }
  12. const build = workflow.jobs.build!
  13. const selector = build['runs-on'].slice(3, -2).trim()
  14. const windows = ['self-hosted', 'dsh-win-ci', 'windows', 'x64']
  15. function context() {
  16. return {
  17. inputs: { ci: true, release: false },
  18. github: {
  19. repository: 'deepseek-harness/deepseek-harness',
  20. event_name: 'pull_request',
  21. ref: 'refs/pull/42/merge',
  22. event: { pull_request: {
  23. head: { repo: { full_name: 'deepseek-harness/deepseek-harness', fork: false } },
  24. user: { login: 'contributor' },
  25. } },
  26. },
  27. matrix: { target: 'node24-win-x64', runner: 'windows-2025' },
  28. vars: { DSH_CI_FAILOVER_WINDOWS: 'selfhosted' },
  29. fromJSON: JSON.parse,
  30. }
  31. }
  32. function route(value: ReturnType<typeof context>, expression = selector): unknown {
  33. // These canonical-case fixtures share JS/Actions comparison results; Actions also ignores string case.
  34. // This evaluates the selected syntax, not GitHub's complete expression language.
  35. return runInNewContext(expression, value, { timeout: 1000 })
  36. }
  37. describe('Python runtime self-hosted routing', () => {
  38. it('routes same-repository member PRs to native x64 Windows', () => {
  39. expect(route(context())).toEqual(windows)
  40. })
  41. it.each([
  42. ['release caller', (value: ReturnType<typeof context>) => { value.inputs.release = true }],
  43. ['non-CI caller', (value: ReturnType<typeof context>) => { value.inputs.ci = false }],
  44. ['manual dispatch', (value: ReturnType<typeof context>) => { value.github.event_name = 'workflow_dispatch' }],
  45. ['pull_request_target', (value: ReturnType<typeof context>) => { value.github.event_name = 'pull_request_target' }],
  46. ['unknown event', (value: ReturnType<typeof context>) => { value.github.event_name = '' }],
  47. ['fork', (value: ReturnType<typeof context>) => { value.github.event.pull_request.head.repo.fork = true }],
  48. ['different repository head', (value: ReturnType<typeof context>) => { value.github.event.pull_request.head.repo.full_name = 'someone/fork' }],
  49. ['different caller repository', (value: ReturnType<typeof context>) => { value.github.repository = 'someone/fork' }],
  50. ['Dependabot author', (value: ReturnType<typeof context>) => { value.github.event.pull_request.user.login = 'dependabot[bot]' }],
  51. ['disabled failover', (value: ReturnType<typeof context>) => { value.vars.DSH_CI_FAILOVER_WINDOWS = '' }],
  52. ['unknown failover value', (value: ReturnType<typeof context>) => { value.vars.DSH_CI_FAILOVER_WINDOWS = 'hosted' }],
  53. ['master push', (value: ReturnType<typeof context>) => { value.github.event_name = 'push'; value.github.ref = 'refs/heads/master' }],
  54. ['branch push', (value: ReturnType<typeof context>) => { value.github.event_name = 'push'; value.github.ref = 'refs/heads/topic' }],
  55. ['tag push', (value: ReturnType<typeof context>) => { value.github.event_name = 'push'; value.github.ref = 'refs/tags/python-v1' }],
  56. ] as const)('keeps %s on the hosted fallback', (_name, change) => {
  57. const value = context()
  58. change(value)
  59. expect(route(value)).toBe('windows-2025')
  60. })
  61. it.each([
  62. ['node24-linux-x64', 'ubuntu-latest'],
  63. ['node24-linux-arm64', 'ubuntu-24.04-arm'],
  64. ['node24-macos-arm64', 'macos-latest'],
  65. ['node24-macos-x64', 'macos-15-intel'],
  66. ])('keeps %s hosted even with failover enabled', (target, runner) => {
  67. const value = context()
  68. value.matrix = { target, runner }
  69. expect(route(value)).toBe(runner)
  70. })
  71. it('keeps setup helper jobs on hosted images', () => {
  72. expect(workflow.jobs.plan!['runs-on']).toBe('ubuntu-latest')
  73. expect(workflow.jobs['sdk-wheel']!['runs-on']).toBe('ubuntu-latest')
  74. })
  75. it('isolates setup before pnpm and excludes shared installers and cache archives', () => {
  76. const privateSetup = build.steps.findIndex(step => step.id === 'private-windows')
  77. expect(privateSetup).toBeGreaterThan(0)
  78. expect(privateSetup).toBeLessThan(build.steps.findIndex(step => step.uses?.startsWith('pnpm/action-setup@')))
  79. for (const step of build.steps.filter(step => step.uses?.startsWith('actions/setup-python@') || step.uses?.startsWith('actions/cache@') || step.name === 'Install Python build tooling')) {
  80. expect(step.if).toBe("runner.environment != 'self-hosted'")
  81. }
  82. expect(build.steps.find(step => step.name?.startsWith('Enable Windows'))?.if).toBe("runner.os == 'Windows' && runner.environment != 'self-hosted'")
  83. expect(build.steps.find(step => step.uses?.startsWith('actions/setup-node@'))?.with?.cache).toContain("runner.environment != 'self-hosted'")
  84. expect(build.steps.at(-1)).toMatchObject({ if: "always() && steps.private-windows.outputs.root != ''", shell: 'pwsh' })
  85. expect(build.steps.find(step => step.uses?.startsWith('actions/setup-node@'))?.with?.['package-manager-cache']).toBe(false)
  86. expect(build.steps.find(step => step.name === 'Install (immutable)')?.if).toBe("runner.environment != 'self-hosted'")
  87. expect(build.steps.find(step => step.name === 'Install private Windows dependencies (immutable)')).toMatchObject({
  88. if: "runner.os == 'Windows' && runner.environment == 'self-hosted'",
  89. shell: 'pwsh',
  90. })
  91. expect(build.steps.find(step => step.name === 'Install private Windows dependencies (immutable)')?.run).toContain('pnpm install --frozen-lockfile --package-import-method=copy')
  92. const cleanup = build.steps.at(-1)!.run!
  93. expect(cleanup).toContain('"NODE_COMPILE_CACHE=" >> $env:GITHUB_ENV')
  94. expect(cleanup).toContain('"TMP=$env:RUNNER_TEMP" >> $env:GITHUB_ENV')
  95. expect(cleanup).toContain('"TEMP=$env:RUNNER_TEMP" >> $env:GITHUB_ENV')
  96. expect(cleanup).toContain('maxRetries: 10, retryDelay: 100')
  97. })
  98. it.each(['root', 'nested', 'absent'] as const)('cleans a %s job directory without deleting another target', (location) => {
  99. const temp = mkdtempSync(resolve(tmpdir(), 'python-runtime-cleanup-'))
  100. try {
  101. const target = resolve(temp, 'other-job')
  102. const owned = resolve(temp, 'owned')
  103. mkdirSync(target)
  104. writeFileSync(resolve(target, 'sentinel'), 'preserve')
  105. if (location === 'nested') mkdirSync(owned)
  106. if (location !== 'absent') symlinkSync(target, location === 'root' ? owned : resolve(owned, 'link'), 'junction')
  107. const command = /node -e "([^"\n]+)"/.exec(build.steps.at(-1)!.run!)?.[1]
  108. expect(command).toBeDefined()
  109. const result = spawnSync(process.execPath, ['-e', command!], {
  110. env: { ...process.env, PRIVATE_ROOT: owned, NODE_COMPILE_CACHE: '' },
  111. encoding: 'utf8',
  112. timeout: 10000,
  113. })
  114. expect(result.error).toBeUndefined()
  115. expect(result.signal).toBeNull()
  116. expect(result.status, result.stderr).toBe(0)
  117. expect(existsSync(owned)).toBe(false)
  118. expect(readFileSync(resolve(target, 'sentinel'), 'utf8')).toBe('preserve')
  119. } finally {
  120. rmSync(temp, { recursive: true, force: true })
  121. }
  122. })
  123. it('reads UTF-8 Session JSONL independently of the host locale', () => {
  124. const setup = readFileSync(resolve(root, 'scripts/setup-python-runtime-windows.ps1'), 'utf8')
  125. const utf8 = /PYTHONUTF8 = '([^']+)'/.exec(setup)?.[1]
  126. expect(utf8).toBe('1')
  127. const result = spawnSync(process.platform === 'win32' ? 'python' : 'python3', ['-c', [
  128. 'import pathlib, tempfile, sys',
  129. 'assert sys.flags.utf8_mode == 1',
  130. 'with tempfile.TemporaryDirectory(prefix="python-runtime-encoding-") as root:',
  131. ' log = pathlib.Path(root) / "session.jsonl"',
  132. ' text = chr(0x2014) + chr(0x4e2d)',
  133. ' log.write_bytes(text.encode("utf-8"))',
  134. ' assert log.read_text() == text',
  135. ].join('\n')], {
  136. env: { ...process.env, LC_ALL: 'C', LANG: 'C', PYTHONCOERCECLOCALE: '0', PYTHONUTF8: utf8 },
  137. encoding: 'utf8',
  138. timeout: 10000,
  139. })
  140. expect(result.error).toBeUndefined()
  141. expect(result.signal).toBeNull()
  142. expect(result.status, result.stderr).toBe(0)
  143. })
  144. it('pins portable Python without registry or shared cache writes', () => {
  145. const setup = readFileSync(resolve(root, 'scripts/setup-python-runtime-windows.ps1'), 'utf8')
  146. expect(setup).toContain('--no-bin --no-registry 3.10')
  147. expect(setup).toContain('--managed-python --no-python-downloads --seed')
  148. expect(setup).toContain('UV_PYTHON_INSTALL_REGISTRY')
  149. expect(setup).toContain('PNPM_CONFIG_STORE_DIR')
  150. expect(setup).toContain('PKG_CACHE_PATH')
  151. expect(setup.indexOf('$bootstrapScripts >> $env:GITHUB_PATH')).toBeLessThan(setup.indexOf('$toolingScripts >> $env:GITHUB_PATH'))
  152. expect(setup).toContain('AllowDevelopmentWithoutDevLicense -ErrorAction SilentlyContinue')
  153. expect(setup).toContain('$null -eq $devMode -or')
  154. expect(setup).not.toMatch(/reg add|Set-ItemProperty|InstallAllUsers/)
  155. })
  156. })