1
0

runtime.spec.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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('drops a binding resolution that lands after the run settled', async () => {
  158. const { runtime } = await setup()
  159. const controller = new AbortController()
  160. let replyDelivered!: Promise<void>
  161. const result = await runtime.run({
  162. program: 'void tools.late({}); for (;;) {}',
  163. bindings: tools({
  164. // Anchored on invocation: abort 100ms after the call reaches the
  165. // host, resolve 400ms after — by then the run has settled, so the
  166. // resolution's reply hits the post-settlement drop.
  167. late: () => new Promise((resolve) => {
  168. setTimeout(() => { controller.abort('cancel-now') }, 100)
  169. replyDelivered = new Promise(done => setTimeout(() => { resolve('too-late'); done() }, 400))
  170. }),
  171. }),
  172. signal: controller.signal,
  173. })
  174. expect(result.error).toEqual({ kind: 'abort', message: 'cancel-now' })
  175. // Let the late resolution actually fire so its reply executes instead of
  176. // being cancelled with the test.
  177. await replyDelivered
  178. }, 15_000)
  179. it('contains an OOM under resourceLimits as worker-exit, host process healthy', async () => {
  180. const { runtime } = await setup({ maxOldGenerationSizeMb: 32 })
  181. const result = await runtime.run({
  182. program: 'const hog = []; for (;;) hog.push(new Array(1e6).fill(1));',
  183. bindings: [],
  184. })
  185. expect(result.error?.kind).toBe('worker-exit')
  186. // And the host is fine: run something else.
  187. const after = await runtime.run({ program: 'return "alive"', bindings: [] })
  188. expect(after.value).toBe('alive')
  189. }, 30_000)
  190. it('fails runaway log output explicitly while retaining a bounded prefix', async () => {
  191. const { runtime } = await setup({ maxOutputBytes: 300 })
  192. const result = await runtime.run({
  193. program: 'for (let i = 0; i < 1000; i++) console.log("spam line", i); return 1',
  194. bindings: [],
  195. })
  196. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 300 bytes' })
  197. expect(result.value).toBeUndefined()
  198. expect(result.logs.length).toBeGreaterThan(0)
  199. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(300)
  200. })
  201. it('fails an oversized return value without substituting a string', async () => {
  202. const { runtime } = await setup({ maxOutputBytes: 64 })
  203. const result = await runtime.run({ program: 'return "y".repeat(10_000)', bindings: [] })
  204. expect(result.value).toBeUndefined()
  205. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  206. })
  207. it('uses UTF-8 serialized bytes at the exact completion boundary', async () => {
  208. const exact = await setup({ maxOutputBytes: 7 })
  209. const exactResult = await exact.runtime.run({ program: 'return "€"', bindings: [] })
  210. // [] costs two bytes and JSON serialization of "€" costs five.
  211. expect(exactResult).toEqual({ logs: [], value: '€' })
  212. const over = await setup({ maxOutputBytes: 6 })
  213. const overResult = await over.runtime.run({ program: 'return "€"', bindings: [] })
  214. expect(overResult.error?.kind).toBe('output-limit')
  215. })
  216. it('accounts logs and completion in one exact combined ledger', async () => {
  217. // JSON(["abc"]) is seven bytes and JSON("xy") is four.
  218. const exact = await setup({ maxOutputBytes: 11 })
  219. expect(await exact.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] }))
  220. .toEqual({ logs: ['abc'], value: 'xy' })
  221. const over = await setup({ maxOutputBytes: 10 })
  222. const result = await over.runtime.run({ program: 'console.log("abc"); return "xy"', bindings: [] })
  223. expect(result.value).toBeUndefined()
  224. expect(result.error?.kind).toBe('output-limit')
  225. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8') + Buffer.byteLength(JSON.stringify(result.error?.message), 'utf8')).toBeLessThanOrEqual(10)
  226. })
  227. it('completes a program that awaits its write callback, capturing the chunk', async () => {
  228. // Node's write(chunk[, encoding][, callback]) contract: dropping the
  229. // callback would leave this promise pending until the wall ceiling and
  230. // misreport a completed program as a timeout.
  231. const { runtime } = await setup({ maxWallMs: 2_000 })
  232. const result = await runtime.run({
  233. program: 'await new Promise(resolve => process.stdout.write("flushed", resolve)); return "done"',
  234. bindings: [],
  235. })
  236. expect(result.error).toBeUndefined()
  237. expect(result.value).toBe('done')
  238. expect(result.logs).toContain('flushed')
  239. })
  240. it('returns a large JSON container exactly when the outer cap permits it', async () => {
  241. const { runtime } = await setup()
  242. const result = await runtime.run({ program: 'return new Array(50_000).fill(7)', bindings: [] })
  243. expect(result.error).toBeUndefined()
  244. expect(result.value).toEqual(new Array(50_000).fill(7))
  245. })
  246. it('returns an exact completion at the default 64 MiB combined boundary', async () => {
  247. const { runtime } = await setup()
  248. // [] costs two bytes and the JSON string contributes two quotes, leaving
  249. // exactly this many payload bytes under the 67_108_864-byte default.
  250. const result = await runtime.run({ program: 'return "x".repeat(67_108_860)', bindings: [] })
  251. expect(result.error).toBeUndefined()
  252. expect(result.logs).toEqual([])
  253. expect(result.value).toHaveLength(67_108_860)
  254. }, 60_000)
  255. it('fails one byte over the default 64 MiB combined boundary', async () => {
  256. const { runtime } = await setup()
  257. const result = await runtime.run({ program: 'return "x".repeat(67_108_861)', bindings: [] })
  258. expect(result.value).toBeUndefined()
  259. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' })
  260. }, 60_000)
  261. it('accounts pipe writes that bypass the patched write slot in the same outer ledger', async () => {
  262. const { runtime } = await setup({ maxOutputBytes: 80 })
  263. const result = await runtime.run({
  264. // The prototype write bypasses the patched instance and reaches the real pipe. Pauses keep
  265. // writes in separate chunks and let both reach the host before settlement.
  266. program: `
  267. const write = (text) => Object.getPrototypeOf(process.stdout).write.call(process.stdout, text);
  268. write('a'.repeat(20));
  269. await new Promise(resolve => setTimeout(resolve, 150));
  270. write('b'.repeat(100));
  271. await new Promise(resolve => setTimeout(resolve, 100));
  272. return 1;
  273. `,
  274. bindings: [],
  275. })
  276. expect(result.error?.kind).toBe('output-limit')
  277. expect(result.logs).toContain('a'.repeat(20))
  278. expect(result.logs).not.toContain('b'.repeat(100))
  279. }, 15_000)
  280. })
  281. describe('WorkerCodeRuntime — hostile programs (real workers)', () => {
  282. it('survives forged port traffic: unknown binding names, duplicate ids, junk shapes', async () => {
  283. const { runtime } = await setup()
  284. const result = await runtime.run({
  285. program: `
  286. const { parentPort } = await import('node:worker_threads');
  287. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  288. parentPort.postMessage({ type: 'call', id: 7777, global: 'tools', name: 'missing', args: {} });
  289. parentPort.postMessage({ type: 'call', id: 7778, global: 'tools', name: 'constructor', args: {} });
  290. parentPort.postMessage({ type: '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. })
  298. it('survives arbitrary junk on the port: non-objects, junk types, malformed calls, logs, and dones', async () => {
  299. const { runtime } = await setup()
  300. const result = await runtime.run({
  301. program: `
  302. const { parentPort } = await import('node:worker_threads');
  303. for (const junk of [
  304. null, 42, 'junk', [],
  305. { type: 'nope' },
  306. { type: 'call' },
  307. { type: 'call', id: 'x', global: 'tools', name: 'real', args: {} },
  308. { type: 'call', id: 1e9, global: 7, name: 'real', args: {} },
  309. { type: 'call', id: 1e9, global: 'tools', name: 7, args: {} },
  310. { type: 'log' },
  311. { type: 'log', text: null },
  312. { type: 'log', text: 7 },
  313. { type: 'log', text: {} },
  314. { type: 'done', error: 5 },
  315. { type: 'done', error: { kind: 'exception', message: 5 } },
  316. { type: 'done', error: { kind: 'invented', message: 'bad kind' } },
  317. ]) parentPort.postMessage(junk);
  318. return await tools.real({});
  319. `,
  320. bindings: tools({ real: async () => 'still-works' }),
  321. })
  322. expect(result.error).toBeUndefined()
  323. expect(result.value).toBe('still-works')
  324. expect(result.logs).toEqual([])
  325. })
  326. it('fails forged log floods and forged done values through the same outer cap', async () => {
  327. const { runtime } = await setup({ maxOutputBytes: 200 })
  328. const result = await runtime.run({
  329. // Forged messages bypass the worker-side LogBuffer and completion check
  330. // entirely — only the host-side ledger and re-cap stand between model
  331. // code and an unbounded result.
  332. program: `
  333. const { parentPort } = await import('node:worker_threads');
  334. for (let i = 0; i < 50; i++) parentPort.postMessage({ type: 'log', text: 'F'.repeat(100), forged: true });
  335. parentPort.postMessage({ type: 'done', value: 'V'.repeat(100000) });
  336. for (;;) {}
  337. `,
  338. bindings: [],
  339. })
  340. expect(result.value).toBeUndefined()
  341. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 200 bytes' })
  342. expect(Buffer.byteLength(JSON.stringify(result.logs), 'utf8')).toBeLessThan(200)
  343. })
  344. it('drops a malformed forged done carrying both value and error', async () => {
  345. const { runtime } = await setup()
  346. const result = await runtime.run({
  347. program: `
  348. const { parentPort } = await import('node:worker_threads');
  349. parentPort.postMessage({ type: 'done', value: 'lied', error: { kind: 'exception', message: 'fake failure' } });
  350. return 'honest';
  351. `,
  352. bindings: [],
  353. })
  354. expect(result).toEqual({ logs: [], error: { kind: 'exception', message: 'fake failure' } })
  355. })
  356. it('turns forged over-limit error text into output-limit at the host', async () => {
  357. const { runtime } = await setup({ maxOutputBytes: 64 })
  358. const result = await runtime.run({
  359. program: `
  360. const { parentPort } = await import('node:worker_threads');
  361. parentPort.postMessage({ type: 'done', error: { kind: 'exception', message: '€'.repeat(1000) } });
  362. for (;;) {}
  363. `,
  364. bindings: [],
  365. })
  366. expect(result.error).toEqual({ kind: 'output-limit', message: 'outer output exceeded 64 bytes' })
  367. })
  368. it('answers a binding whose resolution is not lossless JSON with a typed failure reply', async () => {
  369. const { runtime } = await setup()
  370. const result = await runtime.run({
  371. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  372. bindings: tools({ bad: async () => (() => 1) }),
  373. })
  374. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  375. })
  376. it('contains throwing getters while snapshotting binding resolutions', async () => {
  377. const { runtime } = await setup()
  378. const result = await runtime.run({
  379. program: 'try { await tools.bad({}) } catch (error) { return { name: error.name, toolName: error.toolName, message: error.message } }',
  380. bindings: tools({ bad: async () => Object.defineProperty({}, 'bad', { enumerable: true, get() { throw new Error('getter exploded') } }) }),
  381. })
  382. expect(result.value).toEqual({ name: 'ToolCallError', toolName: 'bad', message: 'binding resolution must be lossless JSON' })
  383. })
  384. it('revalidates a forged lossy completion at the host boundary', async () => {
  385. const { runtime } = await setup()
  386. const result = await runtime.run({
  387. program: `
  388. const { parentPort } = await import('node:worker_threads');
  389. parentPort.postMessage({ type: 'done', value: -0 });
  390. for (;;) {}
  391. `,
  392. bindings: [],
  393. })
  394. expect(result).toEqual({ logs: [], error: { kind: 'invalid-output', message: 'program completion must be lossless JSON' } })
  395. })
  396. it('honors a forged worker-side output-limit signal', async () => {
  397. const { runtime } = await setup()
  398. const result = await runtime.run({
  399. program: `
  400. const { parentPort } = await import('node:worker_threads');
  401. parentPort.postMessage({ type: 'output-limit' });
  402. for (;;) {}
  403. `,
  404. bindings: [],
  405. })
  406. expect(result).toEqual({ logs: [], error: { kind: 'output-limit', message: 'outer output exceeded 67108864 bytes' } })
  407. })
  408. it('exposes binding names that collide with Object.prototype as ordinary functions', async () => {
  409. const { runtime } = await setup()
  410. const result = await runtime.run({
  411. program: 'return [await tools["__proto__"]({}), await tools["constructor"]({}), typeof tools["hasOwnProperty"]]',
  412. // Computed keys: a literal `'__proto__': …` entry would SET the record's
  413. // prototype instead of declaring a binding of that name.
  414. bindings: tools({ ['__proto__']: async () => 'proto-ok', ['constructor']: async () => 'ctor-ok' }),
  415. })
  416. expect(result.value).toEqual(['proto-ok', 'ctor-ok', 'undefined'])
  417. })
  418. })
  419. describe('WorkerCodeRuntime — seam misuse and lifecycle', () => {
  420. it('rejects invalid binding globals loudly (identifier, reserved word, duplicate, reserved injected globals)', async () => {
  421. const { runtime } = await setup()
  422. const cases: [string, RegExp][] = [
  423. ['not valid!', /not a usable identifier/],
  424. ['await', /not a usable identifier/],
  425. ['console', /duplicate binding global/],
  426. ['ToolCallError', /duplicate binding global/],
  427. ]
  428. for (const [global, message] of cases) {
  429. await expect(runtime.run({ program: 'return 1', bindings: [{ global, functions: {} }] })).rejects.toThrow(message)
  430. }
  431. await expect(runtime.run({
  432. program: 'return 1',
  433. bindings: [{ global: 'tools', functions: {} }, { global: 'tools', functions: {} }],
  434. })).rejects.toThrow(/duplicate binding global/)
  435. })
  436. it('rejects config values that are not positive numbers', async () => {
  437. const ctx = new Context()
  438. await expect(ctx.plugin(WorkerCodeRuntime, { computeMs: -1 })).rejects.toThrow(/positive number/)
  439. })
  440. it('requires maxOutputBytes to fit the smallest outer failure envelope', async () => {
  441. const ctx = new Context()
  442. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 3 })).rejects.toThrow(/safe integer of at least 4/)
  443. await expect(ctx.plugin(WorkerCodeRuntime, { maxOutputBytes: 4.5 })).rejects.toThrow(/safe integer of at least 4/)
  444. })
  445. it('keeps runs isolated: no state survives from one run to the next', async () => {
  446. const { runtime } = await setup()
  447. await runtime.run({ program: 'globalThis.leak = "value"; return 1', bindings: [] })
  448. const second = await runtime.run({ program: 'return typeof globalThis.leak', bindings: [] })
  449. expect(second.value).toBe('undefined')
  450. })
  451. it('disposal aborts in-flight runs, awaits worker exit, and rejects later runs', async () => {
  452. const ctx = new Context()
  453. const fiber = await ctx.plugin(WorkerCodeRuntime)
  454. const runtime = ctx.codeRuntime as WorkerCodeRuntime
  455. const inflight: Promise<CodeRunResult> = runtime.run({ program: 'for (;;) {}', bindings: [] })
  456. // Give the worker a moment to actually start spinning.
  457. await new Promise(resolve => setTimeout(resolve, 200))
  458. await fiber.dispose()
  459. const result = await inflight
  460. expect(result.error).toEqual({ kind: 'abort', message: 'runtime disposed' })
  461. await expect(runtime.run({ program: 'return 1', bindings: [] })).rejects.toThrow(/after disposal/)
  462. }, 15_000)
  463. it('removes ctx.codeRuntime when the providing fiber disposes (HMR safety)', async () => {
  464. const ctx = new Context()
  465. const fiber = await ctx.plugin(WorkerCodeRuntime)
  466. expect(ctx.get('codeRuntime')).toBeInstanceOf(WorkerCodeRuntime)
  467. await fiber.dispose()
  468. expect(ctx.get('codeRuntime')).toBeUndefined()
  469. })
  470. })