diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 2082499..ff123d7 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -242,8 +242,10 @@ pub struct Executor { in_csname: bool, command_trace_mode: Option<&'static str>, events: ExecutionEvents, - // Set before operations that inspect earlier events beyond their count. + // The PDF space probe inspects the actual paint of earlier pages. reads_event_history: bool, + // Capacity recounts and tracing use the resource accounting traversal. + accounts_event_history: bool, steps: usize, ligature_carry: super::ligature::Carry, current: Span, @@ -538,6 +540,7 @@ impl Executor { command_trace_mode: None, events: ExecutionEvents::default(), reads_event_history: false, + accounts_event_history: false, steps: 0, ligature_carry: super::ligature::Carry::default(), current: Span::default(), @@ -3534,6 +3537,7 @@ impl Executor { events: self.events.into_vec(), steps: self.steps, reads_event_history: self.reads_event_history, + accounts_event_history: self.accounts_event_history, }) } fn check_input_character(&self, code: i32) -> Result<(), Error> { @@ -4037,6 +4041,7 @@ impl Executor { incoming_state, steps: self.steps, reads_event_history: self.reads_event_history, + accounts_event_history: self.accounts_event_history, }) } fn run_observed( diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index a87b65f..9eb2ba5 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -122,6 +122,11 @@ impl EntryCheckpoint { let mut sources = completed.sources.clone(); sources[self.entry] = current.sources[self.entry].clone(); let tail = completed.events.get(old.events.len()..)?; + if completed.accounts_event_history && !current.equivalent_accounting_history(old) { + return None; + } + // The joined events are published results. Resumption always starts + // from a live checkpoint, whose original shared allocations stay intact. let mut events = current.events.clone().into_vec(); events.extend_from_slice(tail); Some(Execution { @@ -145,6 +150,7 @@ impl EntryCheckpoint { outgoing_state: completed.outgoing_state, steps: completed.steps, reads_event_history: false, + accounts_event_history: completed.accounts_event_history, }) } } @@ -219,6 +225,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { writing, stack_peaks, alignment_balance, + accounts_event_history, ], [ inputs, diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 4e5c38c..548bb75 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -25,7 +25,7 @@ impl Executor { } // Packing can move existing lists or replace an old register. Recount // actual storage here, counting each shared list allocation once. - self.reads_event_history = true; + self.accounts_event_history = true; let usage = self.collect_usage(shipping, None, Collector::for_capacity()); self.material_charge = usage .active_material @@ -41,7 +41,7 @@ impl Executor { shipping: Option<&NativeBox>, host: Option, ) -> ResourceUsage { - self.reads_event_history = true; + self.accounts_event_history = true; self.collect_usage(shipping, host, Collector::default()) } @@ -49,8 +49,19 @@ impl Executor { &self, shipping: Option<&NativeBox>, host: Option, - mut c: Collector, + c: Collector, ) -> ResourceUsage { + let mut c = self.collect_live_usage(shipping, host, c); + Self::collect_event_usage(self.events.iter(), &mut c); + c.usage + } + + fn collect_live_usage( + &self, + shipping: Option<&NativeBox>, + host: Option, + mut c: Collector, + ) -> Collector { self.state.collect_statistics(&mut c); c.usage.steps = self.steps; c.usage.source_files = self.sources.len(); @@ -122,7 +133,11 @@ impl Executor { InputFrame::Boundary => {} } } - for e in self.events.iter() { + c + } + + fn collect_event_usage<'a>(events: impl Iterator, c: &mut Collector) { + for e in events { if matches!(e, Event::Statistics(_)) { continue; } @@ -164,8 +179,30 @@ impl Executor { _ => {} } } - c.usage } + + pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool { + // These containers may reintroduce previously retained allocations + // that are outside the accounting walk at this boundary. + let fully_visited = |engine: &Self| { + engine.state.pdf_forms.is_empty() + && engine.native_page.as_ref().is_none_or(|page| page.insertions.held.is_empty()) + }; + if !fully_visited(self) || !fully_visited(old) { + return false; + } + + [Collector::for_capacity, Collector::default].into_iter().all(|collector| { + let mut history = collector(); + let mut old_history = collector(); + Self::collect_event_usage(self.events.iter(), &mut history); + Self::collect_event_usage(old.events.iter(), &mut old_history); + let live = self.collect_live_usage(None, None, collector().tracking_aliases()); + let old_live = old.collect_live_usage(None, None, collector().tracking_aliases()); + live.has_equivalent_history(&old_live, &history, &old_history) + }) + } + pub(super) fn statistics_before_shipout( &mut self, b: &NativeBox, diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index c1433bf..de20027 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -671,6 +671,8 @@ pub struct Execution { pub steps: usize, #[serde(default, skip_serializing_if = "std::ops::Not::not")] reads_event_history: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + accounts_event_history: bool, } #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 731b52d..790b678 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1466,14 +1466,24 @@ impl State { return; } c.usage.state.command_entries = self.commands.by_name.len(); - for (name, meaning) in &self.commands.by_name { - if let CommandName::Control(name) = name.as_ref() { + let track_aliases = c.tracks_aliases(); + let mut visit_command = |name: &CommandName, meaning: &Meaning| { + if let CommandName::Control(name) = name { c.usage.state.control_name_bytes += name.len(); } if let Meaning::Macro(macro_definition) = meaning { c.usage.state.macro_bindings += 1; c.macro_body(macro_definition); } + }; + if track_aliases { + for (name, meaning) in self.commands.ordered() { + visit_command(name, meaning); + } + } else { + for (name, meaning) in &self.commands.by_name { + visit_command(name, meaning); + } } c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len(); c.usage.state.parameter_entries = diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 0135a30..a323623 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -1,6 +1,9 @@ //! Measured native storage and execution resources, not invented TeX arena words. use super::*; -use std::{collections::BTreeSet, sync::Arc}; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MaterialUsage { @@ -147,12 +150,34 @@ pub(super) enum Ownership { Active, Retained, } +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Allocation { + Macro(usize), + Tokens(usize, usize), + Material(usize), +} + +#[derive(Default)] +struct AliasVisits { + ordinals: BTreeMap, + visits: Vec<(Allocation, usize)>, +} + +impl AliasVisits { + fn record(&mut self, allocation: Allocation) { + let next = self.ordinals.len(); + let ordinal = *self.ordinals.entry(allocation).or_insert(next); + self.visits.push((allocation, ordinal)); + } +} + #[derive(Default)] pub(super) struct Collector { pub usage: ResourceUsage, macros: BTreeSet, token_lists: BTreeSet<(usize, usize)>, shared_lists: Option>, + aliases: Option, } impl Collector { pub fn for_capacity() -> Self { @@ -162,12 +187,61 @@ impl Collector { } } + pub(super) fn tracking_aliases(mut self) -> Self { + self.aliases = Some(AliasVisits::default()); + self + } + + pub(super) fn tracks_aliases(&self) -> bool { + self.aliases.is_some() + } + + fn tracks_allocation(&mut self, allocation: Allocation) { + if let Some(aliases) = &mut self.aliases { + aliases.record(allocation); + } + } + + fn contains(&self, allocation: Allocation) -> bool { + match allocation { + Allocation::Macro(address) => self.macros.contains(&address), + Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)), + Allocation::Material(address) => self + .shared_lists + .as_ref() + .is_some_and(|lists| lists.contains(&address)), + } + } + + /// Check the live allocation correspondence and each allocation's + /// membership in the retained history. Counting a later event can + /// encounter older storage only through these surviving references. + pub(super) fn has_equivalent_history( + &self, + other: &Self, + history: &Self, + old_history: &Self, + ) -> bool { + let a = &self.aliases.as_ref().expect("live alias traversal").visits; + let b = &other.aliases.as_ref().expect("live alias traversal").visits; + self.usage == other.usage + && history.usage == old_history.usage + && a.len() == b.len() + && a.iter().zip(b).all(|(&(new, ni), &(old, oi))| { + ni == oi + && std::mem::discriminant(&new) == std::mem::discriminant(&old) + && history.contains(new) == old_history.contains(old) + }) + } + pub(super) fn material_only(&self) -> bool { self.shared_lists.is_some() } pub fn macro_body(&mut self, m: &Arc) { - if self.macros.insert(Arc::as_ptr(m) as usize) { + let address = Arc::as_ptr(m) as usize; + self.tracks_allocation(Allocation::Macro(address)); + if self.macros.insert(address) { self.usage.unique_macro_bodies += 1; self.usage.macro_token_cells += m.prefix.len() + m.parameters.iter().map(Vec::len).sum::() @@ -175,7 +249,11 @@ impl Collector { } } pub fn shared_tokens(&mut self, t: &Arc<[Token]>) { - if self.token_lists.insert((t.as_ptr() as usize, t.len())) { + let address = t.as_ptr() as usize; + if !t.is_empty() { + self.tracks_allocation(Allocation::Tokens(address, t.len())); + } + if self.token_lists.insert((address, t.len())) { self.usage.token_list_cells += t.len(); } } @@ -312,9 +390,13 @@ impl Collector { self.usage.active_material.ligature_work_items += b.ligature_work_items(); } fn visit_shared(&mut self, list: &Arc) -> bool { - self.shared_lists.as_mut().is_none_or(|seen| { - seen.insert(Arc::as_ptr(list).cast::<()>() as usize) - }) + let address = Arc::as_ptr(list).cast::<()>() as usize; + if self.shared_lists.is_some() { + self.tracks_allocation(Allocation::Material(address)); + } + self.shared_lists + .as_mut() + .is_none_or(|seen| seen.insert(address)) } pub fn shared_diagnostics( @@ -350,3 +432,32 @@ impl Collector { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn history_equivalence_keeps_aliases_that_cross_the_boundary() { + let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default()); + let first: Arc<[Token]> = Arc::from([token.clone()]); + let second: Arc<[Token]> = Arc::from([token.clone()]); + let unrelated: Arc<[Token]> = Arc::from([token]); + let collect = |tokens: &Arc<[Token]>, tracker: Collector| { + let mut collector = tracker; + collector.shared_tokens(tokens); + collector + }; + + let before = collect(&first, Collector::default()); + let after = collect(&second, Collector::default()); + assert_eq!(before.usage, after.usage); + let live = collect(&first, Collector::default().tracking_aliases()); + let independent = collect(&second, Collector::default().tracking_aliases()); + assert!(live.has_equivalent_history(&independent, &before, &after)); + + let detached = collect(&unrelated, Collector::default().tracking_aliases()); + assert!(detached.has_equivalent_history(&detached, &before, &after)); + assert!(!live.has_equivalent_history(&detached, &before, &after)); + } +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 9e4a4ed..330bcd9 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -15,9 +15,42 @@ | W3 页面与输出 | 实施中 | [S1原始列表](NATIVE_LISTS.md)、[S2真实vsplit/迁移marks](NATIVE_SPLITTING.md)、[S3原生page/output/shipout与延迟I/O](NATIVE_PAGES.md)及[S4a真实mag/true与逐页纸张/origin/offset](NATIVE_DEVICE.md)已验收;[S4b真实PDF配置/压缩/原始sp精度](NATIVE_PDF_CONFIG.md)已验收;[S4c真实PK字体设备](NATIVE_PK_FONTS.md)已验收;[S5a实际原生资源统计/分页诊断](NATIVE_STATISTICS_PAGE_TRACE.md)已验收;[S5b真实断行/零规格/普通脚本原生列表](NATIVE_PARAGRAPH_TRACE.md)已验收;其余tracing、插入列表与其余复杂数学field语义盒仍缺 | | W4 格式镜像 | 实施中 | 原样 pdflatex.ini 合法 dump 与七个独立加载作业已复验;实际 article 等价及完整退出条件仍待闭合 | | W5 article | 原语料集成已通过 | 七项各三轮(21 作业)全部成功,14 页;aux/引用、字体/墨迹、全部文字/词序/词框、原始几何及 glyph/rule 交错顺序 gate 均通过;不等于完整项目兼容或阶段结项 | -| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | +| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 保留材料统计与原样 NeurIPS 热编辑 + +输出例程返回后,内核分别核对节点容量和资源统计的实际计数, +以及运行中各分配项之间、与已发出事件之间的共享关系。两次执行 +的对应关系一致时,可保留当前编辑产生的事件并复用此前已经执行的后缀。 +后续恢复从原有的内核检查点开始。容量重算仍使用默认限制。 +已注册 PDF Form、持有的插入材料和直接读取早期页面绘制的作业 +继续走原执行路径。 + +原样 NeurIPS 2025 的 12 页 XeLaTeX 样稿在默认容量下编辑第 3 页。 +会话复用编辑前的 14,289,264 步,并在第 3 页的输出例程返回后跳过 +4,634,847 步。实际重执行从 5,281,627 步减至 646,780 步,减少 87.75%。 +复放 578 次宿主调用,断行求解从 288 次减至 30 次,只更新第 3 页。 +故障保留原发布,恢复原文执行 0 步,也只更新第 3 页。 + +两次成功修订的完整 Execution、PDF、SVG、绘制列表、来源映射、 +依赖和读取、查找与文件流、aux/out 及日志与独立全量一致。输入身份 +与上轮相同,四份 PDF/SVG 也与上轮归档逐字节相同。四项会话定向 +回归、七项资源统计回归和一项分配共享关系回归通过。一次库调用 +用时为普通编辑 1.206 s、恢复原文 0.484 s。固定规模项目的正式 +编辑到可见页面、冷启动和内存继续按原预算及样本量验收。 + +前两种未达到复用条件的实现和最初路径配置失败均留档。证据在 +target/p4-retained-history/,SHA256SUMS 指纹为 +e12dca893223008ad0272635fe4f09d947bc01bd003b8c95e8c1b75a082ef6ff。 + +下一处已定位的兼容差异来自原样 Wiley 双栏第 8 页。pdfTeX +在连字符换行后的下一行保留字体带来的 0.08499 pt 字距。当前 +最小样例仅保留显式字距与字体字距两种情况,定位到断行搜索与 +装盒均把两者当成可裁剪节点。下一批按两种 profile 的上游规则 +修正通用段落行为,用原样 Wiley 核对该页并保留其他页面一致性。 +[pdfTeX 断行语义](https://github.com/TeX-Live/texlive-source/blob/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/web2c/pdftexdir/pdftex.web#L22991-L23007) · [XeTeX 装盒语义](https://github.com/TeX-Live/texlive-source/blob/e49735c7ed1aa2ed9c2e68e6632d27f20d42eca7/texk/web2c/xetexdir/xetex.web#L19486-L19495) + ## 2026-11-29 输出例程返回后的后缀复用 自动会话在输出例程已返回的命令边界留存有限检查点。输入游标、 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index a27cc43..3ea74ca 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1580,7 +1580,9 @@ fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() let aux = cwd.join("job.aux"); let missing_aux = b"Opened\nMissing\n"; fs::write(&aux, missing_aux).unwrap(); + let material = r"\kern1sp".repeat(500); let body = |letter: char| format!(r" +\tracingstats=1 \shipout\hbox{{Cover ABC}} \setbox3=\hbox{{{letter}}} \shipout\box3 @@ -1595,6 +1597,11 @@ fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() \fi \closein2 \immediate\closeout1 +\setbox7=\vbox{{{material}}} +\def\repack{{\ifnum\count0<2050 \advance\count0 by1 + \setbox7=\vbox{{\unvbox7}}\expandafter\repack\fi}} +\repack +\setbox7=\box8 \shipout\hbox{{Unchanged}} \end "); @@ -1603,6 +1610,7 @@ fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() let mut project = ProjectSnapshot::new(definition).unwrap(); let mut request = request(&cwd).observe_generated_initial(); request.world = project.configuration(); + request.limits.steps = 2_000_000; let session = NativeCompiler::default().with_automatic_entry_checkpoints(); let mut previous = session.compile(request.clone().with_project(project.clone())).unwrap(); assert_eq!(previous.pages.len(), 3); @@ -1619,6 +1627,14 @@ fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() let current = request.clone().with_project(project.clone()); let updated = session.compile(current.clone()).unwrap(); let work = &updated.entry_checkpoint_work; + use texrra_tex_core::execution::{Event, StatisticsPhase}; + assert!(updated.execution.execution.events.iter().any(|event| { + let Event::Statistics(report) = event else { + return false; + }; + matches!(&report.phase, StatisticsPhase::End { usage, .. } + if usage.box_nodes_created > usage.token_limit) + })); if revision == 2 { assert!(work.reused_suffix_steps > 0, "{work:?}"); assert_eq!(work.discarded_suffix_attempt_steps, 0);