runtime.spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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 { CodeBindingFunction, CodeBindingNamespace, 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>>): CodeBindingNamespace[] {
  19. return [{ global: 'tools', functions: functions as Record<string, CodeBindingFunction> }]
  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 = { isTyped: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message } }
  52. let caughtRaw = {};
  53. try { await tools.failRaw({}) } catch (error) { caughtRaw = { name: error.name, toolName: error.toolName, message: 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({
  65. first: { echoed: { n: 1 } },
  66. caught: { isTyped: true, name: 'ToolCallError', toolName: 'fail', message: 'nope' },
  67. caughtRaw: { name: 'ToolCallError', toolName: 'failRaw', message: 'raw-nope' },
  68. })
  69. expect(calls).toEqual([{ n: 1 }])
  70. })
  71. it('reports non-erasable syntax as an exception without spawning a worker', async () => {
  72. const { runtime } = await setup()
  73. const result = await runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] })
  74. expect(result.error?.kind).toBe('exception')
  75. expect(result.error?.message).toMatch(/enum|strip/i)
  76. })
  77. it('reports a runtime throw as an exception with the message', async () => {
  78. const { runtime } = await setup()
  79. const result = await runtime.run({ program: 'throw new Error("kaboom")', bindings: [] })
  80. expect(result.error?.kind).toBe('exception')
  81. expect(result.error?.message).toContain('kaboom')
  82. })
  83. it('gives the program an EMPTY environment', async () => {
  84. const { runtime } = await setup()
  85. const result = await runtime.run({ program: 'return JSON.stringify(process.env)', bindings: [] })
  86. expect(result.value).toBe('{}')
  87. })
  88. it('rejects a non-lossless completion instead of replacing it with rendered text', async () => {
  89. const { runtime } = await setup()
  90. const result = await runtime.run({ program: 'return { f: () => 1 }', bindings: [] })
  91. expect(result.value).toBeUndefined()
  92. expect(result.error).toEqual({ kind: 'invalid-output', message: 'program completion must be lossless JSON' })
  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).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. // Keep the binding delay above the compute allowance while leaving enough
  125. // headroom for worker bootstrap on loaded CI hosts.
  126. const { runtime } = await setup({ computeMs: 1_000, maxWallMs: 30_000 })
  127. const result = await runtime.run({
  128. program: 'return await tools.slow({})',
  129. bindings: tools({ slow: () => new Promise(resolve => setTimeout(() => { resolve('slow-done') }, 1_500)) }),
  130. })
  131. expect(result.error).toBeUndefined()
  132. expect(result.value).toBe('slow-done')
  133. }, 15_000)
  134. it('ends an idle-forever run at the wall-clock ceiling', async () => {
  135. const { runtime } = await setup({ computeMs: 30_000, maxWallMs: 400 })
  136. const result = await runtime.run({
  137. program: 'await tools.never({}); return 1',
  138. bindings: tools({ never: () => new Promise(() => {}) }),
  139. })
  140. expect(result.error?.kind).toBe('timeout')
  141. expect(result.error?.message).toContain('wall-clock ceiling')
  142. }, 15_000)
  143. it('reports an abort mid-run and stops the worker', async () => {
  144. const { runtime } = await setup()
  145. const controller = new AbortController()
  146. setTimeout(() => { controller.abort('user-cancel') }, 150)
  147. const result = await runtime.run({ program: 'for (;;) {}', bindings: [], signal: controller.signal })
  148. expect(result.error).toEqual({ kind: 'abort', message: 'user-cancel' })
  149. }, 15_000)
  150. it('reports a pre-aborted signal without spawning', async () => {
  151. const { runtime } = await setup()
  152. const controller = new AbortController()
  153. controller.abort('too-late')
  154. const result = await runtime.run({ program: 'return 1', bindings: [], signal: controller.signal })
  155. expect(result.error).toEqual({ kind: 'abort', message: 'too-late' })
  156. })
  157. it('applies the outer-output cap to failures before worker startup', async () => {
  158. const capped = await setup({ maxOutputBytes: 64 })
  159. const controller = new AbortController()
  160. controller.abort('A'.repeat(1_000))
  161. const aborted = await capped.runtime.run({ program: 'return 1', bindings: [], signal: controller.signal })
  162. expect(aborted).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 64 bytes' } })
  163. const minimal = await setup({ maxOutputBytes: 4 })
  164. const invalid = await minimal.runtime.run({ program: 'enum E { A }\nreturn 1', bindings: [] })
  165. expect(invalid.error?.kind).toBe('output-limit')
  166. expect(Buffer.byteLength(JSON.stringify(invalid.logs), 'utf8') + Buffer.byteLength(JSON.stringify(invalid.error?.message), 'utf8')).toBeLessThanOrEqual(4)
  167. })
  168. it('drops a binding resolution that lands after the run settled', async () => {
  169. const { runtime } = await setup()
  170. const controller = new AbortController()
  171. let replyDelivered!: Promise<void>
  172. const result = await runtime.run({
  173. program: 'void tools.late({}); for (;;) {}',
  174. bindings: tools({
  175. // Anchored on invocation: abort 100ms after the call reaches the
  176. // host, resolve 400ms after — by then the run has settled, so the
  177. // resolution's reply hits the post-settlement drop.
  178. late: () => new Promise((resolve) => {
  179. setTimeout(() => { controller.abort('cancel-now') }, 100)
  180. replyDelivered = new Promise(done => setTimeout(() => { resolve('too-late'); done() }, 400))
  181. }),
  182. }),
  183. signal: controller.signal,
  184. })
  185. expect(result.error).toEqual({ kind: 'abort', message: 'cancel-now' })
  186. // Let the late resolution actually fire so its reply executes instead of
  187. // being cancelled with the test.
  188. await replyDelivered
  189. }, 15_000)
  190. it('contains an OOM under resourceLimits as worker-exit, host process healthy', async () => {
  191. const { runtime } = await setup({ maxOldGenerationSizeMb: 32 })
  192. const result = await runtime.run({
  193. program: 'const hog = []; for (;;) hog.push(new Array(1e6).fill(1));',
  194. bindings: [],
  195. })
  196. expect(result.error?.kind).toBe('worker-exit')
  197. // And the host is fine: run something else.
  198. const after = await runtime.run({ program: 'return "alive"', bindings: [] })
  199. expect(after.value).toBe('alive')
  200. }, 30_000)
  201. it('reports a worker that exits before publishing a completion', async () => {
  202. const { runtime } = await setup()
  203. const result = await runtime.run({ program: 'process.exit(7)', bindings: [] })
  204. expect(result).toEqual({
  205. logs: [],
  206. error: { kind: 'worker-exit', message: 'worker exited with code 7 before completing' },
  207. })
  208. })
  209. it('fails runaway log output explicitly while retaining a bounded prefix', async () => {
  210. const { runtime } = await setup({ maxOutputBytes: 300 })
  211. const result = await runtime.run({
  212. program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1',
  213. bindings: [],
  214. })
  215. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 300 bytes' })
  216. expect(result.value).toBeUndefined()
  217. expect(result.logs.length).toBeGreaterThan(0)
  218. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(300)
  219. })
  220. it('retains a fitting prefix when one oversized log is the first output', async () => {
  221. const { runtime } = await setup({ maxOutputBytes: 96 })
  222. const result = await runtime.run({
  223. program: 'console.log(`start-${`😀"\\\\\\n`.repeat(100)}`); return null',
  224. bindings: [],
  225. })
  226. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' })
  227. expect(result.logs).toHaveLength(1)
  228. expect(result.logs[0]?.startsWith('start-')).toBe(true)
  229. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')
  230. + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(96)
  231. })
  232. it('fails an oversized return value without substituting a string', async () => {
  233. const { runtime } = await setup({ maxOutputBytes: 64 })
  234. const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] })
  235. expect(result.value).toBeUndefined()
  236. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  237. })
  238. it('uses UTF-8 serialized bytes at the exact completion boundary', async () => {
  239. const exact = await setup({ maxOutputBytes: 7 })
  240. const exactResult = await exact.runtime.run({ program: 'return "€"', bindings: [] })
  241. // [] costs two bytes and JSON serialization of "€" costs five.
  242. expect(exactResult).toEqual({ logs: [], value: '€' })
  243. const over = await setup({ maxOutputBytes: 6 })
  244. const overResult = await over.runtime.run({ program: 'return "€"', bindings: [] })
  245. expect(overResult.error?.kind).toBe('output-limit')
  246. })
  247. it('accounts logs and completion in one exact combined ledger', async () => {
  248. // JSON(["abc"]) is seven bytes and JSON("xy") is four.
  249. const exact = await setup({ maxOutputBytes: 11 })
  250. expect(await exact.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] }))
  251. .toEqual({ logs: ['abc'], value: 'xy' })
  252. const over = await setup({ maxOutputBytes: 10 })
  253. const result = await over.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] })
  254. expect(result.value).toBeUndefined()
  255. expect(result.error?.kind).toBe('output-limit')
  256. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(10)
  257. })
  258. it('completes a program that awaits its write callback, capturing the chunk', async () => {
  259. // Node's write(chunk[, encoding][, callback]) contract: dropping the
  260. // callback would leave this promise pending until the wall ceiling and
  261. // misreport a completed program as a timeout.
  262. const { runtime } = await setup({ maxWallMs: 2_000 })
  263. const result = await runtime.run({
  264. program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"',
  265. bindings: [],
  266. })
  267. expect(result.error).toBeUndefined()
  268. expect(result.value).toBe('done')
  269. expect(result.logs).toContain('flushed')
  270. })
  271. it('returns a large JSON container exactly when the outer cap permits it', async () => {
  272. const { runtime } = await setup()
  273. const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] })
  274. expect(result.error).toBeUndefined()
  275. expect(result.value).toEqual(new Array(50_000).fill(7))
  276. })
  277. it('returns an exact completion at the default 64 MiB combined boundary', async () => {
  278. const { runtime } = await setup()
  279. // [] costs two bytes and the JSON string contributes two quotes, leaving
  280. // exactly this many payload bytes under the 67_108_864-byte default.
  281. const result = await runtime.run({ program: 'return "x".repeat(67_108_860)', bindings: [] })
  282. expect(result.error).toBeUndefined()
  283. expect(result.logs).toEqual([])
  284. expect(result.value).toHaveLength(67_108_860)
  285. }, 60_000)
  286. it('fails one byte over the default 64 MiB combined boundary', async () => {
  287. const { runtime } = await setup()
  288. const result = await runtime.run({ program: 'return "x".repeat(67_108_861)', bindings: [] })
  289. expect(result.value).toBeUndefined()
  290. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' })
  291. }, 60_000)
  292. it('accounts pipe writes that bypass the patched write slot in the same outer ledger', async () => {
  293. const { runtime } = await setup({ maxOutputBytes: 80 })
  294. const result = await runtime.run({
  295. // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep
  296. // writes in separate chunks and let both reach the host before settlement.
  297. program: `
  298. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  299. write('a'.repeat(20));
  300. await new Promise(resolve => setTimeout(resolve, 150));
  301. write('b'.repeat(100));
  302. await new Promise(resolve => setTimeout(resolve, 100));
  303. return 1;
  304. `,
  305. bindings: [],
  306. })
  307. expect(result.error?.kind).toBe('output-limit')
  308. expect(result.logs).toContain('a'.repeat(20))
  309. expect(result.logs[1]?.length).toBeGreaterThan(0)
  310. expect('b'.repeat(100).startsWith(result.logs[1] ?? '')).toBe(true)
  311. }, 15_000)
  312. it('drains pipe output queued before terminal worker teardown completes', async () => {
  313. const { runtime } = await setup({ maxOutputBytes: 200_000 })
  314. const payload = `late-pipe-${'x'.repeat(100_000)}`
  315. const result = await runtime.run({
  316. program: `
  317. const { parentPort } = await import('node:worker_threads');
  318. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  319. write('late-pipe-' + 'x'.repeat(100_000));
  320. parentPort.postMessage({ type: 'done', value: 'done' });
  321. for (;;) {}
  322. `,
  323. bindings: [],
  324. })
  325. expect(result.error).toBeUndefined()
  326. expect(result.value).toBe('done')
  327. expect(result.logs.join('') === payload).toBe(true)
  328. }, 15_000)
  329. })
  330. describe('WorkerCodeRuntime — hostile programs (real workers)', () => {
  331. it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => {
  332. const { runtime } = await setup()
  333. const result = await runtime.run({
  334. program: `
  335. const { parentPort } = await import('node:worker_threads');
  336. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  337. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  338. parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} });
  339. parentPort.postMessage({ type: 'junk' });
  340. return await tools.real({});
  341. `,
  342. bindings: tools({ real: async () => 'still-works' }),
  343. })
  344. expect(result.error).toBeUndefined()
  345. expect(result.value).toBe('still-works')
  346. })
  347. it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => {
  348. const { runtime } = await setup()
  349. const result = await runtime.run({
  350. program: `
  351. const { parentPort } = await import('node:worker_threads');
  352. for (const junk of [
  353. null, 42, 'junk', [],
  354. { type: 'nope' },
  355. { type: 'call' },
  356. { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} },
  357. { type: 'call', id: 1e9, global: 7, name: 'real', args: {} },
  358. { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} },
  359. { type: 'log' },
  360. { type: 'log', text: null },
  361. { type: 'log', text: 7 },
  362. { type: 'log', text: {} },
  363. { type: 'done', error: 5 },
  364. { type: 'done', error: { kind: 'exception', message: 5 } },
  365. { type: 'done', error: { kind: 'invented', message: 'bad kind' } },
  366. ]) parentPort.postMessage(junk);
  367. return await tools.real({});
  368. `,
  369. bindings: tools({ real: async () => 'still-works' }),
  370. })
  371. expect(result.error).toBeUndefined()
  372. expect(result.value).toBe('still-works')
  373. expect(result.logs).toEqual([])
  374. })
  375. it('fails forged log floods and forged done values through the same outer cap', async () => {
  376. const { runtime } = await setup({ maxOutputBytes: 200 })
  377. const result = await runtime.run({
  378. // Forged messages bypass the worker-side LogBuffer and completion check
  379. // entirely — only the host-side ledger and re-cap stand between model
  380. // code and an unbounded result.
  381. program: `
  382. const { parentPort } = await import('node:worker_threads');
  383. for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', text: 'F'.repeat(100), forged: true });
  384. parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) });
  385. for (;;) {}
  386. `,
  387. bindings: [],
  388. })
  389. expect(result.value).toBeUndefined()
  390. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 200 bytes' })
  391. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(200)
  392. })
  393. it('bounds one oversized forged log while retaining its fitting escaped prefix', async () => {
  394. const { runtime } = await setup({ maxOutputBytes: 96 })
  395. const result = await runtime.run({
  396. program: `
  397. const { parentPort } = await import('node:worker_threads');
  398. parentPort.postMessage({ type: 'log', text: '"'.repeat(1_000_000) });
  399. for (;;) {}
  400. `,
  401. bindings: [],
  402. })
  403. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' })
  404. expect(result.logs).toHaveLength(1)
  405. expect(result.logs[0]).toMatch(/^"+$/)
  406. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify('outer output exceeded 96 bytes'), 'utf8')).toBeLessThanOrEqual(96)
  407. })
  408. it('drops a malformed forged done carrying both value and error', async () => {
  409. const { runtime } = await setup()
  410. const result = await runtime.run({
  411. program: `
  412. const { parentPort } = await import('node:worker_threads');
  413. parentPort.postMessage({ type: 'done', value: 'lied', error: { kind: 'exception', message: 'fake failure' } });
  414. return 'honest';
  415. `,
  416. bindings: [],
  417. })
  418. expect(result).toEqual({ logs: [], error: { kind: 'exception', message: 'fake failure' } })
  419. })
  420. it('contains a deeply nested forged completion without overflowing the host meter', async () => {
  421. const { runtime } = await setup()
  422. const result = await runtime.run({
  423. program: `
  424. const { parentPort } = await import('node:worker_threads');
  425. let value = null;
  426. for (let depth = 0; depth < 3_000; depth++) value = [value];
  427. parentPort.postMessage({ type: 'done', value });
  428. `,
  429. bindings: [],
  430. })
  431. expect(result.error).toBeUndefined()
  432. let value = result.value
  433. let depth = 0
  434. while (Array.isArray(value)) {
  435. expect(value).toHaveLength(1)
  436. value = value[0]
  437. depth += 1
  438. }
  439. expect(depth).toBe(3_000)
  440. expect(value).toBeNull()
  441. })
  442. it('turns forged over-limit error text into output-limit at the host', async () => {
  443. const { runtime } = await setup({ maxOutputBytes: 64 })
  444. const result = await runtime.run({
  445. program: `
  446. const { parentPort } = await import('node:worker_threads');
  447. parentPort.postMessage({ type: 'done', error: { kind: 'exception', message: '€'.repeat(1000) } });
  448. for (;;) {}
  449. `,
  450. bindings: [],
  451. })
  452. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  453. })
  454. it('answers a binding whose resolution is not lossless JSON with a typed failure reply', async () => {
  455. const { runtime } = await setup()
  456. const result = await runtime.run({
  457. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  458. bindings: tools({ bad: async () => (() => 1) }),
  459. })
  460. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  461. })
  462. it('rejects lossy binding arguments in the worker before invoking the host binding', async () => {
  463. const { runtime } = await setup()
  464. let calls = 0
  465. const result = await runtime.run({
  466. program: `
  467. const decorated = [1]; Object.defineProperty(decorated, 'extra', { value: true });
  468. const values = [new Date(), decorated, () => 1];
  469. const failures = [];
  470. for (const value of values) {
  471. try { await tools.never(value) } catch (error) {
  472. failures.push({ typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message });
  473. }
  474. }
  475. return failures;
  476. `,
  477. bindings: tools({ never: async () => { calls += 1; return null } }),
  478. })
  479. expect(calls).toBe(0)
  480. expect(result.value).toEqual(new Array(3).fill({
  481. typed: true,
  482. name: 'ToolCallError',
  483. toolName: 'never',
  484. message: 'binding arguments must be lossless JSON',
  485. }))
  486. })
  487. it('rejects forged lossy binding arguments again at the host boundary', async () => {
  488. const { runtime } = await setup()
  489. let calls = 0
  490. const result = await runtime.run({
  491. program: `
  492. const { parentPort } = await import('node:worker_threads');
  493. const forged = (id, args) => new Promise((resolve) => {
  494. const receive = (message) => {
  495. if (message?.type !== 'reply' || message.id !== id) return;
  496. parentPort.off('message', receive);
  497. resolve(message);
  498. };
  499. parentPort.on('message', receive);
  500. parentPort.postMessage({ type: 'call', id, global: 'tools', name: 'never', args });
  501. });
  502. const sparse = []; sparse.length = 1;
  503. const cycle = {}; cycle.self = cycle;
  504. return await Promise.all([
  505. forged(8001, new Date()),
  506. forged(8002, -0),
  507. forged(8003, sparse),
  508. forged(8004, cycle),
  509. ]);
  510. `,
  511. bindings: tools({ never: async () => { calls += 1; return null } }),
  512. })
  513. expect(calls).toBe(0)
  514. expect(result.value).toEqual([8001, 8002, 8003, 8004].map(id => ({
  515. type: 'reply',
  516. id,
  517. ok: false,
  518. message: 'binding arguments must be lossless JSON',
  519. })))
  520. })
  521. it('contains throwing getters while snapshotting binding resolutions', async () => {
  522. const { runtime } = await setup()
  523. const result = await runtime.run({
  524. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  525. bindings: tools({ bad: async () => Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('getter exploded') } }) }),
  526. })
  527. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  528. })
  529. it('revalidates a forged lossy completion at the host boundary', async () => {
  530. const { runtime } = await setup()
  531. const result = await runtime.run({
  532. program: `
  533. const { parentPort } = await import('node:worker_threads');
  534. parentPort.postMessage({ type: 'done', value: -0 });
  535. for (;;) {}
  536. `,
  537. bindings: [],
  538. })
  539. expect(result).toEqual({ logs: [], error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } })
  540. })
  541. it('honors a forged worker-side output-limit signal', async () => {
  542. const { runtime } = await setup()
  543. const result = await runtime.run({
  544. program: `
  545. const { parentPort } = await import('node:worker_threads');
  546. parentPort.postMessage({ type: 'output-limit' });
  547. for (;;) {}
  548. `,
  549. bindings: [],
  550. })
  551. expect(result).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' } })
  552. })
  553. it('exposes binding names that collide with Object.prototype as ordinary functions', async () => {
  554. const { runtime } = await setup()
  555. const result = await runtime.run({
  556. program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]',
  557. // Computed keys: a literal `'__proto__': …` entry would SET the record's
  558. // prototype instead of declaring a binding of that name.
  559. bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }),
  560. })
  561. expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined'])
  562. })
  563. })
  564. describe('WorkerCodeRuntime — seam misuse and lifecycle', () => {
  565. it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, reserved injected globals)', async () => {
  566. const { runtime } = await setup()
  567. const cases: [string, RegExp][] = [
  568. ['not valid!', /not a usable identifier/],
  569. ['await', /not a usable identifier/],
  570. ['console', /duplicate binding global/],
  571. ['ToolCallError', /duplicate binding global/],
  572. ]
  573. for (const [global, message] of cases) {
  574. await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message)
  575. }
  576. await expect(runtime.run({
  577. program: 'return 1',
  578. bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }],
  579. })).rejects.toThrow(/duplicate binding global/)
  580. })
  581. it('rejects config values that are not positive numbers', async () => {
  582. const ctx = new Context()
  583. await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/)
  584. })
  585. it('requires maxOutputBytes to fit the smallest outer failure envelope', async () => {
  586. const ctx = new Context()
  587. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 3 })).rejects.toThrow(/safe integer of at least 4/)
  588. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 4.5 })).rejects.toThrow(/safe integer of at least 4/)
  589. })
  590. it('keeps runs isolated: no state survives from one run to the next', async () => {
  591. const { runtime } = await setup()
  592. await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] })
  593. const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] })
  594. expect(second.value).toBe('undefined')
  595. })
  596. it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => {
  597. const ctx = new Context()
  598. const fiber = await ctx.plugin(WorkerCodeRuntime)
  599. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  600. const inflight: Promise<CodeRunResult> = runtime.run({ program: 'for (;;) {}', bindings: [] })
  601. // Give the worker a moment to actually start spinning.
  602. await new Promise(resolve => setTimeout(resolve, 200))
  603. await fiber.dispose()
  604. const result = await inflight
  605. expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' })
  606. await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/)
  607. }, 15_000)
  608. it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => {
  609. const ctx = new Context()
  610. const fiber = await ctx.plugin(WorkerCodeRuntime)
  611. expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime)
  612. await fiber.dispose()
  613. expect(ctx.get('codeRuntime')).toBeUndefined()
  614. })
  615. })