Skip to content

Commit a56552d

Browse files
committed
feat(runtime): find the JS/Java cycles canary mode keeps alive (experimental)
Adds ns:runtime findLeakCycles(). It joins a V8 heap snapshot and an HPROF dump of the Java heap into one graph: JS roots minus the runtime's handles to canary records, Java GC roots minus the runtime's object table and Reference referents, and the runtime's cross-heap edges (a live wrapper holds its Java object, a Java object holds its canary record). A Java object the runtime holds for a live wrapper and that nothing else reaches is leaked; the report gives the path from it back to its wrapper, a signature free of ids, and its members. Slow and on demand: the dump suspends the process.
1 parent b513579 commit a56552d

13 files changed

Lines changed: 1180 additions & 4 deletions

File tree

‎docs/ns-builtin-modules.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,7 @@ wrapper.
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. |
107107
| `getWrapperClassCounts()` | Per Java class name (`<unknown>` for a link whose class was never recorded), the calling isolate's live `wrappers`, the `canaries` among them and the canary `states` (see [Wrapper lifetime](#wrapper-lifetime)). |
108+
| `findLeakCycles()` | Experimental and slow: joins a V8 heap snapshot and a Java heap dump to find the JS ↔ Java cycles canary mode keeps alive (see [Wrapper lifetime](#wrapper-lifetime)). |
108109
| `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)). |
109110

110111
*Platform note (Android):* the original exception is the Java throwable `x`
@@ -239,6 +240,25 @@ A canary built after another died is a new JS object, which `===` cannot tell
239240
because nothing kept the old one. `__releaseNativeCounterpart` drops the
240241
object's state with its link.
241242

243+
**Finding leaked cycles (experimental).** Each heap has its own collector,
244+
so neither sees a cycle that crosses into the other. `findLeakCycles()` joins
245+
them into one graph and asks what a single collector would keep: the JS heap
246+
from a V8 heap snapshot (its roots minus the runtime's handles to canary
247+
records), the Java heap from an HPROF dump (`android.os.Debug.dumpHprofData`;
248+
its GC roots minus the runtime's object table, `Reference` referents skipped),
249+
and the runtime's own edges between them (a live wrapper holds its Java object;
250+
a Java object holds its canary record: state, prototype and implementation
251+
object). A Java object the runtime holds for a live wrapper, and that nothing
252+
else reaches, is leaked. For each, the report gives the path from the Java
253+
object to its own wrapper through fields, properties and the runtime's edges,
254+
a `signature` (the path's node labels from their smallest rotation, free of
255+
ids), and the Java classes of the leaked objects on it (`members`).
256+
`leakedOutsideCycles` counts leaked objects held by a reported cycle rather
257+
than being on one. In `"resurrecting"` mode the report is always empty:
258+
resurrection breaks these cycles. The call suspends the process for a full
259+
heap dump and parses it, so it takes seconds and briefly needs memory of the
260+
order of the Java heap; it is a debugging tool, not for production.
261+
242262
**Weak collections.** What could notice a new canary is whatever keys on the
243263
old one without keeping it, so in canary mode a builtin
244264
(`js/weak-collections.js`) replaces `WeakMap`, `WeakSet`, `WeakRef` and

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ require("./tests/testGC");
6363
require("./tests/testWrapperLifetime");
6464
require("./tests/testWrapperLifetimeModes");
6565
require("./tests/testWrapperLifetimeWeakCollections");
66+
require("./tests/testWrapperLifetimeLeaks");
6667
require("./tests/testsMemoryManagement");
6768
require("./tests/testFieldGetSet");
6869
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", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
14+
expect(Object.keys(runtime).sort()).toEqual(["escapeException", "findLeakCycles", "getConfig", "getWrapperClassCounts", "getWrapperLifetimeStats", "setConfig"]);
1515
});
1616

1717
it("rejects unknown keys", function () {
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
describe("Wrapper lifetime leak probe", function () {
2+
var runtime = require("ns:runtime");
3+
var mode = runtime.getConfig("wrapperLifetimeMode");
4+
var canary = mode === "canary";
5+
var Holder = com.tns.tests.WrapperHolder;
6+
// WeakRefs, so the spec itself keeps nothing it planted alive.
7+
var planted = [];
8+
var report;
9+
10+
function cyclesThrough(edge) {
11+
return report.cycles.filter(function (cycle) {
12+
return cycle.path.indexOf("--" + edge + "-->") !== -1;
13+
});
14+
}
15+
16+
// Each probe dumps the Java heap, so every shape is planted once and probed once, on a
17+
// later task: a WeakRef keeps its target alive until the job that made it ends.
18+
beforeAll(function (done) {
19+
(function () {
20+
// A JS property referencing its own object.
21+
var selfReferencing = new java.lang.Runnable({ run: function () {} });
22+
selfReferencing.probeSelf = selfReferencing;
23+
planted.push(new WeakRef(selfReferencing));
24+
25+
var twin = new java.lang.Runnable({ run: function () {} });
26+
twin.probeSelf = twin;
27+
planted.push(new WeakRef(twin));
28+
29+
// A cycle through Java: the object's state holds a list that holds the object.
30+
var listed = new java.lang.Runnable({ run: function () {} });
31+
var list = new java.util.ArrayList();
32+
list.add(listed);
33+
listed.probeList = list;
34+
planted.push(new WeakRef(listed));
35+
36+
// Held by a Java static: alive for a reason of its own, not a leak.
37+
var held = new java.lang.Runnable({ run: function () {} });
38+
held.probeHeld = held;
39+
Holder.held = held;
40+
planted.push(new WeakRef(held));
41+
42+
// A back reference through a WeakRef keeps nothing.
43+
var weak = new java.lang.Runnable({ run: function () {} });
44+
weak.probeWeak = new WeakRef(weak);
45+
})();
46+
setTimeout(function () {
47+
gc();
48+
java.lang.System.nanoTime();
49+
report = runtime.findLeakCycles();
50+
console.log("leak probe: " + JSON.stringify({
51+
leaked: report.leaked,
52+
leakedOutsideCycles: report.leakedOutsideCycles,
53+
probed: report.probed,
54+
cycles: report.cycles.length,
55+
durationMs: report.durationMs,
56+
dumpBytes: report.dumpBytes
57+
}));
58+
report.cycles.forEach(function (cycle) {
59+
console.log("leak probe cycle: " + cycle.signature);
60+
});
61+
done();
62+
}, 0);
63+
});
64+
65+
afterAll(function () {
66+
Holder.held = null;
67+
planted.forEach(function (ref) {
68+
var object = ref.deref();
69+
if (object !== undefined) {
70+
__releaseNativeCounterpart(object);
71+
}
72+
});
73+
planted = [];
74+
report = null;
75+
});
76+
77+
it("reports the heaps it joined (" + mode + ")", function () {
78+
expect(report.mode).toBe(mode);
79+
expect(Array.isArray(report.cycles)).toBe(true);
80+
expect(report.javaObjects).toBeGreaterThan(0);
81+
expect(report.jsNodes).toBeGreaterThan(0);
82+
expect(report.probed).toBeGreaterThan(0);
83+
expect(report.durationMs).toBeGreaterThan(0);
84+
});
85+
86+
it("finds an object whose JS state references it", function () {
87+
var cycles = cyclesThrough("probeSelf");
88+
if (!canary) {
89+
// Resurrection breaks it: nothing keeps the object once JS lets go.
90+
expect(cycles.length).toBe(0);
91+
return;
92+
}
93+
expect(cycles.length).toBe(2);
94+
expect(cycles[0].path).toContain("--ns:record-->");
95+
expect(cycles[0].path).toContain("--ns:wrapper-->");
96+
expect(cycles[0].members.length).toBe(1);
97+
});
98+
99+
it("gives the same shape the same signature, free of ids", function () {
100+
if (!canary) {
101+
return;
102+
}
103+
var cycles = cyclesThrough("probeSelf");
104+
expect(cycles[0].signature).toBe(cycles[1].signature);
105+
});
106+
107+
it("finds a cycle through a Java collection", function () {
108+
var cycles = cyclesThrough("probeList");
109+
if (!canary) {
110+
expect(cycles.length).toBe(0);
111+
return;
112+
}
113+
expect(cycles.length).toBe(1);
114+
expect(cycles[0].path).toContain("--java.util.ArrayList.elementData-->");
115+
});
116+
117+
it("does not report an object Java holds for a reason of its own", function () {
118+
expect(cyclesThrough("probeHeld").length).toBe(0);
119+
});
120+
121+
it("does not report a back reference through a WeakRef", function () {
122+
expect(cyclesThrough("probeWeak").length).toBe(0);
123+
});
124+
});

‎test-app/runtime/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,7 @@ add_library(
191191
src/main/cpp/FieldAccessor.cpp
192192
src/main/cpp/File.cpp
193193
src/main/cpp/Interop.cpp
194+
src/main/cpp/LeakProbe.cpp
194195
src/main/cpp/IsolateTracked.cpp
195196
src/main/cpp/JEnv.cpp
196197
src/main/cpp/DesugaredInterfaceCompanionClassNameResolver.cpp

0 commit comments

Comments
 (0)