Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/workerd/jsg/setup.c++
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,7 @@ void IsolateBase::applyDeferredActions() {
}

externalMemoryTarget->applyDeferredMemoryUpdate();
heapTracer.flushExternalMemory();
}

HeapTracer::HeapTracer(v8::Isolate* isolate)
Expand Down
67 changes: 67 additions & 0 deletions src/workerd/jsg/tracing-test.c++
Original file line number Diff line number Diff line change
Expand Up @@ -445,5 +445,72 @@ KJ_TEST("allocating short-lived wrappers eventually triggers a major GC") {
KJ_EXPECT(majorGcCount > 0);
}

// Wrappable bytes charged in this isolate, reported to V8 or not.
int64_t wrappableBytes(Evaluator<TraceTestContext, TraceTestIsolate>& e) {
return e.getIsolate().runInLockScope([&](TraceTestIsolate::Lock& lock) {
return HeapTracer::getTracer(lock.v8Isolate).getChargedWrappableBytes();
});
}

int64_t reportedWrappableBytes(Evaluator<TraceTestContext, TraceTestIsolate>& e) {
return e.getIsolate().runInLockScope([&](TraceTestIsolate::Lock& lock) {
return HeapTracer::getTracer(lock.v8Isolate).getReportedWrappableBytes();
});
}

constexpr int kKeptBoxes = 10000;

// Keeps kKeptBoxes NumberBoxes alive in `globalThis.keep`.
void keepBoxes(Evaluator<TraceTestContext, TraceTestIsolate>& e) {
e.expectEval(kj::str("globalThis.keep = []; for (let i = 0; i < ", kKeptBoxes,
"; ++i) keep.push(new NumberBox(i));"),
"number", kj::str(kKeptBoxes));
}

KJ_TEST("wrappables are charged as external memory while they live") {
util::Autogate::initAutogateForTest({util::AutogateKey::WRAPPABLE_EXTERNAL_MEMORY});
KJ_DEFER(util::Autogate::deinitAutogate());
Evaluator<TraceTestContext, TraceTestIsolate> e(v8System);

e.expectEval("gc()", "undefined", "undefined");
int64_t before = wrappableBytes(e);

// Kept alive, so each is charged and none is released yet.
keepBoxes(e);
int64_t live = wrappableBytes(e) - before;
KJ_EXPECT(live >= int64_t(kKeptBoxes * sizeof(NumberBox)), live);

// The charge is reported to V8 in batches, so at most one batch is still pending.
e.getIsolate().runInLockScope([&](TraceTestIsolate::Lock& lock) {
int64_t pending = HeapTracer::getTracer(lock.v8Isolate).getUnreportedWrappableBytesForTest();
KJ_EXPECT(pending < HeapTracer::kExternalMemoryFlushBytes, pending);
});

// Collected, so the charges are released again, with slack for a few boxes the GCs leave alive.
// The GC is requested from C++ without stack scanning, as a stale stack slot that points at
// `keep` would keep every box alive.
e.expectEval("keep = null", "object", "null");
e.getIsolate().runInLockScope([&](TraceTestIsolate::Lock& lock) {
for (int i = 0; i < 2; ++i) {
lock.v8Isolate->RequestGarbageCollectionForTesting(
v8::Isolate::kFullGarbageCollection, v8::StackState::kNoHeapPointers);
}
});
int64_t remaining = wrappableBytes(e) - before;
KJ_EXPECT(remaining < int64_t(sizeof(NumberBox)) * 16, remaining);
}

KJ_TEST("wrappables are counted but not reported to V8 when the autogate is off") {
util::Autogate::initAutogateNamesForTest({}, util::IgnoreAllAutogatesEnv::YES);
KJ_DEFER(util::Autogate::deinitAutogate());
Evaluator<TraceTestContext, TraceTestIsolate> e(v8System);
int64_t before = wrappableBytes(e);
int64_t reportedBefore = reportedWrappableBytes(e);
keepBoxes(e);
int64_t live = wrappableBytes(e) - before;
KJ_EXPECT(live >= int64_t(kKeptBoxes * sizeof(NumberBox)), live);
KJ_EXPECT(reportedWrappableBytes(e) == reportedBefore);
}

} // namespace
} // namespace workerd::jsg::test
42 changes: 41 additions & 1 deletion src/workerd/jsg/wrappable.c++
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "jsg.h"
#include "setup.h"

