Derived: a value kept per component id and rebuilt only when its key changes

`runtime::derived::derived(ctx, id, &key, build)` (and `BodyCx::derived`) keeps one
value per id and value type. The key is `MemoProps`, so it holds only checked inputs.
A value no pass asks for is dropped by the memo rule for absent entries, which moves
into one helper both stores call. `testing::last_pass_derived_builds` counts builds.

Part of #2336.
This commit is contained in:
aiongg
2026-11-20 18:16:52 +00:00
parent e94e82dc8c
commit ea48749d34
10 changed files with 205 additions and 11 deletions
@@ -203,6 +203,12 @@ impl<'a> BodyCx<'a> {
}
impl BodyCx<'_> {
/// The value this body derives from `key`: kept while `key` is unchanged, else built by `build`
/// ([`runtime::derived`](crate::runtime::derived::derived), under the body's id).
pub fn derived<K: crate::contract::MemoProps, V: Send + Sync + 'static>(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc<V> {
crate::runtime::derived::derived(self.memory.ctx(), self.id, key, build)
}
/// Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it
/// is empty. `true` once per Escape; the enclosing scope (a dialog, a popover) then does not act on it.
/// Components shown earlier in the body have run by the time the body asks.
+75
View File
@@ -0,0 +1,75 @@
//! Derived values: data a component computes from its inputs and keeps across passes. [`derived`] keeps one value per
//! component id and value type, and builds it again only when its key changes. The key implements
//! [`MemoProps`](crate::contract::MemoProps), so it can only be made of checked inputs (`Tracked` revisions, framework
//! revisions, plain values), and a kept value is never stale while the key compiles.
//!
//! A value no pass asks for is dropped by the rule memoized views follow for absent entries (`lazy::absent_past_room`).
use crate::contract::{MemoKey, MemoProps};
use crate::runtime::egui::pass;
use crate::runtime::frame::PerViewport;
use egui::{Context, Id, IdMap};
use std::any::{Any, TypeId};
use std::sync::Arc;
/// A kept value: the key it was built from and the frame a pass last asked for it.
struct Entry {
key: u128,
value: Arc<dyn Any + Send + Sync>,
touched: u64,
}
/// The kept values of one viewport.
#[derive(Default)]
pub(crate) struct Store {
entries: IdMap<Entry>,
/// The frame the entries were last pruned in.
pruned: u64,
}
impl Store {
/// Drops the absent entries past the memo rule's room, once per frame. An entry asked for in this frame or the one
/// before is shown.
fn prune(&mut self, frame: u64) {
if self.pruned == frame {
return;
}
self.pruned = frame;
let shown = self.entries.values().filter(|entry| entry.touched + 1 >= frame).count();
let absent = self.entries.iter().filter(|(_, entry)| entry.touched + 1 < frame).map(|(id, entry)| (entry.touched, *id));
for id in super::lazy::absent_past_room(shown, absent) {
self.entries.remove(&id);
}
}
}
/// The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else
/// `build`'s, which is kept in its place. One value is kept per id and value type `V`; a component that derives two
/// values of one type gives each its own id.
pub fn derived<K: MemoProps, V: Send + Sync + 'static>(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc<V> {
let mut memo = MemoKey::of_view(ctx);
memo.feed_hash(&K::identity());
key.key(&mut memo);
#[cfg(feature = "testing")]
crate::runtime::measure::count_memo_key_bytes(ctx, memo.bytes());
let key = memo.finish();
let slot = id.with(TypeId::of::<V>());
let viewport = pass::current_viewport(ctx);
let frame = pass::frame_nr(ctx, viewport);
let kept = PerViewport::<Store>::with(ctx, viewport, |store| {
store.prune(frame);
let entry = store.entries.get_mut(&slot).filter(|entry| entry.key == key)?;
entry.touched = frame;
Arc::clone(&entry.value).downcast::<V>().ok()
});
if let Some(value) = kept {
return value;
}
#[cfg(feature = "testing")]
crate::runtime::measure::count_derived(ctx, id);
// Built outside the store, so a build may derive values of its own.
let value = Arc::new(build());
let entry = Entry { key, value: Arc::clone(&value) as Arc<dyn Any + Send + Sync>, touched: frame };
PerViewport::<Store>::with(ctx, viewport, |store| store.entries.insert(slot, entry));
value
}
@@ -1270,6 +1270,7 @@ pub(crate) mod guard {
"runtime::lazy::Store",
"lazy extents: the kept extent of content out of view, its own mechanism; a pass a kept transcript serves decides in its real run, which compares each row by its backstop",
),
("runtime::derived::Store", "derived values: a pure function of their key, so a value a measuring run builds is the one a real run builds"),
("contract::steps::scroll_owner::", "scroll reveals and moves: read; taken through take_queued"),
("contract::body::scroll::Jumps", "scroll jumps: taken through take_queued"),
("runtime::edit::CancelAll", "edit cancels: read; a measuring run ends nothing"),
+19 -9
View File
@@ -335,6 +335,20 @@ impl Store {
}
}
/// The memo rule for absent entries, shared by every memo store (memoized views, `runtime::derived`): an entry
/// outlives its absence while the absent ones are at most twice as many as the shown ones, the longest absent dropped
/// first. Takes the absent entries as (frame last touched, id) and returns the ones to drop.
pub(crate) fn absent_past_room(shown: usize, absent: impl IntoIterator<Item = (u64, Id)>) -> Vec<Id> {
let mut absent: Vec<(u64, Id)> = absent.into_iter().collect();
let room = 2 * shown;
if absent.len() <= room {
return Vec::new();
}
absent.sort_unstable_by_key(|(touched, _)| *touched);
absent.truncate(absent.len() - room);
absent.into_iter().map(|(_, id)| id).collect()
}
fn with<R>(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
let viewport = pass::current_viewport(ctx);
let (pass_nr, frame) = (pass::pass_nr(ctx, viewport), pass::frame_nr(ctx, viewport));
@@ -345,16 +359,12 @@ fn with<R>(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R {
store.pruned = frame;
let reached = &store.reached;
store.entries.retain(|_, entry| entry.memo() || entry.live(frame, reached));
// A memoized view's entry outlives its absence while the absent ones are at most twice as many as the shown
// ones, the longest absent dropped first: a view shown again with the same props replays.
// A memoized view's entry outlives its absence by the memo rule: a view shown again with the same props
// replays.
let shown = store.entries.values().filter(|entry| entry.memo() && entry.live(frame, reached)).count();
let mut absent: Vec<(u64, Id)> =
store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)).collect();
if absent.len() > 2 * shown {
absent.sort_unstable_by_key(|(touched, _)| *touched);
for (_, id) in &absent[..absent.len() - 2 * shown] {
store.entries.remove(id);
}
let absent = store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id));
for id in absent_past_room(shown, absent) {
store.entries.remove(&id);
}
let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect();
store.reached.retain(|owner, _| owners.contains(owner));
+34
View File
@@ -52,6 +52,14 @@ struct BodyRuns {
runs: Vec<(Id, u32)>,
}
/// The derived values built in a pass, by component id, with the pass that counted them.
#[cfg(feature = "testing")]
#[derive(Default)]
pub(crate) struct DerivedBuilds {
pass: u64,
builds: Vec<(Id, u32)>,
}
/// How many contributions the measuring runs of a pass made that stand, with the pass that counted them.
#[cfg(feature = "testing")]
#[derive(Default)]
@@ -540,6 +548,32 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize {
last_totals(ctx, |log| log.key_bytes, 0)
}
/// Counts a build of a derived value of the component `id` in this pass (`runtime::derived`).
#[cfg(feature = "testing")]
pub(crate) fn count_derived(ctx: &Context, id: Id) {
if uncounted(ctx) {
return;
}
let pass = ctx.cumulative_pass_nr();
pass_state::with::<DerivedBuilds, _>(ctx, |log| {
if log.pass != pass {
*log = DerivedBuilds { pass, builds: Vec::new() };
}
match log.builds.iter_mut().find(|(of, _)| *of == id) {
Some((_, count)) => *count += 1,
None => log.builds.push((id, 1)),
}
});
}
/// The components that built a derived value in the last pass, and how many builds each; empty when that pass built
/// none.
#[cfg(feature = "testing")]
pub fn last_pass_derived_builds(ctx: &Context) -> Vec<(Id, u32)> {
let last = ctx.cumulative_pass_nr().saturating_sub(1);
pass_state::with::<DerivedBuilds, _>(ctx, |log| if log.pass == last { log.builds.clone() } else { Vec::new() })
}
/// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass.
#[cfg(feature = "testing")]
pub(crate) fn count_text_layout(ctx: &Context) {
+1
View File
@@ -5,6 +5,7 @@ pub mod access;
pub(crate) mod audit;
pub mod commands;
pub mod cursor;
pub mod derived;
pub mod drag;
pub mod edit;
pub mod egui;
@@ -119,6 +119,8 @@ pass_state! {
memo_log: crate::runtime::measure::MemoLog,
#[cfg(feature = "testing")]
pass_totals: crate::runtime::measure::PassTotals,
#[cfg(feature = "testing")]
derived_builds: crate::runtime::measure::DerivedBuilds,
}
records {
focus: crate::runtime::focus::State,
@@ -126,6 +128,7 @@ pass_state! {
cursor: crate::runtime::cursor::State,
layout: crate::runtime::layout_memory::Entries,
lazy: crate::runtime::lazy::Store,
derived: crate::runtime::derived::Store,
arenas: crate::primitives::sensing::Arenas,
envs: crate::runtime::env::ViewportEnvs,
pointer: crate::runtime::pointer::Memory,
+3 -2
View File
@@ -46,8 +46,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements;
pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves;
pub use crate::runtime::measure::{
MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs,
last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs,
last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs,
last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs,
last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects,
widest_runs,
};
pub use craft_ui_macros::{story, trial};
pub use fixture::{Fixture, Impure, Room, Target};
@@ -0,0 +1,62 @@
//! Derived values: built once per key, kept while the key is unchanged, and dropped by the memo rule once absent.
use craft_ui::runtime::derived::derived;
use craft_ui::testing::{Fixture, last_pass_derived_builds, trial};
use egui::Id;
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
/// A fixture whose pass derives a value under each id `ids` holds, keyed by `key`; `seen` collects the values.
fn deriving(ids: Rc<RefCell<Vec<u32>>>, key: Rc<Cell<u32>>, seen: Rc<RefCell<Vec<Arc<String>>>>) -> Fixture {
Fixture::new(move |ui| {
seen.borrow_mut().clear();
for id in ids.borrow().iter() {
let value = derived(ui.ctx(), Id::NULL.with(("derived", *id)), &key.get(), || format!("{id} at {}", key.get()));
seen.borrow_mut().push(value);
}
})
}
/// The number of builds in the last pass.
fn builds(fixture: &Fixture) -> u32 {
last_pass_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum()
}
/// An unchanged key returns the kept value without a build; a changed key builds once, then keeps that.
#[trial]
fn a_derived_value_builds_once_per_key() {
let (ids, key, seen) = (Rc::new(RefCell::new(vec![1])), Rc::new(Cell::new(7)), Rc::default());
let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen));
fixture.frame(Vec::new());
let first = Arc::clone(&seen.borrow()[0]);
for _ in 0..3 {
fixture.frame(Vec::new());
assert_eq!(builds(&fixture), 0, "an unchanged key builds nothing");
assert!(Arc::ptr_eq(&seen.borrow()[0], &first), "and returns the kept value");
}
key.set(8);
fixture.frame(Vec::new());
assert_eq!(builds(&fixture), 1, "a changed key builds once");
assert_eq!(*seen.borrow()[0], "1 at 8");
fixture.frame(Vec::new());
assert_eq!(builds(&fixture), 0, "then keeps the new value");
}
/// A value no pass asks for is kept while the absent ones are at most twice the shown ones, and dropped past that.
#[trial]
fn an_absent_derived_value_is_dropped_by_the_memo_rule() {
let (ids, key, seen) = (Rc::new(RefCell::new(vec![1, 2, 3])), Rc::new(Cell::new(0)), Rc::default());
let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen));
fixture.frame(Vec::new()).frame(Vec::new());
*ids.borrow_mut() = vec![1];
fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new());
*ids.borrow_mut() = vec![1, 2, 3];
fixture.frame(Vec::new());
assert_eq!(builds(&fixture), 0, "two absent values beside one shown are kept");
*ids.borrow_mut() = Vec::new();
fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new());
*ids.borrow_mut() = vec![1];
fixture.frame(Vec::new());
assert_eq!(builds(&fixture), 1, "with none shown, every absent value was dropped");
}
@@ -4,6 +4,7 @@ mod chord_fallthrough;
mod clipboard;
mod control_click;
mod cursor;
mod derived;
mod elapsed;
mod env;
mod frame;