diff --git a/Cargo.lock b/Cargo.lock index e08b214..6508d7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1593,6 +1593,7 @@ name = "texrra-tex-core" version = "0.1.0" dependencies = [ "flate2", + "hashbrown", "harfbuzz_rs", "hyphenate", "image 0.23.14", diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index dce6fcc..5ff201b 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -7,6 +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"] } 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/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 790b678..fb2a8f3 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1,6 +1,7 @@ -use std::collections::{BTreeMap, HashMap}; -use std::hash::{DefaultHasher, Hash, Hasher}; -use std::sync::Arc; +use hashbrown::HashMap; +use std::collections::BTreeMap; +use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; +use std::sync::{Arc, OnceLock}; use super::{ CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register, @@ -796,23 +797,78 @@ enum PdftexRevision { R24, } -#[derive(Clone, Debug, Default)] +const COMMAND_SHARDS: usize = 32; +type CommandShard = HashMap, Meaning, RandomState>; + +#[derive(Clone, Debug)] struct CommandBindings { - by_name: HashMap, Meaning>, + shards: [Arc; COMMAND_SHARDS], revision: u64, } +impl Default for CommandBindings { + fn default() -> Self { + // A shared seed gives independently built tables the same partition. + // The seed and partition are private to this process. + static HASHER: OnceLock = OnceLock::new(); + let hash = HASHER.get_or_init(RandomState::new); + Self { + shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hash.clone()))), + revision: 0, + } + } +} + impl PartialEq for CommandBindings { fn eq(&self, other: &Self) -> bool { - self.by_name == other.by_name + self.shards == other.shards } } impl Eq for CommandBindings {} impl CommandBindings { + fn shard_index(hash: u64) -> usize { + // Use bits separate from the table's bucket index and control tag. + ((hash >> 32) as usize) % COMMAND_SHARDS + } + + fn get(&self, name: &CommandName) -> Option<&Meaning> { + let hash = self.shards[0].hasher().hash_one(name); + self.shards[Self::shard_index(hash)] + .raw_entry() + .from_key_hashed_nocheck(hash, name) + .map(|(_, meaning)| meaning) + } + + fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard { + let hash = self.shards[0].hasher().hash_one(name); + Arc::make_mut(&mut self.shards[Self::shard_index(hash)]) + } + + fn insert(&mut self, name: Arc, meaning: Meaning) { + self.shard_mut(&name).insert(name, meaning); + } + + fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) { + self.shard_mut(&name).entry(name.into()).or_insert(meaning); + } + + fn remove(&mut self, name: &CommandName) { + self.shard_mut(name).remove(name); + } + + fn len(&self) -> usize { + self.shards.iter().map(|shard| shard.len()).sum() + } + + fn iter(&self) -> impl Iterator, &Meaning)> { + self.shards.iter().flat_map(|shard| shard.iter()) + } + fn ordered(&self) -> Vec<(&Arc, &Meaning)> { - let mut entries: Vec<_> = self.by_name.iter().collect(); + let mut entries = Vec::with_capacity(self.len()); + entries.extend(self.iter()); entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right)); entries } @@ -835,17 +891,18 @@ impl<'de> serde::Deserialize<'de> for CommandBindings { let entries = , Meaning)> as serde::Deserialize>::deserialize( deserializer, )?; - Ok(Self { - by_name: entries.into_iter().collect(), - revision: 0, - }) + let mut bindings = Self::default(); + for (name, meaning) in entries { + bindings.insert(name, meaning); + } + Ok(bindings) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct State { - // Checkpoints share the table. A write copies the bindings, while names - // and macro bodies stay shared. Formats and fingerprints use key order. + // Checkpoints share the table. A write copies just its command shard. + // Formats and fingerprints use key order. commands: Arc, catcodes: BTreeMap, counts: BTreeMap, @@ -978,7 +1035,7 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() { assert_eq!(state.fingerprint(), direct.finish()); let mut ordered_hash = DefaultHasher::new(); let mut table_hash = DefaultHasher::new(); - let ordered: BTreeMap<_, _> = state.commands.by_name.iter().collect(); + let ordered: BTreeMap<_, _> = state.commands.iter().collect(); ordered.hash(&mut ordered_hash); state.commands.hash(&mut table_hash); assert_eq!(table_hash.finish(), ordered_hash.finish()); @@ -994,6 +1051,25 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() { check(&state); } +#[test] +fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() { + let mut state = State::initex().with_etex(); + let name = CommandName::Control("checkpointbinding".into()); + state.define(name.clone(), Meaning::Count(3), true); + let snapshot = state.clone(); + state.define(name.clone(), Meaning::Count(7), true); + assert_eq!(snapshot.meaning(&name), Meaning::Count(3)); + assert_eq!(state.meaning(&name), Meaning::Count(7)); + let shared = state.commands.shards.iter().zip(&snapshot.commands.shards) + .filter(|(current, saved)| Arc::ptr_eq(current, saved)).count(); + assert_eq!(shared, COMMAND_SHARDS - 1); + + state.define(name, Meaning::Count(3), true); + assert_eq!(state, snapshot); + assert_eq!(state.fingerprint(), snapshot.fingerprint()); + assert_eq!(serde_json::to_vec(&state).unwrap(), serde_json::to_vec(&snapshot).unwrap()); +} + // These primitives belong to the pdfTeX command surface. Position queries, // page dimensions and the shared margin-kern extension are installed separately. const PDFTEX_ONLY_PRIMITIVES: &[(&str, Primitive)] = { @@ -1465,7 +1541,7 @@ impl State { } return; } - c.usage.state.command_entries = self.commands.by_name.len(); + c.usage.state.command_entries = self.commands.len(); let track_aliases = c.tracks_aliases(); let mut visit_command = |name: &CommandName, meaning: &Meaning| { if let CommandName::Control(name) = name { @@ -1481,7 +1557,7 @@ impl State { visit_command(name, meaning); } } else { - for (name, meaning) in &self.commands.by_name { + for (name, meaning) in self.commands.iter() { visit_command(name, meaning); } } @@ -1947,8 +2023,7 @@ impl State { ), ] { self.command_bindings_mut() - .entry(CommandName::Control(name.into()).into()) - .or_insert(meaning); + .insert_if_absent(CommandName::Control(name.into()), meaning); } } @@ -1964,8 +2039,7 @@ impl State { if self.profile == Profile::EtexBootstrap { for kind in LinePenaltyKind::ALL { self.command_bindings_mut() - .entry(CommandName::Control(kind.name().into()).into()) - .or_insert(Meaning::Primitive(Primitive::LinePenalties(kind))); + .insert_if_absent(CommandName::Control(kind.name().into()), Meaning::Primitive(Primitive::LinePenalties(kind))); } } } @@ -1985,8 +2059,7 @@ impl State { pub(super) fn restore_legacy_etex_parameter(&mut self, parameter: Parameter) { if self.profile == Profile::EtexBootstrap { self.command_bindings_mut() - .entry(CommandName::Control(parameter.name()).into()) - .or_insert(Meaning::Parameter(parameter)); + .insert_if_absent(CommandName::Control(parameter.name()), Meaning::Parameter(parameter)); } } @@ -2073,8 +2146,8 @@ impl State { fn update_profile_command(&mut self, name: &str, meaning: Meaning, enabled: bool) { let name = CommandName::Control(name.into()); if enabled { - self.command_bindings_mut().entry(name.into()).or_insert(meaning); - } else if self.commands.by_name.get(&name) == Some(&meaning) { + self.command_bindings_mut().insert_if_absent(name, meaning); + } else if self.commands.get(&name) == Some(&meaning) { self.command_bindings_mut().remove(&name); } } @@ -2251,7 +2324,7 @@ impl State { let meaning = Meaning::Primitive(primitive); if self.input_profile != super::InputProfile::TeX8Bit { self.command_bindings_mut().insert(name.into(), meaning); - } else if self.commands.by_name.get(&name) == Some(&meaning) { + } else if self.commands.get(&name) == Some(&meaning) { self.command_bindings_mut().remove(&name); } } @@ -2321,8 +2394,9 @@ impl State { let state = Self::initex().with_input_profile(self.input_profile); let state = if extended { state.with_etex() } else { state }; Arc::unwrap_or_clone(state.commands) - .by_name + .shards .into_iter() + .flat_map(Arc::unwrap_or_clone) .filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) { CommandName::Control(name) => Some((name, meaning)), _ => None, @@ -2333,10 +2407,10 @@ impl State { .map(|meaning| (name, meaning)) } - fn command_bindings_mut(&mut self) -> &mut HashMap, Meaning> { + fn command_bindings_mut(&mut self) -> &mut CommandBindings { let bindings = Arc::make_mut(&mut self.commands); bindings.revision += 1; - &mut bindings.by_name + bindings } pub(super) fn command_revision(&self) -> u64 { @@ -2350,7 +2424,7 @@ impl State { CommandName::FrozenPrimitive(_) => self.original_primitive(name) .map(|(_, meaning)| meaning.clone()).unwrap_or(Meaning::Undefined), CommandName::Font(font) => Meaning::Font(*font), - _ => self.commands.by_name.get(name).cloned().unwrap_or(Meaning::Undefined), + _ => self.commands.get(name).cloned().unwrap_or(Meaning::Undefined), } } /// Classic projection for byte-table consumers. A code outside the @@ -2749,7 +2823,7 @@ impl State { return; } let value = match &key { - Key::Command(name) => Saved::Command(self.commands.by_name.get(name).cloned()), + Key::Command(name) => Saved::Command(self.commands.get(name).cloned()), Key::Catcode(c) => Saved::Catcode(self.catcodes.get(c).copied()), Key::Count(index) => Saved::Integer(self.count(*index)), Key::Endlinechar => Saved::Integer(self.endlinechar), diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index d3e684f..ca6fa61 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,30 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 检查点按分区共享命令绑定 + +命令表以 32 个写时复制的分区共享给检查点。命令查找用一次散列选取 +分区及表内键。局部定义、全局覆盖和出组恢复仍用同一含义解析与版本 +更新。只有修改涉及的分区需要复制。持久格式及状态指纹继续按命令 +名有序计算。旧版的实际 pdfLaTeX 与 XeLaTeX 镜像用基线和候选分别 +重载,重编码指纹逐项一致。 + +原样 A4 的主文件和子文件各做等长编辑、异长编辑和恢复。六次修订 +均只更新受影响的一页。复用与重执行步数逐项对应。候选每次的完整 +内核结果、PDF、绘制列表、SVG、源映射、读取轨迹、aux 和日志都与 +同一初态的独立全量一致。13 项命令、格式、状态和检查点定向回归通过。 + +16 次同序的主文件热编辑中,执行阶段每次分配的字节均下降,中位数 +从 18,778,196 降至 17,309,578,减少 1,468,618 字节(7.82%)。 +另 16 次有 CPU 采样的编辑中,命令表复制由 64/311 个样本变为 +55/318,执行阶段中位从 73.006 ms 至 71.794 ms。准备至可发布 +阶段的中位为 91.055 ms 和 90.766 ms,时延收益尚需稳定复测。 +原样 A4 的正式浏览器可见时延和峰值内存仍按总目标验收。 + +证据在 target/p4-a4-convergence/,SHA256SUMS 指纹为 +ca03d3948be148af23f1b132297291fa7ba1b4e40ab3c9d6b6d3522a90724666。下一处可复用范围从子文件异长修改后失去内部检查点 +入手。原样 A4 的该路径实际执行约 79,000 步,等长修改约 57,000 步。 + ## 2026-11-29 保留换行后的字体字距 断行搜索和装盒都区分字体生成的普通 kern 与显式 kern。