#include <workerd/util/autogate.h>
#include <workerd/util/thread-scopes.h>

#include <cppgc/allocation.h>
Expand Down Expand Up @@ -94,6 +95,8 @@ void HeapTracer::unbind(Wrappable& wrappable) {
if (wrappable.link.isLinked()) {
(wrappable.linkedInWrappers ? wrappers : unwrapped).remove(wrappable);
wrappable.linkedInWrappers = false;
// Its charge goes with this isolate, so a later isolate does not release it.
wrappable.accountedBytes = 0;
}
wrappable.isolate = nullptr;
}
Expand All @@ -108,9 +111,39 @@ void Wrappable::unlinkFromTracer() {
abort();
}
auto& tracer = HeapTracer::getTracer(isolate);
tracer.releaseWrappable(*this);
(linkedInWrappers ? tracer.wrappers : tracer.unwrapped).remove(*this);
}

void HeapTracer::chargeWrappable(Wrappable& wrappable) {
if (wrappable.accountedBytes != 0) return;
size_t size = wrappable.jsgGetMemorySelfSize();
wrappable.accountedBytes = static_cast<uint16_t>(kj::min(size, size_t{UINT16_MAX}));
unreportedWrappableBytes += wrappable.accountedBytes;
}

void HeapTracer::releaseWrappable(Wrappable& wrappable) {
unreportedWrappableBytes -= wrappable.accountedBytes;
wrappable.accountedBytes = 0;
}

void HeapTracer::flushExternalMemory() {
if (isolate == nullptr ||
!util::Autogate::isEnabled(util::AutogateKey::WRAPPABLE_EXTERNAL_MEMORY)) {
return;
}
if (unreportedWrappableBytes < kExternalMemoryFlushBytes &&
unreportedWrappableBytes > -kExternalMemoryFlushBytes) {
return;
}
// Taken before the call: V8 may run a GC inside it, and what that GC charges or releases must
// stay pending for the next flush.
int64_t delta = unreportedWrappableBytes;
unreportedWrappableBytes = 0;
reportedWrappableBytes += delta;
isolate->AdjustAmountOfExternalAllocatedMemoryImpl(delta);
}

