1
0

runtime.spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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('fails runaway log output explicitly while retaining a bounded prefix', async () => {
  202. const { runtime } = await setup({ maxOutputBytes: 300 })
  203. const result = await runtime.run({
  204. program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1',
  205. bindings: [],
  206. })
  207. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 300 bytes' })
  208. expect(result.value).toBeUndefined()
  209. expect(result.logs.length).toBeGreaterThan(0)
  210. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(300)
  211. })
  212. it('retains a fitting prefix when one oversized log is the first output', async () => {
  213. const { runtime } = await setup({ maxOutputBytes: 96 })
  214. const result = await runtime.run({
  215. program: 'console.log(`start-${`😀"\\\\\\n`.repeat(100)}`); return null',
  216. bindings: [],
  217. })
  218. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' })
  219. expect(result.logs).toHaveLength(1)
  220. expect(result.logs[0]?.startsWith('start-')).toBe(true)
  221. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')
  222. + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(96)
  223. })
  224. it('fails an oversized return value without substituting a string', async () => {
  225. const { runtime } = await setup({ maxOutputBytes: 64 })
  226. const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] })
  227. expect(result.value).toBeUndefined()
  228. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  229. })
  230. it('uses UTF-8 serialized bytes at the exact completion boundary', async () => {
  231. const exact = await setup({ maxOutputBytes: 7 })
  232. const exactResult = await exact.runtime.run({ program: 'return "€"', bindings: [] })
  233. // [] costs two bytes and JSON serialization of "€" costs five.
  234. expect(exactResult).toEqual({ logs: [], value: '€' })
  235. const over = await setup({ maxOutputBytes: 6 })
  236. const overResult = await over.runtime.run({ program: 'return "€"', bindings: [] })
  237. expect(overResult.error?.kind).toBe('output-limit')
  238. })
  239. it('accounts logs and completion in one exact combined ledger', async () => {
  240. // JSON(["abc"]) is seven bytes and JSON("xy") is four.
  241. const exact = await setup({ maxOutputBytes: 11 })
  242. expect(await exact.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] }))
  243. .toEqual({ logs: ['abc'], value: 'xy' })
  244. const over = await setup({ maxOutputBytes: 10 })
  245. const result = await over.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] })
  246. expect(result.value).toBeUndefined()
  247. expect(result.error?.kind).toBe('output-limit')
  248. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(10)
  249. })
  250. it('completes a program that awaits its write callback, capturing the chunk', async () => {
  251. // Node's write(chunk[, encoding][, callback]) contract: dropping the
  252. // callback would leave this promise pending until the wall ceiling and
  253. // misreport a completed program as a timeout.
  254. const { runtime } = await setup({ maxWallMs: 2_000 })
  255. const result = await runtime.run({
  256. program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"',
  257. bindings: [],
  258. })
  259. expect(result.error).toBeUndefined()
  260. expect(result.value).toBe('done')
  261. expect(result.logs).toContain('flushed')
  262. })
  263. it('returns a large JSON container exactly when the outer cap permits it', async () => {
  264. const { runtime } = await setup()
  265. const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] })
  266. expect(result.error).toBeUndefined()
  267. expect(result.value).toEqual(new Array(50_000).fill(7))
  268. })
  269. it('returns an exact completion at the default 64 MiB combined boundary', async () => {
  270. const { runtime } = await setup()
  271. // [] costs two bytes and the JSON string contributes two quotes, leaving
  272. // exactly this many payload bytes under the 67_108_864-byte default.
  273. const result = await runtime.run({ program: 'return "x".repeat(67_108_860)', bindings: [] })
  274. expect(result.error).toBeUndefined()
  275. expect(result.logs).toEqual([])
  276. expect(result.value).toHaveLength(67_108_860)
  277. }, 60_000)
  278. it('fails one byte over the default 64 MiB combined boundary', async () => {
  279. const { runtime } = await setup()
  280. const result = await runtime.run({ program: 'return "x".repeat(67_108_861)', bindings: [] })
  281. expect(result.value).toBeUndefined()
  282. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' })
  283. }, 60_000)
  284. it('accounts pipe writes that bypass the patched write slot in the same outer ledger', async () => {
  285. const { runtime } = await setup({ maxOutputBytes: 80 })
  286. const result = await runtime.run({
  287. // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep
  288. // writes in separate chunks and let both reach the host before settlement.
  289. program: `
  290. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  291. write('a'.repeat(20));
  292. await new Promise(resolve => setTimeout(resolve, 150));
  293. write('b'.repeat(100));
  294. await new Promise(resolve => setTimeout(resolve, 100));
  295. return 1;
  296. `,
  297. bindings: [],
  298. })
  299. expect(result.error?.kind).toBe('output-limit')
  300. expect(result.logs).toContain('a'.repeat(20))
  301. expect(result.logs[1]?.length).toBeGreaterThan(0)
  302. expect('b'.repeat(100).startsWith(result.logs[1] ?? '')).toBe(true)
  303. }, 15_000)
  304. })
  305. describe('WorkerCodeRuntime — hostile programs (real workers)', () => {
  306. it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => {
  307. const { runtime } = await setup()
  308. const result = await runtime.run({
  309. program: `
  310. const { parentPort } = await import('node:worker_threads');
  311. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  312. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  313. parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} });
  314. parentPort.postMessage({ type: 'junk' });
  315. return await tools.real({});
  316. `,
  317. bindings: tools({ real: async () => 'still-works' }),
  318. })
  319. expect(result.error).toBeUndefined()
  320. expect(result.value).toBe('still-works')
  321. })
  322. it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => {
  323. const { runtime } = await setup()
  324. const result = await runtime.run({
  325. program: `
  326. const { parentPort } = await import('node:worker_threads');
  327. for (const junk of [
  328. null, 42, 'junk', [],
  329. { type: 'nope' },
  330. { type: 'call' },
  331. { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} },
  332. { type: 'call', id: 1e9, global: 7, name: 'real', args: {} },
  333. { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} },
  334. { type: 'log' },
  335. { type: 'log', text: null },
  336. { type: 'log', text: 7 },
  337. { type: 'log', text: {} },
  338. { type: 'done', error: 5 },
  339. { type: 'done', error: { kind: 'exception', message: 5 } },
  340. { type: 'done', error: { kind: 'invented', message: 'bad kind' } },
  341. ]) parentPort.postMessage(junk);
  342. return await tools.real({});
  343. `,
  344. bindings: tools({ real: async () => 'still-works' }),
  345. })
  346. expect(result.error).toBeUndefined()
  347. expect(result.value).toBe('still-works')
  348. expect(result.logs).toEqual([])
  349. })
  350. it('fails forged log floods and forged done values through the same outer cap', async () => {
  351. const { runtime } = await setup({ maxOutputBytes: 200 })
  352. const result = await runtime.run({
  353. // Forged messages bypass the worker-side LogBuffer and completion check
  354. // entirely — only the host-side ledger and re-cap stand between model
  355. // code and an unbounded result.
  356. program: `
  357. const { parentPort } = await import('node:worker_threads');
  358. for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', text: 'F'.repeat(100), forged: true });
  359. parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) });
  360. for (;;) {}
  361. `,
  362. bindings: [],
  363. })
  364. expect(result.value).toBeUndefined()
  365. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 200 bytes' })
  366. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(200)
  367. })
  368. it('bounds one oversized forged log while retaining its fitting escaped prefix', async () => {
  369. const { runtime } = await setup({ maxOutputBytes: 96 })
  370. const result = await runtime.run({
  371. program: `
  372. const { parentPort } = await import('node:worker_threads');
  373. parentPort.postMessage({ type: 'log', text: '"'.repeat(1_000_000) });
  374. for (;;) {}
  375. `,
  376. bindings: [],
  377. })
  378. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 96 bytes' })
  379. expect(result.logs).toHaveLength(1)
  380. expect(result.logs[0]).toMatch(/^"+$/)
  381. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify('outer output exceeded 96 bytes'), 'utf8')).toBeLessThanOrEqual(96)
  382. })
  383. it('drops a malformed forged done carrying both value and error', async () => {
  384. const { runtime } = await setup()
  385. const result = await runtime.run({
  386. program: `
  387. const { parentPort } = await import('node:worker_threads');
  388. parentPort.postMessage({ type: 'done', value: 'lied', error: { kind: 'exception', message: 'fake failure' } });
  389. return 'honest';
  390. `,
  391. bindings: [],
  392. })
  393. expect(result).toEqual({ logs: [], error: { kind: 'exception', message: 'fake failure' } })
  394. })
  395. it('contains a deeply nested forged completion without overflowing the host meter', async () => {
  396. const { runtime } = await setup()
  397. const result = await runtime.run({
  398. program: `
  399. const { parentPort } = await import('node:worker_threads');
  400. let value = null;
  401. for (let depth = 0; depth < 3_000; depth++) value = [value];
  402. parentPort.postMessage({ type: 'done', value });
  403. `,
  404. bindings: [],
  405. })
  406. expect(result.error).toBeUndefined()
  407. let value = result.value
  408. let depth = 0
  409. while (Array.isArray(value)) {
  410. expect(value).toHaveLength(1)
  411. value = value[0]
  412. depth += 1
  413. }
  414. expect(depth).toBe(3_000)
  415. expect(value).toBeNull()
  416. })
  417. it('turns forged over-limit error text into output-limit at the host', async () => {
  418. const { runtime } = await setup({ maxOutputBytes: 64 })
  419. const result = await runtime.run({
  420. program: `
  421. const { parentPort } = await import('node:worker_threads');
  422. parentPort.postMessage({ type: 'done', error: { kind: 'exception', message: '€'.repeat(1000) } });
  423. for (;;) {}
  424. `,
  425. bindings: [],
  426. })
  427. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  428. })
  429. it('answers a binding whose resolution is not lossless JSON with a typed failure reply', async () => {
  430. const { runtime } = await setup()
  431. const result = await runtime.run({
  432. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  433. bindings: tools({ bad: async () => (() => 1) }),
  434. })
  435. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  436. })
  437. it('rejects lossy binding arguments in the worker before invoking the host binding', async () => {
  438. const { runtime } = await setup()
  439. let calls = 0
  440. const result = await runtime.run({
  441. program: `
  442. const decorated = [1]; Object.defineProperty(decorated, 'extra', { value: true });
  443. const values = [new Date(), decorated, () => 1];
  444. const failures = [];
  445. for (const value of values) {
  446. try { await tools.never(value) } catch (error) {
  447. failures.push({ typed: error instanceof ToolCallError, name: error.name, toolName: error.toolName, message: error.message });
  448. }
  449. }
  450. return failures;
  451. `,
  452. bindings: tools({ never: async () => { calls += 1; return null } }),
  453. })
  454. expect(calls).toBe(0)
  455. expect(result.value).toEqual(new Array(3).fill({
  456. typed: true,
  457. name: 'ToolCallError',
  458. toolName: 'never',
  459. message: 'binding arguments must be lossless JSON',
  460. }))
  461. })
  462. it('rejects forged lossy binding arguments again at the host boundary', async () => {
  463. const { runtime } = await setup()
  464. let calls = 0
  465. const result = await runtime.run({
  466. program: `
  467. const { parentPort } = await import('node:worker_threads');
  468. const forged = (id, args) => new Promise((resolve) => {
  469. const receive = (message) => {
  470. if (message?.type !== 'reply' || message.id !== id) return;
  471. parentPort.off('message', receive);
  472. resolve(message);
  473. };
  474. parentPort.on('message', receive);
  475. parentPort.postMessage({ type: 'call', id, global: 'tools', name: 'never', args });
  476. });
  477. const sparse = []; sparse.length = 1;
  478. const cycle = {}; cycle.self = cycle;
  479. return await Promise.all([
  480. forged(8001, new Date()),
  481. forged(8002, -0),
  482. forged(8003, sparse),
  483. forged(8004, cycle),
  484. ]);
  485. `,
  486. bindings: tools({ never: async () => { calls += 1; return null } }),
  487. })
  488. expect(calls).toBe(0)
  489. expect(result.value).toEqual([8001, 8002, 8003, 8004].map(id => ({
  490. type: 'reply',
  491. id,
  492. ok: false,
  493. message: 'binding arguments must be lossless JSON',
  494. })))
  495. })
  496. it('contains throwing getters while snapshotting binding resolutions', async () => {
  497. const { runtime } = await setup()
  498. const result = await runtime.run({
  499. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  500. bindings: tools({ bad: async () => Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('getter exploded') } }) }),
  501. })
  502. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  503. })
  504. it('revalidates a forged lossy completion at the host boundary', async () => {
  505. const { runtime } = await setup()
  506. const result = await runtime.run({
  507. program: `
  508. const { parentPort } = await import('node:worker_threads');
  509. parentPort.postMessage({ type: 'done', value: -0 });
  510. for (;;) {}
  511. `,
  512. bindings: [],
  513. })
  514. expect(result).toEqual({ logs: [], error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } })
  515. })
  516. it('honors a forged worker-side output-limit signal', async () => {
  517. const { runtime } = await setup()
  518. const result = await runtime.run({
  519. program: `
  520. const { parentPort } = await import('node:worker_threads');
  521. parentPort.postMessage({ type: 'output-limit' });
  522. for (;;) {}
  523. `,
  524. bindings: [],
  525. })
  526. expect(result).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' } })
  527. })
  528. it('exposes binding names that collide with Object.prototype as ordinary functions', async () => {
  529. const { runtime } = await setup()
  530. const result = await runtime.run({
  531. program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]',
  532. // Computed keys: a literal `'__proto__': …` entry would SET the record's
  533. // prototype instead of declaring a binding of that name.
  534. bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }),
  535. })
  536. expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined'])
  537. })
  538. })
  539. describe('WorkerCodeRuntime — seam misuse and lifecycle', () => {
  540. it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, reserved injected globals)', async () => {
  541. const { runtime } = await setup()
  542. const cases: [string, RegExp][] = [
  543. ['not valid!', /not a usable identifier/],
  544. ['await', /not a usable identifier/],
  545. ['console', /duplicate binding global/],
  546. ['ToolCallError', /duplicate binding global/],
  547. ]
  548. for (const [global, message] of cases) {
  549. await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message)
  550. }
  551. await expect(runtime.run({
  552. program: 'return 1',
  553. bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }],
  554. })).rejects.toThrow(/duplicate binding global/)
  555. })
  556. it('rejects config values that are not positive numbers', async () => {
  557. const ctx = new Context()
  558. await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/)
  559. })
  560. it('requires maxOutputBytes to fit the smallest outer failure envelope', async () => {
  561. const ctx = new Context()
  562. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 3 })).rejects.toThrow(/safe integer of at least 4/)
  563. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 4.5 })).rejects.toThrow(/safe integer of at least 4/)
  564. })
  565. it('keeps runs isolated: no state survives from one run to the next', async () => {
  566. const { runtime } = await setup()
  567. await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] })
  568. const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] })
  569. expect(second.value).toBe('undefined')
  570. })
  571. it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => {
  572. const ctx = new Context()
  573. const fiber = await ctx.plugin(WorkerCodeRuntime)
  574. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  575. const inflight: Promise<CodeRunResult> = runtime.run({ program: 'for (;;) {}', bindings: [] })
  576. // Give the worker a moment to actually start spinning.
  577. await new Promise(resolve => setTimeout(resolve, 200))
  578. await fiber.dispose()
  579. const result = await inflight
  580. expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' })
  581. await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/)
  582. }, 15_000)
  583. it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => {
  584. const ctx = new Context()
  585. const fiber = await ctx.plugin(WorkerCodeRuntime)
  586. expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime)
  587. await fiber.dispose()
  588. expect(ctx.get('codeRuntime')).toBeUndefined()
  589. })
  590. })