Cache source measurements and propagate native viewport inputs
Verify Tessera GUI / verify (push) Failing after 7m29s

This commit is contained in:
2026-10-21 16:33:35 +08:00
parent 1b5fe1069f
commit 3ea4bac48c
12 changed files with 744 additions and 37 deletions
+183 -18
View File
@@ -14,13 +14,55 @@ use endor_core::{
NativeContext, NativeResult, ObjectRef, Opcode, Value, Vm, VmError, WeakObjectRef,
};
use std::{
collections::{BTreeSet, HashMap},
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
sync::{Arc, Mutex},
};
fn invalid(message: &'static str) -> VmError {
VmError::InvalidArgument(message)
}
fn desktop_type_registry(cx: &NativeContext<'_>, desktop: ObjectRef) -> Result<ObjectRef, VmError> {
match cx.store().get_attr(desktop, "types")? {
Value::Object(object) => Ok(object),
_ => Err(invalid("missing type registry")),
}
}
#[derive(Debug, Clone)]
struct Measurement {
owner: ObjectRef,
method: ObjectRef,
children: Vec<Size>,
constraints: [f32; 4],
size: Size,
reads: BTreeMap<ObjectRef, u64>,
}
/// Borrowed identities and versions only: this cache adds no managed roots.
#[derive(Debug, Default, Clone)]
pub struct Cache {
entries: HashMap<WeakObjectRef, Measurement>,
pub hits: usize,
pub misses: usize,
}
impl Cache {
pub fn invalidate(&mut self, owners: &HashSet<ObjectRef>) {
self.entries
.retain(|_, entry| !owners.contains(&entry.owner));
}
pub fn clear(&mut self) {
self.entries.clear();
self.hits = 0;
self.misses = 0;
}
}
#[derive(Debug)]
struct Pending {
token: usize,
owner: ObjectRef,
method: ObjectRef,
children: Vec<Size>,
constraints: [f32; 4],
key: WeakObjectRef,
}
#[derive(Debug)]
struct Plan {
nodes: Vec<Arc<UiNode>>,
@@ -29,6 +71,9 @@ struct Plan {
bounds: Vec<Option<[f32; 4]>>,
runtime: LayoutRuntime,
custom: bool,
cache: Cache,
pending: Vec<Option<Pending>>,
constraints: Vec<[f32; 4]>,
}
type Shared = Arc<Mutex<Plan>>;
#[derive(Debug, Clone, Copy)]
@@ -92,9 +137,41 @@ impl NativeCallable for Step {
plan.custom = true;
}
if matches!(self.phase, Phase::Measure) {
plan.runtime.measured += 1;
let key = cx.store().downgrade(self.mount)?;
let constraints = plan.constraints[self.index];
let cached = plan
.cache
.entries
.get(&key)
.filter(|entry| {
entry.owner == mount.block
&& entry.method == method
&& entry.children == children
&& entry.constraints == constraints
&& entry.reads.iter().all(|(object, version)| {
cx.store().change_version(*object).ok() == Some(*version)
})
})
.map(|entry| entry.size);
if let Some(size) = cached {
plan.cache.hits += 1;
Some(size)
} else {
plan.cache.misses += 1;
plan.runtime.measured += 1;
plan.pending[self.index] = Some(Pending {
token: 0,
owner: mount.block,
method,
children: children.clone(),
constraints,
key,
});
None
}
} else {
None
}
None
};
if matches!(self.phase, Phase::Arrange) {
plan.runtime.arranged += 1;
@@ -119,17 +196,24 @@ impl NativeCallable for Step {
)?)));
}
let input = match self.phase {
Phase::Measure => record(
cx,
self.desktop,
"Constraints",
vec![
("minWidth", value(0.0)),
("minHeight", value(0.0)),
("maxWidth", value(MAX_DIMENSION as f32)),
("maxHeight", value(MAX_DIMENSION as f32)),
],
)?,
Phase::Measure => {
let constraints = self
.plan
.lock()
.map_err(|_| invalid("layout plan poisoned"))?
.constraints[self.index];
record(
cx,
self.desktop,
"Constraints",
vec![
("minWidth", value(constraints[0])),
("minHeight", value(constraints[1])),
("maxWidth", value(constraints[2])),
("maxHeight", value(constraints[3])),
],
)?
}
Phase::Arrange => {
let [x, y, width, height] =
bounds.ok_or(invalid("arrangement has no allocated bounds"))?;
@@ -146,6 +230,16 @@ impl NativeCallable for Step {
)?
}
};
if matches!(self.phase, Phase::Measure) {
let token = cx.store().begin_read_tracking()?;
self.plan
.lock()
.map_err(|_| invalid("layout plan poisoned"))?
.pending[self.index]
.as_mut()
.ok_or(invalid("missing measurement tracking state"))?
.token = token;
}
Ok(NativeResult::Invoke {
function: method,
arguments: vec![
@@ -165,6 +259,15 @@ struct Collect {
}
impl NativeCallable for Collect {
fn invoke(&self, cx: &mut NativeContext<'_>, args: &[Value]) -> Result<NativeResult, VmError> {
let pending = if matches!(self.phase, Phase::Measure) {
self.plan
.lock()
.map_err(|_| invalid("layout plan poisoned"))?
.pending[self.index]
.take()
} else {
None
};
let [Value::Object(result)] = args else {
return Err(invalid("layout must return a managed result"));
};
@@ -184,10 +287,54 @@ impl NativeCallable for Collect {
.map_err(|_| invalid("layout plan poisoned"))?;
match self.phase {
Phase::Measure => {
let size = Size {
width: number(cx, *result, "width", false)?,
height: number(cx, *result, "height", false)?,
};
let size = layout::constrained(
Size {
width: number(cx, *result, "width", false)?,
height: number(cx, *result, "height", false)?,
},
plan.constraints[self.index],
);
// Decoding is part of the subcall dependency region: a source
// method may return an existing result whose fields can change.
let tracked = pending
.map(|pending| {
cx.store()
.end_read_tracking(pending.token)
.map(|reads| (pending, reads))
})
.transpose()?;
if let Some((pending, reads)) = tracked {
let mut versions = BTreeMap::new();
let mut volatile = false;
let registry = desktop_type_registry(cx, self.desktop)?;
for object in reads {
if object == self.desktop || object == registry {
continue;
}
// A Mount's layoutVersion/geometry may be observed by
// source. Object-granular tracking cannot prove those
// accesses stable, so conservatively bypass its cache.
if cx.store().object(object)?.payload().as_any().is::<Mount>() {
volatile = true;
}
versions.insert(object, cx.store().change_version(object)?);
}
if volatile {
plan.cache.entries.remove(&pending.key);
} else {
plan.cache.entries.insert(
pending.key,
Measurement {
owner: pending.owner,
method: pending.method,
children: pending.children,
constraints: pending.constraints,
size,
reads: versions,
},
);
}
}
plan.sizes[self.index] = size;
if self.index == 0 {
plan.bounds[0] = Some([0.0, 0.0, size.width, size.height]);
@@ -327,7 +474,12 @@ pub fn render(
root: Arc<UiNode>,
frame: &mut Frame,
runtime: &mut LayoutRuntime,
cache: &mut Cache,
) -> Result<BTreeSet<ObjectRef>> {
cache.hits = 0;
cache.misses = 0;
let live: HashSet<_> = mounts.iter().copied().collect();
cache.entries.retain(|mount, _| live.contains(mount));
// Preserve the existing native measurement cache and avoid VM/result
// allocation for trees without custom layout methods. Contexts already exist.
let block_type = desktop_type(vm.object_store(), "Block", desktop)?;
@@ -353,6 +505,7 @@ pub fn render(
custom |= result?;
}
if !custom {
cache.clear();
let mut native = runtime.frame(&root)?;
// Only the structural pass consumes a published version.
native.layout_version = frame.layout_version;
@@ -382,6 +535,14 @@ pub fn render(
children[indices[&parent]].push(index);
}
}
let mut constraints = vec![layout::root_constraints(runtime.viewport); nodes.len()];
for index in 0..nodes.len() {
let next = layout::child_constraints(&nodes[index], constraints[index]);
for child in &children[index] {
constraints[*child] = next;
}
}
let count = nodes.len();
let plan = Arc::new(Mutex::new(Plan {
sizes: vec![Size::default(); nodes.len()],
bounds: vec![None; nodes.len()],
@@ -389,6 +550,9 @@ pub fn render(
children,
runtime: runtime.clone(),
custom: false,
cache: cache.clone(),
pending: (0..count).map(|_| None).collect(),
constraints,
}));
let prepare = vm.allocate(ContextNativeFunction::new(
"prepare source layout",
@@ -429,6 +593,7 @@ pub fn render(
}
}
*runtime = plan.runtime.clone();
*cache = plan.cache.clone();
if !plan.custom {
return Ok(BTreeSet::new());
}