From 48c980c871e831de07e76586c7d4b1753bfabd53 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Thu, 19 Nov 2026 19:00:39 +0800 Subject: [PATCH] Share TeX hyphenation patterns and reuse verified state fingerprints --- .../texrra-tex-core/src/execution/engine.rs | 19 ++- .../src/execution/hyphenation.rs | 108 +++++++++++++++--- .../texrra-tex-core/src/execution/session.rs | 2 + docs/P2_M1_PROGRESS.md | 37 ++++++ docs/PUBLISHER_TEMPLATE_MATRIX.md | 8 ++ 5 files changed, 150 insertions(+), 24 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 051ca00..5ae3551 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -292,7 +292,7 @@ impl EntryCheckpoint { files: &mut impl SourceProvider, cancellation: Cancellation, ) -> Option> { - self.resume_observed(source, files, cancellation, None, |_, _, _| {}) + self.resume_observed(source, files, cancellation, None, None, |_, _, _| {}) } pub(super) fn resume_capturing_entries_after_host_replay( @@ -301,6 +301,7 @@ impl EntryCheckpoint { files: &mut F, cancellation: Cancellation, line_break_cache: std::sync::Arc, + previous: Option<&Execution>, select: impl FnMut(usize, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Option> { @@ -309,6 +310,7 @@ impl EntryCheckpoint { files, cancellation, Some(line_break_cache), + previous, Executor::entry_observer(self.incoming_state, select, capture), ) } @@ -319,6 +321,7 @@ impl EntryCheckpoint { files: &mut F, cancellation: Cancellation, line_break_cache: Option>, + previous: Option<&Execution>, capture_boundary: impl FnMut(&mut Executor, usize, &mut F), ) -> Option> { if !self.accepts_entry(&source) { @@ -335,7 +338,7 @@ impl EntryCheckpoint { .check_cancellation() .and_then(|_| executor.run_active_input(self.initial_depth, files, capture_boundary)); let result = executor.finish_observed_input(result, files); - Some(executor.finish_execution(result, self.incoming_state)) + Some(executor.finish_execution(result, self.incoming_state, previous)) } } @@ -3037,7 +3040,7 @@ impl Executor { ) -> Result { let incoming_state = self.state.fingerprint(); let result = self.run_observed(file, files, |_, _, _| {}); - self.finish_execution(result, incoming_state) + self.finish_execution(result, incoming_state, None) } /// Capture the first eligible entry command boundary at or beyond the /// requested physical byte. The callback captures the matching host state. @@ -3086,7 +3089,7 @@ impl Executor { files, Self::entry_observer(incoming_state, select, capture), ); - self.finish_execution(result, incoming_state) + self.finish_execution(result, incoming_state, None) } fn entry_observer( @@ -3146,6 +3149,7 @@ impl Executor { mut self, result: Result<(), Error>, incoming_state: u64, + previous: Option<&Execution>, ) -> Result { self.collect_meaning_reads(); if let Err(error) = result { @@ -3183,6 +3187,11 @@ impl Executor { evidence, }); } + // An identical completed state has the same fingerprint. Compare + // the entire state, including token source spans and assignments. + let outgoing_state = previous + .filter(|last| last.state == self.state) + .map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state); Ok(Execution { format_dumped: self.format_dumped, job_name: self.job_name, @@ -3191,7 +3200,7 @@ impl Executor { events: self.events.into_vec(), native_page: self.native_page, split_discards: self.split_discards, - outgoing_state: self.state.fingerprint(), + outgoing_state, state: self.state, io: self.io, input_position: self.input_position, diff --git a/crates/texrra-tex-core/src/execution/hyphenation.rs b/crates/texrra-tex-core/src/execution/hyphenation.rs index 5cba602..0354b67 100644 --- a/crates/texrra-tex-core/src/execution/hyphenation.rs +++ b/crates/texrra-tex-core/src/execution/hyphenation.rs @@ -1,6 +1,10 @@ //! Native language tables and pattern trie. No implicit English dictionary. use super::*; -use std::collections::BTreeMap; +use std::{ + collections::BTreeMap, + hash::{Hash, Hasher}, + sync::{Arc, OnceLock}, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct HyphenationLanguage { pub language: u8, @@ -39,20 +43,48 @@ struct TrieNode { edges: BTreeMap, weights: Vec, } +// Job state and checkpoints share the pattern trie. Pattern assignments +// can still mutate it while building a format. +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +struct TrieNodes { + values: Vec, + #[serde(skip)] + counts: OnceLock<(usize, usize)>, +} + +impl PartialEq for TrieNodes { + fn eq(&self, other: &Self) -> bool { + self.values == other.values + } +} + +impl Eq for TrieNodes {} + +impl Hash for TrieNodes { + fn hash(&self, hasher: &mut H) { + self.values.hash(hasher); + } +} + #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(super) struct HyphenationData { - nodes: Vec, + nodes: Arc, roots: BTreeMap, pub exceptions: BTreeMap>>, pub sealed: bool, } impl HyphenationData { pub(super) fn resource_counts(&self) -> (usize, usize, usize) { - ( - self.nodes.len(), - self.nodes.iter().map(|n| n.edges.len()).sum(), - self.nodes.iter().map(|n| n.weights.len()).sum(), - ) + let (edges, weights) = *self.nodes.counts.get_or_init(|| { + self.nodes + .values + .iter() + .fold((0, 0), |(edges, weights), node| { + (edges + node.edges.len(), weights + node.weights.len()) + }) + }); + (self.nodes.values.len(), edges, weights) } pub fn insert( &mut self, @@ -61,34 +93,37 @@ impl HyphenationData { weights: &[u8], limit: usize, ) -> Result<(), String> { + let trie = Arc::make_mut(&mut self.nodes); + trie.counts.take(); + let nodes = &mut trie.values; let mut at = if let Some(&root) = self.roots.get(&language) { root } else { - let root = self.node(limit)?; + let root = Self::node(nodes, limit)?; self.roots.insert(language, root); root }; for c in letters { - at = if let Some(&next) = self.nodes[at].edges.get(c) { + at = if let Some(&next) = nodes[at].edges.get(c) { next } else { - let next = self.node(limit)?; - self.nodes[at].edges.insert(*c, next); + let next = Self::node(nodes, limit)?; + nodes[at].edges.insert(*c, next); next }; } - if self.nodes[at].weights.iter().any(|v| *v != 0) { + if nodes[at].weights.iter().any(|v| *v != 0) { return Err("duplicate hyphenation pattern".into()); } - self.nodes[at].weights = weights.to_vec(); + nodes[at].weights = weights.to_vec(); Ok(()) } - fn node(&mut self, limit: usize) -> Result { - if self.nodes.len() >= limit { + fn node(nodes: &mut Vec, limit: usize) -> Result { + if nodes.len() >= limit { return Err("native hyphenation pattern memory limit exceeded".into()); } - let next = self.nodes.len(); - self.nodes.push(TrieNode::default()); + let next = nodes.len(); + nodes.push(TrieNode::default()); Ok(next) } pub fn points(&self, language: u8, word: &str) -> Vec { @@ -98,6 +133,7 @@ impl HyphenationData { let Some(&root) = self.roots.get(&language) else { return Vec::new(); }; + let nodes = &self.nodes.values; let letters: Vec<_> = std::iter::once(0) .chain(word.chars().map(|c| c as u32)) .chain([0]) @@ -106,11 +142,11 @@ impl HyphenationData { for start in 0..letters.len() { let mut at = root; for c in &letters[start..] { - let Some(&next) = self.nodes[at].edges.get(c) else { + let Some(&next) = nodes[at].edges.get(c) else { break; }; at = next; - for (i, &v) in self.nodes[at].weights.iter().enumerate() { + for (i, &v) in nodes[at].weights.iter().enumerate() { scores[start + i] = scores[start + i].max(v); } } @@ -120,3 +156,37 @@ impl HyphenationData { .collect() } } + +#[test] +fn cloned_patterns_remain_isolated_on_assignment() { + let mut format = HyphenationData::default(); + let letters = ['t' as u32, 'e' as u32]; + format.insert(0, &letters, &[0, 1, 0], 12).unwrap(); + assert_eq!(format.resource_counts(), (3, 2, 3)); + + let shared = format.clone(); + assert!(Arc::ptr_eq(&format.nodes, &shared.nodes)); + format.insert(0, &['a' as u32], &[0, 0], 12).unwrap(); + assert_eq!(format.resource_counts(), (4, 3, 5)); + assert_eq!(shared.resource_counts(), (3, 2, 3)); + assert_eq!(shared.points(0, "tea"), [1]); + assert_eq!(format.points(0, "tea"), [1]); + + let encoded = serde_json::to_value(&shared).unwrap(); + assert_eq!( + encoded["nodes"], + serde_json::to_value(&shared.nodes.values).unwrap() + ); + let restored: HyphenationData = serde_json::from_value(encoded).unwrap(); + assert_eq!(restored, shared); + assert_eq!(restored.resource_counts(), (3, 2, 3)); + + let hash = |nodes: &TrieNodes| { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + nodes.hash(&mut hasher); + hasher.finish() + }; + let mut legacy = std::collections::hash_map::DefaultHasher::new(); + shared.nodes.values.hash(&mut legacy); + assert_eq!(hash(&shared.nodes), legacy.finish()); +} diff --git a/crates/texrra-tex-core/src/execution/session.rs b/crates/texrra-tex-core/src/execution/session.rs index f95860b..1369b06 100644 --- a/crates/texrra-tex-core/src/execution/session.rs +++ b/crates/texrra-tex-core/src/execution/session.rs @@ -207,11 +207,13 @@ impl RevisionJob { select: impl FnMut(usize, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Option, RevisionFailure>> { + let previous = self.session.latest(); let executed = checkpoint.resume_capturing_entries_after_host_replay( source, files, self.cancellation.clone(), line_break_cache, + previous.as_deref().map(|revision| &revision.execution), select, capture, )?; diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index a9cf1d4..e15d8a1 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -437,6 +437,43 @@ SHA-256 为 `40fde3f64d7209d55a5442c49db6203a2cf99845936ef3342d0b58b758176e42` `target/p4-warm-cpu-profile/original-a4/symbolized.json` SHA-256 为 `b7b48e1be44de33c531279628d244dcd2a71814ad3dbfb9f9377e6ff64aa7e48`。 +### 共享断字模式与已验证的末态指纹 + +格式和各编辑检查点共享只读字典树。INITEX 插入模式时复制并更新实际节点, +当前断字统计随树版本重新计算。格式编码和原有完整指纹保留。自动恢复结束 +后,只有完整状态与会话前一份成功执行相等才复用其指纹,否则重新计算。 +比较包含宏参数、分组、来源跨度和真实寄存器。560 项定向回归通过。 + +原样 A4 在 Edge 上两轮交替比较,每轮各版本30次主文件和30次子文件编辑。 +真实格式、字体、执行和复用步数相同,每个对应修订的 PDF、SVG、来源版本 +及映射相同,最终 aux 相同。用同版二进制最后两份浏览器缓冲区独立全量, +得到同样输出,零复用步骤。 + +| 轮次 | 编辑 | 基线执行 p50 / p95 (ms) | 新版执行 p50 / p95 (ms) | 基线绘制 p50 / p95 (ms) | 新版绘制 p50 / p95 (ms) | +| ---: | --- | ---: | ---: | ---: | ---: | +| 1 | 主文件 | 85.2 / 118.2 | 81.6 / 110.4 | 211.2 / 273.5 | 211.4 / 256.1 | +| 1 | 子文件 | 105.4 / 147.4 | 59.8 / 90.2 | 228.2 / 308.5 | 188.3 / 251.1 | +| 2 | 主文件 | 83.1 / 102.8 | 84.3 / 141.0 | 209.1 / 259.9 | 206.9 / 268.9 | +| 2 | 子文件 | 105.7 / 136.4 | 60.5 / 87.6 | 226.0 / 277.3 | 184.1 / 220.5 | + +两轮服务端峰值 RSS 分别由625832降至591780 KiB、由625860降至591332 KiB。 +第一轮子文件可见 p95 略超250 ms,第二轮低于门限。主文件100 ms门限仍未 +达到,第二轮主文件可见 p95 比当轮基线增加9.0 ms。两轮 WSL I/O 压力 some +avg10 起止分别为15.85%与47.50%、7.56%与60.70%。 + +复测给各浏览器配置足够的资源记录容量。每条响应记录均落在对应编辑的 +时间窗口。新版子文件从收完响应至浏览器确认绘制的 p50 为 +29.3 ms,响应体传输 p50 为 0.8 ms。 +从发送请求至响应头的时间扣除服务端排队和准备到就绪,剩余 p50 为 +49.2 ms,包含连接两端的剩余开销。 + +浏览器回执位于 `target/p4-shared-patterns/edge-a4`,`run-1/receipt.json` +SHA-256 为 `56724948c13ad54bdfef4d095b7f78025e35dbf24ed5d2f20ab88cf98bb8ad69`, +`run-2/receipt.json` SHA-256 为 +`0bf8d4b09eb9e52e23739bef7e2c999607bf890395e9461bf50e59df6927bbfd`。独立全量回执 `full-equivalence/receipt.json` +SHA-256 为 `287bb542d9da1429fe0aa0134490b0c65485c4433026eb988e4de8f6d41c7b35`。定向回归 `directed.log` SHA-256 +为 `6ddbccc5481fb4ff752db594bf5da54a0cffda152741197d745161c536317bd1`。 + ### schema27 与主线兼容性 合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 7893f39..73e957b 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -351,6 +351,14 @@ pdfTeX 会把该操作写入页面内容流,并链接对应的 `ExtGState` 资 的实际诊断和参考 PDF 保留在 `color-stack-probe`。 [pdfTeX 上游对颜色栈参数的扫描](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L10457-L10478) +两份独立的 pdfTeX 参考作业补齐跨页与对象生命周期的约束。第一页先发初始 +图形状态再推入新状态,第二页先重放新状态再弹回。当前页的资源字典连接两个 +实际对象。对象编号保留、立即写出、页面引用、丢弃盒及从未引用对象各有实际 +PDF 证据。回执 `target/p3-pdf-graphic-state-reference/receipt.json` +SHA-256 为 `0f9082ccfabbd34895b95abe9a20011c68cd9669a5cc69c2068e97b7aa3ae631`。 +[pdfTeX 对象写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L31785-L31839) +[pdfTeX 页面资源写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L17886-L17903) + 最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json` SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存 DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有