You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
fix(runtime): resolve fresh call arguments again after an explicit release - #2151
Current behavior. When Java calls a JS method with an object JS has never seen, Runtime.packageArgs registers it for the call and passes its id with FreshArg set. ArgConverter::ConvertJavaArgsToJsArgs then wraps it straight from that id, without asking Java again, provided no wrapper exists for the id yet.
JS runs between that registration and the argument conversion: the method lookup on the JS object (a getter, a Proxy get trap) happens first. If that JS reaches the same Java object another way (say a static field), passes it to __releaseNativeCounterpart and lets the wrapper be collected, Java drops the id and native drops its registration. The fast path then sees no wrapper for the id, links a new one to an id Java no longer knows, and the first use of the argument fails:
Error: Failed to get Java object by ID. id=338124, class=java/lang/StringBuilder.
com.tns.NativeScriptException: No weak reference found. Attempt to use cleared object reference id=338124
This reproduces on main in both single- and multithreaded JS.
New behavior.ObjectManager counts explicit releases (ReleaseNativeCounterpart). Runtime::CallJSMethodNative records the count in JavaCallArgs before any of the call's JS runs. The fast path is taken only while the count has not moved. Otherwise the argument is resolved through Java (GetOrCreateObjectId) like any other object, which registers it again under a new id. On the hot path this adds one load and compare. The counter is per-runtime ObjectManager state and needs no lock, since it is only touched under the isolate lock.
An explicit release is the only way a fresh id can be dropped while its Java object is alive. A collected wrapper's flush only weakens the Java entry, and the native registration stays until Java reports the object dead. ReleaseIfCollected only fires for collected Java objects.
Not covered here: in multithreaded JS, Java registers the argument before the calling thread takes the isolate lock. Another JS thread could in principle reach, release and collect the object in that window, before the count is recorded. That needs the object to be published to the other thread mid-call. Closing it would take a Java-side change, so it is left out.
Does your commit message include the wording below to reference a specific issue in this repo?
No.
Related Pull Requests
#2127 found and fixed the same issue on the wrapper lifetime canary stack, where the guard reuses the canary release counter. This PR fixes it on main independently of that mode.
Yes. testReleaseNativeCounterpart.js adds a spec built on a new fixture, FreshArgCaller. The fixture passes a new StringBuilder to a JS interface implementation and also exposes it through a static field. The spec's take getter reads that field, releases the result, runs gc() and returns the method. The spec checks that the argument is still usable and that the lookup ran once.
On an arm64 emulator (android-36.1 google_apis image), full suite:
without the fix
with the fix
multithreaded JS (as committed)
1789 specs, 1 failure (the new spec, error above)
1789 specs, 0 failures
single-threaded JS
1789 specs, 1 failure (the new spec, error above)
1789 specs, 0 failures
Summary by CodeRabbit
Bug Fixes
Improved reliability when JavaScript accesses a Java object during a call that triggers object release and garbage collection. The call now continues with the correct object value, avoiding stale-wrapper behavior.
Added coverage for this scenario, including verifying that the object lookup runs only once.
…lease
Java registers an object argument it has not seen before for the call
and passes its id with FreshArg set, so native wraps it from that id
without asking Java again. JS that runs before the arguments are
converted (the method lookup: a getter, a Proxy trap) can reach the same
object another way, pass it to __releaseNativeCounterpart and let the
wrapper be collected. The fast path then found no wrapper for the id and
linked a new one to an id Java no longer knew, so the first use of the
argument threw "No weak reference found".
ObjectManager now counts explicit releases. A call records the count
before any of its JS runs, and the fast path is taken only while it has
not moved; otherwise the argument is resolved through Java as for any
other object.
The runtime now tracks native counterpart releases during JavaScript calls. Argument conversion uses that count to decide whether to create a fresh wrapper. A regression test covers a method lookup that releases the pending argument.
Changes: Fresh argument release guard
Layer / File(s)
Summary
Track releases during JavaScript calls test-app/runtime/src/main/cpp/ObjectManager.h, test-app/runtime/src/main/cpp/ObjectManager.cpp, test-app/runtime/src/main/cpp/ArgConverter.h, test-app/runtime/src/main/cpp/Runtime.cpp
ObjectManager counts native counterpart releases. CallJSMethodNative records the count before JavaScript runs.
Guard fresh argument conversion and test release during lookup test-app/runtime/src/main/cpp/ArgConverter.cpp, test-app/app/src/main/java/com/tns/tests/FreshArgCaller.java, test-app/app/src/main/assets/app/tests/testReleaseNativeCounterpart.js
Argument conversion creates a fresh wrapper only if the release count has not changed since the call began. The new fixture and regression test cover a release during method lookup.
NativeScript/android#2127: It guards the same fresh-argument path against releases during a call, using a different condition.
Suggested reviewers:nathanwalker
Merge Risk: Low · up to cfd7b
The change fixes a failure where a fresh argument is released by JavaScript before it is converted. The remaining concern is a rare, unconfirmed edge case in which a failed wrapper creation could keep an object alive. The risk of merging is low.
Pre-merge checks: 4
Check name
Status
Explanation
Description Check
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
The title names the fix and its scope: the runtime re-resolves fresh call arguments after an explicit release. The changeset matches this. It adds a release counter in ObjectManager, records it in Jav…
Linked Issues check
Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check
Check skipped because no linked issues were found for this pull request.
Full details: Title check
Explanation
The title names the fix and its scope: the runtime re-resolves fresh call arguments after an explicit release. The changeset matches this. It adds a release counter in ObjectManager, records it in JavaCallArgs at call start, and gates the fresh-argument fast path in ArgConverter on that counter being unchanged. It also adds a regression test with the FreshArgCaller fixture. The title is specific and follows the conventional-commit style, so it passes.
Finishing Touches
Generate unit tests (beta)
Commit to this branch
Create a new PR
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.
156-156: Minor · Stability & Availability · Quick win
Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.
Release replacement registrations when wrapper creation fails.
If lookup releases fresh id A, this guard now selects the fallback. GetOrCreateObjectId can register the argument strongly as B. If CreateJSWrapper then throws before Link, for example on a native allocation, no wrapper owns B. The helper has no rollback. (raw.githubusercontent.com)
ReleaseUnwrappedArgs still reads A from the packed arguments. It cannot release B, so the failed call retains the argument indefinitely. Track the replacement registration until linking succeeds. On failure, release that registration if it still has no wrapper. Preserve wrapper ownership on success. (raw.githubusercontent.com)
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.
### Description
Third of the stacked wrapper-lifetime series (on #2126), the Android
port of NativeScript/ios#561. Adds `"wrapperLifetime": { "mode":
"canary" }`, the resurrection-free model the iOS runtime and the
Node-API runtimes (NativeScript/runtimes) share. The default stays
`"resurrecting"`, so nothing changes unless an app opts in.
#### Current behavior
A wrapper's `kFinalizer` resurrects it while Java may hold its object,
and weakens the Java side. Everything the wrapper's JS properties
reference is finalized in the same collection, so its Java objects are
weakened too and Java can collect them under the live wrapper (#2126
reproduces it on a plain holder, where touching the child throws
`Attempt to use cleared object reference`; this PR's spec reproduces it
on a JS-extended holder, where it throws `The JavaScript instance no
longer has available Java instance counterpart`). The model also depends
on `v8_resurrecting_finalizers.patch`.
#### New behavior
- **The wrapper is a canary.** Every wrapper of a Java object gets a
phantom (`kParameter`) weak handle and no finalizer: it dies with its JS
references. While a canary is alive, Java holds its object strongly.
- **State is mirrored onto a separate object.** A masking named
interceptor (setter, deleter, definer; nothing on reads) on the instance
templates whose canaries are in scope copies each JS property write into
a null-prototype state object and declines, so V8 applies it to the
canary too and reads cost what they cost on a plain object. A write that
resolves to a Java field, another inherited accessor or a read-only
property is not state; shadowing a prototype member is. A canary built
later for the same object is hydrated from the state, attributes,
accessors and symbol keys included. The handler code is a port of iOS's.
- **When a canary dies**, the next JS↔Java crossing (or a short-delayed
task scheduled from a GC epilogue) settles it in one JNI call: Java
holds an object that has state through a watched `WeakReference`, and
releases any other from its object table. A canary built again before
the settle is detected and its object stays strong.
- **Noticing Java's collection.** Watched references share one
`ReferenceQueue`, drained by a process-wide daemon thread
(`WrapperLifetimeWatcher`) that removes the cleared entries and passes
the ids to the owning runtime through a mutex-guarded inbox; the runtime
lets go of the state on its own thread, from an event loop task or the
next settle. The watcher never touches V8.
- **JS-extended instances** (`extend()`, interface implementations,
interface proxies, and instances Java constructed through
`createJSInstance`) keep a record from the moment they are registered,
whether or not JS wrote to them: their class, and a pointer to class
data the records of one class share: the prototype,
`CallSuper`/`Metadata` fields and implementation object the instance
registered with, and the class's own instance template (owned by the
metadata cache). The class data is reference-counted and reused while
those values match, so a record adds no handle at registration and one
(its state) once JS writes; an interface implementation, whose
implementation object and prototype are per instance, gets class data of
its own. Java can call into such an object after its canary died, and
the canary is rebuilt (holding the Java object strongly again) instead
of handing out a plain base-class wrapper or throwing `JavaScript object
for Java ID N not found`. The first rebuild makes the canary from the
class's own template (skipping `SetPrototype` when the prototype already
matches), links and hydrates it, then clones it into the record's shell,
unlinked and before JS can reach it, so the shell holds nothing JS adds
later (`#private` brands, weak-collection keys). A later rebuild is
`shell->Clone()` and `Link`, with no hydration. Every write to the state
(rewrite, define and delete paths, through `StateChanging`) drops the
shell first, so it never keeps a value JS has since overwritten or
deleted, and the next rebuild hydrates and copies a new one. On a phone
(`canary`/`all`, release build): a repeat rebuild costs about 3.8–4.3 µs
at 0, 4 and 16 properties (7.4, 14.6 and 27.5 µs for interface
implementations before this work); the first rebuild costs about what it
did before; `new` of an extended class and a GC per dead extended
wrapper with state are unchanged (about 5.0–5.2 µs and 2.0–2.1 µs).
`CallJSMethodNative` and hinted Java→JS arguments rebuild from the id
Java passed, through `GetLinkedJsObjectByJavaObject`, without asking
Java for the id again (ids are never reused; `strengthenInstance` is the
only upcall); when the object is gone the rebuild comes back empty and
the call is still dropped with a warning (below). Method returns, field
reads and other arguments go through `CreateJSWrapperHelper`, which
looks the record up once and rebuilds or links with it.
- **Cheaper write handlers.** The handlers take their `ObjectManager`
from the handler data rather than a thread-local and an isolate lookup,
find the canary once per write, and reach its record through a pointer
cached on the wrapper's registration (cleared when the record is erased
and at teardown). A write that resolves to a Java instance field runs
the field's setter from the handler (class prototypes keep their fields'
accessor data under a private key), and a state of plain data properties
is hydrated into a rebuilt canary with data defines. On a phone (release
build, medians): an existing-name expando write on a canary 308 → 235
ns, a new name 630 → 487 ns, a Java field write one level up 748 → 615
ns.
- **Write mirroring of a known name.** A rewrite of a name the state
already holds as a plain, writable data property is mirrored with one
`Set` on the state, without looking the name up there first: the name is
cached for its record on its first rewrite (not when it is added, which
would slow new-name writes), and dropped before a delete or define of
the name, when the record is erased and at teardown; a state that stops
being plain is never served from the cache. The handlers also find their
`ObjectManager` and the wrapper's registration without V8 calls (the
manager now comes from an isolate data slot rather than the handler
data, and the link field is read directly), and the uncached path is out
of line. On a phone (release build, `canary`/`all`): existing-name
writes take ×0.76–0.80 of their previous time (instructions per write in
a hot loop 2318 → 1794); new-name writes, deletes and defines are
unchanged.
- **Write-path and record costs.** Measured on a phone (release build,
`canary`/`all`, 6 rounds with an A/A copy, ratios of medians within a
round):
- *Java field writes:* the write handler caches which Java field
accessor a write lands on, by the name written and the canary's
prototype. A hit rechecks the canary's state and the prototypes between
the canary's prototype and the accessor's owner; field accessors are
non-configurable, so the owner needs no recheck. A write of a name with
no entry reads one line of name tags and makes no V8 call. A field on
the class's own prototype 468 → 203 ns, one prototype up 597 → 318 ns,
four up 766 → 465 ns, the same on a canary with state 519 → 252 ns, one
name written through 8 prototypes in turn 641 → 349 ns.
- *First and new-name writes:* the first write makes the state holding
the property, from the canary handle the handler already has. A record
keeps the tags of the first six names the handlers added to its plain
state, so a write of any other name skips the state lookup (a stale tag
only sends it down the path that handles both).
- *Records:* the shared class data above replaces four global handles
per extended record (global-handle bytes per canary 160 → 32 with no
state and 192 → 64 with three names; native bytes about 430 → 212), and
records live in the radix object id index instead of an `unordered_map`.
- Together: a first write ×0.76–0.80, a new name ×0.91–0.92, `extend()`
construction with 1, 3 or 5 fields ×0.91–0.92, a full GC with 10,000
live stateful canaries ×0.68–0.70; existing-name rewrites, expando reads
and field writes unchanged.
- *Fast-mode states:* a state is a clone of one empty, null-prototype,
fast-mode object instead of a dictionary-mode `Object::New`, so states
that get the same names in the same order share map transitions. Against
the commits before it: a three-name state 208 → 104 bytes, a first write
×0.75–0.77, a new name ×0.85, construction ×0.92–0.94, the full GC
×0.80–0.88. **Trade-off:** rewriting a name the state already has costs
×1.11–1.12 (about 106 → 118 ns), and ×1.07 across 512 objects. Accepted
for the memory and construction gains.
- Against this PR before these commits, all of the above: first write
×0.60, new name ×0.77–0.78, construction ×0.83–0.84, full GC ×0.57,
rewrites ×1.07–1.11.
- After folding into this PR and rebasing the stack onto `main`, the top
of the stack against its previous tip (S20 FE, 4 rounds with an A/A
copy; `main` moved too, which explains the method-call rows):
| row | ratio (min–max) | A/A |
|---|---|---|
| Java field write, own prototype (`F0`) | 0.42 (0.41–0.42) | 1.00 |
| Java field write, one up (`Ext0`) | 0.52 (0.51–0.53) | 1.00 |
| first write `Ext0` / `F0` | 0.59 / 0.62 | 0.99 / 0.97 |
| new name `Ext0` / `F0` | 0.77 / 0.86 | 0.99 / 1.01 |
| existing name `Ext0` / `F0` | 1.11 / 1.09 | 0.99 / 0.98 |
| existing name, 512 objects | 1.09 | 1.00 |
| `extend()` construct, 1 / 3 / 5 fields | 0.82 / 0.84 / 0.81 |
1.01–1.02 |
| full GC, 10,000 stateful canaries | 0.64–0.66 | 0.95–0.99 |
| heap per 3-name canary | 0.50 (208 → 104 B) | 1.00 |
| expando reads | 0.98–1.06, inside the A/A band | 0.94–1.02 |
| Java method call `getF()` | 0.95–0.96 | 1.00 |
- **Java→JS calls on an object Java let go of are dropped.** Java clears
a weak reference before it finalizes the object, so a call a
`finalize()` makes into a JS-implemented method has no registered object
to run on. Such a call used to throw `Cannot find object id` and end the
rest of the finalizer; like other Java→JS calls without a target, it is
now logged with a warning and dropped, and a primitive return gets its
type's default. This also applies in the default `"resurrecting"` mode:
to a `finalize()` reaching a resurrecting wrapper's weakened object, to
a Java callback into an object whose link was released, and to the
posted single-threaded call path when the binding had stamped an id. A
call on an object that was never registered (a superclass constructor
calling an override before `initInstance`) still throws.
- **Fresh-argument fast path.** A Java→JS argument Java registered for
the call is wrapped without being looked up again, while the release
count `main` keeps for it (#2151: explicit releases, recorded when the
call starts) has not moved. In canary mode a settle can release such an
id when JS made and dropped its canary in the meantime, so a settle that
releases ids bumps the same count, and under
`enableMultithreadedJavascript` the path stays off (another thread can
do that before the call takes the isolate lock, where the count cannot
see it): `initNativeScript` gains a parameter carrying the flag
(`ObjectManager::SetMultithreadedJavascript`).
- **Class index for an id Java already knew.**
`getOrCreateJavaObjectIDAndClass` (#2099) returns an object's class
index only when it registered the object in that call. The object of a
dead canary keeps its id until its settle (and for good when it has a
record), so a Java field read or method return that handed it back took
the slow class lookup (`GetObjectClass`, the class name, `FindClass`).
`WrapperClassFor` now asks Java for a missing index (`getClassIndex`,
one call) and takes the cached path. On a phone (release,
`canary`/`extended`, 3 rounds, A/A): re-wrapping such an object through
a field read 1806–1920 → 1330 ns (−27%); a method return of an
already-wrapped object unchanged (+0.4% against an A/A of 1.6%,
re-measured on its own after a first session showed +1.9%). Returning
the index with every id instead was faster on the re-wrap (−35%) but
cost +9–10% on every return of an already-wrapped object, in every mode,
so it was not kept.
- **Scope** chooses which canaries keep state:
| mode / scope | JS-extended instances | other wrappers |
|---|---|---|
| `resurrecting` (either scope) | resurrected | resurrected |
| `canary` / `extended` (default) | canaries with state | canaries
without state |
| `canary` / `all` | canaries with state | canaries with state (Java
arrays included) |
Under `"extended"`, a plain wrapper is a cheap canary: no interceptor,
no record, no resurrection. Once JS drops it, it dies and its settle
releases the Java object's id; when Java hands the object back, the
wrapper is a new, empty object. JS properties on plain native objects
are therefore not preserved under `"extended"` (documented: keep such
state on a JS object of your own, or use `"all"`). Array buffers backed
by Java buffers keep the resurrecting lifetime in both scopes (they
cannot carry the interceptor).
- `__releaseNativeCounterpart` drops the object's state with its link:
Java no longer knows the id.
- **`ns:runtime`** gains `getWrapperClassCounts()` (per Java class, as
own properties: live `wrappers`, `canaries`, `states`), and
`getWrapperLifetimeStats()` gains `canaryStates`, `canaryNativeDeaths`,
`canaryInterceptedWrites`, `canaryCachedWrites` (the writes mirrored
from the name cache), `canaryCachedFieldWrites` (the Java field writes
placed by the field cache) and `canaryRebuilds`.
Docs: `docs/ns-builtin-modules.md`.
#### The contract (as on iOS)
Nothing JS references is released under it, and the state of an object
Java holds keeps everything it references. So state that references its
own object (a closure over `this`, `this.onTap = this.onTap.bind(this)`,
a `WeakMap` value naming it) keeps the object alive until one side lets
go; break such back references with a `WeakRef`. A cycle that
resurrection used to break is now kept: a JS-extended listener whose
implementation closes over its owner keeps the owner, the owner's
`nativeView` wrapper keeps the Java view, and the view keeps the
listener. `@nativescript/core`'s `owner: WeakRef<View>` pattern avoids
it; `getWrapperClassCounts()` shows classes that grow across a repeated
journey. A leak finder like iOS's NativeScriptLeakProbe needs a new
design on Android (Java has no retain counts); #2130 adds an
experimental one.
A call a `finalize()` makes into a JS-implemented method is dropped with
a warning (see above): Java clears the watched `WeakReference` before
finalizing. Other limits, as on iOS: `Object.freeze`, `seal` and
`preventExtensions` throw on a canary; index-keyed properties are not
mirrored; a write through an object whose prototype is a canary lands on
that object. A prototype set later with `Object.setPrototypeOf` or
`__proto__` is not state (V8 reports no prototype change to the
handler), so a rebuilt canary has the prototype it was built with;
native `#private` fields are branded on the canary and do not carry
over. A JS class that extends a Java class with `class X extends
java.lang.Object` and no `extend()` (Java cannot call its overrides
either) is linked as a plain wrapper, so under `"extended"` a canary
built later for one of its objects has the Java class's prototype and
none of the old canary's JS properties (documented). A canary built
after another died is a new JS object: `===` cannot tell (nothing kept
the old one), but weak collections keyed on the old canary lose their
entries; the next PR keys them by the Java object instead. **This PR is
meant to merge together with #2128:** on its own, a `WeakMap`/`WeakSet`
entry or `WeakRef` on a plain wrapper dies with that wrapper under
`"extended"`, and a `FinalizationRegistry` callback for one can run
while Java still holds the object.
#### Lessons from the iOS series applied here
- Cache readers never hand out a dead wrapper: the phantom callback
erases the id's entry immediately (#559's empty-handle fix).
- A new canary built while the old one's settle is queued takes over:
the settle skips ids that gained a canary, and Java holds the object
strongly again on every rebuild (#559's queued-release takeover).
- A failed settle keeps its ids and retries after a back-off (#561's
re-posted drain).
- Every instance with state carries the handlers: the interface and
`extend()` templates always, class templates and the array template
under `"all"`, and rebuilt canaries are made from the class's own
instance template, or cloned from the record's shell (#561's
intercepted-constructor fix).
- Receivers of JS methods Java calls are canaries rebuilt with their
state (#561's callback-receiver fix).
- Releases are settled on the runtime's thread only; the watcher thread
posts.
#### V8
Canaries need no V8 patch: phantom callbacks and named interceptors are
stock. The interceptor relies on the `-11` fixes pinned in #2125 for
class fields and `CreateDataProperty`. `"resurrecting"`, and array
buffers backed by Java buffers in canary mode, still need
`v8_resurrecting_finalizers.patch`.
### Testing
- New `testWrapperLifetimeModes.js`, mode-aware (the mode is in a spec
title, and each run's log was checked for it):
- own-property semantics on a JS-extended object;
- a Java-held `Runnable` implementation keeps its state and the Java
objects it references after its canary died (in `"resurrecting"` the
referenced object is collected by Java, asserted as such);
- Java calls into a `Callable` implementation whose canary died
(`FutureTask.run`), into an `extend()` instance (`String.valueOf` → JS
`toString`), into an instance Java constructed
(`getClass().newInstance()`), and into a TypeScript
`__extends`/`__native` subclass whose constructor set state;
- shadowing and deleting a prototype member, non-enumerable, read-only,
accessor and symbol-keyed properties across a rebuild;
- Java field writes are not state; `freeze` throws on a canary with
state; plain wrappers under `"extended"` have no handler;
- plain wrappers under `"extended"`: they die without a resurrection
(`resurrections` flat, `collected` up, no state), a plain object Java
hands back gets a new wrapper without the old one's properties (kept
under `"resurrecting"` and `"all"`), `getWrapperClassCounts()` counts
them as canaries without state, and `__releaseNativeCounterpart` on one
releases its link and lets Java hand the object back in a new wrapper;
- an extended object only JS referenced is collected by Java and its
state let go (through the watcher);
- the self-reference leak; explicit release dropping the state; class
counts and counters;
- a `finalize()` calling a JS override (`FinalizeCallsOverride`): the
call is dropped with the primitive default in canary mode, and nothing
throws in either mode;
- rebuilds: an interface implementation rebuilt by a Java call with its
prototype, Java methods and state; Java-held extended objects whose
canaries died handed to a JS `Comparator` through `Collections.sort`; an
`extend()` instance rebuilt more than once with its class, `super` calls
and state; an extended object Java constructed, rebuilt with its class;
a canary rebuilt twice with no write in between (the second a clone,
keeping read-only, non-enumerable, accessor and symbol-keyed properties
as defined); a canary written since its last rebuild (the stale-shell
path); writes a Java call makes into the canary rebuilt for it.
- New `testWrapperLifetimeStateWrites.js`: writes, deletes and defines
in patterns a cached mirror could get wrong, each checked on a rebuilt
canary: repeat writes interleaved with Java field and prototype accessor
writes, a write after a define that changed the attributes, writes past
a deleted own property that shadowed a Java field or accessor, a name
deleted and added again, one name written on two objects in turn, more
than one rebuild, and class fields (cold and warm) and TypeScript-style
constructor defines.
- New `testWrapperLifetimeFieldWrites.js` (with `fieldWritesWorker.js`
and `CanaryFieldFixtures.java`), each case checked through the stats
counter where the cache should or should not serve the write: a field
declared on the own, an extended or a farther class prototype; one field
name through more prototypes than a cache set has ways; an accessor or
data property defined later on a Java class prototype between the canary
and the field, or on the extended class prototype; an own property
defined on the instance, then deleted; an own property an object with JS
state has, whichever object filled the cache; a plain object and an
extended one whose prototype has its own accessor; the own property a
rebuilt canary got from its state; a final field throwing on a cached
write as on the first; a prototype chain changed under a cached write;
field writes from a worker, each runtime with its own cache.
- New `testWrapperLifetimeRecordSharing.js`: rewrites of names written
before and after more names than a record tags, of a name added by a
define, of a name made at run time across collections, and of a name
deleted and written again, each on a rebuilt canary; rebuilds of
instances of one class (prototype and methods), of interface
implementations (their own implementation objects), of 60 interleaved
instances of 20 classes (more than the 16 class-data slots), and of an
instance of a class whose earlier records were all freed.
- An independent review pass (second commit) fixed: a GC epilogue
callback removed on a failed bootstrap that never added it; a fresh
Java->JS argument id that a settle could release under multithreaded JS
before it was wrapped (now resolved again unless the fast path above
applies); a settle batch that fails after weakening some ids (now
idempotent, and the ids are treated as weak); a record read after it
could be dropped; a watcher thread that one failure could end.
- A later review pass fixed: the watcher thread returning on
`InterruptedException` (it now keeps going); a throw partway through a
drain losing the ids whose entries it had already removed (they are now
reported on the way out); `ReleaseUnwrappedArgs` removing the Java entry
of a fresh argument JS had meanwhile wrapped into a canary (an id with a
canary record is now left to its settle); the write handlers looking the
runtime up with a call that throws inside a V8 interceptor (they now
find none and decline).
- Full suite on an arm64 emulator, on `main` at a59e6ba: on this PR,
`canary`/`extended` and `canary`/`all`, 1867 specs each, 0 failures; on
the top of the stack (#2130), `resurrecting`/`extended` (1909 specs),
`canary`/`extended` and `canary`/`all` (1907 each; two resurrecting-only
specs register conditionally), 0 failures.
- `canary`/`extended` with `enableMultithreadedJavascript: false` (the
cross-thread post-and-wait path the default suite never takes, and the
only canary configuration that takes the fresh-argument fast path), on
the top of the stack: 1907 specs, 0 failures; the
multithreaded-JavaScript feature specs are skipped (#2133). `main`'s
`testReleaseNativeCounterpart.js` (#2151) covers a fresh argument
released by the method lookup.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
<!-- coderabbit-ai-generated:v1 -->
## Summary by CodeRabbit
* **New Features**
* Added canary mode for wrapper lifetimes, with configurable scope and
preservation of JavaScript state when wrappers are rebuilt.
* Added per-class wrapper, canary, and state counts through the runtime
API.
* Added canary-related lifetime statistics.
* **Documentation**
* Expanded wrapper lifetime guidance with mode behavior, state
retention, counters, and limitations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Current behavior. When Java calls a JS method with an object JS has never seen,
Runtime.packageArgsregisters it for the call and passes its id withFreshArgset.ArgConverter::ConvertJavaArgsToJsArgsthen wraps it straight from that id, without asking Java again, provided no wrapper exists for the id yet.JS runs between that registration and the argument conversion: the method lookup on the JS object (a getter, a Proxy
gettrap) happens first. If that JS reaches the same Java object another way (say a static field), passes it to__releaseNativeCounterpartand lets the wrapper be collected, Java drops the id and native drops its registration. The fast path then sees no wrapper for the id, links a new one to an id Java no longer knows, and the first use of the argument fails:This reproduces on
mainin both single- and multithreaded JS.New behavior.
ObjectManagercounts explicit releases (ReleaseNativeCounterpart).Runtime::CallJSMethodNativerecords the count inJavaCallArgsbefore any of the call's JS runs. The fast path is taken only while the count has not moved. Otherwise the argument is resolved through Java (GetOrCreateObjectId) like any other object, which registers it again under a new id. On the hot path this adds one load and compare. The counter is per-runtimeObjectManagerstate and needs no lock, since it is only touched under the isolate lock.An explicit release is the only way a fresh id can be dropped while its Java object is alive. A collected wrapper's flush only weakens the Java entry, and the native registration stays until Java reports the object dead.
ReleaseIfCollectedonly fires for collected Java objects.Not covered here: in multithreaded JS, Java registers the argument before the calling thread takes the isolate lock. Another JS thread could in principle reach, release and collect the object in that window, before the count is recorded. That needs the object to be published to the other thread mid-call. Closing it would take a Java-side change, so it is left out.
Does your commit message include the wording below to reference a specific issue in this repo?
No.
Related Pull Requests
#2127 found and fixed the same issue on the wrapper lifetime canary stack, where the guard reuses the canary release counter. This PR fixes it on
mainindependently of that mode.Does your pull request have unit tests?
Yes.
testReleaseNativeCounterpart.jsadds a spec built on a new fixture,FreshArgCaller. The fixture passes a newStringBuilderto a JS interface implementation and also exposes it through a static field. The spec'stakegetter reads that field, releases the result, runsgc()and returns the method. The spec checks that the argument is still usable and that the lookup ran once.On an arm64 emulator (android-36.1 google_apis image), full suite:
Summary by CodeRabbit