Skip to content

Improve object safety - #500

Open
Vladimir Morozov (vmoroz) wants to merge 3 commits into
microsoft:mainfrom
vmoroz:PR/improve-object-safety
Open

Vladimir Morozov (vmoroz) wants to merge 3 commits into
microsoft:mainfrom
vmoroz:PR/improve-object-safety

Conversation

@vmoroz

@vmoroz Vladimir Morozov (vmoroz) commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Type of change

  • Refactor / object-lifetime hardening
  • ⚠️ Breaking API change (pre-1.0), so the version moves to 0.10. See Breaking changes below.

Why

Node-API values (napi_value) and references (napi_ref) have strict, environment-scoped
lifetimes, but the previous design spread responsibility for them across five JSValueScope
types, a separate JSModuleContext, and a "no-context" JSReference path. That made two simple
invariants hard to guarantee:

  • a napi_value is valid exactly while its JSValueScope is open, and
  • a JSReference is owned by the one JSRuntimeContext bound to its napi_env.

This change makes both invariants structural. It builds on #487, #492, and #495. Because
no-context references no longer exist, the deferred-deletion queue that #495 added for them is
removed; #495's TSFN call gate is unchanged.

What

  • Values live exactly as long as their scope. Value validity flows only through the owning
    JSValueScope, so using a value after its scope closes fails predictably. A scope must be closed
    on its own thread and in reverse order of creation; a wrong close throws instead of corrupting the
    scope stack, and a failed native close can be retried.

  • One runtime context per napi_env, disposed at env teardown. The context is stored in the
    env's instance data and resolved from it (JSRuntimeContext.FromEnv), and it is bound to the env's
    JS thread. The env's instance-data finalizer disposes it, and a native-to-managed host handshake
    does the same for the managed host, without calling into JavaScript. Only the hosting
    infrastructure disposes a context.

  • References belong to that context. Every JSReference has a context. Deletes are posted to
    the JS thread, and once the context is disposed a reference never touches the dead env. This
    removes the no-context path and the teardown edge cases that came with it.

  • Simpler JSValueScope API. Three internal scope types (RuntimeContext, Handle,
    Escapable) sit behind static factories: CreateRuntimeScope, CreateHandleScope,
    CreateEscapableScope, and CreateModuleScope, plus JSRuntimeContext.Create. A small module
    holder replaces JSModuleContext, so each loaded module resolves its own instance, and an
    IDisposable module is disposed once at env teardown.

  • Hosts, embedding, and generated code updated. The native and managed hosts, the embedding
    adapters, and the generated module entry points create or resolve the context explicitly, and
    their callbacks no longer let exceptions cross the native boundary.

  • Tests and docs. The scope and reference unit tests are rewritten for the new model, a
    worker-teardown stress test repeatedly loads and tears down the host, and the value-scope docs use
    the new factories.

Breaking changes

.NET modules built with an earlier version of Microsoft.JavaScript.NodeApi.Generator must be
rebuilt, because their generated code calls the removed JSValueScope constructor. Source changes:

  • new JSValueScope() → JSValueScope.CreateHandleScope()
  • new JSValueScope(JSValueScopeType.Escapable) → JSValueScope.CreateEscapableScope()
  • new JSValueScope(JSValueScopeType.Callback) → JSValueScope.CreateRuntimeScope()
  • new JSValueScope(JSValueScopeType.Root, env, runtime) → create the env's context once with
    JSRuntimeContext.Create(env, runtime), then open scopes with
    JSValueScope.CreateRuntimeScope(env, context)
  • JSModuleContext.Current.Module → JSValueScope.Current.Module, and scope.ModuleContext.Module
    → scope.Module
  • (JSRuntimeContext)env → JSRuntimeContext.FromEnv(env), which returns null when the env has no
    context
  • JSRuntimeContext.Dispose() is removed; the context is disposed when its env is torn down.
  • JSValueScopeType and JSValueScope.ScopeType are internal, and the NoContext scope type is gone.

Testing

Built and packed in Release; the full test suite passes on net10.0, net9.0, net8.0, and net472.

Release notes

