diff --git a/crates/texrra-tex-core/src/execution/dependency_reads.rs b/crates/texrra-tex-core/src/execution/dependency_reads.rs index fda105f..1ffbc0a 100644 --- a/crates/texrra-tex-core/src/execution/dependency_reads.rs +++ b/crates/texrra-tex-core/src/execution/dependency_reads.rs @@ -30,15 +30,42 @@ impl DependencyReads { self.other.contains(&Dependency::ResourceStatistics) } - pub(super) fn into_ordered(self) -> BTreeSet { - let byte_catcodes = (0..=u8::MAX) - .filter(|&index| { - let index = usize::from(index); - self.byte_catcodes[index / 64] & (1 << (index % 64)) != 0 - }) - .map(|index| Dependency::CatCode(char::from(index))); - self.other.into_iter().chain(byte_catcodes).collect() + pub(super) fn is_subset(&self, other: &Self) -> bool { + self.byte_catcodes + .iter() + .zip(other.byte_catcodes) + .all(|(&bits, permitted)| bits & !permitted == 0) + && self.other.is_subset(&other.other) } + + /// Extend a completed execution with observations made only in the new prefix. + /// The caller has already checked that the prefix keeps all old observations. + pub(super) fn extend_ordered_delta(&self, prior: &Self, into: &mut BTreeSet) { + if self.byte_catcodes != prior.byte_catcodes { + into.extend(byte_catcode_dependencies(std::array::from_fn(|index| { + self.byte_catcodes[index] & !prior.byte_catcodes[index] + }))); + } + if self.other.len() != prior.other.len() { + into.extend(self.other.difference(&prior.other).cloned()); + } + } + + pub(super) fn into_ordered(self) -> BTreeSet { + self.other + .into_iter() + .chain(byte_catcode_dependencies(self.byte_catcodes)) + .collect() + } +} + +fn byte_catcode_dependencies(bits: [u64; 4]) -> impl Iterator { + (0..=u8::MAX) + .filter(move |&index| { + let index = usize::from(index); + bits[index / 64] & (1 << (index % 64)) != 0 + }) + .map(|index| Dependency::CatCode(char::from(index))) } impl Extend for DependencyReads { @@ -53,6 +80,28 @@ impl Extend for DependencyReads { mod tests { use super::*; + #[test] + fn prefix_delta_keeps_old_suffix_observations() { + let mut prior = DependencyReads::default(); + prior.extend([Dependency::CatCode('A'), Dependency::EndLineChar]); + let mut current = prior.clone(); + current.extend([ + Dependency::CatCode('ÿ'), + Dependency::CatCode('文'), + Dependency::ParagraphToken, + ]); + + assert!(prior.is_subset(¤t)); + assert!(!current.is_subset(&prior)); + let mut reads = prior.clone().into_ordered(); + reads.insert(Dependency::EscapeChar); + current.extend_ordered_delta(&prior, &mut reads); + + let mut expected = current.into_ordered(); + expected.insert(Dependency::EscapeChar); + assert_eq!(reads, expected); + } + #[test] fn cloned_record_preserves_byte_and_unicode_dependencies() { let mut read = DependencyReads::default(); diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 0857919..3fdc6ca 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -3594,6 +3594,7 @@ impl Executor { line_observations: Some(self.line_observations), events: self.events.into_vec(), steps: self.steps, + box_nodes_created: Some(self.box_nodes_created), reads_event_history: self.reads_event_history, accounts_event_history: self.accounts_event_history, }) @@ -4100,6 +4101,7 @@ impl Executor { line_observations: Some(self.line_observations), incoming_state, steps: self.steps, + box_nodes_created: Some(self.box_nodes_created), reads_event_history: self.reads_event_history, accounts_event_history: self.accounts_event_history, }) diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index 381969e..e463f7a 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -1,5 +1,6 @@ use super::super::{ source_relocation::SourceRelocation, source_relocation_events::EventRelocation, + statistics::BoxNodeOffset, }; use super::*; use std::time::{Duration, Instant}; @@ -178,6 +179,26 @@ impl EntryCheckpoint { { return None; } + let box_offset = BoxNodeOffset::new(old.box_nodes_created, current.box_nodes_created); + let box_nodes_created = match completed.box_nodes_created { + Some(donor) => Some(box_offset.apply(donor)?), + None if box_offset.is_identity() => None, + None => return None, + }; + if current.material_charge != old.material_charge { + // A capacity recount can lower the running charge and change + // which storage TeX counts. Bound every future charge on both + // histories so neither can enter that path. + let donor = completed.box_nodes_created?; + if donor == usize::MAX { + return None; + } + let remaining = donor.checked_sub(old.box_nodes_created)?; + let largest = current.material_charge.max(old.material_charge); + if largest.checked_add(remaining)? > current.limits.tokens { + 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()) @@ -245,6 +266,16 @@ impl EntryCheckpoint { let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || { let mut events = Vec::with_capacity(completed.events.len()); events.extend(current.events.iter().cloned()); + let mut reads = completed.reads.clone(); + current.reads.extend_ordered_delta(&old.reads, &mut reads); + if current.meaning_reads.len() != old.meaning_reads.len() { + reads.extend( + current.meaning_reads.keys() + .filter(|name| !old.meaning_reads.contains_key(*name)) + .cloned() + .map(Dependency::Meaning), + ); + } let mut execution = Execution { format_dumped: completed.format_dumped, format_pdf_images: completed.format_pdf_images.clone(), @@ -261,24 +292,32 @@ impl EntryCheckpoint { sources, stream_sources: completed.stream_sources.clone(), generated_inputs: completed.generated_inputs.clone(), - reads: completed.reads.clone(), + reads, line_observations, incoming_state: completed.incoming_state, outgoing_state: completed.outgoing_state, steps, + box_nodes_created, reads_event_history: false, accounts_event_history: completed.accounts_event_history, }; if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) { - relocate::append_suffix(&mut execution, tail, offset, moved, sizes, old.sources.len())?; + relocate::append_suffix( + &mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(), + )?; if execution.state != completed.state { execution.outgoing_state = execution.state.fingerprint(); } - } else if offset.is_identity() { + } else if offset.is_identity() && box_offset.is_identity() { execution.events.extend_from_slice(tail); } else { for event in tail { - execution.events.push(offset_event_steps(event, offset)?); + execution.events.push(match event { + Event::Statistics(report) => Event::Statistics(Box::new( + report.with_execution_offsets(offset, box_offset)?, + )), + _ => event.clone(), + }); } } Some(execution) @@ -305,6 +344,18 @@ impl EntryCheckpoint { { return None; } + let current = &self.executor; + let old = &prior.executor; + // Later snapshots retain the donor's meaning cache and read history. + // A successful splice proved key inclusion, so equal lengths prove + // that no new meaning lookup would be lost by carrying the snapshot. + if current.reads != old.reads + || current.meaning_reads.len() != old.meaning_reads.len() + || current.box_nodes_created != old.box_nodes_created + || current.material_charge != old.material_charge + { + return None; + } // A restored checkpoint may later be asked to account for its // history, even if the job that furnished the suffix did not. if !completed.accounts_event_history @@ -494,7 +545,6 @@ fn same_kernel_continuation( limits, interaction_mode, stream_sources, - reads, reads_tracing_macros, in_csname, command_trace_mode, @@ -515,8 +565,6 @@ fn same_kernel_continuation( restored_pdf_image_count, format_image_warnings, pdf_force_pagebox_warned, - box_nodes_created, - material_charge, mark_cells_created, diagnostic_bytes, after_group_tokens, @@ -550,6 +598,9 @@ fn same_kernel_continuation( inputs, sources, steps, + box_nodes_created, + material_charge, + reads, meaning_reads, events, reads_event_history, @@ -576,9 +627,12 @@ fn same_kernel_continuation( return false; } if current.events.len() != prior.events.len() - || current.meaning_reads.len() != prior.meaning_reads.len() - || !current.meaning_reads.keys().all(|name| prior.meaning_reads.contains_key(name)) || current.inputs.len() != prior.inputs.len() + // Statistics membership also constrains source rebinding. + || current.reads.observed_statistics() != prior.reads.observed_statistics() + || !prior.reads.is_subset(¤t.reads) + || prior.meaning_reads.len() > current.meaning_reads.len() + || !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name)) { return false; } 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 3ae30db..90c1ea2 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs @@ -1,5 +1,5 @@ use super::*; -use crate::execution::source_relocation_events::EventRelocation; +use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset}; pub(super) fn same_kernel_provenance( current: &Executor, @@ -107,6 +107,7 @@ pub(super) fn append_suffix( execution: &mut Execution, tail: &[Event], offset: StepOffset, + boxes: BoxNodeOffset, relocation: &mut EventRelocation<'_>, (previous_bytes, current_bytes): (usize, usize), source_count: usize, @@ -123,7 +124,7 @@ pub(super) fn append_suffix( } } let mut report = report - .with_step_offset(offset)? + .with_execution_offsets(offset, boxes)? .with_suffix_entry_resize(previous_bytes, current_bytes)?; report.span = map.relocate_span(report.span)?; execution.events.push(Event::Statistics(Box::new(report))); diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 5098db0..2e24c7c 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -254,8 +254,9 @@ impl Executor { Self::collect_event_usage_pair(&self.events, &old.events, collector()); let mut live = self.collect_live_usage(None, None, collector().tracking_aliases()); let old_live = old.collect_live_usage(None, None, collector().tracking_aliases()); - // The splice translates steps separately and checks the job limit. + // 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 { let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous); let Some(source) = restore(live.usage.source_payload_bytes) else { return false; }; diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index c473dbb..7f57184 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -687,6 +687,9 @@ pub struct Execution { pub incoming_state: u64, pub outgoing_state: u64, pub steps: usize, + /// Completed charge count for proving remaining box capacity at a splice. + #[serde(default, skip_serializing_if = "Option::is_none")] + box_nodes_created: Option, #[serde(default, skip_serializing_if = "std::ops::Not::not")] reads_event_history: bool, #[serde(default, skip_serializing_if = "std::ops::Not::not")] diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index c54cb54..98aaea1 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -171,6 +171,32 @@ impl StepOffset { } } +/// Translate the cumulative, saturating count of box node visits. +#[derive(Clone, Copy)] +pub(super) struct BoxNodeOffset { + previous: usize, + current: usize, +} + +impl BoxNodeOffset { + pub(super) fn new(previous: usize, current: usize) -> Self { + Self { previous, current } + } + + pub(super) fn is_identity(self) -> bool { + self.previous == self.current + } + + pub(super) fn apply(self, nodes: usize) -> Option { + let suffix_nodes = nodes.checked_sub(self.previous)?; + // A saturated donor does not reveal how much work would survive a decrease. + if self.current < self.previous && nodes == usize::MAX { + return None; + } + Some(self.current.saturating_add(suffix_nodes)) + } +} + impl StatisticsReport { pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self { let text = phase.text(); @@ -224,13 +250,26 @@ impl StatisticsReport { } pub fn with_step_offset(&self, offset: StepOffset) -> Option { + self.with_execution_offsets(offset, BoxNodeOffset::new(0, 0)) + } + + pub(super) fn with_execution_offsets( + &self, + steps: StepOffset, + boxes: BoxNodeOffset, + ) -> Option { + let translate = |usage: &mut ResourceUsage| { + usage.steps = steps.apply(usage.steps)?; + usage.box_nodes_created = boxes.apply(usage.box_nodes_created)?; + Some(()) + }; let mut phase = self.phase.clone(); match &mut phase { StatisticsPhase::Shipout { before, after } => { - before.steps = offset.apply(before.steps)?; - after.steps = offset.apply(after.steps)?; + translate(before)?; + translate(after)?; } - StatisticsPhase::End { usage, .. } => usage.steps = offset.apply(usage.steps)?, + StatisticsPhase::End { usage, .. } => translate(usage)?, } let report = Self::new(phase, self.destination, self.span); report.within_diagnostic_budget().then_some(report) @@ -616,6 +655,43 @@ impl Collector { mod tests { use super::*; + #[test] + fn box_node_offsets_require_an_exact_saturating_count() { + let max = usize::MAX; + assert_eq!(BoxNodeOffset::new(10, 12).apply(17), Some(19)); + assert_eq!(BoxNodeOffset::new(12, 10).apply(17), Some(15)); + assert_eq!(BoxNodeOffset::new(12, 10).apply(11), None); + assert_eq!(BoxNodeOffset::new(10, 12).apply(max - 1), Some(max)); + assert_eq!(BoxNodeOffset::new(10, 12).apply(max), Some(max)); + assert_eq!(BoxNodeOffset::new(10, 10).apply(max), Some(max)); + assert_eq!(BoxNodeOffset::new(12, 10).apply(max), None); + } + + #[test] + fn statistics_translate_box_counts_without_changing_the_transcript() { + let usage = |box_nodes_created| ResourceUsage { + box_nodes_created, + token_limit: 4096, + ..ResourceUsage::default() + }; + let translate = |old, expected| { + let report = StatisticsReport::new(old, WriteDestination::Log, Span::default()); + let updated = report + .with_execution_offsets(StepOffset::new(0, 0), BoxNodeOffset::new(2, 7)) + .unwrap(); + assert_eq!(updated.phase, expected); + assert_eq!(updated.text, report.text); + }; + translate( + StatisticsPhase::Shipout { before: usage(5), after: usage(8) }, + StatisticsPhase::Shipout { before: usage(10), after: usage(13) }, + ); + translate( + StatisticsPhase::End { success: true, usage: usage(8) }, + StatisticsPhase::End { success: true, usage: usage(13) }, + ); + } + #[test] fn history_equivalence_keeps_aliases_that_cross_the_boundary() { let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default()); diff --git a/crates/texrra-tex-core/src/pdf_unicode.rs b/crates/texrra-tex-core/src/pdf_unicode.rs index 4da3a00..286131c 100644 --- a/crates/texrra-tex-core/src/pdf_unicode.rs +++ b/crates/texrra-tex-core/src/pdf_unicode.rs @@ -1,6 +1,6 @@ //! pdfTeX-profile glyph-name mappings. Values retain PDF hex strings, including //! explicitly supplied UTF-16 code units; they are not Rust Unicode labels. -use std::collections::BTreeMap; +use std::{collections::BTreeMap, sync::Arc}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] enum Mapping { @@ -10,7 +10,7 @@ enum Mapping { #[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct GlyphUnicodeMap { - entries: BTreeMap, + entries: Arc>, } fn upper_hex(s: &str) -> bool { @@ -69,7 +69,7 @@ impl GlyphUnicodeMap { } } }; - self.entries.insert(glyph, mapping); + Arc::make_mut(&mut self.entries).insert(glyph, mapping); warning } /// Resolve against the actual TFM namespace and encoding glyph name. An @@ -185,10 +185,13 @@ mod tests { ] { assert_eq!(map.lookup(font, name).as_deref(), expected, "{font}/{name}"); } + let snapshot = map.clone(); assert!(map.define("A".into(), "03b1").is_some()); + assert!(Arc::ptr_eq(&map.entries, &snapshot.entries)); assert_eq!(map.lookup("g", "A").as_deref(), Some("0041")); assert!(map.define("tfm:f/A".into(), "110000").is_some()); assert_eq!(map.lookup("f", "A"), None); + assert_eq!(snapshot.lookup("f", "A").as_deref(), Some("D83DDE00")); assert_eq!(map.lookup("g", "A").as_deref(), Some("0041")); } } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 4363979..771915e 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -43,6 +43,50 @@ 依赖和计数换算,再用相同样例对照独立全量。 原始样本、阶段用时和构建指纹位于 `target/p4-browser-visible-progress/`。 +## 2026-12-02 后缀复用的依赖与盒节点计数 + +编辑后的前缀保留全部旧前缀依赖时,可把新增依赖并入结果,并保留 +被跳过的后缀依赖。旧前缀独有的依赖若消失,继续执行。资源统计读取 +仍须相同。累计盒节点数可沿用后缀增量。若两次运行的盒容量累计值 +不同,只有在证明后缀不会触发容量重算时才复用。即时发页统计和 +收尾报告同步换算,宿主重放使用内核确认的收尾报告。依赖记录或 +累计值变化后,后续快照重新捕获。 + +十四项定向管线回归和四项内核单测通过。用例覆盖新增依赖后的实际跳步、依赖减少 +时重新执行,以及累计节点数双向变化。增量与独立全量的执行、PDF、 +统计日志和来源映射通过对照。冻结 A4 的六次主文件正文编辑每次 +只更新第 1 页,复用 849,607 步前缀,仍执行剩余的 53,612 或 +53,615 步。六次均与独立全量的执行、PDF、SVG、来源、资源记录 +和生成文件一致。样本与构建清单在 +`target/p4-a4-suffix-proof/run-men4zig6/`。该批使用 opt-level 0 +的诊断构建,计时与浏览器基线分开记录。另两次带诊断探针的 +编辑到达同一发页后的检查,首个拒绝条件均为前缀事件数改变 +(680 → 694、694 → 696)。A4 的收尾统计确实计入保留事件, +后续复用须证明跨接缝的共享关系与新前缀的统计增量。诊断在 +`target/p4-a4-suffix-proof/run-rabbmwpj/run.log`。 + +原生检查点还改为共享未修改的字形 Unicode 映射,实际定义变动时 +复制。序列化格式和 PDF 字符映射按原规则生成。 + +### A4 浏览器复测 + +同一台机器的 Edge、同一份格式和资源、同一组实际输入事件。 +使用相同的 release opt-level 1 构建设置和独立试用服务。 +主文件和子文件各 30 次,均更新实际显示页。60 次输出的 PDF、 +SVG 和来源映射指纹逐项与上一批一致。 + +| A4 热编辑 | 实际执行 p50 / p95 | 编辑到可见 p50 / p95 | +| --- | ---: | ---: | +| 主文件正文 | 132.3 / 145.3 ms | 230.3 / 256.3 ms | +| 子文件正文 | 86.0 / 126.0 ms | 184.1 / 241.5 ms | + +从输入到发起请求的 p50 均为 1.5 ms。两组的响应到确认绘制 +p50 分别为 33.2 和 33.3 ms,进程峰值 RSS 为 603,280 KiB。 +本轮可见时延低于上一批,100 ms 条件仍未通过。两批实际执行 +步数一致,机器负载有变化,不能把时延差额归因于单个代码变动。 +原始样本、构建清单、机器状态和逐次输出对照在 +`target/p4-a4-browser-recheck/`。 + ## 2026-12-02 XeTeX 整行编辑复用 XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他 diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 3b5b454..9fa209b 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -10,7 +10,7 @@ use std::{ time::Instant, }; use texrra_tex_core::{ - execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, RelocatedShipoutSuffix}, + execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport}, resources::{ResourceKind, ResourceLookup, ResourceReadRange}, }; #[cfg(test)] @@ -416,6 +416,7 @@ impl<'a> CapturedEntries<'a> { current: &EntryCheckpoint, prior: &SettledCheckpoint, completed: &CompletedExecution, + end_statistics: Option<&StatisticsReport>, host: &mut RecordingHost, cancellation: &Cancellation, ) -> Result<(), String> { @@ -423,15 +424,11 @@ impl<'a> CapturedEntries<'a> { let path = &completed.guard.entry; let bytes = project.file(path).expect("settled entry").data.len(); let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len(); - let resize = (previous_bytes != bytes).then_some((previous_bytes, bytes)); let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1); - let offset = texrra_tex_core::execution::StepOffset::new( - prior.entry.completed_steps(), current.completed_steps(), - ); 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 resize.is_none() + if 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. @@ -454,7 +451,7 @@ impl<'a> CapturedEntries<'a> { let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { continue; }; - host.replay_suffix(calls, offset, None, cancellation)?; + host.replay_suffix(calls, end_statistics, cancellation)?; replayed = anchor.call_count; if anchor.host == host.files().replay_boundary() { let regular = CaptureSlots { @@ -467,7 +464,7 @@ impl<'a> CapturedEntries<'a> { self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); } } - host.replay_suffix(&completed.calls[replayed..], offset, resize, cancellation)?; + host.replay_suffix(&completed.calls[replayed..], end_statistics, cancellation)?; completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) } @@ -1020,8 +1017,15 @@ impl SelectedCheckpoint { return CheckpointDecision::Continue; }; let calls = &completed.calls[old.call_count..]; + let end_statistics = execution.events.last().and_then(|event| match event { + Event::Statistics(report) if matches!(report.phase, StatisticsPhase::End { .. }) => + Some(report.as_ref()), + _ => None, + }); let replayed = measure(&mut timings.suffix_host_replay, timed, || { - captures.replay_settled_suffix(page, &entry, old, completed, host, &cancellation) + captures.replay_settled_suffix( + page, &entry, old, completed, end_statistics, host, &cancellation, + ) }); if let Err(error) = replayed { let discarded = entry.completed_steps().saturating_sub(work.reused_steps); diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 777eeb7..bacf1d9 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -6,7 +6,7 @@ use std::fs; #[cfg(test)] use texrra_tex_core::source_map::SourceMap; use texrra_tex_core::{ - execution::{Error, HostResourceUsage, StatisticsPhase, StatisticsReport, StepOffset, WriteDestination}, + execution::{Error, HostResourceUsage, StatisticsPhase, StatisticsReport, WriteDestination}, resources::{LoadedResource, ResourceKind, ResourceVersion}, }; @@ -177,8 +177,7 @@ impl<'a> RecordingHost<'a> { pub(super) fn replay_suffix( &mut self, calls: &[Call], - offset: StepOffset, - resize: Option<(usize, usize)>, + end_statistics: Option<&StatisticsReport>, cancellation: &Cancellation, ) -> Result<(), String> { let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?; @@ -188,15 +187,14 @@ impl<'a> RecordingHost<'a> { for call in calls { check(cancellation).map_err(|error| error.to_string())?; let call = match call { - Call::EndStatistics(report) if !offset.is_identity() || resize.is_some() => { - let report = report.with_step_offset(offset).ok_or("invalid replayed statistics")?; - let report = if let Some((previous, current)) = resize { - report.with_suffix_entry_resize(previous, current) - .ok_or("invalid replayed entry size in statistics")? + Call::EndStatistics(report) => { + // The kernel has already checked and translated this report. + let translated = end_statistics.ok_or("completed suffix is missing its final statistics")?; + if report.as_ref() == translated { + call.clone() } else { - report - }; - Call::EndStatistics(Arc::new(report)) + Call::EndStatistics(Arc::new(translated.clone())) + } } call => call.clone(), }; diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index c3790ee..d4c63c5 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1762,6 +1762,106 @@ fn settled_suffix_carries_a_verified_prefix_into_later_edits() { fs::remove_dir_all(cwd).unwrap(); } +#[test] +fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() { + use texrra_tex_core::execution::Dependency; + + let cwd = directory("settled-prefix-dependencies"); + let entry = cwd.join("main.tex"); + let body = |ignored| format!(r" +\catcode64=9 \catcode63=9 +?\relax +\shipout\hbox{{Cover}}\relax +{ignored}\relax +\shipout\hbox{{Checkpoint}}\relax +\shipout\hbox{{Suffix}}\relax +\endinput\shipout\hbox{{Final}}\relax\end +"); + for (before, after, reuse) in [('?', '@', true), ('@', '?', false)] { + let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let donor = session.compile(request.clone().with_project(project.clone())).unwrap(); + let new_read = Dependency::CatCode('@'); + assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@'); + let source = format!("{HEADER}{}", body(after)); + let project = project.with_file_edits( + 2, [(entry.clone(), Arc::from(source.into_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:?}"); + assert_eq!(work.reused_suffix_steps > 0, reuse, "{work:?}"); + assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@'); + 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.pdf, full.pdf); + 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 settled_suffix_translates_cumulative_box_charges_in_both_directions() { + use texrra_tex_core::execution::{Event, StatisticsPhase}; + + let cwd = directory("settled-box-charge"); + let entry = cwd.join("main.tex"); + let body = |variant| format!(r" +\tracingstats=2 +\setbox0=\vbox{{\kern1sp\kern2sp}} +\def\variantA{{\relax}} +\def\variantB{{\setbox7=\copy0\setbox7=\box9\relax}} +\variantA\variantB\relax +\shipout\hbox{{Cover}}\relax +\variant{variant}\relax +\shipout\hbox{{Checkpoint}}\relax +\shipout\hbox{{Suffix}}\relax +\endinput\shipout\hbox{{Final}}\relax\end +"); + let final_charge = |document: &CompiledDocument| { + let Some(Event::Statistics(report)) = document.execution.execution.events.last() else { + panic!("missing final resource report"); + }; + let StatisticsPhase::End { usage, .. } = &report.phase else { + panic!("expected final resource report"); + }; + usage.box_nodes_created + }; + + for (before, after) in [('A', 'B'), ('B', 'A')] { + let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let donor = session.compile(request.clone().with_project(project.clone())).unwrap(); + let source = format!("{HEADER}{}", body(after)); + let project = project.with_file_edits( + 2, [(entry.clone(), Arc::from(source.into_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:?}"); + if after == 'B' { + assert!(final_charge(&updated) > final_charge(&donor)); + } else { + assert!(final_charge(&updated) < final_charge(&donor)); + } + 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!(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");