Skip to content

Truly independent web browser

LibWeb: Stop reading every row to lease a hover frame's records

Andreas Klingdebaca9fd22d
diff --git a/Libraries/LibWeb/Rust/src/css/style/computed.rs b/Libraries/LibWeb/Rust/src/css/style/computed.rs
index 4945d97f881..c72c9dcaf8c 100644
--- a/Libraries/LibWeb/Rust/src/css/style/computed.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/computed.rs
@@ -450,6 +450,27 @@ impl FinalStyleRecordID {
}
}
+/// Whether the raw identity `raw` names a style record other than one the engine installed.
+#[must_use]
+pub(crate) fn names_an_uninstalled_record(raw: u64) -> bool {
+ FinalStyleRecordID::from_raw(raw).is_some_and(|record| record.installed_record().is_none())
+}
+
+/// An immutable hover frame's hold on the style records its rows name, all of which something holds as it is taken: the
+/// engine frees no record whose last holder lets go while the lease stands, until so many did that it reads the rows to
+/// tell which of them they name.
+pub(crate) struct HoverFrameLease {
+ epoch: u32,
+ nodes: crate::cow_column::ColumnSnapshot<
+ crate::layout::node_data::PaintNode,
+ { crate::layout::tree_shape::PUBLISHED_ROWS_PER_CHUNK },
+ >,
+}
+
+/// How many records a task that sees no frame may let go of under a hover frame's lease before it reads the frame's rows:
+/// as many as they are, so that reading them costs a task less than what it made them for, but at least this many.
+const MIN_RECORDS_RELEASED_BEFORE_READING_LEASES: usize = 1024;
+
/// A reader's hold on the payloads of every style record published so far: while one is held, the
/// engine frees no record's payloads, which a reader on another thread may be reading.
pub(crate) struct StyleRecordLease {
@@ -807,7 +828,9 @@ pub struct ComputedGroupSets {
pseudo_rows_moved: Vec<StyleNodeID>,
/// Long-lived immutable readers pin only the records they actually read. Expired readers leave weak entries
/// that the next lease removes, so they neither block reclamation nor need to call back into the owner.
- selected_style_record_leases: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Weak<[u64]>>>>,
+ hover_frame_leases: std::sync::Arc<std::sync::Mutex<Vec<std::sync::Weak<HoverFrameLease>>>>,
+ /// How many released records have the next sweep read the rows of the hover frames' leases.
+ released_records_reading_leases: usize,
// Recyclable animation overlays are deliberately separate from the installed records above.
// Dense element assignments and sparse pseudo assignments pin at most one slot each.
animation_overlay_column: AnimationOverlayColumn,
@@ -835,7 +858,8 @@ impl Default for ComputedGroupSets {
installed_column: Default::default(),
installed_pseudo_column: Default::default(),
pseudo_rows_moved: Vec::new(),
- selected_style_record_leases: std::sync::Arc::default(),
+ hover_frame_leases: std::sync::Arc::default(),
+ released_records_reading_leases: MIN_RECORDS_RELEASED_BEFORE_READING_LEASES,
animation_overlay_column: AnimationOverlayColumn::default(),
animation_overlay_slots: animation_overlay_slots::AnimationOverlaySlots::default(),
animation_overlay_slots_by_record: HashMap::default(),
@@ -891,23 +915,30 @@ impl ComputedGroupSets {
self.installed_column.version()
}
- /// Leases `records` to an immutable hover frame, or answers none where one of them is an animation overlay record,
+ /// Leases the records the rows of an immutable hover frame name, none of which may be an animation overlay record,
/// whose payloads such a lease does not keep.
- pub(crate) fn lease_selected_style_records(&self, records: Vec<u64>) -> Option<std::sync::Arc<[u64]>> {
- for &raw_record in &records {
- // NB: A row can name an overlay record no element is assigned anymore, such as the row of a removed
- // element, which pins its record until the rebuild of its parent frees it.
- let installed = FinalStyleRecordID(raw_record).installed_record()?;
- assert!(self.installed.get(installed).is_some());
- }
- let records: std::sync::Arc<[u64]> = records.into();
- let mut leases = self
- .selected_style_record_leases
- .lock()
- .expect("selected style-record leases");
+ pub(crate) fn lease_hover_frame_style_records(
+ &mut self,
+ nodes: crate::cow_column::ColumnSnapshot<
+ crate::layout::node_data::PaintNode,
+ { crate::layout::tree_shape::PUBLISHED_ROWS_PER_CHUNK },
+ >,
+ ) -> std::sync::Arc<HoverFrameLease> {
+ let lease = std::sync::Arc::new(HoverFrameLease {
+ epoch: self.installed.begin_lease_epoch(),
+ nodes,
+ });
+ let mut leases = self.hover_frame_leases.lock().expect("hover frame leases");
leases.retain(|lease| lease.strong_count() != 0);
- leases.push(std::sync::Arc::downgrade(&records));
- Some(records)
+ leases.push(std::sync::Arc::downgrade(&lease));
+ lease
+ }
+
+ /// Whether something holds the record `raw` names, where it names an installed one.
+ pub(crate) fn style_record_is_held(&self, raw: u64) -> bool {
+ FinalStyleRecordID(raw)
+ .installed_record()
+ .is_some_and(|installed| self.installed.is_held(installed))
}
fn style_records_are_leased(&self) -> bool {
@@ -1651,29 +1682,48 @@ impl ComputedGroupSets {
self.live_animation_overlay_assignments
}
- /// Free the installed records nothing holds, but for those an immutable hover frame reads.
+ /// Free the installed records nothing holds, but for those an immutable hover frame may read.
fn sweep_installed_records(&mut self) {
if self.installed.released_count() == 0 {
return;
}
- let leases = self
- .selected_style_record_leases
+ let leases: Vec<_> = self
+ .hover_frame_leases
.lock()
- .expect("selected style-record leases");
- // NB: An animation overlay keeps the installed record it composes over.
- let kept: super::fast_hash::FastSet<InstalledRecordID> = leases
+ .expect("hover frame leases")
.iter()
.filter_map(std::sync::Weak::upgrade)
- .flat_map(|records| {
- records
- .iter()
- .filter_map(|&record| FinalStyleRecordID(record).installed_record())
- .collect::<Vec<_>>()
- })
- .chain(self.animation_overlay_slots.iter().map(|overlay| overlay.base))
.collect();
- drop(leases);
- let freed = self.installed.sweep(&kept);
+ // NB: An animation overlay keeps the installed record it composes over.
+ let mut kept: super::fast_hash::FastSet<InstalledRecordID> = self
+ .animation_overlay_slots
+ .iter()
+ .map(|overlay| overlay.base)
+ .collect();
+ // NB: A record let go of before a lease was taken is no record its frame names, which tells most of them with no
+ // row read, but a task that sees no next frame would keep all it lets go of.
+ let reads_leases = self.installed.released_count() >= self.released_records_reading_leases;
+ let oldest_lease = match reads_leases {
+ true => None,
+ false => leases.iter().map(|lease| lease.epoch).min(),
+ };
+ let mut rows_read = 0;
+ for lease in leases.iter().filter(|_| reads_leases) {
+ rows_read += lease.nodes.slot_capacity();
+ let mut last = 0;
+ for slot in 0..lease.nodes.slot_capacity() {
+ let record = lease.nodes.get(slot).map_or(0, |node| node.style_record);
+ if record != last {
+ last = record;
+ kept.extend(FinalStyleRecordID(record).installed_record());
+ }
+ }
+ }
+ let freed = self.installed.sweep(&kept, oldest_lease);
+ if reads_leases {
+ self.released_records_reading_leases =
+ self.installed.released_count() + rows_read.max(MIN_RECORDS_RELEASED_BEFORE_READING_LEASES);
+ }
self.records_freed_since_reclamation = self.records_freed_since_reclamation.saturating_add(freed);
}
@@ -2047,21 +2097,20 @@ mod tests {
sets.remove(node);
assert_eq!(sets.live_animation_overlay_records(), 0);
assert_eq!(sets.retired_animation_overlay_records(), 0);
- assert!(
- sets.lease_selected_style_records(vec![base.raw(), overlay.raw()])
- .is_none()
- );
- assert!(sets.lease_selected_style_records(vec![base.raw()]).is_some());
+ assert!(names_an_uninstalled_record(overlay.raw()));
+ assert!(!names_an_uninstalled_record(base.raw()));
sets.unpin_style_record(overlay.raw());
sets.unpin_style_record(base.raw());
}
#[test]
- fn a_selected_record_lease_allows_other_records_to_be_reclaimed() {
+ fn a_hover_frame_lease_allows_records_let_go_of_before_it_to_be_reclaimed() {
let mut sets = ComputedGroupSets::default();
let kept = install(&mut sets, 1, 0);
let discarded = install(&mut sets, 2, 0);
- let lease = sets.lease_selected_style_records(vec![kept.raw()]).unwrap();
+ sets.pin_style_record(kept.raw());
+ let lease = sets.lease_hover_frame_style_records(Default::default());
+ sets.unpin_style_record(kept.raw());
sets.reclaim_unreachable();
assert!(sets.final_style_record_is_live(kept.raw()));
assert!(!sets.final_style_record_is_live(discarded.raw()));
@@ -2075,6 +2124,35 @@ mod tests {
assert!(!sets.final_style_record_is_live(kept.raw()));
}
+ #[test]
+ fn a_hover_frame_lease_keeps_only_what_its_rows_name_once_many_records_are_let_go_of() {
+ let mut sets = ComputedGroupSets::default();
+ let named = install(&mut sets, 1, 0);
+ sets.pin_style_record(named.raw());
+ let mut rows = crate::cow_column::CowColumn::default();
+ rows.grow_to(1);
+ rows.set(
+ 0,
+ crate::layout::node_data::PaintNode {
+ style_record: named.raw(),
+ ..Default::default()
+ },
+ );
+ let lease = sets.lease_hover_frame_style_records(rows.publish());
+ sets.unpin_style_record(named.raw());
+ let unnamed: Vec<_> = (2..=MIN_RECORDS_RELEASED_BEFORE_READING_LEASES + 2)
+ .map(|id| install(&mut sets, id as u64, 0))
+ .collect();
+ sets.reclaim_unreachable();
+ assert!(sets.final_style_record_is_live(named.raw()));
+ assert!(
+ unnamed
+ .iter()
+ .all(|record| !sets.final_style_record_is_live(record.raw()))
+ );
+ drop(lease);
+ }
+
#[test]
fn a_pinned_record_outlives_its_assignment_until_the_last_pin_releases() {
let mut sets = ComputedGroupSets::default();
diff --git a/Libraries/LibWeb/Rust/src/css/style/installed_records.rs b/Libraries/LibWeb/Rust/src/css/style/installed_records.rs
index 3ea3483cd9b..f701ef05c7b 100644
--- a/Libraries/LibWeb/Rust/src/css/style/installed_records.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/installed_records.rs
@@ -76,6 +76,8 @@ pub(super) struct InstalledRecord {
record: Arc<Record>,
/// The assignments and pins holding the record.
holders: u32,
+ /// The epoch of the sweeps' leases the record's last holder let go in.
+ released_in: u32,
}
impl InstalledRecord {
@@ -109,6 +111,8 @@ pub(super) struct InstalledRecords {
by_content: hashbrown::HashTable<InstalledRecordSlot>,
/// The records whose last holder let go, which the next sweep frees unless one took them again.
released: Vec<InstalledRecordID>,
+ /// How many leases on the records held as they are taken were taken.
+ lease_epoch: u32,
}
impl InstalledRecords {
@@ -180,7 +184,11 @@ impl InstalledRecords {
copy
}
};
- self.slots[id.slot.index()] = Some(InstalledRecord { record, holders: 0 });
+ self.slots[id.slot.index()] = Some(InstalledRecord {
+ record,
+ holders: 0,
+ released_in: self.lease_epoch,
+ });
let slots = &self.slots;
self.by_content.insert_unique(content_key, id.slot, |slot| {
slots[slot.index()]
@@ -262,17 +270,30 @@ impl InstalledRecords {
.checked_sub(1)
.expect("installed style record holder underflow");
if entry.holders == 0 {
+ entry.released_in = self.lease_epoch;
self.released.push(id);
}
}
+ /// Whether anything holds the record.
+ pub(super) fn is_held(&self, id: InstalledRecordID) -> bool {
+ self.get(id).is_some_and(|entry| entry.holders != 0)
+ }
+
+ /// Begin the epoch of a lease on the records held now, which keeps those released from here on.
+ pub(super) fn begin_lease_epoch(&mut self) -> u32 {
+ // NB: One that saturates keeps what it released for as long as any lease of the epoch stands.
+ self.lease_epoch = self.lease_epoch.saturating_add(1);
+ self.lease_epoch
+ }
+
pub(super) fn released_count(&self) -> usize {
self.released.len()
}
- /// Free the records no holder took again since they were released, but for those of `kept`,
- /// and answer how many it freed.
- pub(super) fn sweep(&mut self, kept: &HashSet<InstalledRecordID>) -> usize {
+ /// Free the records no holder took again since they were released, but for those of `kept`
+ /// and those released in or after the epoch `oldest_lease`, and answer how many it freed.
+ pub(super) fn sweep(&mut self, kept: &HashSet<InstalledRecordID>, oldest_lease: Option<u32>) -> usize {
let mut freed = 0;
// NB: The list keeps its room for the records released after the sweep.
let mut released = std::mem::take(&mut self.released);
@@ -286,9 +307,10 @@ impl InstalledRecords {
// NB: A record the host or a reader still holds a reference to keeps its slot, so that
// its identity keeps naming it until the last reference beside the slot's goes.
if kept.contains(&id)
- || self.slots[index]
- .as_ref()
- .is_some_and(|entry| Arc::strong_count(entry.record()) > 1)
+ || self.slots[index].as_ref().is_some_and(|entry| {
+ Arc::strong_count(entry.record()) > 1
+ || oldest_lease.is_some_and(|epoch| entry.released_in >= epoch)
+ })
{
return true;
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rs
index 90a6f3d7d0a..3674e172fc5 100644
--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs
@@ -125,7 +125,8 @@ pub(crate) mod pipeline;
mod transition_baselines;
pub(crate) use atoms::{AtomLease, AtomLeases, ProcessAtoms, process_atoms};
pub(crate) use computed::{
- ENGINE_INHERITED_GROUP_COUNT, ReleasedAnimationOverlayRecords, StyleRecordLease, StyleRecordView, ViewLonghands,
+ ENGINE_INHERITED_GROUP_COUNT, HoverFrameLease, ReleasedAnimationOverlayRecords, StyleRecordLease, StyleRecordView,
+ ViewLonghands, names_an_uninstalled_record,
};
pub(crate) use process_style::ProcessStyle;
pub(crate) use publication::RecordDemand;
diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rs
index e85e56c4c01..e8b4895d3b3 100644
--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs
@@ -587,8 +587,18 @@ impl RetainedState {
|| self.computed_group_sets.retired_animation_overlay_records() != 0
}
- pub(crate) fn lease_selected_style_records(&self, records: Vec<u64>) -> Option<std::sync::Arc<[u64]>> {
- self.computed_group_sets.lease_selected_style_records(records)
+ pub(crate) fn lease_hover_frame_style_records(
+ &mut self,
+ nodes: crate::cow_column::ColumnSnapshot<
+ crate::layout::node_data::PaintNode,
+ { crate::layout::tree_shape::PUBLISHED_ROWS_PER_CHUNK },
+ >,
+ ) -> std::sync::Arc<computed::HoverFrameLease> {
+ self.computed_group_sets.lease_hover_frame_style_records(nodes)
+ }
+
+ pub(crate) fn style_record_is_held(&self, record: u64) -> bool {
+ self.computed_group_sets.style_record_is_held(record)
}
pub(crate) fn lease_style_records(&self) -> computed::StyleRecordLease {
diff --git a/Libraries/LibWeb/Rust/src/css/style/tests.rs b/Libraries/LibWeb/Rust/src/css/style/tests.rs
index e877ef22551..c1f41814af3 100644
--- a/Libraries/LibWeb/Rust/src/css/style/tests.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/tests.rs
@@ -1223,6 +1223,35 @@ fn pseudo_element_records_the_host_references_outlive_engine_assignments() {
assert!(!engine.computed_group_sets.final_style_record_is_live(replacement));
}
+#[test]
+fn a_hover_frame_lease_keeps_only_the_records_let_go_of_since_it_was_taken() {
+ let mut engine = StyleEngine::new();
+ let mut raw_node = [0];
+ engine.allocate_style_nodes(&mut raw_node);
+ let target = computed::ComputedStyleTarget::new(StyleNodeID::from_raw(raw_node[0]).unwrap(), u8::MAX);
+ let first = engine.install_test_record(target, None, None, 0).raw();
+ let named_by_the_frame = engine.install_test_record(target, None, None, 1).raw();
+
+ let lease = engine.lease_hover_frame_style_records(Default::default());
+ let last = engine.install_test_record(target, None, None, 2).raw();
+ engine.computed_group_sets.reclaim_unreachable();
+ assert!(!engine.computed_group_sets.final_style_record_is_live(first));
+ assert!(
+ engine
+ .computed_group_sets
+ .final_style_record_is_live(named_by_the_frame)
+ );
+
+ drop(lease);
+ engine.computed_group_sets.reclaim_unreachable();
+ assert!(
+ !engine
+ .computed_group_sets
+ .final_style_record_is_live(named_by_the_frame)
+ );
+ assert!(engine.computed_group_sets.final_style_record_is_live(last));
+}
+
#[test]
fn records_left_unreachable_under_a_lease_are_reclaimed_once_it_drops() {
let mut engine = StyleEngine::new();
diff --git a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
index 95afb091c84..ca885f65436 100644
--- a/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
+++ b/Libraries/LibWeb/Rust/src/layout/layout_node_arena.rs
@@ -1064,6 +1064,8 @@ pub(crate) struct LayoutNodeArena {
chunks_by_address: Vec<ChunkAddress>,
slot_metadata: Vec<SlotMetadata>,
style_records: Vec<u64>,
+ /// How many of `style_records` name a record other than one the engine installed.
+ rows_naming_uninstalled_records: u32,
/// The style record whose image resources the host was last owed for each row, or zero. A row whose record has not
/// changed since holds those resources still, so a build that visits it again owes it nothing.
image_resources_owed_records: Vec<u64>,
@@ -1234,6 +1236,7 @@ impl LayoutNodeArena {
chunks_by_address: Vec::new(),
slot_metadata: Vec::new(),
style_records: Vec::new(),
+ rows_naming_uninstalled_records: 0,
image_resources_owed_records: Vec::new(),
style_record_pins: Vec::new(),
style_records_pinned_by_host: Vec::new(),
@@ -1613,7 +1616,7 @@ impl LayoutNodeArena {
self.forget_row_sharing_dom_node(id);
self.unbind_row(id);
self.set_node_style_node(id, None);
- self.style_records[index as usize] = 0;
+ self.replace_style_record(index as usize, 0);
self.image_resources_owed_records[index as usize] = 0;
self.style_record_pins[index as usize] = ArenaStylePin::None;
self.style_records_pinned_by_host[index as usize] = 0;
@@ -2823,6 +2826,8 @@ impl LayoutNodeArena {
let previous = std::mem::replace(&mut self.style_records[index], record);
if previous != record {
self.image_resources_owed_records[index] = 0;
+ self.rows_naming_uninstalled_records += u32::from(crate::css::style::names_an_uninstalled_record(record));
+ self.rows_naming_uninstalled_records -= u32::from(crate::css::style::names_an_uninstalled_record(previous));
}
previous
}
@@ -3938,16 +3943,15 @@ impl LayoutNodeArena {
}
}
- pub(crate) fn hover_frame_style_records(&self) -> Vec<u64> {
- let mut records: Vec<_> = self
- .style_records
- .iter()
- .copied()
- .filter(|&record| record != 0)
- .collect();
- records.sort_unstable();
- records.dedup();
- records
+ /// The style records the rows name.
+ pub(crate) fn style_records(&self) -> &[u64] {
+ &self.style_records
+ }
+
+ /// Whether a row names a style record other than one the engine installed, as an animation overlay record, which a
+ /// row of a removed element can still name, where no element is assigned it anymore.
+ pub(crate) fn names_uninstalled_style_records(&self) -> bool {
+ self.rows_naming_uninstalled_records != 0
}
pub(crate) fn refresh_style_flags(&mut self, slot: NodeSlotId) {
diff --git a/Libraries/LibWeb/Rust/src/painting/published_frame.rs b/Libraries/LibWeb/Rust/src/painting/published_frame.rs
index 69fbf7781e6..c8ec459941f 100644
--- a/Libraries/LibWeb/Rust/src/painting/published_frame.rs
+++ b/Libraries/LibWeb/Rust/src/painting/published_frame.rs
@@ -63,6 +63,11 @@ pub(crate) struct PublishedRows {
}
impl PublishedRows {
+ /// The column of the nodes, as published.
+ pub(crate) fn paint_nodes(&self) -> &ColumnSnapshot<PaintNode, PUBLISHED_ROWS_PER_CHUNK> {
+ &self.nodes
+ }
+
/// What a live text row published.
pub(crate) fn text(&self, id: NodeSlotId) -> Option<&PublishedTextSlot> {
self.node(id)?;
diff --git a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs
index 69ecbc18b5f..de33495a383 100644
--- a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs
+++ b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs
@@ -123,7 +123,7 @@ struct ReadOnlyHoverFrame {
cursors: Arc<crate::css::style::hover_lane::HoverCursorFacts>,
image_map_areas: crate::painting::image_map_areas::ImageMapAreaColumn,
visual_context: crate::painting::visual_context::VisualContextState,
- _style_records: Arc<[u64]>,
+ _style_records: Arc<crate::css::style::HoverFrameLease>,
}
/// What a lane's ticks hit test and restyle with, sealed with the clock plan at the end of a rendering update.
@@ -209,12 +209,26 @@ impl HoverPlan {
if visual_context.tree.is_none() {
return;
}
- let records = state.arena.arena().hover_frame_style_records();
- let Some(style_records) = state.engine_ref().lease_selected_style_records(records) else {
+ if state.arena.arena().names_uninstalled_style_records() {
return;
- };
+ }
+ // NB: A sweep frees what no holder holds, which no row of the arena can read after it, so what its rows name
+ // is held. The lease has only to keep what is let go of from here on.
+ debug_assert!(
+ state
+ .arena
+ .arena()
+ .style_records()
+ .iter()
+ .all(|&record| record == 0 || state.engine_ref().style_record_is_held(record)),
+ "a row of a hover frame names a record nothing holds"
+ );
+ let rows = state.arena.arena_mut().publish_rows();
+ let style_records = state
+ .engine_mut()
+ .lease_hover_frame_style_records(rows.paint_nodes().clone());
self.read_only_frame = Some(ReadOnlyHoverFrame {
- rows: state.arena.arena_mut().publish_rows(),
+ rows,
bound_rows: state.arena.arena_mut().bound_rows_mut().publish(),
cursors: state.engine_mut().hover_cursor_facts(),
image_map_areas: state.arena.arena().image_map_areas().clone(),