Should this change be included in the release notes: yes — Object-lifetime safety: a
napi_value is valid exactly while its JSValueScope is open, and a JSReference is owned by the
JSRuntimeContext of its napi_env. Breaking (version 0.10): JSValueScope is created through
static factory methods, JSValueScopeType is internal, JSModuleContext is replaced by
JSValueScope.Module, JSRuntimeContext is no longer publicly disposable, and .NET modules built
with an earlier version must be rebuilt.

Copilot AI balanced review requested due to automatic review settings August 27, 2026 19:00

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Refactors Node-API object lifetimes around environment-owned runtime contexts and explicit value-scope factories.

Changes:

  • Reworks scope, reference, module-holder, and runtime-context ownership.
  • Updates hosts, embedding adapters, source generation, and Hermes integration.
  • Expands lifetime and worker-teardown testing; updates documentation and dependencies.

Reviewed changes

Copilot reviewed 30 out of 30 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
test/TestCases/napi-dotnet/worker_teardown_stress.js Adds repeated worker teardown coverage.
test/TestBuilder.cs Hardens SDK selection for test builds.
test/MockJSRuntime.cs Mocks escapable-handle behavior.
test/JSValueScopeTests.cs Tests the new scope model.
test/JSReferenceTests.cs Updates reference lifetime tests.
test/GCTests.cs Uses runtime-scope factories.
src/NodeApi/Runtime/TracingJSRuntime.cs Migrates traced callbacks to runtime scopes.
src/NodeApi/Runtime/NodeEmbeddingNodeApiScope.cs Creates an embedding runtime context.
src/NodeApi/Runtime/NodeEmbedding.cs Updates embedding callback scopes.
src/NodeApi/NodeApi.csproj Grants internal access to host and tests.
src/NodeApi/JSValueScope.cs Introduces factory-based scope construction.
src/NodeApi/JSValue.cs Removes no-context callback paths.
src/NodeApi/JSReference.cs Makes references context-owned.
src/NodeApi/JSPropertyDescriptor.cs Captures module holders.
src/NodeApi/JSError.cs Adapts error handling to new scopes.
src/NodeApi/Interop/JSThreadSafeFunction.cs Uses context-resolving callback scopes.
src/NodeApi/Interop/JSSynchronizationContext.cs Adds an inline host synchronization context.
src/NodeApi/Interop/JSRuntimeContext.cs Adds environment registration and annotations.
src/NodeApi/Interop/JSModuleContext.cs Removes the former module context.
src/NodeApi/Interop/JSModuleBuilderOfT.cs Stores module instances in holders.
src/NodeApi/Interop/JSCallbackDescriptor.cs Carries module holders through callbacks.
src/NodeApi/DotNetHost/NativeHost.cs Adds managed-host teardown registration.
src/NodeApi.Generator/ModuleGenerator.cs Generates separate AOT and hosted entry paths.
src/NodeApi.DotNetHost/ManagedHostRegistration.cs Defines the host teardown handshake.
src/NodeApi.DotNetHost/ManagedHost.cs Registers and disposes managed contexts.
src/NodeApi.DotNetHost/JSMarshaller.cs Resolves module instances from scopes.
examples/hermes-engine/HermesRuntime.cs Migrates Hermes to scope factories.
docs/features/js-value-scopes.md Documents the new factory API.
Directory.Packages.props Updates Nullability.Source.
bench/Benchmarks.cs Updates benchmark scope creation.
Suppressed comments (3)

