Skip to content

fix(runtime): keep per-isolate state live until teardown ends - #627

Merged
edusperoni merged 1 commit into
mainfrom
fix/isolate-state-lifetime
Dec 5, 2026
Merged

edusperoni merged 1 commit into
mainfrom
fix/isolate-state-lifetime

Conversation

@edusperoni

@edusperoni edusperoni commented Dec 5, 2026 •

Copy link
Copy Markdown
Collaborator

The per-isolate state contract the shared core relies on (NativeScript/runtime-common docs/DESIGN.md §4.7, decision F1): Android's. This is the iOS side of it, landing on its own before the core adopts IsolateState.

The contract

  • Caches::StateFor<T> returns, and creates on demand, the isolate's state through the whole teardown, until Caches::Remove. It is null only once the isolate's Caches is gone. This matches Android's RuntimeState::For, which stays live until the last teardown statement.
  • "Stop accepting new work" is a separate flag: Caches::BeginTeardown(), set where InvalidateIsolate() was (the start of ~Runtime), read with cache->IsTearingDown() or Caches::IsTearingDown(isolate). A caller that must not post tasks, build or adopt wrappers, register callbacks or dispatch events during teardown checks it explicitly. The static form also reads true once the Caches is gone, and the stand-in Caches that Get() returns after removal reads as tearing down, so every check that used to reject it still does.
  • Caches::ExistingStateFor<T> is unchanged: the never-create accessor, for reads off the home thread under the Locker.
  • IsValid(), InvalidateIsolate() and getIsolateId() are removed, so the compiler proves the audit below covers every caller. getGateId() is unchanged.

The flag is a std::atomic<bool>. isolateId_ was a plain int read without a lock by Runtime::IsAlive and IsolateWrapper::IsValid on other threads.

Why

The shared core cannot be written against both contracts. Before this change, iOS went null at the start of ~Runtime, before the loader quiesce, so subsystems that finish work during teardown had to reach for ExistingStateFor or keep side registries. F1 picked Android's semantics plus a separate flag, with this iOS change landing first.

Caller audit

Explicit validity checks. These were IsValid(); each is now !IsTearingDown() with the same meaning.

Caller Classification
Runtime::IsAlive fast path Refuse: liveness
IsolateWrapper::IsValid (every ObjC callback, adapters, timers, rAF, ports) Refuse: new work
EventLoop runner (enter the context or not) Same as before
PromiseRejectionTracker::DrainIfPending Refuse: dispatches events
NativeMessagePort::EmitClose, NativeMessagePort::Drain Refuse: dispatches events
ArgConverter::GetEscapeExceptionBrand Refuse: also the stand-in check after removal
LeakProbe ForEachInstance Refuse: walks Instances while teardown empties it
Runtime::~Runtime InvalidateIsolate() becomes BeginTeardown()

getIsolateId()

Caller Classification
ClassBuilder extend() / __extends (worker class-name scoping) Identity, not validity. Now getGateId(), the same id. A worker class extended during teardown used to get a _-1 suffix.

StateFor callers gated by the flag. Each of these relied on the null to refuse new work, and keeps refusing.

