From e4d6e049f86978a0368b687ea56fb5b6ee342cec Mon Sep 17 00:00:00 2001 From: GloamXun Date: Wed, 2 Dec 2026 01:53:20 +0800 Subject: [PATCH] Reuse settled suffixes after verified closed child edits --- .../texrra-tex-core/src/execution/engine.rs | 2 +- .../src/execution/engine/continuation.rs | 147 +++++++++++++++--- .../execution/engine/continuation/relocate.rs | 8 +- .../src/execution/engine/statistics.rs | 23 +-- crates/texrra-tex-core/src/execution/mod.rs | 3 +- .../src/execution/statistics.rs | 98 ++++++++++-- docs/P2_M1_PROGRESS.md | 22 +++ src/native_checkpoint_guard.rs | 144 ++++++++++++++--- src/native_checkpoint_probe.rs | 82 ++++++++++ src/native_job.rs | 36 +++++ tests/native_pipeline.rs | 72 +++++++++ 11 files changed, 565 insertions(+), 72 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 5fc15a8..956aa4c 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -44,7 +44,7 @@ mod scheduling; mod specials; mod statistics; mod continuation; -pub use continuation::{RelocatedShipoutSuffix, SuffixKernelTimings}; +pub use continuation::{ClosedSourceChange, RelocatedShipoutSuffix, SuffixKernelTimings}; mod xdv_annotation; #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index ae4ee4d..0824a14 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -1,7 +1,7 @@ use super::super::{ dependency_reads::DependencyEvidence, source_relocation::SourceRelocation, source_relocation_events::EventRelocation, - statistics::{BoxNodeOffset, RetainedHistoryOffset}, + statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize}, }; use super::*; use std::time::{Duration, Instant}; @@ -123,7 +123,71 @@ impl RelocatedShipoutSuffix { } } +/// One changed physical child whose scanner has already left the input stack. +pub struct ClosedSourceChange<'a> { + pub source_id: usize, + pub name: &'a str, + pub previous_bytes: usize, + pub current_bytes: usize, +} + impl EntryCheckpoint { + /// Identify a closed byte-framed child before the host verifies its path, + /// distinct file roles, read counts, and absence of later observations. + pub fn closed_source_change<'a>( + &'a self, + prior: &Self, + completed: &Execution, + ) -> Option> { + let current = &self.executor; + let old = &prior.executor; + if self.entry != self.active_source + || prior.entry != prior.active_source + || self.entry != prior.entry + || current.sources.len() != old.sources.len() + || !matches!(current.state.input_profile(), InputProfile::TeX8Bit | InputProfile::UnicodeScalar) + || current.state.input_profile() != old.state.input_profile() + { + return None; + } + let mut differences = current.sources.iter().zip(&old.sources).enumerate() + .filter(|(_, (new, old))| new != old); + let (source_id, (new, old_source)) = differences.next()?; + if differences.next().is_some() + || source_id == self.entry + || new.name != old_source.name + || completed.sources.get(source_id)? != old_source + { + return None; + } + let uniquely_named = |sources: &[Arc]| { + sources.iter().filter(|source| source.name == new.name).take(2).count() == 1 + }; + let is_closed = |executor: &Executor| { + !executor.stream_sources.contains(&source_id) + && !executor.generated_inputs.contains_key(&source_id) + && !executor.inputs.iter().any(|frame| matches!( + frame, InputFrame::Source { source, .. } if *source == source_id + )) + }; + if !uniquely_named(&old.sources) + || !uniquely_named(¤t.sources) + || !uniquely_named(&completed.sources) + || !is_closed(old) + || !is_closed(current) + || completed.stream_sources.contains(&source_id) + || completed.generated_inputs.contains_key(&source_id) + { + return None; + } + Some(ClosedSourceChange { + source_id, + name: &new.name, + previous_bytes: old_source.data.len(), + current_bytes: new.data.len(), + }) + } + /// Construct an execution with the current prefix and a previously /// completed suffix. The host must still validate and replay that suffix. pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option { @@ -146,6 +210,36 @@ impl EntryCheckpoint { &self, prior: &Self, completed: &Execution, + timings: Option<&mut SuffixKernelTimings>, + ) -> Option<(Execution, Option)> { + self.splice_settled_sources(prior, completed, self.entry, 1, timings) + } + + /// Reuse a suffix after the caller has verified the actual host reads + /// of the changed child, including probes that only consumed its size. + /// The caller must reject later uses of this file and replay all effects. + pub fn splice_settled_closed_source_suffix_observed( + &self, + prior: &Self, + completed: &Execution, + source_id: usize, + prefix_resource_reads: usize, + timings: Option<&mut SuffixKernelTimings>, + ) -> Option<(Execution, Option)> { + if prefix_resource_reads == 0 + || self.closed_source_change(prior, completed)?.source_id != source_id + { + return None; + } + self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, timings) + } + + fn splice_settled_sources( + &self, + prior: &Self, + completed: &Execution, + source_id: usize, + prefix_resource_reads: usize, mut timings: Option<&mut SuffixKernelTimings>, ) -> Option<(Execution, Option)> { if self.entry != self.active_source @@ -170,7 +264,7 @@ impl EntryCheckpoint { .zip(&old.sources) .enumerate() .any(|(id, (new, old))| { - if id == self.entry { + if id == source_id { new.name != old.name } else { new != old @@ -199,12 +293,15 @@ impl EntryCheckpoint { if current.material_charge != old.material_charge && !no_suffix_recount { return None; } - let previous_bytes = &old.sources[self.entry].data; - let current_bytes = ¤t.sources[self.entry].data; - let entry_sizes = (previous_bytes.len() != current_bytes.len()) - .then_some((previous_bytes.len(), current_bytes.len())); - let relocation = match entry_sizes { - Some(_) => { + let previous_bytes = &old.sources[source_id].data; + let current_bytes = ¤t.sources[source_id].data; + let resize = (previous_bytes.len() != current_bytes.len()).then_some(SuffixSourceResize { + sizes: (previous_bytes.len(), current_bytes.len()), + active_at_anchor: source_id == self.entry, + prefix_resource_reads, + }); + let relocation = match resize { + Some(resize) if resize.active_at_anchor => { let map = self.source_mouth(self.entry) .relocation_from(prior.source_mouth(prior.entry))?; if map.relocate_offset(prior.frontier) != Some(self.frontier) { @@ -212,13 +309,16 @@ impl EntryCheckpoint { } Some(map) } + Some(_) if self.frontier == prior.frontier => { + Some(SourceRelocation::new(source_id, previous_bytes, current_bytes)?) + } None if self.frontier == prior.frontier => None, - None => return None, + _ => return None, }; - let observes_entry_line = completed.line_observations.as_ref().is_none_or(|observations| { - observations.get(&self.entry) != old.line_observations.get(&self.entry) + let observes_changed_line = completed.line_observations.as_ref().is_none_or(|observations| { + observations.get(&source_id) != old.line_observations.get(&source_id) }); - if observes_entry_line + if observes_changed_line && relocation.as_ref().map_or_else( || !SourceRelocation::same_line_breaks(previous_bytes, current_bytes), |map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1, @@ -252,12 +352,12 @@ impl EntryCheckpoint { return None; } let mut sources = completed.sources.clone(); - sources[self.entry] = current.sources[self.entry].clone(); + sources[source_id] = current.sources[source_id].clone(); let tail = completed.events.get(old.events.len()..)?; let retained_history = if completed.accounts_event_history { measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || { if current.events.len() == old.events.len() - && current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes) + && current.equivalent_accounting_history_with_source_resize(old, resize) { return Some(None); } @@ -271,7 +371,7 @@ impl EntryCheckpoint { { return None; } - let history = current.retained_history_offset(old, entry_sizes)?; + let history = current.retained_history_offset(old, resize)?; Some((!history.is_identity()).then_some(history)) })? } else { @@ -310,9 +410,9 @@ impl EntryCheckpoint { reads_event_history: false, accounts_event_history: completed.accounts_event_history, }; - if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) { + if let Some((moved, resize)) = moved.as_mut().zip(resize) { relocate::append_suffix( - &mut execution, tail, &statistics, moved, sizes, old.sources.len(), + &mut execution, tail, &statistics, moved, resize, old.sources.len(), )?; if execution.state != completed.state { execution.outgoing_state = execution.state.fingerprint(); @@ -355,6 +455,13 @@ impl EntryCheckpoint { } let current = &self.executor; let old = &prior.executor; + // Rebased checkpoints retain the donor's closed-source bytes. + if current.sources.len() != old.sources.len() + || current.sources.iter().zip(&old.sources).enumerate() + .any(|(id, (new, old))| id != self.entry && new != old) + { + return None; + } // Later snapshots retain the donor's meaning cache and read history. // Keeping them requires the same keys, even when the finished splice // could publish a different set using exact suffix evidence. @@ -567,10 +674,10 @@ impl SuffixStatistics { fn translate( &self, report: &StatisticsReport, - entry_sizes: Option<(usize, usize)>, + resize: Option, ) -> Option { - report.with_suffix_adjustments( - self.steps, self.boxes, entry_sizes, self.retained_history.as_ref(), + report.with_source_resize( + self.steps, self.boxes, resize, self.retained_history.as_ref(), ) } } diff --git a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs index bbc8358..e33f2e8 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs @@ -108,13 +108,15 @@ pub(super) fn append_suffix( tail: &[Event], statistics: &SuffixStatistics, relocation: &mut EventRelocation<'_>, - (previous_bytes, current_bytes): (usize, usize), + resize: SuffixSourceResize, source_count: usize, ) -> Option<()> { let map = relocation.map(); for event in tail { if let Event::Statistics(report) = event { - if let StatisticsPhase::Shipout { before, after } = &report.phase { + if resize.active_at_anchor + && let StatisticsPhase::Shipout { before, after } = &report.phase + { // The active entry was the only source frame at convergence. // If a report follows any later input open, its mouth payload // alone cannot prove whether that frame is still present. @@ -122,7 +124,7 @@ pub(super) fn append_suffix( return None; } } - let mut report = statistics.translate(report, Some((previous_bytes, current_bytes)))?; + let mut report = statistics.translate(report, Some(resize))?; report.span = map.relocate_span(report.span)?; execution.events.push(Event::Statistics(Box::new(report))); } else { diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 6301ebb..614dce2 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -1,7 +1,7 @@ use super::super::statistics::{ Collector, Ownership::{Active, Retained}, - RetainedHistoryOffset, + RetainedHistoryOffset, SuffixSourceResize, }; use super::*; impl Executor { @@ -232,16 +232,16 @@ impl Executor { } pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool { - self.equivalent_accounting_history_with_entry_sizes(old, None) + self.equivalent_accounting_history_with_source_resize(old, None) } - pub(super) fn equivalent_accounting_history_with_entry_sizes( + pub(super) fn equivalent_accounting_history_with_source_resize( &self, old: &Self, - entry_sizes: Option<(usize, usize)>, + resize: Option, ) -> bool { [Collector::for_capacity, Collector::default].into_iter().all(|collector| { - self.collect_compared_accounting(old, entry_sizes, collector).is_some_and( + self.collect_compared_accounting(old, resize, collector).is_some_and( |(live, old_live, history, old_history)| { live.has_equivalent_history(&old_live, &history, &old_history) }, @@ -252,17 +252,17 @@ impl Executor { pub(super) fn retained_history_offset( &self, old: &Self, - entry_sizes: Option<(usize, usize)>, + resize: Option, ) -> Option { let (live, old_live, history, old_history) = - self.collect_compared_accounting(old, entry_sizes, Collector::default)?; + self.collect_compared_accounting(old, resize, Collector::default)?; live.retained_history_offset(&old_live, &history, &old_history) } fn collect_compared_accounting( &self, old: &Self, - entry_sizes: Option<(usize, usize)>, + resize: Option, collector: fn() -> Collector, ) -> Option<(Collector, Collector, Collector, Collector)> { // These containers may reintroduce previously retained allocations @@ -284,10 +284,13 @@ impl Executor { // The splice translates the cumulative counters separately. live.usage.steps = old_live.usage.steps; live.usage.box_nodes_created = old_live.usage.box_nodes_created; - if let Some((previous, current)) = entry_sizes { + if let Some(resize) = resize { + let (previous, current) = resize.sizes; let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous); live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?; - live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?; + if resize.active_at_anchor { + live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?; + } } Some((live, old_live, history, old_history)) } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 2251555..a1f0a62 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -72,7 +72,8 @@ pub use context::{ContextFrame, ContextKind, InputContext}; pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; pub use engine::{ - CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, + CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Executor, Limits, + RelocatedShipoutSuffix, SuffixKernelTimings, }; pub use font_catalog::{ diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 0b07321..e8b452e 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -271,6 +271,24 @@ impl RetainedHistoryOffset { } } +/// Byte counts affected by the sole changed physical source at convergence. +#[derive(Clone, Copy)] +pub(super) struct SuffixSourceResize { + pub(super) sizes: (usize, usize), + pub(super) active_at_anchor: bool, + pub(super) prefix_resource_reads: usize, +} + +impl SuffixSourceResize { + pub(super) fn entry(sizes: (usize, usize)) -> Self { + Self { + sizes, + active_at_anchor: true, + prefix_resource_reads: 1, + } + } +} + impl StatisticsReport { pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self { let text = phase.text(); @@ -292,7 +310,7 @@ impl StatisticsReport { if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() { return None; } - usage.resize_entry_payload(previous, current, true)?; + usage.resize_source_payload(SuffixSourceResize::entry((previous, current)), true)?; } debug_assert_eq!(self.text, self.phase.text()); Some(()) @@ -324,6 +342,16 @@ impl StatisticsReport { boxes: BoxNodeOffset, entry_sizes: Option<(usize, usize)>, history: Option<&RetainedHistoryOffset>, + ) -> Option { + self.with_source_resize(steps, boxes, entry_sizes.map(SuffixSourceResize::entry), history) + } + + pub(super) fn with_source_resize( + &self, + steps: StepOffset, + boxes: BoxNodeOffset, + resize: Option, + history: Option<&RetainedHistoryOffset>, ) -> Option { let translate = |usage: &mut ResourceUsage| { usage.steps = steps.apply(usage.steps)?; @@ -338,22 +366,24 @@ impl StatisticsReport { } for usage in [before, after] { translate(usage)?; - if let Some((previous, current)) = entry_sizes { - let active = usage.mouth_payload_bytes == previous; - if !active && usage.mouth_payload_bytes != 0 { + if let Some(resize) = resize { + let active = resize.active_at_anchor && usage.mouth_payload_bytes == resize.sizes.0; + if resize.active_at_anchor && !active && usage.mouth_payload_bytes != 0 { return None; } - usage.resize_entry_payload(previous, current, active)?; + usage.resize_source_payload(resize, active)?; } } } StatisticsPhase::End { usage, .. } => { translate(usage)?; - if let Some((previous, current)) = entry_sizes { - if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 { + if let Some(resize) = resize { + if resize.active_at_anchor + && (usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0) + { return None; } - usage.resize_entry_payload(previous, current, false)?; + usage.resize_source_payload(resize, false)?; } if let Some(offset) = history { offset.replace_prefix(usage)?; @@ -376,18 +406,17 @@ impl StatisticsReport { } impl ResourceUsage { - fn resize_entry_payload( - &mut self, - previous: usize, - current: usize, - active: bool, - ) -> Option<()> { + fn resize_source_payload(&mut self, resize: SuffixSourceResize, active: bool) -> Option<()> { + let (previous, current) = resize.sizes; self.source_payload_bytes = self.source_payload_bytes.checked_sub(previous)?.checked_add(current)?; if active { self.mouth_payload_bytes = self.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?; } if let Some(host) = &mut self.host { - host.rebind_entry_bytes(u64::try_from(previous).ok()?, u64::try_from(current).ok()?)?; + let reads = u64::try_from(resize.prefix_resource_reads).ok()?; + let previous = u64::try_from(previous).ok()?.checked_mul(reads)?; + let current = u64::try_from(current).ok()?.checked_mul(reads)?; + host.rebind_entry_bytes(previous, current)?; } Some(()) } @@ -920,6 +949,45 @@ mod tests { ).is_none()); } + #[test] + fn closed_source_resize_counts_each_host_read_and_leaves_other_mouths() { + let usage = ResourceUsage { + source_payload_bytes: 50, + mouth_payload_bytes: 30, + host: Some(HostResourceUsage { + resource_reads: 5, + resource_bytes_read: 100, + ..HostResourceUsage::default() + }), + token_limit: 4096, + ..ResourceUsage::default() + }; + let resize = SuffixSourceResize { + sizes: (8, 11), + active_at_anchor: false, + prefix_resource_reads: 3, + }; + let report = StatisticsReport::new( + StatisticsPhase::Shipout { before: usage.clone(), after: usage }, + WriteDestination::Log, + Span::default(), + ); + let adjusted = report.with_source_resize( + StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some(resize), None, + ).unwrap(); + assert_eq!(adjusted.text, report.text); + let StatisticsPhase::Shipout { before, after } = adjusted.phase else { + unreachable!(); + }; + for usage in [before, after] { + assert_eq!(usage.source_payload_bytes, 53); + assert_eq!(usage.mouth_payload_bytes, 30); + let host = usage.host.unwrap(); + assert_eq!(host.resource_reads, 5); + assert_eq!(host.resource_bytes_read, 109); + } + } + #[test] fn tracked_macro_counts_share_the_ordinal_index_without_losing_visits() { let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default()); diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4777946..8f9c787 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -213,6 +213,28 @@ Edge 同机、同格式和资源,主文件与子文件各 30 次。原有绘 逐次记录在 `target/p4-a4-release-opt3/`。 [Element Timing 规范草案](https://w3c.github.io/element-timing/) +## 2026-12-02 已关闭子文件的后缀复用 + +已完成读取的一个按字节分行子文件可在入口不变时参与后缀复用。 +内核核对唯一源编号、其他来源与活动扫描器,并按实际文件变化 +迁移来源坐标。宿主验证同一个规范路径与两版内容版本,核对 +一次正文读取及已执行的大小查询,检查后缀没有新的子文件访问, +并重放真实效果。源码总字节按一次变动更新,宿主读取总量按 +实际读取次数更新。已关闭的子文件不进入活动扫描器字节数。 + +新用例包含两次实际大小查询、一次正文读取和后缀引用子文件内 +定义。连同入口长度变化和 XeTeX 整行编辑在内的五项管线测试 +与两项记账单测均通过。变化后的 PDF、SVG、页面、日志、来源映射及宿主资源轨迹 +均与独立全量一致。 + +冻结 A4 只改子文件的三次实测也与各自独立全量逐项相同,每次 +都读取该子文件五次,流式读取为零。第一次执行 78,475 步,后两次 +各跳过 20,618 步后缀,实际执行 57,863 和 57,857 步。 +子文件 185 → 188 → 185 字节,最终源码字节相应 ±3,宿主读量 +±15,最终扫描器字节为零,宿主读取次数保持 93。当前样本使用 +诊断构建。原始核对在 `target/p4-child-source-splice/a4-child-only/`。 +浏览器 100 ms 条件仍待在发布构建上实测。 + ## 2026-12-02 XeTeX 整行编辑复用 XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他 diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 9fa209b..949ddc9 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -1,5 +1,5 @@ //! Reuse a recorded entry prefix only after validating the current job host. -use super::checkpoint_probe::{Call, RecordingHost}; +use super::checkpoint_probe::{Call, ClosedSourceUsageOffset, RecordingHost, closed_source_reads}; use super::*; #[cfg(test)] use std::fs; @@ -10,7 +10,7 @@ use std::{ time::Instant, }; use texrra_tex_core::{ - execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport}, + execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport}, resources::{ResourceKind, ResourceLookup, ResourceReadRange}, }; #[cfg(test)] @@ -59,9 +59,17 @@ struct CompletedExecution { result: Arc, guard: PrefixInputGuard, calls: Arc<[Call]>, + trace: ResourceTrace, settled: BTreeMap, } +struct ClosedSourceSuffix { + source_id: usize, + prefix_resource_reads: usize, + version: ResourceVersion, + usage: ClosedSourceUsageOffset, +} + struct SettledCheckpoint { entry: Arc, host: crate::native_job::ReplayBoundary, @@ -417,6 +425,7 @@ impl<'a> CapturedEntries<'a> { prior: &SettledCheckpoint, completed: &CompletedExecution, end_statistics: Option<&StatisticsReport>, + closed_source: Option<&ClosedSourceSuffix>, host: &mut RecordingHost, cancellation: &Cancellation, ) -> Result<(), String> { @@ -426,9 +435,10 @@ impl<'a> CapturedEntries<'a> { let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len(); let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1); let mut later = [const { None }; SOURCE_INTERVALS]; - // Untranslated live continuations and their source intervals still - // refer to the old entry when its length changed. - if previous_bytes == bytes + // Carried checkpoints still carry the donor's scanner and source + // allocations. An exhausted child edit also changes that history. + if closed_source.is_none() + && previous_bytes == bytes && let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) { // Keep the deepest compatible settled continuation per source interval. @@ -451,7 +461,7 @@ impl<'a> CapturedEntries<'a> { let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { continue; }; - host.replay_suffix(calls, end_statistics, cancellation)?; + host.replay_suffix(calls, end_statistics, None, cancellation)?; replayed = anchor.call_count; if anchor.host == host.files().replay_boundary() { let regular = CaptureSlots { @@ -464,7 +474,16 @@ impl<'a> CapturedEntries<'a> { self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); } } - host.replay_suffix(&completed.calls[replayed..], end_statistics, cancellation)?; + host.replay_suffix( + &completed.calls[replayed..], end_statistics, closed_source.map(|child| child.usage), + cancellation, + )?; + if let Some(child) = closed_source { + let (trace, calls) = host.prefix().ok_or("child suffix host observations are unavailable")?; + if closed_source_reads(&child.version, trace, calls) != Some(child.prefix_resource_reads) { + return Err("completed suffix observed the changed child again".into()); + } + } completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) } @@ -521,17 +540,18 @@ impl<'a> CapturedEntries<'a> { recording.generated_outputs(), self.initial?, ).ok()?; - Some(guard) + Some((guard, trace.clone())) }).flatten(); let mut calls = recording.into_calls()?; if completion.is_none() { calls.truncate(replay_count); } let calls = Arc::<[Call]>::from(calls); - let completion = completion.map(|guard| Arc::new(CompletedExecution { + let completion = completion.map(|(guard, trace)| Arc::new(CompletedExecution { result: result.clone(), guard, calls: calls.clone(), + trace, settled: self.settled, })); Some(Arc::new(CheckpointSet { @@ -996,23 +1016,38 @@ impl SelectedCheckpoint { let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else { return CheckpointDecision::Continue; }; - let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| { + let Some((completed, old, execution, layout, closed_source)) = suffixes.clone().find_map(|completed| { let old = completed.settled.get(&page)?; - let host_matches = measure(&mut timings.suffix_host_validation, timed, || { - old.call_count == new.call_count - && new.host.matches_for_suffix(&old.host) + let closed_source = measure(&mut timings.suffix_host_validation, timed, || { + if old.call_count != new.call_count { + return None; + } + if new.host.matches_for_suffix(&old.host) && can_replay_completed_suffix(completed, request, host.files()) - }); - if !host_matches { - return None; - } + { + return Some(None); + } + let change = entry.closed_source_change(&old.entry, &completed.result.execution)?; + prove_closed_source_suffix(change, old, new, completed, request, host) + .map(Some) + })?; let kernel_timings = timed.then_some(&mut timings.suffix_kernel); let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || { - entry.splice_settled_suffix_observed( - &old.entry, &completed.result.execution, kernel_timings, - ) + if let Some(child) = &closed_source { + entry.splice_settled_closed_source_suffix_observed( + &old.entry, + &completed.result.execution, + child.source_id, + child.prefix_resource_reads, + kernel_timings, + ) + } else { + entry.splice_settled_suffix_observed( + &old.entry, &completed.result.execution, kernel_timings, + ) + } })?; - Some((completed, old, execution, layout)) + Some((completed, old, execution, layout, closed_source)) }) else { return CheckpointDecision::Continue; }; @@ -1024,7 +1059,8 @@ impl SelectedCheckpoint { }); let replayed = measure(&mut timings.suffix_host_replay, timed, || { captures.replay_settled_suffix( - page, &entry, old, completed, end_statistics, host, &cancellation, + page, &entry, old, completed, end_statistics, + closed_source.as_ref(), host, &cancellation, ) }); if let Err(error) = replayed { @@ -1090,6 +1126,61 @@ fn can_replay_completed_suffix( completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok() } +fn prove_closed_source_suffix( + change: ClosedSourceChange<'_>, + old: &SettledCheckpoint, + current: &SettledCheckpoint, + completed: &CompletedExecution, + request: &CompileRequest, + host: &RecordingHost<'_>, +) -> Option { + let path = Path::new(change.name); + let guard = &completed.guard; + let next_project = request.project.as_deref()?; + if path == guard.entry || !guard.immutable.contains(path) || guard.generated.contains(path) + || !guard.project.immutable_paths().eq(next_project.immutable_paths()) + { + return None; + } + // The child route cannot simultaneously relocate or replace the entry. + if guard.project.file(&guard.entry)?.version != next_project.file(&guard.entry)?.version { + return None; + } + let previous = &guard.project.file(path)?.version; + let current_version = &next_project.file(path)?.version; + if previous == current_version || previous.path != path || current_version.path != path + || previous.bytes != u64::try_from(change.previous_bytes).ok()? + || current_version.bytes != u64::try_from(change.current_bytes).ok()? + { + return None; + } + let (trace, calls) = host.prefix()?; + if calls.len() != current.call_count || trace.project_version.as_ref() != Some(next_project.version()) { + return None; + } + let prefix_resource_reads = closed_source_reads( + previous, old.host.trace_for_suffix(), completed.calls.get(..old.call_count)?, + )?; + // In the donor's whole job, the only observations of the child must + // be the reads already present at the splice. The live prefix has + // actually made the same count of allowed observations of its new version. + if closed_source_reads(previous, &completed.trace, &completed.calls)? != prefix_resource_reads + || closed_source_reads(current_version, trace, calls)? != prefix_resource_reads + || !current.host.matches_for_closed_source_suffix(&old.host, previous, current_version) + { + return None; + } + let files = host.files(); + let project = guard.verify_project_with_closed_source(request, Some(path)).ok()?; + guard.verify_host(project, files.replay_world(), files.preparation()).ok()?; + Some(ClosedSourceSuffix { + source_id: change.source_id, + prefix_resource_reads, + version: current_version.clone(), + usage: ClosedSourceUsageOffset::new(previous.bytes, current_version.bytes, prefix_resource_reads)?, + }) +} + fn changed_line_start(previous: &[u8], current: &[u8]) -> Option { if previous == current { return None; @@ -1317,6 +1408,14 @@ impl PrefixInputGuard { fn verify_project<'a>( &self, request: &'a CompileRequest, + ) -> Result<&'a ProjectSnapshot, String> { + self.verify_project_with_closed_source(request, None) + } + + fn verify_project_with_closed_source<'a>( + &self, + request: &'a CompileRequest, + closed_source: Option<&Path>, ) -> Result<&'a ProjectSnapshot, String> { let old = &self.original; if old.input != request.input @@ -1354,6 +1453,7 @@ impl PrefixInputGuard { let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and( |(old, new)| { old.version == new.version + || closed_source == Some(path.as_path()) || self.nested_source.as_ref().is_some_and(|source| &source.path == path) || self.immutable_sizes.get(path) == Some(&new.version.bytes) || self.immutable_stream_prefixes.get(path).is_some_and(|&end| { diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index bacf1d9..ebb5cdc 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -42,6 +42,75 @@ pub(super) struct RebindableSourceObservations { pub(super) size: Option, } +#[derive(Clone, Copy)] +pub(super) struct ClosedSourceUsageOffset { + previous: u64, + current: u64, +} + +impl ClosedSourceUsageOffset { + pub(super) fn new(previous: u64, current: u64, reads: usize) -> Option { + let reads = u64::try_from(reads).ok()?; + Some(Self { + previous: previous.checked_mul(reads)?, + current: current.checked_mul(reads)?, + }) + } +} + +/// Return the entire byte-read count of a closed immutable child, including +/// typed size queries. Every other observation of the child rules out reuse. +pub(super) fn closed_source_reads( + version: &ResourceVersion, + trace: &ResourceTrace, + calls: &[Call], +) -> Option { + let path = &version.path; + if trace.stream_reads.iter().any(|read| &read.path == path) + || trace.file_modifications.iter().any(|item| &item.path == path) + || trace.generated_lookups.iter().any(|lookup| &lookup.target == path) + || trace.format_input_bindings.iter().any(|(old, current)| old == path || current == path) + || trace.read_errors.iter().any(|(read, _)| read == path) + || !trace.namespace_capture_failures.is_empty() + { + return None; + } + let mut sources = 0usize; + let mut sizes = 0usize; + for call in calls { + match call { + Call::ReadSource(source) => { + if let Ok(read) = &source.expected + && &read.path == path + { + if read != version { + return None; + } + sources += 1; + } + } + Call::FileSize(size) if size.read.as_ref().is_some_and(|read| &read.path == path) => { + // A size query can have been replayed from an equal-sized + // earlier source. Its exact path and numeric result are + // evidence, while the actual trace authenticates the bytes. + if call.observed_file_size() != Some((path.as_path(), version.bytes)) { + return None; + } + sizes += 1; + } + _ => {} + } + } + let count = sources.checked_add(sizes)?; + let mut actual = trace.reads.iter().filter(|read| &read.path == path); + if sources != 1 || actual.clone().count() != count || !actual.all(|read| read == version) { + return None; + } + let mut lookups = trace.lookups.iter().filter(|lookup| lookup.resolved.as_ref() == Some(path)); + (lookups.clone().count() == count && lookups.all(|item| item.kind == ResourceKind::Tex)) + .then_some(count) +} + impl Call { pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> { let Self::FileSize(read) = self else { return None }; @@ -178,6 +247,7 @@ impl<'a> RecordingHost<'a> { &mut self, calls: &[Call], end_statistics: Option<&StatisticsReport>, + closed_source: Option, cancellation: &Cancellation, ) -> Result<(), String> { let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?; @@ -196,6 +266,18 @@ impl<'a> RecordingHost<'a> { Call::EndStatistics(Arc::new(translated.clone())) } } + Call::ResourceUsage(read) if closed_source.is_some_and(|bytes| bytes.previous != bytes.current) => { + let bytes = closed_source.expect("checked closed source adjustment"); + let mut observed = read.observed.clone(); + if let Some(usage) = &mut observed { + usage.rebind_entry_bytes(bytes.previous, bytes.current) + .ok_or("invalid replayed child resource usage")?; + } + Call::ResourceUsage(Arc::new(ResourceUsageRead { + observed, + entry_bytes: read.entry_bytes, + })) + } call => call.clone(), }; call.replay(self.files, None)?; diff --git a/src/native_job.rs b/src/native_job.rs index a45263a..2315bb2 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -169,6 +169,42 @@ impl ReplayBoundary { pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool { self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state } + + pub(super) fn trace_for_suffix(&self) -> &texrra_tex_core::resources::ResourceTrace { + &self.state.trace + } + + /// The caller proves that all reads of this canonical path are the + /// closed source or its typed size queries, and that none are in the tail. + pub(super) fn matches_for_closed_source_suffix( + &self, + prior: &Self, + previous: &ResourceVersion, + current: &ResourceVersion, + ) -> bool { + if self.entry_bytes.is_none() || self.entry_bytes != prior.entry_bytes { + return false; + } + let ReplayState { + inputs, outputs, next_handle, columns, terminal_enabled, generated_reads, + generated_before, generated_written, trace, stream_events, + } = &self.state; + let old = &prior.state; + if inputs != &old.inputs || outputs != &old.outputs || next_handle != &old.next_handle + || columns != &old.columns || terminal_enabled != &old.terminal_enabled + || generated_reads != &old.generated_reads || generated_before != &old.generated_before + || generated_written != &old.generated_written || stream_events != &old.stream_events + { + return false; + } + let mut old_trace = old.trace.clone(); + for read in &mut old_trace.reads { + if read == previous { + *read = current.clone(); + } + } + *trace == old_trace + } } #[derive(PartialEq, Eq)] diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 223e254..e2806e1 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1918,6 +1918,78 @@ fn settled_suffix_translates_final_retained_statistics_for_unequal_histories() { fs::remove_dir_all(cwd).unwrap(); } +#[test] +fn settled_suffix_reuses_an_exhausted_child_and_adjusts_repeated_resource_reads() { + use texrra_tex_core::execution::{Event, ResourceUsage, StatisticsPhase}; + + let cwd = directory("closed-child-suffix"); + let child = cwd.join("chapter.tex"); + let body = r" +\tracingstats=1 +\shipout\hbox{Cover}\relax +\begingroup +\count0=\pdffilesize{chapter.tex}\relax +\count0=\pdffilesize{chapter.tex}\relax +\endgroup +\input chapter.tex +\shipout\hbox{Page with \childtext}\relax +\shipout\hbox{Suffix with \childtext}\relax +\endinput\shipout\hbox{Final}\relax\end +"; + let child_source = |comment| format!("% {comment}\n\\def\\childtext{{Body}}\n").into_bytes(); + let previous_bytes = child_source("old"); + let current_bytes = child_source("the expanded frozen comment"); + let extra = current_bytes.len() - previous_bytes.len(); + let end_usage = |result: &CompiledDocument| -> ResourceUsage { + let Some(Event::Statistics(report)) = result.execution.execution.events.last() else { + panic!("missing final resource report"); + }; + let StatisticsPhase::End { usage, .. } = &report.phase else { + panic!("expected final resource report"); + }; + usage.clone() + }; + + let mut definition = atomic_definition(&cwd, 1, body); + definition.files.insert(child.clone(), Arc::from(previous_bytes)); + let project = ProjectSnapshot::new(definition).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let original = session.compile(request.clone().with_project(project.clone())).unwrap(); + + let project = project.with_file_edits( + 2, [(child.clone(), Arc::from(current_bytes))].into(), + ).unwrap(); + let input = request.with_project(project); + let updated = session.compile(input.clone()).unwrap(); + let work = &updated.entry_checkpoint_work; + assert!(!work.reused_completion && work.reused_suffix_steps > 0, "{work:?}"); + let actual_child_reads = updated.resources.trace.reads.iter().filter(|read| read.path == child).count(); + assert_eq!(actual_child_reads, 3); + let before = end_usage(&original); + let after = end_usage(&updated); + assert_eq!(after.source_payload_bytes, before.source_payload_bytes + extra); + assert_eq!(after.mouth_payload_bytes, before.mouth_payload_bytes); + assert_eq!( + after.host.unwrap().resource_bytes_read, + before.host.unwrap().resource_bytes_read + (actual_child_reads * extra) as u64, + ); + assert_ne!(updated.source_map.pages, original.source_map.pages); + 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.resources.stream_io, full.resources.stream_io); + assert_eq!(updated.pdf, full.pdf); + assert_eq!(updated.pages, full.pages); + assert_eq!(updated.source_map.sources, full.source_map.sources); + assert_eq!(updated.source_map.pages, full.source_map.pages); + assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + assert_eq!(log, fs::read(cwd.join("job.log")).unwrap()); + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn resized_entry_prefix_reuses_verified_statistics() { let cwd = directory("resized-entry-statistics");