The headless browser for AI agents and web scraping
fix(render): run the style cascade on an explicit stack
SGavrl11e142292b53
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 881a0c40..0aaa535c 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -2558,7 +2558,11 @@ fn apply_picture_source_hints(/// `matcher`'s ancestor filter as we descend so descendant-combinator rules/// fast-reject correctly. Non-element nodes (text, comments) are skipped but/// still walked through, since an element may be their descendant.-fn cascade_walk(+/// Per-node half of the style cascade: compute and record the style for+/// one node and report the values its subtree inherits. Split out of+/// `cascade_walk` so the traversal can run on an explicit work stack+/// instead of one native frame per DOM level.+fn cascade_node_style(tree: &DomTree,id: NodeId,sheet: &crate::css::Stylesheet,@@ -2576,9 +2580,14 @@ fn cascade_walk(inherited_cell_padding: Option<f32>,inherited_color_scheme_dark: bool,fresh_styles: Option<&HashSet<NodeId>>,-) {+) -> Option<(+ std::rc::Rc<HashMap<String, String>>,+ Option<f32>,+ bool,+ bool,+)> {let Some(node) = tree.get_node(id) else {- return;+ return None;};let is_element = node.is_element();// The custom-property map in force for this node's subtree: the parent's,@@ -2827,108 +2836,210 @@ fn cascade_walk(styles.insert(id, style);}- if is_element {- matcher.push_ancestor(tree, id);+ Some((+ this_props,+ descendant_cell_padding,+ descendant_color_scheme_dark,+ is_element,+ ))+}++/// Compute the UA + author style for every element in preorder, maintaining+/// `matcher`'s ancestor filter as we descend so descendant-combinator rules+/// fast-reject correctly. Non-element nodes (text, comments) are skipped but+/// still walked through, since an element may be their descendant.+///+/// The traversal runs on an explicit work stack. It used to recurse once per+/// DOM level, and the per-level frame is large (UA style, rule matching, and+/// pseudo-style temporaries), so a page-controlled tree a few dozen levels+/// deep overflowed the caller's thread stack and aborted the whole process.+/// Stack usage is now independent of DOM depth.+fn cascade_walk(+ tree: &DomTree,+ id: NodeId,+ sheet: &crate::css::Stylesheet,+ document_sheet: &crate::css::Stylesheet,+ shadow_sheets: &HashMap<NodeId, std::sync::Arc<crate::css::Stylesheet>>,+ matcher: &mut obscura_dom::selector::Matcher,+ styles: &mut HashMap<NodeId, crate::LayoutStyle>,+ custom_properties: &mut HashMap<NodeId, std::rc::Rc<HashMap<String, String>>>,+ parent_props: &std::rc::Rc<HashMap<String, String>>,+ container_evaluator: &mut Option<&mut crate::css::ContainerQueryEvaluator<'_>>,+ quirks_mode: bool,+ viewport: (f32, f32),+ animation_sample: crate::AnimationSample,+ animation_timeline: &mut crate::AnimationTimelineState,+ inherited_cell_padding: Option<f32>,+ inherited_color_scheme_dark: bool,+ fresh_styles: Option<&HashSet<NodeId>>,+) {+ #[derive(Clone, Copy, PartialEq, Eq)]+ enum MatcherBase {+ // Push/pop on the matcher currently on top (the caller's matcher, or+ // the enclosing subtree's), matching the recursive descent.+ Incremental,+ // Assigned (slotted) nodes match from a matcher pre-seeded with their+ // light-DOM ancestors.+ FreshFromAncestors,+ // Shadow-root children match with an empty ancestor filter, so+ // document rules stay out of the shadow tree.+ FreshEmpty,}- let is_shadow_host = tree.shadow_root(id).is_some();- for cid in tree.children(id) {- // Assigned light children are cascaded from their flattened slot- // below. Unslotted children still need CSSOM-computed styles and stay- // on the ordinary host path.- if is_shadow_host && tree.assigned_slot(cid).is_some() {- continue;- }- cascade_walk(- tree,- cid,- sheet,- document_sheet,- shadow_sheets,- matcher,- styles,- custom_properties,- &this_props,- container_evaluator,- quirks_mode,- viewport,- animation_sample,- animation_timeline,- descendant_cell_padding,- descendant_color_scheme_dark,- fresh_styles,- );- }- if let Some(assigned_nodes) = tree.assigned_nodes(id) {- for cid in assigned_nodes {- let assigned_sheet = tree- .containing_shadow_root(cid)- .and_then(|root| shadow_sheets.get(&root).map(|sheet| &**sheet))- .unwrap_or(document_sheet);- let mut assigned_matcher = tree.matcher();- for ancestor in tree.ancestors(cid).into_iter().rev() {- if tree- .get_node(ancestor)- .is_some_and(|node| node.is_element())- {- assigned_matcher.push_ancestor(tree, ancestor);++ struct Visit<'a> {+ id: NodeId,+ sheet: &'a crate::css::Stylesheet,+ props: std::rc::Rc<HashMap<String, String>>,+ cell_padding: Option<f32>,+ color_scheme_dark: bool,+ matcher_base: MatcherBase,+ use_container_evaluator: bool,+ }++ enum Work<'a> {+ Visit(Visit<'a>),+ PopAncestor,+ PopSubtreeMatcher,+ }++ let mut subtree_matchers: Vec<obscura_dom::selector::Matcher> = Vec::new();+ let mut work: Vec<Work> = vec![Work::Visit(Visit {+ id,+ sheet,+ props: parent_props.clone(),+ cell_padding: inherited_cell_padding,+ color_scheme_dark: inherited_color_scheme_dark,+ matcher_base: MatcherBase::Incremental,+ use_container_evaluator: true,+ })];++ while let Some(item) = work.pop() {+ match item {+ Work::PopAncestor => {+ if let Some(top) = subtree_matchers.last_mut() {+ top.pop_ancestor();+ } else {+ matcher.pop_ancestor();}}- cascade_walk(- tree,- cid,- assigned_sheet,- document_sheet,- shadow_sheets,- &mut assigned_matcher,- styles,- custom_properties,- &this_props,- container_evaluator,- quirks_mode,- viewport,- animation_sample,- animation_timeline,- descendant_cell_padding,- descendant_color_scheme_dark,- fresh_styles,- );- }- }- if let Some(root) = tree.shadow_root(id) {- // Start matching with an empty ancestor filter at each tree-scope- // boundary. That keeps document rules out of the shadow tree and- // shadow rules out of the document/other roots by construction.- if let Some(shadow_sheet) = shadow_sheets.get(&root) {- let mut shadow_matcher = tree.matcher();- let mut no_container_evaluator = None;- for child in tree.children(root) {- cascade_walk(+ Work::PopSubtreeMatcher => {+ subtree_matchers.pop();+ }+ Work::Visit(visit) => {+ if visit.matcher_base != MatcherBase::Incremental {+ let mut fresh = tree.matcher();+ if visit.matcher_base == MatcherBase::FreshFromAncestors {+ for ancestor in tree.ancestors(visit.id).into_iter().rev() {+ if tree+ .get_node(ancestor)+ .is_some_and(|node| node.is_element())+ {+ fresh.push_ancestor(tree, ancestor);+ }+ }+ }+ subtree_matchers.push(fresh);+ // Runs after the subtree's own PopAncestor markers.+ work.push(Work::PopSubtreeMatcher);+ }+ let current_matcher = subtree_matchers.last_mut().unwrap_or(&mut *matcher);+ let mut no_container_evaluator = None;+ let evaluator: &mut Option<&mut crate::css::ContainerQueryEvaluator<'_>> =+ if visit.use_container_evaluator {+ container_evaluator+ } else {+ &mut no_container_evaluator+ };+ let Some((+ this_props,+ descendant_cell_padding,+ descendant_color_scheme_dark,+ is_element,+ )) = cascade_node_style(tree,- child,- shadow_sheet,+ visit.id,+ visit.sheet,document_sheet,shadow_sheets,- &mut shadow_matcher,+ current_matcher,styles,custom_properties,- &this_props,- &mut no_container_evaluator,+ &visit.props,+ evaluator,quirks_mode,viewport,animation_sample,animation_timeline,- None,- descendant_color_scheme_dark,+ visit.cell_padding,+ visit.color_scheme_dark,fresh_styles,- );+ ) else {+ continue;+ };++ if is_element {+ current_matcher.push_ancestor(tree, visit.id);+ work.push(Work::PopAncestor);+ }+ // LIFO: push the later phases first so regular children run+ // first, then assigned nodes, then the shadow subtree, all in+ // document order.+ if let Some(root) = tree.shadow_root(visit.id) {+ if let Some(shadow_sheet) = shadow_sheets.get(&root) {+ for child in tree.children(root).into_iter().rev() {+ work.push(Work::Visit(Visit {+ id: child,+ sheet: shadow_sheet,+ props: this_props.clone(),+ cell_padding: None,+ color_scheme_dark: descendant_color_scheme_dark,+ matcher_base: MatcherBase::FreshEmpty,+ use_container_evaluator: false,+ }));+ }+ }+ }+ if let Some(assigned_nodes) = tree.assigned_nodes(visit.id) {+ for cid in assigned_nodes.into_iter().rev() {+ let assigned_sheet = tree+ .containing_shadow_root(cid)+ .and_then(|root| shadow_sheets.get(&root).map(|sheet| &**sheet))+ .unwrap_or(document_sheet);+ work.push(Work::Visit(Visit {+ id: cid,+ sheet: assigned_sheet,+ props: this_props.clone(),+ cell_padding: descendant_cell_padding,+ color_scheme_dark: descendant_color_scheme_dark,+ matcher_base: MatcherBase::FreshFromAncestors,+ use_container_evaluator: true,+ }));+ }+ }+ let is_shadow_host = tree.shadow_root(visit.id).is_some();+ for cid in tree.children(visit.id).into_iter().rev() {+ // Assigned light children are cascaded from their flattened+ // slot above. Unslotted children still need CSSOM-computed+ // styles and stay on the ordinary host path.+ if is_shadow_host && tree.assigned_slot(cid).is_some() {+ continue;+ }+ work.push(Work::Visit(Visit {+ id: cid,+ sheet: visit.sheet,+ props: this_props.clone(),+ cell_padding: descendant_cell_padding,+ color_scheme_dark: descendant_color_scheme_dark,+ matcher_base: MatcherBase::Incremental,+ use_container_evaluator: visit.use_container_evaluator,+ }));+ }}}}- if is_element {- matcher.pop_ancestor();- }}+#[derive(Default)]struct CssCounterState {values: HashMap<String, Vec<i32>>,diff --git a/crates/obscura-render/tests/layout_test.rs b/crates/obscura-render/tests/layout_test.rsindex 084653ce..ad3b12c1 100644--- a/crates/obscura-render/tests/layout_test.rs+++ b/crates/obscura-render/tests/layout_test.rs@@ -4471,3 +4471,28 @@ fn grid_ordinary_aspect_ratio_preserves_normal_alignment_provenance() {assert_eq!(size("parent-align-stretch"), (400.0, 200.0));assert_eq!(size("parent-justify-stretch"), (300.0, 150.0));}++#[test]+fn deeply_nested_wrappers_cascade_without_stack_overflow() {+ // The style cascade used to recurse once per DOM level with a fat frame,+ // so a page-controlled tree a few dozen levels deep overflowed the native+ // stack and aborted the process. The traversal is iterative now; depth+ // must change neither survival nor rule matching.+ let open: String = (0..400).map(|_| "<span>").collect::<Vec<_>>().join("");+ let close = "</span>".repeat(400);+ let tree = parse_html(&format!(+ r#"<style>+ html, body {{ margin:0; font:16px/18px monospace }}+ div span #deep {{ display:block; width:50px }}+ </style>+ <div>{open}<span id="deep">deep</span>{close}<input type="checkbox"></div>"#+ ));+ let layout = layout_dom(&tree, (400.0, 200.0));+ let rect = layout.rects[&tree.get_element_by_id("deep").unwrap()];+ // A descendant-combinator match at depth 400: the matcher's ancestor+ // filter is maintained across the whole iterative walk.+ assert!(+ (rect.width - 50.0).abs() < 0.01,+ "the descendant rule must match at depth 400, got {rect:?}"+ );+}