Skip to content

Commit 9d257e8

Browse files
committed
feat(runtime): canary wrapper lifetime mode
Adds "wrapperLifetime": { "mode": "canary" }, the resurrection-free model the iOS runtime (NativeScript/ios#561) and the Node-API runtimes share. A wrapper in scope is a phantom-weak canary that dies with its JS references. A masking setter/deleter/definer interceptor mirrors its JS properties into a state object that lives until Java collects the object; a canary built later gets them back. When a canary dies, the Java object table holds an object with state through a watched weak reference and releases the others; a daemon thread on the references' queue reports Java collections, and the state is let go of on the runtime's thread. JS-extended instances (extend(), interface implementations, instances Java constructed) keep a record from registration, so Java can still call into JS after their canary died: the runtime rebuilds the canary with the instance's prototype, implementation object, internal fields and state. Scope "extended" (default) makes canaries of JS-extended instances only; other wrappers keep the resurrecting lifetime. "all" covers every wrapper of a Java object. ns:runtime gains getWrapperClassCounts() and canary counters.
1 parent 15d44aa commit 9d257e8

23 files changed

Lines changed: 1537 additions & 23 deletions

‎docs/ns-builtin-modules.md‎

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ wrapper.
104104
| `setConfig(key, value)` | Sets a runtime config key. Throws `TypeError` on an unknown key, an invalid value, or (for process-wide keys) when called from a worker isolate. |
105105
| `getConfig(key)` | Returns the current value of a config key. Throws `TypeError` on an unknown key. Readable from any isolate. |
106106
| `getWrapperLifetimeStats()` | Wrapper lifetime counters for the calling isolate (see [Wrapper lifetime](#wrapper-lifetime)). A fresh object on every call. |
107+
| `getWrapperClassCounts()` | Per Java class name, the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). |
107108
| `escapeException(x)` | Returns an `Error` branded so that, when it is thrown back across a native callback boundary, the native caller receives the original native exception `x` carries rather than the runtime's wrapper exception. Idempotent: a branded error is returned unchanged. Throws `TypeError` when called with no argument. The global `interop.escapeException` is this same function (see [Legacy globals](#legacy-globals)). |
108109

109110
*Platform note (Android):* the original exception is the Java throwable `x`
@@ -118,7 +119,7 @@ Config keys:
118119
| key | values | scope | default |
119120
|---|---|---|---|
120121
| `debug` | comma-separated category list, e.g. `"esm,fetch"` | process-wide (main-isolate writes only; read live by every isolate) | the `NS_DEBUG` environment variable, or `""` |
121-
| `wrapperLifetimeMode` | `"resurrecting"` | process-wide, read-only | the app config `"wrapperLifetime": { "mode": … }`, or `"resurrecting"` |
122+
| `wrapperLifetimeMode` | `"resurrecting"` \| `"canary"` | process-wide, read-only | the app config `"wrapperLifetime": { "mode": … }`, or `"resurrecting"` |
122123
| `wrapperLifetimeScope` | `"extended"` \| `"all"` | process-wide, read-only | the app config `"wrapperLifetime": { "scope": … }`, or `"extended"` |
123124

124125
iOS additionally registers `releasedObjectPolicy`, which governs access to a
@@ -160,7 +161,7 @@ top-level `"wrapperLifetime"` object of the app's `package.json`, the same key
160161
iOS reads:
161162

162163
```json
163-
{ "wrapperLifetime": { "mode": "resurrecting", "scope": "extended" } }
164+
{ "wrapperLifetime": { "mode": "canary", "scope": "all" } }
164165
```
165166

166167
A value that is not an object, or an unknown `mode` or `scope`, logs a warning
@@ -188,6 +189,55 @@ every build on cold paths only:
188189
| `collected` | wrappers released because Java had collected their object |
189190
| `releasedExplicitly` | links released through `__releaseNativeCounterpart` |
190191
| `releasedAccesses` | lookups of the Java object of a wrapper whose link was released or whose Java object Java had already collected: calling its methods, using its fields or passing it to Java. Resolving an overloaded method looks its arguments up too, so one call can count more than once |
192+
| `canaryStates` | `"canary"` only: state objects created to hold JS properties |
193+
| `canaryNativeDeaths` | `"canary"` only: state objects let go of because Java collected their object |
194+
| `canaryInterceptedWrites` | `"canary"` only: writes to canaries the write handler saw. Other wrappers have no handler |
195+
| `canaryRebuilds` | `"canary"` only: canaries built anew for a JS-extended instance whose previous canary died while Java kept the object |
196+
197+
In `"canary"` mode, `weakened` counts objects held weakly because their
198+
canary died while they had JS state, and `collected` counts canaries whose
199+
object had none, which Java no longer holds for JS.
200+
201+
`"canary"` is the resurrection-free model the iOS runtime and the Node-API
202+
runtimes share. A wrapper in scope is a canary: a phantom-weak JS object that
203+
dies with its JS references.
204+
205+
- **State.** A masking named interceptor (a setter, a deleter and a definer,
206+
nothing that runs on reads) mirrors every JS property written to a canary
207+
into a separate state object and lets V8 apply the write to the canary too,
208+
so reads cost what they cost on a plain object. A write that resolves to a
209+
Java field, another inherited accessor or a read-only property is not state.
210+
The state lives until Java collects the object; a canary built later for the
211+
same object gets its properties back, attributes, accessors and symbol keys
212+
included.
213+
- **Java's side.** While a canary is alive, Java holds its object strongly.
214+
When it dies, Java holds an object with state weakly and releases any other.
215+
A thread watching those weak references tells the runtime when Java collects
216+
an object, and its state is let go of on the runtime's thread.
217+
- **JS-extended instances** (`extend()`, interface implementations, Java
218+
objects of those classes) keep a record from the moment they are registered,
219+
whether or not JS wrote to them, so that Java can still call into JS after
220+
their canary died: the runtime builds a new canary with the instance's
221+
prototype, implementation object and state.
222+
- **Scope.** `"extended"` (default) makes canaries of JS-extended instances
223+
only; every other wrapper keeps the `"resurrecting"` lifetime, so its JS
224+
properties still survive while Java holds its object. `"all"` makes every
225+
Java object's wrapper a canary, Java arrays included. Array buffers backed by
226+
Java buffers keep the `"resurrecting"` lifetime in both.
227+
228+
What this trades: nothing JS references is released under it, and the state of
229+
an object Java holds keeps everything it references. So state that references
230+
its own object (a closure over `this`, `this.onTap = this.onTap.bind(this)`,
231+
a `WeakMap` value naming it) keeps the object alive, through Java, for as long
232+
as the cycle lasts; break such back references with a `WeakRef`.
233+
`getWrapperClassCounts()` shows which classes grow across a repeated journey.
234+
Other limits, as on iOS: `Object.freeze`, `seal` and `preventExtensions` throw
235+
on a canary; index-keyed properties are not mirrored and die with the canary;
236+
a write through an object whose prototype is a canary lands on that object.
237+
A canary built after another died is a new JS object, which `===` cannot tell
238+
because nothing kept the old one, but which keys `WeakMap`, `WeakSet`,
239+
`WeakRef` and `FinalizationRegistry` entries separately.
240+
`__releaseNativeCounterpart` drops the object's state with its link.
191241

192242
Remote-module security (`security.allowRemoteModules`,
193243
`security.remoteModuleAllowlist`) is **not** part of this surface. Those

‎test-app/app/src/main/assets/app/mainpage.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ require("./tests/stringConversionTests");
6161
require("./tests/testsForTypescript");
6262
require("./tests/testGC");
6363
require("./tests/testWrapperLifetime");
64+
require("./tests/testWrapperLifetimeModes");
6465
require("./tests/testsMemoryManagement");
6566
require("./tests/testFieldGetSet");
6667
require("./tests/extendedClassesTests");

‎test-app/app/src/main/assets/app/tests/testNsRuntime.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ describe("ns:runtime", function () {
1111
// The export set is public API, declared alongside docs/ns-builtin-modules.md
1212
// — all of them change together.
1313
it("exposes exactly the declared surface", function () {
14-
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperLifetimeStats", "setConfig"]);
14+
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "getConfig", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
1515
});
1616

1717
it("rejects unknown keys", function () {

‎test-app/app/src/main/assets/app/tests/testWrapperLifetime.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ describe("Wrapper lifetime", function () {
2121
});
2222

2323
it("reports the configured mode and scope (" + mode + "/" + scope + ")", function () {
24-
expect(["resurrecting"]).toContain(mode);
24+
expect(["resurrecting", "canary"]).toContain(mode);
2525
expect(["extended", "all"]).toContain(scope);
2626
});
2727

@@ -37,7 +37,8 @@ describe("Wrapper lifetime", function () {
3737
it("exposes numeric counters", function () {
3838
var stats = runtime.getWrapperLifetimeStats();
3939
expect(Object.keys(stats).sort()).toEqual(
40-
["collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]);
40+
["canaryInterceptedWrites", "canaryNativeDeaths", "canaryRebuilds", "canaryStates",
41+
"collected", "releasedAccesses", "releasedExplicitly", "resurrections", "weakened"]);
4142
Object.keys(stats).forEach(function (key) {
4243
expect(typeof stats[key]).toBe("number");
4344
});

0 commit comments

Comments
 (0)