runtime.spec.ts 18 KB

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