Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(style): enforce stable document observations
ldm0542f303b787a
diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rsindex 0c7d7a021..8a0d14b5c 100644--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs@@ -205,6 +205,7 @@ impl JsContextHost {layout_snapshot_cache_hits: Cell::new(0),layout_snapshot_cache_misses: Cell::new(0),layout_snapshot_cache_publishes: Cell::new(0),+ style_viewport_generation: Cell::new(0),#[cfg(test)]force_fresh_layout_reads_for_test: false,root_document_lifecycle: None,diff --git a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rsindex 240cabf68..d84683f3b 100644--- a/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/host_environment.rs@@ -1482,20 +1482,67 @@ impl JsContextHost {}#[cfg(debug_assertions)]- pub(crate) fn computed_style_read_invariant_state(+ pub(crate) fn computed_style_observation_input_epochs(&self,document: DomHandle,- ) -> (u64, u64, u64) {- let (source_set_generation, retained_style_system_generation) = self- .style_engine- .computed_style_read_invariant_state(document);- (+ tree_scope_versions: crate::style_engine::StyleTreeScopeVersions,+ ) -> crate::style_engine::ComputedStyleObservationInputEpochs {+ self.style_engine.computed_style_observation_input_epochs(+ self.computed_style_observation_dependency_documents(document),self.dom_host().dom_version(),- source_set_generation,- retained_style_system_generation,+ self.style_viewport_generation(),+ tree_scope_versions,)}+ #[cfg(debug_assertions)]+ pub(crate) fn complete_computed_style_observation(+ &self,+ document: DomHandle,+ input_epochs_before_read: &crate::style_engine::ComputedStyleObservationInputEpochs,+ ) {+ let tree_scope_versions =+ crate::style_engine::StyleTreeScopeVersions::current(self.dom_host(), Some(document));+ let input_epochs_after_read =+ self.computed_style_observation_input_epochs(document, tree_scope_versions);+ self.style_engine.complete_computed_style_observation(+ document,+ input_epochs_before_read,+ input_epochs_after_read,+ );+ }++ #[cfg(debug_assertions)]+ fn computed_style_observation_dependency_documents(+ &self,+ document: DomHandle,+ ) -> Vec<DomHandle> {+ let mut documents = Vec::new();+ let mut current = Some(document);+ while let Some(candidate) = current {+ if documents.contains(&candidate) {+ break;+ }+ documents.push(candidate);+ if candidate == self.document_handle() {+ break;+ }+ current = self+ .child_browsing_context_host_for_document_handle(candidate)+ .and_then(|frame| self.dom_host().owner_document_handle(frame));+ }+ documents+ }++ #[cfg(all(test, debug_assertions))]+ pub(crate) fn completed_style_observation_stability_check_count_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.style_engine+ .completed_style_observation_stability_check_count_for_document_for_test(document)+ }+#[cfg(test)]pub(crate) fn note_style_world_update_materialization_for_test(&self) {self.style_world_update_materializations.set(diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout.rs b/moli-renderer-v8/src/native_bridge/context_host/layout.rsindex c9b0abe6f..33ddda09d 100644--- a/moli-renderer-v8/src/native_bridge/context_host/layout.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/layout.rs@@ -142,6 +142,34 @@ impl JsContextHost {.frame_viewport(frame)}+ pub(crate) fn style_viewport_generation(&self) -> u64 {+ self.style_viewport_generation.get()+ }++ /// Marks the exact viewport selected by an active layout pass before that+ /// pass reads the Document's styles.+ ///+ /// An embedded Document's persistent frame viewport is published only+ /// after the recursive pass succeeds. Advancing this input generation+ /// first also distinguishes an explicit main-Document capture viewport+ /// from ordinary DOM APIs selecting conflicting implicit viewports.+ pub(crate) fn note_layout_style_viewport(&self, document: DomHandle, viewport: StyleViewport) {+ let matches_cached = if document == self.document_handle() {+ viewport == self.style_viewport()+ } else {+ self.child_browsing_context_host_for_document_handle(document)+ .and_then(|frame| self.frame_viewport(frame))+ .is_some_and(|cached| {+ viewport.width == Some(f64::from(cached.css_width))+ && viewport.height == Some(f64::from(cached.css_height))+ })+ };+ if !matches_cached {+ self.style_viewport_generation+ .set(self.style_viewport_generation.get().saturating_add(1));+ }+ }+pub(crate) fn inferred_frame_style_viewport(&self,frame: DomHandle,@@ -241,10 +269,14 @@ impl JsContextHost {}).collect::<Vec<_>>();let tree = pass.into_tree();- {+ let frame_viewports_changed = {let mut state = self.document_layout_state.borrow_mut();state.publish_latest_layout(document, tree);- state.update_frame_viewports(frame_viewports);+ state.update_frame_viewports(frame_viewports)+ };+ if frame_viewports_changed {+ self.style_viewport_generation+ .set(self.style_viewport_generation.get().saturating_add(1));}self.last_layout_pass_metrics.set(Some(metrics));self.layout_snapshot_cache_publishes@@ -448,6 +480,8 @@ impl JsContextHost {pub(crate) fn reset_document_layout_state(&self) {*self.document_layout_state.borrow_mut() = Default::default();+ self.style_viewport_generation+ .set(self.style_viewport_generation.get().saturating_add(1));}pub(crate) fn invalidate_layout_after_interaction_state_change(&self) {diff --git a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rsindex 62c414293..574eebcd2 100644--- a/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/layout_state.rs@@ -181,17 +181,22 @@ impl DocumentLayoutState {pub(super) fn update_frame_viewports(&mut self,updates: impl IntoIterator<Item = (DomHandle, Option<LayoutViewport>)>,- ) {+ ) -> bool {+ let mut changed = false;for (frame, viewport) in updates {match viewport {Some(viewport) => {- self.frame_viewports.insert(frame, viewport);+ if self.frame_viewports.get(&frame) != Some(&viewport) {+ self.frame_viewports.insert(frame, viewport);+ changed = true;+ }}None => {- self.frame_viewports.remove(&frame);+ changed |= self.frame_viewports.remove(&frame).is_some();}}}+ changed}pub(super) fn retain_live_frame_viewports(diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rsindex 61cb2cff3..86db14fb9 100644--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs@@ -806,6 +806,7 @@ pub(crate) struct JsContextHost {layout_snapshot_cache_hits: Cell<u64>,layout_snapshot_cache_misses: Cell<u64>,layout_snapshot_cache_publishes: Cell<u64>,+ style_viewport_generation: Cell<u64>,#[cfg(test)]force_fresh_layout_reads_for_test: bool,root_document_lifecycle: Option<RendererDocumentLifecycleJournalHandle>,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 913c4a7bd..8f418ea54 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@@ -50,20 +50,14 @@ impl StyleComputationContext {runtime: &JsContextHost,handle: DomHandle,) -> DomHandle {- self.read_document- .or_else(|| runtime.dom_host().owner_document_handle(handle))+ runtime+ .dom_host()+ .owner_document_handle(handle)+ .or(self.read_document).unwrap_or_else(|| runtime.document_handle())}}-#[cfg(debug_assertions)]-#[derive(Clone, Copy)]-struct ComputedStyleReadInvariant {- dom_version: u64,- source_set_generation: u64,- retained_style_system_generation: u64,-}-/// One synchronous observation of the persistent style worlds it touches.////// The observation drains pending style work once per Document and reads@@ -76,18 +70,22 @@ pub(crate) struct StyleObservation<'a> {/// detached CSSOM snapshots use `Some` to pin an exact caller-owned/// viewport instead.fixed_context: Option<StyleComputationContext>,+ /// Explicit layout observations may intentionally use a caller-owned+ /// viewport that differs from the Window surface. They advance the style+ /// viewport input epoch, but do not become the baseline for ordinary DOM+ /// API observations.+ tracks_persistent_world: bool,drained_document: Option<DomHandle>,additional_drained_documents: Vec<DomHandle>,primary_document: Option<Rc<StyleObservationInputs<'a>>>,additional_documents: Vec<Rc<StyleObservationInputs<'a>>>,- #[cfg(debug_assertions)]- invariants: Vec<(DomHandle, ComputedStyleReadInvariant)>,}pub(super) struct StyleObservationInputs<'a> {runtime: &'a JsContextHost,key: StyleObservationKey,context: StyleComputationContext,+ tracks_persistent_world: bool,prepared_update: RefCell<Option<Rc<PreparedStyleWorldUpdate>>>,stylesheet_query_snapshot: RefCell<Option<Rc<FullStyleWorldSnapshot>>>,}@@ -97,11 +95,13 @@ impl<'a> StyleObservationInputs<'a> {runtime: &'a JsContextHost,source_document: Option<DomHandle>,context: StyleComputationContext,+ tracks_persistent_world: bool,) -> Self {Self {runtime,key: StyleObservationKey::for_document(runtime, source_document),context,+ tracks_persistent_world,prepared_update: RefCell::new(None),stylesheet_query_snapshot: RefCell::new(None),}@@ -150,8 +150,22 @@ pub(super) trait RetainedStyleObservation {impl RetainedStyleObservation for StyleObservationInputs<'_> {fn style_snapshot(&self, handle: DomHandle) -> Option<StyloComputedStyleSnapshot> {+ #[cfg(debug_assertions)]+ let invariant_input = self+ .tracks_persistent_world+ .then_some(self.source_document())+ .flatten()+ .map(|document| {+ (+ document,+ self.runtime.computed_style_observation_input_epochs(+ document,+ self.tree_scope_versions(),+ ),+ )+ });let read_document = self.context.resolved_read_document(self.runtime, handle);- match self+ let style = match self.runtime.computed_style_snapshot_from_current_observation(handle,@@ -168,13 +182,19 @@ impl RetainedStyleObservation for StyleObservationInputs<'_> {read_document,)}+ };+ #[cfg(debug_assertions)]+ if let Some((document, input_epochs)) = invariant_input {+ self.runtime+ .complete_computed_style_observation(document, &input_epochs);}+ style}}impl<'a> StyleObservation<'a> {pub(crate) fn new(runtime: &'a JsContextHost) -> Self {- Self::new_with_fixed_context(runtime, None)+ Self::new_with_fixed_context(runtime, None, true)}/// Creates one synchronous style-observation scope for an exact document@@ -190,9 +210,11 @@ impl<'a> StyleObservation<'a> {document: DomHandle,viewport: StyleViewport,) -> Self {- Self::new_with_context(+ runtime.note_layout_style_viewport(document, viewport);+ Self::new_with_fixed_context(runtime,- StyleComputationContext::new(viewport).with_read_document(Some(document)),+ Some(StyleComputationContext::new(viewport).with_read_document(Some(document))),+ false,)}@@ -200,22 +222,22 @@ impl<'a> StyleObservation<'a> {runtime: &'a JsContextHost,context: StyleComputationContext,) -> Self {- Self::new_with_fixed_context(runtime, Some(context))+ Self::new_with_fixed_context(runtime, Some(context), true)}fn new_with_fixed_context(runtime: &'a JsContextHost,fixed_context: Option<StyleComputationContext>,+ tracks_persistent_world: bool,) -> Self {Self {runtime,fixed_context,+ tracks_persistent_world,drained_document: None,additional_drained_documents: Vec::new(),primary_document: None,additional_documents: Vec::new(),- #[cfg(debug_assertions)]- invariants: Vec::new(),}}@@ -228,6 +250,7 @@ impl<'a> StyleObservation<'a> {.fixed_context.unwrap_or_default().resolved_read_document(self.runtime, handle);+ let source_document = stylesheet_source_document_for_handle(self.runtime, handle);if self.drained_document != Some(read_document)&& !self.additional_drained_documents.contains(&read_document){@@ -242,9 +265,22 @@ impl<'a> StyleObservation<'a> {);}- let source_document = stylesheet_source_document_for_handle(self.runtime, handle);let observation_inputs = self.observation_inputs(source_document, read_document);let context = observation_inputs.context();+ #[cfg(debug_assertions)]+ let invariant_input = self+ .tracks_persistent_world+ .then_some(source_document)+ .flatten()+ .map(|document| {+ (+ document,+ self.runtime.computed_style_observation_input_epochs(+ document,+ observation_inputs.tree_scope_versions(),+ ),+ )+ });let stylo_style = match self.runtime.computed_style_snapshot_from_current_observation(@@ -264,7 +300,10 @@ impl<'a> StyleObservation<'a> {}};#[cfg(debug_assertions)]- self.verify_stable_style_world_after_read(source_document);+ if let Some((document, input_epochs)) = invariant_input {+ self.runtime+ .complete_computed_style_observation(document, &input_epochs);+ }ComputedStyleRead {runtime: self.runtime,handle,@@ -292,13 +331,30 @@ impl<'a> StyleObservation<'a> {return Rc::clone(observation);}- let context = self.fixed_context.unwrap_or_else(|| {- StyleComputationContext::new(style_viewport_for_document(self.runtime, read_document))- });+ let context = self+ .fixed_context+ .map(|context| {+ if context.read_document.is_some() && context.read_document != Some(read_document) {+ StyleComputationContext::new(style_viewport_for_document(+ self.runtime,+ read_document,+ ))+ .with_read_document(Some(read_document))+ } else {+ context+ }+ })+ .unwrap_or_else(|| {+ StyleComputationContext::new(style_viewport_for_document(+ self.runtime,+ read_document,+ ))+ });let observation = Rc::new(StyleObservationInputs::new(self.runtime,source_document,context,+ self.tracks_persistent_world,));if self.primary_document.is_none() {self.primary_document = Some(Rc::clone(&observation));@@ -307,38 +363,6 @@ impl<'a> StyleObservation<'a> {}observation}-- #[cfg(debug_assertions)]- fn verify_stable_style_world_after_read(&mut self, source_document: Option<DomHandle>) {- let Some(document) = source_document else {- return;- };- let (dom_version, source_set_generation, retained_style_system_generation) =- self.runtime.computed_style_read_invariant_state(document);- let current = ComputedStyleReadInvariant {- dom_version,- source_set_generation,- retained_style_system_generation,- };- let Some((_, previous)) = self- .invariants- .iter_mut()- .find(|(candidate, _)| *candidate == document)- else {- self.invariants.push((document, current));- return;- };- if previous.dom_version == current.dom_version- && previous.source_set_generation == current.source_set_generation- {- debug_assert_eq!(- current.retained_style_system_generation, previous.retained_style_system_generation,- "one StyleObservation updated or replaced the retained style world without a DOM or style-source mutation",- );- } else {- *previous = current;- }- }}/// One synchronous computed-style read after the pending style lifecycle hasdiff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rsindex bd2f0f00e..9f6255847 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style.rs@@ -4578,6 +4578,11 @@ fn child_document_mixed_style_observations_do_not_churn_the_retained_world() {let child_document = child_document_handle_for_frame_id(&vm, "mixed-observation-frame");let child_updates = vm.retained_style_system_update_count_for_document_for_test(child_document);let child_stylist = vm.retained_stylist_identity_for_document_for_test(child_document);+ #[cfg(debug_assertions)]+ let invariant_checks = vm+ ._context_host+ .borrow()+ .completed_style_observation_stability_check_count_for_document_for_test(child_document);let materializations = vm._context_host.borrow()@@ -4699,6 +4704,86 @@ fn child_document_mixed_style_observations_do_not_churn_the_retained_world() {"clean child style observations must reuse the inferred iframe viewport",);assert_eq!(final_viewport_cache_entries, viewport_cache_entries);+ #[cfg(debug_assertions)]+ assert!(+ vm._context_host+ .borrow()+ .completed_style_observation_stability_check_count_for_document_for_test(+ child_document,+ )+ > invariant_checks,+ "independent child DOM API operations must be compared by the persistent style-world invariant",+ );+}++#[test]+fn layout_publishes_authoritative_iframe_viewport_without_style_world_ping_pong() {+ let mut vm = new_storage_test_vm("https://authoritative-child-style-viewport.test/");+ let result = vm+ .eval(+ r#"+(() => {+ const frame = document.createElement('iframe');+ frame.id = 'authoritative-style-viewport-frame';+ frame.style.cssText = [+ 'box-sizing:border-box',+ 'width:200px',+ 'height:160px',+ 'padding:20px',+ 'border:10px solid black'+ ].join(';');+ (document.body || document.documentElement || document).appendChild(frame);++ const childWindow = frame.contentWindow;+ const childDocument = childWindow.document;+ childDocument.open();+ childDocument.write(`+ <style>+ body { color: rgb(0, 0, 0); }+ @media (width: 200px) { body { color: rgb(200, 0, 0); } }+ @media (width: 140px) { body { color: rgb(0, 140, 0); } }+ </style>+ <body>authoritative viewport</body>`);+ childDocument.close();++ const beforeLayout = childWindow.getComputedStyle(childDocument.body).color;+ const frameWidth = frame.getBoundingClientRect().width;+ const afterLayout = childWindow.getComputedStyle(childDocument.body).color;+ globalThis.__authoritativeStyleViewport = { frame, childWindow, childDocument };+ return [beforeLayout, frameWidth, childWindow.innerWidth, afterLayout].join('|');+})()+"#,+ )+ .expect("layout should publish an exact iframe content viewport");++ assert_eq!(result, "rgb(200, 0, 0)|200|140|rgb(0, 140, 0)");+ let child_document =+ child_document_handle_for_frame_id(&vm, "authoritative-style-viewport-frame");+ let updates = vm.retained_style_system_update_count_for_document_for_test(child_document);++ let stable = vm+ .eval(+ r#"+(() => {+ const { frame, childWindow, childDocument } = __authoritativeStyleViewport;+ let stable = true;+ for (let index = 0; index < 8; index += 1) {+ stable &&= childWindow.getComputedStyle(childDocument.body).color === 'rgb(0, 140, 0)';+ stable &&= childDocument.body.innerText === 'authoritative viewport';+ stable &&= frame.getBoundingClientRect().width === 200;+ stable &&= childWindow.innerWidth === 140;+ }+ return String(stable);+})()+"#,+ )+ .expect("published iframe viewport should remain stable across DOM APIs");+ assert_eq!(stable, "true");+ assert_eq!(+ vm.retained_style_system_update_count_for_document_for_test(child_document),+ updates,+ "automatic and layout observations must converge on the published iframe content viewport",+ );}#[test]diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rsindex 63ec6f5f1..3f901edee 100644--- a/moli-renderer-v8/src/style_engine/mod.rs+++ b/moli-renderer-v8/src/style_engine/mod.rs@@ -78,6 +78,8 @@ mod source_owner_text;mod source_record;mod source_scope_plan;mod state;+#[cfg(debug_assertions)]+pub(crate) use state::ComputedStyleObservationInputEpochs;mod stylesheet;mod stylesheet_resources;mod target_plan;@@ -271,13 +273,45 @@ impl MoliStyleEngine {}#[cfg(debug_assertions)]- pub(crate) fn computed_style_read_invariant_state(&self, document: DomHandle) -> (u64, u64) {- let world = self.world_for_document(document);- let generations = world.document_state.generation_snapshot();- (- generations.source_set_generation,- generations.retained_style_system_generation,- )+ pub(crate) fn computed_style_observation_input_epochs(+ &self,+ documents: impl IntoIterator<Item = DomHandle>,+ dom_version: u64,+ style_viewport_generation: u64,+ tree_scope_versions: StyleTreeScopeVersions,+ ) -> ComputedStyleObservationInputEpochs {+ let document_generations = self+ .document_worlds+ .observation_generations(documents)+ .into_iter()+ .map(+ |(document, source_set_generation, _, target_context_epoch)| {+ (document, source_set_generation, target_context_epoch)+ },+ )+ .collect();+ ComputedStyleObservationInputEpochs {+ dom_version,+ style_viewport_generation,+ tree_scope_versions,+ document_generations,+ }+ }++ #[cfg(debug_assertions)]+ pub(crate) fn complete_computed_style_observation(+ &self,+ document: DomHandle,+ input_epochs_before_read: &ComputedStyleObservationInputEpochs,+ input_epochs_after_read: ComputedStyleObservationInputEpochs,+ ) {+ self.world_for_document(document)+ .document_state+ .complete_computed_style_observation(+ document,+ input_epochs_before_read,+ input_epochs_after_read,+ );}#[cfg(test)]@@ -305,6 +339,16 @@ impl MoliStyleEngine {.retained_style_system_generation()}+ #[cfg(all(test, debug_assertions))]+ pub(crate) fn completed_style_observation_stability_check_count_for_document_for_test(+ &self,+ document: DomHandle,+ ) -> u64 {+ self.world_for_document(document)+ .document_state+ .completed_style_observation_stability_check_count()+ }+pub(crate) fn target_context_epoch_for_document(&self, document: DomHandle) -> u64 {self.world_for_document(document).document_statediff --git a/moli-renderer-v8/src/style_engine/registered_properties.rs b/moli-renderer-v8/src/style_engine/registered_properties.rsindex e6e6a4fd4..69555e64d 100644--- a/moli-renderer-v8/src/style_engine/registered_properties.rs+++ b/moli-renderer-v8/src/style_engine/registered_properties.rs@@ -96,6 +96,7 @@ impl MoliStyleEngine {world.registered_custom_properties.register(registration, base_url)?;+ world.document_state.bump_target_context_epoch();world.document_state.record_source_dirty_scope(StyleScopeId::Document(document),StyleSourceDirtyReason::CustomPropertyRegistration,diff --git a/moli-renderer-v8/src/style_engine/state.rs b/moli-renderer-v8/src/style_engine/state.rsindex 70be1b607..2ec0fe97d 100644--- a/moli-renderer-v8/src/style_engine/state.rs+++ b/moli-renderer-v8/src/style_engine/state.rs@@ -41,6 +41,35 @@ pub(super) struct RetainedStyleSystem {pub(super) script_custom_property_registrations: Vec<CssCustomPropertyRegistrationRecord>,}+/// Style inputs that are allowed to change a completed Document observation.+///+/// This deliberately excludes computed-style and retained-world generations:+/// those are outputs. Including either output here would let an accidental+/// clean-operation rebuild justify itself on the next read.+#[cfg(debug_assertions)]+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct ComputedStyleObservationInputEpochs {+ pub(crate) dom_version: u64,+ pub(crate) style_viewport_generation: u64,+ pub(crate) tree_scope_versions: StyleTreeScopeVersions,+ pub(crate) document_generations: Vec<(DomHandle, u64, u64)>,+}++#[cfg(debug_assertions)]+#[derive(Clone, Debug, PartialEq, Eq)]+struct CompletedStyleObservationWorld {+ retained_style_system_generation: u64,+ stylist_identity: u64,+ key: StyleWorldKey,+}++#[cfg(debug_assertions)]+#[derive(Clone, Debug)]+struct CompletedStyleObservation {+ input_epochs_after_read: ComputedStyleObservationInputEpochs,+ world: CompletedStyleObservationWorld,+}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(super) struct StyleDocumentGenerationSnapshot {pub(super) source_set_generation: u64,@@ -57,6 +86,10 @@ pub(super) struct StyleDocumentState {computed_cache_generation: Cell<u64>,retained_style_system_generation: Cell<u64>,target_context_epoch: Cell<u64>,+ #[cfg(debug_assertions)]+ completed_style_observation: RefCell<Option<CompletedStyleObservation>>,+ #[cfg(all(test, debug_assertions))]+ completed_style_observation_stability_checks: Cell<u64>,#[cfg(test)]retained_style_system_rebuilds: Cell<u64>,#[cfg(test)]@@ -75,6 +108,10 @@ impl StyleDocumentState {computed_cache_generation: Cell::new(0),retained_style_system_generation: Cell::new(0),target_context_epoch: Cell::new(0),+ #[cfg(debug_assertions)]+ completed_style_observation: RefCell::new(None),+ #[cfg(all(test, debug_assertions))]+ completed_style_observation_stability_checks: Cell::new(0),#[cfg(test)]retained_style_system_rebuilds: Cell::new(0),#[cfg(test)]@@ -125,6 +162,50 @@ impl StyleDocumentState {.set(self.target_context_epoch().saturating_add(1));}+ #[cfg(debug_assertions)]+ pub(super) fn complete_computed_style_observation(+ &self,+ document: DomHandle,+ input_epochs_before_read: &ComputedStyleObservationInputEpochs,+ input_epochs_after_read: ComputedStyleObservationInputEpochs,+ ) {+ let Some(world) =+ self.try_with_retained_style_system(|retained| CompletedStyleObservationWorld {+ retained_style_system_generation: self.retained_style_system_generation.get(),+ stylist_identity: retained.stylist_identity,+ key: retained.key.clone(),+ })+ else {+ return;+ };+ let current = CompletedStyleObservation {+ input_epochs_after_read,+ world,+ };+ let mut previous = self.completed_style_observation.borrow_mut();+ if previous.as_ref().is_some_and(|previous| {+ verify_completed_style_observation_transition(+ document,+ previous,+ input_epochs_before_read,+ ¤t,+ )+ }) {+ #[cfg(test)]+ self.completed_style_observation_stability_checks.set(+ self.completed_style_observation_stability_checks+ .get()+ .saturating_add(1),+ );+ }+ *previous = Some(current);+ }++ #[cfg(all(test, debug_assertions))]+ pub(super) fn completed_style_observation_stability_check_count(&self) -> u64 {+ self.completed_style_observation_stability_checks.get()+ }+pub(super) fn clear_retained_style_system(&self) {self.retained_style_system.borrow_mut().take();self.clear_source_dirty_scopes();@@ -324,3 +405,90 @@ impl StyleDocumentState {})}}++#[cfg(debug_assertions)]+fn verify_completed_style_observation_transition(+ document: DomHandle,+ previous: &CompletedStyleObservation,+ input_epochs_before_read: &ComputedStyleObservationInputEpochs,+ current: &CompletedStyleObservation,+) -> bool {+ if previous.input_epochs_after_read != *input_epochs_before_read {+ return false;+ }+ debug_assert_eq!(+ current.world, previous.world,+ "completed style observations changed the retained world for {document:?} without an intervening DOM, style-source, style-context, or style-viewport input change"+ );+ true+}++#[cfg(all(test, debug_assertions))]+mod observation_invariant_tests {+ use style::context::QuirksMode;++ use super::*;++ fn input_epochs(dom_version: u64) -> ComputedStyleObservationInputEpochs {+ ComputedStyleObservationInputEpochs {+ dom_version,+ style_viewport_generation: 4,+ tree_scope_versions: StyleTreeScopeVersions::for_test(5),+ document_generations: vec![(DomHandle::new(1), 2, 3)],+ }+ }++ fn world(generation: u64) -> CompletedStyleObservationWorld {+ CompletedStyleObservationWorld {+ retained_style_system_generation: generation,+ stylist_identity: 9,+ key: StyleWorldKey {+ viewport_width_bits: 800.0_f32.to_bits(),+ viewport_height_bits: 600.0_f32.to_bits(),+ screen_width_bits: 800.0_f32.to_bits(),+ screen_height_bits: 600.0_f32.to_bits(),+ environment: StyloStyleEnvironment::default(),+ quirks_mode: QuirksMode::NoQuirks,+ tree_scope_versions: None,+ },+ }+ }++ #[test]+ #[should_panic(expected = "without an intervening DOM, style-source, style-context")]+ fn unchanged_inputs_reject_a_different_completed_world() {+ let epochs = input_epochs(1);+ let previous = CompletedStyleObservation {+ input_epochs_after_read: epochs.clone(),+ world: world(7),+ };+ let current = CompletedStyleObservation {+ input_epochs_after_read: epochs.clone(),+ world: world(8),+ };+ verify_completed_style_observation_transition(+ DomHandle::new(1),+ &previous,+ &epochs,+ ¤t,+ );+ }++ #[test]+ fn changed_inputs_allow_one_completed_world_update() {+ let previous = CompletedStyleObservation {+ input_epochs_after_read: input_epochs(1),+ world: world(7),+ };+ let current = CompletedStyleObservation {+ input_epochs_after_read: input_epochs(2),+ world: world(8),+ };+ assert!(!verify_completed_style_observation_transition(+ DomHandle::new(1),+ &previous,+ &input_epochs(2),+ ¤t,+ ));+ }+}diff --git a/moli-renderer-v8/src/style_engine/world_environment.rs b/moli-renderer-v8/src/style_engine/world_environment.rsindex ddbdaafd5..0637f3a23 100644--- a/moli-renderer-v8/src/style_engine/world_environment.rs+++ b/moli-renderer-v8/src/style_engine/world_environment.rs@@ -22,6 +22,13 @@ impl StyleTreeScopeVersions {.unwrap_or(0),}}++ #[cfg(test)]+ pub(super) const fn for_test(document_tree_scopes: u64) -> Self {+ Self {+ document_tree_scopes,+ }+ }}#[derive(Clone, Copy, Debug, Default, PartialEq)]