host-failures.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. import { Duplex, PassThrough } from 'node:stream'
  2. import { setImmediate } from 'node:timers/promises'
  3. import { Context } from '@deepseek-ai/cordis'
  4. import { describe, expect, it, onTestFinished, vi } from 'vitest'
  5. import type { CodeBindingFunction, CodeRunRequest } from '@deepseek-ai/dsh-code-runtime'
  6. import type { SubprocessHandle, SubprocessOutcome } from '@deepseek-ai/dsh-subprocess'
  7. import { SandboxUnavailableError } from '@deepseek-ai/dsh-sandbox'
  8. import type { ConfinedArgv } from '@deepseek-ai/dsh-sandbox'
  9. import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
  10. import type { Config } from '../src/index.ts'
  11. import { JsonChannel } from '../src/channel.ts'
  12. import { encodeCodeJsonWire } from '../src/json-wire.ts'
  13. import { mountRuntime } from './setup.ts'
  14. const request: CodeRunRequest = { program: 'return 1', bindings: [] }
  15. const NO_INITIAL_FRAME = Symbol('no initial frame')
  16. async function setup(config: Config = {}, mode: 'read-only' | 'danger-full-access' = 'danger-full-access') {
  17. const ctx = new Context()
  18. const runtime = await mountRuntime(ctx, config, { mode, workspaceRoot: process.cwd() })
  19. const control = new Duplex({
  20. read() {},
  21. write(chunk: Buffer, _encoding, callback) {
  22. if (childControl.destroyed) { callback(new Error('peer closed')); return }
  23. childControl.push(chunk)
  24. callback()
  25. },
  26. })
  27. const childControl = new Duplex({
  28. read() {},
  29. write(chunk: Buffer, _encoding, callback) {
  30. if (control.destroyed) { callback(new Error('peer closed')); return }
  31. control.push(chunk)
  32. callback()
  33. },
  34. })
  35. const stdout = new PassThrough()
  36. const stderr = new PassThrough()
  37. const direct = Promise.withResolvers<SubprocessOutcome>()
  38. const messages: unknown[] = []
  39. const handle: SubprocessHandle = {
  40. stdin: undefined,
  41. stdout,
  42. stderr,
  43. control,
  44. collected: {},
  45. done: direct.promise,
  46. terminate: vi.fn(() => {
  47. stdout.end()
  48. stderr.end()
  49. direct.resolve({ exitCode: 0, signal: null })
  50. }),
  51. waitForExit: vi.fn(async () => true),
  52. }
  53. const writes = new Set<Promise<void>>()
  54. let receive: (message: unknown) => void = () => {}
  55. const peer = new JsonChannel(childControl, 1024 * 1024, (message) => {
  56. messages.push(message)
  57. receive(message)
  58. }, () => {})
  59. const emit = (message: unknown): void => {
  60. const write = peer.send(message).catch(() => {}).finally(() => { writes.delete(write) })
  61. writes.add(write)
  62. }
  63. const resolveExecutable = vi.spyOn(ctx.subprocess, 'resolveExecutable').mockResolvedValue(process.execPath)
  64. const spawn = vi.spyOn(ctx.subprocess, 'spawn').mockReturnValue(handle)
  65. onTestFinished(async () => {
  66. peer.close()
  67. control.destroy()
  68. stdout.destroy()
  69. stderr.destroy()
  70. direct.resolve({ exitCode: 0, signal: null })
  71. await Promise.all(writes)
  72. })
  73. const start = (input: CodeRunRequest = request, first: unknown = { type: 'ready' }) => {
  74. const result = runtime.run(runtime.resolve(input))
  75. if (first !== NO_INITIAL_FRAME) queueMicrotask(() => { emit(first) })
  76. return result
  77. }
  78. const onBoot = (callback: () => void): void => {
  79. receive = (message) => {
  80. if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'boot') callback()
  81. }
  82. }
  83. return {
  84. ctx, runtime, handle, direct, stdout, stderr, control, peer, messages, spawn, resolveExecutable, emit, start, onBoot,
  85. receive: (callback: typeof receive) => { receive = callback },
  86. }
  87. }
  88. function call(id: number, value: string = '') {
  89. return { type: 'call', id, global: 'tools', name: 'test', args: encodeCodeJsonWire(value) }
  90. }
  91. function withBinding(fn: CodeBindingFunction): CodeRunRequest {
  92. return { ...request, bindings: [{ global: 'tools', functions: { test: fn } }] }
  93. }
  94. function confinement(argv: string[]): ConfinedArgv {
  95. return { argv, enforcement: 'partial', denialSignatures: ['EACCES'], runnerFailureRules: [{ fatalSignatures: ['sandbox-fatal:'] }] }
  96. }
  97. describe('Node runtime host failures', () => {
  98. it.each<[Config, string]>([
  99. [{ timeoutMs: 0 }, 'timeoutMs'],
  100. [{ maxPendingCalls: -1 }, 'maxPendingCalls'],
  101. [{ maxOldGenerationSizeMb: Infinity }, 'maxOldGenerationSizeMb'],
  102. [{ timeoutMs: MAX_TIMER_DELAY_MS + 1 }, 'timeoutMs'],
  103. [{ maxTimeoutMs: MAX_TIMER_DELAY_MS + 1 }, 'maxTimeoutMs'],
  104. [{ graceMs: MAX_TIMER_DELAY_MS + 1 }, 'graceMs'],
  105. [{ maxOutputBytes: 3 }, 'maxOutputBytes'],
  106. [{ maxOutputBytes: 4.5 }, 'maxOutputBytes'],
  107. [{ maxMessageBytes: 1.5 }, 'maxMessageBytes'],
  108. [{ maxMessageBytes: 0x1_0000_0000 }, 'maxMessageBytes'],
  109. [{ maxPendingCalls: 1.5 }, 'maxPendingCalls'],
  110. [{ maxOldGenerationSizeMb: 1.5 }, 'maxOldGenerationSizeMb'],
  111. [{ nodeExecutable: '' }, 'nodeExecutable'],
  112. [{ bootstrapPath: 'relative-bootstrap.js' }, 'bootstrapPath'],
  113. ])('rejects deployment configuration %j', async (config, field) => {
  114. await expect(mountRuntime(new Context(), config)).rejects.toThrow(field)
  115. })
  116. it('reports the deployment mode and rejects unsupported resolved inputs before spawning', async () => {
  117. const h = await setup({}, 'read-only')
  118. expect(h.runtime.sandboxMode).toBe('read-only')
  119. expect(() => h.runtime.resolve({ ...request, cwd: 'relative' })).toThrow('cwd must be absolute')
  120. await expect(h.runtime.run({ ...request, cwd: process.cwd(), timeoutMs: 1 })).rejects.toThrow('resolved sandbox policy')
  121. const spec = h.runtime.resolve(request)
  122. await expect(h.runtime.run({ ...spec, timeoutMs: Infinity })).rejects.toThrow('resolved cwd and timeout')
  123. expect(h.spawn).not.toHaveBeenCalled()
  124. await h.ctx.fiber.dispose()
  125. expect(() => h.runtime.resolve(request)).toThrow('resolve after disposal')
  126. await expect(h.runtime.run(spec)).rejects.toThrow('run after disposal')
  127. })
  128. it('fails a required unavailable sandbox before spawning', async () => {
  129. const h = await setup({}, 'read-only')
  130. vi.spyOn(h.ctx.sandbox, 'confine').mockImplementation(() => { throw new SandboxUnavailableError('read-only') })
  131. expect((await h.start()).error?.kind).toBe('sandbox-unavailable')
  132. expect(h.spawn).not.toHaveBeenCalled()
  133. })
  134. it('keeps partial enforcement separate from a successful program', async () => {
  135. const h = await setup({}, 'read-only')
  136. vi.spyOn(h.ctx.sandbox, 'confine').mockImplementation(argv => confinement([...argv]))
  137. h.onBoot(() => { h.emit({ type: 'done', value: encodeCodeJsonWire(42) }) })
  138. expect(await h.start()).toEqual({ logs: [], value: 42, sandbox: { mode: 'read-only', denied: false, enforcement: 'partial' } })
  139. })
  140. it.each([['EACCES: blocked', true], ['EPERM: unrelated dialect', false]] as const)('uses only the selected denial dialect for %s', async (message, denied) => {
  141. const h = await setup({}, 'read-only')
  142. vi.spyOn(h.ctx.sandbox, 'confine').mockImplementation(argv => confinement([...argv]))
  143. h.onBoot(() => { h.emit({ type: 'done', error: { kind: 'exception', message } }) })
  144. const result = await h.start()
  145. expect(result.error).toEqual({ kind: 'exception', message })
  146. expect(result.sandbox).toEqual({ mode: 'read-only', denied, enforcement: 'partial' })
  147. })
  148. it('distinguishes fatal sandbox startup output from a program denial', async () => {
  149. const h = await setup({}, 'read-only')
  150. vi.spyOn(h.ctx.sandbox, 'confine').mockImplementation(argv => confinement([...argv]))
  151. h.onBoot(() => {
  152. h.stderr.write('sandbox-fatal: runner could not initialize')
  153. h.direct.resolve({ exitCode: 1, signal: null })
  154. })
  155. const result = await h.start()
  156. expect(result.error?.kind).toBe('sandbox-unavailable')
  157. expect(result.sandbox?.denied).toBe(false)
  158. })
  159. it('reports bootstrap assets that cannot map into the execution world', async () => {
  160. const h = await setup()
  161. vi.spyOn(h.ctx.fs, 'processPathFromHostPath').mockReturnValue(undefined)
  162. expect((await h.start()).error?.message).toContain('bootstrap is unavailable')
  163. expect(h.spawn).not.toHaveBeenCalled()
  164. })
  165. it('cleans up a provider that fails to supply its requested control pipe', async () => {
  166. const h = await setup()
  167. h.spawn.mockReturnValue({ ...h.handle, control: undefined })
  168. expect((await h.start()).error?.message).toContain('did not supply the requested control')
  169. expect(h.handle.terminate).toHaveBeenCalledOnce()
  170. expect(h.handle.waitForExit).toHaveBeenCalledOnce()
  171. })
  172. it('reports an executable lookup failure without allocating a process', async () => {
  173. const h = await setup()
  174. h.resolveExecutable.mockRejectedValue(new Error('Node executable missing'))
  175. expect((await h.start()).error).toEqual({ kind: 'worker-exit', message: 'Node executable missing' })
  176. expect(h.spawn).not.toHaveBeenCalled()
  177. })
  178. it('honors an already-aborted run without beginning executable lookup', async () => {
  179. const h = await setup()
  180. const result = await h.start({ ...request, signal: AbortSignal.abort('already stopped') }, NO_INITIAL_FRAME)
  181. expect(result.error).toEqual({ kind: 'abort', message: 'already stopped' })
  182. expect(h.resolveExecutable).not.toHaveBeenCalled()
  183. })
  184. it('does not launch after cancellation races executable lookup completion', async () => {
  185. const h = await setup()
  186. const controller = new AbortController()
  187. h.resolveExecutable.mockImplementation(async () => {
  188. controller.abort('lookup canceled')
  189. return process.execPath
  190. })
  191. expect((await h.start({ ...request, signal: controller.signal }, NO_INITIAL_FRAME)).error?.kind).toBe('abort')
  192. expect(h.spawn).not.toHaveBeenCalled()
  193. })
  194. it('reports an early control EOF using the direct process result', async () => {
  195. const h = await setup()
  196. h.spawn.mockImplementation(() => {
  197. queueMicrotask(() => {
  198. h.control.push(null)
  199. h.direct.resolve({ exitCode: 7, signal: null })
  200. })
  201. return h.handle
  202. })
  203. expect((await h.start(request, NO_INITIAL_FRAME)).error).toEqual({
  204. kind: 'worker-exit', message: 'Node process exited before completing (7)',
  205. })
  206. })
  207. it('reports startup transport loss when the direct process outcome rejects', async () => {
  208. const h = await setup()
  209. h.spawn.mockImplementation(() => {
  210. queueMicrotask(() => {
  211. h.control.emit('error', new Error('control transport closed'))
  212. h.direct.reject(new Error('runner connection broken'))
  213. })
  214. return h.handle
  215. })
  216. expect((await h.start(request, NO_INITIAL_FRAME)).error).toEqual({ kind: 'worker-exit', message: 'runner connection broken' })
  217. })
  218. it('reports control loss after readiness as a substrate failure', async () => {
  219. const h = await setup()
  220. h.onBoot(() => { h.control.emit('error', new Error('control transport closed')) })
  221. expect((await h.start()).error).toEqual({ kind: 'worker-exit', message: 'control transport closed' })
  222. })
  223. it('classifies invalid UTF-8 on the live control stream as a protocol failure', async () => {
  224. const h = await setup()
  225. h.onBoot(() => { h.control.push(Buffer.from([0, 0, 0, 1, 0xff])) })
  226. expect((await h.start()).error?.kind).toBe('protocol')
  227. })
  228. it('rejects traffic before readiness without invoking host bindings', async () => {
  229. const h = await setup()
  230. const binding = vi.fn(async () => null)
  231. const result = await h.start(withBinding(binding), call(1))
  232. expect(result.error?.message).toContain('before bootstrap readiness')
  233. expect(binding).not.toHaveBeenCalled()
  234. })
  235. it.each<[unknown, string]>([
  236. [null, 'invalid control frame'],
  237. [{ type: 'log', text: 1 }, 'invalid log frame'],
  238. [{ type: 'done', error: null }, 'invalid terminal error'],
  239. [{ type: 'done', error: { kind: 'exception', message: 1 } }, 'invalid terminal error'],
  240. [{ type: 'done', error: { kind: 'timeout', message: 'forged' } }, 'invalid terminal error'],
  241. [{ type: 'call', id: 0, global: 'tools', name: 'test' }, 'invalid binding call identity'],
  242. [{ ...call(1), name: 'constructor' }, 'undeclared binding'],
  243. [{ type: 'call', id: 1, global: 'tools', name: 'test' }, 'arguments must be lossless JSON'],
  244. [{ type: 'unknown' }, 'unknown control message'],
  245. ])('rejects malformed program frame %j', async (frame, message) => {
  246. const h = await setup()
  247. const binding = vi.fn(async () => null)
  248. h.onBoot(() => { h.emit(frame) })
  249. const result = await h.start(withBinding(binding))
  250. expect(result.error).toEqual({ kind: 'protocol', message: expect.stringContaining(message) })
  251. expect(binding).not.toHaveBeenCalled()
  252. })
  253. it('refuses a repeated call id instead of dispatching it twice', async () => {
  254. const h = await setup()
  255. const binding = vi.fn(async () => null)
  256. h.onBoot(() => { h.emit(call(1)); h.emit(call(1)) })
  257. expect((await h.start(withBinding(binding))).error?.kind).toBe('protocol')
  258. expect(binding).toHaveBeenCalledOnce()
  259. })
  260. it.each<Config>([{ maxPendingCalls: 1 }, { maxMessageBytes: 512 }])('bounds unresolved host calls with %j', async (config) => {
  261. const h = await setup(config)
  262. const release = Promise.withResolvers<null>()
  263. onTestFinished(() => { release.resolve(null) })
  264. const binding = vi.fn(async () => await release.promise)
  265. h.onBoot(() => { h.emit(call(1, 'a'.repeat(300))); h.emit(call(2, 'b'.repeat(300))) })
  266. expect((await h.start(withBinding(binding))).error?.message).toContain('pending binding calls exceed')
  267. expect(binding).toHaveBeenCalledOnce()
  268. release.resolve(null)
  269. await setImmediate()
  270. })
  271. it('rejects an untransferable completion instead of returning a substituted value', async () => {
  272. const h = await setup()
  273. h.onBoot(() => { h.emit({ type: 'done', value: { invalid: true } }) })
  274. expect((await h.start()).error?.kind).toBe('invalid-output')
  275. })
  276. it('returns non-lossless binding resolutions as program-visible binding failures', async () => {
  277. const h = await setup()
  278. h.receive((message) => {
  279. if (typeof message !== 'object' || message === null || !('type' in message)) return
  280. if (message.type === 'boot') h.emit(call(1))
  281. if (message.type === 'reply') h.emit({ type: 'done' })
  282. })
  283. expect((await h.start(withBinding(async () => Number.NaN))).error).toBeUndefined()
  284. expect(h.messages).toContainEqual({ type: 'reply', id: 1, ok: false, message: expect.stringContaining('lossless JSON') })
  285. })
  286. it('does not publish a late binding reply after the program has settled', async () => {
  287. const h = await setup()
  288. const release = Promise.withResolvers<null>()
  289. onTestFinished(() => { release.resolve(null) })
  290. h.onBoot(() => { h.emit(call(1)); h.emit({ type: 'done' }) })
  291. expect((await h.start(withBinding(async () => await release.promise))).error).toBeUndefined()
  292. release.resolve(null)
  293. await setImmediate()
  294. expect(h.messages).not.toContainEqual(expect.objectContaining({ type: 'reply' }))
  295. expect(h.control.destroyed).toBe(true)
  296. })
  297. it('reports failed managed cleanup even when the program returns successfully', async () => {
  298. const h = await setup()
  299. vi.mocked(h.handle.waitForExit).mockRejectedValue(new Error('range cannot be observed'))
  300. h.onBoot(() => { h.emit({ type: 'done', value: encodeCodeJsonWire(42) }) })
  301. expect((await h.start()).error).toEqual({ kind: 'worker-exit', message: 'managed process cleanup failed: range cannot be observed' })
  302. })
  303. it('fails when the configured frame budget cannot carry bootstrap data', async () => {
  304. const h = await setup({ maxMessageBytes: 32 })
  305. expect((await h.start()).error?.message).toContain('control output exceeds 32 queued bytes')
  306. })
  307. it('turns an oversized binding reply into a protocol failure', async () => {
  308. const h = await setup({ maxMessageBytes: 256 })
  309. h.onBoot(() => { h.emit(call(1)) })
  310. const result = await h.start(withBinding(async () => 'x'.repeat(512)))
  311. expect(result.error).toEqual({ kind: 'protocol', message: 'control output exceeds 256 queued bytes' })
  312. })
  313. it('retains admitted logs when the program reports its own output limit', async () => {
  314. const h = await setup()
  315. h.onBoot(() => {
  316. h.emit({ type: 'log', text: 'retained' })
  317. h.emit({ type: 'done', error: { kind: 'output-limit', message: 'child ledger exhausted' } })
  318. })
  319. const result = await h.start()
  320. expect(result.error?.kind).toBe('output-limit')
  321. expect(result.logs).toEqual(['retained'])
  322. })
  323. })