Truly independent web browser
LibWeb: Check layout run cache claims against the committed subtree
Aliaksandr Kalenika5d840f60b2c
diff --git a/Libraries/LibWeb/Rust/src/layout/commit.rs b/Libraries/LibWeb/Rust/src/layout/commit.rsindex a9c41f4ae14..22f62948fec 100644--- a/Libraries/LibWeb/Rust/src/layout/commit.rs+++ b/Libraries/LibWeb/Rust/src/layout/commit.rs@@ -306,6 +306,7 @@ pub(crate) fn commit_replacing(arena: &mut LayoutNodeArena,pass_fragments: &fragment_tree::CompletedPassFragments,) -> CommitNotifications {+ arena.note_layout_commit();let links_by_slot = pass_fragments.links_by_slot();let mut paintables = crate::painting::paintable_build::PaintableCommit::new(arena, root);paintables.begin_commit();diff --git a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rsindex 42fdccfa213..4780a935174 100644--- a/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs+++ b/Libraries/LibWeb/Rust/src/layout/fc_run_cache.rs@@ -220,33 +220,75 @@ pub(crate) struct FcRunCacheValidity {pub(crate) fragment_cache_epoch: u32,}+/// The outputs of a completed run, which stand for any run with a matching key, whether or not the stored run's own+/// result was committed. Its fragments are those it produced; where they are what the box committed, a hit keeps the+/// committed subtree instead of replaying them.pub(super) struct FcRunCacheEntry {key: FcRunCacheKey,validity: FcRunCacheValidity,pub(super) outputs: formatting_context::RunOutputs,- /// Whether the run ran ahead of the committing run it stands for (see- /// run_table_cell_ahead_of_its_intrinsic_block_padding), so that its subtree was never committed and a hit has to- /// replay its descendant fragments.- uncommitted: bool,/// Whether the run is a table cell's that cannot observe the intrinsic block padding its table hands it (see/// table_cell_contents_never_observe_intrinsic_block_padding), so that it stands for runs with any such padding.table_cell_intrinsic_block_padding_unobserved: bool,+ /// How many layouts the arena had committed when the run was stored. The subtrees the run took from the cache as+ /// they were committed are only known to be so while no layout was committed since.+ layout_commits_when_stored: u64,}-impl FcRunCacheEntry {- pub(super) fn can_reuse_committed_subtree(&self) -> bool {- !self.uncommitted && outputs_allow_committed_subtree_reuse(&self.outputs)- }+/// A stored run a probe may take in place of running, and whether it keeps the box's committed subtree.+pub(super) struct FcRunCacheHit {+ pub(super) entry: std::sync::Arc<FcRunCacheEntry>,+ pub(super) reuses_committed_subtree: bool,+}- pub(super) fn is_uncommitted(&self) -> bool {- self.uncommitted+impl FcRunCacheEntry {+ /// Whether the committed fragment of `box_` and every fragment committed in its subtree are the ones the stored run+ /// produced: the root's fragment shows the stored line data at the stored content size, and each fragment the run+ /// placed in its own scope is the box's committed fragment, placed as the run placed it. A fragment that was+ /// committed holds the fragments committed below it.+ fn describes_committed_subtree(&self, callbacks: &LayoutPass<'_>, box_: Node) -> bool {+ let Some(root) = self.outputs.root.as_ref() else {+ return false;+ };+ if !root.propagated_pending_abspos.is_empty() {+ return false;+ }+ let arena = callbacks.arena();+ if !arena.paintable_row_is_populated(box_) {+ return false;+ }+ let cells = &self.outputs.root_outcome.cells;+ let root_fragment_is_the_stored_one = arena+ .with_current_committed_fragment(box_, |fragment| {+ same_allocation(+ fragment.line_data.as_ref(),+ self.outputs.root_outcome.line_data.as_ref(),+ ) && fragment.content_inline_size == cells.content_inline_size+ && fragment.content_block_size == cells.content_block_size+ })+ .unwrap_or(false);+ root_fragment_is_the_stored_one && links_are_committed(callbacks, &root.scoped_descendants)+ }++ /// Whether the stored fragments can be replayed. Those of the subtrees the stored run took from the cache are the+ /// committed ones, so such a run is replayed only before anything else is committed.+ fn can_be_replayed(&self, callbacks: &LayoutPass<'_>) -> bool {+ self.outputs.root.as_ref().is_none_or(|root| {+ root.reused_subtree_roots.is_empty()+ || callbacks.arena().layout_commit_count() == self.layout_commits_when_stored+ })}- /// The outputs a hit for `probe` replays: the stored ones, with the root's block paddings moved by however much- /// the intrinsic block padding `probe` carries differs from the stored run's.- pub(super) fn outputs_to_replay(&self, probe: &FcRunCacheKey) -> formatting_context::RunOutputs {- let mut outputs = if self.can_reuse_committed_subtree() {- self.outputs_for_reused_subtree()+ /// The outputs a hit for `probe` absorbs: the stored ones, or only what escapes the stored run where the hit keeps+ /// the committed subtree, with the root's block paddings moved by however much the intrinsic block padding `probe`+ /// carries differs from the stored run's.+ pub(super) fn outputs_to_replay(+ &self,+ probe: &FcRunCacheKey,+ reuses_committed_subtree: bool,+ ) -> formatting_context::RunOutputs {+ let mut outputs = if reuses_committed_subtree {+ outputs_without_descendant_fragments(&self.outputs)} else {self.outputs.clone()};@@ -259,19 +301,36 @@ impl FcRunCacheEntry {cells.padding_top += probe.root_cells.padding_top - self.key.root_cells.padding_top;cells.padding_bottom += probe.root_cells.padding_bottom - self.key.root_cells.padding_bottom;}+}- pub(super) fn outputs_for_reused_subtree(&self) -> formatting_context::RunOutputs {- debug_assert!(self.can_reuse_committed_subtree());- // conclude() already stored this entry without its descendant fragments.- self.outputs.clone()+fn same_allocation<T>(left: Option<&std::sync::Arc<T>>, right: Option<&std::sync::Arc<T>>) -> bool {+ match (left, right) {+ (None, None) => true,+ (Some(left), Some(right)) => std::sync::Arc::ptr_eq(left, right),+ _ => false,}}-fn outputs_allow_committed_subtree_reuse(outputs: &formatting_context::RunOutputs) -> bool {- outputs- .root- .as_ref()- .is_none_or(|root| root.propagated_pending_abspos.is_empty())+/// Whether each of `links` is the committed fragment of its box, or the later committed fragment of a box with+/// several, placed as the link places it.+fn links_are_committed(callbacks: &LayoutPass<'_>, links: &[fragment_tree::FragmentLink]) -> bool {+ let arena = callbacks.arena();+ let mut earlier_fragments_of_box: HashMap<Node, usize> = HashMap::default();+ links.iter().all(|link| {+ let node = link.fragment.node;+ let fragment_index = earlier_fragments_of_box.entry(node).or_default();+ let index = *fragment_index;+ *fragment_index += 1;+ if index == 0 {+ return arena.holds_current_committed_fragment_link(node, link);+ }+ arena.paintable_row_is_populated(node)+ && arena+ .committed_side_data(node)+ .box_fragments()+ .get(index - 1)+ .is_some_and(|committed| link.places_same_fragment_identically_to(&committed.link))+ })}fn outputs_without_descendant_fragments(outputs: &formatting_context::RunOutputs) -> formatting_context::RunOutputs {@@ -556,7 +615,7 @@ impl FcRunCacheAttempt {should_collect_devtools_layout_data: bool,callbacks: &LayoutPass<'_>,key: &FcRunCacheKey,- ) -> Result<Self, std::sync::Arc<FcRunCacheEntry>> {+ ) -> Result<Self, FcRunCacheHit> {// A run this cache cannot describe still commits its subtree, so a stored entry would go on// describing paintables that run has replaced. Measurement runs commit nothing and leave it alone.let run_supersedes_stored_entry = layout_mode == LayoutMode::Normal && !purpose.is_measurement();@@ -579,7 +638,13 @@ impl FcRunCacheAttempt {let validity = run_root_validity(callbacks, box_);let structural_epoch_bumps = store.inline_layout_damage_since_stored(box_);if let Some(entry) = store.matching(box_.slot_index(), validity, key) {- return Err(entry);+ let reuses_committed_subtree = entry.describes_committed_subtree(callbacks, box_);+ if reuses_committed_subtree || entry.can_be_replayed(callbacks) {+ return Err(FcRunCacheHit {+ entry,+ reuses_committed_subtree,+ });+ }}let structurally_damaged_entry =store.structurally_damaged_entry(box_.slot_index(), validity, key, structural_epoch_bumps);@@ -606,29 +671,6 @@ impl FcRunCacheAttempt {box_: Node,key: FcRunCacheKey,outputs: &formatting_context::RunOutputs,- ) {- self.conclude_run(callbacks, box_, key, outputs, false);- }-- /// Concludes a run that ran ahead of the committing run it stands for, which replays its outputs, descendant- /// fragments included, as a hit (see run_table_cell_ahead_of_its_intrinsic_block_padding).- pub(super) fn conclude_uncommitted(- self,- callbacks: &LayoutPass<'_>,- box_: Node,- key: FcRunCacheKey,- outputs: &formatting_context::RunOutputs,- ) {- self.conclude_run(callbacks, box_, key, outputs, true);- }-- fn conclude_run(- self,- callbacks: &LayoutPass<'_>,- box_: Node,- key: FcRunCacheKey,- outputs: &formatting_context::RunOutputs,- uncommitted: bool,) {let Self::Store {validity,@@ -656,18 +698,14 @@ impl FcRunCacheAttempt {let entry = FcRunCacheEntry {key,validity,- outputs: if uncommitted || !outputs_allow_committed_subtree_reuse(outputs) {- outputs.clone()- } else {- outputs_without_descendant_fragments(outputs)- },- uncommitted,+ outputs: outputs.clone(),table_cell_intrinsic_block_padding_unobserved: key.input.sizing.table_cell_intrinsic_block_padding.is_some()&& table_cell_contents_never_observe_intrinsic_block_padding(callbacks, box_),+ layout_commits_when_stored: callbacks.arena().layout_commit_count(),};store.store(box_.slot_index(), entry);}@@ -734,30 +772,6 @@ pub(super) fn can_describe_run_in_any_layout_mode()}-/// Stores the entry a committing run replayed from an uncommitted one as an ordinary entry for the key it was probed-/// with, now that the replayed subtree is committed with the run's parent.-pub(super) fn store_replayed_uncommitted_entry(- callbacks: &LayoutPass<'_>,- box_: Node,- key: FcRunCacheKey,- replayed: &FcRunCacheEntry,- outputs: &formatting_context::RunOutputs,-) {- debug_assert!(replayed.uncommitted);- let entry = FcRunCacheEntry {- key,- validity: replayed.validity,- outputs: if !outputs_allow_committed_subtree_reuse(outputs) {- outputs.clone()- } else {- outputs_without_descendant_fragments(outputs)- },- uncommitted: false,- table_cell_intrinsic_block_padding_unobserved: replayed.table_cell_intrinsic_block_padding_unobserved,- };- callbacks.arena().fc_run_cache_store().store(box_.slot_index(), entry);-}-/// Whether a table cell's run cannot observe the intrinsic block padding its table hands it (the vertical-alignment/// stretch): the padding only moves the cell's content box, and content that is only text lays out relative to that./// Nothing in it resolves against the padding box, as out-of-flow descendants would, and it holds no scroll container.@@ -833,8 +847,8 @@ mod tests {atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above: None,host_findings: None,},- uncommitted: false,table_cell_intrinsic_block_padding_unobserved: false,+ layout_commits_when_stored: 0,};store.store(0, entry(1));store.store(1, entry(1));diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rsindex 11b835f6773..6aec366bbd3 100644--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs@@ -1940,7 +1940,7 @@ pub(super) fn run_formatting_context(&cache_key,) {Ok(attempt) => attempt,- Err(entry) => {+ Err(hit) => {if let Some(result) = reuse_committed_subtree_as_it_is(purpose,parent_fragments,@@ -1948,11 +1948,11 @@ pub(super) fn run_formatting_context(box_,&callbacks,&cache_key,- &entry,+ &hit,) {return result;}- let reuses_committed_subtree = entry.can_reuse_committed_subtree();+ let reuses_committed_subtree = hit.reuses_committed_subtree;let _trace = callbacks.arena().layout_trace@@ -1963,10 +1963,7 @@ pub(super) fn run_formatting_context("REPLAY FRAGMENTS"}});- let outputs = entry.outputs_to_replay(&cache_key);- if entry.is_uncommitted() {- fc_run_cache::store_replayed_uncommitted_entry(&callbacks, box_, cache_key, &entry, &outputs);- }+ let outputs = hit.entry.outputs_to_replay(&cache_key, reuses_committed_subtree);return absorb_run_outputs(&callbacks,parent_fragments,@@ -2028,10 +2025,10 @@ pub(super) fn run_formatting_context(absorb_run_outputs(&callbacks, parent_fragments, parent_used, box_, outputs, false)}-/// Takes a committing run of `box_` from the cache entry `entry` with nothing replayed: its root record gets what the+/// Takes a committing run of `box_` from the cache hit `hit` with nothing replayed: its root record gets what the/// stored run left, and the run's placement attaches the box's committed fragment as it is. That is exact where the-/// committed fragment is the one the stored run produced, which a plain box shows by holding the record's metrics and-/// the very line data the run left, and where nothing from the stored run reaches past its root.+/// committed subtree is the one the stored run produced, the box is plain, and nothing from the stored run reaches+/// past its root.fn reuse_committed_subtree_as_it_is(purpose: LayoutPurpose,parent_fragments: Option<&fragment_tree::RunFragmentBuilder>,@@ -2039,14 +2036,18 @@ fn reuse_committed_subtree_as_it_is(box_: Node,callbacks: &LayoutPass<'_>,cache_key: &fc_run_cache::FcRunCacheKey,- entry: &fc_run_cache::FcRunCacheEntry,+ hit: &fc_run_cache::FcRunCacheHit,) -> Option<ChildLayoutResult> {let fragments = parent_fragments?;+ let entry = &*hit.entry;if purpose != LayoutPurpose::Commit- || !entry.can_reuse_committed_subtree()- || entry.is_uncommitted()+ || !hit.reuses_committed_subtree|| !cache_key.has_no_table_cell_intrinsic_block_padding()- || entry.outputs.root.as_ref().is_some_and(|root| !root.carries_nothing())+ || entry+ .outputs+ .root+ .as_ref()+ .is_some_and(|root| !root.propagates_nothing())|| NodeFacts::new(callbacks, box_).has_anchor_names(){return None;@@ -2850,7 +2851,7 @@ pub(crate) fn run_table_cell_ahead_of_its_intrinsic_block_padding() {Ok(fc_run_cache::FcRunCacheAttempt::Bypass) => return None,Ok(attempt) => attempt,- Err(entry) => {+ Err(hit) => {let _trace = run.callbacks.arena().layout_trace.run(cell,FormattingContextType::Block,@@ -2858,7 +2859,7 @@ pub(crate) fn run_table_cell_ahead_of_its_intrinsic_block_padding(LayoutMode::Normal,|| "READ RESULT AHEAD OF INTRINSIC BLOCK PADDING",);- return Some(entry.outputs.result);+ return Some(hit.entry.outputs.result);}};let _trace = run.callbacks.arena().layout_trace.run(@@ -2874,7 +2875,7 @@ pub(crate) fn run_table_cell_ahead_of_its_intrinsic_block_padding(if let Some(discarded_outputs) = &discarded_outputs {run_repeatability::verify_repeated_run(&run.callbacks, cell, discarded_outputs, &outputs);}- cache_attempt.conclude_uncommitted(&run.callbacks, cell, cache_key, &outputs);+ cache_attempt.conclude(&run.callbacks, cell, cache_key, &outputs);Some(outputs.result)}diff --git a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rsindex 1d29619aa45..a55defe264f 100644--- a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs+++ b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs@@ -58,8 +58,9 @@ pub(crate) struct FragmentLink {pub(crate) inset_top: CssPixels,pub(crate) inset_bottom: CssPixels,pub(crate) containing_line_box_index: Option<usize>,- /// Boxed, as few links place an absolutely positioned box and the inputs are larger than the rest of the link.- pub(crate) abspos_layout_inputs: Option<Box<abspos_inputs::AbsposLayoutInputs>>,+ /// Shared, as few links place an absolutely positioned box, the inputs are larger than the rest of the link, and+ /// layout run cache entries keep copies of links.+ pub(crate) abspos_layout_inputs: Option<std::sync::Arc<abspos_inputs::AbsposLayoutInputs>>,/// The default scroll shift of a box whose anchor insets its layout resolved, which commit records for the box.pub(crate) default_scroll_shift: Option<abspos_inputs::DefaultScrollShift>,pub(crate) containing_block: crate::layout::node_data::NodeSlotId,@@ -616,7 +617,7 @@ fn link_fragment(fragment: std::sync::Arc<Fragment>, placement: PlacementData) -inset_top: placement.inset_top,inset_bottom: placement.inset_bottom,containing_line_box_index: placement.containing_line_box_index,- abspos_layout_inputs: placement.abspos_layout_inputs.map(Box::new),+ abspos_layout_inputs: placement.abspos_layout_inputs.map(std::sync::Arc::new),default_scroll_shift: placement.default_scroll_shift,containing_block: placement.containing_block,frame: placement.frame,@@ -635,11 +636,9 @@ pub(crate) struct UnplacedRootFragment {}impl UnplacedRootFragment {- /// Whether the root holds nothing past its box: no descendant fragment, reuse marker or payload for an ancestor.- pub(crate) fn carries_nothing(&self) -> bool {- self.scoped_descendants.is_empty()- && self.reused_subtree_roots.is_empty()- && self.propagated_pending_abspos.is_empty()+ /// Whether the root hands its ancestors no payload.+ pub(crate) fn propagates_nothing(&self) -> bool {+ self.propagated_pending_abspos.is_empty()&& self.propagated_anchor_candidates.is_empty()&& self.propagated_inline_containing_block_rects.is_empty()&& self.propagated_abspos_containing_block_info.is_empty()diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rsindex 93f1bf152fd..c473a84534f 100644--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs@@ -1282,6 +1282,8 @@ pub(crate) struct LayoutNodeArena {unresolved_container_lengths: RefCell<Vec<NodeSlotId>>,partial_layout_count: Cell<u64>,full_layout_count: Cell<u64>,+ /// How many layouts were committed, full and partial.+ layout_commit_count: u64,layout_tree_build_stats: Cell<FfiLayoutTreeBuildStats>,pre_order_labels: Vec<Cell<u64>>,pre_order_relabel_count: Cell<u64>,@@ -1403,6 +1405,7 @@ impl LayoutNodeArena {unresolved_container_lengths: RefCell::new(Vec::new()),partial_layout_count: Cell::new(0),full_layout_count: Cell::new(0),+ layout_commit_count: 0,layout_tree_build_stats: Cell::new(FfiLayoutTreeBuildStats::default()),pre_order_labels: Vec::new(),pre_order_relabel_count: Cell::new(0),@@ -1470,6 +1473,14 @@ impl LayoutNodeArena {self.intrinsic_size_cache_drops.take()}+ pub(crate) fn layout_commit_count(&self) -> u64 {+ self.layout_commit_count+ }++ pub(crate) fn note_layout_commit(&mut self) {+ self.layout_commit_count += 1;+ }+pub(crate) fn has_intrinsic_size_cache_drops(&self) -> bool {!self.intrinsic_size_cache_drops.borrow().is_empty()}@@ -7361,7 +7372,7 @@ mod tests {let allocation = arena.allocate_for_test();let inputs = test_abspos_layout_inputs();let mut link = fragment_tree::FragmentLink::for_test(allocation.slot);- link.abspos_layout_inputs = Some(Box::new(inputs));+ link.abspos_layout_inputs = Some(std::sync::Arc::new(inputs));arena.set_committed_fragment_link(allocation.slot, link, None);assert!(arena.committed_fragment_link(arena.data(allocation.slot)).is_some());assert_eq!(@@ -7390,7 +7401,7 @@ mod tests {let new = arena.allocate_for_test();let inputs = test_abspos_layout_inputs();let mut link = fragment_tree::FragmentLink::for_test(old.slot);- link.abspos_layout_inputs = Some(Box::new(inputs));+ link.abspos_layout_inputs = Some(std::sync::Arc::new(inputs));let retained_fragment = link.fragment.clone();arena.set_committed_fragment_link(old.slot, link, None);