linux-scope.spec.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. import { EventEmitter } from 'node:events'
  2. import { existsSync, rmSync, unlinkSync, writeFileSync } from 'node:fs'
  3. import { PassThrough } from 'node:stream'
  4. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  5. import type { SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess'
  6. import {
  7. launchLinuxScope,
  8. prepareLinuxTerminalScope,
  9. probeLinuxBootstrap,
  10. probeLinuxManager,
  11. probeLinuxNative,
  12. probeLinuxScope,
  13. signalLinuxDirectProcess,
  14. } from '../src/linux-scope.ts'
  15. import type { LinuxScopeInternals } from '../src/linux-scope.ts'
  16. import {
  17. consumeLinuxLaunchRequest,
  18. linuxLaunchFilesFromLocator,
  19. writeLinuxStartupError,
  20. } from '../src/runner-protocol.ts'
  21. import { SUBPROCESS_RUNNER_ENV } from '../src/runner-launch.ts'
  22. import { bindManagedProcess } from '../src/spawn.ts'
  23. const childProcessMocks = vi.hoisted(() => ({
  24. execFile: vi.fn(),
  25. spawn: vi.fn(),
  26. spawnSync: vi.fn(),
  27. }))
  28. vi.mock('node:child_process', async (importOriginal) => {
  29. const actual = await importOriginal<typeof import('node:child_process')>()
  30. return {
  31. ...actual,
  32. execFile: childProcessMocks.execFile as unknown as typeof actual.execFile,
  33. spawn: childProcessMocks.spawn as typeof actual.spawn,
  34. spawnSync: childProcessMocks.spawnSync as typeof actual.spawnSync,
  35. }
  36. })
  37. class FakeChild extends EventEmitter {
  38. pid: number | undefined = 321
  39. exitCode: number | null = null
  40. signalCode: NodeJS.Signals | null = null
  41. stdin = new PassThrough()
  42. stdout = new PassThrough()
  43. stderr = new PassThrough()
  44. control = new PassThrough()
  45. stdio = [this.stdin, this.stdout, this.stderr, null, null, null, null, this.control]
  46. kills: NodeJS.Signals[] = []
  47. kill(signal: NodeJS.Signals): boolean {
  48. this.kills.push(signal)
  49. return true
  50. }
  51. exit(exitCode: number | null, signal: NodeJS.Signals | null): void {
  52. this.exitCode = exitCode
  53. this.signalCode = signal
  54. this.emit('exit', exitCode, signal)
  55. }
  56. }
  57. const directories: string[] = []
  58. // Every test must isolate fake PIDs from host signals, including cases without custom mocks.
  59. beforeEach(() => { denyProcessGroups() })
  60. afterEach(() => {
  61. for (const directory of directories.splice(0)) {
  62. rmSync(directory, { recursive: true, force: true })
  63. }
  64. vi.restoreAllMocks()
  65. childProcessMocks.execFile.mockReset()
  66. childProcessMocks.spawn.mockReset()
  67. childProcessMocks.spawnSync.mockReset()
  68. })
  69. function missingUnit() {
  70. return { status: 1, stdout: '', stderr: 'Unit dsh.scope could not be found.' }
  71. }
  72. function activeUnit(state = 'active') {
  73. return { status: 0, stdout: `LoadState=loaded\nActiveState=${state}\n`, stderr: '' }
  74. }
  75. function unloadedUnit() {
  76. return { status: 0, stdout: 'LoadState=not-found\nActiveState=inactive\n', stderr: '' }
  77. }
  78. function unitState(loadState: string, activeState: string) {
  79. return { status: 0, stdout: `LoadState=${loadState}\nActiveState=${activeState}\n`, stderr: '' }
  80. }
  81. function activeUnitWithTasks(tasks: string) {
  82. return { status: 0, stdout: `LoadState=loaded\nActiveState=active\nTasksCurrent=${tasks}\n`, stderr: '' }
  83. }
  84. /** Reject group delivery and accept direct-PID signals without reaching the host. */
  85. function denyProcessGroups(): void {
  86. vi.spyOn(process, 'kill').mockImplementation((pid) => {
  87. if (pid < 0) throw new Error('missing process group')
  88. return true
  89. })
  90. }
  91. /** Record the systemctl invocations a scope owner makes, succeeding unless a case overrides it. */
  92. function recordingSystemctl() {
  93. return vi.fn((_command: string, _args: readonly string[]) => ({ status: 0, stdout: '', stderr: '' }))
  94. }
  95. function spec() {
  96. return {
  97. argv: ['tool', 'literal arg'],
  98. cwd: '/target',
  99. stdio: { stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' },
  100. graceMs: 100,
  101. env: { TARGET: 'yes' },
  102. } as const
  103. }
  104. function launch(
  105. query: LinuxScopeInternals['systemctlQuery'],
  106. overrides: LinuxScopeInternals = {},
  107. request: SubprocessSpawnSpec = spec(),
  108. ) {
  109. const child = new FakeChild()
  110. let options: { env?: NodeJS.ProcessEnv; cwd?: string; detached?: boolean } | undefined
  111. const spawn = vi.fn((_command: string, _args: readonly string[], received: typeof options) => {
  112. options = received
  113. return child
  114. })
  115. const spawnSync = vi.fn(() => ({ status: 0, stdout: '', stderr: '' }))
  116. const systemctlQuery = overrides.systemctlQuery ?? query
  117. const result = launchLinuxScope(request, { TARGET: 'yes' }, {
  118. spawn: overrides.spawn ?? spawn as never,
  119. spawnSync: overrides.spawnSync ?? spawnSync as never,
  120. ...systemctlQuery === undefined ? {} : { systemctlQuery },
  121. systemdRun: overrides.systemdRun ?? '/bin/systemd-run',
  122. systemctl: overrides.systemctl ?? '/bin/systemctl',
  123. runnerInvocation: overrides.runnerInvocation ?? ['/usr/bin/node', '/runner.js'],
  124. ...overrides.runnerAvailable === undefined ? {} : { runnerAvailable: overrides.runnerAvailable },
  125. ...overrides.loadLinuxExecve === undefined ? {} : { loadLinuxExecve: overrides.loadLinuxExecve },
  126. ...overrides.sleep === undefined ? {} : { sleep: overrides.sleep },
  127. })
  128. const requestPath = options?.env?.[SUBPROCESS_RUNNER_ENV]
  129. if (requestPath === undefined) throw new Error('launch did not publish a request locator')
  130. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  131. return { child, result, requestPath, spawn, spawnSync, options }
  132. }
  133. describe('Linux native capability selection', () => {
  134. it.each([
  135. { delivered: true, error: undefined, accepted: true },
  136. { delivered: false, error: undefined, accepted: false },
  137. { delivered: false, error: 'ESRCH', accepted: true },
  138. { delivered: false, error: 'EPERM', accepted: false },
  139. ])('distinguishes direct signal delivery=$delivered and absence=$error', ({ delivered, error, accepted }) => {
  140. const probe = vi.spyOn(process, 'kill').mockImplementation(() => {
  141. if (error !== undefined) throw Object.assign(new Error(error), { code: error })
  142. return true
  143. })
  144. expect(signalLinuxDirectProcess(123, () => delivered)).toBe(accepted)
  145. if (delivered) expect(probe).not.toHaveBeenCalled()
  146. else expect(probe).toHaveBeenCalledExactlyOnceWith(123, 0)
  147. })
  148. it('checks direct absence after a signal operation throws', () => {
  149. vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('absent'), { code: 'ESRCH' }) })
  150. expect(signalLinuxDirectProcess(123, () => { throw new Error('signal failed') })).toBe(true)
  151. })
  152. it('rechecks bootstrap and literal transient-scope support', () => {
  153. const spawnSync = vi.fn(() => ({ status: 0, error: undefined }))
  154. const runnerAvailable = vi.fn(() => true)
  155. const loadLinuxExecve = vi.fn(() => vi.fn() as never)
  156. const inputs = {
  157. spawnSync: spawnSync as never,
  158. runnerAvailable,
  159. runnerInvocation: ['/usr/bin/node', '/runner.js'] as [string, ...string[]],
  160. loadLinuxExecve,
  161. systemdRun: '/bin/systemd-run',
  162. systemctl: '/bin/systemctl',
  163. }
  164. expect(probeLinuxNative(inputs)).toBe(true)
  165. expect(probeLinuxNative(inputs)).toBe(true)
  166. expect(runnerAvailable).toHaveBeenCalledTimes(2)
  167. expect(loadLinuxExecve).toHaveBeenCalledTimes(2)
  168. expect(spawnSync).toHaveBeenCalledTimes(2)
  169. expect(probeLinuxBootstrap({
  170. ...inputs,
  171. loadLinuxExecve: () => { throw new Error('libc execve missing') },
  172. })).toBe(false)
  173. })
  174. it('reports each failed dynamic prerequisite without executing a target', () => {
  175. expect(probeLinuxScope({
  176. spawnSync: vi.fn(() => ({ status: null, error: new Error('missing') })) as never,
  177. })).toBe(false)
  178. expect(probeLinuxBootstrap({
  179. loadLinuxExecve: () => vi.fn() as never,
  180. runnerInvocation: ['/missing'],
  181. runnerAvailable: () => false,
  182. })).toBe(false)
  183. expect(probeLinuxBootstrap({
  184. loadLinuxExecve: () => vi.fn() as never,
  185. resolveRunnerInvocation: () => { throw new Error('runner resolution failed') },
  186. })).toBe(false)
  187. })
  188. it('uses the default command adapters and runner resolution', () => {
  189. childProcessMocks.spawnSync.mockReturnValue({ status: 0, error: undefined })
  190. expect(probeLinuxScope()).toBe(true)
  191. expect(probeLinuxManager()).toBe(true)
  192. expect(childProcessMocks.spawnSync).toHaveBeenCalledTimes(2)
  193. expect(probeLinuxBootstrap({ loadLinuxExecve: () => vi.fn() as never })).toBe(true)
  194. expect(probeLinuxBootstrap({
  195. runnerInvocation: [process.execPath],
  196. runnerAvailable: () => true,
  197. })).toBe(process.platform !== 'win32')
  198. })
  199. it('keeps quieting on the transient-scope probe but preserves manager diagnostics', () => {
  200. const spawnSync = vi.fn((
  201. _command: string,
  202. _args: readonly string[],
  203. _options: unknown,
  204. ) => ({ status: 0, error: undefined }))
  205. expect(probeLinuxScope({ spawnSync: spawnSync as never })).toBe(true)
  206. expect(probeLinuxManager({ spawnSync: spawnSync as never })).toBe(true)
  207. const scopeOptions = spawnSync.mock.calls[0]?.[2] as { env: NodeJS.ProcessEnv }
  208. const managerOptions = spawnSync.mock.calls[1]?.[2] as { env: NodeJS.ProcessEnv }
  209. expect(scopeOptions.env).toMatchObject({ LC_ALL: 'C', SYSTEMD_LOG_TARGET: 'null' })
  210. expect(managerOptions.env).toMatchObject({ LC_ALL: 'C' })
  211. expect(managerOptions.env).not.toHaveProperty('SYSTEMD_LOG_TARGET')
  212. expect(probeLinuxManager({
  213. spawnSync: vi.fn(() => ({ status: 1, error: undefined })) as never,
  214. })).toBe(false)
  215. expect(probeLinuxManager({
  216. spawnSync: vi.fn(() => ({ status: null, error: new Error('missing') })) as never,
  217. })).toBe(false)
  218. })
  219. })
  220. describe('Linux scope establishment and quiescence', () => {
  221. it.each(['abort', 'terminate'] as const)('settles and cleans a managed handle after early %s', async (action) => {
  222. const { child, result, requestPath } = launch(async () => missingUnit())
  223. const processKill = vi.spyOn(process, 'kill')
  224. const controller = new AbortController()
  225. const handle = bindManagedProcess({ ...spec(), signal: controller.signal }, result)
  226. if (action === 'abort') controller.abort(new Error('cancelled'))
  227. else handle.terminate()
  228. expect(processKill).toHaveBeenCalledWith(321, 'SIGTERM')
  229. child.exit(null, 'SIGTERM')
  230. child.stdout.end()
  231. child.stderr.end()
  232. await expect(handle.done).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  233. await expect(handle.waitForExit()).resolves.toBe(true)
  234. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  235. })
  236. it.each([
  237. { exitCode: 1, signal: null },
  238. { exitCode: null, signal: 'SIGSEGV' as const },
  239. ])('retains unrelated bootstrap failure $exitCode / $signal after a termination request', async (outcome) => {
  240. const { child, result } = launch(async () => missingUnit())
  241. result.owner.signal('SIGTERM')
  242. child.exit(outcome.exitCode, outcome.signal)
  243. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  244. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  245. result.owner.cleanup?.()
  246. })
  247. it('does not mistake pre-establishment unit absence for quiescence and settles an empty range after cancellation', async () => {
  248. const { child, result, requestPath, spawnSync } = launch(async () => missingUnit())
  249. const processKill = vi.spyOn(process, 'kill')
  250. const waiting = result.owner.waitForExit()
  251. result.owner.signal('SIGTERM')
  252. expect(processKill).toHaveBeenCalledWith(321, 'SIGTERM')
  253. expect(spawnSync).toHaveBeenCalledWith('/bin/systemctl', expect.arrayContaining([
  254. 'kill', '--kill-whom=all', '--signal=SIGTERM',
  255. ]), expect.anything())
  256. const direct = expect(result.direct).resolves.toEqual({ exitCode: null, signal: 'SIGTERM' })
  257. child.exit(null, 'SIGTERM')
  258. await direct
  259. await expect(waiting).resolves.toBeUndefined()
  260. expect(existsSync(requestPath)).toBe(true)
  261. result.owner.cleanup?.()
  262. })
  263. it('accepts request consumption followed by rapid --collect unload as stopped', async () => {
  264. const states = [activeUnit(), unloadedUnit()]
  265. const { child, result, requestPath } = launch(async () => states.shift() ?? missingUnit())
  266. expect(consumeLinuxLaunchRequest(requestPath)).toEqual({ cwd: '/target', env: { TARGET: 'yes' } })
  267. const waiting = result.owner.waitForExit()
  268. child.exit(0, null)
  269. await expect(result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  270. await expect(waiting).resolves.toBeUndefined()
  271. result.owner.signal('SIGKILL')
  272. result.owner.cleanup?.()
  273. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  274. })
  275. it.each(['SIGTERM', 'SIGKILL'] as const)('uses the scope alone after establishment and the direct range only when scope %s fails', async (signal) => {
  276. const spawnSync = vi.fn()
  277. .mockReturnValueOnce({ status: 0, stdout: '', stderr: '' })
  278. .mockReturnValueOnce({ status: 1, stdout: '', stderr: 'scope signal failed' })
  279. const { child, result, requestPath } = launch(async () => activeUnit(), {
  280. spawnSync: spawnSync as never,
  281. })
  282. consumeLinuxLaunchRequest(requestPath)
  283. const processKill = vi.spyOn(process, 'kill').mockReturnValue(true)
  284. result.owner.signal('SIGTERM')
  285. expect(processKill).not.toHaveBeenCalled()
  286. result.owner.signal(signal)
  287. expect(processKill.mock.calls).toEqual(signal === 'SIGKILL'
  288. ? [[-321, signal], [321, signal]]
  289. : [[-321, signal]])
  290. expect(child.kills).toEqual([])
  291. expect(spawnSync).toHaveBeenCalledTimes(2)
  292. child.exit(null, signal)
  293. await expect(result.direct).resolves.toEqual({ exitCode: null, signal })
  294. result.owner.cleanup?.()
  295. })
  296. it('uses manager-observed unit existence as establishment proof', async () => {
  297. const { child, result } = launch(async () => activeUnit('inactive'))
  298. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  299. child.exit(1, null)
  300. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  301. result.owner.cleanup?.()
  302. })
  303. it('keeps waiting while the unit is absent and the direct launcher is still running', async () => {
  304. const states = [missingUnit(), activeUnit('inactive')]
  305. const { child, result } = launch(async () => states.shift() ?? activeUnit('inactive'))
  306. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  307. child.exit(1, null)
  308. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  309. result.owner.cleanup?.()
  310. })
  311. it('treats status-zero not-found as pending until the direct launcher proves the range was never created', async () => {
  312. const state: { child?: FakeChild } = {}
  313. const launched = launch(async () => unloadedUnit(), {
  314. sleep: async () => { state.child?.exit(127, null) },
  315. })
  316. state.child = launched.child
  317. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  318. await expect(launched.result.direct).rejects.toThrow('before its bootstrap consumed')
  319. launched.result.owner.cleanup?.()
  320. })
  321. it('polls promptly before establishment and backs off established active scopes', async () => {
  322. const delays: number[] = []
  323. const states = [
  324. missingUnit(),
  325. activeUnit(),
  326. activeUnit(),
  327. activeUnit(),
  328. activeUnit(),
  329. activeUnit(),
  330. activeUnit(),
  331. activeUnit(),
  332. activeUnit(),
  333. activeUnit('inactive'),
  334. ]
  335. const launched = launch(
  336. async () => states.shift() ?? activeUnit('inactive'),
  337. { sleep: async (delayMs) => { delays.push(delayMs) } },
  338. )
  339. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  340. expect(delays).toEqual([50, 50, 100, 200, 400, 800, 1_600, 3_200, 5_000])
  341. launched.result.owner.cleanup?.()
  342. })
  343. it('keeps reloading scopes active and lets terminate wake a backed-off observation', async () => {
  344. const states = [activeUnit('reloading'), activeUnit('inactive')]
  345. const sleeping = Promise.withResolvers<undefined>()
  346. const sleep = vi.fn(async (_delayMs: number, signal?: AbortSignal) => {
  347. sleeping.resolve(undefined)
  348. if (signal === undefined) throw new Error('missing sleep cancellation signal')
  349. await new Promise<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
  350. })
  351. const launched = launch(async () => states.shift() ?? activeUnit('inactive'), { sleep })
  352. consumeLinuxLaunchRequest(launched.requestPath)
  353. const waiting = launched.result.owner.waitForExit()
  354. await sleeping.promise
  355. launched.result.owner.signal('SIGTERM')
  356. await expect(waiting).resolves.toBeUndefined()
  357. expect(sleep).toHaveBeenCalledOnce()
  358. expect(sleep.mock.calls[0]?.[0]).toBe(50)
  359. expect(sleep.mock.calls[0]?.[1]?.aborted).toBe(true)
  360. expect(launched.spawnSync).toHaveBeenCalledOnce()
  361. launched.result.owner.cleanup?.()
  362. })
  363. it('skips the next poll delay when terminate arrives during a manager query', async () => {
  364. const firstQuery = Promise.withResolvers<ReturnType<typeof activeUnit>>()
  365. const query = vi.fn()
  366. .mockImplementationOnce(async () => await firstQuery.promise)
  367. .mockResolvedValueOnce(activeUnit('inactive'))
  368. const sleep = vi.fn(async () => {})
  369. const launched = launch(query, { sleep })
  370. consumeLinuxLaunchRequest(launched.requestPath)
  371. const waiting = launched.result.owner.waitForExit()
  372. launched.result.owner.signal('SIGTERM')
  373. firstQuery.resolve(activeUnit())
  374. await expect(waiting).resolves.toBeUndefined()
  375. expect(sleep).not.toHaveBeenCalled()
  376. launched.result.owner.cleanup?.()
  377. })
  378. it.each([
  379. { exitCode: 127, signal: null },
  380. { exitCode: null, signal: 'SIGTERM' as const },
  381. ])('rejects unexpected bootstrap exit $exitCode / $signal and settles the empty range', async (outcome) => {
  382. const { child, result } = launch(async () => missingUnit())
  383. child.exit(outcome.exitCode, outcome.signal)
  384. await expect(result.direct).rejects.toThrow('before its bootstrap consumed')
  385. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  386. result.owner.cleanup?.()
  387. })
  388. it('preserves a recorded pre-exec failure even when cancellation also terminates the bootstrap', async () => {
  389. const { child, result, requestPath } = launch(async () => missingUnit())
  390. const files = linuxLaunchFilesFromLocator(requestPath)
  391. result.owner.signal('SIGTERM')
  392. unlinkSync(requestPath)
  393. writeLinuxStartupError(files, {
  394. type: 'error',
  395. error: { name: 'Error', message: 'spawn tool ENOENT', code: 'ENOENT' },
  396. })
  397. child.exit(null, 'SIGTERM')
  398. await expect(result.direct).rejects.toMatchObject({ code: 'ENOENT' })
  399. result.owner.cleanup?.()
  400. })
  401. it('retries a failed state query and rejects unknown states or failed final kills', async () => {
  402. const query = vi.fn()
  403. .mockResolvedValueOnce({ status: null, stdout: '', stderr: '', error: new Error('query failed') })
  404. .mockResolvedValueOnce(missingUnit())
  405. const { result, requestPath } = launch(query)
  406. unlinkSync(requestPath)
  407. await expect(result.owner.waitForExit()).rejects.toThrow('query failed')
  408. await expect(result.owner.waitForExit()).resolves.toBeUndefined()
  409. result.owner.cleanup?.()
  410. const unknown = launch(async () => activeUnit('mystery'))
  411. await expect(unknown.result.owner.waitForExit()).rejects.toThrow('unknown ActiveState')
  412. unknown.result.owner.cleanup?.()
  413. const unknownLoad = launch(async () => unitState('masked', 'inactive'))
  414. await expect(unknownLoad.result.owner.waitForExit()).rejects.toThrow('unknown state')
  415. unknownLoad.result.owner.cleanup?.()
  416. const killFailed = launch(async () => activeUnit(), {
  417. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'permission denied' })) as never,
  418. })
  419. vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('denied'), { code: 'EPERM' }) })
  420. killFailed.result.owner.signal('SIGKILL')
  421. await expect(killFailed.result.owner.waitForExit()).rejects.toThrow('could not signal')
  422. killFailed.result.owner.cleanup?.()
  423. })
  424. it('rechecks a pre-signal observation before reporting a failed final kill', async () => {
  425. denyProcessGroups()
  426. const beforeKill = Promise.withResolvers<ReturnType<typeof activeUnit>>()
  427. const query = vi.fn()
  428. .mockImplementationOnce(() => beforeKill.promise)
  429. .mockResolvedValueOnce(activeUnit('inactive'))
  430. const sleep = vi.fn(async () => {})
  431. const launched = launch(query, {
  432. sleep,
  433. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'Invalid argument' })) as never,
  434. })
  435. consumeLinuxLaunchRequest(launched.requestPath)
  436. const waiting = launched.result.owner.waitForExit()
  437. launched.result.owner.signal('SIGKILL')
  438. launched.child.exit(null, 'SIGKILL')
  439. beforeKill.resolve(activeUnit())
  440. await expect(waiting).resolves.toBeUndefined()
  441. await expect(launched.result.direct).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  442. expect(query).toHaveBeenCalledTimes(2)
  443. expect(sleep).not.toHaveBeenCalled()
  444. launched.result.owner.cleanup?.()
  445. })
  446. it('does not accept a pre-signal empty observation when the fresh range remains populated', async () => {
  447. denyProcessGroups()
  448. const beforeKill = Promise.withResolvers<ReturnType<typeof activeUnit>>()
  449. const query = vi.fn()
  450. .mockImplementationOnce(() => beforeKill.promise)
  451. .mockResolvedValueOnce(activeUnitWithTasks('1'))
  452. const launched = launch(query, {
  453. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'Invalid argument' })) as never,
  454. })
  455. consumeLinuxLaunchRequest(launched.requestPath)
  456. const waiting = launched.result.owner.waitForExit()
  457. launched.result.owner.signal('SIGKILL')
  458. launched.child.exit(null, 'SIGKILL')
  459. beforeKill.resolve(activeUnit('inactive'))
  460. await expect(waiting).rejects.toThrow('Invalid argument')
  461. await launched.result.direct
  462. expect(query).toHaveBeenCalledTimes(2)
  463. launched.result.owner.cleanup?.()
  464. })
  465. it('accepts a confirmed empty range after a failed final kill', async () => {
  466. denyProcessGroups()
  467. const spawnSync = recordingSystemctl()
  468. .mockReturnValueOnce({ status: 1, stdout: '', stderr: 'Invalid argument' })
  469. const launched = launch(async () => activeUnitWithTasks('0'), { spawnSync: spawnSync as never })
  470. consumeLinuxLaunchRequest(launched.requestPath)
  471. launched.result.owner.signal('SIGKILL')
  472. launched.child.exit(null, 'SIGKILL')
  473. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  474. await expect(launched.result.direct).resolves.toEqual({ exitCode: null, signal: 'SIGKILL' })
  475. expect(spawnSync.mock.calls.map(call => call[1]?.[1])).toEqual(['kill', 'stop'])
  476. launched.result.owner.cleanup?.()
  477. })
  478. it.each([
  479. { state: 'empty', fresh: activeUnitWithTasks('0'), settles: true },
  480. { state: 'inactive', fresh: activeUnit('inactive'), settles: true },
  481. { state: 'populated', fresh: activeUnitWithTasks('1'), settles: false },
  482. { state: 'unknown', fresh: activeUnitWithTasks('[not set]'), settles: false },
  483. ].flatMap(value => ['delivered', 'already absent'].map(delivery => ({ ...value, delivery })))
  484. .flatMap(value => [false, true].map(groupAccepted => ({ ...value, groupAccepted }))))(
  485. 'joins a $delivery direct kill with groupAccepted=$groupAccepted before deciding a $state scope', async ({ fresh, settles, delivery, groupAccepted }) => {
  486. const processKill = vi.spyOn(process, 'kill').mockImplementation((pid) => {
  487. if ((pid < 0 && groupAccepted) || (pid > 0 && delivery === 'delivered')) return true
  488. throw Object.assign(new Error('absent'), { code: 'ESRCH' })
  489. })
  490. const firstRead = Promise.withResolvers<ReturnType<typeof activeUnit>>()
  491. const queried = Promise.withResolvers<undefined>()
  492. const query = vi.fn()
  493. .mockImplementationOnce(() => { queried.resolve(undefined); return firstRead.promise })
  494. .mockResolvedValueOnce(fresh)
  495. const sleep = vi.fn(async () => { throw new Error('unexpected poll delay') })
  496. const spawnSync = recordingSystemctl()
  497. .mockReturnValueOnce({ status: 1, stdout: '', stderr: 'Invalid argument' })
  498. const launched = launch(query, { sleep, spawnSync: spawnSync as never }, {
  499. ...spec(), stdio: { ...spec().stdio, control: 'pipe' },
  500. })
  501. consumeLinuxLaunchRequest(launched.requestPath)
  502. launched.result.owner.signal('SIGKILL')
  503. let completed = false
  504. const waiting = launched.result.owner.waitForExit().finally(() => { completed = true })
  505. void waiting.catch(() => {})
  506. try {
  507. await queried.promise
  508. firstRead.resolve(activeUnitWithTasks('1'))
  509. await new Promise<void>(resolve => setImmediate(resolve))
  510. expect(completed).toBe(false)
  511. expect(processKill).toHaveBeenCalledWith(321, 'SIGKILL')
  512. expect(query).toHaveBeenCalledOnce()
  513. expect(sleep).not.toHaveBeenCalled()
  514. launched.child.exit(null, 'SIGKILL')
  515. if (settles) await expect(waiting).resolves.toBeUndefined()
  516. else await expect(waiting).rejects.toThrow('Invalid argument')
  517. expect(query).toHaveBeenCalledTimes(2)
  518. expect(sleep).not.toHaveBeenCalled()
  519. expect(launched.result.control).toBe(launched.child.control)
  520. expect(launched.child.stdout.destroyed).toBe(false)
  521. expect(launched.child.control.destroyed).toBe(false)
  522. } finally {
  523. launched.child.exit(null, 'SIGKILL')
  524. await launched.result.direct
  525. launched.child.stdout.destroy()
  526. launched.child.stderr.destroy()
  527. launched.child.control.destroy()
  528. launched.result.owner.cleanup?.()
  529. }
  530. },
  531. )
  532. it('reports failed scope and direct kill submission without awaiting direct exit', async () => {
  533. vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('denied'), { code: 'EPERM' }) })
  534. const query = vi.fn(async () => activeUnitWithTasks('1'))
  535. const launched = launch(query, {
  536. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'permission denied' })) as never,
  537. })
  538. consumeLinuxLaunchRequest(launched.requestPath)
  539. launched.result.owner.signal('SIGKILL')
  540. try {
  541. await expect(launched.result.owner.waitForExit()).rejects.toThrow('permission denied')
  542. expect(launched.child.signalCode).toBeNull()
  543. expect(query).toHaveBeenCalledOnce()
  544. } finally {
  545. launched.child.exit(null, 'SIGKILL')
  546. await launched.result.direct
  547. launched.result.owner.cleanup?.()
  548. }
  549. })
  550. it.each(['live', 'EPERM', 'ESRCH'].flatMap(probe => [
  551. { probe, exitCode: 23, signal: null },
  552. { probe, exitCode: null, signal: 'SIGKILL' as const },
  553. ]))('preserves the eventual direct exit $exitCode / $signal after a denied kill and a $probe PID probe', async ({ probe, exitCode, signal }) => {
  554. const signalFailure = Object.assign(new Error('kill EPERM'), { code: 'EPERM' })
  555. const processKill = vi.spyOn(process, 'kill').mockImplementation((pid, signal) => {
  556. if (pid < 0 || (signal === 0 && probe === 'live')) return true
  557. if (signal === 0) throw Object.assign(new Error(probe), { code: probe })
  558. throw signalFailure
  559. })
  560. const query = vi.fn(async () => activeUnitWithTasks('1'))
  561. const launched = launch(query, {
  562. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'scope permission denied' })) as never,
  563. })
  564. vi.spyOn(launched.child, 'kill').mockImplementation(() => {
  565. launched.child.emit('error', signalFailure)
  566. return false
  567. })
  568. let directSettled = false
  569. const direct = launched.result.direct.finally(() => { directSettled = true })
  570. void direct.catch(() => {})
  571. consumeLinuxLaunchRequest(launched.requestPath)
  572. launched.result.owner.signal('SIGKILL')
  573. let failure: unknown
  574. const waiting = launched.result.owner.waitForExit().catch((error: unknown) => { failure = error })
  575. try {
  576. await new Promise<void>(resolve => setImmediate(resolve))
  577. expect(directSettled).toBe(false)
  578. if (probe === 'ESRCH') expect(failure).toBeUndefined()
  579. else expect(failure).toHaveProperty('message', expect.stringContaining('scope permission denied'))
  580. expect(launched.child.signalCode).toBeNull()
  581. expect(query).toHaveBeenCalledOnce()
  582. expect(processKill.mock.calls).toEqual([[-321, 'SIGKILL'], [321, 'SIGKILL'], [321, 0]])
  583. launched.child.exit(exitCode, signal)
  584. await expect(direct).resolves.toEqual({ exitCode, signal })
  585. await waiting
  586. expect(failure).toHaveProperty('message', expect.stringContaining('scope permission denied'))
  587. expect(query).toHaveBeenCalledTimes(probe === 'ESRCH' ? 2 : 1)
  588. } finally {
  589. launched.child.exit(exitCode, signal)
  590. await direct.catch(() => {})
  591. await waiting
  592. launched.result.owner.cleanup?.()
  593. }
  594. })
  595. it('reports a fresh surviving range immediately when direct exit precedes its query', async () => {
  596. denyProcessGroups()
  597. const query = vi.fn(async () => activeUnitWithTasks('1'))
  598. const launched = launch(query, {
  599. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'Invalid argument' })) as never,
  600. })
  601. consumeLinuxLaunchRequest(launched.requestPath)
  602. launched.result.owner.signal('SIGKILL')
  603. launched.child.exit(null, 'SIGKILL')
  604. await expect(launched.result.owner.waitForExit()).rejects.toThrow('Invalid argument')
  605. expect(query).toHaveBeenCalledOnce()
  606. await launched.result.direct
  607. launched.result.owner.cleanup?.()
  608. })
  609. it('keeps a direct launch error observable while joining its settlement', async () => {
  610. denyProcessGroups()
  611. const firstRead = Promise.withResolvers<ReturnType<typeof activeUnit>>()
  612. const query = vi.fn()
  613. .mockImplementationOnce(() => firstRead.promise)
  614. .mockResolvedValueOnce(activeUnit('inactive'))
  615. const launched = launch(query, {
  616. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'Invalid argument' })) as never,
  617. })
  618. consumeLinuxLaunchRequest(launched.requestPath)
  619. launched.result.owner.signal('SIGKILL')
  620. const waiting = launched.result.owner.waitForExit()
  621. firstRead.resolve(activeUnitWithTasks('1'))
  622. await new Promise<void>(resolve => setImmediate(resolve))
  623. const failure = new Error('direct process error')
  624. const directFailure = expect(launched.result.direct).rejects.toBe(failure)
  625. launched.child.emit('error', failure)
  626. await directFailure
  627. await expect(waiting).resolves.toBeUndefined()
  628. expect(query).toHaveBeenCalledTimes(2)
  629. launched.result.owner.cleanup?.()
  630. })
  631. it('retains state-query errors without awaiting direct settlement', async () => {
  632. denyProcessGroups()
  633. const failure = new Error('manager unreachable')
  634. const launched = launch(async () => { throw failure }, {
  635. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'Invalid argument' })) as never,
  636. })
  637. consumeLinuxLaunchRequest(launched.requestPath)
  638. launched.result.owner.signal('SIGKILL')
  639. await expect(launched.result.owner.waitForExit()).rejects.toBe(failure)
  640. expect(launched.child.signalCode).toBeNull()
  641. launched.child.exit(null, 'SIGKILL')
  642. await launched.result.direct
  643. launched.result.owner.cleanup?.()
  644. })
  645. it('settles a consumed empty scope before its launcher reports exit after a failed kill', async () => {
  646. denyProcessGroups()
  647. const spawnSync = recordingSystemctl()
  648. .mockReturnValueOnce({ status: 1, stdout: '', stderr: 'Invalid argument' })
  649. const launched = launch(async () => activeUnitWithTasks('0'), { spawnSync: spawnSync as never })
  650. consumeLinuxLaunchRequest(launched.requestPath)
  651. launched.result.owner.signal('SIGKILL')
  652. try {
  653. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  654. expect(launched.child.exitCode).toBeNull()
  655. expect(launched.child.signalCode).toBeNull()
  656. expect(spawnSync.mock.calls.map(call => call[1]?.[1])).toEqual(['kill', 'stop'])
  657. } finally {
  658. launched.child.exit(null, 'SIGKILL')
  659. await launched.result.direct
  660. launched.result.owner.cleanup?.()
  661. }
  662. })
  663. it.each([
  664. { tasks: '1', clientRunning: false },
  665. { tasks: '[not set]', clientRunning: false },
  666. { tasks: '0', clientRunning: true },
  667. ])('retains a failed kill with tasks=$tasks and clientRunning=$clientRunning', async ({ tasks, clientRunning }) => {
  668. denyProcessGroups()
  669. const spawnSync = recordingSystemctl()
  670. .mockReturnValueOnce({ status: 1, stdout: '', stderr: 'Invalid argument' })
  671. const launched = launch(async () => activeUnitWithTasks(tasks), { spawnSync: spawnSync as never })
  672. if (clientRunning) {
  673. vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('denied'), { code: 'EPERM' }) })
  674. }
  675. if (!clientRunning) consumeLinuxLaunchRequest(launched.requestPath)
  676. launched.result.owner.signal('SIGKILL')
  677. if (!clientRunning) launched.child.exit(null, 'SIGKILL')
  678. await expect(launched.result.owner.waitForExit()).rejects.toThrow('Invalid argument')
  679. expect(spawnSync).toHaveBeenCalledOnce()
  680. if (clientRunning) launched.child.exit(null, 'SIGKILL')
  681. await launched.result.direct
  682. launched.result.owner.cleanup?.()
  683. })
  684. it('reports command-query failures from the default systemctl adapter', async () => {
  685. childProcessMocks.execFile.mockImplementationOnce((...args: unknown[]) => {
  686. const callback = args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void
  687. const options = args[2] as { env: NodeJS.ProcessEnv }
  688. expect(options.env).toMatchObject({ LC_ALL: 'C' })
  689. expect(options.env).not.toHaveProperty('SYSTEMD_LOG_TARGET')
  690. callback(null, 'LoadState=loaded\nActiveState=inactive\n', 'manager diagnostic remains readable')
  691. return new EventEmitter()
  692. })
  693. const stopped = launch(undefined)
  694. await expect(stopped.result.owner.waitForExit()).resolves.toBeUndefined()
  695. stopped.result.owner.cleanup?.()
  696. const queryError = Object.assign(new Error('systemctl execution failed'), { code: 'ENOENT' })
  697. childProcessMocks.execFile.mockImplementationOnce((...args: unknown[]) => {
  698. const callback = args.at(-1) as (error: Error | null, stdout: string, stderr: string) => void
  699. callback(queryError, '', '')
  700. return new EventEmitter()
  701. })
  702. const failed = launch(undefined)
  703. await expect(failed.result.owner.waitForExit()).rejects.toBe(queryError)
  704. failed.result.owner.cleanup?.()
  705. })
  706. it('rejects malformed, duplicate, incomplete, and extra manager state fields', async () => {
  707. for (const [stdout, message] of [
  708. ['loaded\nActiveState=active\n', 'malformed state'],
  709. ['LoadState=loaded\nLoadState=loaded\nActiveState=active\n', 'duplicate LoadState'],
  710. ['LoadState=loaded\n', 'incomplete state'],
  711. ['LoadState=loaded\nActiveState=inactive\nOther=value\n', 'incomplete state'],
  712. ['LoadState=loaded\nActiveState=active\nTasksCurrent=0\nOther=value\n', 'incomplete state'],
  713. ] as const) {
  714. const launched = launch(async () => ({ status: 0, stdout, stderr: '' }))
  715. await expect(launched.result.owner.waitForExit()).rejects.toThrow(message)
  716. launched.result.owner.cleanup?.()
  717. }
  718. })
  719. it('rejects a manager process count that is neither numeric nor the unset sentinel', async () => {
  720. const launched = launch(async () => activeUnitWithTasks('many'))
  721. await expect(launched.result.owner.waitForExit()).rejects.toThrow('non-numeric TasksCurrent')
  722. launched.result.owner.cleanup?.()
  723. })
  724. it('releases an active scope left with no processes once its client has gone', async () => {
  725. // Regression: the manager's empty cgroup never ends this unit on its own.
  726. denyProcessGroups()
  727. const spawnSync = recordingSystemctl()
  728. const launched = launch(async () => activeUnitWithTasks('0'), { spawnSync: spawnSync as never })
  729. launched.result.owner.signal('SIGKILL')
  730. launched.child.exit(null, 'SIGKILL')
  731. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  732. expect(spawnSync.mock.calls.map(call => call[1])).toEqual([
  733. ['--user', 'kill', '--kill-whom=all', '--signal=SIGKILL', expect.stringMatching(/\.scope$/u)],
  734. ['--user', 'stop', expect.stringMatching(/\.scope$/u)],
  735. ])
  736. launched.result.owner.cleanup?.()
  737. })
  738. it('concludes the empty range even when releasing the leftover scope fails', async () => {
  739. denyProcessGroups()
  740. const spawnSync = recordingSystemctl()
  741. .mockImplementationOnce(() => ({ status: 0, stdout: '', stderr: '' }))
  742. .mockImplementationOnce(() => { throw new Error('systemctl is gone') })
  743. const launched = launch(async () => activeUnitWithTasks('0'), { spawnSync: spawnSync as never })
  744. launched.result.owner.signal('SIGKILL')
  745. launched.child.exit(null, 'SIGKILL')
  746. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  747. launched.result.owner.cleanup?.()
  748. })
  749. it('keeps waiting while the client still owns an active scope with no processes', async () => {
  750. denyProcessGroups()
  751. const spawnSync = recordingSystemctl()
  752. const states = [activeUnitWithTasks('0'), unloadedUnit()]
  753. const launched = launch(async () => states.shift() ?? unloadedUnit(), {
  754. spawnSync: spawnSync as never,
  755. })
  756. launched.result.owner.signal('SIGTERM')
  757. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  758. expect(spawnSync.mock.calls.map(call => call[1]?.[1])).toEqual(['kill'])
  759. launched.result.owner.cleanup?.()
  760. })
  761. it('keeps waiting for an active empty scope no termination has requested', async () => {
  762. const states = [activeUnitWithTasks('0'), unloadedUnit()]
  763. const launched = launch(async () => states.shift() ?? unloadedUnit())
  764. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  765. expect(launched.spawnSync).not.toHaveBeenCalled()
  766. launched.result.owner.cleanup?.()
  767. })
  768. it('treats an unset process count as unknown and keeps waiting', async () => {
  769. const states = [activeUnitWithTasks('[not set]'), unloadedUnit()]
  770. const launched = launch(async () => states.shift() ?? unloadedUnit())
  771. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  772. expect(launched.spawnSync).not.toHaveBeenCalled()
  773. launched.result.owner.cleanup?.()
  774. })
  775. it('keeps signal failures scoped to final kill proof and stays idempotent after stop', async () => {
  776. const spawnSync = vi.fn()
  777. .mockReturnValueOnce({ status: 1, stdout: '', stderr: '' })
  778. .mockReturnValueOnce({ status: 1, stderr: 'Unit dsh.scope could not be found.' })
  779. .mockReturnValueOnce({ status: 1, stdout: '', stderr: '' })
  780. .mockReturnValueOnce({ status: 0, stdout: '', stderr: '' })
  781. const states = [activeUnit(), activeUnit('failed')]
  782. const launched = launch(async () => states.shift() ?? missingUnit(), {
  783. spawnSync: spawnSync as never,
  784. })
  785. launched.child.pid = undefined
  786. unlinkSync(launched.requestPath)
  787. launched.result.owner.signal('SIGTERM')
  788. launched.result.owner.signal('SIGKILL')
  789. launched.result.owner.signal('SIGKILL')
  790. launched.result.owner.signal('SIGKILL')
  791. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  792. await expect(launched.result.owner.waitForExit()).resolves.toBeUndefined()
  793. launched.result.owner.terminateForHostExit()
  794. expect(spawnSync).toHaveBeenCalledTimes(4)
  795. launched.result.owner.cleanup?.()
  796. })
  797. it('reports unreadable manager output and a failed kill before establishment', async () => {
  798. const withOutput = launch(async () => ({
  799. status: 5, stdout: '', stderr: 'permission denied',
  800. }))
  801. await expect(withOutput.result.owner.waitForExit()).rejects.toThrow('permission denied')
  802. withOutput.result.owner.cleanup?.()
  803. const withoutOutput = launch(async () => ({ status: null, stdout: '', stderr: '' }))
  804. await expect(withoutOutput.result.owner.waitForExit()).rejects.toThrow('exit null')
  805. withoutOutput.result.owner.cleanup?.()
  806. const killFailed = launch(async () => missingUnit(), {
  807. spawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: 'kill denied' })) as never,
  808. })
  809. vi.spyOn(process, 'kill').mockImplementation(() => { throw new Error('missing process group') })
  810. killFailed.result.owner.signal('SIGKILL')
  811. await expect(killFailed.result.owner.waitForExit()).rejects.toThrow('kill denied')
  812. killFailed.result.owner.cleanup?.()
  813. })
  814. it('settles direct outcomes once and reports malformed startup errors', async () => {
  815. const childError = launch(async () => missingUnit())
  816. const spawnError = new Error('systemd-run failed')
  817. childError.child.emit('error', spawnError)
  818. childError.child.exit(1, null)
  819. await expect(childError.result.direct).rejects.toBe(spawnError)
  820. childError.result.owner.cleanup?.()
  821. const lateError = launch(async () => missingUnit())
  822. consumeLinuxLaunchRequest(lateError.requestPath)
  823. lateError.child.exit(0, null)
  824. lateError.child.emit('error', new Error('late child error'))
  825. await expect(lateError.result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  826. lateError.result.owner.cleanup?.()
  827. const malformed = launch(async () => missingUnit())
  828. const files = linuxLaunchFilesFromLocator(malformed.requestPath)
  829. unlinkSync(malformed.requestPath)
  830. writeFileSync(files.startupErrorPath, '{', { mode: 0o600 })
  831. malformed.child.exit(127, null)
  832. await expect(malformed.result.direct).rejects.toBeInstanceOf(SyntaxError)
  833. malformed.result.owner.cleanup?.()
  834. })
  835. it('does not signal a direct group before the launcher publishes a pid', async () => {
  836. const launched = launch(async () => activeUnit('inactive'))
  837. launched.child.pid = undefined
  838. const processKill = vi.spyOn(process, 'kill')
  839. launched.result.owner.signal('SIGTERM')
  840. expect(processKill).not.toHaveBeenCalled()
  841. expect(launched.child.kills).toEqual([])
  842. consumeLinuxLaunchRequest(launched.requestPath)
  843. launched.child.exit(0, null)
  844. await expect(launched.result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  845. launched.result.owner.cleanup?.()
  846. })
  847. it('does not signal the direct group after the launcher exits', async () => {
  848. const { child, result, requestPath, spawnSync } = launch(async () => activeUnit())
  849. consumeLinuxLaunchRequest(requestPath)
  850. child.exit(0, null)
  851. await expect(result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  852. const processKill = vi.spyOn(process, 'kill')
  853. result.owner.signal('SIGTERM')
  854. result.owner.terminateForHostExit()
  855. expect(processKill).not.toHaveBeenCalled()
  856. expect(child.kills).toEqual([])
  857. expect(spawnSync).toHaveBeenCalledTimes(2)
  858. result.owner.cleanup?.()
  859. })
  860. it('signals the group and direct process before the exact synchronous scope kill on host exit', () => {
  861. const events: string[] = []
  862. const { result } = launch(async () => missingUnit(), {
  863. spawnSync: vi.fn(() => { events.push('scope'); return { status: 0 } }) as never,
  864. })
  865. vi.spyOn(process, 'kill').mockImplementation((pid) => { events.push(pid < 0 ? 'group' : 'direct'); return true })
  866. result.owner.terminateForHostExit()
  867. expect(events).toEqual(['group', 'direct', 'scope'])
  868. result.owner.cleanup?.()
  869. })
  870. })
  871. describe('Linux PTY bootstrap reuse', () => {
  872. const terminalSpec = {
  873. argv: ['bash', '--noprofile'],
  874. cwd: '/target',
  875. env: { TARGET: 'yes' },
  876. rows: 24,
  877. cols: 80,
  878. graceMs: 100,
  879. } as const
  880. it.each(['SIGTERM', 'SIGKILL'] as const)('preserves %s before bootstrap consumption and joins the empty scope', async (signal) => {
  881. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' }, {
  882. spawnSync: vi.fn(() => missingUnit()) as never,
  883. systemctlQuery: async () => missingUnit(),
  884. })
  885. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  886. if (requestPath === undefined) throw new Error('missing PTY request')
  887. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  888. let running = true
  889. const kill = vi.fn()
  890. const owner = scope.bindOwner({ running: () => running, signal: kill.mockReturnValue(true), settled: Promise.resolve() })
  891. owner.signal(signal)
  892. expect(kill).toHaveBeenCalledExactlyOnceWith(signal)
  893. running = false
  894. expect(existsSync(requestPath)).toBe(true)
  895. expect(scope.resolveOutcome({ exitCode: 0, signal })).toEqual({ exitCode: 0, signal })
  896. await expect(owner.waitForExit()).resolves.toBeUndefined()
  897. scope.cleanup()
  898. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  899. })
  900. it('uses the same request/bootstrap, preserves argv, and cleans after owner settlement', async () => {
  901. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' }, {
  902. systemdRun: '/bin/systemd-run',
  903. systemctl: '/bin/systemctl',
  904. runnerInvocation: ['/usr/bin/node', '/runner.js'],
  905. spawnSync: vi.fn(() => ({ status: 0 })) as never,
  906. systemctlQuery: async () => missingUnit(),
  907. })
  908. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  909. if (requestPath === undefined) throw new Error('missing PTY request')
  910. expect(scope.args.slice(-3)).toEqual(['--', 'bash', '--noprofile'])
  911. expect(consumeLinuxLaunchRequest(requestPath)).toEqual({ cwd: '/target', env: { TARGET: 'yes' } })
  912. const owner = scope.bindOwner({ running: () => false, signal: vi.fn(() => true), settled: Promise.resolve() })
  913. await expect(owner.waitForExit()).resolves.toBeUndefined()
  914. expect(scope.resolveOutcome({ exitCode: 0, signal: null })).toEqual({ exitCode: 0, signal: null })
  915. scope.cleanup()
  916. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  917. })
  918. it('surfaces PTY pre-exec errors instead of launcher outcomes', () => {
  919. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' })
  920. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  921. if (requestPath === undefined) throw new Error('missing PTY request')
  922. const files = linuxLaunchFilesFromLocator(requestPath)
  923. unlinkSync(requestPath)
  924. writeLinuxStartupError(files, {
  925. type: 'error', error: { name: 'Error', message: 'bad cwd', code: 'ENOENT' },
  926. })
  927. expect(() => scope.resolveOutcome({ exitCode: 127, signal: null })).toThrow('bad cwd')
  928. scope.cleanup()
  929. })
  930. it('uses default owner dependencies and rejects an unconsumed request', () => {
  931. const scope = prepareLinuxTerminalScope(terminalSpec, { TARGET: 'yes' })
  932. const requestPath = scope.env[SUBPROCESS_RUNNER_ENV]
  933. if (requestPath === undefined) throw new Error('missing PTY request')
  934. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  935. scope.bindOwner({ running: () => true, signal: vi.fn(() => true), settled: Promise.resolve() })
  936. expect(() => scope.resolveOutcome({ exitCode: 1, signal: null })).toThrow(
  937. 'before its bootstrap consumed',
  938. )
  939. scope.cleanup()
  940. })
  941. })
  942. describe('Linux ordinary launch adapters', () => {
  943. it('uses the default launch dependencies without changing the target request', async () => {
  944. const child = new FakeChild()
  945. childProcessMocks.spawn.mockReturnValue(child)
  946. const result = launchLinuxScope(spec(), { TARGET: 'yes' })
  947. const call = childProcessMocks.spawn.mock.calls[0]
  948. const options = call?.[2] as { env?: NodeJS.ProcessEnv } | undefined
  949. const requestPath = options?.env?.[SUBPROCESS_RUNNER_ENV]
  950. if (requestPath === undefined) throw new Error('launch did not publish a request locator')
  951. directories.push(linuxLaunchFilesFromLocator(requestPath).directory)
  952. expect(call?.[0]).toBe('systemd-run')
  953. expect(consumeLinuxLaunchRequest(requestPath)).toEqual({ cwd: '/target', env: { TARGET: 'yes' } })
  954. child.exit(0, null)
  955. await expect(result.direct).resolves.toEqual({ exitCode: 0, signal: null })
  956. result.owner.cleanup?.()
  957. })
  958. it('removes the private launch directory when spawn throws synchronously', () => {
  959. const spawnError = new Error('synchronous spawn failure')
  960. let requestPath: string | undefined
  961. expect(() => launchLinuxScope(spec(), { TARGET: 'yes' }, {
  962. runnerInvocation: ['/usr/bin/node', '/runner.js'],
  963. spawn: vi.fn((_command: string, _args: readonly string[], options: { env?: NodeJS.ProcessEnv }) => {
  964. requestPath = options.env?.[SUBPROCESS_RUNNER_ENV]
  965. throw spawnError
  966. }) as never,
  967. })).toThrow(spawnError)
  968. if (requestPath === undefined) throw new Error('spawn did not receive a request locator')
  969. expect(existsSync(linuxLaunchFilesFromLocator(requestPath).directory)).toBe(false)
  970. })
  971. })