Skip to content

Commit 4b61a3d

Browse files
littledivyclaude
andcommitted
Report wrappables' shallow size to V8 as external memory
V8 sees a JSG object only as its small CppgcShim, so a loop that creates and drops API objects gives V8 no reason to run a major GC, and the C++ objects pile up until one runs. Behind the WRAPPABLE_EXTERNAL_MEMORY autogate, charge each Wrappable its jsgGetMemorySelfSize() once when it is first bound to an isolate, and release it when it is destroyed. Both happen under that isolate's lock, so the total is a plain per-isolate integer. It is reported to V8 in 64 KB batches from attachWrapper() and lock acquisition, never during GC. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 805cb9c commit 4b61a3d

5 files changed

Lines changed: 134 additions & 2 deletions

File tree

‎src/workerd/jsg/setup.c++‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ void IsolateBase::applyDeferredActions() {
325325
}
326326

327327
externalMemoryTarget->applyDeferredMemoryUpdate();
328+
heapTracer.flushExternalMemory();
328329
}
329330

330331
HeapTracer::HeapTracer(v8::Isolate* isolate)

‎src/workerd/jsg/tracing-test.c++‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
#include "jsg-test.h"
66

7+
#include <workerd/util/autogate.h>
8+
79
namespace workerd::jsg::test {
810
namespace {
911

@@ -326,5 +328,56 @@ KJ_TEST("allocating short-lived wrappers eventually triggers a major GC") {
326328
KJ_EXPECT(majorGcCount > 0);
327329
}
328330

331+
// Wrappable bytes charged in this isolate, reported to V8 or not.
332+
int64_t wrappableBytes(Evaluator<TraceTestContext, TraceTestIsolate>& e) {
333+
return e.getIsolate().runInLockScope([&](TraceTestIsolate::Lock& lock) {
334+
auto& tracer = HeapTracer::getTracer(lock.v8Isolate);
335+
return tracer.getReportedWrappableBytesForTest() + tracer.getUnreportedWrappableBytesForTest();
336+
});
337+
}
338+
339+
constexpr int kKeptBoxes = 10000;
340+
341+
// Keeps kKeptBoxes NumberBoxes alive in `globalThis.keep`.
342+
void keepBoxes(Evaluator<TraceTestContext, TraceTestIsolate>& e) {
343+
e.expectEval(kj::str("globalThis.keep = []; for (let i = 0; i < ", kKeptBoxes,
344+
"; ++i) keep.push(new NumberBox(i));"),
345+
"number", kj::str(kKeptBoxes));
346+
}
347+
348+
KJ_TEST("wrappables are charged as external memory while they live") {
349+
util::Autogate::initAutogateForTest({util::AutogateKey::WRAPPABLE_EXTERNAL_MEMORY});
350+
KJ_DEFER(util::Autogate::deinitAutogate());
351+
Evaluator<TraceTestContext, TraceTestIsolate> e(v8System);
352+
353+
e.expectEval("gc()", "undefined", "undefined");
354+
int64_t before = wrappableBytes(e);
355+
356+
// Kept alive, so each is charged and none is released yet.
357+
keepBoxes(e);
358+
int64_t live = wrappableBytes(e) - before;
359+
KJ_EXPECT(live >= int64_t(kKeptBoxes * sizeof(NumberBox)), live);
360+
361+
// The charge is reported to V8 in batches, so at most one batch is still pending.
362+
e.getIsolate().runInLockScope([&](TraceTestIsolate::Lock& lock) {
363+
int64_t pending = HeapTracer::getTracer(lock.v8Isolate).getUnreportedWrappableBytesForTest();
364+
KJ_EXPECT(pending < HeapTracer::kExternalMemoryFlushBytes, pending);
365+
});
366+
367+
// Collected, so the charges are released again, with slack for a few boxes the GCs leave alive.
368+
e.expectEval("keep = null; gc(); gc();", "undefined", "undefined");
369+
int64_t remaining = wrappableBytes(e) - before;
370+
KJ_EXPECT(remaining < int64_t(sizeof(NumberBox)) * 16, remaining);
371+
}
372+
373+
KJ_TEST("wrappables are not charged when the autogate is off") {
374+
util::Autogate::initAutogateNamesForTest({}, util::IgnoreAllAutogatesEnv::YES);
375+
KJ_DEFER(util::Autogate::deinitAutogate());
376+
Evaluator<TraceTestContext, TraceTestIsolate> e(v8System);
377+
int64_t before = wrappableBytes(e);
378+
keepBoxes(e);
379+
KJ_EXPECT(wrappableBytes(e) == before);
380+
}
381+
329382
} // namespace
330383
} // namespace workerd::jsg::test

