From 6acd82dbfafb5476e336cfb97bb7f4f48f414251 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 1 Dec 2026 21:42:04 +0800 Subject: [PATCH] Reuse native checkpoints before source length changes --- .../texrra-tex-core/src/execution/engine.rs | 27 +++++- .../src/execution/engine/statistics.rs | 18 ++++ crates/texrra-tex-core/src/execution/mod.rs | 5 ++ .../src/execution/statistics.rs | 31 +++++++ docs/P2_M1_PROGRESS.md | 21 +++++ src/native_checkpoint_probe.rs | 34 +++++++- src/native_job.rs | 4 + tests/native_pipeline.rs | 86 +++++++++++++++++++ 8 files changed, 222 insertions(+), 4 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 8522089..be9ae99 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -366,8 +366,8 @@ impl EntryCheckpoint { && self.executor.sources[self.entry].name == earlier.executor.sources[earlier.entry].name && self.source_mouth(self.entry) .same_loaded_prefix_constraint(earlier.source_mouth(earlier.entry)) - && (!self.executor.reads.observed_statistics() - || (earlier.executor.reads.observed_statistics() + && (self.can_resize_entry() + || (!earlier.can_resize_entry() && self.executor.sources[self.entry].data.len() == earlier.executor.sources[earlier.entry].data.len())) } @@ -380,7 +380,20 @@ impl EntryCheckpoint { let entry = &self.executor.sources[self.entry]; // A suspended scanner may only accept unchanged bytes when its // boundary cannot be authenticated as a physical line. - entry.name == name && (entry.data == data || self.matches_scanned_source(self.entry, data)) + entry.name == name + && (entry.data == data + || ((entry.data.len() == data.len() || self.can_resize_entry()) + && self.source_mouth(self.entry).matches_loaded_prefix(data))) + } + + fn can_resize_entry(&self) -> bool { + // At each retained shipout, the original entry is still the bottom + // source frame. Reject ambiguous accounting if it also opened as + // another source before this checkpoint. + !self.executor.reads.observed_statistics() + || self.executor.sources.iter().filter(|source| { + source.name == self.executor.sources[self.entry].name + }).take(2).count() == 1 } pub fn entry_frontier(&self) -> usize { @@ -487,6 +500,14 @@ impl EntryCheckpoint { } let mut executor = self.executor.clone().with_cancellation(cancellation); executor.line_break_cache = line_break_cache; + let previous_len = self.executor.sources[self.entry].data.len(); + let current_len = source.data.len(); + if previous_len != current_len + && self.executor.reads.observed_statistics() + && executor.resize_entry_statistics(previous_len, current_len, files.replayed_entry_bytes()).is_none() + { + return Ok(None); + } executor.rebind_checkpoint_source(self.entry, source); if let Some(nested) = nested { executor.rebind_checkpoint_source(self.active_source, nested); diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 688ddf9..87d8b64 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -181,6 +181,24 @@ impl Executor { } } + pub(super) fn resize_entry_statistics( + &mut self, + previous: usize, + current: usize, + replayed_entry_bytes: Option, + ) -> Option<()> { + let events = self.events.prefix.iter_mut() + .filter(|chunk| chunk.iter().any(|event| matches!(event, Event::Statistics(_)))) + .flat_map(|chunk| Arc::make_mut(chunk).iter_mut()) + .chain(&mut self.events.tail); + for event in events { + if let Event::Statistics(report) = event { + report.resize_entry_payload(previous, current, replayed_entry_bytes)?; + } + } + Some(()) + } + 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. diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index be0193b..f3abe94 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -376,6 +376,11 @@ pub trait SourceProvider { ) -> Result<(), String> { Ok(()) } + /// Size of the entry read already validated by the host's prefix replay. + /// Hosts that report resource telemetry can opt in to resizing that read. + fn replayed_entry_bytes(&self) -> Option { + None + } /// Observe resource accounting while preserving the typed report for replay. fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> { self.observe_diagnostic(report.destination, &report.text) diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 576195a..8d50366 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -81,6 +81,11 @@ pub struct HostResourceUsage { pub open_outputs: Option, } impl HostResourceUsage { + pub fn rebind_entry_bytes(&mut self, previous: u64, current: u64) -> Option<()> { + self.resource_bytes_read = self.resource_bytes_read.checked_sub(previous)?.checked_add(current)?; + Some(()) + } + pub fn from_trace(trace: &crate::resources::ResourceTrace) -> Self { Self { lookups: trace.lookups.len(), @@ -172,6 +177,32 @@ impl StatisticsReport { Self { phase, destination, text, span } } + pub(super) fn resize_entry_payload( + &mut self, + previous: usize, + current: usize, + replayed_entry_bytes: Option, + ) -> Option<()> { + // Closeout reports are produced only after resuming, never captured + // in an executable prefix. Shipout text does not print byte totals. + let StatisticsPhase::Shipout { before, after } = &mut self.phase else { + return None; + }; + for usage in [before, after] { + usage.source_payload_bytes = usage.source_payload_bytes.checked_sub(previous)?.checked_add(current)?; + usage.mouth_payload_bytes = usage.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?; + if let Some(host) = &mut usage.host { + let size = u64::try_from(current).ok()?; + if replayed_entry_bytes != Some(size) { + return None; + } + host.rebind_entry_bytes(u64::try_from(previous).ok()?, size)?; + } + } + debug_assert_eq!(self.text, self.phase.text()); + Some(()) + } + pub fn with_step_offset(&self, offset: StepOffset) -> Option { let mut phase = self.phase.clone(); match &mut phase { diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 3969748..eaf9144 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,27 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-12-01 源码增删后复用已执行的前缀 + +原生会话校验入口已装载的物理行和前缀字节。改动留在未读部分时, +可以恢复已经出页的检查点。历史出页统计使用当前入口字节数重算 +源码、扫描缓冲区及首次宿主读取的计数。其余资源、输入流和输出 +操作仍逐项核验。若正文已通过 `\pdffilesize` 读取入口大小, +文件长度改变会使该检查点失效,查询从较早边界重新执行。 + +优化构建与七项定向回归通过,包含插入、删除、显式大小查询,以及 +原有后缀复用和资源核验。12 页 NeurIPS 样稿保留原始文件,项目 +快照另加一行 `\tracingstats=2` 以覆盖全部 12 次出页统计。在第 9 页 +先插入 5 字节,再删除 6 字节,分别从第 621、644 行恢复。 +实际重新执行 1,966,711 和 1,733,850 步,分别约占同版本全量的 +10.0% 和 8.9%。两次都只发布第 9 页的预览更新。完整执行、PDF、 +显示列表、SVG、来源映射、资源与流轨迹,以及 aux、out、log +都与独立全量一致。证据在 `target/p4-resized-entry-prefix/`。 + +异长编辑后仍执行剩余输入。下一步以字节一致的物理行验证会合, +将旧后缀内已核实的来源区间映射至当前入口坐标,并用独立全量核对。 +正式兼容性矩阵、可见时延及内存报告继续按产品目标验收。 + ## 2026-12-01 逻辑步数变化后复用已核验的后缀 会合时用当前已完成步数加上旧后缀实际执行的步数。全程保留原有 diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 3caf1ee..1a458be 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -17,6 +17,7 @@ pub(super) enum Call { ReadSource(Arc), FileSize(Arc), EndStatistics(Arc), + ResourceUsage(Arc), } pub(super) struct SourceRead { @@ -32,6 +33,11 @@ pub(super) struct SizeRead { read: Option, } +pub(super) struct ResourceUsageRead { + observed: Option, + entry_bytes: Option, +} + pub(super) struct RebindableSourceObservations { pub(super) size: Option, } @@ -47,6 +53,22 @@ impl Call { match self { Self::Checked(call) => call(files), Self::EndStatistics(report) => files.observe_statistics(report), + Self::ResourceUsage(read) => { + let mut expected = read.observed.clone(); + if let (Some(usage), Some(previous), Some(current)) = + (&mut expected, read.entry_bytes, files.replayed_entry_bytes()) + { + // The first read was the verified entry. All other + // resource and stream observations are still exact. + usage.rebind_entry_bytes(previous, current) + .ok_or("invalid replayed entry resource usage")?; + } + let actual = files.resource_usage()?; + if actual != expected { + return Err(format!("resource usage changed: expected {expected:?}, observed {actual:?}")); + } + Ok(()) + } Self::FileSize(read) => { let before = files.resource_trace().reads.len(); let observed = files.file_size(&read.name, &read.from); @@ -238,8 +260,18 @@ impl SourceProvider for RecordingHost<'_> { fn set_interaction_mode(&mut self, mode: u8) -> Result<(), String> { call!(self, set_interaction_mode(mode)) } + fn replayed_entry_bytes(&self) -> Option { + self.files.replayed_entry_bytes() + } fn resource_usage(&mut self) -> Result, String> { - call!(self, resource_usage()) + let observed = self.files.resource_usage()?; + if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS { + calls.push(Call::ResourceUsage(Arc::new(ResourceUsageRead { + observed: observed.clone(), + entry_bytes: self.files.replayed_entry_bytes(), + }))); + } + Ok(observed) } fn read(&mut self, name: &str, from: &str) -> Result { let result = self.files.read_versioned_source(name, from); diff --git a/src/native_job.rs b/src/native_job.rs index c1dbc26..7bd516e 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -1634,6 +1634,10 @@ impl SourceProvider for Files { Some(self.world.trace()) } + fn replayed_entry_bytes(&self) -> Option { + self.world.trace().reads.first().map(|read| read.bytes) + } + fn resource_usage( &mut self, ) -> Result, String> { diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 273a769..ed1c822 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1761,6 +1761,92 @@ fn settled_suffix_carries_a_verified_prefix_into_later_edits() { fs::remove_dir_all(cwd).unwrap(); } +#[test] +fn resized_entry_prefix_reuses_verified_statistics() { + let cwd = directory("resized-entry-statistics"); + let entry = cwd.join("main.tex"); + let stable = r" +\tracingstats=2 +\shipout\hbox{Cover}\relax +\shipout\hbox{Second}\relax +\shipout\hbox{Third}\relax +"; + let body = |text| format!(r"{stable} +\shipout\hbox{{{text}}}\relax +\shipout\hbox{{Last}}\relax +\end +"); + let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body("Late"))).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + session.compile(request.clone().with_project(project.clone())).unwrap(); + + for (revision, text) in [(2, "Later"), (3, "Now")] { + let source = format!("{HEADER}{}", body(text)); + let after_first_shipout = source.find(r"\shipout\hbox{Second}").unwrap(); + project = project + .with_file_edits(revision, [(entry.clone(), Arc::from(source.into_bytes()))].into()) + .unwrap(); + let input = request.clone().with_project(project.clone()); + let updated = session.compile(input.clone()).unwrap(); + let work = &updated.entry_checkpoint_work; + assert!( + work.reused_frontier.is_some_and(|frontier| frontier >= after_first_shipout), + "{work:?}" + ); + assert!(work.reused_steps > 0, "{work:?}"); + + let log = fs::read(cwd.join("job.log")).unwrap(); + let full = NativeCompiler::default().compile(input).unwrap(); + assert_eq!(updated.execution.execution, full.execution.execution); + assert_eq!(updated.resources.trace, full.resources.trace); + assert_eq!(updated.pdf, full.pdf); + assert_eq!(updated.source_map.sources, full.source_map.sources); + assert_eq!(updated.source_map.pages, full.source_map.pages); + assert_eq!(log, fs::read(cwd.join("job.log")).unwrap()); + } + fs::remove_dir_all(cwd).unwrap(); +} + +#[test] +fn resized_entry_prefix_invalidates_an_executed_file_size_query() { + let cwd = directory("resized-entry-file-size"); + let entry = cwd.join("main.tex"); + let body = |text| format!(r" +\shipout\hbox{{Cover}}\relax +\count42=\pdffilesize{{main.tex}}\relax +\tracingstats=2 +\shipout\hbox{{\the\count42}}\relax +\shipout\hbox{{{text}}}\relax +\end +"); + let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body("Late"))).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let initial = session.compile(request.clone().with_project(project.clone())).unwrap(); + + let source = format!("{HEADER}{}", body("Later")); + let query = source.find(r"\count42=").unwrap(); + let query_end = query + source[query..].find('\n').unwrap() + 1; + assert!(initial.entry_checkpoint_work.captured_frontier.is_some_and(|frontier| frontier > query_end)); + let bytes = i32::try_from(source.len()).unwrap(); + let project = project + .with_file_edits(2, [(entry, Arc::from(source.into_bytes()))].into()) + .unwrap(); + let request = request.with_project(project); + let updated = session.compile(request.clone()).unwrap(); + let full = NativeCompiler::default().compile(request).unwrap(); + let work = &updated.entry_checkpoint_work; + assert!(work.reused_frontier.is_none_or(|frontier| frontier <= query_end), "{work:?}"); + assert_eq!(updated.execution.execution.state.count(42), bytes); + assert_eq!(updated.execution.execution, full.execution.execution); + assert_eq!(updated.resources.trace, full.resources.trace); + assert_eq!(updated.pdf, full.pdf); + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn settled_suffix_translates_step_counts_and_enforces_the_limit() { let cwd = directory("settled-step-counts");