From e3be6dcd091f518f978baf796995a7c41eb1659e Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 01:54:35 +0800 Subject: [PATCH] Reuse native checkpoints for unread stream changes --- docs/P2_M1_PROGRESS.md | 18 +++++++++ src/native_checkpoint_guard.rs | 64 +++++++++++++++++++++++------ tests/native_pipeline.rs | 73 ++++++++++++++++++++++++++++++++++ 3 files changed, 142 insertions(+), 13 deletions(-) diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 700032a..675672c 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,24 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 按流输入的已读范围恢复检查点 + +检查点区分完整文件消费与逐行流输入。只从流读取一部分时,按实际已观察 +字节验证前缀,恢复时重放宿主调用,再核对读取范围、查找结果和文件结尾。 +如果同一文件曾被完整读取、查询修改时间或读到文件结尾,仍验证完整版本。 +更改实际读过的字节时回退到更早的检查点。 + +使用实际 pdflatex 格式和 article 类的两页项目外置正文流。两次修改第二页 +正文,分别将重执行从 912,893 步降至 62,292 步,从 912,931 步降至 +62,330 步。两次都复用 850,601 步并仅刷新第 2 页。两个版本的 PDF、SVG、 +来源映射、aux 和归一化日志与修改前内核对照一致,末版另从同一生成初态 +独立全量编译核对。三项定向回归通过,覆盖修改未读字节、追加已在后页观察 +文件结尾的输入、修改已读首行,以及既有末行出页检查点和拒绝重放后的回退。 + +回执在 target/p4-stream-prefix-reuse/。本轮数据覆盖外部正文流。 +原样 A4 主文件的浏览器时延及出版模板矩阵仍待统一验收。后续开发优先 +补齐真实项目阻塞的数学与表格、浮动与分页、图形与字体能力。 + ## 2026-11-29 末行出页检查点与出页后依赖 入口最后一条物理行读入后,可以在真实出页处保存检查点。同一物理位置 diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index cbddcbc..af64dcc 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -2,15 +2,15 @@ use super::checkpoint_probe::{Call, RecordingHost}; use super::*; #[cfg(test)] -use std::{collections::BTreeMap, fs}; +use std::fs; use std::{ - collections::{BTreeSet, VecDeque}, + collections::{BTreeMap, BTreeSet, VecDeque}, ffi::OsString, path::Path, }; use texrra_tex_core::{ execution::EntryCheckpoint, - resources::{ResourceKind, ResourceLookup}, + resources::{ResourceKind, ResourceLookup, ResourceReadRange}, }; #[cfg(test)] use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy}; @@ -463,13 +463,7 @@ impl PublishedCheckpoints { continue 'retry; } } - if !checkpoint - .guard - .project - .immutable_paths() - .eq(project.immutable_paths()) - && let Err(error) = checkpoint.guard.verify_replayed_lookups(&prepared.files) - { + if let Err(error) = checkpoint.guard.verify_replayed_inputs(&prepared.files, project) { replay_rejection.get_or_insert(error); continue; } @@ -644,8 +638,10 @@ struct PrefixInputGuard { initial: GeneratedInitialState, entry: PathBuf, immutable: BTreeSet, + immutable_stream_prefixes: BTreeMap, generated: BTreeSet, lookups: Vec, + stream_reads: Vec, format_input_bindings: BTreeMap, clock_environment: Option<[Option; 3]>, } @@ -720,14 +716,40 @@ impl PrefixInputGuard { } immutable.insert(observed.path.clone()); } + // A stream can have unconsumed bytes even though the host pinned a + // complete buffer. Whole-file consumers, dates and observed EOF + // still require the immutable input version. + let whole_files: BTreeSet<_> = trace + .reads + .iter() + .map(|version| version.path.as_path()) + .chain(trace.file_modifications.iter().map(|item| item.path.as_path())) + .chain(trace.stream_reads.iter().filter(|item| item.eof).map(|item| item.path.as_path())) + .collect(); + let mut immutable_stream_prefixes = BTreeMap::::new(); + for range in &trace.stream_reads { + if !immutable.contains(&range.path) || whole_files.contains(range.path.as_path()) { + continue; + } + let end = range + .offset + .checked_add(range.bytes) + .and_then(|end| usize::try_from(end).ok()) + .filter(|&end| project.file(&range.path).is_some_and(|file| end <= file.data.len())) + .ok_or("checkpoint stream range exceeds its captured input")?; + let prefix = immutable_stream_prefixes.entry(range.path.clone()).or_default(); + *prefix = (*prefix).max(end); + } Ok(Self { original: AttemptRequest::from(request), project: project.clone(), initial, entry: entry.to_path_buf(), immutable, + immutable_stream_prefixes, generated, lookups: trace.lookups.clone(), + stream_reads: trace.stream_reads.clone(), format_input_bindings: trace.format_input_bindings.clone(), clock_environment: (!trace.file_modifications.is_empty()).then(date_environment), }) @@ -759,9 +781,15 @@ impl PrefixInputGuard { return Err("checkpoint lookup configuration changed".into()); } for path in &self.immutable { - let old = self.project.file(path).map(|file| &file.version); - let new = current.file(path).map(|file| &file.version); - if old != new || self.project.modification_time(path) != current.modification_time(path) + let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and( + |(old, new)| { + old.version == new.version + || self.immutable_stream_prefixes.get(path).is_some_and(|&end| { + new.data.get(..end) == Some(&old.data[..end]) + }) + }, + ); + if !same_bytes || self.project.modification_time(path) != current.modification_time(path) { return Err(format!( "checkpoint observed input changed: {}", @@ -779,6 +807,16 @@ impl PrefixInputGuard { Ok(current) } + fn verify_replayed_inputs(&self, files: &Files, current: &ProjectSnapshot) -> Result<(), CompileError> { + if files.resource_trace().stream_reads != self.stream_reads { + return Err(CompileError::Host("checkpoint replayed stream reads changed".into())); + } + if !self.project.immutable_paths().eq(current.immutable_paths()) { + self.verify_replayed_lookups(files)?; + } + Ok(()) + } + fn verify_replayed_lookups(&self, files: &Files) -> Result<(), CompileError> { let trace = files.resource_trace(); if trace.lookups != self.lookups diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index aebc16b..5db5360 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1344,6 +1344,79 @@ fn xetex_glyph_bounds_and_dash_breaks_follow_revision_local_parameters() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() { + let p = directory("stream-prefix-page"); + let padding = "\\relax ".repeat(36); + let body = format!( + r" +\openin1=flow.dat \readline1 to\headline +{padding} +\shipout\hbox{{\headline}} +{padding} +\readline1 to\bodyline \readline1 to\lastline +\ifeof1 \def\lastline{{End of input}}\fi +\shipout\hbox{{\bodyline\ \lastline}} +\closein1 \end +" + ); + let input = p.join("flow.dat"); + let mut definition = atomic_definition(&p, 1, &body); + definition.files.insert( + input.clone(), + Arc::from(b"Stable heading\nOriginal body\n".as_slice()), + ); + let mut project = ProjectSnapshot::new(definition).unwrap(); + let mut request = request(&p); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let mut published = session + .compile(request.clone().with_project(project.clone())) + .unwrap(); + assert_eq!(published.pages.len(), 2); + assert!(published.resources.trace.stream_reads.iter().any(|read| read.eof)); + + for (revision, bytes, reused_pages, expected_change) in [ + (2, b"Stable heading\nEdited body with more text\n".as_slice(), 1, [1]), + (3, b"Stable heading\nEdited body with more text\nAppendix\n".as_slice(), 1, [1]), + (4, b"Edited heading\nEdited body with more text\nAppendix\n".as_slice(), 0, [0]), + ] { + project = project + .with_file_edits(revision, [(input.clone(), Arc::from(bytes))].into()) + .unwrap(); + let request = request.clone().with_project(project.clone()); + let resumed = session.compile(request.clone()).unwrap(); + let work = &resumed.entry_checkpoint_work; + assert_eq!(resumed.shipout_layout_work.reused_pages, reused_pages, "{work:?}"); + assert_eq!(resumed.shipout_layout_work.lowered_pages, 2 - reused_pages); + let changed: Vec<_> = resumed + .preview_since(Some(published.revision())) + .unwrap() + .pages + .into_iter() + .map(|page| page.index) + .collect(); + assert_eq!(changed, expected_change); + let log = fs::read(p.join("job.log")).unwrap(); + let full = NativeCompiler::default().compile(request).unwrap(); + assert_eq!(resumed.execution.execution, full.execution.execution); + assert_eq!(resumed.resources.trace, full.resources.trace); + assert_eq!(resumed.resources.stream_io, full.resources.stream_io); + assert_eq!(resumed.pdf, full.pdf); + assert_eq!(resumed.pages, full.pages); + assert_eq!(resumed.source_map.sources, full.source_map.sources); + assert_eq!(resumed.source_map.pages, full.source_map.pages); + assert_eq!( + resumed.preview_since(None).unwrap().pages, + full.preview_since(None).unwrap().pages + ); + assert_eq!(log, fs::read(p.join("job.log")).unwrap()); + eprintln!("revision={revision} {work:?} layout={:?} changed={changed:?}", resumed.shipout_layout_work); + published = resumed; + } + fs::remove_dir_all(p).unwrap(); +} + #[test] fn checkpoint_reuses_shipouts_when_late_inputs_share_the_final_entry_line() { let p = directory("shared-final-line");