Skip to content

Truly independent web browser

LibWeb: Verify that layout runs repeat without memoized layout

Aliaksandr Kalenik19e47549a09c
diff --git a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs
index 0dba710a9e1..96d5c2caa70 100644
--- a/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/block_formatting_context.rs
@@ -2551,7 +2551,8 @@ impl<'pass> BlockFormattingContext<'pass> {
) -> bool {
let facts = self.facts(node);
let container_facts = self.facts(block_container);
- self.run.purpose == formatting_context::LayoutPurpose::Commit
+ !self.run.callbacks.scratch().reads_no_memoized_layout()
+ && self.run.purpose == formatting_context::LayoutPurpose::Commit
&& self.run.fragmentainer.is_none()
&& self.run.layout_mode == LayoutMode::Normal
&& self.run.fragments.is_some()
diff --git a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
index 33f36162ddf..11b835f6773 100644
--- a/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/formatting_context.rs
@@ -1894,6 +1894,25 @@ pub(super) fn run_formatting_context(
parent_fragments.clear_reused_subtree_root(box_, parent_used);
}
let root_cells = used_values::UsedValuesCellState::capture(parent_used);
+ if callbacks.scratch().reads_no_memoized_layout() {
+ let outputs = execute_formatting_context_run(
+ purpose,
+ root_cells,
+ box_,
+ root_containing_block,
+ parent_grid,
+ fc_type,
+ layout_mode,
+ should_collect_devtools_layout_data,
+ callbacks,
+ input,
+ parent_block,
+ None,
+ table_inline_layout,
+ None,
+ );
+ return absorb_run_outputs(&callbacks, parent_fragments, parent_used, box_, outputs, false);
+ }
let cache_key = fc_run_cache::FcRunCacheKey::new(fc_type, input, root_cells);
let memoizes_measurement = purpose.is_measurement()
&& callbacks.scratch().memoizes_measurements()
@@ -1963,6 +1982,24 @@ pub(super) fn run_formatting_context(
.layout_trace
.run(box_, fc_type, purpose, layout_mode, || cache_attempt.trace_action());
let previous_line_data = cache_attempt.previous_line_data();
+ let discarded_outputs = run_repeatability::lay_out_discarded_run(&callbacks, || {
+ execute_formatting_context_run(
+ purpose,
+ root_cells,
+ box_,
+ root_containing_block,
+ parent_grid,
+ fc_type,
+ layout_mode,
+ should_collect_devtools_layout_data,
+ callbacks,
+ input,
+ parent_block,
+ None,
+ table_inline_layout.clone(),
+ None,
+ )
+ });
let outputs = execute_formatting_context_run(
purpose,
root_cells,
@@ -1979,6 +2016,9 @@ pub(super) fn run_formatting_context(
table_inline_layout,
None,
);
+ if let Some(discarded_outputs) = &discarded_outputs {
+ run_repeatability::verify_repeated_run(&callbacks, box_, discarded_outputs, &outputs);
+ }
if memoizes_measurement {
callbacks
.scratch()
@@ -2768,6 +2808,37 @@ pub(crate) fn run_table_cell_ahead_of_its_intrinsic_block_padding(
input.sizing.flex_self_block_size_resolution_space = None;
let root_cells = used_values::UsedValuesCellState::capture(run.records.used_values(cell));
let cache_key = fc_run_cache::FcRunCacheKey::new(FormattingContextType::Block, input, root_cells);
+ let execute = |previous_line_data| {
+ execute_formatting_context_run(
+ LayoutPurpose::Commit,
+ root_cells,
+ cell,
+ root_containing_block,
+ None,
+ FormattingContextType::Block,
+ LayoutMode::Normal,
+ run.should_collect_devtools_layout_data,
+ run.callbacks,
+ input,
+ None,
+ previous_line_data,
+ None,
+ None,
+ )
+ };
+ if run.callbacks.scratch().reads_no_memoized_layout() {
+ if !fc_run_cache::can_describe_run(
+ cell,
+ false,
+ LayoutMode::Normal,
+ run.should_collect_devtools_layout_data,
+ &run.callbacks,
+ &cache_key,
+ ) {
+ return None;
+ }
+ return Some(execute(None).result);
+ }
let cache_attempt = match fc_run_cache::FcRunCacheAttempt::probe(
LayoutPurpose::Commit,
cell,
@@ -2798,22 +2869,11 @@ pub(crate) fn run_table_cell_ahead_of_its_intrinsic_block_padding(
|| "RUN AHEAD OF INTRINSIC BLOCK PADDING",
);
let previous_line_data = cache_attempt.previous_line_data();
- let outputs = execute_formatting_context_run(
- LayoutPurpose::Commit,
- root_cells,
- cell,
- root_containing_block,
- None,
- FormattingContextType::Block,
- LayoutMode::Normal,
- run.should_collect_devtools_layout_data,
- run.callbacks,
- input,
- None,
- previous_line_data,
- None,
- None,
- );
+ let discarded_outputs = run_repeatability::lay_out_discarded_run(&run.callbacks, || execute(None));
+ let outputs = execute(previous_line_data);
+ 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);
Some(outputs.result)
}
diff --git a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
index 41ff46ca88c..1d29619aa45 100644
--- a/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
+++ b/Libraries/LibWeb/Rust/src/layout/fragment_tree.rs
@@ -75,6 +75,23 @@ fn same_allocation<T>(left: Option<&std::sync::Arc<T>>, right: Option<&std::sync
}
}
+/// How two fragments' shared payloads compare: as the same allocations, as painting needs, or as equal values, as
+/// two layouts of one box do.
+#[derive(Clone, Copy)]
+enum PayloadComparison {
+ SameAllocation,
+ SameValue,
+}
+
+impl PayloadComparison {
+ fn matches<T: PartialEq>(self, left: Option<&std::sync::Arc<T>>, right: Option<&std::sync::Arc<T>>) -> bool {
+ match self {
+ Self::SameAllocation => same_allocation(left, right),
+ Self::SameValue => left.map(|left| &**left) == right.map(|right| &**right),
+ }
+ }
+}
+
impl Fragment {
fn builds_identically_to(&self, previous: &Fragment) -> bool {
self.has_same_box_properties(previous)
@@ -113,6 +130,15 @@ impl Fragment {
/// Box properties excluding inline content and child fragments. Painting compares those
/// separately: a new descendant fragment does not necessarily change this box's commands.
pub(crate) fn has_same_box_properties(&self, previous: &Fragment) -> bool {
+ self.has_same_box_properties_comparing_payloads(previous, PayloadComparison::SameAllocation)
+ }
+
+ /// Box properties excluding inline content and child fragments, with payloads compared by value.
+ pub(crate) fn has_same_box_properties_comparing_payloads_by_value(&self, previous: &Fragment) -> bool {
+ self.has_same_box_properties_comparing_payloads(previous, PayloadComparison::SameValue)
+ }
+
+ fn has_same_box_properties_comparing_payloads(&self, previous: &Fragment, payloads: PayloadComparison) -> bool {
self.node == previous.node
&& self.content_inline_size == previous.content_inline_size
&& self.content_block_size == previous.content_block_size
@@ -133,18 +159,18 @@ impl Fragment {
&& self.table_column_index == previous.table_column_index
&& self.table_column_span == previous.table_column_span
&& self.hidden_by_collapsed_columns == previous.hidden_by_collapsed_columns
- && same_allocation(
+ && payloads.matches(
self.collapsed_table_borders.as_ref(),
previous.collapsed_table_borders.as_ref(),
)
- && same_allocation(self.grid_layout_data.as_ref(), previous.grid_layout_data.as_ref())
- && same_allocation(self.flex_layout_data.as_ref(), previous.flex_layout_data.as_ref())
+ && payloads.matches(self.grid_layout_data.as_ref(), previous.grid_layout_data.as_ref())
+ && payloads.matches(self.flex_layout_data.as_ref(), previous.flex_layout_data.as_ref())
&& self.multicol_layout_data == previous.multicol_layout_data
&& self.math_paint_data == previous.math_paint_data
- && same_allocation(self.used_grid_tracks.as_ref(), previous.used_grid_tracks.as_ref())
+ && payloads.matches(self.used_grid_tracks.as_ref(), previous.used_grid_tracks.as_ref())
&& self.svg == previous.svg
- && same_allocation(self.computed_svg_path.as_ref(), previous.computed_svg_path.as_ref())
- && same_allocation(
+ && payloads.matches(self.computed_svg_path.as_ref(), previous.computed_svg_path.as_ref())
+ && payloads.matches(
self.svg_text_character_cells.as_ref(),
previous.svg_text_character_cells.as_ref(),
)
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
index 3fed5a512b6..93f1bf152fd 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
@@ -351,9 +351,18 @@ pub(crate) struct IntrinsicSizeCacheStamp {
#[derive(Default)]
pub(crate) struct IntrinsicSizeCaches {
slots: RefCell<Vec<IntrinsicSizeCacheSlot>>,
+ suspended: Cell<bool>,
}
impl IntrinsicSizeCaches {
+ /// Runs `measure` with the caches answering nothing and keeping nothing.
+ pub(crate) fn suspended_while<R>(&self, measure: impl FnOnce() -> R) -> R {
+ let was_suspended = self.suspended.replace(true);
+ let result = measure();
+ self.suspended.set(was_suspended);
+ result
+ }
+
/// Drops the entries of `slots`, which were freed or whose rows' cache epoch wrapped.
pub(crate) fn drop_slots(&self, slots: Vec<u32>) {
let mut caches = self.slots.borrow_mut();
@@ -370,6 +379,9 @@ impl IntrinsicSizeCaches {
stamp: IntrinsicSizeCacheStamp,
answer: impl FnOnce(&IntrinsicSizeMaps) -> Option<R>,
) -> Option<R> {
+ if self.suspended.get() {
+ return None;
+ }
let caches = self.slots.borrow();
let slot = caches.get(stamp.index as usize)?;
if slot.generation != stamp.generation || slot.epoch != stamp.epoch {
@@ -393,6 +405,9 @@ impl IntrinsicSizeCaches {
}
fn with_maps_mut(&self, stamp: IntrinsicSizeCacheStamp, callback: impl FnOnce(&mut IntrinsicSizeMaps)) {
+ if self.suspended.get() {
+ return;
+ }
let IntrinsicSizeCacheStamp {
index,
generation,
diff --git a/Libraries/LibWeb/Rust/src/layout/mod.rs b/Libraries/LibWeb/Rust/src/layout/mod.rs
index 91a8cdfa141..21b3fc8b549 100644
--- a/Libraries/LibWeb/Rust/src/layout/mod.rs
+++ b/Libraries/LibWeb/Rust/src/layout/mod.rs
@@ -46,6 +46,7 @@ pub(crate) mod rendered_text;
mod replaced_with_children_formatting_context;
pub(crate) mod row_reads;
pub(crate) mod run_records;
+pub(crate) mod run_repeatability;
pub(crate) mod script_entries;
pub(crate) mod shell_reads;
pub(crate) mod sizing_context;
diff --git a/Libraries/LibWeb/Rust/src/layout/run_records.rs b/Libraries/LibWeb/Rust/src/layout/run_records.rs
index aa5ca55cdee..be657223f0b 100644
--- a/Libraries/LibWeb/Rust/src/layout/run_records.rs
+++ b/Libraries/LibWeb/Rust/src/layout/run_records.rs
@@ -32,6 +32,8 @@ pub(crate) struct LayoutScratch {
/// outside any run.
host_findings_of_runs_in_progress: RefCell<Vec<HostFindings>>,
host_findings_outside_runs: RefCell<HostFindings>,
+ /// How many runs whose results are discarded are in progress, which neither read nor keep memoized layout.
+ discarded_runs_in_progress: Cell<u32>,
}
/// What layout found out that the host hears of once the layout that found it is committed: the nodes whose SVG
@@ -148,6 +150,7 @@ impl Default for LayoutScratch {
has_position_option_styles: Cell::new(false),
host_findings_of_runs_in_progress: RefCell::new(Vec::new()),
host_findings_outside_runs: RefCell::new(HostFindings::default()),
+ discarded_runs_in_progress: Cell::new(0),
}
}
}
@@ -185,6 +188,9 @@ impl LayoutScratch {
block_container: NodeSlotId,
stash: super::inline_level_iterator::StashedInlineItems,
) {
+ if self.reads_no_memoized_layout() {
+ return;
+ }
self.inline_item_stashes.borrow_mut().insert(block_container, stash);
}
@@ -192,9 +198,28 @@ impl LayoutScratch {
&self,
block_container: NodeSlotId,
) -> Option<super::inline_level_iterator::StashedInlineItems> {
+ if self.reads_no_memoized_layout() {
+ return None;
+ }
self.inline_item_stashes.borrow().get(&block_container).cloned()
}
+ /// Lays out `run`, whose result is discarded, without reading or keeping memoized layout, so that it computes
+ /// everything afresh and leaves nothing for the runs after it.
+ pub(crate) fn lay_out_discarded_run<R>(&self, run: impl FnOnce() -> R) -> R {
+ let in_progress = &self.discarded_runs_in_progress;
+ in_progress.set(in_progress.get() + 1);
+ let result = self.intrinsic_size_caches.suspended_while(run);
+ in_progress.set(in_progress.get() - 1);
+ result
+ }
+
+ /// Whether a run whose result is discarded is in progress, which reads and keeps no memoized layout: the run
+ /// cache, the in-flow block cache, inline item stashes, intrinsic sizes and memoized measurements.
+ pub(crate) fn reads_no_memoized_layout(&self) -> bool {
+ self.discarded_runs_in_progress.get() > 0
+ }
+
/// Notes what the innermost run in progress found out for the host, or the pass outside any run.
pub(crate) fn note_host_findings(&self, note: impl FnOnce(&mut HostFindings)) {
let mut runs = self.host_findings_of_runs_in_progress.borrow_mut();
@@ -229,7 +254,7 @@ impl LayoutScratch {
}
pub(crate) fn memoizes_measurements(&self) -> bool {
- self.measurement_memo.borrow().depth > 0
+ self.measurement_memo.borrow().depth > 0 && !self.reads_no_memoized_layout()
}
pub(super) fn memoized_measurement(
diff --git a/Libraries/LibWeb/Rust/src/layout/run_repeatability.rs b/Libraries/LibWeb/Rust/src/layout/run_repeatability.rs
new file mode 100644
index 00000000000..57896e8cb31
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/layout/run_repeatability.rs
@@ -0,0 +1,376 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! With LIBWEB_VERIFY_RUN_REPEATABILITY=cold, every layout run that executes is laid out twice. The first layout
+//! reads and keeps no memoized layout and its result is discarded; the second is the run itself. Both have to agree on
+//! everything the run hands its parent, which shows that a run depends on nothing but its input and the state of the
+//! pass, and that what it reads from memoized layout is what it would have computed.
+
+use super::*;
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum RunRepeatabilityVerification {
+ Off,
+ Cold,
+}
+
+fn run_repeatability_verification() -> RunRepeatabilityVerification {
+ static VERIFICATION: std::sync::OnceLock<RunRepeatabilityVerification> = std::sync::OnceLock::new();
+ *VERIFICATION.get_or_init(|| match std::env::var("LIBWEB_VERIFY_RUN_REPEATABILITY").as_deref() {
+ Err(_) => RunRepeatabilityVerification::Off,
+ Ok("cold") => RunRepeatabilityVerification::Cold,
+ Ok(other) => panic!("LIBWEB_VERIFY_RUN_REPEATABILITY must be cold, not {other:?}"),
+ })
+}
+
+/// Lays out a run whose result is discarded through `run`, where the verification is on and no such run is in
+/// progress around it already. Nothing it does is traced.
+pub(super) fn lay_out_discarded_run(
+ callbacks: &LayoutPass<'_>,
+ run: impl FnOnce() -> formatting_context::RunOutputs,
+) -> Option<formatting_context::RunOutputs> {
+ if run_repeatability_verification() == RunRepeatabilityVerification::Off
+ || callbacks.scratch().reads_no_memoized_layout()
+ {
+ return None;
+ }
+ Some(
+ callbacks
+ .arena()
+ .layout_trace
+ .without_events(|| callbacks.scratch().lay_out_discarded_run(run)),
+ )
+}
+
+/// Checks that the run of `box_` that produced `used` repeated what the discarded run that produced `discarded` did.
+pub(super) fn verify_repeated_run(
+ callbacks: &LayoutPass<'_>,
+ box_: Node,
+ discarded: &formatting_context::RunOutputs,
+ used: &formatting_context::RunOutputs,
+) {
+ assert_eq!(
+ used.result, discarded.result,
+ "the run of {box_:?} returned a result its discarded repetition does not"
+ );
+ assert_eq!(
+ used.root_outcome.cells, discarded.root_outcome.cells,
+ "the run of {box_:?} left a root record its discarded repetition does not"
+ );
+ assert_eq!(
+ used.root_outcome.own_metrics_sealed, discarded.root_outcome.own_metrics_sealed,
+ "the run of {box_:?} seals the root's metrics unlike its discarded repetition"
+ );
+ assert!(
+ used.root_outcome.line_data.as_deref() == discarded.root_outcome.line_data.as_deref(),
+ "the run of {box_:?} left line data its discarded repetition does not"
+ );
+ assert!(
+ rare_payloads_match(
+ used.root_outcome.rare.as_deref(),
+ discarded.root_outcome.rare.as_deref()
+ ),
+ "the run of {box_:?} left rare payloads its discarded repetition does not"
+ );
+ assert_eq!(
+ used.atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above,
+ discarded.atomic_root_sizing_repeats_for_available_inline_sizes_at_or_above,
+ "the run of {box_:?} claims an available inline size threshold its discarded repetition does not"
+ );
+ assert!(
+ host_findings_match(used.host_findings.as_deref(), discarded.host_findings.as_deref()),
+ "the run of {box_:?} found out for the host what its discarded repetition does not"
+ );
+ let (used_root, discarded_root) = match (&used.root, &discarded.root) {
+ (None, None) => return,
+ (Some(used_root), Some(discarded_root)) => (used_root, discarded_root),
+ _ => panic!("the run of {box_:?} and its discarded repetition do not both build fragments"),
+ };
+ assert!(
+ discarded_root.reused_subtree_roots.is_empty(),
+ "the discarded repetition of the run of {box_:?} reused a subtree"
+ );
+ assert!(
+ same_elements_in_any_order(
+ &used_root.propagated_pending_abspos,
+ &discarded_root.propagated_pending_abspos
+ ) && same_elements_in_any_order(
+ &used_root.propagated_anchor_candidates,
+ &discarded_root.propagated_anchor_candidates
+ ) && same_elements_in_any_order(
+ &used_root.propagated_inline_containing_block_rects,
+ &discarded_root.propagated_inline_containing_block_rects
+ ) && same_elements_in_any_order(
+ &used_root.propagated_abspos_containing_block_info,
+ &discarded_root.propagated_abspos_containing_block_info
+ ),
+ "the run of {box_:?} propagates payloads its discarded repetition does not"
+ );
+ let mut nodes_laid_out_afresh = HashSet::default();
+ collect_nodes_of_fragment_subtrees(&discarded_root.scoped_descendants, &mut nodes_laid_out_afresh);
+ let comparison = FreshDescendantComparison {
+ callbacks,
+ reused_subtree_roots: &used_root.reused_subtree_roots,
+ nodes_laid_out_afresh,
+ };
+ if let Err(difference) = comparison.compare_children(
+ box_,
+ &used_root.scoped_descendants,
+ &discarded_root.scoped_descendants,
+ false,
+ ) {
+ panic!("the run of {box_:?} lays out descendants unlike its discarded repetition: {difference}");
+ }
+}
+
+fn same_elements_in_any_order<T: PartialEq>(left: &[T], right: &[T]) -> bool {
+ if left.len() != right.len() {
+ return false;
+ }
+ let mut matched = vec![false; right.len()];
+ left.iter().all(|element| {
+ let Some(index) = (0..right.len()).find(|&index| !matched[index] && right[index] == *element) else {
+ return false;
+ };
+ matched[index] = true;
+ true
+ })
+}
+
+fn host_findings_match(left: Option<&run_records::HostFindings>, right: Option<&run_records::HostFindings>) -> bool {
+ let none = run_records::HostFindings::default();
+ let left = left.unwrap_or(&none);
+ let right = right.unwrap_or(&none);
+ same_elements_in_any_order(
+ &left.nodes_with_unresolved_container_lengths,
+ &right.nodes_with_unresolved_container_lengths,
+ ) && same_elements_in_any_order(&left.messages, &right.messages)
+ && left.document_svg_root_natural_size == right.document_svg_root_natural_size
+}
+
+fn rare_payloads_match(
+ left: Option<&used_values::UsedValuesRareData>,
+ right: Option<&used_values::UsedValuesRareData>,
+) -> bool {
+ let none = used_values::UsedValuesRareData::default();
+ let left = left.unwrap_or(&none);
+ let right = right.unwrap_or(&none);
+ let used_values::UsedValuesRareData {
+ computed_svg_path,
+ svg_text_character_cells,
+ svg,
+ grid_layout_data,
+ flex_layout_data,
+ multicol_layout_data,
+ math_paint_data,
+ used_grid_tracks,
+ collapsed_table_borders,
+ abspos_layout_inputs,
+ default_scroll_shift,
+ orthogonal_flow_baselines,
+ } = left;
+ computed_svg_path.as_deref() == right.computed_svg_path.as_deref()
+ && svg_text_character_cells.as_deref() == right.svg_text_character_cells.as_deref()
+ && *svg == right.svg
+ && grid_layout_data.as_deref() == right.grid_layout_data.as_deref()
+ && flex_layout_data.as_deref() == right.flex_layout_data.as_deref()
+ && multicol_layout_data.as_deref() == right.multicol_layout_data.as_deref()
+ && math_paint_data.as_deref() == right.math_paint_data.as_deref()
+ && used_grid_tracks.as_deref() == right.used_grid_tracks.as_deref()
+ && collapsed_table_borders.as_deref() == right.collapsed_table_borders.as_deref()
+ && *abspos_layout_inputs == right.abspos_layout_inputs
+ && *default_scroll_shift == right.default_scroll_shift
+ && *orthogonal_flow_baselines == right.orthogonal_flow_baselines
+}
+
+fn collect_nodes_of_fragment_subtrees(links: &[fragment_tree::FragmentLink], nodes: &mut HashSet<u32>) {
+ for link in links {
+ nodes.insert(link.fragment.node.slot_index());
+ collect_nodes_of_fragment_subtrees(&link.fragment.children, nodes);
+ }
+}
+
+/// Compares the descendant fragments a run produced with those a fresh layout of its root produced. Where the run
+/// reused a committed subtree, the committed fragments stand for the ones it did not lay out again.
+struct FreshDescendantComparison<'comparison, 'pass> {
+ callbacks: &'comparison LayoutPass<'pass>,
+ reused_subtree_roots: &'comparison HashSet<u32>,
+ nodes_laid_out_afresh: HashSet<u32>,
+}
+
+impl FreshDescendantComparison<'_, '_> {
+ fn compare_children(
+ &self,
+ parent: Node,
+ expected: &[fragment_tree::FragmentLink],
+ fresh: &[fragment_tree::FragmentLink],
+ expected_is_committed: bool,
+ ) -> Result<(), String> {
+ if expected.is_empty() && expected_is_committed {
+ return self.compare_with_committed_fragments_of_descendants(parent, fresh);
+ }
+ // NB: Below a subtree the run reused, the run holds the committed fragments, whose children a commit that
+ // reused them left out.
+ if !expected_is_committed && self.reused_subtree_roots.contains(&parent.slot_index()) {
+ return self.compare_with_committed_descendants(parent, fresh);
+ }
+ if expected.len() != fresh.len() {
+ return Err(format!(
+ "{parent:?} has children {:?} where the fresh layout has {:?}",
+ nodes_of(expected),
+ nodes_of(fresh)
+ ));
+ }
+ for (index, fresh_link) in fresh.iter().enumerate() {
+ let node = fresh_link.fragment.node;
+ let expected_link = if expected[index].fragment.node == node {
+ &expected[index]
+ } else {
+ let occurrence = fresh[..index].iter().filter(|link| link.fragment.node == node).count();
+ expected
+ .iter()
+ .filter(|link| link.fragment.node == node)
+ .nth(occurrence)
+ .ok_or_else(|| {
+ format!(
+ "{parent:?} has children {:?} where the fresh layout has {:?}",
+ nodes_of(expected),
+ nodes_of(fresh)
+ )
+ })?
+ };
+ self.compare_links(expected_link, fresh_link, expected_is_committed)?;
+ }
+ Ok(())
+ }
+
+ fn compare_with_committed_descendants(
+ &self,
+ parent: Node,
+ fresh: &[fragment_tree::FragmentLink],
+ ) -> Result<(), String> {
+ let committed_children = self
+ .callbacks
+ .arena()
+ .with_current_committed_fragment(parent, |fragment| fragment.children.clone())
+ .unwrap_or_default();
+ if !committed_children.is_empty() {
+ return self.compare_children(parent, &committed_children, fresh, true);
+ }
+ self.compare_with_committed_fragments_of_descendants(parent, fresh)
+ }
+
+ fn compare_with_committed_fragments_of_descendants(
+ &self,
+ parent: Node,
+ fresh: &[fragment_tree::FragmentLink],
+ ) -> Result<(), String> {
+ self.ensure_every_committed_descendant_is_laid_out_afresh(parent)?;
+ for (index, fresh_link) in fresh.iter().enumerate() {
+ let node = fresh_link.fragment.node;
+ let fragment_index = fresh[..index].iter().filter(|link| link.fragment.node == node).count();
+ let Some(committed_link) = self.committed_fragment_link(node, fragment_index) else {
+ return Err(format!(
+ "{node:?}, a child of the reused subtree of {parent:?}, has no committed fragment {fragment_index}"
+ ));
+ };
+ self.compare_links(&committed_link, fresh_link, true)?;
+ let is_last_fresh_fragment = !fresh[index + 1..].iter().any(|link| link.fragment.node == node);
+ if is_last_fresh_fragment && self.committed_fragment_link(node, fragment_index + 1).is_some() {
+ return Err(format!(
+ "{node:?}, a child of the reused subtree of {parent:?}, has more committed fragments than the {} of \
+ the fresh layout",
+ fragment_index + 1
+ ));
+ }
+ }
+ Ok(())
+ }
+
+ fn ensure_every_committed_descendant_is_laid_out_afresh(&self, subtree_root: Node) -> Result<(), String> {
+ let mut committed_descendant_missing_from_fresh_layout = None;
+ self.callbacks
+ .arena()
+ .for_each_node_in_layout_subtree_in_pre_order(subtree_root, |node| {
+ if node != subtree_root
+ && committed_descendant_missing_from_fresh_layout.is_none()
+ && self.callbacks.has_committed_fragment_link(node)
+ && !self.nodes_laid_out_afresh.contains(&node.slot_index())
+ {
+ committed_descendant_missing_from_fresh_layout = Some(node);
+ }
+ });
+ match committed_descendant_missing_from_fresh_layout {
+ None => Ok(()),
+ Some(node) => Err(format!(
+ "{node:?}, a descendant of the reused subtree of {subtree_root:?}, has a committed fragment where the \
+ fresh layout has none"
+ )),
+ }
+ }
+
+ fn committed_fragment_link(&self, node: Node, fragment_index: usize) -> Option<fragment_tree::FragmentLink> {
+ if fragment_index == 0 {
+ return self.callbacks.committed_fragment_link(node);
+ }
+ let arena = self.callbacks.arena();
+ if !arena.paintable_row_is_populated(node) {
+ return None;
+ }
+ arena
+ .committed_side_data(node)
+ .box_fragments()
+ .get(fragment_index - 1)
+ .map(|later_fragment| later_fragment.link.clone())
+ }
+
+ fn compare_links(
+ &self,
+ expected: &fragment_tree::FragmentLink,
+ fresh: &fragment_tree::FragmentLink,
+ expected_is_committed: bool,
+ ) -> Result<(), String> {
+ let node = fresh.fragment.node;
+ if !expected.has_same_placement(fresh) {
+ return Err(format!(
+ "{node:?} is placed at {} where the fresh layout places it at {}",
+ describe_placement(expected),
+ describe_placement(fresh)
+ ));
+ }
+ let (expected, fresh) = (&expected.fragment, &fresh.fragment);
+ if !expected.has_same_box_properties_comparing_payloads_by_value(fresh) {
+ return Err(format!("{node:?} has box properties unlike the fresh layout"));
+ }
+ if expected.line_data.as_deref() != fresh.line_data.as_deref() {
+ return Err(format!("{node:?} has line data unlike the fresh layout"));
+ }
+ self.compare_children(node, &expected.children, &fresh.children, expected_is_committed)
+ }
+}
+
+fn nodes_of(links: &[fragment_tree::FragmentLink]) -> Vec<Node> {
+ links.iter().map(|link| link.fragment.node).collect()
+}
+
+fn describe_placement(link: &fragment_tree::FragmentLink) -> String {
+ format!(
+ "offset ({:?}, {:?}) insets ({:?} {:?} {:?} {:?}) line box {:?} in {:?}, abspos inputs {}",
+ link.committed_offset.x,
+ link.committed_offset.y,
+ link.inset_top,
+ link.inset_right,
+ link.inset_bottom,
+ link.inset_left,
+ link.containing_line_box_index,
+ link.containing_block,
+ if link.abspos_layout_inputs.is_some() {
+ "present"
+ } else {
+ "absent"
+ }
+ )
+}
diff --git a/Libraries/LibWeb/Rust/src/layout/table_formatting_context.rs b/Libraries/LibWeb/Rust/src/layout/table_formatting_context.rs
index a5ca2b798d6..d5cb54c7c41 100644
--- a/Libraries/LibWeb/Rust/src/layout/table_formatting_context.rs
+++ b/Libraries/LibWeb/Rust/src/layout/table_formatting_context.rs
@@ -623,6 +623,7 @@ pub(crate) struct TableCell {
pub(crate) max_content_inline_size: Option<CssPixels>,
}
+#[derive(Clone)]
pub(crate) struct Row {
pub(crate) box_: Node,
pub(crate) base_block_size: CssPixels,
@@ -670,6 +671,7 @@ pub(crate) struct TableGrid {
pub(crate) occupancy: HashSet<(usize, usize)>,
}
+#[derive(Clone)]
pub(crate) struct TableInlineLayout {
table_box: Node,
table_constraints: ContainingBlockConstraints,
diff --git a/Libraries/LibWeb/Rust/src/layout/trace.rs b/Libraries/LibWeb/Rust/src/layout/trace.rs
index e0aa624301c..19b5effcf91 100644
--- a/Libraries/LibWeb/Rust/src/layout/trace.rs
+++ b/Libraries/LibWeb/Rust/src/layout/trace.rs
@@ -146,6 +146,14 @@ impl LayoutTrace {
Some(Scope { trace: self, line })
}
+ /// Runs `untraced` with nothing it does traced.
+ pub(super) fn without_events<R>(&self, untraced: impl FnOnce() -> R) -> R {
+ let trace = self.0.take();
+ let result = untraced();
+ *self.0.borrow_mut() = trace;
+ result
+ }
+
pub(super) fn pass(&self, partial_root: Option<NodeSlotId>) -> Option<Scope<'_>> {
match partial_root {
Some(root) => self.scope("layout PARTIAL ", Some(root), String::new),
diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.py
index 98e9da85b77..1e66d9468e3 100755
--- a/Meta/Linters/check_rust_process_wide_state.py
+++ b/Meta/Linters/check_rust_process_wide_state.py
@@ -119,6 +119,7 @@ RENDER_STATE_ALLOWED = {
"css/style/mod.rs:STYLE_ANSWER_PATCH",
"css/style/mod.rs:STYLE_PLAN_PROVENANCE",
"layout/in_flow_block_cache.rs:ENABLED",
+ "layout/run_repeatability.rs:VERIFICATION",
"render_state/clock/hover.rs:LOGS",
],
),