Share common macro accounting and reduce command checkpoint copies

This commit is contained in:
gloamxun committed 2026-12-02 03:14:10 +08:00
1 parent f558bf43ea
commit d74933348d
6 files changed
+129 -26

No files matched your search

Generated
+3
View File
@@ -636,6 +636,9 @@ name = "hashbrown"
version = "0.17.2" version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
dependencies = [
"foldhash",
]
[[package]] [[package]]
name = "hayro-ccitt" name = "hayro-ccitt"
+1 -1
View File
@@ -7,7 +7,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D
[dependencies] [dependencies]
flate2 = "1.1" 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" harfbuzz_rs = "=3.0.1"
image = { version = "0.23.12", default-features = false, features = ["bmp"] } image = { version = "0.23.12", default-features = false, features = ["bmp"] }
lopdf = "0.26" lopdf = "0.26"
@@ -245,7 +245,8 @@ pub struct Executor {
reads: DependencyReads, reads: DependencyReads,
// Cache the resolved meaning alongside the last read epoch. A shard's // Cache the resolved meaning alongside the last read epoch. A shard's
// revision is only valid on this executor's state history. // revision is only valid on this executor's state history.
meaning_reads: HashMap<CommandName, (u64, Meaning, u32), RandomState>, // Keep the read epoch on each executor, while snapshots share cache keys.
meaning_reads: HashMap<Arc<CommandName>, (u64, Meaning, u32), RandomState>,
reads_tracing_macros: bool, reads_tracing_macros: bool,
conditionals: Vec<Conditional>, conditionals: Vec<Conditional>,
in_csname: bool, in_csname: bool,
@@ -854,12 +855,12 @@ impl Executor {
} }
fn dependency_observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ { fn dependency_observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
self.reads.observations().chain(self.meaning_reads.iter() 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<Dependency>, DependencyEvidence) { fn take_dependency_reads(&mut self) -> (BTreeSet<Dependency>, DependencyEvidence) {
std::mem::take(&mut self.reads).into_evidence(self.meaning_reads.drain() 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 { fn meaning(&mut self, token: &Token) -> Meaning {
@@ -884,7 +885,7 @@ impl Executor {
} }
RawEntryMut::Vacant(entry) => { RawEntryMut::Vacant(entry) => {
let meaning = self.state.meaning_hashed(name, hash); 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 meaning
} }
} }
@@ -670,8 +670,7 @@ fn splice_dependencies(
if current.meaning_reads.len() != prior.meaning_reads.len() { if current.meaning_reads.len() != prior.meaning_reads.len() {
reads.extend(current.meaning_reads.keys() reads.extend(current.meaning_reads.keys()
.filter(|name| !prior.meaning_reads.contains_key(*name)) .filter(|name| !prior.meaning_reads.contains_key(*name))
.cloned() .map(|name| Dependency::Meaning(name.as_ref().clone())));
.map(Dependency::Meaning));
} }
Some((reads, DependencyEvidence::default())) Some((reads, DependencyEvidence::default()))
} }
+117 -15
View File
@@ -804,7 +804,9 @@ enum PdftexRevision {
R24, 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<Arc<CommandName>, Meaning, RandomState>; type CommandEntries = HashMap<Arc<CommandName>, Meaning, RandomState>;
#[derive(Clone, Debug)] #[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 second = CommandName::Control("other-common-definition".into());
let shard = |name: &CommandName| CommandBindings::shard_index(command_hasher().hash_one(name)); let shard = |name: &CommandName| CommandBindings::shard_index(command_hasher().hash_one(name));
let shared_shards = [shard(&first), shard(&second)]; let shared_shards = [shard(&first), shard(&second)];
let edited = (0..128) let edited = (0..COMMAND_SHARDS)
.map(|index| CommandName::Control(format!("edited-alias-{index}"))) .map(|index| CommandName::Control(format!("edited-alias-{index}")))
.find(|name| !shared_shards.contains(&shard(name))) .find(|name| !shared_shards.contains(&shard(name)))
.unwrap(); .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)); 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<CommandName>; 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, &current.commands.shards[index]));
assert_eq!(current, prior);
assert!(counts(&current));
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(&current));
}
}
#[test] #[test]
fn command_shard_equality_checks_values_in_matching_bucket_order() { fn command_shard_equality_checks_values_in_matching_bucket_order() {
let mut before = CommandShard::new(command_hasher().clone()); let mut before = CommandShard::new(command_hasher().clone());
@@ -1823,9 +1902,9 @@ impl State {
let mut old_usage = if current_usage.material_only() { let mut old_usage = if current_usage.material_only() {
current_usage.clone() current_usage.clone()
} else { } else {
let pairs = self.commands.shards.iter().zip(&old.commands.shards);
current_usage.usage.state.command_entries = old.commands.len(); 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() { if current.entries.len() != prior.entries.len() {
return None; return None;
} }
@@ -1833,21 +1912,44 @@ impl State {
for (name, meaning) in &prior.entries { for (name, meaning) in &prior.entries {
Self::collect_command_statistics(&mut current_usage, name, meaning); 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. // The same permutation on both sides leaves the alias proof
// Copy their ordinals before counting the remaining bindings so // intact. Record common allocations first so a later reference
// a later alias to a shared macro still has the original ordinal. // to any of them still has the original ordinal on both sides.
let mut old_usage = current_usage.clone(); let mut old_usage = current_usage.clone();
for (current, prior) in pairs { for (body, old_body) in changed_macros {
if !Arc::ptr_eq(current, prior) { current_usage.macro_body(body);
for (name, old_meaning) in &prior.entries { old_usage.macro_body(old_body);
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);
}
}
} }
old_usage old_usage
}; };
@@ -1,9 +1,7 @@
//! Measured native storage and execution resources, not invented TeX arena words. //! Measured native storage and execution resources, not invented TeX arena words.
use super::*; use super::*;
use std::{ use hashbrown::{HashMap, HashSet, hash_map::Entry};
collections::{BTreeSet, HashMap, HashSet, hash_map::Entry}, use std::{collections::BTreeSet, sync::Arc};
sync::Arc,
};
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MaterialUsage { pub struct MaterialUsage {