The headless browser for AI agents and web scraping
Prevent deep DOM CDP stack aborts
SGavrl62c3be662953
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rsindex 009ee813..5ec56ea3 100644--- a/crates/obscura-cdp/src/server.rs+++ b/crates/obscura-cdp/src/server.rs@@ -44,14 +44,16 @@ const MAX_PENDING_WS_HANDOFFS: usize = 128;// V8 isolates. `MAX_PENDING_WS_HANDOFFS` above bounds only the handoff queue —// connections that have already been handed off are unbounded without this.//-// 128 matches the handoff bound and is well above any real client fan-out-// (Playwright/Puppeteer use one connection per browser). Threads are what this-// actually bounds: with arenas capped by `cap_malloc_arenas`, 128 idle-// connections cost 146 threads, 33.2 GiB of reserved address space and 51 MiB-// resident -- and nearly all of that 33.2 GiB is V8's process-wide sandbox,-// which is there at zero connections. Override with `--max-connections`.+// 128 matches the handoff bound and is well above normal client fan-out+// (Playwright/Puppeteer use one connection per browser). This also bounds+// per-connection native stack reservations and V8 isolates. Stack address+// space is reserved rather than committed. Override with --max-connections.pub const DEFAULT_MAX_CONNECTIONS: usize = 128;+// Match the CLI's native stack so supported deep parser trees cannot abort+// every connection during recursive layout, paint, or serialization.+const CDP_CONN_STACK_BYTES: usize = 512 * 1024 * 1024;+// How long shutdown waits for connection threads to finish before persisting// the cookie jar. Well under the 10s `docker stop` gives us before SIGKILL.const SHUTDOWN_DRAIN_MS: u64 = 3_000;@@ -831,6 +833,7 @@ fn run_connection(let slot = live_connections.clone();let spawned = std::thread::Builder::new().name("obscura-cdp-conn".into())+ .stack_size(CDP_CONN_STACK_BYTES).spawn(move || {let mut slot_guard = SlotGuard(Some(slot));let default_context = Arc::new(@@ -2701,6 +2704,135 @@ mod tests {}).await.expect("connection and I/O threads must stop on socket close");}+ #[cfg(feature = "render")]+ #[tokio::test(flavor = "current_thread")]+ async fn connection_survives_deep_parser_and_scripted_layouts() {+ use futures_util::{SinkExt, StreamExt};+ use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};+ use std::time::Duration;+ use tokio::sync::Notify;+ use tokio_tungstenite::tungstenite::Message;++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let live = Arc::new(AtomicUsize::new(1));+ let live_server = live.clone();+ let accept = tokio::spawn(async move {+ let (stream, _) = listener.accept().await.unwrap();+ let context = crate::dispatch::CdpContext::new().default_context;+ super::run_connection(stream.into_std().unwrap(), context.clone(), context,+ Arc::new(std::sync::Mutex::new(())), Arc::new(Notify::new()), live_server);+ });+ let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();+ accept.await.unwrap();+ ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget",+ "params":{"url":"about:blank"}}).to_string().into())).await.unwrap();+ let target_id = loop {+ let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();+ if let Message::Text(text) = message {+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();+ if value["id"] == 1 {+ break value["result"]["targetId"].as_str().unwrap().to_string();+ }+ }+ };+ let session = format!("{target_id}-session");+ let scripted = "(function(){document.body.textContent='';let parent=document.body;for(let i=0;i<1500;i++){const child=document.createElement('div');parent.appendChild(child);parent=child}parent.textContent='content';const r=document.body.getBoundingClientRect();return {height:r.height,nodes:document.querySelectorAll('div').length}})()";+ for (index, (count, with_mutations)) in [(400, false), (10000, false), (1500, true)].into_iter().enumerate() {+ let expression = if with_mutations {+ scripted.to_string()+ } else {+ format!("(function(){{document.body.innerHTML='<div>'.repeat({count})+'content';const r=document.body.getBoundingClientRect();return {{height:r.height,nodes:document.querySelectorAll('div').length}}}})()")+ };+ let id = index + 2;+ ws.send(Message::Text(json!({"id":id,"method":"Runtime.evaluate","sessionId":session,+ "params":{"expression":expression,"returnByValue":true}}).to_string().into())).await.unwrap();+ loop {+ let message = tokio::time::timeout(Duration::from_secs(20), ws.next()).await.unwrap().unwrap().unwrap();+ if let Message::Text(text) = message {+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();+ if value["id"] == id {+ assert!(value["error"].is_null(), "{value}");+ assert!(value["result"]["exceptionDetails"].is_null(), "{value}");+ assert_eq!(value["result"]["result"]["value"]["nodes"].as_u64(), Some(count), "{value}");+ assert!(value["result"]["result"]["value"]["height"].as_f64().unwrap() > 0.0, "{value}");+ break;+ }+ }+ }+ }+ ws.close(None).await.unwrap();+ tokio::time::timeout(Duration::from_secs(5), async {+ while live.load(Ordering::Acquire) != 0 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ }).await.expect("deep-document connection must release its slot");+ }++ #[tokio::test(flavor = "current_thread")]+ async fn busy_page_tcp_resets_release_every_connection() {+ use futures_util::{SinkExt, StreamExt};+ use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};+ use std::time::Duration;+ use tokio_tungstenite::{MaybeTlsStream, tungstenite::Message};++ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let live = Arc::new(AtomicUsize::new(0));+ let live_server = live.clone();+ let accept = tokio::spawn(async move {+ let context = crate::dispatch::CdpContext::new().default_context;+ for _ in 0..8 {+ let (stream, _) = listener.accept().await.unwrap();+ live_server.fetch_add(1, Ordering::AcqRel);+ super::run_connection(stream.into_std().unwrap(), context.clone(), context.clone(),+ Arc::new(std::sync::Mutex::new(())), Arc::new(tokio::sync::Notify::new()), live_server.clone());+ }+ });+ for _ in 0..8 {+ let (mut ws, _) = tokio_tungstenite::connect_async(format!("ws://{address}/devtools/browser")).await.unwrap();+ ws.send(Message::Text(json!({"id":1,"method":"Target.createTarget",+ "params":{"url":"about:blank"}}).to_string().into())).await.unwrap();+ let target_id = loop {+ let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();+ if let Message::Text(text) = message {+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();+ if value["id"] == 1 {+ break value["result"]["targetId"].as_str().unwrap().to_string();+ }+ }+ };+ ws.send(Message::Text(json!({"id":2,"method":"Runtime.evaluate",+ "sessionId":format!("{target_id}-session"),+ "params":{"expression":"requestAnimationFrame(function busy(){requestAnimationFrame(busy)});const channel=new MessageChannel();channel.port1.onmessage=()=>channel.port2.postMessage(null);channel.port2.postMessage(null);'armed'","returnByValue":true}})+ .to_string().into())).await.unwrap();+ loop {+ let message = tokio::time::timeout(Duration::from_secs(5), ws.next()).await.unwrap().unwrap().unwrap();+ if let Message::Text(text) = message {+ let value: serde_json::Value = serde_json::from_str(&text).unwrap();+ if value["id"] == 2 {+ assert_eq!(value["result"]["result"]["value"], "armed", "{value}");+ break;+ }+ }+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ // Zero linger sends an RST without a WebSocket close handshake.+ #[allow(deprecated)]+ match ws.get_mut() {+ MaybeTlsStream::Plain(stream) => stream.set_linger(Some(Duration::ZERO)).unwrap(),+ _ => panic!("local ws connection unexpectedly used TLS"),+ }+ drop(ws);+ tokio::time::timeout(Duration::from_secs(5), async {+ while live.load(Ordering::Acquire) != 0 {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ }).await.expect("busy disconnected page must release its connection");+ }+ accept.await.unwrap();+ }+#[tokio::test(flavor = "current_thread")]async fn connection_fetch_progresses_during_continuously_ready_page_tasks() {use futures_util::{SinkExt, StreamExt};diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rsindex 95a60456..66ab2b79 100644--- a/crates/obscura-dom/src/tree.rs+++ b/crates/obscura-dom/src/tree.rs@@ -1,5 +1,5 @@use html5ever::{LocalName, Namespace, Prefix, QualName};-use std::cell::RefCell;+use std::cell::{Cell, RefCell};use std::collections::{HashMap, HashSet};use std::fmt;use std::sync::Arc;@@ -247,6 +247,9 @@ impl Node {pub struct DomTree {inner: RefCell<DomTreeInner>,+ // Only the last parser parent/child pair is cached; external tree changes+ // invalidate it rather than maintaining depths across DOM reparenting.+ pub(crate) parser_depth_cache: Cell<Option<(NodeId, usize, NodeId, usize)>>,}/// Host-fetched author CSS kept outside the page-visible DOM.@@ -305,6 +308,7 @@ impl DomTree {data: NodeData::Document,};DomTree {+ parser_depth_cache: Cell::new(None),inner: RefCell::new(DomTreeInner {nodes: vec![Some(doc_node)],free_list: Vec::new(),@@ -883,6 +887,7 @@ impl DomTree {whereF: FnOnce(&mut Node) -> R,{+ self.parser_depth_cache.set(None);let mut inner = self.inner.borrow_mut();if inner.nodes.get(id.index()).and_then(Option::as_ref).is_some_and(|node| matches!(node.data, NodeData::Text { .. })) {@@ -892,6 +897,7 @@ impl DomTree {}pub fn append_child(&self, parent_id: NodeId, child_id: NodeId) {+ self.parser_depth_cache.set(None);// Per DOM spec, appending a node to itself is a HierarchyRequestError;// here we treat it as a no-op rather than panic. Without this the// sibling-pointer fixup below sets the node's prev_sibling to itself@@ -978,6 +984,7 @@ impl DomTree {}pub fn insert_before(&self, existing_id: NodeId, new_sibling_id: NodeId) {+ self.parser_depth_cache.set(None);// Per DOM spec: if the node being inserted IS the reference node,// the operation is a no-op (the node is already in its target// position). Without this, the linked-list fixup below sets the@@ -1066,6 +1073,7 @@ impl DomTree {}fn detach_for_reparent(&self, node_id: NodeId, disconnect: bool) {+ self.parser_depth_cache.set(None);let mut inner = self.inner.borrow_mut();// The document and registered ShadowRoots have no ordinary parent anddiff --git a/crates/obscura-dom/src/tree_sink.rs b/crates/obscura-dom/src/tree_sink.rsindex be5a9127..37e52a6d 100644--- a/crates/obscura-dom/src/tree_sink.rs+++ b/crates/obscura-dom/src/tree_sink.rs@@ -8,6 +8,48 @@ use html5ever::{Attribute as HtmlAttribute, LocalName, Namespace, QualName};use crate::tree::{Attribute, DomTree, NodeData, NodeId, ShadowRootMode};+const MAX_PARSER_DEPTH: usize = 512;++impl DomTree {+ fn parser_insertion_parent(&self, parent: NodeId) -> (NodeId, Option<usize>) {+ if let Some((previous_parent, parent_depth, previous_child, child_depth)) =+ self.parser_depth_cache.get()+ {+ let depth = if parent == previous_parent {+ Some(parent_depth)+ } else if parent == previous_child {+ Some(child_depth)+ } else {+ None+ };+ if let Some(depth) = depth {+ if depth <= MAX_PARSER_DEPTH {+ return (parent, Some(depth));+ }+ let up = self.with_node(parent, |node| node.parent).flatten().unwrap_or(parent);+ return (up, Some(depth - 1));+ }+ }+ let inner = self.borrow_inner();+ let mut depth = 0;+ let mut current = parent;+ while let Some(up) = inner.nodes.get(current.index())+ .and_then(Option::as_ref).and_then(|node| node.parent)+ {+ depth += 1;+ if depth > MAX_PARSER_DEPTH {+ let insertion_parent = inner.nodes.get(parent.index()).and_then(Option::as_ref)+ .and_then(|node| node.parent).unwrap_or(parent);+ let known_depth = inner.nodes.get(up.index()).and_then(Option::as_ref)+ .is_some_and(|node| node.parent.is_none()).then_some(depth - 1);+ return (insertion_parent, known_depth);+ }+ current = up;+ }+ (parent, Some(depth))+ }+}+/// DOM's valid-shadow-host-name predicate. Gecko's/// `nsContentUtils::IsValidShadowHostName` uses this same HTML allowlist plus/// valid custom-element names; keeping the check at the parser boundary makes@@ -178,10 +220,19 @@ impl TreeSink for DomTree {fn append(&self, parent: &NodeId, child: NodeOrText<NodeId>) {match child {NodeOrText::AppendNode(node_id) => {- self.append_child(*parent, node_id);+ // Chromium flattens further parser insertions at this depth+ // without changing the tree builder's open-elements stack.+ let (insertion_parent, depth) = self.parser_insertion_parent(*parent);+ self.append_child(insertion_parent, node_id);+ let cache = depth.filter(|_| {+ self.with_node(node_id, |node| node.parent).flatten() == Some(insertion_parent)+ }).map(|depth| (insertion_parent, depth, node_id, depth + 1));+ self.parser_depth_cache.set(cache);}NodeOrText::AppendText(text) => {+ let cache = self.parser_depth_cache.get();self.append_text(*parent, &text);+ self.parser_depth_cache.set(cache);}}}@@ -401,6 +452,97 @@ pub fn parse_fragment_with_context(html: &str, context_name: QualName) -> DomTremod tests {use super::*;+ fn max_div_nesting(tree: &DomTree) -> usize {+ let mut stack = vec![(tree.document(), 0)];+ let mut maximum = 0;+ while let Some((id, depth)) = stack.pop() {+ let is_div = tree.with_node(id, |node| {+ node.as_element().is_some_and(|name| name.local.as_ref() == "div")+ }).unwrap_or(false);+ let depth = depth + usize::from(is_div);+ maximum = maximum.max(depth);+ stack.extend(tree.children(id).into_iter().map(|child| (child, depth)));+ }+ maximum+ }++ #[test]+ fn document_parser_caps_nesting_without_dropping_content() {+ for (count, expected_depth) in [(400, 400), (1000, 511), (100000, 511)] {+ let tree = parse_html(&format!("{}content", "<div>".repeat(count)));+ assert_eq!(max_div_nesting(&tree), expected_depth);+ assert_eq!(tree.query_selector_all("div").unwrap().len(), count);+ assert_eq!(tree.text_content(tree.document()), "content");+ }+ }++ #[test]+ fn fragment_parser_caps_nesting_without_dropping_content() {+ for (count, expected_depth) in [(400, 400), (1000, 512), (100000, 512)] {+ let tree = parse_fragment(&format!("{}content", "<div>".repeat(count)));+ assert_eq!(max_div_nesting(&tree), expected_depth);+ assert_eq!(tree.query_selector_all("div").unwrap().len(), count);+ assert_eq!(tree.text_content(tree.document()), "content");+ }+ }++ #[test]+ fn parser_depth_cap_does_not_restrict_dom_mutations() {+ let tree = parse_html("<main id='root'></main>");+ let mut parent = tree.get_element_by_id("root").unwrap();+ for _ in 0..600 {+ let child = tree.new_node(NodeData::Element {+ name: QualName::new(None, ns!(html), local_name!("div")),+ attrs: vec![],+ template_contents: None,+ mathml_annotation_xml_integration_point: false,+ });+ tree.append_child(parent, child);+ parent = child;+ }+ assert_eq!(max_div_nesting(&tree), 600);+ }++ #[test]+ fn parser_depth_cache_is_invalidated_by_reparenting() {+ let tree = parse_html("<main id='deep'></main><section id='shallow'></section>");+ let mut deep = tree.get_element_by_id("deep").unwrap();+ for _ in 0..600 {+ let child = tree.create_element(QualName::new(None, ns!(html), local_name!("div")),+ vec![], ElementFlags::default());+ tree.append_child(deep, child);+ deep = child;+ }+ let shallow = tree.get_element_by_id("shallow").unwrap();+ let leaf = tree.create_element(QualName::new(None, ns!(html), local_name!("div")),+ vec![], ElementFlags::default());+ TreeSink::append(&tree, &shallow, NodeOrText::AppendNode(leaf));+ assert_eq!(tree.parser_insertion_parent(leaf).0, leaf);+ tree.append_child(deep, shallow);+ assert_eq!(tree.parser_insertion_parent(leaf).0, shallow);+ }++ #[test]+ fn parser_depth_cache_is_invalidated_when_nodes_leave_a_deep_parent() {+ for mutation in ["append", "insert", "detach", "raw"] {+ let tree = parse_html(&"<div>".repeat(1000));+ let leaf = *tree.query_selector_all("div").unwrap().last().unwrap();+ let parent = tree.with_node(leaf, |node| node.parent).flatten().unwrap();+ assert_eq!(tree.parser_insertion_parent(leaf).0, parent);+ let document = tree.document();+ let html = tree.children(document)[0];+ match mutation {+ "append" => tree.append_child(document, leaf),+ "insert" => tree.insert_before(html, leaf),+ "detach" => tree.detach(leaf),+ "raw" => { tree.with_node_mut(leaf, |node| node.parent = None); }+ _ => unreachable!(),+ }+ let expected_depth = usize::from(matches!(mutation, "append" | "insert"));+ assert_eq!(tree.parser_insertion_parent(leaf), (leaf, Some(expected_depth)));+ }+ }+#[test]fn test_parse_simple_html() {let tree = parse_html("<html><head></head><body><h1>Hello</h1></body></html>");diff --git a/docs/Architecture-overview.md b/docs/Architecture-overview.mdindex 6a821fd3..70b98f3b 100644--- a/docs/Architecture-overview.md+++ b/docs/Architecture-overview.md@@ -88,6 +88,18 @@ within one connection so handlers do not interleave isolate entry. It is not aprocess-wide lock. Long operations use `process_with_interception` in`server.rs` so the connection can keep processing interception messages.+Connection threads reserve the same 512 MiB native stack address range as the+CLI, with memory committed on demand. This protects recursive native rendering+from the small default thread stack. HTML parsing also flattens excessive+nesting like Chromium: 511 nested divs in a document and 512 in a fragment,+without discarding elements or text. This parser rule does not cap DOM mutations.+The last parser parent/child depths are cached to avoid walking every ancestor+on ordinary insertions; DOM mutations invalidate that cache. The+`render-repros/deep-parser-layout.html` fixture covers retained content and the+Chromium-compatible fragment depth.+The performance smoke gate includes balanced HTML trees at depths 4, 32, 128,+and 300 so the depth guard cannot hide a parser throughput regression.+Targets and sessions belong to the connection that created them. A separatebrowser WebSocket does not attach to another connection's pages. Within oneconnection, additional flattened sessions can observe the same target.diff --git a/render-repros/checks.json b/render-repros/checks.jsonindex e2c7e117..3aec5c6a 100644--- a/render-repros/checks.json+++ b/render-repros/checks.json@@ -1,4 +1,7 @@{+ "deep-parser-layout": [+ {"name": "fragment depth matches Chromium without losing the last element", "color": "#3186e8", "x": 545, "width": 80, "height": 20}+ ],"hidden-table-rows": [{"name": "rowspan counts visible rows only", "color": "#1971c2", "x": 20, "y": 20, "width": 30, "height": 40},{"name": "next visible row occupies the second column", "color": "#e8590c", "x": 50, "y": 40, "width": 30, "height": 20},diff --git a/render-repros/deep-parser-layout.html b/render-repros/deep-parser-layout.htmlnew file mode 100644index 00000000..c238b7de--- /dev/null+++ b/render-repros/deep-parser-layout.html@@ -0,0 +1,25 @@+<!doctype html>+<meta charset="utf-8">+<title>Deep parser layout</title>+<style>+ body { margin: 24px; font: 18px sans-serif; color: #17324d; background: white; }+ h1 { font-size: 26px; }+ #root { border: 1px solid #17324d; padding: 8px; }+ #root div { padding-left: 1px; }+ #stats { margin-top: 20px; }+</style>+<h1>Deep parsed DOM retains every element</h1>+<main id="root"></main>+<pre id="stats"></pre>+<script>+ const root = document.getElementById("root");+ const count = 600;+ root.innerHTML = "<div>".repeat(count) + "All " + count + " nodes retained";+ const divs = root.querySelectorAll("div");+ const marker = document.createElement("span");+ marker.style.cssText = "display:block;width:80px;height:20px;background:#3186e8";+ divs[divs.length - 1].appendChild(marker);+ let depth = 0;+ for (let node = divs[divs.length - 1]; node !== root; node = node.parentElement) depth++;+ document.getElementById("stats").textContent = "Nodes: " + divs.length + "\nDiv depth: " + depth;+</script>diff --git a/scripts/ci/perf_smoke.py b/scripts/ci/perf_smoke.pyindex 5db9d7a4..513b9a92 100755--- a/scripts/ci/perf_smoke.py+++ b/scripts/ci/perf_smoke.py@@ -48,6 +48,16 @@ SCENARIOS = {200000,),}+SCENARIOS.update({+ f"html-parse-depth-{depth}": (+ "(function(){const html='<div>'.repeat(" + str(depth) + ")+"+ "'text'+'</div>'.repeat(" + str(depth) + ");"+ "for(let i=0;i<3;i++)document.body.innerHTML=html.repeat(60);"+ "return document.querySelectorAll('div').length})()",+ depth * 60,+ )+ for depth in (4, 32, 128, 300)+})class Handler(BaseHTTPRequestHandler):