Repository navigation
fix(runtime): keep per-isolate state live until teardown ends - #627
Conversation
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.
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
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 adoptsIsolateState.The contract
Caches::StateFor<T>returns, and creates on demand, the isolate's state through the whole teardown, untilCaches::Remove. It is null only once the isolate's Caches is gone. This matches Android'sRuntimeState::For, which stays live until the last teardown statement.Caches::BeginTeardown(), set whereInvalidateIsolate()was (the start of~Runtime), read withcache->IsTearingDown()orCaches::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-inCachesthatGet()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()andgetIsolateId()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 plainintread without a lock byRuntime::IsAliveandIsolateWrapper::IsValidon 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 forExistingStateForor 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.Runtime::IsAlivefast pathIsolateWrapper::IsValid(every ObjC callback, adapters, timers, rAF, ports)EventLooprunner (enter the context or not)PromiseRejectionTracker::DrainIfPendingNativeMessagePort::EmitClose,NativeMessagePort::DrainArgConverter::GetEscapeExceptionBrandLeakProbeForEachInstanceInstanceswhile teardown empties itRuntime::~RuntimeInvalidateIsolate()becomesBeginTeardown()getIsolateId()ClassBuilderextend()/__extends(worker class-name scoping)getGateId(), the same id. A worker class extended during teardown used to get a_-1suffix.StateForcallers gated by the flag. Each of these relied on the null to refuse new work, and keeps refusing.ObjectManagerReconcileOwnershipBeforeGC(GC prologue)ForgetOwnership, somanagedcan hold freed states. The old null kept this prologue out of them.ObjectManager::ManageOwnershipObjectManagerNoteStateLostCandidateWrapperLifetimePhantomCallbackWrapperLifetimePrologueCallback(GC prologue)WrapperLifetime::AdoptWrapperLifetimeCanaryStateForWrite(new record)WrapperLifetimeCanaryPostSweepAfterGCWorker::OnMessageCallback,EmitError,EmitEndedState()(one accessor for every port entry point)CloseAllPortsorphans them all.ModuleLoaderStateFor(one accessor for the loader's ~40 callers)QuiesceModuleLoadsForIsolatekills only the loads that exist when it runsModuleInternalQueuePendingScriptCacheInspectorSessionsconstructorLeakProbeisolateState/setIsolateStateSPIStateForcallers left ungated. These read state, finish work, or fill a lazy cache that is destroyed with the Caches.ObjectManagerForgetOwnership,WrapperLifetime::ForgetWrapperLifetime::DrainReleasesDrainForTeardown, becausePhantomCallbackis gated.ObjectManagerConfirmStateLost,PromiseProxyRunNextSettlement, script-cacheRunScriptCacheSlice/ScheduleScriptCacheSlice/FlushScriptCaches~Runtime(RunNestableV8Tasksruns V8 tasks only) and drops everything atShutdown.ObjectManager::GetLifetimeStatsStateForWrite(existing record),WrapCallback,KeepWeakCollectionKey,KeepPlainWeakCollectionKey,Find,ForEachState,BorrowedRecordCloseForTeardown, at the start of the teardown walk, and resets every record's state there.UnwrapCallback(withcreate)CloseForTeardown. Such a record is handled like any record made before teardown:CloseForTeardownresets its state and clearsplainRecords, and its posts are dropped by the stopped loop. AfterCloseForTeardown,registry->closedrefuses creation. A new canary record is gated by the flag (above).MetadataBuilderstruct ctor/template caches,NewStructInstance, protocol bindings,PublishNativeSetters, native member guardStructTypeWrapper.ArgConvertercanary constructed instanceClassBuilderRetainTrackedClassesConsoletime/timeEnd,URL/URLSearchParams/Workerconstructors,Interopprimitive types,BuiltinLoader::GetExports, DOMException brandObjectManager::Init,WrapperLifetime::Init,WrapperLifetimeCanary::Init/RegisterWrapFunctions,LeakProbe::Init,InitReleasedMarkers,ArgConverter::Init,PromiseProxy::Init,Worker::InitEventsExistingStateForcallers are unchanged. Comments that stated the old contract as fact are rewritten, inMessaging.cpp,ModuleInternalCallbacks.{h,mm},Helpers.mm,ArgConverter.mm,ObjectManager.mm,MetadataBuilder.mm,StructuredSerialization.cpp,WrapperLifetime.{h,mm}andInterop.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_statesmap is redundant withExistingStateFor. 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_tests.sh --temp-sim(default mode, resurrecting)./run_tests.sh --temp-sim -a(AddressSanitizer)./run_tests.sh --temp-sim --wrapper-lifetime canary:all(CI's second pass)Worker platform optionsQoS specs. They callpending()under AddressSanitizer.xit/pendingin the spec sources.Summary by CodeRabbit