The headless browser for AI agents and web scraping
fix(obscura-cdp): keep concurrent pages' JS isolates live on a shared connection (#872)
Andrey Mnatsakanovd792bae37ce3
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex 99e820f8..518757a7 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -515,25 +515,22 @@ impl CdpContext {}pub fn get_session_page_mut(&mut self, session_id: &Option<String>) -> Option<&mut Page> {+ // Lazily bring the target page's JS isolate live, but — unlike before —+ // do NOT suspend the other pages. Since #756 made N concurrently-live+ // isolates on one thread safe (every op enters its isolate only+ // transiently, never across an `.await`), routing a command to one page+ // no longer needs to tear down another's isolate. Tearing them down is+ // exactly what silently destroyed a concurrent page's JS heap and+ // object handles (#872); a page resumed here now simply stays live.let page_id = session_id.as_ref().and_then(|sid| self.sessions.get(sid)).cloned()?;-- let target_has_js = self.pages.iter().any(|p| p.id == page_id && p.has_js());-- if !target_has_js {- for page in &mut self.pages {- if page.id != page_id && page.has_js() {- page.suspend_js();- break;- }- }- if let Some(target) = self.pages.iter_mut().find(|p| p.id == page_id) {+ if let Some(target) = self.pages.iter_mut().find(|p| p.id == page_id) {+ if !target.has_js() {target.resume_js();}}-self.get_page_mut(&page_id)}}@@ -647,9 +644,10 @@ mod context_ownership_tests {////// Methods listed here were audited to confirm they do not transitively/// call into a `JsRuntime`. They either don't touch any `Page` at all, or-/// use only the immutable `get_session_page` accessor and Rust-side field-/// reads. `get_session_page_mut` triggers `suspend_js`/`resume_js` and-/// must stay behind the lock.+/// use only page accessors plus Rust-side field reads and run no script.+/// (As of #872 `get_session_page_mut` no longer enters V8 — it just returns+/// the session's page — so calling it does not by itself require the lock;+/// only a handler that actually runs JS does.)fn is_v8_free_method(method: &str) -> bool {matches!(method,@@ -742,8 +740,8 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {// Optimization: methods that demonstrably never touch V8 bypass the lock// (Puppeteer's newPage() setup issues ~8 such calls). Each listed method was// audited to confirm it never reaches `JsRuntime::execute_script` or DOM- // mutation that re-enters V8; `get_session_page_mut` (which can trigger- // `suspend_js`/`resume_js`) is NOT in the list.+ // mutation that re-enters V8. (`get_session_page_mut` itself no longer+ // enters V8 as of #872, so calling it is not what gates a method here.)let _v8_guard = if is_v8_free_method(&req.method) {None} else {diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex d5917634..2e75d778 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -1091,57 +1091,89 @@ fn emit_intercepted_request(}async fn pump_live_page_event_loop(ctx: &mut CdpContext) -> Result<bool, String> {- let Some(page) = ctx.pages.iter_mut().find(|page| page.has_js()) else {+ // Several pages on one connection can be live at once (#872), each with its+ // own event loop, so pump a turn on *every* live page rather than only the+ // first. The pump stays armed until all live pages report idle.+ let live_ids: Vec<String> = ctx+ .pages+ .iter()+ .filter(|page| page.has_js())+ .map(|page| page.id.clone())+ .collect();+ if live_ids.is_empty() {return Ok(true);- };- page.run_autonomous_event_loop_turn().await+ }+ let mut all_idle = true;+ for page_id in live_ids {+ if let Some(page) = ctx.get_page_mut(&page_id) {+ all_idle &= page.run_autonomous_event_loop_turn().await?;+ }+ }+ Ok(all_idle)}fn sync_live_page_network_events(ctx: &mut CdpContext) {- let page_route = ctx.pages.iter().find(|page| page.has_js()).and_then(|page| {- ctx.sessions+ // Emit script-initiated network events for every live page, each attributed+ // to its own session/frame — not just the first live page (#872).+ let live_ids: Vec<String> = ctx+ .pages+ .iter()+ .filter(|page| page.has_js())+ .map(|page| page.id.clone())+ .collect();+ for page_id in live_ids {+ let Some(session_id) = ctx+ .sessions.iter()- .find(|(_, page_id)| *page_id == &page.id)- .map(|(session_id, _)| {- (- Some(session_id.clone()),- page.id.clone(),- page.frame_id.clone(),- page.url_string(),- )- })- });- let Some((session_id, page_id, frame_id, page_url)) = page_route else {- return;- };- let network_events = {- let Some(page) = ctx.get_page_mut(&page_id) else {- return;+ .find(|(_, pid)| *pid == &page_id)+ .map(|(session_id, _)| Some(session_id.clone()))+ else {+ continue;};- page.sync_js_network_events();- page.network_events.drain(..).collect::<Vec<_>>()- };- crate::domains::page::emit_runtime_network_events(- ctx,- &session_id,- &frame_id,- &page_url,- &page_id,- &network_events,- );+ let (frame_id, page_url, network_events) = {+ let Some(page) = ctx.get_page_mut(&page_id) else {+ continue;+ };+ page.sync_js_network_events();+ (+ page.frame_id.clone(),+ page.url_string(),+ page.network_events.drain(..).collect::<Vec<_>>(),+ )+ };+ if network_events.is_empty() {+ continue;+ }+ crate::domains::page::emit_runtime_network_events(+ ctx,+ &session_id,+ &frame_id,+ &page_url,+ &page_id,+ &network_events,+ );+ }}fn take_live_pending_navigation(ctx: &CdpContext,) -> Option<(String, String, String, String)> {- let page = ctx.pages.iter().find(|page| page.has_js())?;- let session_id = ctx- .sessions- .iter()- .find(|(_, page_id)| *page_id == &page.id)- .map(|(session_id, _)| session_id.clone())?;- let (url, method, body) = page.take_pending_navigation()?;- Some((session_id, url, method, body))+ // With several live pages, a pending navigation may belong to any of them,+ // not just the first live page — scan until one yields a navigation (#872).+ for page in ctx.pages.iter().filter(|page| page.has_js()) {+ let Some(session_id) = ctx+ .sessions+ .iter()+ .find(|(_, page_id)| *page_id == &page.id)+ .map(|(session_id, _)| session_id.clone())+ else {+ continue;+ };+ if let Some((url, method, body)) = page.take_pending_navigation() {+ return Some((session_id, url, method, body));+ }+ }+ None}fn forward_pending_events(@@ -1308,20 +1340,15 @@ async fn process_with_interception(}};- // Issue #19 follow-up: V8 only allows ONE entered Isolate per OS thread.- // The regular dispatch path enforces this via `get_session_page_mut`- // (which `suspend_js`'es every other page before letting the target- // page run JS). The interception path here bypasses that — it removes- // the target page and spawns a nav task — so we have to enforce the- // same invariant explicitly. Otherwise nav-2's `init_js` constructs- // Isolate-2 while page-1's Isolate-1 is still alive in ctx.pages, and- // the next V8 scope unwind aborts the process via `Context::Exit`'s- // `heap->isolate() == Isolate::TryGetCurrent()` check.- for other in ctx.pages.iter_mut() {- if other.has_js() {- other.suspend_js();- }- }+ // V8 allows only ONE *entered* isolate per OS thread, but many *live*+ // ones. Since #756 every op enters its isolate only transiently (never+ // across an `.await`) and construction leaves the entry stack empty, so a+ // nav task's `init_js` can build a new isolate while other pages' isolates+ // are live without tripping `Context::Exit`'s+ // `heap->isolate() == Isolate::TryGetCurrent()` check. The old defensive+ // `suspend_js` of every other page here (which tore their heaps down and+ // was never resumed once the dispatch-path resume was removed in #872) is+ // therefore no longer needed and would strand concurrent pages.let url = req.params.get("url").and_then(|v| v.as_str()).unwrap_or("");let wait_until = crate::domains::page::parse_wait_until(&req.params);diff --git a/crates/obscura-cdp/tests/concurrent_page_isolation.rs b/crates/obscura-cdp/tests/concurrent_page_isolation.rsnew file mode 100644index 00000000..c61f2c8f--- /dev/null+++ b/crates/obscura-cdp/tests/concurrent_page_isolation.rs@@ -0,0 +1,201 @@+//! #872 / #873 — concurrent pages over ONE CDP connection must each keep their+//! own live JS heap.+//!+//! Playwright's `connectOverCDP` multiplexes N contexts/pages over a single+//! connection. It installs a per-page utility-script object, hands back an+//! `objectId`, and later drives the page through `callFunctionOn { objectId }`.+//!+//! The server used to allow only ONE live V8 isolate per connection: routing a+//! command to another page `suspend_js`'d whichever page was live (tearing its+//! isolate down) and `resume_js`'d the target (rebuilding a fresh one from the+//! snapshot). So a command for page-B destroyed page-A's isolate, and page-A's+//! installed object — and its `objectId` binding — vanished. Playwright then+//! saw `Cannot read properties of undefined (reading 'evaluate')` (issue #872),+//! and the constant snapshot re-deserialization retained ~130 MB per rebuild+//! (issue #873).+//!+//! The runtime layer has supported many concurrently-live isolates on one+//! thread since #756 (each entered only transiently per op, strictly nested),+//! so a page's heap must now survive a command routed to a different page.++use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};++async fn cdp(+ ctx: &mut CdpContext,+ id: u64,+ method: &str,+ params: Value,+ session_id: Option<&str>,+) -> obscura_cdp::types::CdpResponse {+ dispatch(+ &CdpRequest {+ id,+ method: method.to_string(),+ params,+ session_id: session_id.map(str::to_string),+ },+ ctx,+ )+ .await+}++async fn create_and_attach(ctx: &mut CdpContext, url: &str, id: u64) -> String {+ let created = cdp(ctx, id, "Target.createTarget", json!({ "url": url }), None).await;+ assert!(created.error.is_none(), "createTarget failed: {:?}", created.error);+ let target = created.result.unwrap()["targetId"].as_str().unwrap().to_string();+ let attached = cdp(+ ctx,+ id + 1,+ "Target.attachToTarget",+ json!({ "targetId": target, "flatten": true }),+ None,+ )+ .await;+ attached.result.unwrap()["sessionId"].as_str().unwrap().to_string()+}++/// State established in one page's JS heap must still be there after an+/// unrelated command runs against a *different* page on the same connection.+#[tokio::test(flavor = "current_thread")]+async fn concurrent_pages_keep_their_own_js_heap() {+ let mut ctx = CdpContext::new();+ let first = create_and_attach(&mut ctx, "about:blank", 1).await;+ let second = create_and_attach(&mut ctx, "about:blank", 10).await;++ // Give each page a distinct value in its own default context.+ let set_a = cdp(+ &mut ctx,+ 20,+ "Runtime.evaluate",+ json!({ "expression": "globalThis.__probe = 'first-state'; '__probe set'" }),+ Some(&first),+ )+ .await;+ assert!(set_a.error.is_none(), "set on first failed: {:?}", set_a.error);++ let set_b = cdp(+ &mut ctx,+ 21,+ "Runtime.evaluate",+ json!({ "expression": "globalThis.__probe = 'second-state'; '__probe set'" }),+ Some(&second),+ )+ .await;+ assert!(set_b.error.is_none(), "set on second failed: {:?}", set_b.error);++ // Read each page's value back. Under the single-live-isolate model, setting+ // `second` tore down `first`'s isolate, so `first.__probe` is gone.+ let read_a = cdp(+ &mut ctx,+ 22,+ "Runtime.evaluate",+ json!({ "expression": "globalThis.__probe", "returnByValue": true }),+ Some(&first),+ )+ .await;+ assert!(read_a.error.is_none(), "read on first errored: {:?}", read_a.error);+ assert_eq!(+ read_a.result.unwrap()["result"]["value"],+ json!("first-state"),+ "first page's JS heap was destroyed by a command routed to the second page"+ );++ let read_b = cdp(+ &mut ctx,+ 23,+ "Runtime.evaluate",+ json!({ "expression": "globalThis.__probe", "returnByValue": true }),+ Some(&second),+ )+ .await;+ assert!(read_b.error.is_none(), "read on second errored: {:?}", read_b.error);+ assert_eq!(+ read_b.result.unwrap()["result"]["value"],+ json!("second-state"),+ "second page's JS heap was destroyed by a command routed to the first page"+ );+}++/// The exact Playwright pattern: an `objectId` handed out for one page is+/// driven through `callFunctionOn`. The handle must keep pointing at the *same*+/// live object across a command routed to another page — mutations made through+/// it must persist. Tearing the page's isolate down and rebuilding it from a+/// stored recipe silently resets that object's state, which is what breaks+/// Playwright's utility script.+#[tokio::test(flavor = "current_thread")]+async fn an_objectid_keeps_its_live_object_across_a_command_on_another_page() {+ let mut ctx = CdpContext::new();+ let first = create_and_attach(&mut ctx, "about:blank", 1).await;+ let second = create_and_attach(&mut ctx, "about:blank", 10).await;++ // Mint a stateful object handle in `first` (stands in for Playwright's+ // utility script object, which accumulates state as it drives the page).+ let handle = cdp(+ &mut ctx,+ 20,+ "Runtime.evaluate",+ json!({ "expression": "globalThis.__util = { n: 0 }; globalThis.__util" }),+ Some(&first),+ )+ .await;+ assert!(handle.error.is_none(), "evaluate on first failed: {:?}", handle.error);+ let object_id = handle.result.unwrap()["result"]["objectId"]+ .as_str()+ .expect("evaluate should return an objectId for an object")+ .to_string();++ // First call through the handle: n -> 1.+ let first_call = cdp(+ &mut ctx,+ 21,+ "Runtime.callFunctionOn",+ json!({+ "objectId": object_id,+ "functionDeclaration": "function () { return ++this.n; }",+ "returnByValue": true,+ }),+ Some(&first),+ )+ .await;+ assert!(first_call.error.is_none(), "first callFunctionOn failed: {:?}", first_call.error);+ assert_eq!(first_call.result.unwrap()["result"]["value"], json!(1.0));++ // Touch the other page — this is what tore `first`'s isolate down before.+ let touch = cdp(+ &mut ctx,+ 22,+ "Runtime.evaluate",+ json!({ "expression": "1 + 1", "returnByValue": true }),+ Some(&second),+ )+ .await;+ assert!(touch.error.is_none(), "evaluate on second failed: {:?}", touch.error);++ // Second call through the SAME handle must continue from n == 1 -> 2. If+ // the isolate was rebuilt, the handle points at a freshly reconstructed+ // `{ n: 0 }` and this wrongly returns 1 again.+ let second_call = cdp(+ &mut ctx,+ 23,+ "Runtime.callFunctionOn",+ json!({+ "objectId": object_id,+ "functionDeclaration": "function () { return ++this.n; }",+ "returnByValue": true,+ }),+ Some(&first),+ )+ .await;+ assert!(+ second_call.error.is_none(),+ "second callFunctionOn (after touching the other page) failed: {:?}",+ second_call.error+ );+ assert_eq!(+ second_call.result.unwrap()["result"]["value"],+ json!(2.0),+ "the first page's object handle lost its state when the second page ran a command"+ );+}