diff --git a/crates/doc/src/entity/block.rs b/crates/doc/src/entity/block.rs index 9d41548ea..652e2fb2e 100644 --- a/crates/doc/src/entity/block.rs +++ b/crates/doc/src/entity/block.rs @@ -154,7 +154,43 @@ impl AttribProps { #[derive(Clone, Copy, Debug)] pub struct TagKey<'a>(pub &'a str); +#[cfg(test)] +std::thread_local! { + static TAG_CROSS_PROBE: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn record_tag_cross_probe(left: &str, right: &str) { + TAG_CROSS_PROBE.with(|probe| { + let Some((position, mut counts)) = probe.get() else { return }; + match (left.as_bytes().get(position), right.as_bytes().get(position)) { + (Some(b'A'), Some(b'D')) => counts[0] += 1, + (Some(b'D'), Some(b'A')) => counts[1] += 1, + _ => return, + } + probe.set(Some((position, counts))); + }); +} + impl TagKey<'_> { + /// Count comparisons in both directions between the A and D fixture tag sets. + #[cfg(test)] + pub(crate) fn with_cross_probes(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) { + struct Restore(Option<(usize, [usize; 2])>); + + impl Drop for Restore { + fn drop(&mut self) { + TAG_CROSS_PROBE.with(|probe| probe.set(self.0)); + } + } + + TAG_CROSS_PROBE.with(|probe| { + let _restore = Restore(probe.replace(Some((position, [0; 2])))); + let value = f(); + (value, probe.get().map_or([0; 2], |(_, counts)| counts)) + }) + } + /// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case` /// finds equal. fn folded(&self) -> impl Iterator + '_ { @@ -164,6 +200,8 @@ impl TagKey<'_> { impl PartialEq for TagKey<'_> { fn eq(&self, other: &Self) -> bool { + #[cfg(test)] + record_tag_cross_probe(self.0, other.0); self.0.eq_ignore_ascii_case(other.0) } } @@ -172,6 +210,8 @@ impl Eq for TagKey<'_> {} impl Ord for TagKey<'_> { fn cmp(&self, other: &Self) -> Ordering { + #[cfg(test)] + record_tag_cross_probe(self.0, other.0); self.folded().cmp(other.folded()) } } diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index f04c86b00..550059aa2 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -1076,9 +1076,13 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() { let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") }; ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect(); d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); - let t = std::time::Instant::now(); - assert!(!d.extents(&Space::Model).is_empty()); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); + let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model)); + assert!(!bounds.is_empty()); + // Layer inheritance and the constant-value filter each query the opposite set. + // With no matches, an unindexed scan bypasses the probe (zero) or compares every pair. + for probes in cross_probes { + assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}"); + } } /// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N diff --git a/crates/engine/src/cmd/blocks/attribs.rs b/crates/engine/src/cmd/blocks/attribs.rs index b6d6b2d24..ac7cf7868 100644 --- a/crates/engine/src/cmd/blocks/attribs.rs +++ b/crates/engine/src/cmd/blocks/attribs.rs @@ -104,12 +104,17 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec let m = ins.transform(blk.base.xy()); // The reference's attributes by tag, gathered once for all the definitions (#1923). let carried = ins.attribs_by_tag(); + #[cfg(test)] + let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::>(); defs.iter() .map(|ad| { let mut k = EntityKind::Text(ad.text.clone()); k.transform(&m); let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() }; - t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone()); + let key = TagKey(&ad.tag); + #[cfg(test)] + let key = tests::MeasuredTag(key); + t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone()); Attrib { tag: ad.tag.clone(), text: t, @@ -359,6 +364,74 @@ impl Interactive for AttsyncM { mod tests { use super::*; + std::thread_local! { + static SYNC_CROSS_PROBES: std::cell::Cell> = const { std::cell::Cell::new(None) }; + } + + /// Use the actual tag ordering and count only probes between different fixture sets. + pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>); + + impl MeasuredTag<'_> { + fn record(&self, other: &Self) { + let TagKey(left) = self.0; + let TagKey(right) = other.0; + let sides = (left.as_bytes().first(), right.as_bytes().first()); + if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) { + SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1))); + } + } + } + + impl PartialEq for MeasuredTag<'_> { + fn eq(&self, other: &Self) -> bool { + self.record(other); + self.0 == other.0 + } + } + + impl Eq for MeasuredTag<'_> {} + + impl PartialOrd for MeasuredTag<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + + impl Ord for MeasuredTag<'_> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.record(other); + self.0.cmp(&other.0) + } + } + + #[test] + fn sync_uses_indexed_cross_set_tag_matching() { + const N: usize = 512; + let mut s = Session::new(); + s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap(); + s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap(); + let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap(); + let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap(); + let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap(); + let doc = s.doc().unwrap(); + let blk = doc.block("B").unwrap(); + let base = (*attdefs(blk)[0]).clone(); + let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") }; + let value = ins.attribs[0].clone(); + let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect(); + let defs: Vec<_> = defs.iter().collect(); + ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect(); + + SYNC_CROSS_PROBES.with(|count| count.set(Some(0))); + let result = synced(blk, &defs, &ins); + let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap()); + assert_eq!(result.len(), N); + assert!(result.iter().all(|a| a.text.value == "d")); + // No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N. + assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}"); + } + #[test] fn attdisp_keywords_map_to_attmode() { assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]); diff --git a/crates/engine/tests/it/attribute_tag_matching.rs b/crates/engine/tests/it/attribute_tag_matching.rs index f06cfd2b4..5e69c4a99 100644 --- a/crates/engine/tests/it/attribute_tag_matching.rs +++ b/crates/engine/tests/it/attribute_tag_matching.rs @@ -65,9 +65,9 @@ fn burst_matches_many_attributes_without_comparing_every_pair() { #[test] fn attsync_matches_many_definitions_without_comparing_every_pair() { let (mut s, h) = reference(N); - let t = std::time::Instant::now(); + // The adjacent engine unit test checks exact indexed lookup work; this keeps + // the same end-to-end ATTSYNC fixture and its result checks. s.execute("attsync", &json!({"name": "B"})).unwrap(); - assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed()); // An attribute for each definition (T and the N others), with its default value: the // reference carried none of their tags. let a = attribs(&s, h);