From 84ad68293924d2e1949b419df475e375eb492ac6 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 06:04:51 +0800 Subject: [PATCH] Resume validated native checkpoints inside included sources --- .../src/execution/dependency_reads.rs | 4 + .../texrra-tex-core/src/execution/engine.rs | 141 +++++++++--- crates/texrra-tex-core/src/execution/mod.rs | 2 +- .../texrra-tex-core/src/execution/session.rs | 36 +++- docs/P2_M1_PROGRESS.md | 25 +++ src/native_checkpoint_guard.rs | 203 ++++++++++++++---- src/native_checkpoint_probe.rs | 133 ++++++++++-- tests/native_pipeline.rs | 81 +++++++ 8 files changed, 537 insertions(+), 88 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/dependency_reads.rs b/crates/texrra-tex-core/src/execution/dependency_reads.rs index 2db6984..b8415b4 100644 --- a/crates/texrra-tex-core/src/execution/dependency_reads.rs +++ b/crates/texrra-tex-core/src/execution/dependency_reads.rs @@ -26,6 +26,10 @@ impl DependencyReads { } } + pub(super) fn observed_statistics(&self) -> bool { + self.other.contains(&Dependency::ResourceStatistics) + } + pub(super) fn into_ordered(self) -> BTreeSet { let byte_catcodes = (0..=u8::MAX) .filter(|&index| { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index cd082e2..6422abe 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -305,12 +305,22 @@ impl Default for Executor { } } +/// Physical position available for a continuation at a command boundary. +pub struct CheckpointSource<'a> { + pub id: usize, + pub name: &'a str, + pub bytes: usize, + pub frontier: usize, + pub is_entry: bool, +} + /// A live, in-memory kernel continuation at an entry-file command boundary. /// The host must validate dependencies and replay all prefix effects before /// resumption. The checkpoint itself validates the entry bytes already loaded. pub struct EntryCheckpoint { executor: Executor, entry: usize, + active_source: usize, initial_depth: usize, incoming_state: u64, frontier: usize, @@ -331,10 +341,42 @@ impl EntryCheckpoint { } pub fn accepts_entry_bytes(&self, name: &str, data: &[u8]) -> bool { - let Some(InputFrame::Source { mouth, .. }) = self.executor.inputs.first() else { - unreachable!("entry checkpoints start with the physical source frame"); - }; - self.executor.sources[self.entry].name == name && mouth.matches_loaded_prefix(data) + 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)) + } + + pub fn entry_frontier(&self) -> usize { + self.source_mouth(self.entry).physical_frontier().unwrap_or(0) + } + + pub fn nested_source_id(&self) -> Option { + (self.active_source != self.entry).then_some(self.active_source) + } + + pub fn nested_source(&self) -> Option<&str> { + (self.active_source != self.entry) + .then(|| self.executor.sources[self.active_source].name.as_str()) + } + + pub fn accepts_nested_source(&self, name: &str, data: &[u8]) -> bool { + self.nested_source() == Some(name) + && self.matches_scanned_source(self.active_source, data) + } + + fn matches_scanned_source(&self, id: usize, data: &[u8]) -> bool { + // A statistics event can already include the complete source length. + (self.executor.sources[id].data.len() == data.len() + || !self.executor.reads.observed_statistics()) + && self.source_mouth(id).matches_loaded_prefix(data) + } + + fn source_mouth(&self, id: usize) -> &Mouth { + self.executor.inputs.iter().rev().find_map(|frame| match frame { + InputFrame::Source { source, mouth, .. } if *source == id => Some(mouth), + _ => None, + }).expect("checkpoint retains the active scanner") } pub fn resume_after_host_replay( @@ -343,21 +385,23 @@ impl EntryCheckpoint { files: &mut impl SourceProvider, cancellation: Cancellation, ) -> Option> { - self.resume_observed(source, files, cancellation, None, None, |_, _, _, _| {}) + self.resume_observed(source, None, files, cancellation, None, None, |_, _, _, _| {}) } - pub(super) fn resume_capturing_entries_after_host_replay( + pub(super) fn resume_capturing_sources_after_host_replay( &self, source: SourceFile, + nested: Option, files: &mut F, cancellation: Cancellation, line_break_cache: std::sync::Arc, previous: Option<&Execution>, - select: impl FnMut(usize, usize) -> Option, + select: impl FnMut(CheckpointSource<'_>, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Option> { self.resume_observed( source, + nested, files, cancellation, Some(line_break_cache), @@ -369,22 +413,27 @@ impl EntryCheckpoint { fn resume_observed( &self, source: SourceFile, + nested: Option, files: &mut F, cancellation: Cancellation, line_break_cache: Option>, previous: Option<&Execution>, capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F), ) -> Option> { - if !self.accepts_entry(&source) { + if !self.accepts_entry(&source) + || match &nested { + Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data), + None => self.nested_source().is_some(), + } + { return None; } let mut executor = self.executor.clone().with_cancellation(cancellation); executor.line_break_cache = line_break_cache; - let Some(InputFrame::Source { mouth, .. }) = executor.inputs.first_mut() else { - unreachable!("entry checkpoints start with the physical source frame"); - }; - mouth.rebind_loaded_prefix(source.data.clone()); - executor.sources[self.entry] = Arc::new(source); + executor.rebind_checkpoint_source(self.entry, source); + if let Some(nested) = nested { + executor.rebind_checkpoint_source(self.active_source, nested); + } let result = executor .check_cancellation() .and_then(|_| { @@ -401,6 +450,17 @@ impl EntryCheckpoint { } impl Executor { + fn rebind_checkpoint_source(&mut self, id: usize, file: SourceFile) { + let mouth = self.inputs.iter_mut().rev().find_map(|frame| match frame { + InputFrame::Source { source, mouth, .. } if *source == id => Some(mouth), + _ => None, + }).expect("checkpoint retains the active scanner"); + if self.sources[id].as_ref() != &file { + mouth.rebind_loaded_prefix(file.data.clone()); + self.sources[id] = Arc::new(file); + } + } + pub fn with_byte_translation(mut self, table: ByteTranslation) -> Self { self.state.byte_translation = Some(Arc::new(table)); self @@ -3749,10 +3809,24 @@ impl Executor { /// Observe eligible boundaries during normal execution. Only clone the /// state when the caller selects a boundary, giving it its matching host. pub fn run_capturing_entries( + self, + file: SourceFile, + files: &mut F, + mut select: impl FnMut(usize, usize) -> Option, + capture: impl FnMut(S, EntryCheckpoint, &mut F), + ) -> Result { + self.run_capturing_sources( + file, files, + |source, pages| source.is_entry.then(|| select(source.frontier, pages)).flatten(), + capture, + ) + } + + pub fn run_capturing_sources( mut self, file: SourceFile, files: &mut F, - select: impl FnMut(usize, usize) -> Option, + select: impl FnMut(CheckpointSource<'_>, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Result { let incoming_state = self.state.fingerprint(); @@ -3766,7 +3840,7 @@ impl Executor { fn entry_observer( incoming_state: u64, - mut select: impl FnMut(usize, usize) -> Option, + mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option, mut capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> impl FnMut(&mut Self, usize, bool, &mut F) { move |engine, initial_depth, pages_processed, files| { @@ -3774,35 +3848,39 @@ impl Executor { return; } let Some(InputFrame::Source { - source, - mouth, - eof_seen: false, - pseudo_trace: None, - .. + source: entry, eof_seen: false, pseudo_trace: None, .. }) = engine.inputs.first() else { return; }; + // Retain the active scanner plus its suspended parents. A pseudo + // input or an EOF hook has no replaceable physical byte prefix. + let Some(InputFrame::Source { + source, mouth, eof_seen: false, pseudo_trace: None, .. + }) = engine.inputs.iter().rev().find(|frame| matches!(frame, InputFrame::Source { .. })) + else { + return; + }; let Some(frontier) = mouth.physical_frontier() else { return; }; - // Keep the active macro and argument cursors, but a second - // physical source would have an independent unread frontier. - if engine.inputs[1..] - .iter() - .any(|frame| matches!(frame, InputFrame::Source { .. })) - { - return; - } - let Some(slot) = select(frontier, engine.shipped_pages) else { + let (entry, active_source) = (*entry, *source); + let file = &engine.sources[active_source]; + let position = CheckpointSource { + id: active_source, + name: &file.name, + bytes: file.data.len(), + frontier, + is_entry: active_source == entry, + }; + let Some(slot) = select(position, engine.shipped_pages) else { return; }; if engine.sources.iter().enumerate().any(|(index, other)| { - index != *source && other.name == engine.sources[*source].name + index != active_source && other.name == file.name }) { return; } - let entry = *source; engine.events.seal_prefix(); let mut executor = engine.clone(); executor.cancellation = None; @@ -3810,6 +3888,7 @@ impl Executor { let checkpoint = EntryCheckpoint { executor, entry, + active_source, initial_depth, incoming_state, frontier, diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 489f37b..6e68ff0 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -68,7 +68,7 @@ pub use case::CaseCode; pub use context::{ContextFrame, ContextKind, InputContext}; pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; -pub use engine::{EntryCheckpoint, Executor, Limits}; +pub use engine::{CheckpointSource, EntryCheckpoint, Executor, Limits}; pub use font_catalog::{ FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource, }; diff --git a/crates/texrra-tex-core/src/execution/session.rs b/crates/texrra-tex-core/src/execution/session.rs index c3c5946..29f6012 100644 --- a/crates/texrra-tex-core/src/execution/session.rs +++ b/crates/texrra-tex-core/src/execution/session.rs @@ -222,6 +222,21 @@ impl RevisionJob { self.finish_execution(executed, files, None) } + /// Capture selected physical source continuations, including child input. + pub fn run_capturing_sources( + self, + executor: Executor, + source: SourceFile, + files: &mut F, + select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option, + capture: impl FnMut(S, EntryCheckpoint, &mut F), + ) -> Result, RevisionFailure> { + let executed = executor + .with_cancellation(self.cancellation.clone()) + .run_capturing_sources(source, files, select, capture); + self.finish_execution(executed, files, None) + } + /// Resume after the host has validated prefix dependencies and replayed /// their effects into the new revision's isolated file host. pub fn resume_entry_after_host_replay( @@ -245,10 +260,29 @@ impl RevisionJob { line_break_cache: Arc, select: impl FnMut(usize, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F), + ) -> Option, RevisionFailure>> { + let mut select = select; + self.resume_capturing_sources_after_host_replay( + checkpoint, source, None, files, line_break_cache, + |source, pages| source.is_entry.then(|| select(source.frontier, pages)).flatten(), + capture, + ) + } + + pub fn resume_capturing_sources_after_host_replay( + self, + checkpoint: &EntryCheckpoint, + source: SourceFile, + nested: Option, + files: &mut F, + line_break_cache: Arc, + select: impl FnMut(super::CheckpointSource<'_>, 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( + let executed = checkpoint.resume_capturing_sources_after_host_replay( source, + nested, files, self.cancellation.clone(), line_break_cache, diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index f990bdb..6c4a298 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,31 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 在子文件内部恢复检查点 + +原生会话在读取实际项目子文件时记录输入游标与完整 TeX 状态。 +恢复时分别验证主文件和当前子文件已加载的字节以及物理行边界, +并把两个输入游标接到当前版本。其他已读资源继续按完整版本验证。 +文件存在和大小查询由宿主重新执行,仍须得到同样结果。文件流、 +日期查询或其他整文件读取保留各自的校验。已记录统计时还核对 +源长度。子文件保留最多四个附加检查点。 + +新增对照覆盖两层输入、连续子文件改动、同时修改主文件未读 +后缀、子文件前缀失效,以及大小查询观察到长度变化后的回退。 +输出例程共享末行和延迟输出两个相关回归通过。原样 A4 先改 +主文件,再改子文件,后一步从 chapter.tex 的第 100 字节恢复。 +重新执行由 79,008 步减至 56,893 步,节省 22,115 步,约 28%。 +两轮 PDF、SVG、来源映射、状态、实际资源和流记录及 aux 与 +独立全量一致。 + +既有流编辑测试最后一次还期望两页重新布局。候选与改动前的 +宿主控制组都只重新布局变更页,仍复用另一页。原测试和断言保留, +另在归档诊断副本核对流前缀失效,最后一次只替换第一页,与 +独立全量的 PDF、预览、来源映射及流记录一致。失败回执与候选 +发布构建保存在 target/p4-child-checkpoints/。SHA256SUMS 指纹为 +0fdf7891611110c73df67e5374ae96b55a5077e7cf86a101b16361e0aed69f8d。 +正式浏览器可见延迟与内存仍按原预算统一验收。 + ## 2026-11-29 输入栈中的单个 token 扫描器回退单个 token、插入段落 token、注入对齐标记或暂存 XeTeX diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 54d6a22..9fb0d42 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -9,7 +9,7 @@ use std::{ path::Path, }; use texrra_tex_core::{ - execution::EntryCheckpoint, + execution::{CheckpointSource, EntryCheckpoint}, resources::{ResourceKind, ResourceLookup, ResourceReadRange}, }; #[cfg(test)] @@ -22,6 +22,8 @@ pub struct EntryCheckpointWork { /// Checkpoints in the selected or freshly captured set. pub retained_checkpoints: usize, pub reused_frontier: Option, + /// Child input at the resume frontier, when the entry scanner was suspended. + pub reused_source: Option, pub reused_steps: usize, pub replayed_calls: usize, pub rejection: Option, @@ -41,7 +43,8 @@ struct CachedCheckpoint { entry: EntryCheckpoint, guard: PrefixInputGuard, replay_count: usize, - slots: CaptureSlots, + slots: Capture, + } pub(super) struct CheckpointSet { @@ -78,6 +81,52 @@ struct CaptureSlots { next_page: usize, } +const NESTED_FILES: usize = 2; +const NESTED_INTERVALS: usize = 2; + +#[derive(Clone, Copy)] +enum Capture { + Entry(CaptureSlots), + Nested { file: usize, interval: usize }, +} + +#[derive(Default)] +struct NestedSchedule { + sources: [Option; NESTED_FILES], + seen: [[bool; NESTED_INTERVALS]; NESTED_FILES], + recent: Option<(usize, Option)>, +} + +impl NestedSchedule { + fn select(&mut self, source: CheckpointSource<'_>, cwd: &Path) -> Option { + let file = if let Some((id, file)) = self.recent && id == source.id { + file + } else { + let file = if Path::new(source.name).starts_with(cwd) { + self.sources.iter().position(|id| *id == Some(source.id)) + .or_else(|| self.sources.iter().position(Option::is_none)) + } else { + None + }; + self.recent = Some((source.id, file)); + file + }?; + if source.frontier >= source.bytes { + return None; + } + let stride = source.bytes.div_ceil(NESTED_INTERVALS); + let interval = (source.frontier - 1) / stride; + self.sources[file] = Some(source.id); + (!std::mem::replace(&mut self.seen[file][interval], true)) + .then_some(Capture::Nested { file, interval }) + } + + fn retain(&mut self, file: usize, interval: usize, source: usize) { + self.sources[file] = Some(source); + self.seen[file][interval] = true; + } +} + impl CaptureSchedule { fn new(bytes: usize, fixed_frontier: Option, edit_frontier: Option) -> Self { Self { @@ -143,21 +192,22 @@ impl CaptureSchedule { } fn retain(&mut self, checkpoint: &CachedCheckpoint) -> Option { + let Capture::Entry(slots) = checkpoint.slots else { return None; }; let frontier = checkpoint.entry.frontier(); - if frontier > self.bytes || (frontier == self.bytes && !checkpoint.slots.page) { + if frontier > self.bytes || (frontier == self.bytes && !slots.page) { return None; } let interval = (frontier - 1) / self.stride; let early = frontier < self.bytes - && checkpoint.slots.early + && slots.early && !std::mem::replace(&mut self.seen[interval], true); - self.next_page = self.next_page.max(checkpoint.slots.next_page); + self.next_page = self.next_page.max(slots.next_page); Some(CaptureSlots { interval, early, edit: frontier < self.bytes - && self.take_edit_frontier(frontier, early || checkpoint.slots.page), - ..checkpoint.slots + && self.take_edit_frontier(frontier, early || slots.page), + ..slots }) } } @@ -169,6 +219,7 @@ struct CapturedEntries<'a> { early: [Option>; SOURCE_INTERVALS], shipped: [Option>; SOURCE_INTERVALS], edit: Option>, + nested: [[Option>; NESTED_INTERVALS]; NESTED_FILES], changed: bool, } @@ -185,11 +236,19 @@ impl<'a> CapturedEntries<'a> { early: Default::default(), shipped: Default::default(), edit: None, + nested: Default::default(), changed: false, } } - fn retain(&mut self, slots: CaptureSlots, checkpoint: Arc) { + fn retain(&mut self, slots: Capture, checkpoint: Arc) { + let slots = match slots { + Capture::Entry(slots) => slots, + Capture::Nested { file, interval } => { + self.nested[file][interval] = Some(checkpoint); + return; + } + }; if slots.early { self.early[slots.interval] = Some(checkpoint.clone()); } @@ -201,7 +260,7 @@ impl<'a> CapturedEntries<'a> { } } - fn capture(&mut self, slots: CaptureSlots, entry: EntryCheckpoint, host: &RecordingHost) { + fn capture(&mut self, slots: Capture, entry: EntryCheckpoint, host: &RecordingHost) { let (Some((trace, replay_count)), Some(path), Some(initial)) = ( host.prefix(), self.entry_path.as_deref(), @@ -209,7 +268,7 @@ impl<'a> CapturedEntries<'a> { ) else { return; }; - let Ok(guard) = PrefixInputGuard::capture( + let Ok(mut guard) = PrefixInputGuard::capture( self.request, path, trace, @@ -218,6 +277,11 @@ impl<'a> CapturedEntries<'a> { ) else { return; }; + if let Some(source) = entry.nested_source() + && !guard.allow_nested_source(Path::new(source), trace, host) + { + return; + } self.retain( slots, Arc::new(CachedCheckpoint { @@ -260,12 +324,14 @@ impl<'a> CapturedEntries<'a> { .enumerate() .skip(1) .filter(|(_, checkpoint)| { - !checkpoint.slots.page && checkpoint.entry.frontier() != edit + matches!(checkpoint.slots, Capture::Entry(slots) if !slots.page) && checkpoint.entry.frontier() != edit }) .min_by_key(|(_, checkpoint)| checkpoint.entry.frontier().abs_diff(edit)) .expect("the full schedule has ordinary continuations"); entries.remove(index); } + entries.extend(self.nested.into_iter().flatten().flatten()); + entries.sort_by_key(|candidate| candidate.entry.completed_steps()); let replay_count = entries.iter().map(|entry| entry.replay_count).max()?; let mut calls = recording.into_calls()?; calls.truncate(replay_count); @@ -324,7 +390,7 @@ impl CheckpointCache { .current .entries .iter() - .find(|entry| entry.slots.page) + .find(|entry| matches!(entry.slots, Capture::Entry(slots) if slots.page)) .is_some_and(|entry| entry.accept_entry(project).is_err()) { // Keep useful continuations from before a change to the first @@ -354,11 +420,21 @@ impl CheckpointCache { let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None); let mut captures = CapturedEntries::new(request, files); let mut recording = RecordingHost::new(files); - let result = job.run_capturing_entries( + let mut nested = NestedSchedule::default(); + let cwd = &request.world.cwd; + let result = job.run_capturing_sources( executor, source, &mut recording, - |frontier, pages| schedule.select(frontier, pages), + |source, pages| { + if source.is_entry { + schedule.select(source.frontier, pages).map(Capture::Entry) + } else if self.minimum_frontier.is_none() { + nested.select(source, cwd) + } else { + None + } + }, |slots, entry, host| captures.capture(slots, entry, host), ); let next = if result.is_ok() { @@ -450,9 +526,11 @@ impl PublishedCheckpoints { )?; let selected = selected.expect("resume preparation chose a verified checkpoint"); let checkpoint = &selected.set.entries[selected.index]; + let partial_source = checkpoint.guard.nested_source.as_deref() + .and_then(|path| project.file(path)).map(|file| &file.version); for (index, call) in selected.set.calls[..checkpoint.replay_count].iter().enumerate() { check(cancellation)?; - if let Err(error) = call(&mut prepared.files) { + if let Err(error) = call.replay(&mut prepared.files, partial_source) { replay_rejection.get_or_insert(CompileError::Host(error)); // Other checkpoints sharing this call cannot use the // invalidated prefix either. Drop the draft on retry. @@ -481,7 +559,7 @@ impl CheckpointSet { .entries .iter() .rev() - .filter(|entry| entry.slots.page) + .filter(|entry| matches!(entry.slots, Capture::Entry(slots) if slots.page)) .take(2) .cloned() .collect(); @@ -497,7 +575,9 @@ impl CheckpointSet { pub(super) fn report_capture(&self, work: &mut EntryCheckpointWork) { work.retained_checkpoints = self.entries.len(); - work.captured_frontier = self.entries.last().map(|entry| entry.entry.frontier()); + work.captured_frontier = self.entries.iter().rev() + .find(|entry| matches!(entry.slots, Capture::Entry(_))) + .map(|entry| entry.entry.frontier()); } fn candidates(self: &Arc) -> impl Iterator + '_ { @@ -521,6 +601,12 @@ impl CachedCheckpoint { { return Err("checkpoint entry prefix changed".into()); } + if let Some(path) = &self.guard.nested_source { + let child = project.file(path).ok_or("checkpoint child is unavailable")?; + if !self.entry.accepts_nested_source(&path.to_string_lossy(), &child.data) { + return Err("checkpoint child prefix changed".into()); + } + } Ok(()) } } @@ -549,6 +635,7 @@ impl SelectedCheckpoint { let frontier = checkpoint.entry.frontier(); work.retained_checkpoints = self.set.entries.len(); work.reused_frontier = Some(frontier); + work.reused_source = checkpoint.guard.nested_source.clone(); work.reused_steps = checkpoint.entry.completed_steps(); work.replayed_calls = checkpoint.replay_count; let changed_prefix = || CompileError::Host("prepared checkpoint prefix changed".into()); @@ -566,31 +653,57 @@ impl SelectedCheckpoint { .expect("a checkpoint records its source"); let edit = changed_line_start(&previous.data, &source.data).or(self.set.edit_frontier); let mut schedule = CaptureSchedule::new(source.data.len(), None, edit); + let mut nested_schedule = NestedSchedule::default(); + let entry_frontier = checkpoint.entry.entry_frontier(); + let current_nested = checkpoint.guard.nested_source.as_deref() + .and_then(|path| request.project.as_ref()?.file(path)); + let nested_source = current_nested.map(|file| SourceFile { + name: file.version.path.display().to_string(), + data: file.data.to_vec(), + }); let mut captures = CapturedEntries::new(request, files); - // Share only calls and continuations from the prefix just replayed. + // Earlier retained positions refer only to calls already replayed. for previous in &self.set.entries[..=self.index] { - if previous.replay_count <= checkpoint.replay_count - && previous.entry.frontier() <= frontier - && let Some(slots) = schedule.retain(previous) - { - captures.retain(slots, previous.clone()); + if previous.replay_count > checkpoint.replay_count { + continue; + } + match previous.slots { + Capture::Entry(_) if previous.entry.frontier() <= entry_frontier => { + if let Some(slots) = schedule.retain(previous) { + captures.retain(Capture::Entry(slots), previous.clone()); + } + } + Capture::Nested { file, interval } => { + let id = previous.entry.nested_source_id().expect("nested checkpoint source"); + nested_schedule.retain(file, interval, id); + captures.retain(previous.slots, previous.clone()); + } + _ => {} } } - let mut recording = - RecordingHost::after_replay(files, &self.set.calls[..checkpoint.replay_count]); + let mut recording = RecordingHost::after_replay( + files, &self.set.calls[..checkpoint.replay_count], current_nested.map(|file| &file.version), + ); + let cwd = &request.world.cwd; let result = job - .resume_capturing_entries_after_host_replay( + .resume_capturing_sources_after_host_replay( &checkpoint.entry, source, + nested_source, &mut recording, line_break_cache, - |offset, pages| { - // The loaded line may stay the same across several - // pages. A new sampled shipout is still forward progress. - if offset > frontier || (offset == frontier && pages >= schedule.next_page) { - schedule.select(offset, pages) + |source, pages| { + if source.is_entry { + // The loaded entry line can be shared by several shipouts. + if source.frontier > entry_frontier + || (source.frontier == entry_frontier && pages >= schedule.next_page) + { + schedule.select(source.frontier, pages).map(Capture::Entry) + } else { + None + } } else { - None + nested_schedule.select(source, cwd) } }, |slots, entry, host| captures.capture(slots, entry, host), @@ -637,6 +750,7 @@ struct PrefixInputGuard { project: Arc, initial: GeneratedInitialState, entry: PathBuf, + nested_source: Option, immutable: BTreeSet, immutable_stream_prefixes: BTreeMap, generated: BTreeSet, @@ -745,6 +859,7 @@ impl PrefixInputGuard { project: project.clone(), initial, entry: entry.to_path_buf(), + nested_source: None, immutable, immutable_stream_prefixes, generated, @@ -755,6 +870,21 @@ impl PrefixInputGuard { }) } + fn allow_nested_source(&mut self, path: &Path, trace: &ResourceTrace, host: &RecordingHost<'_>) -> bool { + let Some(file) = self.project.file(path) else { return false }; + // Presence and size queries can be replayed against the new bytes. + // All content reads other than the active scanner pin the old bytes. + if !host.source_read_is_rebindable(&file.version) + || trace.stream_reads.iter().any(|read| read.path == path) + || trace.file_modifications.iter().any(|read| read.path == path) + || trace.generated_lookups.iter().any(|read| read.target == path) + { + return false; + } + self.nested_source = Some(path.to_path_buf()); + true + } + fn verify_project<'a>( &self, request: &'a CompileRequest, @@ -784,6 +914,7 @@ impl PrefixInputGuard { let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and( |(old, new)| { old.version == new.version + || self.nested_source.as_ref() == Some(path) || self.immutable_stream_prefixes.get(path).is_some_and(|&end| { new.data.get(..end) == Some(&old.data[..end]) }) @@ -1086,7 +1217,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec ) .unwrap(); for call in &calls { - call(&mut files).unwrap(); + call.replay(&mut files, None).unwrap(); } assert_eq!( files.resource_usage().unwrap().unwrap().open_outputs, @@ -1130,7 +1261,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec ) .unwrap(); for call in &calls { - call(&mut files).unwrap(); + call.replay(&mut files, None).unwrap(); } let result = revision .resume_entry_after_host_replay(&checkpoint, source, &mut files) @@ -1250,7 +1381,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec ) .unwrap(); for call in &calls { - call(&mut files).unwrap(); + call.replay(&mut files, None).unwrap(); } let cancelled = Cancellation::default(); cancelled.cancel(); @@ -1276,7 +1407,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec .unwrap(); assert!(checkpoint.accepts_entry(&source)); for call in &calls { - call(&mut files).unwrap(); + call.replay(&mut files, None).unwrap(); } let resumed_usage: HostResourceUsage = files.resource_usage().unwrap().unwrap(); assert_eq!(resumed_usage.open_outputs, Some(1)); diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 1a7c208..9c2466e 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -7,10 +7,57 @@ use std::{fs, path::Path}; use texrra_tex_core::source_map::SourceMap; use texrra_tex_core::{ execution::{Error, HostResourceUsage, WriteDestination}, - resources::{LoadedResource, ResourceKind}, + resources::{LoadedResource, ResourceKind, ResourceVersion}, }; -pub(super) type Call = Arc Result<(), String> + Send + Sync>; +type CheckedCall = dyn Fn(&mut Files) -> Result<(), String> + Send + Sync; +#[derive(Clone)] +pub(super) enum Call { + Checked(Arc), + ReadSource(Arc), + FileSize(Arc), +} + +pub(super) struct SourceRead { + name: String, + from: String, + expected: Result, +} + +pub(super) struct SizeRead { + name: String, + from: String, + observed: Result, String>, + read: Option, +} + +impl Call { + pub(super) fn replay(&self, files: &mut Files, partial_source: Option<&ResourceVersion>) -> Result<(), String> { + match self { + Self::Checked(call) => call(files), + Self::FileSize(read) => { + let observed = files.file_size(&read.name, &read.from); + if observed == read.observed { + Ok(()) + } else { + Err(format!("file size changed: expected {:?}, observed {observed:?}", read.observed)) + } + } + Self::ReadSource(read) => { + let SourceRead { name, from, expected } = read.as_ref(); + let observed = files.read_versioned_source(name, from).map(|(_, version)| version); + if &observed == expected || matches!((&observed, expected), (Ok(new), Ok(old)) + if partial_source == Some(new) && new.path == old.path) + { + Ok(()) + } else { + Err(format!("read changed: expected {expected:?}, observed {observed:?}")) + } + } + } + } +} + const MAX_REPLAY_CALLS: usize = 65_536; pub(super) struct RecordingHost<'a> { @@ -20,14 +67,30 @@ pub(super) struct RecordingHost<'a> { impl<'a> RecordingHost<'a> { pub(super) fn new(files: &'a mut Files) -> Self { - Self::after_replay(files, &[]) + Self::after_replay(files, &[], None) } - pub(super) fn after_replay(files: &'a mut Files, prefix: &[Call]) -> Self { - Self { - files, - calls: Some(prefix.to_vec()), + pub(super) fn after_replay( + files: &'a mut Files, + prefix: &[Call], + rebound: Option<&ResourceVersion>, + ) -> Self { + let mut calls = prefix.to_vec(); + if let Some(version) = rebound { + for call in &mut calls { + if let Call::ReadSource(read) = call + && let Ok(prior) = &read.expected + && prior.path == version.path && prior != version + { + *call = Call::ReadSource(Arc::new(SourceRead { + name: read.name.clone(), + from: read.from.clone(), + expected: Ok(version.clone()), + })); + } + } } + Self { files, calls: Some(calls) } } #[cfg(test)] @@ -42,6 +105,21 @@ impl<'a> RecordingHost<'a> { (count < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), count)) } + pub(super) fn source_read_is_rebindable(&self, version: &ResourceVersion) -> bool { + let Some(calls) = &self.calls else { return false }; + let mut source_reads = 0; + let mut size_reads = 0; + for call in calls { + match call { + Call::ReadSource(read) if read.expected.as_ref() == Ok(version) => source_reads += 1, + Call::FileSize(read) if read.read.as_ref().is_some_and(|r| r.path == version.path) => size_reads += 1, + _ => {} + } + } + source_reads == 1 && self.files.resource_trace().reads.iter() + .filter(|read| read.path == version.path).count() == source_reads + size_reads + } + pub(super) fn generated_outputs(&self) -> &BTreeSet { self.files.generated_outputs() } @@ -62,7 +140,7 @@ impl<'a> RecordingHost<'a> { return result; } let expected = evidence(&result); - calls.push(Arc::new(move |files| { + calls.push(Call::Checked(Arc::new(move |files| { let observed = evidence(&call(files)); if observed == expected { Ok(()) @@ -71,7 +149,7 @@ impl<'a> RecordingHost<'a> { "{name} changed: expected {expected:?}, observed {observed:?}" )) } - })); + }))); } result } @@ -108,14 +186,17 @@ impl SourceProvider for RecordingHost<'_> { call!(self, resource_usage()) } fn read(&mut self, name: &str, from: &str) -> Result { - let (name, from) = (name.to_owned(), from.to_owned()); - self.record( - "read", - move |files| files.read_versioned_source(&name, &from), - |result| result.as_ref().map(|(_, version)| version.clone()).map_err(Clone::clone), - ) - .map(|(source, _)| source) + let result = self.files.read_versioned_source(name, from); + if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS { + calls.push(Call::ReadSource(Arc::new(SourceRead { + name: name.to_owned(), + from: from.to_owned(), + expected: result.as_ref().map(|(_, version)| version.clone()).map_err(Clone::clone), + }))); + } + result.map(|(source, _)| source) } + fn resource( &mut self, kind: ResourceKind, @@ -214,9 +295,23 @@ impl SourceProvider for RecordingHost<'_> { }) } fn file_size(&mut self, name: &str, from: &str) -> Result, String> { - let (name, from) = (name.to_owned(), from.to_owned()); - call!(self, file_size(&name, &from)) + let previous_reads = self.files.resource_trace().reads.len(); + let observed = self.files.file_size(name, from); + if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS { + let read = match &self.files.resource_trace().reads[previous_reads..] { + [read] => Some(read.clone()), + _ => None, + }; + calls.push(Call::FileSize(Arc::new(SizeRead { + name: name.to_owned(), + from: from.to_owned(), + observed: observed.clone(), + read, + }))); + } + observed } + fn file_modification_date(&mut self, name: &str, from: &str) -> Result, String> { let (name, from) = (name.to_owned(), from.to_owned()); call!(self, file_modification_date(&name, &from)) @@ -421,7 +516,7 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() { changed_prefix.data[0] ^= 1; assert!(!checkpoint.accepts_entry(&changed_prefix)); for (i, call) in calls.iter().enumerate() { - call(&mut files).unwrap_or_else(|error| panic!("replay action {i}: {error}")); + call.replay(&mut files, None).unwrap_or_else(|error| panic!("replay action {i}: {error}")); } let resumed = checkpoint .resume_after_host_replay(source, &mut files, Cancellation::default()) diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index a2b1277..2699449 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -543,6 +543,87 @@ fn resumed_suffix_reuses_search_for_unchanged_paragraphs() { fs::remove_dir_all(p).unwrap(); } + +#[test] +fn child_checkpoints_reuse_only_the_validated_physical_prefix() { + let root = directory("child-continuation"); + let leaf = root.join("leaf.tex"); + let parent = root.join("parent.tex"); + let main = r"\shipout\hbox{Main} +\input parent.tex +\shipout\hbox{Final} +\end +"; + let original = r"\def\prefix{Original} +\shipout\hbox{\prefix} +\def\label{Measured at 100 points} +\shipout\hbox{\label} +\relax +"; + let make_project = |main: &str| { + let mut definition = atomic_definition(&root, 1, main); + definition.files.extend([ + (parent.clone(), Arc::from(br"\relax +\input leaf.tex +\relax +".as_slice())), + (leaf.clone(), Arc::from(original.as_bytes())), + ]); + ProjectSnapshot::new(definition).unwrap() + }; + let mut project = make_project(main); + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let mut request = request(&root).observe_generated_initial(); + request.world = project.configuration(); + let mut prior = compiler.compile(request.clone().with_project(project.clone())).unwrap(); + assert_eq!(prior.pages.len(), 4); + + for (revision, child, expected_pages, reuse_leaf) in [ + (2, original.replace("100 points", "200 points"), vec![2], true), + (3, original.replace("100 points", "3000 points"), vec![2, 3], true), + (4, original.replace("Original", "Different").replace("100 points", "3000 points"), vec![1], false), + ] { + let mut edits = BTreeMap::from([(leaf.clone(), Arc::from(child.into_bytes()))]); + if revision == 3 { + let updated = format!("{HEADER}{}", main.replace("Final", "Close")); + edits.insert(root.join("main.tex"), Arc::from(updated.into_bytes())); + } + project = project.with_file_edits(revision, edits).unwrap(); + let job = request.clone().with_project(project.clone()); + let after = compiler.compile(job.clone()).unwrap(); + let full = NativeCompiler::default().compile(job).unwrap(); + let work = &after.entry_checkpoint_work; + assert_eq!(work.reused_source.as_deref() == Some(leaf.as_path()), reuse_leaf, "{work:?}"); + if reuse_leaf { + assert!(work.reused_frontier.unwrap() >= original.find(r"\shipout\hbox{\prefix}").unwrap(), "{work:?}"); + } + assert!(after.execution.execution == full.execution.execution); + assert_eq!(after.execution.execution_resources, full.execution.execution_resources); + assert_eq!(after.source_map.sources, full.source_map.sources); + assert_eq!(after.source_map.pages, full.source_map.pages); + assert_eq!(after.pdf, full.pdf); + assert_eq!(after.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + assert_eq!(after.preview_since(Some(prior.revision())).unwrap().pages + .into_iter().map(|page| page.index).collect::>(), expected_pages); + prior = after; + } + + // A whole-file consumer makes changes to any byte observable before input. + let probed = make_project(&format!(r"\count0=\pdffilesize{{leaf.tex}}\relax +{main}")); + let guarded = NativeCompiler::default().with_automatic_entry_checkpoints(); + guarded.compile(request.clone().with_project(probed.clone())).unwrap(); + let changed = original.replace("100 points", "3000 points"); + let probed = probed.with_file_edits(2, [(leaf.clone(), Arc::from(changed.into_bytes()))].into()).unwrap(); + let job = request.with_project(probed); + let after = guarded.compile(job.clone()).unwrap(); + let full = NativeCompiler::default().compile(job).unwrap(); + assert_ne!(after.entry_checkpoint_work.reused_source.as_deref(), Some(leaf.as_path())); + assert!(after.execution.execution == full.execution.execution); + assert_eq!(after.pdf, full.pdf); + fs::remove_dir_all(root).unwrap(); +} + #[test] fn unicode_math_code_edit_updates_the_page_that_reads_the_table() { let p = directory("unicode-math-code");