src/NodeApi/Interop/JSRuntimeContext.cs:184

  • FromEnv uses the runtime from the most recently constructed context process-wide. Because Create publicly accepts a runtime per context, creating env A with runtime A and then env B with a stateful runtime B makes FromEnv(envA) call runtimeB.GetInstanceData(envA) and potentially return B's context. Store/resolve the runtime per environment, or require the caller's runtime explicitly instead of using this global.
    public static unsafe JSRuntimeContext? FromEnv(napi_env env)
    {
        JSRuntime? runtime = s_instanceDataRuntime;
        if (runtime is null)
        {
            return null;
        }

        runtime.GetInstanceData(env, out nint instanceData).ThrowIfFailed();

src/NodeApi/Interop/JSRuntimeContext.cs:221

  • Lazy creation makes disposal unsafe for a context that never opened a scope. Dispose() accesses this property, so it attempts JSSynchronizationContext.Create() while no JSValueScope is current (including instance-data finalization), throws, and skips the remaining context/annotation cleanup. Disposal should only dispose an already-created _synchronizationContext, without constructing one.
    /// <summary>
    /// Gets the synchronization context that marshals callbacks and continuations to the JS thread.
    /// A default one is created on first access, which happens while a scope for this context is
    /// current, because creating it requires the current scope's runtime and environment.
    /// </summary>
    public JSSynchronizationContext SynchronizationContext
        => _synchronizationContext ??= JSSynchronizationContext.Create();

src/NodeApi/Interop/JSRuntimeContext.cs:278

  • This silently overwrites an occupied slot instead of enforcing the promised one-context-per-env invariant. The embedding adapters now construct contexts repeatedly for the same lifecycle/env, so earlier contexts remain rooted while FromEnv suddenly resolves the last one; separate AOT addons are worse because the overwritten slot may contain a GCHandle owned by another CLR heap. Reuse/reject an existing registration and provide storage that cannot cross-dereference another runtime's handle.
        ((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi/JSValueScope.cs Resolved
Comment thread src/NodeApi/JSValueScope.cs Resolved
Comment thread src/NodeApi/Runtime/TracingJSRuntime.cs Resolved
Comment thread src/NodeApi/JSReference.cs Resolved
Comment thread src/NodeApi.DotNetHost/ManagedHost.cs Resolved
Comment thread src/NodeApi/DotNetHost/NativeHost.cs Resolved
Copilot AI review requested due to automatic review settings August 27, 2026 21:35

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 30 out of 30 changed files in this pull request and generated 2 comments.

Suppressed comments (2)

src/NodeApi/Interop/JSRuntimeContext.cs:278

  • This unconditionally replaces an existing context for the same runtime/environment. The five changed Node embedding callback adapters each construct a new context, so earlier contexts (including their synchronization contexts and references) remain live while the environment finalizer disposes only the last one. Reuse the context already registered for the environment, and reject duplicate registration in the factory as a safeguard.
        ((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;

src/NodeApi/Interop/JSRuntimeContext.cs:904

  • ContextHandle is intentionally never freed, so this dictionary otherwise keeps every disposed ManagedHost/NativeHost annotation strongly reachable forever. Repeated worker creation therefore accumulates disposed hosts and their load-context object graphs. Clear the owning annotations after all values have been disposed.
        if (_disposableAnnotations != null)
        {
            foreach (IDisposable annotation in _disposableAnnotations.Values)
            {

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Copilot AI review requested due to automatic review settings August 27, 2026 23:13

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.

Suppressed comments (4)

src/NodeApi/Interop/JSRuntimeContext.cs:123

  • The fixed two-slot layout is not actually “one slot per runtime.” Two NativeAOT modules loaded into the same napi_env run in separate managed runtimes, but both use ModuleContextSlot; the later module overwrites the first module’s opaque GCHandle, and the first module’s instance-data finalizer then attempts to interpret a handle owned by the other GC heap. This can leak or crash during teardown. The instance-data representation needs per-runtime ownership that does not place multiple runtimes’ handles in the same fixed slot.
    // Env instance-data layout: one GCHandle slot per runtime sharing the napi_env. Slot 0 is the
    // module context (managed host / AOT module / embedding); slot 1 is the native host context.
    // A runtime reads and writes only its own slot, so it never dereferences the other runtime's
    // GCHandle (which belongs to a separate GC heap).
    private const int ModuleContextSlot = 0;

src/NodeApi/Interop/JSRuntimeContext.cs:136

  • This strong GCHandle is intentionally never freed, so every environment permanently roots its JSRuntimeContext and everything it still references. The worker stress path creates both native- and managed-host contexts per iteration, making repeated worker teardown a guaranteed process-lifetime managed-memory leak. Keep only teardown-safe finalize-hint state alive as long as necessary, and free the context handle after the environment’s dependent finalizers can no longer use it.
    // A GCHandle rooting this context, used both as its env instance-data slot value and as the
    // finalize hint for pooled GC handles. It is intentionally never freed: pooled-handle
    // finalizers dereference it during env teardown, after this context is already disposed.

src/NodeApi/Interop/JSRuntimeContext.cs:180

  • FromEnv uses whichever runtime was registered most recently process-wide. After creating contexts with different JSRuntime instances, resolving the earlier environment calls GetInstanceData on the later runtime; stateful implementations (including the per-instance MockJSRuntime) therefore return the wrong context or fail. Track the runtime/context per environment instead of storing one global runtime.
    public static unsafe JSRuntimeContext? FromEnv(napi_env env)
    {
        JSRuntime? runtime = s_instanceDataRuntime;
        if (runtime is null)
        {

src/NodeApi/Interop/JSRuntimeContext.cs:877

  • Replacing an owning annotation of the same type drops the previous instance without disposing it or returning it to the caller. Because this API promises that the context owns these values, the previous resource is leaked permanently. Define replacement semantics and either dispose the replaced value or reject duplicate registration.
    public void SetDisposableAnnotation<T>(T value) where T : class, IDisposable
    {
        if (value is null) throw new ArgumentNullException(nameof(value));
        (_disposableAnnotations ??= new())[typeof(T)] = value;

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Copilot AI review requested due to automatic review settings August 27, 2026 23:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.

Suppressed comments (3)

Previously missed (1) — in code that hasn't changed since the last review.

src/NodeApi.DotNetHost/ManagedHost.cs:213

  • In hosted mode this context does not own the instance-data finalizer, but the native host receives the managed teardown callback only after ManagedHost construction succeeds and fills registration. If initialization throws before that point, the catch reports the JS error but leaves this context's rooting GCHandle and synchronization context registered forever because the native host has no callback with which to dispose it. Close the scope and dispose the context on the failed-initialization path.
        bool hosted = registration != null;
        JSRuntimeContext context = new(env, runtime);
        using JSValueScope scope = JSValueScope.CreateRuntimeScope(env, context);

src/NodeApi/Interop/JSModuleBuilderOfT.cs:37

  • This drops the previous ownership behavior of JSModuleContext: when module implements IDisposable, it is no longer disposed at module/context teardown. Generated module classes such as test/TestCases/napi-dotnet/ModuleClass.cs:17 rely on that contract. Register disposable module instances with the runtime context (without collapsing multiple modules onto one annotation key) so teardown still invokes Dispose().
        // Write through the holder the descriptors captured, so callbacks bound before the module
        // instance existed observe it.
        JSValueScope.Current.ModuleHolder!.Value = module;
        exports.DefineProperties(Properties.ToArray());

src/NodeApi/Interop/JSRuntimeContext.cs:280

  • This assignment silently replaces an existing context in the slot without disposing it or freeing its ContextHandle, violating the one-context-per-env invariant. The default embedding path already triggers this: RuntimeLoadingCallbackAdapter registers one context, then NodeEmbeddingNodeApiScope registers another for the same environment, permanently rooting the first context and its GC handles. Resolve/reuse the registered context in embedding callbacks/scopes, and reject or safely handle duplicate registration.
        ((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;

Copilot AI review requested due to automatic review settings August 28, 2026 00:08

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 30 out of 30 changed files in this pull request and generated 1 comment.

Suppressed comments (6)

Previously missed (2) — in code that hasn't changed since the last review.

src/NodeApi/JSValueScope.cs:175

  • With no parent and the default null env, this calls FromEnv(default). Once any context has initialized the static runtime, that invokes napi_get_instance_data with a null environment instead of rejecting the invalid factory call. Validate that an env was supplied before attempting environment lookup.
        // Inherit the parent scope's context, else recover it from the env instance data.
        context ??= _parentScope?.RuntimeContext
            ?? JSRuntimeContext.FromEnv(env)
            ?? throw new InvalidOperationException(
                "A runtime context could not be resolved for the scope.");

src/NodeApi.DotNetHost/ManagedHost.cs:213

  • The context is registered and rooted before initialization enters the try, but the native host receives the registration handle only near the end of the successful path. If initialization throws earlier, the catch returns with no handshake handle, so environment teardown cannot dispose this managed context; its instance-data GCHandle, synchronization context, and any installed resolve handlers remain rooted. Dispose the failed scope and context after reporting the JS error.
        bool hosted = registration != null;
        JSRuntimeContext context = new(env, runtime);
        using JSValueScope scope = JSValueScope.CreateRuntimeScope(env, context);

src/NodeApi/JSReference.cs:365

  • This concurrent-disposal assumption is unsafe. JSTsfnSynchronizationContext.Post checks IsDisposed and then calls _tsfn.NonBlockingCall, while Dispose can release the TSFN between those operations. Since reference finalizers now always post here during environment teardown, that race can call a released native TSFN. Gate in-flight calls and close the gate before releasing the TSFN.
        // The guard above handles an already-disposed context; if it is disposed concurrently after
        // that check, the posted delete is still a safe no-op (the napi_ref went with the env).

src/NodeApi/DotNetHost/NativeHost.cs:501

  • On .NET Framework, the managed teardown notification uses _runtimeHost->ExecuteInDefaultAppDomain. This callback closes and nulls _runtimeHost without notifying the managed host, so the later environment finalizer skips its notification and leaks _addonGCHandle plus the managed context. Run the full idempotent Dispose() path so notification occurs before the CLR host is closed.
        exports.DefineProperties(new JSPropertyDescriptor(
            "dispose", (_) => { CloseRuntimeHost(); return default; }));

src/NodeApi.Generator/ModuleGenerator.cs:309

  • This hosted-module scope inherits the ModuleHolder from the current ManagedHost.LoadModule callback. Consequently all dynamically loaded generated modules share one StrongBox; loading a second module overwrites the instance observed by callbacks from the first module. Create a fresh module holder at each module-initialization boundary while continuing to share the runtime context.
        s += "using var moduleScope = JSValueScope.CreateRuntimeScope(env);";
        s += $"return {ModuleExportsMethodName}(moduleScope, exports);";

src/NodeApi/Interop/JSRuntimeContext.cs:880

  • Replacing an owning annotation of the same type drops the previous IDisposable without disposing it, even though this API transfers disposal responsibility to the context. Either reject duplicate keys or dispose the previous value when replacing it so owned resources are not leaked.
    public void SetDisposableAnnotation<T>(T value) where T : class, IDisposable
    {
        if (value is null) throw new ArgumentNullException(nameof(value));
        (_disposableAnnotations ??= new())[typeof(T)] = value;

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Copilot AI review requested due to automatic review settings August 28, 2026 04:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 35 out of 35 changed files in this pull request and generated 4 comments.

Suppressed comments (3)

Previously missed (1) — in code that hasn't changed since the last review.

src/NodeApi/DotNetHost/NativeHost.cs:501

  • On .NET Framework this releases _runtimeHost, but environment teardown later requires that same pointer to call OnEnvironmentFinalize. After an explicit JS dispose(), the condition in NotifyManagedHostEnvironmentFinalize is false, so the managed registration GCHandle and context are never released. Use the full disposal path so the managed host is notified before the runtime-host pointer is cleared.
        // Define a dispose method implemented by the native host that closes the CLR context.
        // The managed host proxy will pass through dispose calls to this callback.
        exports.DefineProperties(new JSPropertyDescriptor(
            "dispose", (_) => { CloseRuntimeHost(); return default; }));

src/NodeApi/Interop/JSRuntimeContext.cs:291

  • This unconditionally overwrites an occupied slot. A second JSRuntimeContext.Create for the same environment leaves the first context rooted by a GCHandle that is no longer reachable through instance data, so it is never disposed. Reject an already-populated slot (and free the newly allocated handle on registration failure) to enforce the stated one-context-per-env invariant.
        ((nint*)instanceData)[s_instanceDataSlot] = ContextHandle;

src/NodeApi/JSReference.cs:374

  • The context can be disposed after the IsDisposed check but before this post. JSTsfnSynchronizationContext.Post itself also checks then calls NonBlockingCall, while Dispose can concurrently release the TSFN, producing a native use-after-release. A try/catch cannot protect that race; gate in-flight TSFN calls against release before using this path for cross-thread reference cleanup.
        if (disposing)
        {
            // Delete the reference on the JS thread (inline if already there).
            _context.SynchronizationContext.Post(
                () => runtime.DeleteReference(env, handle).ThrowIfFailed(), allowSync: true);

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi/JSValueScope.cs Resolved
Comment thread src/NodeApi.DotNetHost/ManagedHost.cs Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 35 out of 35 changed files in this pull request and generated 2 comments.

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

test/TestCases/napi-dotnet/worker_teardown_stress.js:35

  • This one-shot error listener is tied to the readiness promise. After 'ready' resolves that promise, a worker error emitted during terminate() calls reject on an already-settled promise and is silently consumed, allowing this teardown regression test to pass. Keep an error handler that fails the test for the worker's full lifetime, as worker_teardown.js does.

src/NodeApi.DotNetHost/ManagedHost.cs:240

  • The host becomes an owned annotation only after its constructor returns, but that constructor subscribes process-wide resolving handlers before several Node-API operations that can throw (ManagedHost.cs:85-135). If construction fails, the catch disposes a context that does not know about the partially constructed host, leaving those handlers subscribed and rooting the failed worker host. Make construction transactional by unsubscribing on constructor failure, or defer the subscriptions until all fallible initialization is complete.
            // Dispose the host with its environment: as a disposable annotation on the context, the
            // host's full Dispose (which unsubscribes the process-wide resolve handlers) runs when
            // the context is disposed at environment teardown. Mirrors the native host.
            context.SetDisposableAnnotation(host);

Comment thread src/NodeApi/JSValueScope.cs Resolved
Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 35 out of 35 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/NodeApi/DotNetHost/NativeHost.cs:501

  • The JS dispose hook now closes _runtimeHost without notifying the managed host. On .NET Framework, _onEnvFinalize is intentionally unset and teardown can notify managed code only through _runtimeHost; after this callback nulls that pointer, NotifyManagedHostEnvironmentFinalize() skips the notification, so the registration GCHandle, managed JSRuntimeContext, and resolve handlers remain rooted. Run the full idempotent host disposal here so the managed registration is released before the runtime-host channel is closed.
            "dispose", (_) => { CloseRuntimeHost(); return default; }));

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 35 out of 35 changed files in this pull request and generated 2 comments.

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi.DotNetHost/ManagedHost.cs Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved registration rollback, unmanaged-boundary, and scope-disposal issues can break context resolution or leak native runtimes.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

docs/concepts/runtime-model.md:117

  • This says the native reference is released when its context is disposed, but the implementation intentionally marks the context disposed before visiting references, causing JSReference.Dispose() to skip napi_delete_reference; on explicit context disposal, Node retains the reference until later environment teardown. Document that context disposal invalidates the managed reference and that the native napi_ref is reclaimed by environment teardown.
  • Files reviewed: 35/35 changed files
  • Comments generated: 4
  • Review effort level: Balanced

Comment thread src/NodeApi.DotNetHost/ManagedHost.cs Resolved
Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread examples/hermes-engine/HermesRuntime.cs Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Deferred teardown can dispose a context while an earlier scope for that context remains open under alternating context nesting.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 35/35 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Comment thread src/NodeApi/JSValueScope.cs Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Context lookup can use the wrong runtime, and reference cleanup retains a TSFN post/release race.

Review details

Suppressed comments (2)

src/NodeApi/Interop/JSRuntimeContext.cs:194

  • FromEnv uses whichever runtime registered most recently for every environment. JSRuntime is a swappable, potentially instance-backed abstraction (for example, MockJSRuntime stores instance data on the runtime instance), so after contexts A and B are created with different runtimes, FromEnv(envA) calls B's GetInstanceData; this can return no context or even dispatch the env to the wrong engine. Keep the runtime association per environment, or require the owning runtime when resolving a context.
        JSRuntime? runtime = s_instanceDataRuntime;

src/NodeApi/JSReference.cs:388

  • Posting here still has the TSFN post/release race: JSTsfnSynchronizationContext.Post can observe IsDisposed == false, then the environment cleanup path can release _tsfn before NonBlockingCall executes. That produces a native use-after-release, and this catch cannot contain it. Synchronize Post/Send with Dispose using an in-flight call gate that closes and drains before releasing the TSFN (as described in the #495 follow-up).
                _context.SynchronizationContext.Post(
  • Files reviewed: 35/35 changed files
  • Comments generated: 0 new
  • Review effort level: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Failed native scope closes can poison the scope stack, and rejected TSFN sends can wait indefinitely.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

src/NodeApi/JSValueScope.cs:364

  • CloseHandleScope/CloseEscapableHandleScope can fail, but the scope is marked disposed before those fallible calls. On failure, CurrentOrNull still points at this now-disposed scope and a retry immediately returns, permanently poisoning the thread's scope stack. Mark the scope disposed only after the native close succeeds.
        IsDisposed = true;
  • Files reviewed: 37/37 changed files
  • Comments generated: 1
  • Review effort level: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Queued synchronous TSFN calls can still deadlock during teardown, and context disposal can invalidate open scope stacks.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (2)

Previously missed (1) — in code that hasn't changed since the last review.

src/NodeApi/JSValueScope.cs:341

  • This ignores the runtimeContext argument whenever any scope is current. If that scope belongs to another context, closing it will dispose its own RuntimeContext at line 393 while the requested context remains live. Only defer onto a scope that belongs to the supplied context; otherwise dispose the supplied context directly (and let its thread-affinity check apply).

src/NodeApi/Interop/JSRuntimeContext.cs:1013

  • Dispose() can still be called while this context has an open handle scope. It marks the context disposed immediately, so that scope's later close reads RuntimeContext.EnvironmentHandle, throws ObjectDisposedException, and remains on the thread-static stack; the outer scope then cannot close either. Route same-context disposal through the idle deferral before mutating IsDisposed (or reject it while scopes are open).
        // Disposal calls thread-affine napi (the sync context's RemoveEnvCleanupHook), so it must
        // run on the thread that created the context -- where the instance-data finalizer and the
        // JS dispose functions, the only expected callers, both run.
        if (OwningThreadId != Environment.CurrentManagedThreadId)
  • Files reviewed: 37/37 changed files
  • Comments generated: 1
  • Review effort level: Balanced

A napi_value is valid exactly while its JSValueScope is open, and a
JSReference is owned by the JSRuntimeContext of its napi_env.

- Each napi_env has exactly one JSRuntimeContext, stored in the env
  instance data and disposed at env teardown by the hosting
  infrastructure only.
- The no-context scope and reference paths are removed, and with them
  the no-context deletion queue from microsoft#495.
- The native and managed hosts, embedding adapters, and generated module
  entry points create or resolve the context explicitly.

Breaking API change: JSValueScope is created through static factory
methods, JSValueScopeType is internal, JSModuleContext is replaced by
JSValueScope.Module, and JSRuntimeContext is no longer IDisposable.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi/Interop/JSRuntimeContext.cs Resolved
Comment thread src/NodeApi/JSReference.cs Resolved
Comment thread src/NodeApi/JSValue.cs Resolved
- Format instance data as a raw address in TracingJSRuntime; it is a
  native block, not a GCHandle.
- Check for a disposed reference or context in JSReference.Run before
  dispatching, so a torn-down reference cannot appear to succeed.
- Run an AddFinalizer action even when no live context can be entered,
  so its managed cleanup still happens.
Copilot AI balanced review requested due to automatic review settings November 20, 2026 02:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JSValueScope API change is breaking, and .NET modules built with an
earlier version must be rebuilt.
Copilot AI balanced review requested due to automatic review settings November 20, 2026 05:38

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Runtime lookup can use the wrong engine, finalizers can access freed memory, and queued callbacks after disposal can terminate the process; reference cleanup also leaks.

No open issues 🎉

Review effort: Balanced

This branch has not been deployed

No deployments
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.

2 participants