Skip to content

The headless browser for AI agents and web scraping

fix(cdp): report native V8 heap usage and collect garbage

SGavrl8bb46be3261a
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rs
index c270c254..71dfceb3 100644
--- a/crates/obscura-cdp/src/dispatch.rs
+++ b/crates/obscura-cdp/src/dispatch.rs
@@ -808,6 +808,15 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
"Accessibility" => {
domains::accessibility::handle(method, &req.params, ctx, &req.session_id).await
}
+ "HeapProfiler" if method == "collectGarbage" => {
+ match ctx.get_session_page_mut(&req.session_id).and_then(|page| page.js.as_mut()) {
+ Some(js) => {
+ js.collect_garbage();
+ Ok(json!({}))
+ }
+ None => Err("No JavaScript runtime".to_string()),
+ }
+ }
// Accepted but no-op. Puppeteer's FrameManager.initialize calls
// Audits.enable on connect — refusing it breaks puppeteer.connect()
// before any user code runs.
@@ -1199,6 +1208,29 @@ mod tests {
}
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn heap_profiler_collect_garbage_reclaims_unreferenced_objects() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session = Some("heap-gc".to_string());
+ ctx.sessions.insert(session.clone().unwrap(), page_id);
+ ctx.get_session_page_mut(&session).unwrap().js.as_mut().unwrap().execute_script("gc-allocations",
+ "globalThis.garbage = Array.from({length: 200000}, (_, i) => ({i}));",
+ ).unwrap();
+ let before = domains::runtime::handle("getHeapUsage", &json!({}), &mut ctx, &session)
+ .await.unwrap()["usedSize"].as_u64().unwrap();
+ ctx.get_session_page_mut(&session).unwrap().evaluate("globalThis.garbage = null");
+ let response = dispatch(&CdpRequest {
+ session_id: session.clone(),
+ ..req("HeapProfiler.collectGarbage")
+ }, &mut ctx).await;
+ assert!(response.error.is_none(), "GC request failed: {:?}", response.error);
+ let after = domains::runtime::handle("getHeapUsage", &json!({}), &mut ctx, &session)
+ .await.unwrap()["usedSize"].as_u64().unwrap();
+ assert!(after + 2 * 1024 * 1024 < before,
+ "explicit GC must reclaim discarded objects: {before} -> {after}");
+ }
+
#[tokio::test]
async fn audits_enable_returns_empty_success() {
let mut ctx = CdpContext::new();
diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rs
index 00dce7b3..00a8dca0 100644
--- a/crates/obscura-cdp/src/domains/runtime.rs
+++ b/crates/obscura-cdp/src/domains/runtime.rs
@@ -102,6 +102,18 @@ pub async fn handle(
session_id: &Option<String>,
) -> Result<Value, String> {
match method {
+ "getHeapUsage" => {
+ let page = ctx.get_session_page_mut(session_id).ok_or("No page")?;
+ let js = page.js.as_mut().ok_or("No JavaScript runtime")?;
+ let stats = js.heap_statistics();
+ Ok(json!({
+ "usedSize": stats.used_heap_size(),
+ "totalSize": stats.total_heap_size(),
+ // Rust-owned DOM storage is not a V8 cppgc heap.
+ "embedderHeapUsedSize": 0,
+ "backingStorageSize": stats.external_memory(),
+ }))
+ }
"enable" => {
// puppeteer-extra's FrameManager.initialize calls Runtime.enable on
// the browser-level connection BEFORE any page target exists. Real
@@ -577,6 +589,32 @@ mod tests {
use super::*;
use crate::dispatch::CdpContext;
+ #[tokio::test(flavor = "current_thread")]
+ async fn heap_usage_reports_live_v8_allocations_without_running_page_tasks() {
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session = Some("heap-usage".to_string());
+ ctx.sessions.insert(session.clone().unwrap(), page_id);
+ let before = handle("getHeapUsage", &json!({}), &mut ctx, &session).await.unwrap();
+ for field in ["usedSize", "totalSize", "embedderHeapUsedSize", "backingStorageSize"] {
+ assert!(before[field].as_u64().is_some(), "missing byte count: {before}");
+ }
+ assert!(before["usedSize"].as_u64().unwrap() > 0);
+ assert!(before["totalSize"].as_u64().unwrap() >= before["usedSize"].as_u64().unwrap());
+ ctx.get_session_page_mut(&session).unwrap().js.as_mut().unwrap().execute_script("heap-allocations",
+ "globalThis.heapObjects = Array.from({length: 100000}, (_, i) => ({i}));\
+ globalThis.heapBuffer = new ArrayBuffer(8 * 1024 * 1024);\
+ globalThis.heapTimerRan = false;\
+ setTimeout(() => { globalThis.heapTimerRan = true; }, 0);",
+ ).unwrap();
+ let after = handle("getHeapUsage", &json!({}), &mut ctx, &session).await.unwrap();
+ assert!(after["usedSize"].as_u64().unwrap() > before["usedSize"].as_u64().unwrap());
+ assert!(after["backingStorageSize"].as_u64().unwrap()
+ >= before["backingStorageSize"].as_u64().unwrap() + 8 * 1024 * 1024);
+ assert_eq!(ctx.get_session_page_mut(&session).unwrap()
+ .evaluate("heapTimerRan"), json!(false));
+ }
+
// Issue #51 — Runtime.evaluate / callFunctionOn must read and validate
// contextId. Pre-fix the parameter was silently dropped, so Playwright's
// locator (which targets the utility world created by
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 9de9b8e5..26dd7002 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -536,6 +536,16 @@ impl ObscuraJsRuntime {
EnteredRuntime(&mut self.js_runtime)
}
+ /// Read native isolate statistics without evaluating scripts or forcing GC.
+ pub fn heap_statistics(&mut self) -> v8::HeapStatistics {
+ self.runtime().v8_isolate().get_heap_statistics()
+ }
+
+ /// Run a full collection only when an automation client explicitly asks.
+ pub fn collect_garbage(&mut self) {
+ self.runtime().v8_isolate().low_memory_notification();
+ }
+
/// Freeze the document timeline for one JavaScript task. Browser timelines
/// update at task/rendering boundaries, not on each forced style or layout
/// read. Keeping one sample across the task also lets repeated CSSOM reads
diff --git a/docs/Use-with-Playwright.md b/docs/Use-with-Playwright.md
index b512ee42..31775f43 100644
--- a/docs/Use-with-Playwright.md
+++ b/docs/Use-with-Playwright.md
@@ -82,6 +82,21 @@ await page.route('**/*', route => {
});
```
+## JavaScript heap measurements
+
+```js
+const client = await context.newCDPSession(page);
+await client.send('HeapProfiler.collectGarbage'); // Optional explicit collection.
+const heap = await client.send('Runtime.getHeapUsage');
+console.log(heap.usedSize, heap.totalSize, heap.backingStorageSize);
+await client.detach();
+```
+
+These are native V8 isolate byte counts, not process memory. Reading them does
+not run page tasks or force collection. `embedderHeapUsedSize` is zero because
+Obscura's Rust DOM is not a V8-managed cppgc heap; Rust allocations and renderer
+memory are not included.
+
## Multiple pages
```js