void HeapTracer::destroyLiveWrappableInstances() {
v8::HandleScope scope(isolate);
while (!wrappers.empty()) {
Expand Down Expand Up @@ -378,6 +411,7 @@ void HeapTracer::linkRestoredWrapper(
shim.state = JSGWrappable::CppgcShim::Active{kj::mv(own)};
wrappable.isolate = isolate;
wrappable.weakShim = &shim;
chargeWrappable(wrappable);

{
// Same invariant as in attachWrapper.
Expand Down Expand Up @@ -670,6 +704,10 @@ void Wrappable::attachWrapper(v8::Isolate* isolate,
// pointer. The shim carries the same tag so it lands in the matching freelist bucket.
auto* shim = tracer.allocateShim(*this, tag);

// Nothing below throws, so `this` is always linked, and therefore released, by the end of this
// function.
tracer.chargeWrappable(*this);

// No garbage collection may run from here to the end of this function. Between creating the
// TracedReference below and linking `object` to its CppgcShim, the traced node exists but
// nothing in the cppgc object graph reaches it, so a major GC's ResetDeadNodes() would free the
Expand Down Expand Up @@ -840,7 +878,9 @@ void Wrappable::visitRef(GcVisitor& visitor, kj::Maybe<Wrappable&>& refParent, b
if (isolate == nullptr && parent.isolate != nullptr) {
// A Ref<T> to an unbound Wrappable implies it has no wrapper.
isolate = parent.isolate;
HeapTracer::getTracer(isolate).addUnwrapped({}, *this);
auto& tracer = HeapTracer::getTracer(isolate);
tracer.addUnwrapped({}, *this);
tracer.chargeWrappable(*this);
}

// Make ref strength match the parent.
Expand Down
48 changes: 48 additions & 0 deletions src/workerd/jsg/wrappable.h
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,12 @@ class Wrappable: public kj::Refcounted {
// before and after. In other words, a wrapper can only be condemned while strongRefcount == 0.
uint strongRefcount = 0;

// The bytes HeapTracer::chargeWrappable() charged to this isolate's external memory, or 0 if
// none. Stored because ~Wrappable() runs after the subclass destructors, when
// jsgGetMemorySelfSize() no longer reports the subclass's size. 16 bits, so that it fits in the
// padding after `strongRefcount`; shallow sizes are far smaller.
uint16_t accountedBytes = 0;

// Whether `link` is in `HeapTracer::wrappers` rather than `HeapTracer::unwrapped`.
bool linkedInWrappers = false;

Expand Down Expand Up @@ -635,6 +641,43 @@ class HeapTracer: public v8::EmbedderRootsHandler {
static void substituteCppgcShimForTest(
v8::Isolate* isolate, v8::Local<v8::Object> target, v8::Local<v8::Object> source);

// External memory accounting for Wrappables.
//
// V8 sees a Wrappable only as its small CppgcShim, so garbage made of API objects gives it no
// reason to run a major GC. Each Wrappable is charged its shallow size (jsgGetMemorySelfSize())
// when first bound to this isolate and released when destroyed, both under the isolate lock, so
// the total is a plain integer. The total is always kept, so getChargedWrappableBytes() can be
// observed before anything depends on it; only with the WRAPPABLE_EXTERNAL_MEMORY autogate is it
// reported to V8.
//
// Neither charging nor releasing calls into V8: both can happen during a GC, and reporting
// external memory can run a full GC synchronously, which must not happen in the middle of
// attaching a wrapper. IsolateBase::applyDeferredActions() calls flushExternalMemory() each time
// the isolate lock is taken, and it reports the total once it has moved by
// kExternalMemoryFlushBytes.
void chargeWrappable(Wrappable& wrappable);
void releaseWrappable(Wrappable& wrappable);
void flushExternalMemory();

static constexpr int64_t kExternalMemoryFlushBytes = 64 * 1024;

// The shallow size of every Wrappable currently bound to this isolate, whether or not it has
// been reported to V8.
int64_t getChargedWrappableBytes() const {
return reportedWrappableBytes + unreportedWrappableBytes;
}

// The Wrappable bytes this isolate has reported to V8 as external memory, and so included in
// v8::Isolate::GetExternalMemory(). An embedder that enforces a memory limit from
// GetExternalMemory() can subtract these to leave them out of the limit.
int64_t getReportedWrappableBytes() const {
return reportedWrappableBytes;
}

int64_t getUnreportedWrappableBytesForTest() const {
return unreportedWrappableBytes;
}

private:
// Returns the head slot of the intrusive freelist for `tag`. The slot has a stable address (it
// lives in the fixed-size freelistedShimsByTag array), so freelisted shims may point back to it.
Expand Down Expand Up @@ -678,6 +721,11 @@ class HeapTracer: public v8::EmbedderRootsHandler {
v8::Isolate* isolate;
kj::Vector<Wrappable*> wrappersToTrace;

// Charged minus released bytes not yet reported to V8.
int64_t unreportedWrappableBytes = 0;
// Bytes reported to V8 so far, net. See getReportedWrappableBytes().
int64_t reportedWrappableBytes = 0;

// Wrappables on which detachWrapper() should be called at the end of this GC pass.
kj::Vector<Wrappable*> detachLater;

Expand Down
5 changes: 4 additions & 1 deletion src/workerd/util/autogate.h
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,10 @@ namespace workerd::util {
/* Counts the outgoing messages a WebSocket has queued but not yet written as the isolate's \
external memory, so that the isolate's memory limit applies to them. See \
LegacyWebSocketAdapter::chargeOutgoing(). */ \
V(WEBSOCKET_OUTGOING_QUEUE_MEMORY)
V(WEBSOCKET_OUTGOING_QUEUE_MEMORY) \
/* Reports each JSG object's shallow size, which is always counted, to V8 as external memory, \
so that garbage made of API objects triggers major GCs. See HeapTracer::chargeWrappable(). */ \
V(WRAPPABLE_EXTERNAL_MEMORY)
// clang-format on
// --------------------------------------------------------------------------------------

Expand Down
Loading