runtime.spec.ts 20 KB

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