diff --git a/Cargo.lock b/Cargo.lock index 802aca2..2bf54f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -636,6 +636,9 @@ name = "hashbrown" version = "0.17.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] [[package]] name = "hayro-ccitt" diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index 5ff201b..cd074d0 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -7,7 +7,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D [dependencies] flate2 = "1.1" -hashbrown = { version = "0.17.2", default-features = false, features = ["raw-entry"] } +hashbrown = { version = "0.17.2", default-features = false, features = ["default-hasher", "raw-entry"] } harfbuzz_rs = "=3.0.1" image = { version = "0.23.12", default-features = false, features = ["bmp"] } lopdf = "0.26" diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index a123537..04342d2 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -245,7 +245,8 @@ pub struct Executor { reads: DependencyReads, // Cache the resolved meaning alongside the last read epoch. A shard's // revision is only valid on this executor's state history. - meaning_reads: HashMap, + // Keep the read epoch on each executor, while snapshots share cache keys. + meaning_reads: HashMap, (u64, Meaning, u32), RandomState>, reads_tracing_macros: bool, conditionals: Vec, in_csname: bool, @@ -854,12 +855,12 @@ impl Executor { } fn dependency_observations(&self) -> impl Iterator + '_ { self.reads.observations().chain(self.meaning_reads.iter() - .map(|(name, (_, _, epoch))| (Dependency::Meaning(name.clone()), *epoch))) + .map(|(name, (_, _, epoch))| (Dependency::Meaning(name.as_ref().clone()), *epoch))) } fn take_dependency_reads(&mut self) -> (BTreeSet, DependencyEvidence) { std::mem::take(&mut self.reads).into_evidence(self.meaning_reads.drain() - .map(|(name, (_, _, epoch))| (Dependency::Meaning(name), epoch))) + .map(|(name, (_, _, epoch))| (Dependency::Meaning(Arc::unwrap_or_clone(name)), epoch))) } fn meaning(&mut self, token: &Token) -> Meaning { @@ -884,7 +885,7 @@ impl Executor { } RawEntryMut::Vacant(entry) => { let meaning = self.state.meaning_hashed(name, hash); - entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone(), epoch)); + entry.insert_hashed_nocheck(hash, Arc::new(name.clone()), (revision, meaning.clone(), epoch)); meaning } } diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index ec5d827..c8c1739 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -670,8 +670,7 @@ fn splice_dependencies( if current.meaning_reads.len() != prior.meaning_reads.len() { reads.extend(current.meaning_reads.keys() .filter(|name| !prior.meaning_reads.contains_key(*name)) - .cloned() - .map(Dependency::Meaning)); + .map(|name| Dependency::Meaning(name.as_ref().clone()))); } Some((reads, DependencyEvidence::default())) } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index b18e16d..4fb788e 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -804,7 +804,9 @@ enum PdftexRevision { R24, } -const COMMAND_SHARDS: usize = 32; +// A single definition after a checkpoint copies its shard. Smaller shards +// keep that copy proportional to the modified part of the command table. +const COMMAND_SHARDS: usize = 128; type CommandEntries = HashMap, Meaning, RandomState>; #[derive(Clone, Debug)] @@ -1222,7 +1224,7 @@ fn paired_statistics_keep_aliases_from_changed_to_shared_command_shards() { let second = CommandName::Control("other-common-definition".into()); let shard = |name: &CommandName| CommandBindings::shard_index(command_hasher().hash_one(name)); let shared_shards = [shard(&first), shard(&second)]; - let edited = (0..128) + let edited = (0..COMMAND_SHARDS) .map(|index| CommandName::Control(format!("edited-alias-{index}"))) .find(|name| !shared_shards.contains(&shard(name))) .unwrap(); @@ -1248,6 +1250,83 @@ fn paired_statistics_keep_aliases_from_changed_to_shared_command_shards() { assert!(same.has_equivalent_history(&old_counts, &history, &history)); } +#[test] +fn paired_statistics_keep_aliases_within_changed_command_shards() { + use super::statistics::Collector; + + let first_body = Arc::new(Macro { + prefix: vec![TokenKind::Character('P', CatCode::Letter)], + parameters: Vec::new(), + parameter_chars: Vec::new(), + replacement: Vec::new(), + long: false, + outer: false, + protected: false, + }); + let second_body = Arc::new(first_body.as_ref().clone()); + + let mut names_by_shard: [Vec; COMMAND_SHARDS] = std::array::from_fn(|_| Vec::new()); + // At least one shard gets nine names, regardless of the process hash seed. + for index in 0..=8 * COMMAND_SHARDS { + let name = CommandName::Control(format!("paired-binding-{index}")); + let shard = CommandBindings::shard_index(command_hasher().hash_one(&name)); + names_by_shard[shard].push(name); + } + let (index, names) = names_by_shard + .into_iter() + .enumerate() + .find(|(_, names)| names.len() >= 9) + .unwrap(); + + let mut prior = State::default(); + let [first, second, edited, rest @ ..] = names.as_slice() else { + unreachable!(); + }; + prior.define(first.clone(), Meaning::Macro(first_body.clone()), true); + prior.define(second.clone(), Meaning::Macro(second_body.clone()), true); + prior.define(edited.clone(), Meaning::Macro(first_body), true); + for name in rest { + prior.define(name.clone(), Meaning::Count(0), true); + } + + let original = &prior.commands.shards[index]; + let mut matching = prior.clone(); + let matching_shard = Arc::make_mut(&mut matching.command_bindings_mut().shards[index]); + assert!(original.entries.keys().eq(matching_shard.entries.keys())); + let mut reordered = matching.clone(); + let changed = Arc::make_mut(&mut reordered.command_bindings_mut().shards[index]); + for capacity in [32, 64, 128, 256, 512, 1024] { + changed.entries.reserve(capacity); + if !original.entries.keys().eq(changed.entries.keys()) { + break; + } + } + assert!(!original.entries.keys().eq(changed.entries.keys())); + + let history = Collector::default(); + let counts = |state: &State| { + let (live, old_live) = state + .collect_compared_statistics(&prior, Collector::default().tracking_aliases()) + .unwrap(); + let mut expected = Collector::default(); + state.collect_statistics(&mut expected); + assert_eq!(live.usage, expected.usage); + assert_eq!(live.usage, old_live.usage); + live.has_equivalent_history(&old_live, &history, &history) + }; + for (mut current, expect_same_order) in [(matching, true), (reordered, false)] { + assert!(!Arc::ptr_eq(original, ¤t.commands.shards[index])); + assert_eq!(current, prior); + assert!(counts(¤t)); + + let changed = Arc::make_mut(&mut current.command_bindings_mut().shards[index]); + *changed.entries.get_mut(edited).unwrap() = Meaning::Macro(second_body.clone()); + assert_eq!(original.entries.keys().eq(changed.entries.keys()), expect_same_order); + assert_eq!(current, prior); + assert!(!counts(¤t)); + } +} + #[test] fn command_shard_equality_checks_values_in_matching_bucket_order() { let mut before = CommandShard::new(command_hasher().clone()); @@ -1823,9 +1902,9 @@ impl State { let mut old_usage = if current_usage.material_only() { current_usage.clone() } else { - let pairs = self.commands.shards.iter().zip(&old.commands.shards); current_usage.usage.state.command_entries = old.commands.len(); - for (current, prior) in pairs.clone() { + let mut changed_macros = Vec::new(); + for (current, prior) in self.commands.shards.iter().zip(&old.commands.shards) { if current.entries.len() != prior.entries.len() { return None; } @@ -1833,21 +1912,44 @@ impl State { for (name, meaning) in &prior.entries { Self::collect_command_statistics(&mut current_usage, name, meaning); } + continue; + } + + let mut ordered = Some(current.entries.iter()); + for (name, old_meaning) in &prior.entries { + let meaning = match ordered.as_mut().and_then(Iterator::next) { + Some((current_name, meaning)) if name == current_name => meaning, + _ => { + ordered = None; + current.entries.get(name)? + } + }; + if let CommandName::Control(name) = name.as_ref() { + current_usage.usage.state.control_name_bytes += name.len(); + } + match (meaning, old_meaning) { + (Meaning::Macro(body), Meaning::Macro(old_body)) => { + current_usage.usage.state.macro_bindings += 1; + if Arc::ptr_eq(body, old_body) { + current_usage.macro_body(body); + } else { + changed_macros.push((body, old_body)); + } + } + // Settled suffixes already require equal live meanings. + (Meaning::Macro(_), _) | (_, Meaning::Macro(_)) => return None, + _ => {} + } } } - // Both alias walks start with the exact same live allocations. - // Copy their ordinals before counting the remaining bindings so - // a later alias to a shared macro still has the original ordinal. + // The same permutation on both sides leaves the alias proof + // intact. Record common allocations first so a later reference + // to any of them still has the original ordinal on both sides. let mut old_usage = current_usage.clone(); - for (current, prior) in pairs { - if !Arc::ptr_eq(current, prior) { - for (name, old_meaning) in &prior.entries { - let meaning = current.entries.get(name)?; - Self::collect_command_statistics(&mut current_usage, name, meaning); - Self::collect_command_statistics(&mut old_usage, name, old_meaning); - } - } + for (body, old_body) in changed_macros { + current_usage.macro_body(body); + old_usage.macro_body(old_body); } old_usage }; diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index e8b452e..1bc8583 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -1,9 +1,7 @@ //! Measured native storage and execution resources, not invented TeX arena words. use super::*; -use std::{ - collections::{BTreeSet, HashMap, HashSet, hash_map::Entry}, - sync::Arc, -}; +use hashbrown::{HashMap, HashSet, hash_map::Entry}; +use std::{collections::BTreeSet, sync::Arc}; #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MaterialUsage {