‎src/workerd/jsg/wrappable.c++‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#include "jsg.h"
88
#include "setup.h"
99

10+
#include <workerd/util/autogate.h>
1011
#include <workerd/util/thread-scopes.h>
1112

1213
#include <cppgc/allocation.h>
@@ -94,6 +95,8 @@ void HeapTracer::unbind(Wrappable& wrappable) {
9495
if (wrappable.link.isLinked()) {
9596
(wrappable.linkedInWrappers ? wrappers : unwrapped).remove(wrappable);
9697
wrappable.linkedInWrappers = false;
98+
// Its charge goes with this isolate, so a later isolate does not release it.
99+
wrappable.accountedBytes = 0;
97100
}
98101
wrappable.isolate = nullptr;
99102
}
@@ -108,9 +111,40 @@ void Wrappable::unlinkFromTracer() {
108111
abort();
109112
}
110113
auto& tracer = HeapTracer::getTracer(isolate);
114+
tracer.releaseWrappable(*this);
111115
(linkedInWrappers ? tracer.wrappers : tracer.unwrapped).remove(*this);
112116
}
113117

118+
void HeapTracer::chargeWrappable(Wrappable& wrappable) {
119+
// Releasing goes by `accountedBytes`, so the gate may change while charged Wrappables live.
120+
if (wrappable.accountedBytes != 0 ||
121+
!util::Autogate::isEnabled(util::AutogateKey::WRAPPABLE_EXTERNAL_MEMORY)) {
122+
return;
123+
}
124+
size_t size = wrappable.jsgGetMemorySelfSize();
125+
wrappable.accountedBytes = static_cast<uint16_t>(kj::min(size, size_t{UINT16_MAX}));
126+
unreportedWrappableBytes += wrappable.accountedBytes;
127+
}
128+
129+
void HeapTracer::releaseWrappable(Wrappable& wrappable) {
130+
unreportedWrappableBytes -= wrappable.accountedBytes;
131+
wrappable.accountedBytes = 0;
132+
}
133+
134+
void HeapTracer::flushExternalMemory() {
135+
if (isolate == nullptr) return;
136+
if (unreportedWrappableBytes < kExternalMemoryFlushBytes &&
137+
unreportedWrappableBytes > -kExternalMemoryFlushBytes) {
138+
return;
139+
}
140+
// Taken before the call: V8 may run a GC inside it, and what that GC charges or releases must
141+
// stay pending for the next flush.
142+
int64_t delta = unreportedWrappableBytes;
143+
unreportedWrappableBytes = 0;
144+
reportedWrappableBytes += delta;
145+
isolate->AdjustAmountOfExternalAllocatedMemoryImpl(delta);
146+
}
147+
114148
void HeapTracer::destroyLiveWrappableInstances() {
115149
v8::HandleScope scope(isolate);
116150
while (!wrappers.empty()) {
@@ -378,6 +412,7 @@ void HeapTracer::linkRestoredWrapper(
378412
shim.state = JSGWrappable::CppgcShim::Active{kj::mv(own)};
379413
wrappable.isolate = isolate;
380414
wrappable.weakShim = &shim;
415+
chargeWrappable(wrappable);
381416

382417
{
383418
// Same invariant as in attachWrapper.
@@ -672,6 +707,12 @@ void Wrappable::attachWrapper(v8::Isolate* isolate,
672707
// pointer. The shim carries the same tag so it lands in the matching freelist bucket.
673708
auto* shim = tracer.allocateShim(*this, tag);
674709

710+
// Charged here rather than when `isolate` is set below, so that the flush, which may call into
711+
// V8, runs while GC is still allowed. Nothing below throws, so `this` is always linked, and
712+
// therefore released, by the end of this function.
713+
tracer.chargeWrappable(*this);
714+
tracer.flushExternalMemory();
715+
675716
// No garbage collection may run from here to the end of this function. Between creating the
676717
// TracedReference below and linking `object` to its CppgcShim, the traced node exists but
677718
// nothing in the cppgc object graph reaches it, so a major GC's ResetDeadNodes() would free the
@@ -831,7 +872,9 @@ void Wrappable::visitRef(GcVisitor& visitor, kj::Maybe<Wrappable&>& refParent, b
831872
if (isolate == nullptr && visitor.parent.isolate != nullptr) {
832873
// A Ref<T> to an unbound Wrappable implies it has no wrapper.
833874
isolate = visitor.parent.isolate;
834-
HeapTracer::getTracer(isolate).addUnwrapped({}, *this);
875+
auto& tracer = HeapTracer::getTracer(isolate);
876+
tracer.addUnwrapped({}, *this);
877+
tracer.chargeWrappable(*this);
835878
}
836879

837880
// Make ref strength match the parent.

‎src/workerd/jsg/wrappable.h‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,12 @@ class Wrappable: public kj::Refcounted {
519519
// before and after. In other words, a wrapper can only be condemned while strongRefcount == 0.
520520
uint strongRefcount = 0;
521521

522+
// The bytes HeapTracer::chargeWrappable() charged to this isolate's external memory, or 0 if
523+
// none. Stored because ~Wrappable() runs after the subclass destructors, when
524+
// jsgGetMemorySelfSize() no longer reports the subclass's size. 16 bits, so that it fits in the
525+
// padding after `strongRefcount`; shallow sizes are far smaller.
526+
uint16_t accountedBytes = 0;
527+
522528
// Whether `link` is in `HeapTracer::wrappers` rather than `HeapTracer::unwrapped`.
523529
bool linkedInWrappers = false;
524530

@@ -634,6 +640,27 @@ class HeapTracer: public v8::EmbedderRootsHandler {
634640
static void substituteCppgcShimForTest(
635641
v8::Isolate* isolate, v8::Local<v8::Object> target, v8::Local<v8::Object> source);
636642

643+
// External memory accounting for Wrappables (the WRAPPABLE_EXTERNAL_MEMORY autogate).
644+
//
645+
// V8 sees a Wrappable only as its small CppgcShim, so garbage made of API objects gives it no
646+
// reason to run a major GC. Each Wrappable is charged its shallow size (jsgGetMemorySelfSize())
647+
// when first bound to this isolate and released when destroyed, both under the isolate lock, so
648+
// the total is a plain integer. Both can happen during a GC, so neither calls into V8;
649+
// flushExternalMemory() reports the total from outside GC once it has moved by
650+
// kExternalMemoryFlushBytes.
651+
void chargeWrappable(Wrappable& wrappable);
652+
void releaseWrappable(Wrappable& wrappable);
653+
void flushExternalMemory();
654+
655+
static constexpr int64_t kExternalMemoryFlushBytes = 64 * 1024;
656+
657+
int64_t getUnreportedWrappableBytesForTest() const {
658+
return unreportedWrappableBytes;
659+
}
660+
int64_t getReportedWrappableBytesForTest() const {
661+
return reportedWrappableBytes;
662+
}
663+
637664
private:
638665
// Returns the head slot of the intrusive freelist for `tag`. The slot has a stable address (it
639666
// lives in the fixed-size freelistedShimsByTag array), so freelisted shims may point back to it.
@@ -677,6 +704,11 @@ class HeapTracer: public v8::EmbedderRootsHandler {
677704
v8::Isolate* isolate;
678705
kj::Vector<Wrappable*> wrappersToTrace;
679706

707+
// Charged minus released bytes not yet reported to V8.
708+
int64_t unreportedWrappableBytes = 0;
709+
// Bytes reported to V8 so far, net.
710+
int64_t reportedWrappableBytes = 0;
711+
680712
// Wrappables on which detachWrapper() should be called at the end of this GC pass.
681713
kj::Vector<Wrappable*> detachLater;
682714

‎src/workerd/util/autogate.h‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,10 @@ namespace workerd::util {
124124
/* Counts the outgoing messages a WebSocket has queued but not yet written as the isolate's \
125125
external memory, so that the isolate's memory limit applies to them. See \
126126
LegacyWebSocketAdapter::chargeOutgoing(). */ \
127-
V(WEBSOCKET_OUTGOING_QUEUE_MEMORY)
127+
V(WEBSOCKET_OUTGOING_QUEUE_MEMORY) \
128+
/* Reports each JSG object's shallow size to V8 as external memory, so that garbage made of \
129+
API objects triggers major GCs. See HeapTracer::chargeWrappable(). */ \
130+
V(WRAPPABLE_EXTERNAL_MEMORY)
128131
// clang-format on
129132
// --------------------------------------------------------------------------------------
130133

0 commit comments

Comments
 (0)