1
0

runtime.spec.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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('caps a multibyte return value by UTF-8 bytes, not string length', async () => {
  204. // 4 code units, 12 UTF-8 bytes: a length-counting cap would let the full
  205. // string cross. The worker's byte-exact capped rendering then passes the
  206. // host re-cap unchanged (cap + marker is exactly the granted slack).
  207. const { runtime } = await setup({ maxValueBytes: 4 })
  208. const result = await runtime.run({ program: 'return "€€€€"', bindings: [] })
  209. expect(result.value).toBe('€… [truncated]')
  210. })
  211. it('completes a program that awaits its write callback, capturing the chunk', async () => {
  212. // Node's write(chunk[, encoding][, callback]) contract: dropping the
  213. // callback would leave this promise pending until the wall ceiling and
  214. // misreport a completed program as a timeout.
  215. const { runtime } = await setup({ maxWallMs: 2_000 })
  216. const result = await runtime.run({
  217. program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"',
  218. bindings: [],
  219. })
  220. expect(result.error).toBeUndefined()
  221. expect(result.value).toBe('done')
  222. expect(result.logs).toContainEqual({ source: 'stdout', text: 'flushed' })
  223. })
  224. it('caps a huge container whose bounded rendering is small (wire size, not rendering, is what counts)', async () => {
  225. const { runtime } = await setup()
  226. const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] })
  227. expect(result.error).toBeUndefined()
  228. expect(typeof result.value).toBe('string')
  229. expect(result.value).toContain('more items')
  230. })
  231. it('captures pipe writes that bypass the patched write slot as stray logs, capped by the same budget', async () => {
  232. const { runtime } = await setup({ maxLogBytes: 4 })
  233. const result = await runtime.run({
  234. // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep
  235. // writes in separate chunks and let both reach the host before settlement.
  236. program: `
  237. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  238. write('abcd');
  239. await new Promise(resolve => setTimeout(resolve, 150));
  240. write('ef');
  241. await new Promise(resolve => setTimeout(resolve, 100));
  242. return 1;
  243. `,
  244. bindings: [],
  245. })
  246. expect(result.error).toBeUndefined()
  247. expect(result.logs).toContainEqual({ source: 'stdout', text: 'abcd' })
  248. expect(result.logs.map(entry => entry.text)).not.toContain('ef')
  249. }, 15_000)
  250. })
  251. describe('WorkerCodeRuntime — hostile programs (real workers)', () => {
  252. it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => {
  253. const { runtime } = await setup()
  254. const result = await runtime.run({
  255. program: `
  256. const { parentPort } = await import('node:worker_threads');
  257. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  258. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  259. parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} });
  260. parentPort.postMessage({ type: 'junk' });
  261. return await tools.real({});
  262. `,
  263. bindings: tools({ real: async () => 'still-works' }),
  264. })
  265. expect(result.error).toBeUndefined()
  266. expect(result.value).toBe('still-works')
  267. })
  268. it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => {
  269. const { runtime } = await setup()
  270. const result = await runtime.run({
  271. program: `
  272. const { parentPort } = await import('node:worker_threads');
  273. for (const junk of [
  274. null, 42, 'junk', [],
  275. { type: 'nope' },
  276. { type: 'call' },
  277. { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} },
  278. { type: 'call', id: 1e9, global: 7, name: 'real', args: {} },
  279. { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} },
  280. { type: 'log' },
  281. { type: 'log', entry: null },
  282. { type: 'log', entry: { source: 'stdout', text: 7 } },
  283. { type: 'log', entry: { source: 'nope', text: 'x' } },
  284. { type: 'log', entry: { source: 'console', level: 'nope', text: 'x' } },
  285. { type: 'log', entry: { source: 'console', level: 7, text: 'x' } },
  286. { type: 'done', error: 5 },
  287. { type: 'done', error: { message: 5 } },
  288. ]) parentPort.postMessage(junk);
  289. return await tools.real({});
  290. `,
  291. bindings: tools({ real: async () => 'still-works' }),
  292. })
  293. expect(result.error).toBeUndefined()
  294. expect(result.value).toBe('still-works')
  295. expect(result.logs).toEqual([])
  296. })
  297. it('caps forged log floods and forged done values at the configured budgets, dropping forged extra fields', async () => {
  298. const { runtime } = await setup({ maxLogBytes: 200, maxValueBytes: 64 })
  299. const result = await runtime.run({
  300. // Forged messages bypass the worker-side LogBuffer and prepareValue
  301. // entirely — only the host-side ledger and re-cap stand between model
  302. // code and an unbounded result.
  303. program: `
  304. const { parentPort } = await import('node:worker_threads');
  305. for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', entry: { source: 'stdout', text: 'F'.repeat(100), forged: true } });
  306. parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) });
  307. for (;;) {}
  308. `,
  309. bindings: [],
  310. })
  311. expect(typeof result.value).toBe('string')
  312. const value = result.value as string
  313. expect(value.startsWith('V'.repeat(64))).toBe(true)
  314. expect(value.endsWith('… [truncated]')).toBe(true)
  315. expect(value.length).toBeLessThan(120)
  316. const marker = '[dsh-code-runtime-worker] log capture truncated at 200 bytes'
  317. const total = result.logs.reduce((sum, entry) => sum + Buffer.byteLength(entry.text, 'utf8'), 0)
  318. expect(total).toBeLessThanOrEqual(200 + Buffer.byteLength(marker, 'utf8'))
  319. expect(result.logs.at(-1)?.text).toBe(marker)
  320. expect(result.logs.every(entry => !('forged' in entry))).toBe(true)
  321. })
  322. it('accepts a forged done carrying both value and error (self-sabotage, contained)', async () => {
  323. const { runtime } = await setup()
  324. const result = await runtime.run({
  325. program: `
  326. const { parentPort } = await import('node:worker_threads');
  327. parentPort.postMessage({ type: 'done', value: 'lied', error: { message: 'fake failure' } });
  328. for (;;) {}
  329. `,
  330. bindings: [],
  331. })
  332. expect(result.value).toBe('lied')
  333. expect(result.error).toEqual({ kind: 'exception', message: 'fake failure' })
  334. })
  335. it('byte-bounds forged multibyte error text at the host', async () => {
  336. // Forged error text bypasses the worker entirely; the host bound is a
  337. // BYTE bound (two € = 6 bytes fit an 8-byte cap, a third would not).
  338. const { runtime } = await setup({ maxValueBytes: 8 })
  339. const result = await runtime.run({
  340. program: `
  341. const { parentPort } = await import('node:worker_threads');
  342. parentPort.postMessage({ type: 'done', error: { message: '€'.repeat(1000) } });
  343. for (;;) {}
  344. `,
  345. bindings: [],
  346. })
  347. expect(result.error).toEqual({ kind: 'exception', message: '€€' })
  348. })
  349. it('answers a binding whose resolution cannot be cloned with a failure reply', async () => {
  350. const { runtime } = await setup()
  351. const result = await runtime.run({
  352. program: 'try { await tools.bad({}) } catch (error) { return error.message }',
  353. bindings: tools({ bad: async () => (() => 1) }),
  354. })
  355. expect(result.value).toContain('not structured-cloneable')
  356. })
  357. it('exposes binding names that collide with Object.prototype as ordinary functions', async () => {
  358. const { runtime } = await setup()
  359. const result = await runtime.run({
  360. program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]',
  361. // Computed keys: a literal `'__proto__': …` entry would SET the record's
  362. // prototype instead of declaring a binding of that name.
  363. bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }),
  364. })
  365. expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined'])
  366. })
  367. })
  368. describe('WorkerCodeRuntime — seam misuse and lifecycle', () => {
  369. it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, console)', async () => {
  370. const { runtime } = await setup()
  371. const cases: [string, RegExp][] = [
  372. ['not valid!', /not a usable identifier/],
  373. ['await', /not a usable identifier/],
  374. ['console', /duplicate binding global/],
  375. ]
  376. for (const [global, message] of cases) {
  377. await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message)
  378. }
  379. await expect(runtime.run({
  380. program: 'return 1',
  381. bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }],
  382. })).rejects.toThrow(/duplicate binding global/)
  383. })
  384. it('rejects config values that are not positive numbers', async () => {
  385. const ctx = new Context()
  386. await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/)
  387. })
  388. it('keeps runs isolated: no state survives from one run to the next', async () => {
  389. const { runtime } = await setup()
  390. await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] })
  391. const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] })
  392. expect(second.value).toBe('undefined')
  393. })
  394. it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => {
  395. const ctx = new Context()
  396. const fiber = await ctx.plugin(WorkerCodeRuntime)
  397. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  398. const inflight: Promise<CodeRunResult> = runtime.run({ program: 'for (;;) {}', bindings: [] })
  399. // Give the worker a moment to actually start spinning.
  400. await new Promise(resolve => setTimeout(resolve, 200))
  401. await fiber.dispose()
  402. const result = await inflight
  403. expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' })
  404. await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/)
  405. }, 15_000)
  406. it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => {
  407. const ctx = new Context()
  408. const fiber = await ctx.plugin(WorkerCodeRuntime)
  409. expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime)
  410. await fiber.dispose()
  411. expect(ctx.get('codeRuntime')).toBeUndefined()
  412. })
  413. })