Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
perf(cssom): reuse size projections within style observations
ldm00e14d8248618
diff --git a/moli-layout/src/layout_tree/source_query.rs b/moli-layout/src/layout_tree/source_query.rsindex 999e6e138..7db002011 100644--- a/moli-layout/src/layout_tree/source_query.rs+++ b/moli-layout/src/layout_tree/source_query.rs@@ -11,7 +11,7 @@ use super::{LayoutSize, LayoutTransform2D, LayoutUsedSize,},query::{LayoutElementMetrics, LayoutNodeOutput},- tree::{CssSizingBox, FrozenLayoutTree},+ tree::{CssSizingBox, FrozenLayoutBox, FrozenLayoutTree},};#[derive(Clone, Copy, Debug, PartialEq)]@@ -61,32 +61,24 @@ whereself.element_metrics_for_source_with_offset_parent_filter(source, |_| true)}- /// Physical and logical CSSOM sizes from this snapshot's sizing box, without transforms,- /// integer rounding, or absolute CSS zoom. A source without an applicable- /// principal box has no used size; consumers keep its computed value.+ /// Physical and logical CSSOM sizes from this snapshot's sizing box,+ /// without transforms, integer rounding, or absolute CSS zoom. A source+ /// without an applicable principal box keeps its computed value.pub fn used_size_for_source(&self, source: N) -> Option<LayoutUsedSize> {let layout_box = self.boxes.iter().find(|layout_box| layout_box.principal_source == Some(source))?;- let sizing = layout_box.css_sizing?;- let rect = match sizing.box_kind {- CssSizingBox::Content => layout_box.content_box,- CssSizingBox::Border => layout_box.border_box,- };- let size = CssomAbsoluteZoom::new(layout_box.effective_zoom)- .size(LayoutSize::new(rect.width, rect.height));- let (inline_size, block_size) = if sizing.horizontal {- (size.width, size.height)- } else {- (size.height, size.width)- };- Some(LayoutUsedSize {- width: size.width,- height: size.height,- inline_size,- block_size,- })+ layout_box.used_size()+ }++ /// Derives all applicable sizing boxes in one pass. A batch consumer may+ /// collect this into an operation-local lookup; no index is retained by+ /// the frozen tree, and no DOM or style input is consulted.+ pub fn used_sizes(&self) -> impl Iterator<Item = (N, LayoutUsedSize)> + '_ {+ self.boxes+ .iter()+ .filter_map(|layout_box| Some((layout_box.principal_source?, layout_box.used_size()?)))}/// Returns the exact unprojected content box produced for a source's@@ -499,6 +491,29 @@ where}}+impl<N> FrozenLayoutBox<N> {+ fn used_size(&self) -> Option<LayoutUsedSize> {+ let sizing = self.css_sizing?;+ let rect = match sizing.box_kind {+ CssSizingBox::Content => self.content_box,+ CssSizingBox::Border => self.border_box,+ };+ let size = CssomAbsoluteZoom::new(self.effective_zoom)+ .size(LayoutSize::new(rect.width, rect.height));+ let (inline_size, block_size) = if sizing.horizontal {+ (size.width, size.height)+ } else {+ (size.height, size.width)+ };+ Some(LayoutUsedSize {+ width: size.width,+ height: size.height,+ inline_size,+ block_size,+ })+ }+}+/// Converts effective-zoomed layout scalars to the coordinate space exposed/// by CSSOM box sizes and scroll metrics. Viewport quads intentionally stay/// zoomed: their normalized bases map points back into these unzoomed sizes.diff --git a/moli-layout/tests/phase5_output_contract.rs b/moli-layout/tests/phase5_output_contract.rsindex 58ede2864..57d7783b2 100644--- a/moli-layout/tests/phase5_output_contract.rs+++ b/moli-layout/tests/phase5_output_contract.rs@@ -1963,6 +1963,15 @@ fn frozen_used_size_keeps_its_sizing_basis_after_style_inputs_are_discarded() {block_size: 50.5}));+ let retention = output.retention_metrics();+ let used_sizes = output.used_sizes().collect::<HashMap<_, _>>();+ assert_eq!(used_sizes.len(), 2);+ assert_eq!(used_sizes.get(&1).copied(), output.used_size_for_source(1));+ assert_eq!(+ output.retention_metrics(),+ retention,+ "the batch lookup must stay outside the frozen tree"+ );let model = output.box_model_for_source(1).expect("sized box");let expected_border_width = if box_sizing == BoxSizing::ContentBox {130.25@@ -1997,7 +2006,14 @@ fn frozen_used_size_excludes_non_replaced_inlines_and_suppressed_boxes() {styles.0.insert(index, fixed_size(display, 60.0, 25.0));}let output = build(&source, &mut styles);+ let used_sizes = output.used_sizes().collect::<HashMap<_, _>>();+ assert_eq!(+ used_sizes.len(),+ 2,+ "only the root and the displayed child have sizing boxes"+ );for source in [1, 2, 3, usize::MAX] {+ assert!(!used_sizes.contains_key(&source));assert_eq!(output.used_size_for_source(source),None,@@ -2013,6 +2029,7 @@ fn frozen_used_size_excludes_non_replaced_inlines_and_suppressed_boxes() {block_size: 25.0}));+ assert_eq!(used_sizes.get(&4).copied(), output.used_size_for_source(4));}#[test]diff --git a/moli-renderer-v8/src/native_bridge/element/styles.rs b/moli-renderer-v8/src/native_bridge/element/styles.rsindex 4dcfb3999..7f4e2132c 100644--- a/moli-renderer-v8/src/native_bridge/element/styles.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles.rs@@ -577,21 +577,28 @@ pub(in crate::native_bridge::element) fn style_viewport_for_document(pub(crate) fn computed_style_property_values_for_document_snapshot(host: &JsContextHost,- handle: DomHandle,+ handles: impl IntoIterator<Item = DomHandle>,properties: &[String],-) -> Option<Vec<String>> {- let DocumentSnapshotStyleComputation::Available(context) =- style_computation_context_for_document_snapshot(host, handle)?- else {- return Some(vec![String::new(); properties.len()]);- };- let style = ComputedStyleRead::new_with_context(host, handle, context);- Some(- properties- .iter()- .map(|property| style.property(property))- .collect(),- )+) -> Vec<Vec<String>> {+ let mut observation = StyleObservation::new(host);+ handles+ .into_iter()+ .map(+ |handle| match style_computation_context_for_document_snapshot(host, handle) {+ None => Vec::new(),+ Some(DocumentSnapshotStyleComputation::HiddenChildFrame) => {+ vec![String::new(); properties.len()]+ }+ Some(DocumentSnapshotStyleComputation::Available(_)) => {+ let style = observation.read(handle);+ properties+ .iter()+ .map(|property| style.property(property))+ .collect()+ }+ },+ )+ .collect()}pub(crate) fn computed_style_properties_for_inspector_handle(diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration.rsindex 360fbf0f6..11d5d9300 100644--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration.rs@@ -2,6 +2,7 @@ mod identity;mod observation;mod parse;mod properties;+mod sizing;mod style_world;mod values;diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rsindex 82bf4d878..5e9cb6f1b 100644--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation.rs@@ -10,6 +10,7 @@ use crate::{use super::super::super::super::JsContextHost;use super::super::style_viewport_for_document;+use super::sizing::LayoutSizeReads;use super::style_world::{StyleObservationKey, prepare_style_world_update, stylesheet_query_fallback,stylesheet_source_document_for_handle, stylo_style_environment,@@ -75,6 +76,9 @@ pub(crate) struct StyleObservation<'a> {/// viewport input epoch, but do not become the baseline for ordinary DOM/// API observations.tracks_persistent_world: bool,+ /// A single-element read memoizes just its result; an explicit multi-node+ /// observation can instead derive a temporary per-Document size lookup.+ sizing_target: Option<DomHandle>,drained_document: Option<DomHandle>,additional_drained_documents: Vec<DomHandle>,primary_document: Option<Rc<StyleObservationInputs<'a>>>,@@ -93,6 +97,7 @@ pub(super) struct StyleObservationInputs<'a> {tracks_persistent_world: bool,prepared_update: RefCell<Option<Rc<PreparedStyleWorldUpdate>>>,stylesheet_query_snapshot: RefCell<Option<Rc<FullStyleWorldSnapshot>>>,+ layout_sizes: LayoutSizeReads,}impl<'a> StyleObservationInputs<'a> {@@ -101,6 +106,7 @@ impl<'a> StyleObservationInputs<'a> {source_document: Option<DomHandle>,context: StyleComputationContext,_tracks_persistent_world: bool,+ sizing_target: Option<DomHandle>,) -> Self {let environment = stylo_style_environment(runtime, source_document);Self {@@ -112,6 +118,7 @@ impl<'a> StyleObservationInputs<'a> {tracks_persistent_world: _tracks_persistent_world,prepared_update: RefCell::new(None),stylesheet_query_snapshot: RefCell::new(None),+ layout_sizes: LayoutSizeReads::new(sizing_target),}}@@ -166,9 +173,15 @@ impl<'a> StyleObservationInputs<'a> {pub(super) trait RetainedStyleObservation {fn style_snapshot(&self, handle: DomHandle) -> Option<StyloComputedStyleSnapshot>;+ fn used_size(&self, handle: DomHandle) -> Option<moli_layout::LayoutUsedSize>;}impl RetainedStyleObservation for StyleObservationInputs<'_> {+ fn used_size(&self, handle: DomHandle) -> Option<moli_layout::LayoutUsedSize> {+ self.layout_sizes+ .get(self.runtime, self.source_document(), handle)+ }+fn style_snapshot(&self, handle: DomHandle) -> Option<StyloComputedStyleSnapshot> {#[cfg(debug_assertions)]let invariant_input = self@@ -215,7 +228,7 @@ impl RetainedStyleObservation for StyleObservationInputs<'_> {impl<'a> StyleObservation<'a> {pub(crate) fn new(runtime: &'a JsContextHost) -> Self {- Self::new_with_fixed_context(runtime, None, true)+ Self::new_with_fixed_context(runtime, None, true, None)}/// Creates one synchronous style-observation scope for an exact document@@ -236,25 +249,29 @@ impl<'a> StyleObservation<'a> {runtime,Some(StyleComputationContext::new(viewport).with_read_document(Some(document))),false,+ None,)}- pub(super) fn new_with_context(+ pub(super) fn new_for_element(runtime: &'a JsContextHost,- context: StyleComputationContext,+ handle: DomHandle,+ context: Option<StyleComputationContext>,) -> Self {- Self::new_with_fixed_context(runtime, Some(context), true)+ Self::new_with_fixed_context(runtime, context, true, Some(handle))}fn new_with_fixed_context(runtime: &'a JsContextHost,fixed_context: Option<StyleComputationContext>,tracks_persistent_world: bool,+ sizing_target: Option<DomHandle>,) -> Self {Self {runtime,fixed_context,tracks_persistent_world,+ sizing_target,drained_document: None,additional_drained_documents: Vec::new(),primary_document: None,@@ -377,6 +394,7 @@ impl<'a> StyleObservation<'a> {source_document,context,self.tracks_persistent_world,+ self.sizing_target,));if self.primary_document.is_none() {self.primary_document = Some(Rc::clone(&observation));@@ -398,3 +416,6 @@ pub(crate) struct ComputedStyleRead<'a> {pub(super) observation_inputs: Rc<StyleObservationInputs<'a>>,pub(super) stylo_style: Option<StyloComputedStyleSnapshot>,}++#[cfg(test)]+mod sizing_tests;diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation/sizing_tests.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation/sizing_tests.rsnew file mode 100644index 000000000..9a3b61ca9--- /dev/null+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation/sizing_tests.rs@@ -0,0 +1,346 @@+use super::super::sizing::{SizeQueryCounts, take_query_counts};+use super::*;+use crate::{+ dom::native::DomHost,+ parser::HtmlParser,+ script_vm::{ScriptVmDefaultWorldBootstrap, StandaloneScriptVmHarness},+};++fn fixture(body: &str) -> StandaloneScriptVmHarness {+ let _runtime = crate::JsRuntime::initialize();+ let document = HtmlParser::SCRIPTING_ENABLED.parse(+ url::Url::parse("https://size-queries.test/").unwrap(),+ format!(r#"<!doctype html><style>html,body{{margin:0}}.sized{{width:500px;height:400px;max-width:120px;max-height:80px}}</style>{body}"#),+ );+ let queue = crate::page_task_queue::PageTaskQueueTestHarness::new();+ let mut vm = ScriptVmDefaultWorldBootstrap::standalone_from_dom_host_for_test(+ DomHost::from_dom(document),+ queue.owner_attached_runtime_page_task_sender_for_test(),+ queue.parser_boundary_sender(),+ )+ .unwrap()+ .finish()+ .unwrap();+ vm.install_page_task_residence_for_executor_test(queue.residence());+ vm.set_layout_policy(crate::real_layout_test_policy());+ vm+}++fn sample(vm: &mut StandaloneScriptVmHarness) {+ assert!(+ vm.screenshot_layout_snapshot(moli_layout::LayoutViewport::new(320, 240, 1.0))+ .unwrap()+ .is_some()+ );+}++fn sizes(read: &ComputedStyleRead<'_>) -> [String; 4] {+ ["width", "height", "inline-size", "block-size"].map(|property| read.property(property))+}++#[test]+fn computed_size_property_batch_looks_up_one_element_once_without_a_document_index() {+ let mut vm = fixture("<div id=target class=sized></div>");+ sample(&mut vm);+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let target = host.dom_host().element_handle_by_id("target").unwrap();+ let before = host.layout_snapshot_cache_observability_for_test();+ take_query_counts();+ let read = ComputedStyleRead::new(&host, target);+ read.property("color");+ assert_eq!(+ take_query_counts(),+ SizeQueryCounts::default(),+ "non-size reads do no geometry work"+ );+ for _ in 0..20 {+ assert_eq!(sizes(&read), ["120px", "80px", "120px", "80px"]);+ }+ assert_eq!(+ take_query_counts(),+ SizeQueryCounts {+ source_queries: 1,+ ..SizeQueryCounts::default()+ }+ );+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);+}++#[test]+fn computed_size_inspector_property_batch_shares_one_size_lookup() {+ let mut vm = fixture("<div id=target class=sized></div>");+ sample(&mut vm);+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let target = host.dom_host().element_handle_by_id("target").unwrap();+ take_query_counts();+ let properties = crate::native_bridge::element::computed_style_properties_for_inspector_handle(+ &host, target,+ )+ .unwrap()+ .into_iter()+ .collect::<std::collections::HashMap<_, _>>();+ for (name, value) in [+ ("width", "120px"),+ ("height", "80px"),+ ("inline-size", "120px"),+ ("block-size", "80px"),+ ] {+ assert_eq!(+ properties.get(name).map(String::as_str),+ Some(value),+ "{name}"+ );+ }+ assert_eq!(+ take_query_counts(),+ SizeQueryCounts {+ source_queries: 1,+ ..SizeQueryCounts::default()+ }+ );+}++#[test]+fn computed_size_dom_snapshot_batches_all_nodes_in_one_observation() {+ let mut markup = String::new();+ for i in 0..128 {+ markup.push_str(&format!("<div class=sized id=box-{i}></div>"));+ }+ let mut vm = fixture(&markup);+ sample(&mut vm);+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let handles = {+ let host = host.borrow();+ (0..128)+ .map(|i| {+ host.dom_host()+ .element_handle_by_id(&format!("box-{i}"))+ .unwrap()+ })+ .collect::<Vec<_>>()+ };+ let properties = ["width", "height", "inline-size", "block-size"].map(String::from);+ take_query_counts();+ let values = vm.computed_style_property_values_for_document_snapshot(handles, &properties);+ assert_eq!(values.len(), 128);+ for sizes in values {+ assert_eq!(sizes, ["120px", "80px", "120px", "80px"]);+ }+ let counts = take_query_counts();+ assert_eq!(counts.index_builds, 1);+ assert_eq!(counts.source_queries, 0);+}++#[test]+fn computed_size_multi_element_batch_indexes_each_box_once_and_drops_its_lookup() {+ let mut markup = String::new();+ for i in 0..512 {+ markup.push_str(&format!("<div class=sized id=box-{i}></div>"));+ }+ markup.push_str("<div id=hidden class=sized style='display:none'></div>");+ let mut vm = fixture(&markup);+ sample(&mut vm);+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let handles = (0..512)+ .map(|i| {+ host.dom_host()+ .element_handle_by_id(&format!("box-{i}"))+ .unwrap()+ })+ .collect::<Vec<_>>();+ let hidden = host.dom_host().element_handle_by_id("hidden").unwrap();+ let before = host.layout_snapshot_cache_observability_for_test();+ let boxes = before.cached.unwrap().1.box_count;+ take_query_counts();+ let weak_inputs;+ {+ let mut observation = StyleObservation::new(&host);+ let first = observation.read(handles[0]);+ weak_inputs = Rc::downgrade(&first.observation_inputs);+ first.property("color");+ assert_eq!(take_query_counts(), SizeQueryCounts::default());+ // Non-box misses must also be answered from the one projection, not+ // repeatedly rescan the complete tree.+ for handle in handles+ .iter()+ .rev()+ .chain(handles.iter())+ .copied()+ .chain([hidden; 20])+ {+ let expected = if handle == hidden {+ ["500px", "400px", "500px", "400px"]+ } else {+ ["120px", "80px", "120px", "80px"]+ };+ assert_eq!(sizes(&observation.read(handle)), expected);+ }+ assert_eq!(+ take_query_counts(),+ SizeQueryCounts {+ source_queries: 0,+ index_builds: 1,+ indexed_boxes: boxes+ }+ );+ assert!(weak_inputs.upgrade().is_some());+ }+ assert!(+ weak_inputs.upgrade().is_none(),+ "no Document or wrapper retains the lookup"+ );+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);+ let mut later = StyleObservation::new(&host);+ assert_eq!(+ sizes(&later.read(handles[0])),+ ["120px", "80px", "120px", "80px"]+ );+ assert_eq!(+ take_query_counts().index_builds,+ 1,+ "a new observation derives its own projection"+ );+}++#[test]+fn computed_size_query_reuse_keeps_cold_mock_and_missing_box_reads_lazy() {+ let mut vm = fixture("<div id=target class=sized style='display:none'></div>");+ for sampled in [false, true] {+ if sampled {+ sample(&mut vm);+ }+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let target = host.dom_host().element_handle_by_id("target").unwrap();+ let before = host.layout_snapshot_cache_observability_for_test();+ take_query_counts();+ let read = ComputedStyleRead::new(&host, target);+ for _ in 0..20 {+ assert_eq!(sizes(&read), ["500px", "400px", "500px", "400px"]);+ }+ assert_eq!(+ take_query_counts().source_queries,+ usize::from(sampled),+ "cache an absent sizing box as well as a present one"+ );+ let mut batch = StyleObservation::new(&host);+ for _ in 0..20 {+ assert_eq!(+ sizes(&batch.read(target)),+ ["500px", "400px", "500px", "400px"]+ );+ }+ assert_eq!(take_query_counts().index_builds, usize::from(sampled));+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);+ }+ vm.set_layout_policy(moli_page_types::LayoutPolicy::Mock);+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let target = host.dom_host().element_handle_by_id("target").unwrap();+ let before = host.layout_snapshot_cache_observability_for_test();+ take_query_counts();+ let read = ComputedStyleRead::new(&host, target);+ assert_eq!(sizes(&read), ["500px", "400px", "500px", "400px"]);+ let mut batch = StyleObservation::new(&host);+ assert_eq!(+ sizes(&batch.read(target)),+ ["500px", "400px", "500px", "400px"]+ );+ assert_eq!(take_query_counts(), SizeQueryCounts::default());+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);+}++#[test]+fn computed_size_query_reuse_does_not_survive_mutation_refresh_or_document_replacement() {+ let mut vm = fixture("<div id=target class=sized></div>");+ sample(&mut vm);+ for (action, expected) in [+ ("'unchanged'", ["120px", "80px", "120px", "80px"]),+ (+ "document.getElementById('target').style.cssText='width:30px;height:20px;writing-mode:vertical-rl';'mutated'",+ ["120px", "80px", "120px", "80px"],+ ),+ ("'refresh'", ["30px", "20px", "20px", "30px"]),+ (+ "document.open();document.write('<!doctype html><div id=target style=\"width:90px;height:50px\"></div>');document.close();'replaced'",+ ["90px", "50px", "90px", "50px"],+ ),+ ] {+ vm.eval(action).unwrap();+ if action == "'refresh'" {+ sample(&mut vm);+ }+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let target = host.dom_host().element_handle_by_id("target").unwrap();+ let before = host.layout_snapshot_cache_observability_for_test();+ take_query_counts();+ assert_eq!(+ sizes(&ComputedStyleRead::new(&host, target)),+ expected,+ "{action}"+ );+ let mut observation = StyleObservation::new(&host);+ assert_eq!(sizes(&observation.read(target)), expected, "{action}");+ let counts = take_query_counts();+ let has_tree = before.cached.is_some();+ assert_eq!(counts.source_queries, usize::from(has_tree));+ assert_eq!(counts.index_builds, usize::from(has_tree));+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);+ }+}++#[test]+fn computed_size_batch_partitions_parent_and_iframe_lookups() {+ let mut vm = fixture(+ "<div id=parent class=sized></div><iframe id=frame style='width:180px;height:120px;border:0'></iframe>",+ );+ vm.eval(r#"+const child=document.getElementById('frame').contentDocument;+child.body.innerHTML='<div id=target style="width:500px;height:400px;max-width:90px;max-height:30px;writing-mode:vertical-rl"></div>';+'installed'+"#).unwrap();+ sample(&mut vm);+ let host = vm.context_host_weak_for_test().upgrade().unwrap();+ let host = host.borrow();+ let parent = host.dom_host().element_handle_by_id("parent").unwrap();+ let frame = host.dom_host().element_handle_by_id("frame").unwrap();+ let child = host.child_browsing_context_document_handle(frame).unwrap();+ let target = host+ .dom_host()+ .element_handle_by_id_in_subtree(child, "target")+ .unwrap();+ assert!(+ host.with_latest_layout_tree_for_document(child, |_| ())+ .is_some(),+ "the fixture must publish the child tree, not just the parent geometry"+ );+ let before = host.layout_snapshot_cache_observability_for_test();+ let mut observation = StyleObservation::new(&host);+ take_query_counts();+ for _ in 0..20 {+ assert_eq!(+ sizes(&observation.read(parent)),+ ["120px", "80px", "120px", "80px"]+ );+ assert_eq!(+ sizes(&observation.read(target)),+ ["90px", "30px", "30px", "90px"]+ );+ }+ let counts = take_query_counts();+ assert_eq!(counts.index_builds, 2);+ assert_eq!(counts.source_queries, 0);+ let parent_read = observation.read(parent);+ let child_size = parent_read.observation_inputs.used_size(target).unwrap();+ assert_eq!(+ [child_size.width, child_size.height],+ [90.0, 30.0],+ "a recursive cross-Document read must not use the parent table"+ );+ assert_eq!(take_query_counts().source_queries, 1);+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);+}diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/sizing.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/sizing.rsnew file mode 100644index 000000000..f1638804d--- /dev/null+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/sizing.rs@@ -0,0 +1,122 @@+//! Lazy, synchronous CSSOM size projections. These belong to a style read,+//! never to the Document or the frozen layout tree. Separate JavaScript+//! getters start separate reads; there is no cache spanning a script turn.+//! The first size query samples the available geometry (including absence)+//! for this synchronous read. Nothing here creates or refreshes layout, and+//! the next observation starts again from the latest published snapshot.++use std::{cell::OnceCell, collections::HashMap};++use moli_layout::LayoutUsedSize;++use crate::{document_runtime::DomHandle, native_bridge::JsContextHost};++pub(super) enum LayoutSizeReads {+ /// A single element's property batch needs one lookup, not a whole index.+ Element(DomHandle, OnceCell<Option<LayoutUsedSize>>),+ /// A multi-element observation derives one lookup per Document, lazily.+ Document(OnceCell<HashMap<DomHandle, LayoutUsedSize>>),+}++impl LayoutSizeReads {+ pub(super) fn new(target: Option<DomHandle>) -> Self {+ match target {+ Some(target) => Self::Element(target, OnceCell::new()),+ None => Self::Document(OnceCell::new()),+ }+ }++ pub(super) fn get(+ &self,+ runtime: &JsContextHost,+ source_document: Option<DomHandle>,+ handle: DomHandle,+ ) -> Option<LayoutUsedSize> {+ let document = size_document(runtime, handle)?;+ // Recursive compatibility reads may ask about a different Document.+ // Never answer those from this observation's document-local table.+ if Some(document) != source_document {+ return lookup_size(runtime, document, handle);+ }+ match self {+ Self::Element(target, size) if *target == handle => {+ *size.get_or_init(|| lookup_size(runtime, document, handle))+ }+ Self::Element(..) => lookup_size(runtime, document, handle),+ Self::Document(sizes) => sizes+ .get_or_init(|| {+ runtime+ .with_latest_layout_tree_for_document(document, |tree| {+ #[cfg(test)]+ note_index_build(tree.boxes.len());+ tree.used_sizes().collect()+ })+ .unwrap_or_default()+ })+ .get(&handle)+ .copied(),+ }+ }+}++pub(super) fn used_size_from_layout_snapshot(+ runtime: &JsContextHost,+ handle: DomHandle,+) -> Option<LayoutUsedSize> {+ lookup_size(runtime, size_document(runtime, handle)?, handle)+}++fn size_document(runtime: &JsContextHost, handle: DomHandle) -> Option<DomHandle> {+ (runtime.layout_policy().uses_real_layout() && runtime.dom_host().is_connected(handle))+ .then(|| runtime.layout_document_for_source(handle))+ .flatten()+}++fn lookup_size(+ runtime: &JsContextHost,+ document: DomHandle,+ handle: DomHandle,+) -> Option<LayoutUsedSize> {+ runtime+ .with_latest_layout_tree_for_document(document, |tree| {+ #[cfg(test)]+ note_source_query();+ tree.used_size_for_source(handle)+ })+ .flatten()+}++#[cfg(test)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(super) struct SizeQueryCounts {+ pub source_queries: usize,+ pub index_builds: usize,+ pub indexed_boxes: usize,+}++#[cfg(test)]+thread_local! {+ static QUERY_COUNTS: std::cell::Cell<SizeQueryCounts> = const {+ std::cell::Cell::new(SizeQueryCounts { source_queries: 0, index_builds: 0, indexed_boxes: 0 })+ };+}++#[cfg(test)]+fn note_source_query() {+ let mut counts = QUERY_COUNTS.get();+ counts.source_queries += 1;+ QUERY_COUNTS.set(counts);+}++#[cfg(test)]+fn note_index_build(boxes: usize) {+ let mut counts = QUERY_COUNTS.get();+ counts.index_builds += 1;+ counts.indexed_boxes += boxes;+ QUERY_COUNTS.set(counts);+}++#[cfg(test)]+pub(super) fn take_query_counts() -> SizeQueryCounts {+ QUERY_COUNTS.replace(SizeQueryCounts::default())+}diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rsindex 314d954d3..051cf0556 100644--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs@@ -31,6 +31,7 @@ use super::super::super::super::JsContextHost;use super::observation::{ComputedStyleRead, RetainedStyleObservation, StyleComputationContext, StyleObservation,};+use super::sizing::used_size_from_layout_snapshot;use super::style_world::{effective_raw_stylesheet_sources, style_base_url, stylesheet_source_document_for_handle,};@@ -185,7 +186,7 @@ impl<'a> StyleResolutionContext<'a> {impl<'a> ComputedStyleRead<'a> {pub(crate) fn new(runtime: &'a JsContextHost, handle: DomHandle) -> Self {- StyleObservation::new(runtime).read(handle)+ StyleObservation::new_for_element(runtime, handle, None).read(handle)}pub(in crate::native_bridge::element::styles) fn new_with_context(@@ -193,7 +194,7 @@ impl<'a> ComputedStyleRead<'a> {handle: DomHandle,context: StyleComputationContext,) -> Self {- StyleObservation::new_with_context(runtime, context).read(handle)+ StyleObservation::new_for_element(runtime, handle, Some(context)).read(handle)}pub(in crate::native_bridge::element) fn property(&self, property: &str) -> String {@@ -5126,7 +5127,10 @@ fn resolve_moli_computed_style_value(return tracks;}if matches!(property, "width" | "height" | "inline-size" | "block-size")- && let Some(size) = used_size_from_layout_snapshot(runtime, handle)+ && let Some(size) = match resolution.observation {+ Some(observation) => observation.used_size(handle),+ None => used_size_from_layout_snapshot(runtime, handle),+ }{let value = match property {"width" => size.width,@@ -5183,21 +5187,6 @@ fn resolve_moli_computed_style_value(value.to_owned()}-fn used_size_from_layout_snapshot(- runtime: &JsContextHost,- handle: DomHandle,-) -> Option<moli_layout::LayoutUsedSize> {- if !runtime.layout_policy().uses_real_layout() || !runtime.dom_host().is_connected(handle) {- return None;- }- let document = runtime.layout_document_for_source(handle)?;- // Reading a CSSOM size never creates or refreshes layout. Use the sizing- // basis frozen with the existing geometry, or keep the style-only path.- runtime- .with_latest_layout_tree_for_document(document, |tree| tree.used_size_for_source(handle))- .flatten()-}-fn resolved_grid_template_tracks(runtime: &JsContextHost,handle: DomHandle,diff --git a/moli-renderer-v8/src/runtime/page_dom_snapshot.rs b/moli-renderer-v8/src/runtime/page_dom_snapshot.rsindex 55a29acf7..0655d56d7 100644--- a/moli-renderer-v8/src/runtime/page_dom_snapshot.rs+++ b/moli-renderer-v8/src/runtime/page_dom_snapshot.rs@@ -190,14 +190,20 @@ impl CapturedDocumentState {empty_string: usize,) {let bounds = lightweight_snapshot_bounds();- for (_, node_id) in &self.nodes.layout_nodes {- let values = match self.style_source {- CapturedDocumentStyleSource::Live => vm- .computed_style_property_values_for_document_snapshot(*node_id, computed_styles)- .unwrap_or_default(),- // These compatibility snapshots retain markup but no live style owner.- CapturedDocumentStyleSource::DetachedMarkup => Vec::new(),- };+ let styles = match self.style_source {+ // One observation shares style preparation and the lazy sizing+ // projection across every node in this Document's capture.+ CapturedDocumentStyleSource::Live => vm+ .computed_style_property_values_for_document_snapshot(+ self.nodes.layout_nodes.iter().map(|(_, node_id)| *node_id),+ computed_styles,+ ),+ // These compatibility snapshots retain markup but no live style owner.+ CapturedDocumentStyleSource::DetachedMarkup => {+ vec![Vec::new(); self.nodes.layout_nodes.len()]+ }+ };+ for values in styles {self.styles.push(values.into_iter()diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rsindex 3d993526f..88e198db2 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size.rs@@ -1,5 +1,6 @@use super::*;+mod capture;mod chromium;mod lifecycle;mod logical;diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/capture.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/capture.rsnew file mode 100644index 000000000..8aaaf2f92--- /dev/null+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/capture.rs@@ -0,0 +1,40 @@+use super::*;++#[tokio::test(flavor = "current_thread")]+async fn computed_size_dom_snapshot_capture_preserves_rows_and_never_starts_layout() {+ run_page_vm_async_test(async move {+ let mut page = page_with_size_fixture(r#"+<section style="width:500px;height:400px;max-width:120px;max-height:80px"></section>+<article style="writing-mode:vertical-rl;width:500px;height:400px;max-width:90px;max-height:30px"></article>+"#)?;+ for sampled in [false, true] {+ if sampled { publish_size_layout(&mut page)?; }+ let cache = page.vm().layout_snapshot_cache_observability_for_test();+ let passes = page.vm().layout_pass_observability_for_test().1;+ let payload = page.dom_snapshot_capture_payload("top", crate::runtime::RendererDomSnapshotCaptureOptions {+ computed_styles: ["width","height","inline-size","block-size"].map(String::from).to_vec(),+ ..Default::default()+ }).expect("Document capture").into_protocol_payload();+ let strings = payload["strings"].as_array().expect("string table");+ let decode = |index: &serde_json::Value| strings[index.as_u64().unwrap() as usize].as_str().unwrap();+ let document = &payload["documents"][0];+ let nodes = document["nodes"]["nodeName"].as_array().expect("node names");+ let layout = &document["layout"];+ let indices = layout["nodeIndex"].as_array().expect("layout indices");+ assert_eq!(indices.len(), layout["styles"].as_array().unwrap().len());+ for (tag, expected) in if sampled {+ [("SECTION", ["120px","80px","120px","80px"]), ("ARTICLE", ["90px","30px","30px","90px"])]+ } else {+ [("SECTION", ["500px","400px","500px","400px"]), ("ARTICLE", ["500px","400px","400px","500px"])]+ } {+ let node = nodes.iter().position(|index| decode(index) == tag).expect("fixture element");+ let row = indices.iter().position(|index| index.as_u64() == Some(node as u64)).expect("element style row");+ let values = layout["styles"][row].as_array().unwrap().iter().map(decode).collect::<Vec<_>>();+ assert_eq!(values, expected, "{tag}, sampled={sampled}");+ }+ assert_eq!(page.vm().layout_snapshot_cache_observability_for_test(), cache);+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes);+ }+ Ok::<_, anyhow::Error>(())+ }).await.expect("DOMSnapshot rows must consume the same demand-driven size projection");+}diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rsindex d5cdc2fb2..346dc071a 100644--- a/moli-renderer-v8/src/script_vm.rs+++ b/moli-renderer-v8/src/script_vm.rs@@ -2434,12 +2434,12 @@ impl ScriptVm {pub(super) fn computed_style_property_values_for_document_snapshot(&self,- handle: DomHandle,+ handles: impl IntoIterator<Item = DomHandle>,properties: &[String],- ) -> Option<Vec<String>> {+ ) -> Vec<Vec<String>> {crate::native_bridge::element::computed_style_property_values_for_document_snapshot(&self._context_host.borrow(),- handle,+ handles,properties,)}