diff --git a/moli-renderer-v8/src/style_engine/mod.rs b/moli-renderer-v8/src/style_engine/mod.rs index d79fb5cb66a..4df7e13e575 100644 --- a/moli-renderer-v8/src/style_engine/mod.rs +++ b/moli-renderer-v8/src/style_engine/mod.rs @@ -820,7 +820,7 @@ impl MoliStyleEngine { boundary: StyleInvalidationDrainBoundary, ) { let world = self.world_for_document(document); - self.flush_pending_structural_mutations_for_world(host, document, &world); + self.flush_pending_structural_mutations_for_world(host, &world); let pending = world.pending_invalidations.take(); let source_stores = world.borrow_source_stores(); drain_style_invalidations( diff --git a/moli-renderer-v8/src/style_engine/mutation_effect.rs b/moli-renderer-v8/src/style_engine/mutation_effect.rs index bacfec7fc14..1944f95b531 100644 --- a/moli-renderer-v8/src/style_engine/mutation_effect.rs +++ b/moli-renderer-v8/src/style_engine/mutation_effect.rs @@ -1,4 +1,4 @@ -use std::{borrow::Cow, sync::Arc}; +use std::sync::Arc; use indexmap::IndexSet; use moli_selector::{ @@ -271,62 +271,13 @@ pub(crate) fn normalized_style_attribute_name( .unwrap_or_else(|| name.to_owned()) } -/// Keep only live structural history for an emptied ordinary fragment. Removed -/// roots must already have been invalidated from the original effects, and the -/// caller must retain the original source scope. A fragment with children, an -/// element parent, and a ShadowRoot can still have selector-dependent styles. -/// Their histories must pass the ordinary retained-topology checks unchanged. -pub(super) fn normalized_deferred_structural_mutation_effects<'a>( +/// Drop exhausted ordinary fragment history after resolving the full source +/// scope and retiring removed roots. Later mutations can refill the fragment. +pub(super) fn retain_live_structural_mutation_effects( host: &DomHost, - effects: &'a [StyleMutationEffect], -) -> Cow<'a, [StyleMutationEffect]> { - if !effects - .iter() - .any(|effect| is_empty_ordinary_fragment_child_list(host, effect)) - { - return Cow::Borrowed(effects); - } - - let mut normalized = Vec::with_capacity(effects.len()); - let mut connected_roots = IndexSet::new(); - let mut disconnected_roots = IndexSet::new(); - let mut connected_slot = None; - let mut disconnected_slot = None; - for effect in effects { - if is_empty_ordinary_fragment_child_list(host, effect) { - continue; - } - match effect { - StyleMutationEffect::ConnectedSubtrees { roots } => { - if connected_slot.is_none() { - connected_slot = Some(normalized.len()); - normalized.push(effect.clone()); - } - connected_roots.extend(roots.iter().copied()); - } - StyleMutationEffect::DisconnectedSubtrees { roots } => { - if disconnected_slot.is_none() { - disconnected_slot = Some(normalized.len()); - normalized.push(effect.clone()); - } - disconnected_roots.extend(roots.iter().copied()); - } - // Connection facts are sets, but child-list and slot histories are - // ordered inputs. Do not deduplicate or collapse their splices. - _ => normalized.push(effect.clone()), - } - } - if let Some(slot) = connected_slot { - normalized[slot] = StyleMutationEffect::ConnectedSubtrees { - roots: connected_roots.into_iter().collect::>().into(), - }; - } - if let Some(slot) = disconnected_slot { - normalized[slot] = StyleMutationEffect::DisconnectedSubtrees { - roots: disconnected_roots.into_iter().collect::>().into(), - }; - } - Cow::Owned(normalized) + effects: &mut Vec, +) { + effects.retain(|effect| !is_empty_ordinary_fragment_child_list(host, effect)); } fn is_empty_ordinary_fragment_child_list(host: &DomHost, effect: &StyleMutationEffect) -> bool { @@ -569,8 +520,20 @@ mod tests { )); } + fn merged_structural_effects(effects: &[StyleMutationEffect]) -> Vec { + use crate::style_engine::pending_mutation::PendingStructuralStyleEffects; + + let mut pending = PendingStructuralStyleEffects::default(); + for effect in effects { + pending.extend(std::slice::from_ref(effect)); + } + let (merged, input_count) = pending.into_effects(); + assert_eq!(input_count, effects.len()); + merged + } + #[test] - fn consumed_fragment_normalization_preserves_real_splices_and_the_effect_limit() { + fn consumed_fragment_preparation_preserves_real_splices_and_the_effect_limit() { use crate::style_engine::{ eligibility::child_list_effects_have_current_topology, scope::style_source_scope_for_mutation_effects, @@ -605,8 +568,26 @@ mod tests { inserted, "cleanup must see the original removed roots before normalization" ); - let normalized = normalized_deferred_structural_mutation_effects(&host, &effects); - assert!(matches!(&normalized, Cow::Owned(_))); + let mut normalized = merged_structural_effects(&effects); + let connected_batches = normalized + .iter() + .filter_map(|effect| match effect { + StyleMutationEffect::ConnectedSubtrees { roots } => Some(roots.as_ref()), + _ => None, + }) + .collect::>(); + let connected_roots = effects + .iter() + .filter_map(|effect| match effect { + StyleMutationEffect::ConnectedSubtrees { roots } => Some(roots.iter().copied()), + _ => None, + }) + .flatten() + .collect::>() + .into_iter() + .collect::>(); + assert_eq!(connected_batches, [connected_roots.as_slice()]); + retain_live_structural_mutation_effects(&host, &mut normalized); assert!(normalized.len() <= 256); assert!(child_list_effects_have_current_topology(&host, &normalized)); assert_eq!( @@ -637,7 +618,8 @@ mod tests { let added = host.append_child_effects(parent, child); collect_native_effects(&mut effects, &host, &added); } - let normalized = normalized_deferred_structural_mutation_effects(&host, &effects); + let mut normalized = merged_structural_effects(&effects); + retain_live_structural_mutation_effects(&host, &mut normalized); assert_eq!( normalized .iter() @@ -649,10 +631,10 @@ mod tests { } #[test] - fn ordinary_element_shadow_and_nonempty_fragment_histories_stay_borrowed() { + fn element_shadow_and_refilled_fragment_histories_are_retained() { use crate::style_engine::eligibility::child_list_effects_have_current_topology; - for parent_kind in ["detached-element", "shadow-root", "nonempty-fragment"] { + for parent_kind in ["detached-element", "shadow-root", "refilled-fragment"] { let mut host = test_host(); let document = host.document_handle(); let destination = host.create_element("main"); @@ -664,12 +646,7 @@ mod tests { assert!(host.append_child(document, shadow_host)); host.attach_shadow_root(shadow_host, "open").unwrap() } - "nonempty-fragment" => { - let fragment = host.create_document_fragment(); - let remaining = host.create_element("span"); - assert!(host.append_child(fragment, remaining)); - fragment - } + "refilled-fragment" => host.create_document_fragment(), _ => unreachable!(), }; let moved = host.create_element("span"); @@ -683,9 +660,14 @@ mod tests { StyleMutationEffect::ChildList { parent, removed_nodes, .. } if *parent == old_parent && removed_nodes == &[moved] ))); - let normalized = normalized_deferred_structural_mutation_effects(&host, &effects); - assert!(matches!(&normalized, Cow::Borrowed(_)), "{parent_kind}"); - assert_eq!(normalized.as_ref(), effects.as_slice(), "{parent_kind}"); + let mut normalized = merged_structural_effects(&effects); + if parent_kind == "refilled-fragment" { + let remaining = host.create_element("span"); + assert!(host.append_child(old_parent, remaining)); + } + let original_count = normalized.len(); + retain_live_structural_mutation_effects(&host, &mut normalized); + assert_eq!(normalized.len(), original_count, "{parent_kind}"); assert!( !child_list_effects_have_current_topology(&host, &normalized), "real reparenting must retain the conservative fallback: {parent_kind}" @@ -711,8 +693,8 @@ mod tests { collect_native_effects(&mut effects, &host, &staged); let consumed = host.append_child_effects(destination, fragment); collect_native_effects(&mut effects, &host, &consumed); - let normalized = normalized_deferred_structural_mutation_effects(&host, &effects); - assert!(matches!(&normalized, Cow::Owned(_))); + let mut normalized = merged_structural_effects(&effects); + retain_live_structural_mutation_effects(&host, &mut normalized); assert!(normalized.iter().any(|effect| matches!( effect, StyleMutationEffect::ChildList { parent, removed_nodes, .. } diff --git a/moli-renderer-v8/src/style_engine/pending_mutation.rs b/moli-renderer-v8/src/style_engine/pending_mutation.rs index 46ff1b29d5b..c0adf452013 100644 --- a/moli-renderer-v8/src/style_engine/pending_mutation.rs +++ b/moli-renderer-v8/src/style_engine/pending_mutation.rs @@ -1,6 +1,8 @@ use std::cell::RefCell; -use crate::protocol_types::EmulatedMediaOverrides; +use indexmap::IndexSet; + +use crate::{document_runtime::DomHandle, protocol_types::EmulatedMediaOverrides}; #[cfg(test)] use super::cause::PendingStyleInvalidationWorkKind; @@ -11,13 +13,57 @@ pub(super) struct PendingStructuralStyleMutations { groups: RefCell>, } -#[derive(Clone, Debug, PartialEq)] pub(super) struct PendingStructuralStyleMutationGroup { - pub(super) effects: Vec, + pub(super) effects: PendingStructuralStyleEffects, pub(super) emulated_media: EmulatedMediaOverrides, pub(super) viewport: StyleViewport, } +#[derive(Default)] +pub(super) struct PendingStructuralStyleEffects { + history: Vec, + connected_roots: IndexSet, + disconnected_roots: IndexSet, + input_count: usize, +} + +impl PendingStructuralStyleEffects { + pub(super) fn extend(&mut self, effects: &[StyleMutationEffect]) { + self.input_count += effects.len(); + for effect in effects { + match effect { + StyleMutationEffect::ConnectedSubtrees { roots } => { + self.connected_roots.extend(roots.iter().copied()); + } + StyleMutationEffect::DisconnectedSubtrees { roots } => { + self.disconnected_roots.extend(roots.iter().copied()); + } + // Child-list splices and slot assignments carry ordered history. + effect => self.history.push(effect.clone()), + } + } + } + + pub(super) fn into_effects(self) -> (Vec, usize) { + let mut effects = self.history; + if !self.connected_roots.is_empty() { + effects.push(StyleMutationEffect::ConnectedSubtrees { + roots: self.connected_roots.into_iter().collect::>().into(), + }); + } + if !self.disconnected_roots.is_empty() { + effects.push(StyleMutationEffect::DisconnectedSubtrees { + roots: self + .disconnected_roots + .into_iter() + .collect::>() + .into(), + }); + } + (effects, self.input_count) + } +} + impl PendingStructuralStyleMutations { pub(super) fn new() -> Self { Self::default() @@ -37,11 +83,13 @@ impl PendingStructuralStyleMutations { && group.emulated_media == *emulated_media && group.viewport == viewport { - group.effects.extend_from_slice(effects); + group.effects.extend(effects); return; } + let mut pending_effects = PendingStructuralStyleEffects::default(); + pending_effects.extend(effects); groups.push(PendingStructuralStyleMutationGroup { - effects: effects.to_vec(), + effects: pending_effects, emulated_media: emulated_media.clone(), viewport, }); @@ -65,7 +113,7 @@ impl PendingStructuralStyleMutations { self.groups .borrow() .iter() - .map(|group| group.effects.len()) + .map(|group| group.effects.input_count) .sum() } diff --git a/moli-renderer-v8/src/style_engine/runtime_invalidation.rs b/moli-renderer-v8/src/style_engine/runtime_invalidation.rs index 59c126852be..981c96da4ee 100644 --- a/moli-renderer-v8/src/style_engine/runtime_invalidation.rs +++ b/moli-renderer-v8/src/style_engine/runtime_invalidation.rs @@ -20,7 +20,7 @@ use super::{ document_world::DocumentStyleWorld, eligibility::child_list_effects_have_current_topology, mutation_effect::{ - detached_style_subtree_roots_for_mutations, normalized_deferred_structural_mutation_effects, + detached_style_subtree_roots_for_mutations, retain_live_structural_mutation_effects, }, schedule::queue_style_invalidation_for_scope, scope::{ @@ -110,7 +110,6 @@ impl MoliStyleEngine { &world, host, document_effects, - document_effects, emulated_media, viewport, ); @@ -155,7 +154,6 @@ impl MoliStyleEngine { &self, world: &DocumentStyleWorld, host: &DomHost, - scope_effects: &[StyleMutationEffect], effects: &[StyleMutationEffect], emulated_media: &EmulatedMediaOverrides, viewport: StyleViewport, @@ -163,9 +161,7 @@ impl MoliStyleEngine { let profile_enabled = moli_trace::cpu_profile_enabled(); let total_started = profile_enabled.then(std::time::Instant::now); let source_scope_started = profile_enabled.then(std::time::Instant::now); - // The retained cause may omit exhausted fragment history, but source - // ownership still comes from every original mutation handle. - let source_scope = source_scope_for_mutations(host, scope_effects); + let source_scope = source_scope_for_mutations(host, effects); let source_scope_us = source_scope_started .map(|started| started.elapsed().as_micros()) .unwrap_or_default(); @@ -209,84 +205,49 @@ impl MoliStyleEngine { pub(super) fn flush_pending_structural_mutations_for_world( &self, host: &DomHost, - document: DomHandle, world: &DocumentStyleWorld, ) { for group in world.pending_structural_mutations.take() { - self.queue_deferred_style_invalidation_for_mutations( - document, + let (mut effects, input_count) = group.effects.into_effects(); + // Exhausted fragments can still contribute detached roots and source + // ownership. Resolve these against the full history before pruning. + self.invalidate_detached_style_subtrees_for_mutations(host, &effects); + let source_scope = source_scope_for_mutations(host, &effects); + let merged_count = effects.len(); + retain_live_structural_mutation_effects(host, &mut effects); + if !mutation_effects_have_source_scope(&effects) { + continue; + } + + // Keep the original cutoff for batches with no exhausted fragment + // history. Otherwise count only the work left after pruning. + let effect_count = if effects.len() == merged_count { + input_count + } else { + effects.len() + }; + let pending_effects = if effect_count <= IMMEDIATE_STRUCTURAL_MUTATION_EFFECT_LIMIT + && child_list_effects_have_current_topology(host, &effects) + { + effects.retain(|effect| { + !matches!(effect, StyleMutationEffect::DisconnectedSubtrees { .. }) + }); + effects + } else { + Vec::new() + }; + self.queue_style_invalidation_scope( + world.document, world, host, - &group.effects, &group.emulated_media, group.viewport, + source_scope, + PendingStyleInvalidationCause::Mutation(pending_effects), ); } } - fn queue_deferred_style_invalidation_for_mutations( - &self, - document: DomHandle, - world: &DocumentStyleWorld, - host: &DomHost, - effects: &[StyleMutationEffect], - emulated_media: &EmulatedMediaOverrides, - viewport: StyleViewport, - ) { - // Even an exhausted ordinary fragment can have removed previously - // styled descendants. Retire those inputs before filtering history. - self.invalidate_detached_style_subtrees_for_mutations(host, effects); - let normalized = normalized_deferred_structural_mutation_effects(host, effects); - if !mutation_effects_have_source_scope(&normalized) { - return; - } - if normalized.len() <= IMMEDIATE_STRUCTURAL_MUTATION_EFFECT_LIMIT - && child_list_effects_have_current_topology(host, &normalized) - { - self.queue_style_invalidation_for_mutations( - world, - host, - effects, - &normalized, - emulated_media, - viewport, - ); - return; - } - self.queue_structural_mutation_source_scope_fallback( - document, - world, - host, - effects, - emulated_media, - viewport, - ); - } - - fn queue_structural_mutation_source_scope_fallback( - &self, - document: DomHandle, - world: &DocumentStyleWorld, - host: &DomHost, - effects: &[StyleMutationEffect], - emulated_media: &EmulatedMediaOverrides, - viewport: StyleViewport, - ) { - // Use all mutation handles to cover both the old and new tree scopes. - // Cause-local fallback roots are not enough when old neighbors moved. - let source_scope = source_scope_for_mutations(host, effects); - let cause = PendingStyleInvalidationCause::Mutation(Vec::new()); - self.queue_style_invalidation_scope( - document, - world, - host, - emulated_media, - viewport, - source_scope, - cause, - ); - } - pub(super) fn invalidate_detached_style_subtrees_for_mutations( &self, host: &DomHost,