From 20b557e439fa4f1d3ab68171878a7caca8796bcb Mon Sep 17 00:00:00 2001 From: Pratham Date: Mon, 23 Nov 2026 13:13:39 +0000 Subject: [PATCH] Report a buffer-backed body's bytes as external memory A Request or Response built from a string, BufferSource, Blob, FormData or URLSearchParams keeps a kj-heap copy of its bytes in a JsReadableStream::Buffer. V8 never learned of that copy: to it each body was a small wrapper. A Worker that kept making bodies from a large buffer left the dead copies waiting on a GC that their size never prompted, and they weren't counted against the isolate's memory limit. A production heap profile showed 799 live copies of one 25 MB body, 20 GB in all. Buffer now holds an ExternalMemoryAdjustment for its bytes. Clones and tee branches share the Buffer, so they don't count it again. The adjustment is safe to release without the isolate lock, as happens when the stream's native source drops its reference. Since a Worker that keeps large bodies alive may now exceed its memory limit, and GCs become more frequent for Workers that make many bodies, the BODY_BUFFER_EXTERNAL_MEMORY autogate guards the report. With it off, the adjustment is zero. --- src/workerd/api/js-readable-stream-test.c++ | 56 +++++++++++++++++++++ src/workerd/api/js-readable-stream.c++ | 11 ++-- src/workerd/api/js-readable-stream.h | 8 ++- src/workerd/util/autogate.h | 6 ++- 4 files changed, 75 insertions(+), 6 deletions(-) diff --git a/src/workerd/api/js-readable-stream-test.c++ b/src/workerd/api/js-readable-stream-test.c++ index b1d9eb6cf05..993e079c350 100644 --- a/src/workerd/api/js-readable-stream-test.c++ +++ b/src/workerd/api/js-readable-stream-test.c++ @@ -406,6 +406,62 @@ KJ_TEST("JsReadableStream tee carries the buffer and nullifies the original") { }); } +// The isolate's external memory, including adjustments not yet applied. +int64_t getExternalMemory(jsg::Lock& js) { + js.getExternalMemoryTarget()->applyDeferredMemoryUpdate(); + return js.v8Isolate->GetExternalMemory(); +} + +KJ_TEST("JsReadableStream reports its retransmit buffer as external memory, once") { + TestFixture testFixture( + {.autogateKeys = kj::arr(util::AutogateKey::BODY_BUFFER_EXTERNAL_MEMORY)}); + testFixture.runInIoContext([](const TestFixture::Environment& env) { + auto& js = env.js; + constexpr size_t size = 1024 * 1024; + auto source = jsg::JsArrayBuffer::create(js, size); + + auto before = getExternalMemory(js); + JsReadableStream stream(js, jsg::JsBufferSource(source).addRef(js)); + auto created = getExternalMemory(js) - before; + KJ_EXPECT(created >= size, created); + // The stream itself only adds bookkeeping on top of the copied bytes. + KJ_EXPECT(created < size + 64 * 1024, created); + + // Clones and tee branches share the one buffer, so they don't count it again. + auto clone = KJ_ASSERT_NONNULL(stream.tryClone(js)); + auto tee = stream.tee(js); + auto shared = getExternalMemory(js) - before; + KJ_EXPECT(shared < size + 64 * 1024, shared); + }); +} + +KJ_TEST("JsReadableStream retransmit buffer releases its external memory") { + TestFixture testFixture( + {.autogateKeys = kj::arr(util::AutogateKey::BODY_BUFFER_EXTERNAL_MEMORY)}); + testFixture.runInIoContext([](const TestFixture::Environment& env) { + auto& js = env.js; + constexpr size_t size = 1024 * 1024; + + auto before = getExternalMemory(js); + auto buffer = kj::rc(js, kj::heapArray(size)); + KJ_EXPECT(getExternalMemory(js) - before == size); + buffer = nullptr; + KJ_EXPECT(getExternalMemory(js) == before); + }); +} + +KJ_TEST("JsReadableStream retransmit buffer reports no external memory with its autogate off") { + TestFixture testFixture({.ignoreAllAutogatesEnv = true}); + testFixture.runInIoContext([](const TestFixture::Environment& env) { + auto& js = env.js; + constexpr size_t size = 1024 * 1024; + + auto before = getExternalMemory(js); + auto buffer = kj::rc(js, kj::heapArray(size)); + KJ_EXPECT(getExternalMemory(js) == before); + }); +} + KJ_TEST("JsReadableStream detach takes over the stream, leaving a disturbed husk") { TestFixture testFixture; testFixture.runInIoContext([](const TestFixture::Environment& env) -> kj::Promise { diff --git a/src/workerd/api/js-readable-stream.c++ b/src/workerd/api/js-readable-stream.c++ index 2289b90766c..713dec132c1 100644 --- a/src/workerd/api/js-readable-stream.c++ +++ b/src/workerd/api/js-readable-stream.c++ @@ -756,9 +756,12 @@ kj::Promise> pumpQueuedTsStream(jsg::Lock& js, // ownership of that heap buffer without changing its address, so view remains valid. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdangling-field" -JsReadableStream::Buffer::Buffer(kj::Array data) +JsReadableStream::Buffer::Buffer(jsg::Lock& js, kj::Array data) : owned(kj::mv(data)), - view(owned) {} + view(owned), + externalMemoryAdjustment(js.getExternalMemoryAdjustment( + util::Autogate::isEnabled(util::AutogateKey::BODY_BUFFER_EXTERNAL_MEMORY) ? owned.size() + : 0)) {} #pragma clang diagnostic pop // Blob contents live in a V8 ArrayBuffer. The streams built from this Buffer are read on the @@ -766,7 +769,7 @@ JsReadableStream::Buffer::Buffer(kj::Array data) // kj-heap copy. It is shared by every stream derived from this Buffer -- rewinds and tee // branches alike. JsReadableStream::Buffer::Buffer(jsg::Lock& js, jsg::Ref data) - : Buffer(kj::heapArray(data->getData(js))) {} + : Buffer(js, kj::heapArray(data->getData(js))) {} namespace { @@ -817,7 +820,7 @@ JsReadableStream::JsReadableStream(jsg::Lock&, jsg::JsRef obj) }) {} JsReadableStream::JsReadableStream(jsg::Lock& js, kj::Array data) - : impl(bufferBackedImpl(js, kj::rc(kj::mv(data)))) {} + : impl(bufferBackedImpl(js, kj::rc(js, kj::mv(data)))) {} JsReadableStream::JsReadableStream(jsg::Lock& js, kj::String data) : JsReadableStream(js, webstreams::stringToBytes(kj::mv(data))) {} diff --git a/src/workerd/api/js-readable-stream.h b/src/workerd/api/js-readable-stream.h index bf2756386d7..6ff8721a241 100644 --- a/src/workerd/api/js-readable-stream.h +++ b/src/workerd/api/js-readable-stream.h @@ -54,7 +54,13 @@ class JsReadableStream final { kj::Array owned; kj::ArrayPtr view; - explicit Buffer(kj::Array data); + // Reports `owned` to the isolate as external memory. V8 sees only a small wrapper for each + // Request or Response, so without this, bodies held by objects awaiting collection don't + // prompt a GC and aren't counted against the isolate's memory limit. Reports nothing unless + // the BODY_BUFFER_EXTERNAL_MEMORY autogate is enabled. + jsg::ExternalMemoryAdjustment externalMemoryAdjustment; + + Buffer(jsg::Lock& js, kj::Array data); Buffer(jsg::Lock& js, jsg::Ref data); }; diff --git a/src/workerd/util/autogate.h b/src/workerd/util/autogate.h index c9eb93179fa..07402c3fbb7 100644 --- a/src/workerd/util/autogate.h +++ b/src/workerd/util/autogate.h @@ -141,7 +141,11 @@ namespace workerd::util { V(IO_CHANNELS_FROM_RUNNING_REQUEST) \ /* WorkerInterface::fromException() makes the Rust worker in src/rust/worker/failure.rs \ instead of the C++ ErrorWorkerInterface in io/worker-interface.c++. */ \ - V(RUST_FAILURE_WORKER_INTERFACE) + V(RUST_FAILURE_WORKER_INTERFACE) \ + /* Counts the bytes behind a Request or Response body built from in-memory data, such as a \ + string or BufferSource, as the isolate's external memory, so that they prompt GCs and the \ + isolate's memory limit applies to them. See JsReadableStream::Buffer. */ \ + V(BODY_BUFFER_EXTERNAL_MEMORY) // clang-format on // --------------------------------------------------------------------------------------