Skip to content

next: realm handles and realm entry, with one env per engine instance - #127

Merged
syrusakbary merged 162 commits into
mainfrom
next
Nov 6, 2026
Merged

syrusakbary merged 162 commits into
mainfrom
next

Conversation

@syrusakbary

Copy link
Copy Markdown
Member

next collects the realm work in one branch:

It is up to date with main. It replaces #111, #116 and #120, and the alternative designs #112, #114 and #115. The design is in docs/realms.md.

What changes

One env per engine instance; realms are handles (#111, #116).

  • Each provider is split into an agent (the isolate or runtime) and its env. The bridge and host-JS are split the same way.
  • A vm context or a browser document is an unofficial_napi_realm, not an env.
  • Only the calls that run code take a realm: run_script, compile_function, module creation and bytecode_open. A NULL realm means the env's own.
  • Realms are collected with their global or sandbox on every provider.
  • ABI changes:
    • contextify_make_context is replaced by unofficial_napi_create_realm, plus unofficial_napi_get_realm;
    • module and bytecode options are version 2 (realm_or_null);
    • the context-token hooks are gone;
    • on the guest ABI, a realm id is the value id of the realm's global.

N-API acts in the current realm (#120).

  • What N-API creates comes from the current realm's intrinsics, and napi_get_global returns that realm's global.
  • A native function belongs to the realm that was current when it was made, and its callback runs there.
  • unofficial_napi_enter_realm / unofficial_napi_leave_realm make a realm current, with LIFO scopes and no JavaScript run.
  • Deferreds settle in their promise's realm. Finalizers, cleanup hooks, env hooks and interrupt callbacks run in the env's realm.
  • An embedder that never enters a realm sees no change (Node's and EdgeJS's model).

Fixes from #120's review.

  • Releasing the env closes every scope. V8 used to abort and QuickJS to leak when a cleanup hook or the instance-data finalizer left a scope open.
  • Intrinsics never come from a realm's global, which the realm's scripts control:
    • errors, DataViews and typed arrays come from intrinsics, after Node's range checks and with its error codes;
    • buffers read Buffer from the env's realm.
  • V8 module hooks run in the env's realm, as documented.
  • QuickJS napi_run_script in an entered sandbox realm copies the sandbox in and out, matching V8.
  • Header changes:
    • it no longer promises to refuse a stale realm handle, since providers can reuse its address;
    • it says which realm options each provider honours.

Merged from main.

Tests

macOS arm64, Release, at f928811.

Suite #111 + main (2c158cf) next
V8 native 111 171
QuickJS native (next also under Debug+ASan) 107 162
Rust lib 54 54
concurrent_envs / concurrent_stores / guest_callbacks 11 / 2 / 4 11 / 2 / 4
Manifest, native + WASIX 36 37
host-JS node 36 43
host-JS wasm-bindgen 13 26

All pass. main itself was not measured.

New suites:

  • test_66_unofficial_realm (realm handles);
  • test_69_unofficial_realm_entry and test_70_realm_entry_attack (realm entry and the review's adversarial cases);
  • a wasm-bindgen test that drives the host-JS realm imports from a WAT guest.

Not done yet

  • Two provider bugs that predate this work:

    • QuickJS runs the instance-data finalizer after JS_FreeRuntime;
    • V8's external backing-store deleter calls its finalizer directly, possibly on a GC thread.

    The fixes follow on this branch.

  • Realm APIs a browser embedder needs next: a realm's code-generation policy at run time, realm disposal, a function's realm, and the caller's realm.

🤖 Generated with Claude Code

syrusakbary and others added 30 commits October 23, 2026 16:20
State that belongs to the isolate rather than to one realm lived in
eight process-wide maps keyed by isolate or env, each read under
g_runtime_mu: g_env_by_isolate, g_hash_seeds, g_tracking_allocators,
g_fatal_error_callbacks, g_near_heap_limit_callbacks, g_profiler_states,
g_promise_reject_callbacks and g_promise_hooks. They are gone.

napi_agent__ (internal/napi_v8_agent.h) is created with the isolate,
owned by the env owner handle, and found from an isolate through data
slot 0. It holds the hash seed, the array buffer allocator, the profiler
sessions, the near-heap-limit slot, the embedder hooks (fatal, OOM,
context tokens, foreground task) and the wrap, buffer and type-tag
private keys. It also sets the microtask policy and the default
dynamic-import hook, which the env constructor used to reset.

The promise reject callback and promise hooks are realm state and move
to the env. Dispatch goes isolate -> agent -> principal env; resolving
context -> env is left to a later phase. GetModuleWrapEnvForIsolate is
an agent lookup instead of a scan.

Shutting the agent down now also removes the near-heap-limit trampoline,
which used to stay registered with the freed env as its data. Each
isolate still has one env; there is no ABI change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
napi_env__ carried the runtime-level state of its JSRuntime and a
switchable current_context_ that vm contexts swapped in and out at 16
napi_env_context_scope__ sites. Every napi_value, ref and deferred also
remembered the context it was made in, so a value could be tagged with
the wrong realm when a subsystem wrapped it.

napi_agent__ (internal/napi_agent.{h,cc}) now owns the runtime-level
state: the handle-scope stack, the pending exception (freed with the
runtime, so last_exception_context_ is gone), external memory, the
embedder hooks, continuation data and promise context frames. It also
owns the runtime-wide promise, rejection, import.meta and dynamic-import
hooks, installed with the agent as opaque and dispatched to the env.
The env keeps one JSContext that never changes. current_context_,
main_context(), current_context() and napi_env_context_scope__ are
deleted, and values hold only their runtime.

QuickJS does not switch realms for C-function-data calls, so the
trampoline got the caller's context and took the env from its opaque.
A native function made in the main realm and called from a vm script
then saw the vm global and created objects there. The trampoline now
takes the env from the function's own data and runs in that env's
context, as V8 and Node do. Native callbacks are refused once env
teardown starts; before, only calls from the main context were.

Each runtime still has one env; there is no ABI change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SnapiEnvState held everything the bridge keeps for an env, including
tables that belong to the engine instance: guest value slots, scope
frames, refs, deferreds, the module_wrap, bytecode, profile and buffer
lease handle tables, callback invocations, active_callback_ctx and the
value limit. Once several realm envs share an isolate, a guest value id
minted through one env has to stay valid with the others.

SnapiAgentState now owns those tables, the provider owner and the list
of its envs. SnapiEnvState keeps the agent pointer, the napi_env and the
callback registry and bindings, which record the guest env id their
callbacks are invoked with. The table helpers keep their signatures and
work on the env's agent, so call sites are unchanged.

Scope frames remember the env that opened them and close their napi
scope through it. The value limit counts callback registrations and
bindings across the agent's envs. Disposing an env tears down its whole
agent, in the same order as before.

Each agent has one env; g_mu, g_envs and the Rust-facing signatures
are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
HostJsEnv held the handle space every napi_value and napi_ref resolves
against. It also depended on a module-global active context:
env_mut switched wasmerNapiActiveGlobalContext whenever the thread moved
to another env, and context_eval, is_buffer and buffer_view read it.
So which global a call used depended on which env had run last.

HostJsAgent now owns the handle tables and frames, object_ids, wraps,
references, deferreds, finalizers, pending callbacks and
active_callback_ctx. HostJsEnv keeps its global context, last
exception, callbacks, closures, instance data and modules; each env
creates its own agent.

The JS helpers take the env's context explicitly. A null sandbox, the
host global or the context's own global all mean that context.
wasmerNapiActiveGlobalContext, activate() and the ACTIVE_HOST_JS_ENV
thread-local are deleted, and env_mut is a plain cast. This fixes
create_bytes_value and create_guest_buffer_view, which built their
Buffer view before looking up the env and so used the last active
env's Buffer.

vm sandbox behaviour is unchanged. The node context tests are updated
for the new helper signatures in the tests commit that follows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- NativeFunctionCalledFromContextKeepsItsRealm (both engines): a native
  function made in the main env and called from a script running in a
  vm context sees the main global and creates objects with the main
  realm's Object.prototype. It fails on QuickJS before the trampoline
  fix and passes on V8 unchanged.
- NearHeapLimitCallbackReceivesItsEnvironment (V8): with a 16 MiB old
  generation the near-heap-limit callback fires and receives the env and
  data it was configured with, and releasing the env with the slot still
  set is clean. The trampoline's data is now the agent.
- host-JS context tests pass the env's context to context_eval,
  is_buffer and buffer_view explicitly. A new test checks that two
  contexts each evaluate in their own global for null, undefined and
  globalThis sandboxes, in either call order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/realm-bound-env.md describes splitting each provider into an agent
(the engine instance and its thread) and envs bound to exactly one
realm. It covers why (each layer overrides the realm per call in its own
way today), the state each layer would own, the API that follows
(create_realm and get_realm, no context arguments), realm lifetime, the
EdgeJS migration and a phased plan. Section 11 records what Phase 0
landed in V8, QuickJS, the bridge and host-JS, the test results, and
what Phase 1 still has to settle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The branch was renamed when pushed: the remote has a branch named
`refactor`, so no `refactor/...` branch can exist next to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An env keeps acting in its engine instance's main realm. A vm context is
another realm of that instance, but not an env:

- unofficial_napi_create_realm returns an unofficial_napi_realm and the
  realm's global (or sandbox); unofficial_napi_get_realm finds a realm by
  its global or sandbox.
- Only the calls that run code take a realm: unofficial_napi_run_script and
  unofficial_napi_compile_function (which replace the contextify versions
  that took a sandbox or parsing context), module creation (options
  version 2, realm_or_null instead of context_or_undefined) and
  unofficial_napi_bytecode_open (options version 2). NULL means the env's
  realm.
- A realm is collected when its global and everything made in it are
  unreachable. A realm handle, like a napi_value, is valid while its handle
  scope is open.
- unofficial_napi_contextify_make_context and the context-token hooks are
  removed (env hooks version 2).

In the guest ABI a realm id is the value id of the realm's global, so it
needs no table and has a value id's lifetime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- test_66 (new): creating and finding realms, code, functions, modules and
  bytecode in a realm, native functions staying in the env's realm, the
  env's hooks firing for realm code, and realms collected with their global
  (from #109's tests).
- test_65 makes its vm contexts with create_realm; test_21 and test_65
  reject version 1 hooks and module options.
- test_realm (new) and run_script_test cover the same through the guest ABI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- create_realm makes a context and a realm record the env owns; the
  context's embedder-data slot 33 points at the record, so get_realm is a
  creation-context lookup and needs no scan.
- The record holds its context weakly (as #109 does for contextify records):
  a realm lives while its global, or anything made in it, is reachable. The
  next create_realm frees records of collected realms, and only then their
  own microtask queues.
- run_script, compile_function, module creation and bytecode_open take a
  realm; NULL is the env's context.
- The sandbox-keyed context records, their linear scans, make_context and
  the context-token hooks are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In the guest ABI a realm handle is a value id, so like napi_values two
handles for one realm can differ. The header says so, and the tests compare
realms by their globals instead of by handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- snapi_bridge_unofficial_create_realm and _get_realm return the value id of
  the realm's global (or sandbox) as the realm id; run_script,
  compile_function, module creation and bytecode_open resolve it again with
  unofficial_napi_get_realm. The bridge keeps no realm table, and a realm id
  lives as long as its value id.
- New guest imports unofficial_napi_create_realm, unofficial_napi_get_realm,
  unofficial_napi_run_script and unofficial_napi_compile_function; the
  contextify make_context, run_script and compile_function imports are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A host-JS realm id is the value id of the realm's key: its sandbox, or
its fresh global. 0 means the env's own realm. There is no realm table.

- Each env keeps a WeakMap registry from a realm's key and scope to its
  global context. A key keeps the first realm made for it, and lookups
  only see the env's own registry. Realm 0 never goes through the
  registry, so vm.createContext(globalThis) makes a realm over the env
  global without changing how the env itself evaluates.
- create_realm and get_realm replace contextify_make_context.
  run_script, compile_function, bytecode_open and module create take
  the realm id; an id that names no realm is napi_invalid_arg.
- The guest layer registers unofficial_napi_create_realm, get_realm,
  run_script and compile_function, and reads realm_or_null for modules
  and bytecode. The contextify imports are gone.
- Name, origin, codegen and own-microtask-queue options have no effect
  on host-JS realms, which share their intrinsics.

Tests: node WeakRef tests (--expose-gc) check that realms nothing
refers to are collected while their registry lives, and that a
duplicate sandbox, a non-realm value and another registry find nothing.
wasm-bindgen tests cover run_script, compile_function and bytecode_open
per realm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A vm context is now a realm of the env's runtime: create_realm makes a
JSContext, with or without a sandbox, and returns its record as an
unofficial_napi_realm. run_script, compile_function, module creation
and bytecode_open run or compile in that realm's context, or in the
env's for NULL. A sandbox realm keeps the copy-in/out sync; a realm
with a fresh global needs none. get_realm looks a realm up by its
global or sandbox. make_context, dispose_context and the
sandbox-taking signatures are gone.

Realms are collected with what they belong to. Under private symbols
the sandbox (or a fresh realm's global) holds a function of the realm,
which keeps the context alive, and a sandbox realm's global holds the
sandbox, so the collector sees the whole cycle. The record holds that
object through a native weak link and borrows the context; collected
records are released when the next realm is made. Bytecode handles and
modules of a realm hold its context.

Hooks are called with this = undefined, since they fire for code in
any realm of the env.

On QuickJS a realm's pending job keeps it alive (engine commit
7ddf9e3), so the realm-lifetime test drains the job queue before it
checks that the realm is collected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An env is one engine instance's view from its main realm, and a vm
context is a realm handle that only the calls that run code take. The
doc covers the API, how each provider makes and collects realms, how
EdgeJS uses them, what is not done and how this differs from the
earlier realm-env attempts. It is renamed to realms.md, since vm
contexts are no longer envs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Code in a realm can resolve a promise whose reaction belongs to the
env's realm. The job is queued from the realm, and nothing else need
keep that realm alive until the job runs. On QuickJS this needs engine
commit 7ddf9e3, which makes a job hold its context; without it ASan
reports a use-after-free in promise_reaction_job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Realms are now collected with their global or sandbox. A promise job
queued from a realm took no reference to that realm's context, so if
the realm was collected before the job ran, the job used a freed
context. Engine commit 7ddf9e3 (wasmerio/quickjs#10) makes a job hold
its context until it runs. PendingJobRunsAfterItsRealmIsUnreachable
covers this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
wasmerio/quickjs#10 now ports all of bellard/quickjs 458c34d: besides a
job holding its context, a module can outlive the context that loaded it
(a module whose top-level await is pending when its context is freed was
used after it was freed) and a FinalizationRegistry holds its
constructor's context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
wasmerio/quickjs#10 is merged as 870aa7b, with the same tree as the
commit pinned before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in the V8 foreground-task fixes (#113, #117) and QuickJS
termination (#118, #119).

Conflicts were in the QuickJS provider, where this branch moved
runtime-wide state onto the agent and removed the switchable current
context:
- napi_env.cc: main's runtime interrupt handler with this branch's
  constructor (agent and fixed context). Teardown keeps both the agent's
  value clearing and the interrupt detach, using the env's context.
- napi_function.cc, js_native_api_quickjs.cc: main's termination checks,
  without the napi_env_context_scope__ this branch removed.
- last_exception_is_uncatchable() asks the agent, which now holds the
  pending exception.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in main through #111: the V8 foreground-task fixes and
termination on both engines.

- quickjs/src/internal/napi_module_wrap.cc: evaluation goes through
  main's evaluate_unless_terminated(), which now evaluates the module in
  its realm, as this branch does.
- quickjs/src/internal/napi_contextify.cc: run_script checks the realm,
  then fails while terminating.
- tests/CMakeLists.txt: both sides' tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
N-API acts in one realm at a time, the current realm, as an ECMAScript
engine runs code in the realm of its running execution context. What N-API
creates comes from that realm, and a native function belongs to the realm
current when it was made, like a built-in function's [[Realm]], and runs
there. unofficial_napi_enter_realm makes a realm current until
unofficial_napi_leave_realm. An embedder that never enters a realm acts only
in the env's realm, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The env keeps a stack of realm frames: scopes opened with enter_realm, which
also enter the realm's context, and the native callbacks that are running.
napi_env__::context() is the innermost frame's context. A function made in
a realm names it in its payload; V8 already runs it in its creation
context. Promises settle in their creation context. Finalizers, env hooks
and interrupt callbacks run in the env's realm, and the calls that take a
NULL realm use the env's own context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
QuickJS calls C functions with data in the caller's context; it switches
realms only for its own built-ins. A native function of another realm now
carries that realm's context and anchor in its data, and its trampoline
makes the realm current. The env keeps the same stack of realm frames as on
V8, and deferreds settle in their realm. Finalizers and interrupt callbacks
run in the env's realm.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The guest imports unofficial_napi_enter_realm(env, realm_id, scope_out_ptr)
and unofficial_napi_leave_realm(env, scope). A realm id is the value id of
the realm's global, 0 for the env's own; the scope token is the provider's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Implement snapi_bridge_unofficial_enter_realm and
snapi_bridge_unofficial_leave_realm for the host-JS provider, and the
unofficial_napi_enter_realm / unofficial_napi_leave_realm guest imports
of the in-tab build.

The env keeps a realm stack: scopes opened with enter_realm and the
native callbacks and finalizers running, innermost last. The current
realm is the innermost entry's, else the env's own. napi_get_global
returns the current realm's key (its sandbox, else its global), so
unofficial_napi_get_realm finds the realm again.

A native function belongs to the realm current when it was made. Its JS
wrapper holds that realm's context and passes it to dispatch on every
call; the Rust closure, which the env keeps for its whole life, does not
capture it, so a realm is collected with the last function made in it.
A callback runs with its function's realm current, including a deferred
callback when it is drained, and the scopes it leaves open close when it
returns. napi_run_script runs in the current realm. Finalizers run in
the env's realm. Functions made with no scope open belong to the env's
realm, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_69 covers, on V8 and QuickJS: values made in an entered realm, the
global per realm, nesting and refused leaves, native functions, classes and
properties running in their realm, deferreds, scopes a callback leaves
open, a pending exception, unknown and collected realms, realms kept alive
by their functions, and finalizers. test_realm covers entering a realm
through the guest ABI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The callback trampoline ended with wasm_bindgen::throw_val when the guest
left an exception pending. throw_val unwinds without running Rust
destructors, so the closure's arguments (the arguments array, an undefined
new.target) were never dropped and every throwing call kept two externref
slots for good.

The trampoline now returns Result<JsValue, JsValue>. wasm-bindgen throws an
Err only after the closure has returned and dropped what it owns.
throw_val was the file's only call that throws.

The tests run Rust closures in place of guest callbacks, as on
realm-entry, and count the roots a native function leaves behind when
JavaScript calls it: 0 for one that returns, 2 for one that throws before
this change, 0 after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in #121 (typed guest callbacks) and #122 (host-JS finalizers taken
from a queue of collected objects). This branch moved host-JS finalizer
state from HostJsEnv to HostJsAgent, so #122's queues, indices and
wrap_finalizers live on the agent, and the deferred-finalizer retry,
buffer finalizer registration, napi_remove_wrap and #122's tests reach
them through `state.agent`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in #107 (envs on different threads run JavaScript concurrently).
Releasing an env tears down its whole agent on this branch, so #107's
teardown state moves to SnapiAgentState: `closing`, `stop_requested`,
`teardown_guest_calls` and the pending interrupt requests. GuestCallScope,
the interrupt callback, terminate and request_interrupt reach it through
the env's agent. `holders`, `g_envs` and each thread's owned-env set stay
per env, since they guard the env pointers the Rust registry holds.

DisposeBridgeState keeps #107's order (callback bindings freed after the
release, registry entries dropped under g_mu, unserviced interrupts freed)
for every env of the agent, then frees the agent. snapi_bridge_dispose
releases one owned env at a time, because releasing one forgets every env
of its agent. NewAgentWithPrincipalEnv registers the env under g_mu and
adopts it on the creating thread.

docs/realm-bound-env.md notes that #107 landed and where its state lives.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
syrusakbary and others added 28 commits November 6, 2026 02:36
main has its own test_72_unofficial_memory_pressure, test_73 and test_74
runners, so the termination runners would share their numbers once main
is merged into next. They move to the next free numbers:

- tests/runners/test_72_hooks_keep_termination.cc becomes
  test_75_hooks_keep_termination.cc, suite Test75HooksKeepTermination;
- tests/runners/test_73_termination_until_cancelled.cc becomes
  test_76_termination_until_cancelled.cc, suite
  Test76TerminationUntilCancelled.

tests/CMakeLists.txt registers them under the new names, and the two
comments in test_76 that point at test_72 now point at test_75. The tests
are unchanged otherwise.

Test: both engines build; V8 300/300 and QuickJS 271/271 pass. The
runners keep their cases: 11 in test_75 and 20 in test_76 on V8, 7 and 15
on QuickJS, which compiles out the V8-only ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
unofficial_napi_module_wrap_check_unsettled_top_level_await called
v8::Module::IsGraphAsync on any source text module. V8 accepts only an
instantiated module there and otherwise stops the process with "Fatal
error in v8::Module::IsGraphAsync ... must be used on an instantiated
module". So asking about a module that was never instantiated, or only
linked, aborted. The bug is older than f928811.

A module that is not instantiated has no top-level await under way. The
check now reports it settled, with napi_ok and nothing pending. QuickJS
already answers that for every module. Node makes this check only at
exit, on the entry module, which is instantiated by then. Instantiated
modules are unchanged.

Test: test_77_module_wrap_state, a new runner for module calls made in
the wrong state, on both engines.
CheckUnsettledTopLevelAwaitOfAModuleNotInstantiatedIsSettled asks about a
module with and without top-level await, first never linked, then linked,
then instantiated, and also about a synthetic module. Each answer must be
napi_ok, settled, with nothing pending. Before this commit, V8 aborted on
the first call (exit 133, "v8::Module::IsGraphAsync must be used on an
instantiated module"). QuickJS passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
unofficial_napi_module_wrap_evaluate and _evaluate_sync called
v8::Module::Evaluate whatever the module's state. V8 evaluates only an
instantiated module and otherwise stops the process with "Fatal error in
Module::Evaluate ... Expected instantiated module". So evaluating a
module before instantiating it aborted. The bug is older than f928811.

QuickJS's JS_EvaluateModule links an unlinked module first, so on
QuickJS such a call already worked. V8 now does the same: both calls
instantiate the module first, as unofficial_napi_module_wrap_instantiate
would. When that fails, for example on a request the module was not
linked for, they return what instantiating returned (the error pending)
and the module stays uninstantiated. Instantiated, evaluated and errored
modules are unchanged.

unofficial_napi_module_wrap_instantiate keeps its termination check
first, ahead of the instantiation it now shares. evaluate and
evaluate_sync check the termination before instantiating, so a
terminating env instantiates nothing.

Test: test_77 EvaluatingAModuleNotInstantiatedInstantiatesItFirst, both
engines. Through each of evaluate and evaluate_sync, a module with no
requests that was never linked must evaluate, run once and reach status
4. A module with a request it was not linked for must give
napi_pending_exception with an error pending, stay at status 0 and not
run. Before this commit, V8 aborted on the first evaluate (exit 133,
"Expected instantiated module"). QuickJS passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A module's own body, or a synthetic module's evaluation steps, can call
native code that evaluates the same module again: through
unofficial_napi_module_wrap_evaluate, _evaluate_sync, or
_create_required_module_facade, which evaluates the module it wraps.

- V8 stopped the process with "Check failed: module_status == kLinked ||
  module_status == kEvaluatingAsync || module_status == kEvaluated" (a
  CHECK in Module::Evaluate). For a source text module, only the facade
  got through.
- QuickJS gave evaluate the module's unsettled promise. evaluate_sync
  failed with ERR_REQUIRE_ASYNC_MODULE. The facade over a source text
  module crashed with SIGSEGV in js_inner_module_evaluation.
  js_evaluate_module asserts that the module is not evaluating; that
  assert is compiled out of release builds.

All three calls now refuse such a module on both engines. They throw an
Error with code ERR_VM_MODULE_STATUS ("Module status must not be
evaluating") and return napi_pending_exception. Node's vm refuses a
module whose status is "evaluating" with the same code. The evaluation
already under way goes on. The bugs are older than f928811.

Test: test_77 EvaluatingAModuleWhileItEvaluatesIsRefused, both engines. A
source text module's body, and then a synthetic module's steps, call a
native function. That function makes one of the three calls on the same
module and takes what it left pending. Each call must see status 3,
return napi_pending_exception with that code and message, and the outer
evaluation must resolve with the module run to its end (status 4). Before
this commit, V8 aborted on the first case (exit 133, the CHECK above).
QuickJS failed the source text cases: evaluate returned napi_ok,
evaluate_sync returned ERR_REQUIRE_ASYNC_MODULE, and the facade crashed
(exit 139).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
V8 runs no script while it instantiates a module graph, with one
exception: when a request does not resolve. Then ModuleResolveCallback
throws ERR_VM_MODULE_LINK_FAILURE, and the error gets its `code` with a
plain set, as Node does, which runs an inherited `code` setter. From that
setter, script could reach the module calls again while V8 still held
the graph half prepared:

- unofficial_napi_module_wrap_instantiate on that module or any other,
  and _create_required_module_facade, crashed with SIGBUS. A second
  instantiation walked modules the first had not finished.
- _evaluate and _evaluate_sync on that module (whose status is still
  uninstantiated) aborted before "V8: instantiate a module that is not
  instantiated before evaluating it" ("Expected instantiated module").
  Since that commit they instantiate first, so they would crash the same
  way.

These calls now throw ERR_VM_MODULE_LINK_FAILURE ("A module
instantiation is under way") and return napi_pending_exception while an
instantiation runs for the env. evaluate and evaluate_sync do this only
for a module they would have to instantiate. The provider counts
instantiations per env in its module state, around InstantiateModule in
both instantiate and the facade. The calls that only ask questions
already answered: check_unsettled_top_level_await says settled (since
"V8: report a module that is not instantiated as settled in the TLA
check") and get_namespace throws ERR_MODULE_NOT_INSTANTIATED. QuickJS
runs no script while it links: it reports an unresolved request through
its own loader, with an error that has no code. The bug is older than
f928811.

Test: test_77 NoInstantiationStartsWhileOneRuns, both engines.
Error.prototype gets a `code` setter that calls a native function once.
That function makes each call on the module being instantiated
(instantiate, evaluate, evaluate_sync, facade, check, namespace) and
instantiate on another module, and records what each returned and threw.
Instantiating a module whose request was never linked must then fail
with an error pending. On V8 the setter must have run, and the records
must be the refusal above for the five instantiating calls, "settled"
for the check and ERR_MODULE_NOT_INSTANTIATED for the namespace. That
check is guarded to V8, because only V8 runs the setter there. Both
modules must stay at status 0. Once linked properly they must
instantiate. Before this commit, V8 crashed on the first call (exit 138,
SIGBUS). QuickJS passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
unofficial_napi_module_wrap_set_export sets an export of a synthetic
module from its evaluation steps. Given a source text module:

- V8 stopped the process with "Fatal error in
  v8::Module::SyntheticModuleSetExport ... must only be called on a
  SyntheticModule".
- QuickJS crashed with SIGSEGV before the module was instantiated: the
  export's variable reference does not exist yet. After that,
  JS_SetModuleExport overwrote the module's own binding. A probe set
  `export let value = 1` to "two" from outside the module.

Both engines now return napi_invalid_arg with nothing pending for any
module that is not synthetic, as the host-JS provider does. Synthetic
modules are unchanged. The bug is older than f928811.

Test: test_77 SetExportTakesOnlySyntheticModules, both engines.
set_export on a source text module, with an export's name and with an
unknown name, must return napi_invalid_arg with nothing pending. This
holds before the module is linked and again after it is evaluated, and
then the namespace's `value` must still be "one". Before this commit, V8
aborted on the first call (exit 133, the message above), and QuickJS
crashed on it (exit 139).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A synthetic module has bindings only once it is instantiated.
unofficial_napi_module_wrap_set_export before that, or with a name the
module never exported, failed differently on each engine:

- V8's SetSyntheticModuleExport throws a ReferenceError for both cases.
  The provider returned napi_generic_failure with nothing pending in
  N-API. The ReferenceError went to whatever JS was on the stack, or was
  lost when there was none.
- QuickJS threw a ReferenceError for an unknown name. Before the module
  was instantiated, JS_SetModuleExport wrote through a null variable
  reference, which crashed with SIGSEGV.

Both now return napi_pending_exception with the ReferenceError pending
in N-API. V8 takes its exception through a TryCatch. QuickJS throws its
existing ReferenceError ("Synthetic module export is not defined") for a
module that is not linked yet, without calling JS_SetModuleExport.
Setting an existing export of an instantiated module is unchanged. The
bugs are older than f928811.

Test: test_77 SetExportOfABindingThatDoesNotExistThrows, both engines.
Before the synthetic module is linked, setting its export "value" and an
unknown name must each return napi_pending_exception with a pending
error named ReferenceError. After instantiation, the unknown name must
do the same. "value" must then set with napi_ok and nothing pending, and
read back from the namespace after evaluation. Before this commit, V8
returned napi_generic_failure (9) with nothing pending for all three.
QuickJS crashed on the first call (exit 139).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
unofficial_napi_module_wrap_get_namespace on a QuickJS module that was
not instantiated (never linked, or linked but not instantiated) called
JS_GetModuleNamespace. That builds the namespace over bindings that do
not exist until the module is linked, and it crashed with SIGSEGV. This
held for source text and synthetic modules.

It now throws an Error with code ERR_MODULE_NOT_INSTANTIATED ("Module is
not instantiated") and returns napi_pending_exception. That is what the
V8 provider already did, because V8's GetModuleNamespace takes an
instantiated module only. The bug is older than f928811.

Test: test_77 NamespaceOfAModuleNotInstantiatedIsRefused, both engines.
For a source text and a synthetic module, the namespace must be refused
that way before linking and after linking. After instantiation it must
be given. Before this commit, QuickJS crashed on the first call (exit
139). V8 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
unofficial_napi_module_wrap_create_required_module_facade instantiates a
facade module that re-exports the module it wraps (`import ... from
'original'`). When the wrapped module was not instantiated yet, V8
instantiated it as part of the facade's graph. It resolved the module's
own requests with the facade's resolver, which knows only 'original':

- A module that was linked but not instantiated did not instantiate,
  and the facade failed.
- An import of 'original' would have resolved to the module itself.

The facade's failures, from compiling, instantiating or evaluating, also
returned napi_pending_exception with nothing pending in N-API. What V8
threw went to whatever JS was on the stack, or was lost. The resolver's
refusals threw nothing at all. QuickJS reports these errors as pending.

The facade's resolver now hands a request made by a known module record
to ModuleResolveCallback, as instantiate does. So the module resolves to
what it was linked to, and an unlinked request throws
ERR_VM_MODULE_LINK_FAILURE. The facade's compile, instantiation and
evaluation run in a TryCatch, and what they throw is given to N-API. A
termination stays and is what the call fails with, as elsewhere in the
module calls: ThrowTryCatchException leaves the termination's null
pending (napi_v8_fail_terminating). QuickJS's facade already linked
the module with its own links. The bugs are older than f928811.

Test: test_77 RequiredModuleFacadeInstantiatesOrLeavesItsError, both
engines.
- A module linked to a dependency but not instantiated must get its
  facade with napi_ok: default 2, both modules at status 4.
- A module whose request was never linked must fail with an error
  pending and stay at status 0.
- An evaluated module with no default export must fail with a
  SyntaxError pending.
Before this commit, V8 failed the first case with napi_pending_exception
(10). An earlier run of the last two cases alone found nothing pending
in either. QuickJS passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"V8: forget the module loader's state at the end of an env's release"
added `#include "node_api.h"` to test_65_unofficial_contextify.cc. The
test build defines NAPI_MODULE(modname,regfunc) empty on the command line,
and node_api.h defines it again. So every build of test_65 warned on both
engines:

  include/node_api.h:78:9: warning: 'NAPI_MODULE' macro redefined
  [-Wmacro-redefined]

test_65 now undefines it first, as test_71 and the other runners that
include node_api.h do. No behaviour changes. The V8 and QuickJS builds
show no such warning for test_65, and test_65 passes on both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_75_hooks_keep_termination.cc includes node_api.h (since "V8: refuse
napi_fatal_exception while V8 terminates"), and so does
test_76_termination_until_cancelled.cc (since "V8: drop the
termination's pending null when it is cancelled"). Both warned the same
way as test_65 did, on both engines:

  include/node_api.h:78:9: warning: 'NAPI_MODULE' macro redefined
  [-Wmacro-redefined]

The command line defines the macro empty. test_75 and test_76 now
undefine it first, as the other runners do. No behaviour changes. The
V8 and QuickJS builds show no such warning for either, and both pass on
both engines.

This fix was first written for test_75 alone, on a history without
test_76; test_76 gets the same three lines here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Behaviour the branch has that nothing public described. Each was checked
at the head before writing it down.

docs/realms.md, new section "Views of an ArrayBuffer":
- A view out of bounds of its shrunk resizable buffer has length 0 on
  both engines. V8 reports the view's own offset and the buffer's data
  plus that offset. QuickJS reports offset 0 and the buffer's data. A
  view over a detached buffer has length 0, offset 0 and NULL data on
  both. Measured with a probe on both engines: a Uint8Array(rab, 8, 4),
  a DataView(rab, 6, 4) and a Buffer at 10 over a 16-byte resizable
  buffer, shrunk to 4 and then detached. Before this, only a comment in
  quickjs/src/internal/napi_env.h and the test_33 comments said it.
- Near the engine's stack limit, QuickJS fails napi_get_typedarray_info
  and napi_get_dataview_info (napi_generic_failure) and
  napi_get_buffer_info (napi_invalid_arg), with nothing pending and the
  outputs left as they were, except the `type` that typedarray_info sets
  first. It reads a view through the intrinsic getters, which are calls.
  V8 does not fail there. The release audit's stack-limit probe
  (ReviewViewLayoutNearTheStackLimit), run again on this branch, gives the
  same as at "Pin each engine's outcome of an import() at release, in
  test_65": 48 of 49 reads failed on QuickJS, typed and DataView with
  status 9 and Buffer with 1, outputs at their sentinels. V8 passed.

Context tokens, in the header comment on unofficial_napi_env_hooks and in
docs/realms.md:
- Outside the release, V8's CallContextTokenHook calls the hooks as they
  are, with no TryCatch and no pending exception set aside (only the
  release path saves and restores it). A probe confirmed both effects at
  this head:
  - an assign callback's napi_throw_error left create_realm returning
    napi_ok with "from assign" pending;
  - with "callers" pending, collect_garbage ran three unassign callbacks
    that each saw an exception pending, and returned napi_ok with the
    last callback's "from unassign" pending in place of the caller's.
- In the release contract on unofficial_napi_release_env and in
  docs/realms.md: an unassign callback that makes a realm on every call
  never lets the release finish, as a finalizer that makes a new value
  every time does.

docs/realms.md, new section "Upgrading from the earlier `next`", for code
built against f928811's header. Offsets and sizes were measured with
offsetof and sizeof on f928811's include/unofficial_napi.h and on the
current one, natively and for wasm32-unknown-unknown:
- Bytecode-open options v2: 88 bytes native and 52 wasm32 in both. The
  realm was at offset 8 in both and is now at 80 and 48. So it is
  accepted and read wrongly with no error.
- Module-create options v2: was 64 and 40 bytes with the realm at 32 and
  20; now 72 and 44 with it at 64 and 40. Refused with napi_invalid_arg.
- Env hooks: f928811 had version 2, 40 and 24 bytes. Providers now accept
  only version 1 (56 and 32 bytes), so it gets napi_invalid_arg.
- main's layouts (version 1) are unaffected. Both guest backends read the
  wasm32 structs through src/guest/abi.rs, with the same checks.

Documentation only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found by the Codex review of the commits from "V8: report a module that
is not instantiated as settled in the TLA check" to "Document known
limitations: views, token hooks, upgrading from next". A synthetic
module's evaluation steps can reach native code that evaluates a source
text module importing that same synthetic module. In Node this is a
CommonJS module that requires an ES module importing it, a cycle Node
refuses with ERR_REQUIRE_CYCLE_MODULE. The synthetic module is not itself
the one asked for, so the check from "Refuse to evaluate a module while
its evaluation runs, on both engines" did not see it.

- V8 evaluates the synthetic dependency through Module::Evaluate, whose
  CHECK rejects a module that is evaluating. So evaluate, evaluate_sync
  and the require() facade aborted the process ("Check failed:
  module_status == kLinked || ...").
- QuickJS ran the module against the synthetic module's exports as they
  were.

Both providers now count the synthetic modules whose steps are running.
While any are, before evaluating they walk what the evaluation would
reach: the not yet evaluated source text modules (after evaluate
instantiates one), through the records they were linked to. Records that
were destroyed since are skipped. If one of those requests a synthetic
module that is evaluating, the call throws an Error with code
ERR_VM_MODULE_STATUS ("A synthetic module it imports is evaluating") and
returns napi_pending_exception. Nothing is walked when no steps are
running.

Test: test_77
EvaluatingAModuleThatImportsAnEvaluatingSyntheticModuleIsRefused, both
engines. A source text module imports a synthetic module. It is
instantiated, or only linked. The synthetic module's steps evaluate the
source text module through evaluate, evaluate_sync and the facade, in
turn. Each must be refused with that code and message. The steps must
finish, and the source text module must not run until it is evaluated
afterwards. Before this commit, V8 aborted on the first case (exit 133,
the CHECK above). QuickJS returned napi_ok and ran the module in every
case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found by the Codex review of the commits from "V8: report a module that
is not instantiated as settled in the TLA check" to "Document known
limitations: views, token hooks, upgrading from next". QuickJS runs
script in the middle of a link when it throws there: a request that does
not resolve, or an import the requested module does not export. The error
gets its stack through an Error.prepareStackTrace getter. From that
getter, script could reach the module calls while the first link held its
modules half linked:

- evaluate on the module being linked (status "linking") crashed with
  SIGSEGV;
- instantiate linked it again, taking it to "linked" under the first
  link;
- the facade and evaluate_sync went the same ways.

"V8: start no module instantiation while one runs" gave V8 the same guard
for its own path (an error's `code` setter), and V8 runs no getter there.
The QuickJS provider now counts the links it runs (instantiate, the link
evaluate does for a module not linked yet, the facade's). While one runs,
these calls throw ERR_VM_MODULE_LINK_FAILURE ("A module instantiation is
under way") and return napi_pending_exception, as V8 does:

- instantiate;
- evaluate and evaluate_sync on a module that is not linked;
- the facade.

evaluate now links such a module through the same counted call before
JS_EvaluateModule, instead of letting JS_EvaluateModule link it. The
failure message stays "Failed to evaluate module".

Test: test_77 NoLinkStartsWhileOneRunsFromPrepareStackTrace, both
engines. An Error.prepareStackTrace getter calls a native function once.
That function makes the module calls on the module being instantiated,
and instantiate on another one, as in NoInstantiationStartsWhileOneRuns.
Instantiation must fail with an error pending, both for an unresolved
request and for a missing export. On QuickJS the getter must have run,
and the records must be the refusal for the five instantiating calls,
"settled" for the check and ERR_MODULE_NOT_INSTANTIATED for the
namespace. Afterwards the modules must link and instantiate. The
must-run check is guarded to QuickJS, because V8 reads
Error.prepareStackTrace only when a stack is read, so no script runs
during its instantiation here. Before this commit, QuickJS crashed (exit
139). V8 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found by the Codex review of the commits from "V8: report a module that
is not instantiated as settled in the TLA check" to "Document known
limitations: views, token hooks, upgrading from next".
unofficial_napi_module_wrap_create_required_module_facade instantiated
the facade's graph with LinkRequiredFacadeOriginal and no source
resolver. "V8: instantiate the facade's module with its links, report
its errors" made that instantiation instantiate the wrapped module with
its links when it is not instantiated yet. A source-phase import in that
module (`import source x from '...'`, which V8 parses behind
--js-source-phase-imports) then made V8 call the missing resolver
without checking it (SourceTextModule::PrepareInstantiate). That crashed
with SIGSEGV.

The facade now passes ModuleResolveSourceCallback, as instantiate does.
A source-phase request resolves to the source object set on the module
it was linked to, or throws ERR_SOURCE_PHASE_NOT_DEFINED.

Test: test_77 RequiredModuleFacadeResolvesSourcePhaseImports, both
engines. The test_77 fixture now configures the runtime with
--js-source-phase-imports added to the default flags. Two modules
`import source dependency from 'dependency'; export default
dependency.marker;` are linked to a module whose source object has
marker "its source". One is instantiated and evaluated, the other only
given a facade. Both paths must give the same outcome. On V8 that must
be "ok: its source". That check is guarded to V8, because QuickJS fails
to instantiate such a module at all, the same way on both paths. Before
this commit, V8 crashed in the facade (exit 139). QuickJS passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found by the Codex review of the commits from "V8: report a module that
is not instantiated as settled in the TLA check" to "Document known
limitations: views, token hooks, upgrading from next".
unofficial_napi_module_wrap_create_required_module_facade evaluated the
facade and returned its namespace whatever the evaluation's promise was.
A module that threw (`export default 1; throw new Error('boom')`)
rejects that promise; Evaluate itself succeeds, so the TryCatch from
"V8: instantiate the facade's module with its links, report its errors"
did not see it. A module that awaits forever leaves the promise pending.
In both cases V8 returned napi_ok with a namespace, and nothing pending.
QuickJS's facade fails both. Node's checks that the evaluation is
fulfilled.

The facade now does what evaluate_sync does with the promise:
- rejected: it marks the promise handled (so the reject callback hears
  of the handler) and throws its reason;
- pending: it throws ERR_REQUIRE_ASYNC_MODULE.
It returns napi_pending_exception in both cases. A fulfilled evaluation
is unchanged. The bug is older than f928811.

Test: test_77 RequiredModuleFacadeOfAModuleThatThrowsOrAwaitsFails, both
engines.
- The facade of a linked module that throws "boom" must return
  napi_pending_exception, no namespace, "boom" pending, and the module
  at status 5.
- The facade of one that awaits forever must fail the same way, with
  ERR_REQUIRE_ASYNC_MODULE and a message starting "require() cannot be
  used on an ESM graph with top-level await".
Before this commit, V8 returned napi_ok and a namespace for both.
QuickJS passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found by the Codex review of the commits from "V8: report a module that
is not instantiated as settled in the TLA check" to "Document known
limitations: views, token hooks, upgrading from next". A module's body,
or a synthetic module's evaluation steps, can reach native code that
instantiates that same module. QuickJS's JS_LinkModule then linked the
module again. js_link_module asserts against a module that is
evaluating; that assert is compiled out of release builds, and without
it the module went from "evaluating" back to "linked" while its
evaluation ran. Instantiating a module that imports one being evaluated
did the same to the imported module through js_inner_module_linking. V8
leaves such a module as it is (PrepareInstantiate and FinishInstantiate
return early for it).

The QuickJS provider now does this:
- instantiate returns napi_ok and does nothing for a module that is
  linked already (linked, evaluating, or evaluated), as on V8;
- every link it makes (instantiate, the link evaluate makes, the
  facade's) first walks what the link would reach: the module and,
  through the records they were linked to, the modules not linked yet.
  If one of them is evaluating, it throws ERR_VM_MODULE_STATUS ("A
  module it imports is evaluating") and returns
  napi_pending_exception.
V8 instantiates such an importer, taking the evaluating module as
linked. That difference stays, and the test pins it.

Test: test_77 InstantiatingAModuleWhileItEvaluates, both engines. A
synthetic module's steps, and then a source text module's body,
instantiate the module itself and then a module that imports it. The
first must give napi_ok with the module still at status 3. The second
must give napi_ok and status 2 on V8, and the refusal above with status
0 on QuickJS. That one check is engine-specific, for the reason above.
After the evaluation, the importer must instantiate and evaluate on both
engines. Before this commit, QuickJS returned napi_ok for both calls
with each module at status 2. V8 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Found by the Codex review of the commits from "V8: report a module that
is not instantiated as settled in the TLA check" to "Document known
limitations: views, token hooks, upgrading from next". The upgrade
section that "Document known limitations: views, token hooks, upgrading
from next" added to docs/realms.md said a version-2 bytecode-open struct
built against f928811 is "accepted and read wrongly, with no error".
That overstates it. The struct passes the version and size checks, but
both providers then refuse a NULL `source_text`
(v8/src/unofficial_napi_contextify.cc and
quickjs/src/unofficial_napi.cc, in unofficial_napi_bytecode_open). The
old struct's realm sits where `source_text` is now read:
- a NULL realm reads as a NULL source text, and the call returns
  napi_invalid_arg;
- a realm handle is used as the source text's napi_value, which is
  undefined behavior.

The table cell now says it passes the checks and is read wrongly, and
the paragraph below the table gives both cases.

Documentation only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in #129 (guest C strings read in bulk, guest memory read and
written at the guest heap's fixed base), #131
(unofficial_napi_memory_pressure), #132 (the V8 checkpoint frees its own
handles), #133 (a V8 background job leaves one worker free), #134 (guest
names reach the engine with their exact bytes, V8 refuses lengths above
INT_MAX) and #135 (unit and WAT-guest tests in CI, manifest_tests finds
the checkout).

Conflicts:

- src/guest/napi.rs, src/guest/napi_js.rs: the `use super::{...}` line.
  main imports BridgeName for #134, next imports compat for the
  deprecated contextify imports. Both are kept.
- v8/src/js_native_api_v8.cc, napi_create_function: main refuses a name
  length above INT_MAX, next allocates the callback payload with the
  current realm. Both are kept, the check first, so a refused call
  allocates no payload.

Merged without a conflict, and checked:

- napi_create_function, napi_define_class and
  unofficial_napi_create_private_symbol start with next's termination
  guard (NAPI_V8_RETURN_IF_TERMINATING), then main's INT_MAX refusal,
  then the allocation (the realm-aware payload in the first two). So
  while the env terminates the termination wins (napi_pending_exception,
  nothing allocated), and after the cancel the length is refused
  (napi_invalid_arg). node_api_symbol_for has no termination guard on
  next, so it refuses the length either way. QuickJS takes the length as
  a size_t and has neither check on these calls.
- unofficial_napi_event_loop_checkpoint: #132's handle scope opens
  before next's refusal while the env terminates. A refused checkpoint
  keeps the termination's null in a persistent handle, so it leaves no
  handle in the caller's scope either.
- tests/CMakeLists.txt: main registers
  test_72_unofficial_memory_pressure on both engines and test_73 and
  test_74 on V8. next's termination and module_wrap runners were
  renumbered to test_75, test_76 and test_77 before this merge, so none
  of them shares a number with main's.
- #133 (the V8 platform, its test and the test's registration, and a
  note in src/lib.rs) merged as main has it: next has not changed the
  platform or that test, and its own changes to src/lib.rs and
  tests/CMakeLists.txt are elsewhere in those files.
- #134 and #129 on next's guest code: the realm imports, the deprecated
  contextify imports (src/guest/compat.rs) and the version 1 and 2
  option readers (src/guest/abi.rs) take names, filenames and URLs as
  value ids, and read their option structs with read_guest_bytes. So
  they read no guest C string and pass no name with a length to the
  bridge, and their struct reads already take the guest heap's fixed
  base. The bridge and the providers gained no function that takes a
  name and a length on next. After the merge the guest backends hold the
  same string reads as main.
- QuickJS keeps next's pin: main has not moved the submodule since the
  branches split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main's memory pressure signal (#131) said what each engine collects, but
not what runs when it does, which next's release contract and its realms
make a question: does the call run finalizers or token callbacks?

What a collection there frees is finalized as after any other. V8 queues
the finalizers for the env's thread and runs none in the call, nor any
JavaScript; a drain task goes to the enqueue hook, or else the next
checkpoint runs them. QuickJS runs them in the call, in the env's realm,
as collect_garbage does. Unlike collect_garbage, the call does not free
the records of collected realms, so it runs no context-token callback: a
realm it collects keeps its token until the next create_realm or
collect_garbage, or the release. The release contract, which lists where
V8 runs a collected realm's unassign callback, stays as it is.

Tests pin both, on both engines. test_72's
CriticalPressureFinalizesAsAnyCollection frees an object with a finalizer
by critical pressure: V8 has not run it when the call returns and runs it
at the next checkpoint, QuickJS has run it. test_71's
MemoryPressureLeavesACollectedRealmsTokenToCollectGarbage collects a realm
by critical pressure and checks that no token callback ran until
collect_garbage unassigns its token (V8; QuickJS takes no token hooks).
Neither is a fix: with memory_pressure changed to drain the finalizer
queue and free collected realms, they fail ("V8 ran a finalizer inside
the call", "memory pressure ran a token callback"). Each passed 50 runs in
a row on both engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The memory pressure doc, from "Say what memory_pressure finalizes, and
that it frees no realm record", says that V8 runs what a collection
frees in a task it posts through the enqueue hook, or else at the next
unofficial_napi_event_loop_checkpoint. With next's sticky termination
that does not hold while the env terminates: V8's checkpoint then fails
with napi_pending_exception and runs no finalizer, so with no enqueue
hook the finalizers wait for the first checkpoint after the cancel. The
posted task, and QuickJS in the call, do run them while the env
terminates, and a call a finalizer makes into JS is refused then, as any
call into JS is.

Say so, and pin it in test_72:

- PressureWhileTerminatingFinalizesAsTheEngineDoes, both engines:
  critical pressure while the env terminates, with no enqueue hook. V8
  runs no finalizer in the call, its checkpoint fails and runs none, and
  the first checkpoint after the cancel runs it, and its call into JS
  succeeds. QuickJS finalizes in the call; the finalizer's
  napi_get_named_property is refused with napi_pending_exception and no
  JS runs.
- V8PressureWhileTerminatingPostsTheFinalizers: with an enqueue hook,
  the posted drain runs the finalizer while the env terminates, its call
  into JS is refused, and it does not run again after the cancel.

Documentation and tests only: the behaviour is next's, so the tests pass
as they are. They fail against three mutations of the providers: a V8
checkpoint that drains the finalizers before it refuses ("the checkpoint
of a terminating env ran a finalizer"), a V8 drain task that does
nothing while the env terminates ("the posted task did not finalize
while terminating"), and a QuickJS memory_pressure that skips the
collection while the env terminates ("QuickJS did not finalize in the
call"). Each new test passed 50 runs in a row on each engine it runs on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
test_71's MemoryPressureLeavesACollectedRealmsTokenToCollectGarbage,
from "Say what memory_pressure finalizes, and that it frees no realm
record", declared the TokenLog that the context-token callbacks write to
after the EnvScope, so the log was destroyed before the env was
released. When a failed ASSERT ends the test while the realm it makes is
still alive, the release unassigns that realm's token and the callback
writes to the destroyed log. A regression that the test should report as
a failure became a memory error. The log is now declared before the env.

Test-only. Fails first: with an ASSERT_TRUE(false) injected after the
realm is made, the V8 Release+ASan build reported "AddressSanitizer:
stack-use-after-scope ... in UnassignToken" (exit 134) before this
change, and a plain test failure (exit 1) after it. Without the
injection the test passes under ASan.

Found by a Codex review of the merge's follow-ups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The memory pressure doc, from "Say what memory_pressure finalizes, and
that it frees no realm record", said that unlike
unofficial_napi_collect_garbage the call frees no record of a collected
realm. That is so on V8 only. QuickJS's unofficial_napi_collect_garbage
runs JS_RunGC and nothing else (quickjs/src/unofficial_napi.cc), and
outside the env's release QuickJS frees the records of collected realms
only in prune_collected_records, whose one caller is
create_context_record, which unofficial_napi_create_realm runs
(quickjs/src/internal/napi_contextify.cc). The doc now says that the
call frees no such record on either engine, that this differs from
collect_garbage on V8, where a collected realm keeps its context token
until the next create_realm or collect_garbage or the release, and that
QuickJS frees them at the next create_realm.

test_71's MemoryPressureLeavesACollectedRealmsTokenToCollectGarbage
already pins the V8 part (no token callback in the call, the unassign in
the next collect_garbage). A new QuickJS test in test_72,
QuickJSFreesACollectedRealmsRecordAtTheNextRealm, pins the QuickJS part
through the realm's host-defined option id, which the record holds until
it is freed: the id's finalizer has not run after critical pressure
collected the realm, nor after collect_garbage, and has run once the
next create_realm returns. The test passes as the code is, and fails
("memory pressure freed the collected realm's record", "collect_garbage
freed the collected realm's record") with QuickJS's memory_pressure
changed to free the collected records after its collection. It passed 50
runs in a row.

Found by a Codex review of the merge's follow-ups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
main now has its own tests/runners/test_76_env_cpu_profile.cc (V8, from
"Write a V8 CPU profile per env when NAPI_V8_CPU_PROFILE_DIR is set"),
so next's test_76 would share its number once main is merged. It moves
to the next free number above every runner in either tree (main has 72,
73, 74 and 76; next has 75 and 77):

- tests/runners/test_76_termination_until_cancelled.cc becomes
  test_78_termination_until_cancelled.cc, suite
  Test78TerminationUntilCancelled.

tests/CMakeLists.txt registers it under the new name, with its
NAPI_VERSION=10 definition. No doc, header, script or other test names
it. The tests are unchanged otherwise.

Test: both engines build; V8 327/327 and QuickJS 291/291 pass. The
runner keeps its cases: 20 on V8 and 15 on QuickJS, which compiles out
the V8-only ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings in #139 (a process-wide waker the host installs for V8
foreground tasks only a checkpoint runs:
wasmer_napi::set_foreground_task_waker,
snapi_bridge_set_foreground_task_waker,
EdgeV8Platform::SetForegroundTaskWaker), #138 (host-JS
napi_is_detached_arraybuffer) and #136 (a V8 CPU profile per env when
NAPI_V8_CPU_PROFILE_DIR is set).

Conflicts:

- v8/src/unofficial_napi.cc, UnofficialEnvScope: next added `releasing`
  (a release called again from a hook is refused), main added
  `cpu_profile`. Both are kept.
- v8/src/unofficial_napi.cc, before NearHeapLimitCallback: main adds
  StartEnvCPUProfile and FinishEnvCPUProfile next to its
  NearHeapLimitCallback(void* raw_env, ...), which next changed to take
  the agent. next's callback is kept, and main's two functions are
  moved onto next's agent. main keeps the CPU profiler and the profile
  sessions in g_profiler_states (EnsureProfilerState), under
  g_runtime_mu; next replaced that map with napi_agent__'s cpu_profiler
  and active_profiles, which only the isolate's thread touches. So the
  two functions read env->agent and take no lock. Both check the thread
  first (IsEnvThreadEntered, and in FinishEnvCPUProfile the session's
  owner thread), as unofficial_napi_profile_start and _stop do. The
  session is still listed with the agent's other sessions, so
  napi_agent__::Shutdown (DisposeProfilers) stops and frees it when
  FinishEnvCPUProfile can't.

Merged without a conflict, and fixed:

- src/snapi_js.rs, snapi_bridge_is_detached_arraybuffer and its test
  (#138): main looks the value up with state.get(id) and stores the
  test's values with state.insert. next moved the value table from
  HostJsEnv to its HostJsAgent, so these are state.agent.get and
  state.agent.insert, as everywhere else on next. HostJsEnv has neither
  method, so the wasm32 `js` build did not compile without this.

Merged without a conflict, and checked:

- ReleaseEnvScope: FinishEnvCPUProfile runs after next's refusal of a
  release called again, so such a call leaves the session alone, and
  before DestroyEnvInstance.
- #136 against next's release contract: the profile is stopped and
  written at the start of unofficial_napi_release_env. Then
  napi_agent__::Shutdown disposes the agent's profiler, and only then
  does the env's teardown run the cleanup hooks, the finalizers and the
  instance-data finalizer. So the JS they run, which next's release
  contract allows, is not in the profile, as v8/README.md says (the
  profile ends at the start of the release) and as on main, whose
  DestroyEnvInstance also disposed the profiler before them.
- #136 against realms: V8's CPU profiler samples the isolate, so JS
  that runs in any realm of the env is in the profile.
- #136 against the sticky termination: FinishEnvCPUProfile runs no JS
  (it reads the profile through the public getters), so after an
  uncancelled termination the profile is still written, complete and
  valid.
- #139 against the sticky termination: the waker is called when a task
  is posted, on the posting thread, and never by a checkpoint. A
  checkpoint the termination refuses (napi_pending_exception) runs no
  task and posts none, so a host that sleeps until it is woken takes
  one turn and sleeps again; it does not spin. The task stays queued
  and runs at the first checkpoint after the cancel, and the cancel
  does not call the waker for it.
- #139 against the release: the waker takes no env. Hook JS that posts
  a task during the release (the target is cleared first) calls it on
  the env's thread. Once the isolate's shutdown begins,
  ForegroundTaskRunner drops a post without calling it. Drains of
  next's finalizer queues, which hold the env's drain token, go only to
  the embedder's enqueue hook and never call the waker.
- #138 against next's host-JS realms: realms share the host's
  intrinsics and their values live in the agent's table, so the answer
  is the same for a buffer from any realm, asked in any realm, also
  after realm code replaced the ArrayBuffer getters,
  Function.prototype.call or Uint8Array, which the helper captured at
  load.
- tests/CMakeLists.txt: main registers test_76_env_cpu_profile (V8,
  Linux and macOS) and napi_v8.foreground_task_waker. next's
  test_76_termination_until_cancelled was renumbered to test_78 before
  this merge, so no runner shares a number.
- include/unofficial_napi.h, src/napi_bridge_init.cc, src/snapi.rs and
  tests/host-js/README.md take main's hunks; next's changes to them are
  elsewhere in those files.
- QuickJS keeps next's pin: none of the three changes touches it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The foreground task waker from "Wake the host when V8 queues a task only
a checkpoint runs" (#139) is called when V8 posts an immediate task to
the default platform's queue, which only
unofficial_napi_event_loop_checkpoint runs, so that a host that sleeps
until it is woken takes that checkpoint. Since "V8: keep a termination
until it is cancelled", the checkpoint of an env that terminates
refuses at once (napi_pending_exception) and runs no task. So a task
posted just before or during a termination woke the host once, the
host's turn was refused, and the cancel woke nothing: the task waited
for an unrelated wake, as it did before #139.

unofficial_napi_cancel_terminate_execution now calls the new
EdgeV8Platform::WakeForQueuedForegroundTasks, which calls the waker on
the env's thread when the isolate has used that queue, is not shutting
down, and has tasks pending (the count the platform keeps for the
isolate's shutdown is not 0). The count also holds delayed tasks and
tasks handed to a bound target, so a cancel may wake a host that then
finds nothing due and waits again, which the waker's contract already
allows. A bound target is no reason to skip: tasks posted to the queue
before it was bound stay there (found by a Codex review). A refused
checkpoint still calls no waker, so a host does not spin while the env
terminates. include/unofficial_napi.h, src/lib.rs and
v8/src/edge_v8_platform.h say so.

Test: test_78's CancelWakesTheHostForTheTasksLeftQueued (V8) posts a
task with Atomics.notify on a same-thread Atomics.waitAsync, terminates,
takes 100 refused checkpoints, cancels, and runs the task at a
checkpoint. It counts the waker's calls on the env's thread: one for
the post, none for the refused checkpoints, one for the cancel. Before
this commit it failed at the cancel ("the cancel did not wake the host
for the task left queued": 1 call, expected 2). It passed 50 runs in a
row, and V8 342/342 and QuickJS 291/291 pass. QuickJS has no platform
queue and no waker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Guard the QuickJS require facade, keep active records alive through engine
calls, and invalidate incoming links before a destroyed record can be reused.
Use weak wrappers with GC-visible dependency edges, enforce module state and
realm boundaries, and align async state and error handling across providers.

Keep termination errors catchable after cancellation, preserve Buffer
exceptions, and permit V8 error creation without a code during termination.
Document the three retained termination differences and all 19 dispositions.

Validation: V8 Release 356/356, QuickJS Release 306/306; V8 ASan 355 passed
with one sanitizer-specific skip; QuickJS Debug+ASan 306/306.
@syrusakbary
syrusakbary merged commit 18209d2 into main Nov 6, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant