Title: Runtime lifetime: deferred leaks, cross-isolate sharing, and startup robustness · Issue #2010 · NativeScript/android · GitHub
Open Graph Title: Runtime lifetime: deferred leaks, cross-isolate sharing, and startup robustness · Issue #2010 · NativeScript/android
X Title: Runtime lifetime: deferred leaks, cross-isolate sharing, and startup robustness · Issue #2010 · NativeScript/android
Description: Tracking issue for lifetime problems found while fixing the intermittent worker SIGSEGV (#2006) and the ObjectManager teardown (#2008), and deliberately not fixed there. Each was verified by reading the code; none is speculative. Line nu...
Open Graph Description: Tracking issue for lifetime problems found while fixing the intermittent worker SIGSEGV (#2006) and the ObjectManager teardown (#2008), and deliberately not fixed there. Each was verified by readin...
X Description: Tracking issue for lifetime problems found while fixing the intermittent worker SIGSEGV (#2006) and the ObjectManager teardown (#2008), and deliberately not fixed there. Each was verified by readin...
Opengraph URL: https://github.com/NativeScript/android/issues/2010
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Runtime lifetime: deferred leaks, cross-isolate sharing, and startup robustness","articleBody":"Tracking issue for lifetime problems found while fixing the intermittent worker `SIGSEGV` (#2006) and the `ObjectManager` teardown (#2008), and deliberately **not** fixed there. Each was verified by reading the code; none is speculative. Line numbers are as of `fix/objectmanager-teardown`.\n\nTwo facts underpin most of these, and are worth stating once:\n\n- **V8 does not run weak callbacks when an isolate is disposed.** Anything that frees itself only from a GC finalizer leaks every instance that is still alive when a runtime goes away — and workers make that happen constantly.\n- **`v8::Persistent` and `v8::Global` differ at destruction.** `Persistent` uses `NonCopyablePersistentTraits` (`kResetInDestructor == false`), so `~Persistent` never calls into V8 and `delete po` after `Isolate::Dispose()` is safe. `Global` always resets, so destroying one after disposal writes into a freed handle table. That single difference decides which teardown window each fix belongs in.\n\nThe three windows, from `WorkerWrapper.cpp:461-503`:\n\n| Window | Isolate | JNI | Use for |\n| --- | --- | --- | --- |\n| `Runtime::DestroyRuntime()` | alive, locked | alive | anything touching `v8::Global` / `Persistent::Reset` / JS objects |\n| `~Runtime()` | **disposed** | alive, attached | JNI ref release, `delete` of `Persistent\u003cT>*` |\n| after `DetachCurrentThread` | gone | **detached** | nothing |\n\n---\n\n## Startup robustness\n\n- [ ] **Main-runtime initialization and election are not serialized.** `initRuntime` (`Runtime.java:572-576`) calls the `synchronized (Runtime.currentRuntime)` constructor and *then* `runtime.init()` — and `init()`, which reaches `initNativeScript` → `PrepareV8Runtime`, is **outside** that block. So the `s_mainThreadInitialized` check-then-act is not protected: two concurrent bootstraps could both run `InitializeV8()`, both elect a main runtime, and overwrite `Runtime::platform` / `s_mainEventLoop`. Unreachable today only by ordering — workers are always created from an already-initialized main runtime — so it becomes reachable with concurrent bootstrap (embedding host, `reloadApplication`). Wants `std::call_once` around the whole init-and-elect sequence plus a separate ready signal for workers. (Raised in review of #2006.)\n\n- [ ] **Partial native initialization is never unwound.** If `PrepareV8Runtime` throws after `Isolate::New()`, the isolate is already in `s_isolate2RuntimesCache` but the Java-side rollback only unwinds Java state, leaving the isolate and the half-built `Runtime` allocated. The fix should reuse the two-window teardown above rather than add a third cleanup path. (Raised in review of #2006.)\n\n## Leaks still outstanding\n\n- [ ] **`NativeScriptException::m_javascriptException`** (`NativeScriptException.h:166`, allocated `:48-49`) — a `Persistent\u003cValue>*` holding a **strong** handle to the JS `Error` and its captured stack. **This is the only one that grows within a live runtime**, including the long-lived main one, once per `NativeScriptException(TryCatch&)` that does not round-trip through Java. Not a simple destructor fix: the raw pointer is deliberately handed to Java as a `jlong` (`NativeScriptException.cpp:152` → `NativeScriptException.java:6`) and reclaimed at `:803-810`, so a naive destructor double-frees. Fixing it means changing that cross-language ownership contract.\n\n- [ ] **`ModuleInternal::m_loadedModules`** (`ModuleInternal.h:101`) — one `Persistent\u003cObject>` per loaded module (`ModuleInternal.cpp:376`, `:570`), never freed; `~ModuleInternal` frees its three siblings but not this one. Small (bounded by module count). **Trap:** `TempModule` inserts the same pointer under two keys (`m_modulePath` and `m_cacheKey`), so a naive delete-every-value loop double-frees — dedup by pointer.\n\n- [ ] **`CtorCacheData::instanceMethodCallbacks`** — the `MethodCallbackData*` elements (`MetadataNode.cpp:680`, `:706`, `:856`, `:899`, `:2217`), each carrying a `vector\u003cMetadataEntry>` (~200-500 B). #2008 frees the two `Persistent`s in those caches but deliberately leaves these: they may be shared across entries, so it needs an ownership analysis first.\n\n- [ ] **PODs attached to V8 objects with no finalizer at all** — `TypeMetadata` (`MetadataNode.cpp:1104`, `:1776`), `FieldCallbackData` (`:757`, `:874`, `:922`), `PropertyCallbackData` (`:787`), `ExtendedClassCallbackData` (`:1757`, which also holds a **strong** `Persistent\u003cObject>` pinning the whole JS implementation object). These leak on **every GC**, not only at teardown. Note `MetadataNode.cpp` contains no `delete` at all. They want an owner on the per-runtime `MetadataNodeCache`.\n\n## Cross-isolate sharing (not leaks — the same failure class as #2006)\n\n- [ ] **`HMRSupport`'s three global maps** (`HMRSupport.cpp:22-24`) — `g_hotData`, `g_hotAccept`, `g_hotDispose`, path-keyed, process-wide, unsynchronized, never cleaned, reached from `InitializeImportMetaObject` for every ES module. Same shape as the ES-module registry and the same `.mjs` gating, so low probability today. Should move to `RuntimeState`.\n\n- [ ] **`MetadataNode`'s three static node caches** (`MetadataNode.cpp:2315-2317`) — `s_name2NodeCache`, `s_name2TreeNodeCache`, `s_treeNode2NodeCache`, still unguarded and mutated from any runtime's thread (`GetOrCreate` inserts at `:144-151`, on **every** JS-wrapper creation via `ObjectManager::CreateJSWrapperHelper`). Not a leak — the nodes are bounded — but it is the same container-corruption shape as the `Console` crash, on a hotter path.\n\n- [ ] **The metadata tree and `MetadataReader`'s buffers.** Bigger than the caches: `m_valueData`/`m_valueLength` (`MetadataReader.cpp:320-323`) is a bump allocator, and `m_v.push_back` (`:219`, `:264`, `:328`) reallocates a vector that `GetNodeById` (`:96-98`) indexes **with no bounds check** — a realloc under a concurrent read is a use-after-free. Only reached for types absent from the static metadata, so rare but destructive.\n\n **This one cannot take a coarse lock.** `GetOrCreateTreeNodeByName` mutates those buffers *while calling back into Java* (`CallbackHandlers::GetTypeMetadata` → `Runtime.getTypeMetadata` → `Class.forName`). A function-scope mutex would be held across ART class loading and, on the `.extend()` path, dex generation — and could invert against the process-wide monitor in `Runtime.java:229` and the `r.wait()` cross-thread `callJSMethod` path. It needs a narrow recursive mutex guarding state access only, with the ordering rule: the only permitted successor is `Runtime::s_runtimeCacheMutex`; never hold it across a JNI call that can re-enter JS.\n\n## Cosmetic\n\n- [ ] **ODR violation in `IsolateDisposer.h:24-25`** — `isolateBoundObjects_` and `isolateBoundObjectsMutex_` are defined at namespace scope *in a header* included by three TUs. `nm` shows the same mangled symbol as a strong definition in each object file; the link collapses them, so it is benign in practice and the map genuinely is shared as intended, but it should be `inline` (C++17).\n\n---\n\n### Already handled elsewhere, recorded so they are not re-investigated\n\n- `g_moduleRegistry` — the process-wide, unsynchronized, path-keyed ES-module registry is reworked into per-isolate state in #1965.\n- `SIG_handler` throwing from a signal handler (which suppressed tombstones and is why all of this read as flaky tests for weeks) — removed in #2007.\n\n### Verified **not** leaks\n\n`Timers`, `BuiltinLoader`, `NsBuiltinModules`, `Events`/`ErrorEvents`/`PromiseRejectionTracker`, `WorkerInspectorClient`, the `napi` layer, `DirectBuffer`, and `WeakRef` all release correctly, mostly via `registerIsolateBoundObject` or explicit resets in `DestroyRuntime` before disposal. `JsV8InspectorClient::Domains` looked like cross-isolate corruption but is not: only the main isolate ever populates it (`__registerDomainDispatcher` is installed by `registerModules()` alone, and `WorkerInspectorClient` never installs it). Cached `jclass` statics look like dangling local refs but come from `JEnv::FindClass`, which returns process-wide **global** refs.\n","author":{"url":"https://github.com/edusperoni","@type":"Person","name":"edusperoni"},"datePublished":"2026-08-14T22:47:42Z","url":"https://github.com/NativeScript/android/issues/2010"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:2098f688-4e37-24bd-f6c2-58ad8548ba09 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E53A:1F44:101685B:150F33C:6B013377 |
| html-safe-nonce | 111eb5515d32a5eef86edc94e1725bd937b8f8810a09729741fdd514625bcec6 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFNTNBOjFGNDQ6MTAxNjg1QjoxNTBGMzNDOjZCMDEzMzc3IiwidmlzaXRvcl9pZCI6Ijc5Njc4MzA4MzMxOTUyMDEzOTkiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | ab5a8d0ef36622ef87fa366d8b4692b8bed482abeea3652e0659ae75417670a7 |
| hovercard-subject-tag | issue:5156241941 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/NativeScript/android/2010/issue_layout |
| twitter:image | https://opengraph.githubassets.com/ac6e0ba111f1764a89ee47f07d0f26755c50c400d776426d4bbc855f9b0ee189/NativeScript/android/issues/2010 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/ac6e0ba111f1764a89ee47f07d0f26755c50c400d776426d4bbc855f9b0ee189/NativeScript/android/issues/2010 |
| og:image:alt | Tracking issue for lifetime problems found while fixing the intermittent worker SIGSEGV (#2006) and the ObjectManager teardown (#2008), and deliberately not fixed there. Each was verified by readin... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | edusperoni |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/NativeScript/android git https://github.com/NativeScript/android.git |
| octolytics-dimension-user_id | 7392261 |
| octolytics-dimension-user_login | NativeScript |
| octolytics-dimension-repository_id | 29137950 |
| octolytics-dimension-repository_nwo | NativeScript/android |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 29137950 |
| octolytics-dimension-repository_network_root_nwo | NativeScript/android |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width