Caller Why it refuses
ObjectManager ReconcileOwnershipBeforeGC (GC prologue) Needed for memory safety, not only to keep behaviour. The teardown walk deletes registrations without ForgetOwnership, so managed can hold freed states. The old null kept this prologue out of them.
ObjectManager::ManageOwnership Takes over a new wrapper's handle
ObjectManager NoteStateLostCandidate Records a candidate and posts a confirmation
WrapperLifetime PhantomCallback Queues a release and posts a drain. The registration must stay linked for the teardown walk.
WrapperLifetime PrologueCallback (GC prologue) Promotes and demotes handles
WrapperLifetime::Adopt Adopts a new wrapper
WrapperLifetimeCanary StateForWrite (new record) No new record once teardown began
WrapperLifetimeCanary PostSweepAfterGC Posts a sweep
Worker::OnMessageCallback, EmitError, EmitEnded Run JS listeners
Messaging State() (one accessor for every port entry point) No port is created, delivered to or tracked after teardown begins, so CloseAllPorts orphans them all.
ModuleLoaderStateFor (one accessor for the loader's ~40 callers) QuiesceModuleLoadsForIsolate kills only the loads that exist when it runs
ModuleInternal QueuePendingScriptCache Queues a cache, posts a slice, registers the background observer
InspectorSessions constructor Registers isolate callbacks
LeakProbe isolateState / setIsolateState SPI The SPI header promises null/false once teardown has begun

StateFor callers left ungated. These read state, finish work, or fill a lazy cache that is destroyed with the Caches.

Caller Classification
ObjectManager ForgetOwnership, WrapperLifetime::Forget Cleanup. Erasing during teardown is correct.
WrapperLifetime::DrainReleases Finish. The queue is empty after DrainForTeardown, because PhantomCallback is gated.
ObjectManager ConfirmStateLost, PromiseProxy RunNextSettlement, script-cache RunScriptCacheSlice / ScheduleScriptCacheSlice / FlushScriptCaches Run only as loop entries. The loop is not pumped during ~Runtime (RunNestableV8Tasks runs V8 tasks only) and drops everything at Shutdown.
ObjectManager::GetLifetimeStats Counters
Canary StateForWrite (existing record), WrapCallback, KeepWeakCollectionKey, KeepPlainWeakCollectionKey, Find, ForEachState, BorrowedRecord Lookups. The registry closes itself in CloseForTeardown, at the start of the teardown walk, and resets every record's state there.
Canary UnwrapCallback (with create) Can still create a plain record between the start of teardown and CloseForTeardown. Such a record is handled like any record made before teardown: CloseForTeardown resets its state and clears plainRecords, and its posts are dropped by the stopped loop. After CloseForTeardown, registry->closed refuses creation. A new canary record is gated by the flag (above).
MetadataBuilder struct ctor/template caches, NewStructInstance, protocol bindings, PublishNativeSetters, native member guard Lazy caches. A struct constructor made during teardown is now cached, not rebuilt with a leaked StructTypeWrapper.
ArgConverter canary constructed instance Lookup. It used to assert if reached during teardown.
ClassBuilder RetainTrackedClasses Records a class that already has its -retain/-release pair, keeping it consistent
Console time/timeEnd, URL / URLSearchParams / Worker constructors, Interop primitive types, BuiltinLoader::GetExports, DOMException brand Lazy caches and reads
Init-time callers: ObjectManager::Init, WrapperLifetime::Init, WrapperLifetimeCanary::Init / RegisterWrapFunctions, LeakProbe::Init, InitReleasedMarkers, ArgConverter::Init, PromiseProxy::Init, Worker::InitEvents Run before teardown

ExistingStateFor callers are unchanged. Comments that stated the old contract as fact are rewritten, in Messaging.cpp, ModuleInternalCallbacks.{h,mm}, Helpers.mm, ArgConverter.mm, ObjectManager.mm, MetadataBuilder.mm, StructuredSerialization.cpp, WrapperLifetime.{h,mm} and Interop.mm.

For the reviewer

The loader and messaging are gated at their accessors, so all of their callers refuse during teardown exactly as before. A finer per-caller split is possible once the core takes them over. Messaging's process-wide g_states map is redundant with ExistingStateFor. Removing it is §4.7's follow-up (step 6, "Messaging, after F1"), not this PR.

Tests

All three runs are on the same commit, each on its own throwaway simulator.

Run Passed Failed Skipped
./run_tests.sh --temp-sim (default mode, resurrecting) 2502 0 13
./run_tests.sh --temp-sim -a (AddressSanitizer) 2497 0 18
./run_tests.sh --temp-sim --wrapper-lifetime canary:all (CI's second pass) 2502 0 13
  • The ASan run produced no AddressSanitizer reports.
  • The 5 extra ASan skips are the Worker platform options QoS specs. They call pending() under AddressSanitizer.
  • All other skips are xit/pending in the spec sources.
  • The worker, terminate, messaging, leak-probe and wrapper-lifetime suites all pass in every run.
  • Rooted mode is not run here, and CI does not run it either.
  • The suite rarely collects garbage during a teardown, so these runs do not exercise the gated GC paths much. The audit above is what covers them.

Summary by CodeRabbit

  • Bug Fixes
    • Improved runtime shutdown safety by preventing callbacks, event dispatch, and state access after teardown begins.
    • Reduced the risk of accessing or recreating runtime data during shutdown, while preserving cleanup of resources already in use.
    • Corrected worker-specific class naming to use the appropriate runtime identifier.

Caches::StateFor<T> now returns, and creates, the isolate's state through
the whole teardown, until Caches::Remove, matching Android's
RuntimeState::For. This is the contract the shared runtime-common core
needs (DESIGN 4.7, decision F1).

"Stop accepting new work" moves to a separate flag,
Caches::BeginTeardown() / IsTearingDown(), set where InvalidateIsolate()
was. Callers that relied on the early null to refuse new work now check
the flag explicitly: the ownership and rooted-mode GC prologues, phantom
callbacks, wrapper adoption and ownership tracking, the state-lost
confirmation, canary record creation and sweep posts, worker event
dispatch, the messaging and module loader accessors, script cache
queueing, inspector session registration and the leak probe SPI.

IsValid(), InvalidateIsolate() and getIsolateId() are removed. The
explicit validity checks become !IsTearingDown(). ClassBuilder scopes
worker class names by getGateId(), the same id, which is no longer
cleared during teardown. The stand-in Caches that Get() returns after
removal reads as tearing down.
@coderabbitai

coderabbitai Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Caches now tracks isolate teardown with an atomic flag. Runtime and subsystem paths use the flag to control state access, event dispatch, ownership work, and wrapper-lifetime callbacks.

Changes: Isolate teardown

Layer / File(s) Summary
Cache teardown state and runtime checks
NativeScript/runtime/Caches.*, NativeScript/runtime/Runtime.mm, NativeScript/runtime/ClassBuilder.mm, NativeScript/runtime/IsolateWrapper.cpp
Caches adds an atomic teardown flag and keeps per-isolate state access available through teardown. Runtime checks use the new flag, and class-name scoping uses the cache gate ID.
Teardown guards for state and dispatch
NativeScript/inspector/InspectorSessions.mm, NativeScript/runtime/ArgConverter.mm, NativeScript/runtime/EventLoop.mm, NativeScript/runtime/LeakProbe.mm, NativeScript/runtime/Messaging.cpp, NativeScript/runtime/MetadataBuilder.mm, NativeScript/runtime/ModuleInternal*, NativeScript/runtime/NativeScriptException.mm, NativeScript/runtime/StructuredSerialization.cpp, NativeScript/runtime/Worker.mm
Subsystem paths check teardown state before accessing state, queuing script caches, or dispatching events. Related comments describe teardown-time state and fallback behavior.
Ownership and wrapper-lifetime guards
NativeScript/runtime/ObjectManager.mm, NativeScript/runtime/Helpers.mm, NativeScript/runtime/Interop.mm, NativeScript/runtime/WrapperLifetime*
Ownership and wrapper-lifetime paths avoid state access or callback work during teardown. Comments describe deferred-release handling and callback-slot reachability.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: nathanwalker

Merge Risk: Minimal · up to ba18b

This change keeps per-isolate state available during runtime teardown and uses an explicit teardown flag to refuse new work. No concrete defect was found in the reviewed paths. Rooted-mode tests were not run, and garbage collection during teardown is lightly exercised by the suite, so a quick rooted run before merging would be reasonable.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(runtime): keep per-isolate state live until teardown ends" names the main change. The PR makes Caches::StateFor return or create per-isolate state through teardown, replacing the IsVali…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix(runtime): keep per-isolate state live until teardown ends" names the main change. The PR makes Caches::StateFor return or create per-isolate state through teardown, replacing the IsValid()-based invalidation with a BeginTeardown()/IsTearingDown() flag. The title is specific, concise, and matches the stated objective of PR #627. It omits the teardown-flag refactor and the removed APIs, which is acceptable for a title.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the cache at dawn
The teardown flag is quietly drawn
No worker message hops the gate
No wrapper joins the queue too late
The rabbit thumps, then bounds away
While guarded paths complete the day

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5084ee21-3bad-44fc-8f34-c406545f73f1
Commits

Reviewing files that changed from the base of the PR and between c08bba7 and ba18bab.

Files selected for processing: 23

  • NativeScript/inspector/InspectorSessions.mm
  • NativeScript/runtime/ArgConverter.mm
  • NativeScript/runtime/Caches.cpp
  • NativeScript/runtime/Caches.h
  • NativeScript/runtime/ClassBuilder.mm
  • NativeScript/runtime/EventLoop.mm
  • NativeScript/runtime/Helpers.mm
  • NativeScript/runtime/Interop.mm
  • NativeScript/runtime/IsolateWrapper.cpp
  • NativeScript/runtime/LeakProbe.mm
  • NativeScript/runtime/Messaging.cpp
  • NativeScript/runtime/MetadataBuilder.mm
  • NativeScript/runtime/ModuleInternal.mm
  • NativeScript/runtime/ModuleInternalCallbacks.h
  • NativeScript/runtime/ModuleInternalCallbacks.mm
  • NativeScript/runtime/NativeScriptException.mm
  • NativeScript/runtime/ObjectManager.mm
  • NativeScript/runtime/Runtime.mm
  • NativeScript/runtime/StructuredSerialization.cpp
  • NativeScript/runtime/Worker.mm
  • NativeScript/runtime/WrapperLifetime.h
  • NativeScript/runtime/WrapperLifetime.mm
  • NativeScript/runtime/WrapperLifetimeCanary.mm
Files with no reviewable changes: 1

  • NativeScript/runtime/Helpers.mm

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

@edusperoni
edusperoni marked this pull request as ready for review December 5, 2026 05:25
@edusperoni
edusperoni merged commit 01935f4 into main Dec 5, 2026
11 checks passed
@edusperoni
edusperoni deleted the fix/isolate-state-lifetime branch December 5, 2026 05:46
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