Skip to content

Commit ffde0f7

Browse files
authored
feat(codemode): add a bytecode VM engine behind CodeMode.make({ engine: "vm" }) (#62357)
1 parent 188eee3 commit ffde0f7

120 files changed

Lines changed: 20516 additions & 39 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/codemode/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,9 @@ denies it: the host function is never called, and the program catches the failur
9797
fails the way the call itself would: a tool call or asynchronous global rejects its promise, and a synchronous global
9898
throws.
9999

100+
`engine: "vm"` runs programs on the bytecode VM in `src/vm` instead of the default `"legacy"` interpreter. It is
101+
experimental: `execute` has the same signature and results on both engines.
102+
100103
### `Extension.make`
101104

102105
Extensions are host functions a program calls directly as globals, such as `fetch`. Unlike tools they are not in the

‎packages/codemode/bunfig.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[test]
2+
preload = ["./test/preload.ts"]

‎packages/codemode/package.json‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@
2424
"pack": "bun run script/pack.ts",
2525
"typecheck": "bun check --no-script",
2626
"typecheck:tsc": "tsc --noEmit",
27-
"test": "bun test"
27+
"test": "bun test && CODEMODE_ENGINE=vm bun test",
28+
"test:legacy": "bun test",
29+
"test:vm": "CODEMODE_ENGINE=vm bun test",
30+
"test:roundtrip": "CODEMODE_ENGINE=vm CODEMODE_ROUNDTRIP=1 bun test"
2831
},
2932
"dependencies": {
3033
"acorn": "8.15.0",

‎packages/codemode/script/bench.ts‎

Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
#!/usr/bin/env bun
2+
3+
// Interpreter benchmarks: median and fastest wall-clock milliseconds per program over several runs.
4+
// Usage: bun run script/bench.ts [--engine vm|legacy] [--iterations N] [--filter name] [--mixed] [--jsc]
5+
6+
import { numberOfDFGCompiles, reoptimizationRetryCount } from "bun:jsc"
7+
import { Effect, Schema } from "effect"
8+
import { CodeMode, Tool } from "../src/index.js"
9+
import { Vm } from "../src/vm/vm.js"
10+
11+
const cases: ReadonlyArray<readonly [name: string, code: string]> = [
12+
[
13+
"numeric loop",
14+
`let sum = 0
15+
for (let i = 0; i < 300000; i++) sum = (sum + i * 3) % 1000003
16+
return sum`,
17+
],
18+
[
19+
"closure recursion (fib 22)",
20+
`const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2))
21+
return fib(22)`,
22+
],
23+
[
24+
"array callbacks (50k)",
25+
`const items = Array.from({ length: 50000 }, (_, i) => (i * 7919) % 50000)
26+
const mapped = items.map((x) => x * 2).filter((x) => x % 3 !== 0)
27+
const total = mapped.reduce((a, b) => a + b, 0)
28+
const sorted = mapped.slice(0, 20000).sort((a, b) => a - b)
29+
return [total, sorted[0], sorted[sorted.length - 1]]`,
30+
],
31+
[
32+
"promise fan-out (5k)",
33+
`const work = async (i) => { await null; return i * 2 }
34+
const results = await Promise.all(Array.from({ length: 5000 }, (_, i) => work(i)))
35+
return results.length`,
36+
],
37+
[
38+
"tool fan-out (1k)",
39+
`const results = await Promise.all(Array.from({ length: 1000 }, (_, i) => tools.echo({ id: i })))
40+
return results.length`,
41+
],
42+
[
43+
"JSON round-trip",
44+
`const make = (depth) => depth === 0 ? { a: 1, b: "two", c: [1, 2, 3], d: null } : { left: make(depth - 1), right: make(depth - 1), list: [depth, String(depth)] }
45+
let size = 0
46+
for (let i = 0; i < 20; i++) size += JSON.stringify(JSON.parse(JSON.stringify(make(9)))).length
47+
return size`,
48+
],
49+
[
50+
"generator iteration",
51+
`function* range(n) { for (let i = 0; i < n; i++) yield i }
52+
let sum = 0
53+
for (const x of range(50000)) sum += x
54+
return sum`,
55+
],
56+
[
57+
"string building",
58+
`let out = ""
59+
for (let i = 0; i < 50000; i++) out += String.fromCharCode(97 + (i % 26))
60+
const parts = []
61+
for (let i = 0; i < 20000; i++) parts.push(\`item-\${i}\`)
62+
return out.length + parts.join(",").length`,
63+
],
64+
[
65+
"Map/Set ops",
66+
`const map = new Map()
67+
const set = new Set()
68+
for (let i = 0; i < 30000; i++) { map.set("k" + (i % 5000), i); set.add(i % 7000) }
69+
let sum = 0
70+
for (const [k, v] of map) sum += v
71+
for (const v of set) sum += v
72+
for (let i = 0; i < 5000; i++) { map.delete("k" + i); set.delete(i) }
73+
return sum + map.size + set.size`,
74+
],
75+
]
76+
77+
const argument = (flag: string) => {
78+
const index = process.argv.indexOf(flag)
79+
return index === -1 ? undefined : process.argv[index + 1]
80+
}
81+
const iterations = Number(argument("--iterations") ?? 7)
82+
const filter = argument("--filter")
83+
const engine = (argument("--engine") as "legacy" | "vm" | undefined) ?? "vm"
84+
const mixed = process.argv.includes("--mixed")
85+
const jsc = mixed || process.argv.includes("--jsc")
86+
const exec = Vm.prototype["exec"]
87+
88+
const runtime = CodeMode.make({
89+
engine,
90+
tools: {
91+
echo: Tool.make({
92+
description: "Echo an id",
93+
input: Schema.Struct({ id: Schema.Number }),
94+
output: Schema.Number,
95+
execute: ({ id }) => Effect.succeed(id),
96+
}),
97+
},
98+
})
99+
100+
const median = (values: Array<number>) => {
101+
const sorted = [...values].sort((a, b) => a - b)
102+
return sorted[Math.floor(sorted.length / 2)]!
103+
}
104+
105+
const run = (code: string) => runtime.execute(code)
106+
107+
const selected = cases.filter(([name]) => filter === undefined || name.includes(filter))
108+
109+
const formatRow = (name: string, times: Array<number>) => {
110+
const base = `${name.padEnd(28)} ${median(times).toFixed(1).padStart(8)} ms (min ${Math.min(...times).toFixed(1)} ms)`
111+
if (!jsc) return base
112+
return `${base} [dfg=${numberOfDFGCompiles(exec)} retries=${reoptimizationRetryCount(exec)}]`
113+
}
114+
115+
if (mixed) {
116+
// Pollute profiles in reverse order first, then interleave cases with a stride across rounds.
117+
for (let i = selected.length - 1; i >= 0; i--) {
118+
const [name, code] = selected[i]!
119+
const warm = await Effect.runPromise(run(code))
120+
if (warm.ok !== true) throw new Error(`${name} failed: ${JSON.stringify(warm)}`)
121+
}
122+
const recorded = selected.map((): Array<number> => [])
123+
for (let round = 0; round < iterations; round++) {
124+
for (let step = 0; step < selected.length; step++) {
125+
const idx = (step * 5 + round * 3) % selected.length
126+
const [, code] = selected[idx]!
127+
const start = performance.now()
128+
await Effect.runPromise(run(code))
129+
recorded[idx]!.push(performance.now() - start)
130+
}
131+
}
132+
for (let i = 0; i < selected.length; i++) {
133+
console.log(formatRow(selected[i]![0], recorded[i]!))
134+
}
135+
} else {
136+
for (const [name, code] of selected) {
137+
// One warm-up run, which also checks the program succeeds.
138+
const warm = await Effect.runPromise(run(code))
139+
if (warm.ok !== true) throw new Error(`${name} failed: ${JSON.stringify(warm)}`)
140+
const times = Array.from({ length: iterations }, () => 0)
141+
for (const index of times.keys()) {
142+
const start = performance.now()
143+
await Effect.runPromise(run(code))
144+
times[index] = performance.now() - start
145+
}
146+
console.log(formatRow(name, times))
147+
}
148+
}

‎packages/codemode/script/build.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,5 @@ import { fileURLToPath } from "node:url"
66
process.chdir(fileURLToPath(new URL("..", import.meta.url)))
77

88
await $`rm -rf dist`
9+
await $`bun run script/prelude.ts`
910
await $`bun tsc -p tsconfig.build.json`

0 commit comments

Comments
 (0)