diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 9f3d609..c6b983e 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1,5 +1,6 @@ use std::collections::BTreeMap; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; use super::{ CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register, @@ -789,10 +790,15 @@ enum PdftexRevision { R24, } +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +struct CommandBindings(#[serde(with = "ordered_map")] BTreeMap, Meaning>); + #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct State { - #[serde(with = "ordered_map")] - commands: BTreeMap, + // Checkpoints share the table. A write copies the ordered bindings, but + // their immutable names and macro bodies stay shared across revisions. + commands: Arc, catcodes: BTreeMap, counts: BTreeMap, toks: BTreeMap>, @@ -1035,7 +1041,7 @@ impl Default for State { fn default() -> Self { use Primitive::*; let mut state = Self { - commands: BTreeMap::new(), + commands: Arc::default(), catcodes: BTreeMap::new(), counts: BTreeMap::new(), toks: BTreeMap::new(), @@ -1330,13 +1336,13 @@ impl Default for State { ("font", Font), ("spacefactor", Spacefactor), ] { - state.commands.insert( - CommandName::Control(name.into()), + state.command_bindings_mut().insert( + CommandName::Control(name.into()).into(), Meaning::Primitive(primitive), ); } - state.commands.insert( - CommandName::Control(" ".into()), + state.command_bindings_mut().insert( + CommandName::Control(" ".into()).into(), Meaning::Primitive(Explicitspace), ); for p in TokenParameter::ALL { @@ -1344,8 +1350,8 @@ impl Default for State { continue; } state - .commands - .insert(CommandName::Control(p.name()), Meaning::TokenParameter(*p)); + .command_bindings_mut() + .insert(CommandName::Control(p.name()).into(), Meaning::TokenParameter(*p)); } for p in Parameter::ALL { if matches!( @@ -1364,11 +1370,11 @@ impl Default for State { continue; } state - .commands - .insert(CommandName::Control(p.name()), Meaning::Parameter(*p)); + .command_bindings_mut() + .insert(CommandName::Control(p.name()).into(), Meaning::Parameter(*p)); } - state.commands.insert( - CommandName::Control("nullfont".into()), + state.command_bindings_mut().insert( + CommandName::Control("nullfont".into()).into(), Meaning::Font(FontId::NULL), ); // Explicit text-bootstrap environment, not INITEX defaults or a format. @@ -1400,9 +1406,9 @@ impl State { } return; } - c.usage.state.command_entries = self.commands.len(); - for (name, meaning) in &self.commands { - if let CommandName::Control(name) = name { + c.usage.state.command_entries = self.commands.0.len(); + for (name, meaning) in &self.commands.0 { + if let CommandName::Control(name) = name.as_ref() { c.usage.state.control_name_bytes += name.len(); } if let Meaning::Macro(macro_definition) = meaning { @@ -1620,8 +1626,8 @@ impl State { self.install_line_penalty_primitives(); self.install_primitive_commands(); let hook = TokenParameter::Everyeof; - self.commands.insert( - CommandName::Control(hook.name()), + self.command_bindings_mut().insert( + CommandName::Control(hook.name()).into(), Meaning::TokenParameter(hook), ); for parameter in [ @@ -1635,8 +1641,8 @@ impl State { Parameter::Lastlinefit, Parameter::Savinghyphcodes, ] { - self.commands.insert( - CommandName::Control(parameter.name()), + self.command_bindings_mut().insert( + CommandName::Control(parameter.name()).into(), Meaning::Parameter(parameter), ); } @@ -1681,8 +1687,8 @@ impl State { ("fontchardp", Fontchardp), ("fontcharic", Fontcharic), ] { - self.commands.insert( - CommandName::Control(name.into()), + self.command_bindings_mut().insert( + CommandName::Control(name.into()).into(), Meaning::Primitive(primitive), ); } @@ -1870,8 +1876,8 @@ impl State { Meaning::Parameter(Parameter::Pdfsuppresswarningdupmap), ), ] { - self.commands - .entry(CommandName::Control(name.into())) + self.command_bindings_mut() + .entry(CommandName::Control(name.into()).into()) .or_insert(meaning); } } @@ -1887,8 +1893,8 @@ impl State { pub(super) fn install_line_penalty_primitives(&mut self) { if self.profile == Profile::EtexBootstrap { for kind in LinePenaltyKind::ALL { - self.commands - .entry(CommandName::Control(kind.name().into())) + self.command_bindings_mut() + .entry(CommandName::Control(kind.name().into()).into()) .or_insert(Meaning::Primitive(Primitive::LinePenalties(kind))); } } @@ -1896,8 +1902,8 @@ impl State { pub(super) fn restore_legacy_etex_parameter(&mut self, parameter: Parameter) { if self.profile == Profile::EtexBootstrap { - self.commands - .entry(CommandName::Control(parameter.name())) + self.command_bindings_mut() + .entry(CommandName::Control(parameter.name()).into()) .or_insert(Meaning::Parameter(parameter)); } } @@ -1985,9 +1991,9 @@ impl State { fn update_profile_command(&mut self, name: &str, meaning: Meaning, enabled: bool) { let name = CommandName::Control(name.into()); if enabled { - self.commands.entry(name).or_insert(meaning); - } else if self.commands.get(&name) == Some(&meaning) { - self.commands.remove(&name); + self.command_bindings_mut().entry(name.into()).or_insert(meaning); + } else if self.commands.0.get(&name) == Some(&meaning) { + self.command_bindings_mut().remove(&name); } } @@ -2143,9 +2149,9 @@ impl State { let name = CommandName::Control(name.into()); let meaning = Meaning::Primitive(primitive); if self.input_profile != super::InputProfile::TeX8Bit { - self.commands.insert(name, meaning); - } else if self.commands.get(&name) == Some(&meaning) { - self.commands.remove(&name); + self.command_bindings_mut().insert(name.into(), meaning); + } else if self.commands.0.get(&name) == Some(&meaning) { + self.command_bindings_mut().remove(&name); } } } @@ -2213,15 +2219,23 @@ impl State { .get_or_init(|| { let state = Self::initex().with_input_profile(self.input_profile); let state = if extended { state.with_etex() } else { state }; - state.commands.into_iter().filter_map(|(name, meaning)| match name { - CommandName::Control(name) => Some((name, meaning)), - _ => None, - }).collect() + Arc::unwrap_or_clone(state.commands) + .0 + .into_iter() + .filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) { + CommandName::Control(name) => Some((name, meaning)), + _ => None, + }) + .collect() }) .get(name) .map(|meaning| (name, meaning)) } + fn command_bindings_mut(&mut self) -> &mut BTreeMap, Meaning> { + &mut Arc::make_mut(&mut self.commands).0 + } + pub fn meaning(&self, name: &CommandName) -> Meaning { match name { CommandName::FrozenRelax => Meaning::Primitive(Primitive::Relax), @@ -2229,7 +2243,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.get(name).cloned().unwrap_or(Meaning::Undefined), + _ => self.commands.0.get(name).cloned().unwrap_or(Meaning::Undefined), } } /// Classic projection for byte-table consumers. A code outside the @@ -2486,10 +2500,10 @@ impl State { match (key, value) { (Key::Command(name), Saved::Command(value)) => match value { Some(value) => { - self.commands.insert(name, value); + self.command_bindings_mut().insert(name.into(), value); } None => { - self.commands.remove(&name); + self.command_bindings_mut().remove(&name); } }, (Key::Catcode(c), Saved::Catcode(value)) => match value { @@ -2628,7 +2642,7 @@ impl State { return; } let value = match &key { - Key::Command(name) => Saved::Command(self.commands.get(name).cloned()), + Key::Command(name) => Saved::Command(self.commands.0.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), @@ -2666,7 +2680,7 @@ impl State { } pub(super) fn define(&mut self, name: CommandName, meaning: Meaning, global: bool) { self.save(Key::Command(name.clone()), global); - self.commands.insert(name, meaning); + self.command_bindings_mut().insert(name.into(), meaning); } pub(super) fn assign_catcode(&mut self, c: char, value: CatCode, global: bool) { self.save(Key::Catcode(c), global); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 9bd07ec..e1a6751 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,33 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 检查点命令表与准备阶段文件探测 + +检查点和格式作业共享有序命令表。发生写入时复制绑定表,保留共享的 +不可变命令名和宏定义。普通查找仍直接访问同一张有序表。组内赋值、恢复、 +宏诊断和指纹继续按命令内容处理。加载既有 schema104 后重新编码,字节 +摘要与此前同格式的往返结果一致。五项格式及七项统计定向检查通过。 + +作业准备同时检查 PDF 和日志是否指向受保护的资源或原样输入。Unix 对 +两份输出共用一次实时输入身份扫描,扫描后复核两个目标。如有目标被替换, +重新执行实时检查。定向探针覆盖扫描中更换任一目标后形成硬链接以及缺失 +目标的精确路径匹配。两个相同的原样 A4 主文件热编辑窗口,带路径的 +statx 调用各从 1,371 次降到 1,212 次。 + +构建结束后交替测量旧版 8aa079e 与候选版。原样 A4 的主文件、子文件各 +10 对编辑,逐修订 PDF、SVG、来源映射、aux、归一化日志、变更页及 +执行与复用步数一致。末版由独立进程全量复核。另通过库会话各编辑一次 +主文件和子文件,绘制列表和资源读取也与同初态独立全量一致。 + +按同一编辑配对,服务端预览就绪耗时的中位变化为主文件 -0.51 ms、 +子文件 +1.09 ms。进程峰值 RSS 由 349,996 降至 346,140 KiB。 +首轮构建并发时的原始配对样本也保留。本轮确定了探测次数和内存变化, +尚无稳定的时延改善证据。真实浏览器的编辑到可见页面及按项目规模的 +正式 p50/p95 和内存验收仍待执行。 + +证据在 target/p4-edit-execution-cost/。下一批优先处理剩余的实际 +重执行和文件效果重放开销,从原样项目的依赖变更与后续页面恢复验证。 + ## 2026-11-29 XeTeX 文字基线与 PDF 字距 按 xdvipdfmx 的精度回算 PDF 相对文字移动的舍入余量,按设备能分辨的 diff --git a/src/native_host.rs b/src/native_host.rs index 3677d92..e333f7a 100644 --- a/src/native_host.rs +++ b/src/native_host.rs @@ -193,6 +193,45 @@ impl HostPreparation { } } + /// Compare two outputs with the same protected paths in one live scan. + pub(crate) fn either_aliases_any<'a>( + &mut self, + outputs: [&Path; 2], + candidates: impl Iterator + Clone, + ) -> bool { + #[cfg(unix)] + if let [Some(first), Some(second)] = outputs.map(|path| self.path_identity(path)) { + let identities = [first, second]; + for candidate in candidates.clone() { + if let Some(output) = outputs.iter().find(|&&output| output == candidate) { + return self.record_alias(candidate, output, true); + } + let observed = if identities == [UnixPathIdentity::Missing; 2] { + None + } else { + self.path_identity(candidate) + }; + for (output, identity) in outputs.into_iter().zip(identities) { + let same = if identity == UnixPathIdentity::Missing { + self.record_alias(candidate, output, false) + } else if let Some(observed) = observed { + self.record_alias(candidate, output, identity == observed) + } else { + self.same_file(candidate, output) + }; + if same { + return true; + } + } + } + // Fresh pairwise checks if either destination changed during the scan. + if outputs.map(|path| self.path_identity(path)) == identities.map(Some) { + return false; + } + } + outputs.into_iter().any(|path| self.aliases_any(path, candidates.clone())) + } + #[cfg(unix)] fn path_identity(&mut self, path: &Path) -> Option { use std::os::unix::fs::MetadataExt; diff --git a/src/native_job.rs b/src/native_job.rs index 333b72e..073d973 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -328,12 +328,10 @@ impl Files { || existing_log.as_ref() == Some(&resource.path) || existing_output.as_ref() == Some(&resource.path) }) - || preparation.aliases_any( - &log_path, + || preparation.either_aliases_any( + [&log_path, &pdf], world.trace().reads.iter().map(|r| r.path.as_path()), ) - || preparation - .aliases_any(&pdf, world.trace().reads.iter().map(|r| r.path.as_path())) || preparation.same_file(source, &log_path) || preparation.same_file(&pdf, &log_path) { @@ -368,9 +366,7 @@ impl Files { protected.extend(project.immutable_paths().map(Path::to_path_buf)); protected.sort(); protected.dedup(); - if preparation.aliases_any(&pdf, project.immutable_paths()) - || preparation.aliases_any(&log_path, project.immutable_paths()) - { + if preparation.either_aliases_any([&pdf, &log_path], project.immutable_paths()) { return Err("native output would overwrite an atomic project input".into()); } } @@ -2864,6 +2860,47 @@ mod generated_file_tests { fs::remove_dir_all(root).unwrap(); } + #[cfg(unix)] + #[test] + fn paired_alias_scan_reads_an_input_once_and_rechecks_either_destination() { + use crate::native_host::HostObservation; + use std::cell::Cell; + + let root = root(); + let pdf = root.join("job.pdf"); + let log = root.join("job.log"); + let input = root.join("main.tex"); + let replacement = root.join("pending-link"); + for output in [&pdf, &log] { + fs::write(output, b"independent destination").unwrap(); + } + + let mut preparation = HostPreparation::default(); + assert!(!preparation.either_aliases_any([&pdf, &log], [input.as_path()].into_iter())); + let input_reads = preparation.observations.iter().filter(|observation| { + matches!(observation, HostObservation::Metadata { path, .. } if path == &input) + }); + assert_eq!(input_reads.count(), 1); + + for output in [&pdf, &log] { + fs::hard_link(&input, &replacement).unwrap(); + let switched = Cell::new(false); + let candidates = [input.as_path()].into_iter().inspect(|_| { + if !switched.replace(true) { + fs::rename(&replacement, output).unwrap(); + } + }); + let mut preparation = HostPreparation::default(); + assert!(preparation.either_aliases_any([&pdf, &log], candidates)); + assert!(preparation.observations.iter().any(|observation| { + matches!(observation, HostObservation::Alias { right, same: true, .. } if right == output) + })); + fs::remove_file(output).unwrap(); + fs::write(output, b"independent destination").unwrap(); + } + fs::remove_dir_all(root).unwrap(); + } + #[cfg(unix)] #[test] fn preparation_alias_rejection_records_actual_hardlink_identity() {