Repository navigation
feat(codemode): idempotent and durable tools, and safe suspension on the VM - #62459
Conversation
There was a problem hiding this comment.
The VM side works as described. I ran the new suspend tests, the full VM and round-trip suites and typecheck:tsc, all green. I also checked the timeout/interrupt path of a reconnectable tool on both engines with a throwaway test. On vm, cancel(handle) runs as described. On the default legacy engine it never runs (see inline comment).
Public API (@opencode/codemode, published). Everything is additive and backwards compatible for existing callers:
Tool.makeoptions gaindurable?: false | "rerun" | { start, attach, cancel }, andexecutebecomes optional when reconnectable hooks are given.executealso receives a second{ key }argument.- The
Tooltype gainsdurable?, andexecuteis now(input, context?). ToolInvocationgains a requiredkey. Code that only reads it is unaffected; code that buildsToolInvocationobjects itself must now addkey.SuspendError.runningitems go from{ path }to{ key, path }.VmRuntime.program(code, bindings?, options?)takes a newProgramOptions { runId? }, which is also exported.Extension.make/Extensiongain an optionalsnapshot: { encode, decode }.- The snapshot format changes: the header gains
runId,HostCallrecords gainkey/handle/admitted, and there are newHostValue/HostFunctionrecords. States from older builds already fail to resume because of the build hash check.
| execute: (input, context = { key: crypto.randomUUID() }) => { | ||
| if (execute !== undefined) return execute(input, context) | ||
| const reconnectable = durable as Reconnectable<unknown, unknown, R> | ||
| return Effect.flatMap(reconnectable.start(input, context), (handle) => reconnectable.attach(handle, context)) |
There was a problem hiding this comment.
When a tool only provides reconnectable hooks, this fallback runs start then attach and never calls cancel. It's what runs on the legacy engine, which is still the default, and for anyone who calls tool.execute directly. If the run is interrupted (timeout, abort) during attach, the started work keeps running. I reproduced it: the same tool with a never-ending attach and timeoutMs: 100 has cancel({id:1}) called on vm, but nothing on legacy. This also goes against the README's statement that cancel runs when the run is interrupted for real. Wrapping attach so it calls cancel(handle) on interrupt (e.g. Effect.onInterrupt) would make both engines behave the same.
There was a problem hiding this comment.
The new commit swaps the durable option for Tool.idempotent(execute) and Tool.durable({ start, wait, cancel }) wrappers on execute. The suspend behaviour is the same. I re-ran the suspend tests, the legacy, VM and round-trip suites, and typecheck:tsc: all green.
My earlier point is not addressed yet. With the new API, a Tool.durable tool still never has cancel called when the run is interrupted on the legacy engine, which is the default, or when tool.execute is called directly. I reproduced it again: on a 100 ms timeout, vm calls cancel({id:1}) and legacy calls nothing (see the open thread).
Public API (@opencode/codemode, compared with the base), all additive:
- New
Tool.idempotentandTool.durablewrappers, plus theExecuteFn,Idempotent,DurableandDurableOptionstypes. Tool.make'sexecutealso accepts these wrappers, and gets a second{ key }argument.- The
Tooltype gainsmode?, andexecuteis now(input, context?). ToolInvocationgains a requiredkey.SuspendError.runningitems go from{ path }to{ key, path }.program(code, bindings?, { runId })takes a newProgramOptions.Extensiongains an optionalsnapshot: { encode, decode }.- The snapshot format changes: the header gains
runId,HostCallrecords gainkey,dataandadmitted, and there are newHostValue/HostFunctionrecords.
Existing callers keep working. Code that builds ToolInvocation objects itself must now add key.
There was a problem hiding this comment.
My earlier point is addressed. Tool.durable(...) now cancels the started work on interrupt through acquireUseRelease, so the legacy engine and direct tool.execute callers behave like the VM. On a 100 ms timeout, I saw cancel({id:1}) called on both engines. I re-ran the suspend tests, the legacy, VM and round-trip suites, and typecheck:tsc: all green.
Public API: unchanged from my last review. The new commit splits the requirement type into DurableOptions' RStart/RWait/RCancel parameters, and Idempotent/Durable values can now be called directly. Everything stays additive compared with the base.
One new concern: restoreStart relies on Effect's private internals (see inline comment).
|
|
||
| // Runs `make` with interruptibility restored unless `make()` itself is `Effect.uninterruptible`, so an | ||
| // uninterruptible `start` returns its data into the outer mask without interrupting at its exit boundary. | ||
| const restoreStart = <A, E>( |
There was a problem hiding this comment.
restoreStart reads Effect's private "~effect/Effect/args" field and changes the fiber's _stack and interruptible flag directly. Neither is public API, so an Effect upgrade could silently change what this does. It could drop the data start returned, which leaks the job, or leave the fiber's stack corrupted. If the goal is that a start that has finished never has its data dropped, running start fully uninterruptible, as Effect.acquireRelease does with its acquire step, guarantees that without touching internals. The cost is that a slow start can't be interrupted, which it already can't be during a suspend. If start must stay interruptible, it would be safer to handle that inside the durable tool, for example by letting the tool's own start check its key on retry.
There was a problem hiding this comment.
The Effect-internals concern is addressed: restoreStart is gone and start is back to a plain Effect.suspend.
This commit also undoes the earlier cancel fix. Tool.durable's execute is back to Effect.flatMap(start, wait), so an interrupted run on the legacy engine (the default), or a direct tool.execute caller, leaks the started work. I re-checked it: on a 100 ms timeout, vm calls cancel({id:1}) and legacy calls nothing (see inline comment).
The suspend tests, the legacy, VM and round-trip suites, and typecheck:tsc all pass. The public API is unchanged since my last review.
| const wait = options.wait as (data: Schema.Json, context: ToolContext) => Effect.Effect<Output, unknown, R> | ||
| return Object.assign( | ||
| (input: Input, context: ToolContext): Effect.Effect<Output, unknown, R> => | ||
| Effect.flatMap(options.start(input, context), (data) => wait(data, context)), |
There was a problem hiding this comment.
This brings back the leak from the earlier thread: with flatMap, nothing calls cancel(data) when wait is interrupted on the legacy engine or through a direct tool.execute. I confirmed it at this commit: with a 100 ms timeout, legacy never calls cancel, while vm does. The previous Effect.acquireUseRelease(start, wait, (data, exit) => interrupted ? cancel(data) : void) covered it, and it uses no internals.
Summary
Implements
Tool.idempotentandTool.durable({ start, wait, cancel })wrappers forTool.make'sexecute, stable<runId>:<callId>call keys, safe suspension rules, and extensionsnapshothooks in@opencode/codemodeon the bytecode VM (engine: "vm").API
1. Tool execution wrappers (
Tool.make,Tool.idempotent,Tool.durable)Plain (
execute: (input, { key }) => ...): suspend is refused while the call is running.Tool.idempotent(execute): idempotent/read-only work safe to run again. If a suspend lands while the call is running, the VM detaches and interrupts it without firingtool.after, keeps the call in the snapshot asqueued, and re-runs it on resume with the samekeywithout double-counting it againstmaxToolCalls.Tool.durable({ start, wait, cancel }):start(input, { key }) => Effect<Data /* Json */>begins the work and returns JSONdata(inferred intowaitandcancel);wait(data, { key }) => Effect<Output>connects to the running work and waits for its result;cancel(data) => Effect<void>stops the work when the run is interrupted for real or ends, never when it is suspended.While
startis running, the call blocks suspend. Oncestartreturns its JSON data, the call is in thestartedstate with its data saved in the snapshot, and suspend is allowed.waitis not tied to the program's JavaScriptawait: the VM callswait(data)right afterstartreturns, and callswait(data)again for everystartedcall right whenresumestarts, whatever the program does with the call's promise (await,Promise.all,.then, or holding the unawaited promise in a variable and awaiting it later).2. Call keys and
runIdEvery host call gets a stable key
<runId>:<callId>, saved in the snapshot:runtime.program(code, bindings?, { runId })accepts an explicitrunId(or generates a UUID by default).{ key }as the second argument toexecute(input, { key })(andstart(input, { key })/wait(data, { key })).tool.beforeandtool.afterhooks receivekeyonToolInvocation({ name, input, key }).SuspendError.runningincludes{ key, path }for every call blocking suspension.Safety Rule Table
Suspend is allowed only when every in-flight host call is
queued,Tool.idempotent, orTool.durableinstarted. Otherwiseprogram.suspend()fails withSuspendError(leaving the run undisturbed) and lists each blocking call's{ key, path }inrunning:status: "queued")queued; launched on resume.Tool.idempotenttool (status: "running")tool.after; saved asqueued(admitted: true); re-run on resume with the samekeywithout double-countingmaxToolCalls.Tool.durabletool instarted(status: "started")waitfiber detached without firingtool.afterorcancel; JSONdatasaved in snapshot; VM callswait(data)on resume.Tool.durabletool still instart(status: "running")SuspendError){ key, path }inerror.running; run continues undisturbed.search(status: "running")SuspendError){ key, path }inerror.running; run continues undisturbed.SuspendError){ key, path }inerror.running; run continues undisturbed.Extension Snapshot Hooks
encode(value)receives a host value returned by one of the extension's functions and returns plain data (JSON values andUint8Arrays), recorded once per root object as aHostValuerecord, with each method recorded as aHostFunctionrecord.decode(data)reconstructs the host value once perHostValuerecord and rebinds its methods onto the restored program functions.snapshothooks, extension-returned functions keep today'sLostNativebehaviour.packages/core/src/codemode/fetch.tswill attach a private symbol holding{ url, status, statusText, redirected, headers, body: Uint8Array }to each resolved response and usesnapshot: { encode, decode }to rebuild the response and itstext(),json(),bytes(), andheadersmethods on resume (while an in-flightfetchstays not durable).Out of Scope
packages/corein this PR.search, list/read tools, MCP resources, and worktree list as idempotent, subagent as durable, and keepfetch,shell, MCP tools, and plugin tools plain).Verification
bun run test:legacy: 1,630 pass, 0 failbun run test:vm: 1,630 pass, 0 failbun run test:roundtrip: 1,629 pass, 1 skip, 0 failtest262on VM (CODEMODE_ENGINE=vm bun test test/test262.test.ts): 13,329 pass, 1,678 skip, 1 known fail (language/global-code/import.js)bun run typecheck:tscinpackages/codemodeandpackages/core: 0 errorspackages/core:bun test test/tool-execute.test.ts test/codemode), with flag off and withOPENCODE_FLAGS=codemode_vm: 51 pass, 0 fail on bothbun run script/bench.ts --mixed: no regressionVisual
Added by the opencode bot (AI-generated).
Public API: adds Tool.idempotent / Tool.durable execute wrappers,
execute(input, { key }),ToolInvocation.key,SuspendError.running[].key,program(..., { runId })andExtension.snapshotto @opencode/codemode (additive; snapshot format changes)