runtime.spec.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. import { describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import { WorkerCodeRuntime } from '@deepseek-ai/dsh-code-runtime-worker'
  4. import type { Config } from '@deepseek-ai/dsh-code-runtime-worker'
  5. import type { CodeRunResult } from '@deepseek-ai/dsh-code-runtime'
  6. /**
  7. * Integration suite over REAL worker threads (no mocks — workers are cheap
  8. * and local, per docs/testing.md's real-over-mock policy). Each test builds
  9. * a fresh context so budgets can be tuned per case.
  10. */
  11. async function setup(config: Config = {}) {
  12. const ctx = new Context()
  13. await ctx.plugin(WorkerCodeRuntime, config)
  14. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  15. return { ctx, runtime }
  16. }
  17. /** Convenience: one namespace `tools` with the given functions. */
  18. function tools(functions: Record<string, (args: unknown) => Promise<unknown>>) {
  19. return [{ global: 'tools', functions }]
  20. }
  21. describe('WorkerCodeRuntime — programs and bindings (real workers)', () => {
  22. it('registers with the seam descriptors', async () => {
  23. const { runtime } = await setup()
  24. expect(runtime.language).toBe('typescript')
  25. expect(runtime.isolation).toBe('worker-thread')
  26. })
  27. it('runs TypeScript (erasable syntax), captures output in order, returns the value', async () => {
  28. const { runtime } = await setup()
  29. const result = await runtime.run({
  30. program: `
  31. interface Point { x: number; y: number }
  32. const p: Point = { x: 1, y: 2 } as Point;
  33. console.log('point', p);
  34. process.stdout.write('raw-out\\n');
  35. console.warn('careful');
  36. return p.x + p.y;
  37. `,
  38. bindings: [],
  39. })
  40. expect(result.error).toBeUndefined()
  41. expect(result.value).toBe(3)
  42. expect(result.logs).toEqual(['point { x: 1, y: 2 }', 'raw-out\n', 'careful'])
  43. })
  44. it('bridges binding calls both ways and rejects the program-side call on a host rejection', async () => {
  45. const { runtime } = await setup()
  46. const calls: unknown[] = []
  47. const result = await runtime.run({
  48. program: `
  49. const first = await tools.echo({ n: 1 });
  50. let caught = '';
  51. try { await tools.fail({}) } catch (error) { caught = error.message }
  52. let caughtRaw = '';
  53. try { await tools.failRaw({}) } catch (error) { caughtRaw = error.message }
  54. return { first, caught, caughtRaw };
  55. `,
  56. bindings: tools({
  57. echo: async (args) => { calls.push(args); return { echoed: args } },
  58. fail: async () => { throw new Error('nope') },
  59. // A non-Error throw: the host renders it, the program still catches.
  60. failRaw: async () => { throw 'raw-nope' },
  61. }),
  62. })
  63. expect(result.error).toBeUndefined()
  64. expect(result.value).toEqual({ first: { echoed: { n: 1 } }, caught: 'nope', caughtRaw: 'raw-nope' })
  65. expect(calls).toEqual([{ n: 1 }])
  66. })
  67. it('reports non-erasable syntax as an exception without spawning a worker', async () => {
  68. const { runtime } = await setup()
  69. const result = await runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] })
  70. expect(result.error?.kind).toBe('exception')
  71. expect(result.error?.message).toMatch(/enum|strip/i)
  72. })
  73. it('reports a runtime throw as an exception with the message', async () => {
  74. const { runtime } = await setup()
  75. const result = await runtime.run({ program: 'throw new Error("kaboom")', bindings: [] })
  76. expect(result.error?.kind).toBe('exception')
  77. expect(result.error?.message).toContain('kaboom')
  78. })
  79. it('gives the program an EMPTY environment', async () => {
  80. const { runtime } = await setup()
  81. const result = await runtime.run({ program: 'return JSON.stringify(process.env)', bindings: [] })
  82. expect(result.value).toBe('{}')
  83. })
  84. it('replaces a non-cloneable return value with a string rendering', async () => {
  85. const { runtime } = await setup()
  86. const result = await runtime.run({ program: 'return { f: () => 1 }', bindings: [] })
  87. expect(typeof result.value).toBe('string')
  88. })
  89. it('completes a program that returns nothing with no value at all', async () => {
  90. const { runtime } = await setup()
  91. const result = await runtime.run({ program: 'const x = 1', bindings: [] })
  92. expect(result.error).toBeUndefined()
  93. expect('value' in result).toBe(false)
  94. })
  95. it('keeps logs streamed before a failure', async () => {
  96. const { runtime } = await setup()
  97. const result = await runtime.run({
  98. program: 'console.log("before"); throw new Error("after-log")',
  99. bindings: [],
  100. })
  101. expect(result.error?.kind).toBe('exception')
  102. expect(result.logs).toContain('before')
  103. })
  104. })
  105. describe('WorkerCodeRuntime — budgets and containment (real workers)', () => {
  106. it('ends a hot loop at the compute budget — including behind a pending decoy dispatch', async () => {
  107. const { runtime } = await setup({ computeMs: 300, maxWallMs: 30_000 })
  108. const result = await runtime.run({
  109. // The decoy: fire a call at a never-resolving binding WITHOUT awaiting,
  110. // then spin. Host-side pending-call bookkeeping would pause a naive
  111. // budget here; measured busy time cannot be fooled.
  112. program: 'void tools.slow({}); for (;;) {}',
  113. bindings: tools({ slow: () => new Promise(() => {}) }),
  114. })
  115. expect(result.error?.kind).toBe('timeout')
  116. expect(result.error?.message).toContain('compute budget')
  117. }, 15_000)
  118. it('does not charge time spent awaiting a slow binding against the compute budget', async () => {
  119. const { runtime } = await setup({ computeMs: 250, maxWallMs: 30_000 })
  120. const result = await runtime.run({
  121. program: 'return await tools.slow({})',
  122. bindings: tools({ slow: () => new Promise(resolve => setTimeout(() => { resolve('slow-done') }, 700)) }),
  123. })
  124. expect(result.error).toBeUndefined()
  125. expect(result.value).toBe('slow-done')
  126. }, 15_000)
  127. it('ends an idle-forever run at the wall-clock ceiling', async () => {
  128. const { runtime } = await setup({ computeMs: 30_000, maxWallMs: 400 })
  129. const result = await runtime.run({
  130. program: 'await tools.never({}); return 1',
  131. bindings: tools({ never: () => new Promise(() => {}) }),
  132. })
  133. expect(result.error?.kind).toBe('timeout')
  134. expect(result.error?.message).toContain('wall-clock ceiling')
  135. }, 15_000)
  136. it('reports an abort mid-run and stops the worker', async () => {
  137. const { runtime } = await setup()
  138. const controller = new AbortController()
  139. setTimeout(() => { controller.abort('user-cancel') }, 150)
  140. const result = await runtime.run({ program: 'for (;;) {}', bindings: [], signal: controller.signal })
  141. expect(result.error).toEqual({ kind: 'abort', message: 'user-cancel' })
  142. }, 15_000)
  143. it('reports a pre-aborted signal without spawning', async () => {
  144. const { runtime } = await setup()
  145. const controller = new AbortController()
  146. controller.abort('too-late')
  147. const result = await runtime.run({ program: 'return 1', bindings: [], signal: controller.signal })
  148. expect(result.error).toEqual({ kind: 'abort', message: 'too-late' })
  149. })
  150. it('drops a binding resolution that lands after the run settled', async () => {
  151. const { runtime } = await setup()
  152. const controller = new AbortController()
  153. let replyDelivered!: Promise<void>
  154. const result = await runtime.run({
  155. program: 'void tools.late({}); for (;;) {}',
  156. bindings: tools({
  157. // Anchored on invocation: abort 100ms after the call reaches the
  158. // host, resolve 400ms after — by then the run has settled, so the
  159. // resolution's reply hits the post-settlement drop.
  160. late: () => new Promise((resolve) => {
  161. setTimeout(() => { controller.abort('cancel-now') }, 100)
  162. replyDelivered = new Promise(done => setTimeout(() => { resolve('too-late'); done() }, 400))
  163. }),
  164. }),
  165. signal: controller.signal,
  166. })
  167. expect(result.error).toEqual({ kind: 'abort', message: 'cancel-now' })
  168. // Let the late resolution actually fire so its reply executes instead of
  169. // being cancelled with the test.
  170. await replyDelivered
  171. }, 15_000)
  172. it('contains an OOM under resourceLimits as worker-exit, host process healthy', async () => {
  173. const { runtime } = await setup({ maxOldGenerationSizeMb: 32 })
  174. const result = await runtime.run({
  175. program: 'const hog = []; for (;;) hog.push(new Array(1e6).fill(1));',
  176. bindings: [],
  177. })
  178. expect(result.error?.kind).toBe('worker-exit')
  179. // And the host is fine: run something else.
  180. const after = await runtime.run({ program: 'return "alive"', bindings: [] })
  181. expect(after.value).toBe('alive')
  182. }, 30_000)
  183. it('truncates runaway log output at the byte budget with an in-band marker', async () => {
  184. const { runtime } = await setup({ maxLogBytes: 300 })
  185. const result = await runtime.run({
  186. program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1',
  187. bindings: [],
  188. })
  189. expect(result.logs.at(-1)).toContain('truncated at 300 bytes')
  190. const total = result.logs.reduce((sum, text) => sum + Buffer.byteLength(text, 'utf8'), 0)
  191. expect(total).toBeLessThan(1_000)
  192. })
  193. it('caps an oversized return value with a truncation marker', async () => {
  194. const { runtime } = await setup({ maxValueBytes: 64 })
  195. const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] })
  196. expect(result.value).toBe(`${'y'.repeat(64)}… [truncated]`)
  197. })
  198. it('caps a multibyte return value by UTF-8 bytes, not string length', async () => {
  199. // 4 code units, 12 UTF-8 bytes: a length-counting cap would let the full
  200. // string cross. The worker's byte-exact capped rendering then passes the
  201. // host re-cap unchanged (cap + marker is exactly the granted slack).
  202. const { runtime } = await setup({ maxValueBytes: 4 })
  203. const result = await runtime.run({ program: 'return "€€€€"', bindings: [] })
  204. expect(result.value).toBe('€… [truncated]')
  205. })
  206. it('completes a program that awaits its write callback, capturing the chunk', async () => {
  207. // Node's write(chunk[, encoding][, callback]) contract: dropping the
  208. // callback would leave this promise pending until the wall ceiling and
  209. // misreport a completed program as a timeout.
  210. const { runtime } = await setup({ maxWallMs: 2_000 })
  211. const result = await runtime.run({
  212. program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"',
  213. bindings: [],
  214. })
  215. expect(result.error).toBeUndefined()
  216. expect(result.value).toBe('done')
  217. expect(result.logs).toContain('flushed')
  218. })
  219. it('caps a huge container whose bounded rendering is small (wire size, not rendering, is what counts)', async () => {
  220. const { runtime } = await setup()
  221. const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] })
  222. expect(result.error).toBeUndefined()
  223. expect(typeof result.value).toBe('string')
  224. expect(result.value).toContain('more items')
  225. })
  226. it('captures pipe writes that bypass the patched write slot as stray logs, capped by the same budget', async () => {
  227. const { runtime } = await setup({ maxLogBytes: 4 })
  228. const result = await runtime.run({
  229. // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep
  230. // writes in separate chunks and let both reach the host before settlement.
  231. program: `
  232. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  233. write('abcd');
  234. await new Promise(resolve => setTimeout(resolve, 150));
  235. write('ef');
  236. await new Promise(resolve => setTimeout(resolve, 100));
  237. return 1;
  238. `,
  239. bindings: [],
  240. })
  241. expect(result.error).toBeUndefined()
  242. expect(result.logs).toContain('abcd')
  243. expect(result.logs).not.toContain('ef')
  244. }, 15_000)
  245. })
  246. describe('WorkerCodeRuntime — hostile programs (real workers)', () => {
  247. it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => {
  248. const { runtime } = await setup()
  249. const result = await runtime.run({
  250. program: `
  251. const { parentPort } = await import('node:worker_threads');
  252. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  253. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  254. parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} });
  255. parentPort.postMessage({ type: 'junk' });
  256. return await tools.real({});
  257. `,
  258. bindings: tools({ real: async () => 'still-works' }),
  259. })
  260. expect(result.error).toBeUndefined()
  261. expect(result.value).toBe('still-works')
  262. })
  263. it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => {
  264. const { runtime } = await setup()
  265. const result = await runtime.run({
  266. program: `
  267. const { parentPort } = await import('node:worker_threads');
  268. for (const junk of [
  269. null, 42, 'junk', [],
  270. { type: 'nope' },
  271. { type: 'call' },
  272. { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} },
  273. { type: 'call', id: 1e9, global: 7, name: 'real', args: {} },
  274. { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} },
  275. { type: 'log' },
  276. { type: 'log', text: null },
  277. { type: 'log', text: 7 },
  278. { type: 'log', text: {} },
  279. { type: 'done', error: 5 },
  280. { type: 'done', error: { message: 5 } },
  281. ]) parentPort.postMessage(junk);
  282. return await tools.real({});
  283. `,
  284. bindings: tools({ real: async () => 'still-works' }),
  285. })
  286. expect(result.error).toBeUndefined()
  287. expect(result.value).toBe('still-works')
  288. expect(result.logs).toEqual([])
  289. })
  290. it('caps forged log floods and forged done values at the configured budgets, dropping forged extra fields', async () => {
  291. const { runtime } = await setup({ maxLogBytes: 200, maxValueBytes: 64 })
  292. const result = await runtime.run({
  293. // Forged messages bypass the worker-side LogBuffer and prepareValue
  294. // entirely — only the host-side ledger and re-cap stand between model
  295. // code and an unbounded result.
  296. program: `
  297. const { parentPort } = await import('node:worker_threads');
  298. for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', text: 'F'.repeat(100), forged: true });
  299. parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) });
  300. for (;;) {}
  301. `,
  302. bindings: [],
  303. })
  304. expect(typeof result.value).toBe('string')
  305. const value = result.value as string
  306. expect(value.startsWith('V'.repeat(64))).toBe(true)
  307. expect(value.endsWith('… [truncated]')).toBe(true)
  308. expect(value.length).toBeLessThan(120)
  309. const marker = '[dsh-code-runtime-worker] log capture truncated at 200 bytes'
  310. const total = result.logs.reduce((sum, text) => sum + Buffer.byteLength(text, 'utf8'), 0)
  311. expect(total).toBeLessThanOrEqual(200 + Buffer.byteLength(marker, 'utf8'))
  312. expect(result.logs.at(-1)).toBe(marker)
  313. })
  314. it('accepts a forged done carrying both value and error (self-sabotage, contained)', async () => {
  315. const { runtime } = await setup()
  316. const result = await runtime.run({
  317. program: `
  318. const { parentPort } = await import('node:worker_threads');
  319. parentPort.postMessage({ type: 'done', value: 'lied', error: { message: 'fake failure' } });
  320. for (;;) {}
  321. `,
  322. bindings: [],
  323. })
  324. expect(result.value).toBe('lied')
  325. expect(result.error).toEqual({ kind: 'exception', message: 'fake failure' })
  326. })
  327. it('byte-bounds forged multibyte error text at the host', async () => {
  328. // Forged error text bypasses the worker entirely; the host bound is a
  329. // BYTE bound (two € = 6 bytes fit an 8-byte cap, a third would not).
  330. const { runtime } = await setup({ maxValueBytes: 8 })
  331. const result = await runtime.run({
  332. program: `
  333. const { parentPort } = await import('node:worker_threads');
  334. parentPort.postMessage({ type: 'done', error: { message: '€'.repeat(1000) } });
  335. for (;;) {}
  336. `,
  337. bindings: [],
  338. })
  339. expect(result.error).toEqual({ kind: 'exception', message: '€€' })
  340. })
  341. it('answers a binding whose resolution cannot be cloned with a failure reply', async () => {
  342. const { runtime } = await setup()
  343. const result = await runtime.run({
  344. program: 'try { await tools.bad({}) } catch (error) { return error.message }',
  345. bindings: tools({ bad: async () => (() => 1) }),
  346. })
  347. expect(result.value).toContain('not structured-cloneable')
  348. })
  349. it('exposes binding names that collide with Object.prototype as ordinary functions', async () => {
  350. const { runtime } = await setup()
  351. const result = await runtime.run({
  352. program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]',
  353. // Computed keys: a literal `'__proto__': …` entry would SET the record's
  354. // prototype instead of declaring a binding of that name.
  355. bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }),
  356. })
  357. expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined'])
  358. })
  359. })
  360. describe('WorkerCodeRuntime — seam misuse and lifecycle', () => {
  361. it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, console)', async () => {
  362. const { runtime } = await setup()
  363. const cases: [string, RegExp][] = [
  364. ['not valid!', /not a usable identifier/],
  365. ['await', /not a usable identifier/],
  366. ['console', /duplicate binding global/],
  367. ]
  368. for (const [global, message] of cases) {
  369. await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message)
  370. }
  371. await expect(runtime.run({
  372. program: 'return 1',
  373. bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }],
  374. })).rejects.toThrow(/duplicate binding global/)
  375. })
  376. it('rejects config values that are not positive numbers', async () => {
  377. const ctx = new Context()
  378. await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/)
  379. })
  380. it('keeps runs isolated: no state survives from one run to the next', async () => {
  381. const { runtime } = await setup()
  382. await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] })
  383. const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] })
  384. expect(second.value).toBe('undefined')
  385. })
  386. it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => {
  387. const ctx = new Context()
  388. const fiber = await ctx.plugin(WorkerCodeRuntime)
  389. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  390. const inflight: Promise<CodeRunResult> = runtime.run({ program: 'for (;;) {}', bindings: [] })
  391. // Give the worker a moment to actually start spinning.
  392. await new Promise(resolve => setTimeout(resolve, 200))
  393. await fiber.dispose()
  394. const result = await inflight
  395. expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' })
  396. await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/)
  397. }, 15_000)
  398. it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => {
  399. const ctx = new Context()
  400. const fiber = await ctx.plugin(WorkerCodeRuntime)
  401. expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime)
  402. await fiber.dispose()
  403. expect(ctx.get('codeRuntime')).toBeUndefined()
  404. })
  405. })