From d249ec7eba061505f0353a9e159772503b4c2887 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 10:52:20 +0800 Subject: [PATCH] Reuse command lookup hashes and validate cached meanings by shard --- .../texrra-tex-core/src/execution/engine.rs | 37 +++++++++------- crates/texrra-tex-core/src/execution/state.rs | 42 ++++++++++++------- docs/P2_M1_PROGRESS.md | 26 ++++++++++++ tests/native_execution.rs | 30 +++++++++++++ 4 files changed, 105 insertions(+), 30 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index ff123d7..11f46a9 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -1,9 +1,12 @@ -use std::collections::{BTreeSet, HashMap, VecDeque}; +use std::collections::{BTreeSet, VecDeque}; +use std::hash::{BuildHasher, RandomState}; use std::sync::Arc; +use hashbrown::{HashMap, hash_map::RawEntryMut}; + use super::job::InputStream; use super::mouth::Mouth; -use super::state::{GroupKind, Key, Replacement}; +use super::state::{GroupKind, Key, Replacement, command_hasher}; use super::*; mod alignment; mod boxes; @@ -235,8 +238,8 @@ pub struct Executor { generated_inputs: std::collections::BTreeMap, reads: DependencyReads, // Cache the resolved meaning alongside the already required read evidence. - // The revision is only valid within this executor and its checkpoints. - meaning_reads: HashMap, + // A shard's revision is only valid on this executor's state history. + meaning_reads: HashMap, reads_tracing_macros: bool, conditionals: Vec, in_csname: bool, @@ -533,7 +536,7 @@ impl Executor { stream_sources: BTreeSet::new(), generated_inputs: Default::default(), reads: DependencyReads::default(), - meaning_reads: HashMap::new(), + meaning_reads: HashMap::with_hasher(command_hasher().clone()), reads_tracing_macros: false, conditionals: Vec::new(), in_csname: false, @@ -784,17 +787,23 @@ impl Executor { self.lookup_meaning(name) } fn lookup_meaning(&mut self, name: &CommandName) -> Meaning { - let revision = self.state.command_revision(); - if let Some((cached_revision, meaning)) = self.meaning_reads.get_mut(name) { - if *cached_revision != revision { - *meaning = self.state.meaning(name); - *cached_revision = revision; + let hash = self.meaning_reads.hasher().hash_one(name); + let revision = self.state.command_revision(hash); + match self.meaning_reads.raw_entry_mut().from_key_hashed_nocheck(hash, name) { + RawEntryMut::Occupied(mut entry) => { + let (cached_revision, meaning) = entry.get_mut(); + if *cached_revision != revision { + *meaning = self.state.meaning_hashed(name, hash); + *cached_revision = revision; + } + meaning.clone() + } + RawEntryMut::Vacant(entry) => { + let meaning = self.state.meaning_hashed(name, hash); + entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone())); + meaning } - return meaning.clone(); } - let meaning = self.state.meaning(name); - self.meaning_reads.insert(name.clone(), (revision, meaning.clone())); - meaning } fn primitive(&mut self, token: &Token) -> Option { match self.meaning(token) { diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index fb2a8f3..c2f7cc4 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -800,21 +800,25 @@ enum PdftexRevision { const COMMAND_SHARDS: usize = 32; type CommandShard = HashMap, Meaning, RandomState>; +pub(super) fn command_hasher() -> &'static RandomState { + // Identical hashes feed the binding table and the executor's read cache. + // The seed and partition are private to this process. + static HASHER: OnceLock = OnceLock::new(); + HASHER.get_or_init(RandomState::new) +} + #[derive(Clone, Debug)] struct CommandBindings { shards: [Arc; COMMAND_SHARDS], - revision: u64, + revisions: [u64; COMMAND_SHARDS], } 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); + let hasher = command_hasher(); Self { - shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hash.clone()))), - revision: 0, + shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hasher.clone()))), + revisions: [0; COMMAND_SHARDS], } } } @@ -834,7 +838,10 @@ impl CommandBindings { } fn get(&self, name: &CommandName) -> Option<&Meaning> { - let hash = self.shards[0].hasher().hash_one(name); + self.get_hashed(name, command_hasher().hash_one(name)) + } + + fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> { self.shards[Self::shard_index(hash)] .raw_entry() .from_key_hashed_nocheck(hash, name) @@ -842,8 +849,9 @@ impl CommandBindings { } 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)]) + let index = Self::shard_index(command_hasher().hash_one(name)); + self.revisions[index] += 1; + Arc::make_mut(&mut self.shards[index]) } fn insert(&mut self, name: Arc, meaning: Meaning) { @@ -2408,23 +2416,25 @@ impl State { } fn command_bindings_mut(&mut self) -> &mut CommandBindings { - let bindings = Arc::make_mut(&mut self.commands); - bindings.revision += 1; - bindings + Arc::make_mut(&mut self.commands) } - pub(super) fn command_revision(&self) -> u64 { - self.commands.revision + pub(super) fn command_revision(&self, hash: u64) -> u64 { + self.commands.revisions[CommandBindings::shard_index(hash)] } pub fn meaning(&self, name: &CommandName) -> Meaning { + self.meaning_hashed(name, command_hasher().hash_one(name)) + } + + pub(super) fn meaning_hashed(&self, name: &CommandName, hash: u64) -> Meaning { match name { CommandName::FrozenRelax => Meaning::Primitive(Primitive::Relax), CommandName::FrozenPrimitivePrefix => Meaning::Primitive(Primitive::DeferredPrimitive), CommandName::FrozenPrimitive(_) => self.original_primitive(name) .map(|(_, meaning)| meaning.clone()).unwrap_or(Meaning::Undefined), CommandName::Font(font) => Meaning::Font(*font), - _ => self.commands.get(name).cloned().unwrap_or(Meaning::Undefined), + _ => self.commands.get_hashed(name, hash).cloned().unwrap_or(Meaning::Undefined), } } /// Classic projection for byte-table consumers. A code outside the diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index a86de69..155f824 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,32 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 按命令分区刷新含义缓存 + +执行器与实际命令绑定表共用同一次散列。命令定义和出组恢复更新 +实际写入的分区版本,其他分区继续使用已解析的含义。命令读取 +证据和有序格式编码沿用原身份。局部定义、全局覆盖、出组恢复及 +未定义命令重新定义的用例通过,另两项执行定向检查通过。既有 +pdfLaTeX 和 XeLaTeX 格式镜像可重载,重编码指纹与基线一致。 + +原样 OUP 九份输入从空辅助文件执行首轮。在同机同一逻辑核上, +构建结束后的单对串行结果为 94.224 → 78.668 秒。用户态硬件 +指令数减少 4.83%,峰值 RSS 为 818,368 → 819,080 KiB。 +两版均执行 171,226,512 步。10 页 PDF、aux 和 out 逐字节相同, +原始布局、来源映射及资源和流轨迹一致。校验了两次作业各自生成的 +账本及输出文件身份,并按同一项目相对路径对照。保留受后台构建 +影响而中止的计时。此轮测量范围为命令行冷编译的一对样本。 + +原样 A4 的主、子文件分别执行等长编辑、异长编辑和恢复。六次皆 +只更新受影响的一页。完整执行、PDF、页面绘制、SVG、来源映射、 +读取轨迹、aux 和日志均与独立全量一致。子文件等长改动实际执行 +56,886 步,异长及恢复分别执行 79,031、79,001 步。下一批核查 +真实文件大小查询之后能够安全重用的执行范围,保留当前输入、 +依赖和生成效果校验。编辑到页面可见的正式时延门禁仍待完成。 + +证据在 target/p3-execution-lookups/。SHA256SUMS 指纹为 +2567401aaa34062d216c9e560cc420f161e66ff130e03f5607cfe542a44f7d05。 + ## 2026-11-29 PDF 图形原点的双轴移动阈值 pdfTeX 以输出精度对应的最小 sp 位移检查两轴。两轴均低于阈值时 diff --git a/tests/native_execution.rs b/tests/native_execution.rs index 87a8d60..5cd7e83 100644 --- a/tests/native_execution.rs +++ b/tests/native_execution.rs @@ -63,6 +63,36 @@ fn native_cli_executes_input_macros_registers_and_exports_a_real_pdf() { fs::remove_dir_all(directory).unwrap(); } +#[test] +fn cached_command_meanings_follow_definitions_and_group_restoration() { + let directory = directory(); + fs::write( + directory.join("scoped.tex"), + r"\def\stable{A}\def\globalbinding{G} +\ifdefined\scoped\errmessage{Initially defined}\fi +\message{BEFORE=\stable\globalbinding} +{\def\scoped{B}\def\stable{C} + \ifdefined\scoped\else\errmessage{Local definition lost}\fi + \message{INSIDE=\stable\scoped\globalbinding} + \global\def\globalbinding{H}} +\ifdefined\scoped\errmessage{Local definition leaked}\fi +\message{AFTER=\stable\globalbinding} +\def\scoped{D}\message{DEFINED-AGAIN=\scoped}\end", + ) + .unwrap(); + let output = native_fonts::command() + .args(["native", "--etex", "scoped.tex", "scoped.pdf"]) + .current_dir(&directory) + .output() + .unwrap(); + let diagnostics = String::from_utf8_lossy(&output.stderr); + assert!(output.status.success(), "{diagnostics}"); + for message in ["BEFORE=AG", "INSIDE=CBG", "AFTER=AH", "DEFINED-AGAIN=D"] { + assert!(diagnostics.contains(message), "{diagnostics}"); + } + fs::remove_dir_all(directory).unwrap(); +} + #[test] fn unsupported_native_latex_is_an_error_and_cannot_overwrite_an_existing_pdf() { let directory = directory();