Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

test(cssom): respect layout sampling in computed-style smoke

ldm01d18ae64bff1
diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp.py b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp.py
index 1177db5aa..ead129401 100644
--- a/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp.py
+++ b/moli-cdp-smoke/moli_cdp_smoke/groups/chromium_cdp.py
@@ -70,6 +70,7 @@ async def run_chromium_cdp_group(state: SmokeState) -> None:
async def run_computed_style_group(state: SmokeState) -> None:
"""Run the focused cross-engine computed-style breadth contract."""
await _verify_chromium_css_computed_style_breadth_sample(state)
+ await _verify_sampled_computed_sizes(state)
def _header_value(headers: dict[str, Any], name: str) -> Any:
@@ -4782,9 +4783,26 @@ async def _verify_chromium_css_computed_style_breadth_sample(state: SmokeState)
for shorthand in ["margin", "mask", "padding-block"]:
assert_equal(values.get(shorthand), None, f"CDP must not enumerate {shorthand}")
+ # The first complete read may itself request Grid geometry in Moli. Sizes
+ # sampled before that request can still be computed values, whereas a new
+ # observation can use the newly published layout. Establish a geometry
+ # boundary before asserting whole-declaration stability, retaining the
+ # initial read above to cover cold enumeration and layout-independent data.
+ # Calibrated with Chromium 145.0.7632.116 and Moli 4567db9e (three runs each):
+ # only Moli's four size values change; both are stable after getBoxModel.
+ size_names = ("width", "height", "inline-size", "block-size")
+ initial_sizes = {name: values[name] for name in size_names}
+ await state.cdp.send("DOM.getBoxModel", {"nodeId": target["nodeId"]})
+ sampled_names, sampled_values = await read_computed_style()
+ assert_equal(sampled_names, names, "sampled CDP computed style names")
+ assert_equal(
+ {name: value for name, value in sampled_values.items() if name not in size_names},
+ {name: value for name, value in values.items() if name not in size_names},
+ "geometry sampling preserves this fixture's non-size properties",
+ )
repeated_names, repeated_values = await read_computed_style()
assert_equal(repeated_names, names, "repeated CDP computed style names")
- assert_equal(repeated_values, values, "repeated CDP computed style values")
+ assert_equal(repeated_values, sampled_values, "sampled CDP computed style values stay stable")
await state.cdp.send(
"Runtime.evaluate",
@@ -4807,10 +4825,114 @@ async def _verify_chromium_css_computed_style_breadth_sample(state: SmokeState)
{
"javascriptPropertyCount": js_summary["count"],
"cdpPropertyCount": len(names),
+ "initialSizes": initial_sizes,
+ "sampledSizes": {name: sampled_values[name] for name in size_names},
},
)
+async def _verify_sampled_computed_sizes(state: SmokeState) -> None:
+ """Compare used sizes only after an explicit fresh visual observation.
+
+ Cold CSSOM values need not match between engines. Moli's no-layout cold
+ reads and reuse across mutation are tested with layout counters in Rust;
+ this shared client contract checks the geometry both engines sampled.
+ """
+ size_names = ("width", "height", "inline-size", "block-size")
+ for name, tag, style, expected in [
+ (
+ "content-box",
+ "div",
+ "width:500px;height:400px;max-width:120.5px;max-height:80.25px;"
+ "padding:5px;border:2px solid;zoom:2;transform:scale(1.5)",
+ ("120.5px", "80.25px", "120.5px", "80.25px"),
+ ),
+ (
+ "vertical-border-box",
+ "div",
+ "width:500px;height:400px;max-width:160px;max-height:90px;"
+ "padding:5px;border:2px solid;box-sizing:border-box;writing-mode:vertical-rl",
+ ("160px", "90px", "90px", "160px"),
+ ),
+ (
+ "grid",
+ "div",
+ "display:grid;width:180px;height:90px;grid-template-columns:1fr 2fr",
+ ("180px", "90px", "180px", "90px"),
+ ),
+ (
+ "vertical-canvas",
+ "canvas",
+ "writing-mode:vertical-rl",
+ ("300px", "150px", "150px", "300px"),
+ ),
+ ]:
+ await state.page.set_content(
+ f'<!doctype html><style>html,body{{margin:0}}</style>'
+ f'<{tag} id="sampled-size-target" style="{style}"></{tag}>'
+ )
+ await state.page.evaluate(
+ "globalThis.heldSizeStyle = getComputedStyle(document.getElementById('sampled-size-target'))"
+ )
+
+ async def read_held_sizes() -> dict[str, str]:
+ return await state.page.evaluate(
+ "names => Object.fromEntries(names.map(name => [name, heldSizeStyle.getPropertyValue(name)]))",
+ list(size_names),
+ )
+
+ initial = await read_held_sizes()
+ document = await state.cdp.send("DOM.getDocument", {"depth": -1})
+ target = _find_dom_node(
+ document["root"],
+ lambda node: _attribute_list_to_dict(node.get("attributes") or []).get("id")
+ == "sampled-size-target",
+ )
+ if target is None:
+ raise SmokeError(f"missing sampled size target: {name}")
+ observations = []
+ for mutated in (False, True):
+ if mutated:
+ await state.page.evaluate("""() => {
+ const target = document.getElementById('sampled-size-target');
+ target.style.width = '40px';
+ target.style.height = '30px';
+ }""")
+ expected = (
+ ("40px", "30px", "30px", "40px")
+ if name.startswith("vertical-")
+ else ("40px", "30px", "40px", "30px")
+ )
+ screenshot = await state.cdp.send("Page.captureScreenshot", {"format": "png"})
+ if not base64.b64decode(screenshot.get("data", "")).startswith(b"\x89PNG\r\n\x1a\n"):
+ raise SmokeError(f"sampled size screenshot is missing: {name}, mutated={mutated}")
+ expected_values = dict(zip(size_names, expected, strict=True))
+ previous_values = None
+ for _ in range(2):
+ result = await state.cdp.send(
+ "CSS.getComputedStyleForNode", {"nodeId": target["nodeId"]}
+ )
+ values = {entry["name"]: entry["value"] for entry in result["computedStyle"]}
+ assert_equal(
+ {key: values.get(key) for key in size_names},
+ expected_values,
+ f"sampled CDP sizes: {name}, mutated={mutated}",
+ )
+ assert_equal(
+ await read_held_sizes(),
+ expected_values,
+ f"held CSSOM sizes: {name}, mutated={mutated}",
+ )
+ if previous_values is not None:
+ assert_equal(values, previous_values, f"sampled declaration stability: {name}")
+ previous_values = values
+ observations.append(expected_values)
+ state.record(
+ f"computed_size_sampling_{name}",
+ {"initial": initial, "sampled": observations[0], "refreshed": observations[1]},
+ )
+
+
async def _verify_chromium_dom_query_selector_sample(state: SmokeState) -> None:
await _navigate_with_cdp_until_dom_ready(state, f"{state.fixture}/chromium-cdp-dom-query-page")
wire_order: list[dict[str, Any]] = []
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.rs
index 9a3b61ca9..9da2e0c76 100644
--- 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.rs
@@ -6,6 +6,8 @@ use crate::{
script_vm::{ScriptVmDefaultWorldBootstrap, StandaloneScriptVmHarness},
};
+mod sampling;
+
fn fixture(body: &str) -> StandaloneScriptVmHarness {
let _runtime = crate::JsRuntime::initialize();
let document = HtmlParser::SCRIPTING_ENABLED.parse(
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation/sizing_tests/sampling.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation/sizing_tests/sampling.rs
new file mode 100644
index 000000000..6c7e25949
--- /dev/null
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/observation/sizing_tests/sampling.rs
@@ -0,0 +1,206 @@
+//! A Grid used-track query can create the first geometry sample. Size reads
+//! themselves cannot: their first result, including absence, belongs to one
+//! observation. A later observation may therefore return different sizes
+//! without any intervening DOM/style mutation.
+
+use std::collections::BTreeMap;
+
+use super::*;
+
+const GRID: &str = r#"<div id=target class=sized style="display:grid;grid-template-columns:30px 1fr;grid-template-rows:20px 1fr"></div>"#;
+
+fn inspector_properties(host: &JsContextHost, target: DomHandle) -> BTreeMap<String, String> {
+ crate::native_bridge::element::computed_style_properties_for_inspector_handle(host, target)
+ .unwrap()
+ .into_iter()
+ .collect()
+}
+
+#[test]
+fn computed_size_cold_inspector_enumeration_transitions_to_a_stable_sample() {
+ for real in [false, true] {
+ let mut vm = fixture(GRID);
+ if !real {
+ 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();
+ assert!(before.cached.is_none());
+ let passes = host.layout_pass_observability_for_test().1;
+ take_query_counts();
+ let initial = inspector_properties(&host, target);
+ assert!(initial.len() > 200);
+ let size_names = ["width", "height", "inline-size", "block-size"];
+ for (name, expected) in size_names
+ .into_iter()
+ .zip(["500px", "400px", "500px", "400px"])
+ {
+ assert_eq!(initial[name], expected, "cold {name}, real={real}");
+ }
+ assert_eq!(take_query_counts(), SizeQueryCounts::default());
+ let sampled = host.layout_snapshot_cache_observability_for_test();
+ assert_eq!(sampled.publishes, before.publishes + u64::from(real));
+ assert_eq!(sampled.cached.is_some(), real);
+ assert_eq!(
+ host.layout_pass_observability_for_test().1,
+ passes + u64::from(real)
+ );
+ if !real {
+ assert_eq!(sampled, before);
+ }
+
+ let mut previous = None;
+ for _ in 0..3 {
+ let values = inspector_properties(&host, target);
+ let expected = if real {
+ ["120px", "80px", "120px", "80px"]
+ } else {
+ ["500px", "400px", "500px", "400px"]
+ };
+ for (name, expected) in size_names.into_iter().zip(expected) {
+ assert_eq!(values[name], expected, "sampled {name}, real={real}");
+ }
+ assert_eq!(
+ values.keys().collect::<Vec<_>>(),
+ initial.keys().collect::<Vec<_>>()
+ );
+ for (name, value) in &initial {
+ if !size_names.contains(&name.as_str()) {
+ assert_eq!(&values[name], value, "non-size property {name}");
+ }
+ }
+ if let Some(previous) = previous {
+ assert_eq!(values, previous, "same-sample declarations stay identical");
+ }
+ previous = Some(values);
+ assert_eq!(
+ take_query_counts(),
+ SizeQueryCounts {
+ source_queries: usize::from(real),
+ ..Default::default()
+ }
+ );
+ assert_eq!(
+ host.layout_pass_observability_for_test().1,
+ passes + u64::from(real)
+ );
+ let after = host.layout_snapshot_cache_observability_for_test();
+ assert_eq!(after.publishes, sampled.publishes);
+ assert_eq!(after.cached, sampled.cached);
+ }
+ }
+}
+
+#[test]
+fn computed_size_observation_pins_first_sample_availability_not_the_held_js_wrapper() {
+ for grid_first in [false, true] {
+ let vm = fixture(GRID);
+ 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 passes = host.layout_pass_observability_for_test().1;
+ let before = host.layout_snapshot_cache_observability_for_test();
+ assert!(before.cached.is_none());
+ {
+ let read = ComputedStyleRead::new(&host, target);
+ if !grid_first {
+ assert_eq!(sizes(&read), ["500px", "400px", "500px", "400px"]);
+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), before);
+ }
+ assert_eq!(read.property("grid-template-columns"), "30px 90px");
+ let sampled = host.layout_snapshot_cache_observability_for_test();
+ assert_eq!(sampled.publishes, before.publishes + 1);
+ take_query_counts();
+ for _ in 0..20 {
+ assert_eq!(
+ sizes(&read),
+ if grid_first {
+ ["120px", "80px", "120px", "80px"]
+ } else {
+ ["500px", "400px", "500px", "400px"]
+ }
+ );
+ }
+ assert_eq!(
+ take_query_counts(),
+ SizeQueryCounts {
+ source_queries: usize::from(grid_first),
+ ..Default::default()
+ }
+ );
+ assert_eq!(host.layout_snapshot_cache_observability_for_test(), sampled);
+ }
+ assert_eq!(
+ sizes(&ComputedStyleRead::new(&host, target)),
+ ["120px", "80px", "120px", "80px"]
+ );
+ assert_eq!(take_query_counts().source_queries, 1);
+ assert_eq!(host.layout_pass_observability_for_test().1, passes + 1);
+ }
+}
+
+#[test]
+fn computed_size_document_batch_pins_one_sample_even_if_grid_is_read_mid_batch() {
+ for grid_first in [false, true] {
+ let vm = fixture(&format!("{GRID}<div id=other class=sized></div>"));
+ let host = vm.context_host_weak_for_test().upgrade().unwrap();
+ let handles = {
+ let host = host.borrow();
+ ["target", "other"].map(|id| host.dom_host().element_handle_by_id(id).unwrap())
+ };
+ let properties = if grid_first {
+ [
+ "grid-template-columns",
+ "width",
+ "height",
+ "inline-size",
+ "block-size",
+ ]
+ } else {
+ [
+ "width",
+ "grid-template-columns",
+ "height",
+ "inline-size",
+ "block-size",
+ ]
+ }
+ .map(String::from);
+ let passes = vm.layout_pass_observability_for_test().1;
+ assert!(
+ vm.layout_snapshot_cache_observability_for_test()
+ .3
+ .is_none()
+ );
+ take_query_counts();
+ let rows = vm.computed_style_property_values_for_document_snapshot(handles, &properties);
+ assert_eq!(rows.len(), 2);
+ for (row, tracks) in rows.iter().zip(["30px 90px", "none"]) {
+ let expected = if grid_first {
+ [tracks, "120px", "80px", "120px", "80px"]
+ } else {
+ ["500px", tracks, "400px", "500px", "400px"]
+ };
+ assert_eq!(row, &expected, "grid_first={grid_first}");
+ }
+ assert_eq!(take_query_counts().index_builds, usize::from(grid_first));
+ let sampled = vm.layout_snapshot_cache_observability_for_test();
+ assert!(sampled.3.is_some());
+ let rows = vm.computed_style_property_values_for_document_snapshot(
+ handles,
+ &["width", "height", "inline-size", "block-size"].map(String::from),
+ );
+ for row in rows {
+ assert_eq!(row, ["120px", "80px", "120px", "80px"]);
+ }
+ assert_eq!(
+ take_query_counts().index_builds,
+ 1,
+ "a new batch derives its own table"
+ );
+ assert_eq!(vm.layout_snapshot_cache_observability_for_test(), sampled);
+ assert_eq!(vm.layout_pass_observability_for_test().1, passes + 1);
+ }
+}
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.rs
index 88e198db2..fc7f8ebb1 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
@@ -4,6 +4,7 @@ mod capture;
mod chromium;
mod lifecycle;
mod logical;
+mod sampling;
fn page_with_size_fixture(html: &str) -> anyhow::Result<PageVm> {
let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/sampling.rs b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/sampling.rs
new file mode 100644
index 000000000..742a17352
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/computed_size/sampling.rs
@@ -0,0 +1,182 @@
+//! Grid queries are geometry demands; the four size getters are snapshot-only.
+//! Unlike an internal synchronous property batch, a held JavaScript CSSOM
+//! wrapper starts a new read for each getter and must see newly sampled boxes.
+
+use super::*;
+
+const GRID: &str = r#"<main id=parent style="width:160px"><div id=target style="display:grid;grid-template-columns:1fr 3fr;grid-template-rows:40px"></div></main>"#;
+
+fn held_sizes(page: &mut PageVm) -> anyhow::Result<serde_json::Value> {
+ read_without_layout(
+ page,
+ "[held.width,held.height,held.inlineSize,held.blockSize]",
+ )
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_held_getters_observe_grid_sampling_without_dom_mutation() {
+ run_page_vm_async_test(async move {
+ for real in [false, true] {
+ for (property, raw, used) in [
+ ("gridTemplateColumns", "1fr 3fr", "40px 120px"),
+ ("gridTemplateRows", "40px", "40px"),
+ ] {
+ let mut page = page_with_size_fixture(GRID)?;
+ if !real {
+ page.vm_mut()
+ .set_layout_policy(moli_page_types::LayoutPolicy::Mock);
+ }
+ let before = page.vm().layout_snapshot_cache_observability_for_test();
+ let passes = page.vm().layout_pass_observability_for_test().1;
+ assert!(before.3.is_none());
+ let result = page.vm_mut().eval(&format!(
+ r#"JSON.stringify((() => {{
+ const held = getComputedStyle(document.getElementById('target'));
+ const sizes = () => [held.width,held.height,held.inlineSize,held.blockSize];
+ const before = sizes();
+ const tracks = held.{property};
+ return {{before, tracks, after:sizes(), repeated:sizes()}};
+ }})())"#
+ ))?;
+ let result: serde_json::Value = serde_json::from_str(&result)?;
+ let expected = if real {
+ json!(["160px", "40px", "160px", "40px"])
+ } else {
+ json!(["auto", "auto", "auto", "auto"])
+ };
+ assert_eq!(
+ result,
+ json!({
+ "before":["auto","auto","auto","auto"],
+ "tracks":if real { used } else { raw },
+ "after":expected, "repeated":expected,
+ }),
+ "{property}, real={real}"
+ );
+ assert_eq!(
+ page.vm().layout_pass_observability_for_test().1,
+ passes + u64::from(real)
+ );
+ let after = page.vm().layout_snapshot_cache_observability_for_test();
+ assert_eq!(after.2, before.2 + u64::from(real));
+ assert_eq!(after.3.is_some(), real);
+ if !real {
+ assert_eq!(after, before);
+ }
+ }
+ }
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("held CSSOM objects must not retain a cold geometry miss across getters");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_grid_sampling_reuses_old_geometry_until_explicit_refresh() {
+ run_page_vm_async_test(async move {
+ let mut page = page_with_size_fixture(GRID)?;
+ page.vm_mut()
+ .eval("globalThis.held=getComputedStyle(document.getElementById('target'));'held'")?;
+ assert_eq!(
+ held_sizes(&mut page)?,
+ json!(["auto", "auto", "auto", "auto"])
+ );
+ let passes = page.vm().layout_pass_observability_for_test().1;
+ assert_eq!(
+ page.vm_mut().eval("held.gridTemplateColumns")?,
+ "40px 120px"
+ );
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes + 1);
+ assert_eq!(
+ held_sizes(&mut page)?,
+ json!(["160px", "40px", "160px", "40px"])
+ );
+ let sampled = page.vm().layout_snapshot_cache_observability_for_test();
+ page.vm_mut().eval(
+ r#"
+ document.getElementById('parent').style.width='200px';
+ document.getElementById('target').style.gridTemplateColumns='1fr 1fr';
+ document.getElementById('target').style.color='red';
+ 'mutated'
+ "#,
+ )?;
+ assert_eq!(
+ read_without_layout(&mut page, "held.color")?,
+ json!("rgb(255, 0, 0)")
+ );
+ assert_eq!(
+ held_sizes(&mut page)?,
+ json!(["160px", "40px", "160px", "40px"])
+ );
+ assert_eq!(
+ page.vm_mut().eval("held.gridTemplateColumns")?,
+ "40px 120px"
+ );
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes + 1);
+ assert_eq!(
+ page.vm().layout_snapshot_cache_observability_for_test().2,
+ sampled.2
+ );
+ publish_size_layout(&mut page)?;
+ assert_eq!(
+ held_sizes(&mut page)?,
+ json!(["200px", "40px", "200px", "40px"])
+ );
+ assert_eq!(
+ page.vm_mut().eval("held.gridTemplateColumns")?,
+ "100px 100px"
+ );
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes + 2);
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("Grid-created geometry follows the same snapshot lifecycle as explicit box reads");
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn computed_size_grid_sampling_does_not_warm_another_page() {
+ run_page_vm_async_test(async move {
+ let mut first = page_with_size_fixture(GRID)?;
+ let mut second = page_with_size_fixture(GRID)?;
+ for page in [&mut first, &mut second] {
+ page.vm_mut().eval(
+ "globalThis.held=getComputedStyle(document.getElementById('target'));'held'",
+ )?;
+ assert_eq!(held_sizes(page)?, json!(["auto", "auto", "auto", "auto"]));
+ }
+ let second_cache = second.vm().layout_snapshot_cache_observability_for_test();
+ let second_passes = second.vm().layout_pass_observability_for_test().1;
+ assert_eq!(
+ first.vm_mut().eval("held.gridTemplateColumns")?,
+ "40px 120px"
+ );
+ assert_eq!(
+ held_sizes(&mut first)?,
+ json!(["160px", "40px", "160px", "40px"])
+ );
+ assert_eq!(
+ held_sizes(&mut second)?,
+ json!(["auto", "auto", "auto", "auto"])
+ );
+ assert_eq!(
+ second.vm().layout_snapshot_cache_observability_for_test(),
+ second_cache
+ );
+ assert_eq!(
+ second.vm().layout_pass_observability_for_test().1,
+ second_passes
+ );
+ assert_eq!(second.vm_mut().eval("held.gridTemplateRows")?, "40px");
+ assert_eq!(
+ held_sizes(&mut second)?,
+ json!(["160px", "40px", "160px", "40px"])
+ );
+ assert_eq!(
+ second.vm().layout_pass_observability_for_test().1,
+ second_passes + 1
+ );
+ Ok::<_, anyhow::Error>(())
+ })
+ .await
+ .expect("one Page's geometry publication must not change another Page's cold size reads");
+}