diff --git a/.agents/reports/reactive-signals.md b/.agents/reports/reactive-signals.md index b1522633..39dd1101 100644 --- a/.agents/reports/reactive-signals.md +++ b/.agents/reports/reactive-signals.md @@ -481,3 +481,80 @@ check of a single-row update took 28.0 ms with caching and 61.4 ms without it. Disabling caching suits rows that normally all change together. The matched uncached Rake and GPUI cases still differ by 31% at p50, so the approximately 10% target remains open. The measurements cover headless CPU work. + +## Retained component handles (2026-11-29) + +This experiment keeps the signal runtime unchanged and tests the upper bound of +avoiding the per-redraw keyed-state lookup and unchanged-prop comparison. The +benchmark-only `Retained` variant mounts an equivalent generated function +component once, captures its view as a weak handle during setup, and then lets +the host row own a strong `AnyView`. Subsequent parent redraws reuse that handle +instead of reaching the mounted component through GPUI keyed element state. Props are +unchanged in this workload, so skipping the comparison does not change the +rendered tree. Signal storage, dependency tracking, signal observers, row +contents, caching policy, and write behavior are unchanged. + +The measurements used an Apple M1 Max with 32 GB RAM, macOS 27.2.1 (26B131), +Rust 1.98.0 (`88d9e12ae`), and gpui-pre 0.3.11. The optimized benchmark binary +ran headlessly with 10,000 rows and one signal per row. Every row signal was +incremented in one application update, followed by an explicit parent redraw in +the next application update. Each phase measured process CPU time for 31 samples +after five warmups. Six repetitions rotated the variant order +(`plain signals retained`, `signals retained plain`, `retained plain signals`, +twice). The tables report the median of each repetition's percentile. Every +repetition asserted one host render in both phases, the displayed value of all +10,000 updated rows, stale-write failure after unmount, and zero Rake component, +signal, observer, subscription, and task counts after disposal. + +Commands, once per variant and repetition: + +```sh +cargo bench -p rake-app --locked --features experimental-reactive,view-test-support --bench function_components -- --headless plain bulk-redraw 10000 1 +cargo bench -p rake-app --locked --features experimental-reactive,view-test-support --bench function_components -- --headless signals bulk-redraw 10000 1 +cargo bench -p rake-app --locked --features experimental-reactive,view-test-support --bench function_components -- --headless retained bulk-redraw 10000 1 +``` + +Bulk update, uncached: + +| Implementation | p50 CPU time | p95 CPU time | Allocations per update | +| --- | ---: | ---: | ---: | +| Plain GPUI | 46.54 ms | 51.20 ms | 130,052 | +| Stock Rake function components | 64.31 ms | 66.74 ms | 140,052 | +| Retained component handles | 56.68 ms | 59.78 ms | 130,052 | + +Following parent redraw, uncached: + +| Implementation | p50 CPU time | p95 CPU time | Allocations per redraw | +| --- | ---: | ---: | ---: | +| Plain GPUI | 48.55 ms | 53.52 ms | 130,044 | +| Stock Rake function components | 55.23 ms | 57.95 ms | 140,044 | +| Retained component handles | 49.64 ms | 56.07 ms | 130,044 | + +Against plain GPUI, stock Rake was 38.2% slower at bulk p50 and 30.4% slower at +bulk p95. The retained-handle variant reduced that gap to 21.8% at p50 and +16.8% at p95. For the following parent redraw, stock Rake was 13.8% slower at +p50 and 8.3% slower at p95, while retained handles were 2.2% +slower at p50 and 4.8% slower at p95. Retaining handles removed exactly one +allocation per row in both phases and reduced stock bulk p50 by 11.9% and stock +parent-redraw p50 by 10.1%. Individual repetitions were noisy; for example, +stock bulk p50 ranged from 61.60 ms to 76.14 ms while retained bulk p50 ranged +from 55.47 ms to 65.13 ms. The allocation counts were exact in every +repetition. + +The result isolates a real keyed lookup/prop comparison cost: the parent redraw +with retained handles is within the approximately 10% target and its allocation +count matches plain GPUI. The matched bulk workload still misses the target by +a wide margin, because signal writes, dependency notification, and the actual +row renders dominate that phase. Reusing handles is therefore not sufficient +for the #27 performance gate. + +No runtime change is adopted. The benchmark pattern moves component lifetime +from GPUI's keyed element-state sweep into explicit host-row ownership. That is +valid in this controlled host because dropping a row drops its strong view +handle, but the generated component runtime cannot generally bypass keyed +element-state access under the unchanged GPUI version without changing removal +semantics or requiring a new parent-owned handle contract. Since the runtime +was not changed, the adoption-gate tests for changed props, keyed reorder and +removal, and invalidation through cached ancestors were not applicable. As a +smoke check, the benchmark-only variant passed the existing parent, leaf, bulk, +reorder, and cycle disposal assertions at 1,000 rows. diff --git a/crates/rake/benches/function_components.rs b/crates/rake/benches/function_components.rs index 7cd06bfe..8d2663fb 100644 --- a/crates/rake/benches/function_components.rs +++ b/crates/rake/benches/function_components.rs @@ -29,7 +29,15 @@ const RENDERER: &str = if cfg!(feature = "gpui-fast") { "gpui-pre 0.3.11" }; -const SCENARIOS: [&str; 6] = ["mount", "parent", "leaf", "all", "reorder", "cycle"]; +const SCENARIOS: [&str; 7] = [ + "mount", + "parent", + "leaf", + "all", + "bulk-redraw", + "reorder", + "cycle", +]; struct CountingAllocator; @@ -74,6 +82,7 @@ enum Variant { Plain, PlainCached, Signals, + Retained, Cached, Raw, } @@ -112,6 +121,7 @@ impl Writer { struct Probe { writer: RefCell, rendered: Cell, + retained: RefCell>, } impl PartialEq for Probe { @@ -149,6 +159,16 @@ fn SignalRow(signals: usize, probe: Rc, cx: &mut Setup) -> impl IntoEleme row(&probe, values.iter().map(|value| value.get(cx)).sum()) } +#[rake::component(cached = false)] +fn RetainedRow(signals: usize, probe: Rc, cx: &mut Setup) -> impl IntoElement { + probe + .retained + .replace(Some(gpui::AnyView::from(cx.entity()).downgrade())); + let values = create_signals(cx, signals, &probe); + + row(&probe, values.iter().map(|value| value.get(cx)).sum()) +} + #[rake::component(cached = "w-12 h-4")] fn CachedRow(signals: usize, probe: Rc, cx: &mut Setup) -> impl IntoElement { let values = create_signals(cx, signals, &probe); @@ -199,6 +219,7 @@ struct Row { id: usize, probe: Rc, plain: Option>, + retained: Option, } struct Host { @@ -225,6 +246,7 @@ impl Host { id: self.next, probe: Rc::new(Probe::default()), plain: None, + retained: None, }); self.next += 1; } @@ -254,7 +276,7 @@ impl Host { fn change_values(scenario: &str, probes: &[Rc], cx: &mut gpui::App) -> bool { let count = match scenario { "leaf" => 1, - "all" => probes.len(), + "all" | "bulk-redraw" => probes.len(), _ => return false, }; @@ -299,6 +321,26 @@ impl Render for Host { signals: self.signals, probe: item.probe.clone(), }), + Variant::Retained => { + if item.retained.is_none() { + item.retained = item + .probe + .retained + .borrow() + .as_ref() + .and_then(|view| view.upgrade()); + } + + if let Some(view) = item.retained.clone() { + parent.child(view) + } else { + parent.child(RetainedRow { + id: ("row", item.id).into(), + signals: self.signals, + probe: item.probe.clone(), + }) + } + } Variant::Cached => parent.child(CachedRow { id: ("row", item.id).into(), signals: self.signals, @@ -330,6 +372,39 @@ fn percentiles(times: &mut [f64]) -> (f64, f64) { (times[times.len() / 2], times[times.len() * 95 / 100]) } +#[cfg(unix)] +fn process_cpu_micros() -> Option { + // Safety: `usage` is a valid out pointer for `getrusage`, and the returned + // C struct is read only after successful initialization. + unsafe { + let mut usage: libc::rusage = std::mem::zeroed(); + + if libc::getrusage(libc::RUSAGE_SELF, &mut usage) != 0 { + return None; + } + + let user = usage.ru_utime.tv_sec as u64 * 1_000_000 + usage.ru_utime.tv_usec as u64; + let system = usage.ru_stime.tv_sec as u64 * 1_000_000 + usage.ru_stime.tv_usec as u64; + + Some(user + system) + } +} + +#[cfg(not(unix))] +fn process_cpu_micros() -> Option { + None +} + +fn elapsed_micros(started: Instant, cpu_started: Option) -> f64 { + if let Some(started) = cpu_started + && let Some(finished) = process_cpu_micros() + { + return (finished - started) as f64; + } + + started.elapsed().as_secs_f64() * 1e6 +} + fn measure(variant: Variant, count: usize, signals: usize, scenario: &str, samples: usize) { let mut cx = gpui::TestAppContext::single(); let window = cx.add_window(|_, _| Host::new(variant, signals)); @@ -353,27 +428,34 @@ fn measure(variant: Variant, count: usize, signals: usize, scenario: &str, sampl ) }) .unwrap(); - let updated_rows = match scenario { + let paired = scenario == "bulk-redraw"; + let update_scenario = if paired { "all" } else { scenario }; + let updated_rows = match update_scenario { "leaf" => &probes[..1], "all" => &probes[..], _ => &[], }; let mut times = Vec::with_capacity(samples); + let mut redraw_times = Vec::with_capacity(samples); let mut allocations = 0; + let mut redraw_allocations = 0; for iteration in 0..samples + 5 { let before = ALLOCATIONS.load(Ordering::Relaxed); - let start = Instant::now(); + let cpu_started = process_cpu_micros(); + let started = Instant::now(); // TestAppContext draws invalidated windows when the update flushes. - if !cx.update(|cx| change_values(scenario, &probes, cx)) { + if !cx.update(|cx| change_values(update_scenario, &probes, cx)) { window - .update(&mut cx, |host, _, cx| host.change(scenario, count, cx)) + .update(&mut cx, |host, _, cx| { + host.change(update_scenario, count, cx) + }) .unwrap(); } - let elapsed = start.elapsed().as_secs_f64() * 1e6; + let elapsed = elapsed_micros(started, cpu_started); let allocated = ALLOCATIONS.load(Ordering::Relaxed) - before; let current_renders = window.read_with(&cx, |host, _| host.renders).unwrap(); @@ -388,11 +470,40 @@ fn measure(variant: Variant, count: usize, signals: usize, scenario: &str, sampl ); } + let mut redraw_elapsed = None; + let mut redraw_allocated = 0; + + if paired { + let before = ALLOCATIONS.load(Ordering::Relaxed); + let cpu_started = process_cpu_micros(); + let started = Instant::now(); + + window + .update(&mut cx, |host, _, cx| host.change("parent", count, cx)) + .unwrap(); + + redraw_elapsed = Some(elapsed_micros(started, cpu_started)); + redraw_allocated = ALLOCATIONS.load(Ordering::Relaxed) - before; + let current_renders = window.read_with(&cx, |host, _| host.renders).unwrap(); + + assert_eq!( + current_renders, + renders + 1, + "expected one draw per parent redraw" + ); + renders = current_renders; + } + cx.run_until_parked(); if iteration >= 5 { times.push(elapsed); allocations += allocated; + + if let Some(elapsed) = redraw_elapsed { + redraw_times.push(elapsed); + redraw_allocations += redraw_allocated; + } } } @@ -417,14 +528,21 @@ fn measure(variant: Variant, count: usize, signals: usize, scenario: &str, sampl assert_eq!(runtime_stats, rake::reactive::RuntimeStats::default()); let (p50, p95) = percentiles(&mut times); + let redraw_percentiles = (!redraw_times.is_empty()).then(|| percentiles(&mut redraw_times)); println!( "{}", json!({ "renderer": RENDERER, "backend": "TestAppContext", "variant": format!("{variant:?}"), "scenario": scenario, "instances": count, "signals": signals, "samples": samples, + "time_source": if cfg!(unix) { "process-cpu" } else { "wall" }, "p50_us": p50, "p95_us": p95, + "bulk_p50_us": p50, "bulk_p95_us": p95, "allocations_per_sample": allocations as f64 / samples as f64, + "bulk_allocations_per_update": allocations as f64 / samples as f64, + "redraw_p50_us": redraw_percentiles.map(|values| values.0), + "redraw_p95_us": redraw_percentiles.map(|values| values.1), + "redraw_allocations_per_update": paired.then_some(redraw_allocations as f64 / samples as f64), "live_after_mount_bytes": after_mount, "retained_after_unmount_bytes": retained, "initial_handles_disposed": disposed, "runtime_after_unmount": runtime_stats }) @@ -507,9 +625,12 @@ fn main() { Some("plain") => Variant::Plain, Some("plain-cached") => Variant::PlainCached, Some("signals") => Variant::Signals, + Some("retained") => Variant::Retained, Some("cached") => Variant::Cached, Some("raw") => Variant::Raw, - _ => panic!("a benchmark case requires plain, plain-cached, signals, cached, or raw"), + _ => panic!( + "a benchmark case requires plain, plain-cached, signals, retained, cached, or raw" + ), }; let requested = args.get(index + 2).map(String::as_str).unwrap_or("all"); @@ -579,6 +700,7 @@ fn main() { Variant::Plain, Variant::PlainCached, Variant::Signals, + Variant::Retained, Variant::Cached, Variant::Raw, ] { @@ -592,7 +714,10 @@ fn main() { measure(variant, 100, signals, "signals", samples); } - if !matches!(variant, Variant::Cached | Variant::PlainCached) { + if !matches!( + variant, + Variant::Cached | Variant::PlainCached | Variant::Retained + ) { async_work::measure(variant, false, samples); async_work::measure(variant, true, samples); } diff --git a/crates/rake/benches/function_components/async_work.rs b/crates/rake/benches/function_components/async_work.rs index 9d3134f8..a9fbc9de 100644 --- a/crates/rake/benches/function_components/async_work.rs +++ b/crates/rake/benches/function_components/async_work.rs @@ -205,11 +205,13 @@ impl Render for Host { parent.child(self.plain[id].clone()) } - Variant::Signals | Variant::Cached => parent.child(SignalAsync { - id: ("async", id).into(), - pending: self.pending, - counters: self.counters.clone(), - }), + Variant::Signals | Variant::Retained | Variant::Cached => { + parent.child(SignalAsync { + id: ("async", id).into(), + pending: self.pending, + counters: self.counters.clone(), + }) + } Variant::Raw => parent.child(RawAsync { id, pending: self.pending,