Truly independent web browser
LibWeb: Count style FFI crossings in one static array
Andreas Kling4daa1a1f26d7
diff --git a/Libraries/LibWeb/Rust/src/css/ffi_stats.rs b/Libraries/LibWeb/Rust/src/css/ffi_stats.rsindex 461c6759b56..93bd1df43bc 100644--- a/Libraries/LibWeb/Rust/src/css/ffi_stats.rs+++ b/Libraries/LibWeb/Rust/src/css/ffi_stats.rs@@ -13,14 +13,11 @@//! before/after counts on deterministic workloads. Reading and resetting is//! exposed to C++ for the `internals.styleFfiCounters()` test surface.//!-//! The counters are always compiled in but disabled until reset. Each thread owns-//! a bridge counter context, including operations outside a document update.-//! Observation folds those contexts into process-wide totals; the disabled hot-//! path remains one relaxed atomic load per crossing.+//! The counters are always compiled in but disabled until reset, so the hot path+//! remains one relaxed atomic load per crossing.-use std::cell::{OnceCell, RefCell};+use std::cell::RefCell;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};-use std::sync::{Arc, Mutex, OnceLock};macro_rules! define_ffi_ops {($($variant:ident => $name:literal,)+) => {@@ -45,98 +42,13 @@ define_ffi_ops! {AnimationKeyframeLonghandEntry => "animationKeyframeLonghandEntries",AnimationEvaluationEntry => "animationEvaluationEntries",TransitionDecisionEntry => "transitionDecisionEntries",- // Computed longhand table copies, whose cost follows the table's width rather than a change.- LonghandTableCopiedSlots => "longhandTableCopiedSlots",- LonghandTableCopyRetains => "longhandTableCopyRetains",SubstitutionParse => "substitutionParses",SizesAttributeParseEntry => "sizesAttributeParseEntries",// Ownership callbacks: Rust -> C++.StringRetainReleaseCallback => "stringRetainReleaseCallbacks",}-/// Counts owned by one bridge context. Atomics permit observation from another thread;-/// updates never touch another context's counter cache lines.-struct FfiCounters {- values: [AtomicU64; FFI_OP_COUNT],-}--impl FfiCounters {- fn new() -> Self {- Self {- values: [const { AtomicU64::new(0) }; FFI_OP_COUNT],- }- }-- #[inline]- fn bump(&self, op: FfiOp) {- self.values[op as usize].fetch_add(1, Ordering::Relaxed);- }-}--/// Process-wide observation folds live contexts and the totals of contexts that have exited.-/// The registry is locked only at observation, reset and context creation/destruction.-struct CounterRegistry {- completed: [u64; FFI_OP_COUNT],- live: Vec<Arc<FfiCounters>>,-}--impl CounterRegistry {- const fn new() -> Self {- Self {- completed: [0; FFI_OP_COUNT],- live: Vec::new(),- }- }-- fn value(&self, index: usize) -> u64 {- self.live.iter().fold(self.completed[index], |total, counters| {- total.wrapping_add(counters.values[index].load(Ordering::Relaxed))- })- }-- fn reset(&mut self) {- self.completed.fill(0);- for counters in &self.live {- for value in &counters.values {- value.store(0, Ordering::Relaxed);- }- }- }-}--struct BridgeCounterContext {- counters: Arc<FfiCounters>,- registry: Arc<Mutex<CounterRegistry>>,-}--impl BridgeCounterContext {- fn new(registry: Arc<Mutex<CounterRegistry>>) -> Self {- let counters = Arc::new(FfiCounters::new());- registry.lock().unwrap().live.push(counters.clone());- Self { counters, registry }- }-}--impl Drop for BridgeCounterContext {- fn drop(&mut self) {- let mut registry = self.registry.lock().unwrap();- for (total, value) in registry.completed.iter_mut().zip(&self.counters.values) {- *total = total.wrapping_add(value.load(Ordering::Relaxed));- }- registry.live.retain(|counters| !Arc::ptr_eq(counters, &self.counters));- }-}--fn counter_registry() -> &'static Arc<Mutex<CounterRegistry>> {- static REGISTRY: OnceLock<Arc<Mutex<CounterRegistry>>> = OnceLock::new();- REGISTRY.get_or_init(|| Arc::new(Mutex::new(CounterRegistry::new())))-}--thread_local! {- // Includes parsing and value lifetime operations outside a document's style update.- static COUNTER_CONTEXT: OnceCell<BridgeCounterContext> = const { OnceCell::new() };-}-+static COUNTS: [AtomicU64; FFI_OP_COUNT] = [const { AtomicU64::new(0) }; FFI_OP_COUNT];static COUNTERS_ENABLED: AtomicBool = AtomicBool::new(false);#[cfg(test)]thread_local! {@@ -189,16 +101,7 @@ unsafe extern "C" {#[inline]pub(crate) fn bump(op: FfiOp) {if COUNTERS_ENABLED.load(Ordering::Relaxed) {- let counted = COUNTER_CONTEXT.try_with(|context| {- context- .get_or_init(|| BridgeCounterContext::new(counter_registry().clone()))- .counters- .bump(op);- });- // Another thread-local owner's destructor may count after this context exited.- if counted.is_err() {- BridgeCounterContext::new(counter_registry().clone()).counters.bump(op);- }+ COUNTS[op as usize].fetch_add(1, Ordering::Relaxed);}}@@ -298,13 +201,15 @@ pub extern "C" fn rust_style_ffi_counter_name(index: usize) -> *const u8 {/// Returns the current value of the counter at `index`.#[unsafe(no_mangle)]pub extern "C" fn rust_style_ffi_counter_value(index: usize) -> u64 {- counter_registry().lock().unwrap().value(index)+ COUNTS[index].load(Ordering::Relaxed)}/// Resets every counter to zero.#[unsafe(no_mangle)]pub extern "C" fn rust_style_ffi_counters_reset() {- counter_registry().lock().unwrap().reset();+ for count in &COUNTS {+ count.store(0, Ordering::Relaxed);+ }COUNTERS_ENABLED.store(true, Ordering::Relaxed);}@@ -322,75 +227,3 @@ pub(crate) fn note_animation_evaluation() {pub(crate) fn note_transition_decision() {bump(FfiOp::TransitionDecisionEntry);}--#[cfg(test)]-mod counter_context_tests {- use super::*;-- #[test]- fn observation_includes_live_and_completed_bridge_contexts() {- let registry = Arc::new(Mutex::new(CounterRegistry::new()));- let context = BridgeCounterContext::new(registry.clone());- context.counters.bump(FfiOp::LonghandTableCopiedSlots);- let (ready, ready_rx) = std::sync::mpsc::channel();- let (finish, finish_rx) = std::sync::mpsc::channel();- let other_registry = registry.clone();- let other = std::thread::spawn(move || {- let context = BridgeCounterContext::new(other_registry);- context.counters.bump(FfiOp::LonghandTableCopiedSlots);- context.counters.bump(FfiOp::StyleValueCreateEntry);- ready.send(()).unwrap();- finish_rx.recv().unwrap();- });- ready_rx.recv().unwrap();- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 2- );- assert_eq!(registry.lock().unwrap().value(FfiOp::StyleValueCreateEntry as usize), 1);- finish.send(()).unwrap();- other.join().unwrap();- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 2- );- assert_eq!(registry.lock().unwrap().value(FfiOp::StyleValueCreateEntry as usize), 1);- drop(context);- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 2- );- }-- #[test]- fn reset_clears_completed_counts_and_contexts_continue_counting() {- let registry = Arc::new(Mutex::new(CounterRegistry::new()));- let context = BridgeCounterContext::new(registry.clone());- context.counters.bump(FfiOp::LonghandTableCopiedSlots);- let completed = BridgeCounterContext::new(registry.clone());- completed.counters.bump(FfiOp::LonghandTableCopiedSlots);- drop(completed);- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 2- );- registry.lock().unwrap().reset();- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 0- );- context.counters.bump(FfiOp::LonghandTableCopiedSlots);- let later = BridgeCounterContext::new(registry.clone());- later.counters.bump(FfiOp::LonghandTableCopiedSlots);- drop(later);- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 2- );- drop(context);- assert_eq!(- registry.lock().unwrap().value(FfiOp::LonghandTableCopiedSlots as usize),- 2- );- }-}diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex ab4d4771209..d011f8aa9f4 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -90,9 +90,8 @@ RENDER_STATE_ALLOWED = {["css/ffi_stats.rs:COMPLETE_STYLE_UPDATE_STATE","css/ffi_stats.rs:COUNTERS_ENABLED",- "css/ffi_stats.rs:COUNTER_CONTEXT",+ "css/ffi_stats.rs:COUNTS","css/ffi_stats.rs:CPP_CALLBACK_COUNT",- "css/ffi_stats.rs:REGISTRY","css/ffi_stats.rs:THREAD_UNSAFE_CPP_CALLBACK_COUNT",],),diff --git a/Meta/StyleUpdateCapture/README.md b/Meta/StyleUpdateCapture/README.mdindex f5a15365f1d..78852068769 100644--- a/Meta/StyleUpdateCapture/README.md+++ b/Meta/StyleUpdateCapture/README.md@@ -31,10 +31,8 @@ Alongside the clocks, the same ledgers carry the physical-work counters: how mananswer pass reached, how many cold matching rows and candidate checks ran, how many recorddrives started, how many longhand evaluations were physically executed as opposed toaccepted, and how many drive table slots were copied. A drive that borrows its base copies no-slots, so that last field reads zero; the copies a published result still makes are counted-by the FFI diagnostics counters `longhandTableCopiedSlots` and `longhandTableCopyRetains`.-These are counts of work performed, not of output kept, and they do not depend on how fast-the machine is.+slots, so that last field reads zero. These are counts of work performed, not of output kept,+and they do not depend on how fast the machine is.`internals.styleCounters()` lists the counters, and `StyleCounter` in `css/style/pipeline/counters.rs` describes each.