Runs fail with `setImmediate is not defined` in browsers and Convex's runtime once a program runs longer than ~1 ms

Aperta
#82 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

@fengqiaoqu ci sta già lavorando.

Dal 27/11/2026.

  • #102 di @fengqiaoqu — aperta

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
35/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Ferma
Stack tecnologico
javascript, typescript

Direzione di ricerca

Start with src/runtime/driver.ts around the yielding path and src/vm.ts where the slice timing is defined, then inspect how Runtime.make accepts host configuration. Review the existing implementation in linked PR #102 and locate the runtime or browser tests covering long-running programs. Done means long executions yield successfully in browser and bare V8-like hosts, with an overridable host yield, while existing interrupt and timeout behavior remains covered.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

When testing with v8 runtimes, Claude and I encountered the following. The below is written by Claude.


When a program runs long enough to hit a VM slice, Driver.run() yields with setImmediate
(src/runtime/driver.ts:63).
SLICE_MS is 1 (src/vm.ts:154), so any
program that runs for more than about 1 ms of VM time reaches that call. Browsers don't define setImmediate, and
neither do runtimes like Convex's default V8 runtime.

Short programs, host calls, and suspend → toBytes → fromBytes → resume all work fine in these environments. The
codebase also seems to anticipate non-Node hosts already (Buffer is only installed when the host has one,
globals.ts:184). This looks like the one place where it still assumes Node.

Repro

Tested on dev @ bf492e1, bundled with bun build src/index.ts --target=browser, running in headless Chromium 158:

import { Runtime } from "./psychoscript.browser.js"

const runtime = Runtime.make({ globals: () => ({}) })
console.log(await runtime.execute("return 1 + 1"))
// { ok: true, value: 2 }

console.log(await runtime.execute("let s = 0; for (let i = 0; i < 300000; i++) s += i; return s"))
// { ok: false, error: { kind: "ExecutionFailure", message: "setImmediate is not defined" } }

I got the same failure in Node 24 after delete globalThis.setImmediate (which mimics Convex's runtime, since its
timer setup only
defines setTimeout/setInterval).

Workaround

Shimming it before import fixes it. With this shim, every probe I ran passed in Chromium:

globalThis.setImmediate ??= (fn) => {
  const c = new MessageChannel()
  c.port1.onmessage = () => fn()
  c.port2.postMessage(0)
}
Suggested fix

Use a portable default yield, and let the embedder override it:

const defaultYield = (): Promise<void> =>
  new Promise((resolve) => {
    if (typeof setImmediate === "function") setImmediate(resolve)
    else if (typeof MessageChannel === "function") {
      const { port1, port2 } = new MessageChannel()
      port1.onmessage = () => {
        port1.close()
        resolve()
      }
      port2.postMessage(null)
    } else Promise.resolve().then(() => resolve()) // bare V8 hosts: no queueMicrotask either
  })

// e.g. Runtime.make({ yieldToHost: () => new Promise((r) => setTimeout(r, 0)) })

Why both:

  • Bare V8 hosts like Convex's runtime have no setImmediate, MessageChannel or queueMicrotask. The
    microtask fallback is the only yield that works in Convex queries/mutations. Those hosts define setTimeout but
    refuse to run the timer, so the callback never fires and the function fails.
  • A microtask yield can't be interrupted: timers and abort listeners never run while the guest is CPU-bound, so
    timeoutMs stops working. In a Convex-like action, a 200 ms timeout let a loop run to completion at 793 ms; with a
    setTimeout(r, 0) yield it stopped with TimeoutExceeded at 206 ms. Hosts where timers do work (e.g. Convex
    actions) should be able to pass that yield in.
Lingua principale
Rust
Stelle
470
Fork
11
Merge medio
4h 10m
PR unite (30g)
89

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di anomalyco/psychoscript

Tutte le issue di anomalyco/psychoscript

Issue simili

Altre issue su Rust

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.