From 465a574124ed1aa88bad5ed2cc0c5ad3b863fff9 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 1 Dec 2026 21:16:41 +0800 Subject: [PATCH] Translate logical step counts when replaying native suffixes --- .../src/execution/engine/continuation.rs | 87 +++++++++++---- .../src/execution/engine/statistics.rs | 66 ++--------- crates/texrra-tex-core/src/execution/mod.rs | 5 + .../src/execution/statistics.rs | 104 ++++++++++++++++++ docs/P2_M1_PROGRESS.md | 26 +++++ src/native_checkpoint_guard.rs | 9 +- src/native_checkpoint_probe.rs | 30 ++++- tests/native_pipeline.rs | 96 ++++++++++++++++ 8 files changed, 337 insertions(+), 86 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index 2e0e076..f1a5b7a 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -121,6 +121,13 @@ impl EntryCheckpoint { { return None; } + let offset = StepOffset::new(old.steps, current.steps); + let steps = offset.apply(completed.steps)?; + // Kernel work only advances the step counter. A successful suffix + // remains within budget if its translated final count does. + if steps > current.limits.steps { + return None; + } let mut sources = completed.sources.clone(); sources[self.entry] = current.sources[self.entry].clone(); let tail = completed.events.get(old.events.len()..)?; @@ -130,7 +137,13 @@ impl EntryCheckpoint { // The joined events are published results. Resumption always starts // from a live checkpoint, whose original shared allocations stay intact. let mut events = current.events.clone().into_vec(); - events.extend_from_slice(tail); + if offset.is_identity() { + events.extend_from_slice(tail); + } else { + for event in tail { + events.push(offset_event_steps(event, offset)?); + } + } Some(Execution { format_dumped: completed.format_dumped, format_pdf_images: completed.format_pdf_images.clone(), @@ -150,7 +163,7 @@ impl EntryCheckpoint { reads: completed.reads.clone(), incoming_state: completed.incoming_state, outgoing_state: completed.outgoing_state, - steps: completed.steps, + steps, reads_event_history: false, accounts_event_history: completed.accounts_event_history, }) @@ -162,7 +175,7 @@ impl EntryCheckpoint { &'a self, prior: &'a Self, completed: &Execution, - ) -> Option Option + 'a> { + ) -> Option Option + 'a> { // 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 @@ -191,7 +204,8 @@ impl EntryCheckpoint { } } } - Some(move |later: &Self| self.rebase_verified_suffix(prior, later, &prefix)) + let mut adjusted_chunks = BTreeMap::new(); + Some(move |later: &Self| self.rebase_verified_suffix(prior, later, &prefix, &mut adjusted_chunks)) } fn rebase_verified_suffix( @@ -199,14 +213,21 @@ impl EntryCheckpoint { prior: &Self, later: &Self, prefix: &ExecutionEvents, + adjusted_chunks: &mut BTreeMap>>, ) -> Option { let old = &prior.executor; let next = &later.executor; let current = &self.executor; + let offset = StepOffset::new(old.steps, current.steps); + let steps = offset.apply(next.steps)?; if later.entry != self.entry || later.active_source != self.entry || later.frontier < self.frontier - || later.completed_steps() <= self.completed_steps() + || steps <= current.steps + || steps > current.limits.steps + // An active builder can hold a budget established before + // capture. Its limit cannot be translated by changing steps. + || (!offset.is_identity() && !is_idle_continuation(next)) || later.incoming_state != self.incoming_state || next.reads_event_history || !Arc::ptr_eq(&next.sources[later.entry], &old.sources[prior.entry]) @@ -220,9 +241,25 @@ impl EntryCheckpoint { let mut events = prefix.clone(); // Checkpoint capture seals the event log. Share the old suffix // chunks so all carried checkpoints keep the same allocation graph. - events.prefix.extend_from_slice(&next.events.prefix[old.events.prefix.len()..]); + for chunk in &next.events.prefix[old.events.prefix.len()..] { + if offset.is_identity() || !chunk.iter().any(|event| matches!(event, Event::Statistics(_))) { + events.prefix.push(chunk.clone()); + continue; + } + let address = Arc::as_ptr(chunk) as usize; + let adjusted = match adjusted_chunks.entry(address) { + std::collections::btree_map::Entry::Occupied(entry) => entry.get().clone(), + std::collections::btree_map::Entry::Vacant(entry) => { + let events = chunk.iter().map(|event| offset_event_steps(event, offset)) + .collect::>>()?; + entry.insert(Arc::new(events)).clone() + } + }; + events.prefix.push(adjusted); + } events.prefix_len += next.events.prefix_len - old.events.prefix_len; executor.events = events; + executor.steps = steps; executor.sources[self.entry] = current.sources[self.entry].clone(); let InputFrame::Source { source, mouth, .. } = executor.inputs.first_mut()? else { return None; @@ -248,6 +285,27 @@ impl EntryCheckpoint { } } +fn offset_event_steps(event: &Event, offset: StepOffset) -> Option { + match event { + Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))), + _ => Some(event.clone()), + } +} + +fn is_idle_continuation(e: &Executor) -> bool { + e.output_frame.is_none() + && e.paragraph.is_none() + && e.box_frames.is_empty() + && e.math.is_empty() + && e.display.is_none() + && e.alignments.is_empty() + && e.pdf_link_stack.is_empty() + && e.pdf_active_thread.is_none() + && e.pdf_space_probe.is_none() + && e.pdf_images.is_empty() + && !e.reads_event_history +} + fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { // Every field belongs to one of these checks. Adding kernel state requires // an explicit decision here before a later execution may be skipped. @@ -275,7 +333,6 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { conditionals, in_csname, command_trace_mode, - steps, ligature_carry, current, expression_depth, @@ -323,6 +380,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { [ inputs, sources, + steps, meaning_reads, events, reads_event_history, @@ -344,20 +402,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { ) { return false; } - let idle = |e: &Executor| { - e.output_frame.is_none() - && e.paragraph.is_none() - && e.box_frames.is_empty() - && e.math.is_empty() - && e.display.is_none() - && e.alignments.is_empty() - && e.pdf_link_stack.is_empty() - && e.pdf_active_thread.is_none() - && e.pdf_space_probe.is_none() - && e.pdf_images.is_empty() - && !e.reads_event_history - }; - if !idle(current) || !idle(prior) { + if !is_idle_continuation(current) || !is_idle_continuation(prior) { return false; } #[cfg(all(target_os = "linux", target_env = "gnu"))] diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 548bb75..688ddf9 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -197,8 +197,10 @@ impl Executor { let mut old_history = collector(); Self::collect_event_usage(self.events.iter(), &mut history); Self::collect_event_usage(old.events.iter(), &mut old_history); - let live = self.collect_live_usage(None, None, collector().tracking_aliases()); + 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. + live.usage.steps = old_live.usage.steps; live.has_equivalent_history(&old_live, &history, &old_history) }) } @@ -229,20 +231,9 @@ impl Executor { .resource_usage() .map_err(|e| self.error(e, self.current))?; let after = self.resource_usage(None, host); - let text = format!( - "Route-D resources at shipout: active records {} -> {}; retained records {} -> {}; token cells {} -> {}; retained pages {}.\n", - before.active_material.records(), - after.active_material.records(), - before.retained_material.records(), - after.retained_material.records(), - before.macro_token_cells + before.token_list_cells, - after.macro_token_cells + after.token_list_cells, - after.retained_shipouts - ); self.emit_statistics( StatisticsPhase::Shipout { before, after }, WriteDestination::TerminalAndLog, - text, files, ) } @@ -259,46 +250,9 @@ impl Executor { .resource_usage() .map_err(|e| self.error(e, self.current))?; let usage = self.resource_usage(None, host); - let mut text = format!( - "Route-D resource usage at core execution end ({}):\n {} steps out of {}\n {} source files, {} source payload bytes, {} active mouth payload bytes\n {} command entries, {} control-name bytes\n {} macro bindings, {} unique macro bodies, {} macro token cells\n {} token-list cells, {} saved entries\n {} active material records, {} retained material records, {} retained pages\n {} font instances, {} font parameter cells, {} TFM resources / {} source bytes\n {} hyphenation exceptions\n stack peaks: {} input, {} group, {} box, {} math, {} conditional, {} scanner, {} expansion\n", - if success { "success" } else { "failure" }, - usage.steps, - usage.step_limit, - usage.source_files, - usage.source_payload_bytes, - usage.mouth_payload_bytes, - usage.state.command_entries, - usage.state.control_name_bytes, - usage.state.macro_bindings, - usage.unique_macro_bodies, - usage.macro_token_cells, - usage.token_list_cells, - usage.state.save_entries, - usage.active_material.records(), - usage.retained_material.records(), - usage.retained_shipouts, - usage.state.font_instances, - usage.state.font_parameter_cells, - usage.state.tfm_resources, - usage.state.tfm_resource_bytes, - usage.state.hyphenation_exceptions, - usage.stack_peaks.input_frames, - usage.stack_peaks.groups, - usage.stack_peaks.box_frames, - usage.stack_peaks.math_frames, - usage.stack_peaks.conditionals, - usage.stack_peaks.scanner_depth, - usage.stack_peaks.expansion_depth - ); - if let Some(h) = &usage.host { - text.push_str(&format!(" host resources: {} reads / {} bytes; {} lookups / {} misses / {} errors; {} stream reads / {} bytes\n",h.resource_reads,h.resource_bytes_read,h.lookups,h.negative_lookups,h.failed_lookups,h.stream_read_calls,h.stream_bytes_read)); - } else { - text.push_str(" host resource telemetry unavailable\n"); - } self.emit_statistics( StatisticsPhase::End { success, usage }, WriteDestination::Log, - text, files, ) } @@ -306,23 +260,17 @@ impl Executor { &mut self, phase: StatisticsPhase, destination: WriteDestination, - text: String, files: &mut impl SourceProvider, ) -> Result<(), Error> { - self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(text.len()); + let report = StatisticsReport::new(phase, destination, self.current); + self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(report.text.len()); if self.diagnostic_bytes > self.limits.tokens { return self.fail("native diagnostic output limit exceeded"); } files - .observe_diagnostic(destination, &text) + .observe_statistics(&report) .map_err(|e| self.error(e, self.current))?; - self.events - .push(Event::Statistics(Box::new(StatisticsReport { - phase, - destination, - text, - span: self.current, - }))); + self.events.push(Event::Statistics(Box::new(report))); Ok(()) } } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index de20027..be0193b 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -55,6 +55,7 @@ mod vertical_break; pub use statistics::{ HostResourceUsage, MaterialUsage, ResourceUsage, StackUsage, StateUsage, StatisticsPhase, StatisticsReport, + StepOffset, }; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; @@ -375,6 +376,10 @@ pub trait SourceProvider { ) -> Result<(), String> { Ok(()) } + /// Observe resource accounting while preserving the typed report for replay. + fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> { + self.observe_diagnostic(report.destination, &report.text) + } /// Observe a diagnostic that starts at the current output column. fn observe_inline_diagnostic( &mut self, diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index a323623..576195a 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -145,6 +145,110 @@ pub struct StatisticsReport { pub span: Span, } +/// Maps monotone step counts after one command boundary onto another. +#[derive(Clone, Copy)] +pub struct StepOffset { + previous: usize, + current: usize, +} + +impl StepOffset { + pub fn new(previous: usize, current: usize) -> Self { + Self { previous, current } + } + + pub fn is_identity(self) -> bool { + self.previous == self.current + } + + pub fn apply(self, steps: usize) -> Option { + self.current.checked_add(steps.checked_sub(self.previous)?) + } +} + +impl StatisticsReport { + pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self { + let text = phase.text(); + Self { phase, destination, text, span } + } + + pub fn with_step_offset(&self, offset: StepOffset) -> Option { + 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)?; + } + StatisticsPhase::End { usage, .. } => usage.steps = offset.apply(usage.steps)?, + } + let report = Self::new(phase, self.destination, self.span); + if let StatisticsPhase::End { usage, .. } = &report.phase + && usage.diagnostic_bytes_generated.checked_add(report.text.len())? > usage.token_limit + { + return None; + } + Some(report) + } +} + +impl StatisticsPhase { + fn text(&self) -> String { + match self { + Self::Shipout { before, after } => { + format!( + "Route-D resources at shipout: active records {} -> {}; retained records {} -> {}; token cells {} -> {}; retained pages {}.\n", + before.active_material.records(), + after.active_material.records(), + before.retained_material.records(), + after.retained_material.records(), + before.macro_token_cells + before.token_list_cells, + after.macro_token_cells + after.token_list_cells, + after.retained_shipouts + ) + } + Self::End { success, usage } => { + let mut text = format!( + "Route-D resource usage at core execution end ({}):\n {} steps out of {}\n {} source files, {} source payload bytes, {} active mouth payload bytes\n {} command entries, {} control-name bytes\n {} macro bindings, {} unique macro bodies, {} macro token cells\n {} token-list cells, {} saved entries\n {} active material records, {} retained material records, {} retained pages\n {} font instances, {} font parameter cells, {} TFM resources / {} source bytes\n {} hyphenation exceptions\n stack peaks: {} input, {} group, {} box, {} math, {} conditional, {} scanner, {} expansion\n", + if *success { "success" } else { "failure" }, + usage.steps, + usage.step_limit, + usage.source_files, + usage.source_payload_bytes, + usage.mouth_payload_bytes, + usage.state.command_entries, + usage.state.control_name_bytes, + usage.state.macro_bindings, + usage.unique_macro_bodies, + usage.macro_token_cells, + usage.token_list_cells, + usage.state.save_entries, + usage.active_material.records(), + usage.retained_material.records(), + usage.retained_shipouts, + usage.state.font_instances, + usage.state.font_parameter_cells, + usage.state.tfm_resources, + usage.state.tfm_resource_bytes, + usage.state.hyphenation_exceptions, + usage.stack_peaks.input_frames, + usage.stack_peaks.groups, + usage.stack_peaks.box_frames, + usage.stack_peaks.math_frames, + usage.stack_peaks.conditionals, + usage.stack_peaks.scanner_depth, + usage.stack_peaks.expansion_depth + ); + if let Some(h) = &usage.host { + text.push_str(&format!(" host resources: {} reads / {} bytes; {} lookups / {} misses / {} errors; {} stream reads / {} bytes\n",h.resource_reads,h.resource_bytes_read,h.lookups,h.negative_lookups,h.failed_lookups,h.stream_read_calls,h.stream_bytes_read)); + } else { + text.push_str(" host resource telemetry unavailable\n"); + } + text + } + } + } +} + #[derive(Clone, Copy)] pub(super) enum Ownership { Active, diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 1991b89..3969748 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,32 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-12-01 逻辑步数变化后复用已核验的后缀 + +会合时用当前已完成步数加上旧后缀实际执行的步数。全程保留原有 +内核状态、材料、来源、依赖和宿主核验。换算超出步数上限则继续 +真实执行并给出对应诊断。调整后的检查点仅在布局帧已经结束时 +传给后续编辑,以避免沿用活动帧此前保存的预算。 + +出页和收尾的结构化统计使用换算后的计数,收尾诊断以同一格式 +生成并重放到当前日志,仍核对诊断字节上限。定向用例用相同长度的 +两种宏调用分别增加和减少步数,两个方向都复用后缀。结构化统计、 +PDF、来源及日志与独立全量一致。将步数上限设为原任务总数后, +增加步数的版本与独立全量报同样的错,保留上一版 PDF。 + +原样 12 页 NeurIPS 先改第 3 页标点,随后改第 9 页分号。 +总执行步数由 19,570,891 增至 19,570,892。第二次从第 620 行 +恢复,执行 1,030,251 步,跳过 935,951 步后缀,只更新第 9 页。 +完整执行、PDF、SVG、来源、依赖、文件流及 aux/out/log 均逐轮 +与同版独立全量一致。旧证据相同修改曾跳过零步,两个版本对应的 +PDF、SVG 仍逐字节一致。 + +优化构建和四项定向回归通过。证据在 target/p4-step-offset/, +SHA256SUMS 指纹为 +a89992a774bbde20a66d18106ae8fe7e30eab4cad46b8071f2bee6540443e122。 +后续处理输入长度改变后的来源位置。一致性、可见时延与内存继续 +按产品总目标的正式门禁验收。 + ## 2026-12-01 正文编辑后保留排版材料的共享关系 原样 NeurIPS 改第 3 页标点,完整事件序列中只有四条值发生变化。 diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index dd7810d..6db8bf6 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -416,8 +416,11 @@ impl<'a> CapturedEntries<'a> { let project = self.request.project.as_deref().expect("settled replay uses a project"); let bytes = project.file(&completed.guard.entry).expect("settled entry").data.len(); 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]; - if let Some(rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) { + if let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) { // Keep the deepest compatible settled continuation per source interval. for (&page, anchor) in completed.settled.range((std::ops::Bound::Excluded(page), std::ops::Bound::Unbounded)).rev() { let interval = (anchor.entry.frontier() - 1) / stride; @@ -438,7 +441,7 @@ impl<'a> CapturedEntries<'a> { let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { continue; }; - host.replay_suffix(calls, cancellation)?; + host.replay_suffix(calls, offset, cancellation)?; replayed = anchor.call_count; if anchor.host == host.files().replay_boundary() { let regular = CaptureSlots { @@ -451,7 +454,7 @@ impl<'a> CapturedEntries<'a> { self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); } } - host.replay_suffix(&completed.calls[replayed..], cancellation)?; + host.replay_suffix(&completed.calls[replayed..], offset, cancellation)?; completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) } diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index c7ceb95..3caf1ee 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, WriteDestination}, + execution::{Error, HostResourceUsage, StatisticsPhase, StatisticsReport, StepOffset, WriteDestination}, resources::{LoadedResource, ResourceKind, ResourceVersion}, }; @@ -16,6 +16,7 @@ pub(super) enum Call { Checked(Arc), ReadSource(Arc), FileSize(Arc), + EndStatistics(Arc), } pub(super) struct SourceRead { @@ -45,6 +46,7 @@ impl Call { pub(super) fn replay(&self, files: &mut Files, partial_source: Option<&ResourceVersion>) -> Result<(), String> { match self { Self::Checked(call) => call(files), + Self::EndStatistics(report) => files.observe_statistics(report), Self::FileSize(read) => { let before = files.resource_trace().reads.len(); let observed = files.file_size(&read.name, &read.from); @@ -150,16 +152,27 @@ impl<'a> RecordingHost<'a> { self.files } - pub(super) fn replay_suffix(&mut self, calls: &[Call], cancellation: &Cancellation) -> Result<(), String> { + pub(super) fn replay_suffix( + &mut self, + calls: &[Call], + offset: StepOffset, + cancellation: &Cancellation, + ) -> Result<(), String> { let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?; if recorded.len() + calls.len() >= MAX_REPLAY_CALLS { return Err("completed suffix exceeds the host recording budget".into()); } for call in calls { check(cancellation).map_err(|error| error.to_string())?; + let call = match call { + Call::EndStatistics(report) if !offset.is_identity() => Call::EndStatistics( + Arc::new(report.with_step_offset(offset).ok_or("invalid replayed statistics")?), + ), + call => call.clone(), + }; call.replay(self.files, None)?; + recorded.push(call); } - recorded.extend_from_slice(calls); Ok(()) } @@ -384,6 +397,17 @@ impl SourceProvider for RecordingHost<'_> { let text = text.to_owned(); call!(self, observe_diagnostic(destination, &text)) } + fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> { + // Shipout reports do not write the step count in their transcript. + if !matches!(&report.phase, StatisticsPhase::End { .. }) { + return self.observe_diagnostic(report.destination, &report.text); + } + self.files.observe_statistics(report)?; + if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS { + calls.push(Call::EndStatistics(Arc::new(report.clone()))); + } + Ok(()) + } fn observe_inline_diagnostic( &mut self, destination: WriteDestination, diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 90a7e4c..273a769 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1761,6 +1761,102 @@ fn settled_suffix_carries_a_verified_prefix_into_later_edits() { fs::remove_dir_all(cwd).unwrap(); } +#[test] +fn settled_suffix_translates_step_counts_and_enforces_the_limit() { + let cwd = directory("settled-step-counts"); + let entry = cwd.join("main.tex"); + let body = |command| { + format!( + r" +\tracingstats=2 +\def\unitA{{\relax}}\def\unitB{{\relax\relax}} +\unitA\unitB +\shipout\hbox{{Cover}}\relax +{command} +\shipout\hbox{{Second}}\relax +\shipout\hbox{{Third}}\relax +\shipout\hbox{{Fourth}}\relax +\end +" + ) + }; + let original = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(r"\unitA"))).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = original.configuration(); + let edited = original + .with_file_edits( + 2, + [( + entry.clone(), + Arc::from(format!("{HEADER}{}", body(r"\unitB")).into_bytes()), + )] + .into(), + ) + .unwrap(); + let shorter = edited + .with_file_edits( + 3, + [( + entry.clone(), + Arc::from(format!("{HEADER}{}", body(r"\unitA")).into_bytes()), + )] + .into(), + ) + .unwrap(); + let mut old_steps = 0; + for (seed, project, increased) in [ + (original.clone(), edited.clone(), true), + (edited.clone(), shorter, false), + ] { + // Each direction starts with a single donor so the decreasing + // edit cannot pick an earlier completion with the same count. + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let donor = session.compile(request.clone().with_project(seed)).unwrap(); + let donor_steps = donor.execution.execution.steps; + let input = request.clone().with_project(project); + let updated = session.compile(input.clone()).unwrap(); + assert!( + updated.entry_checkpoint_work.reused_suffix_steps > 0, + "{:?}", + updated.entry_checkpoint_work + ); + if increased { + old_steps = donor_steps; + assert!(updated.execution.execution.steps > old_steps); + } else { + assert!(updated.execution.execution.steps < donor_steps); + assert_eq!(updated.execution.execution.steps, old_steps); + } + 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()); + } + + request.limits.steps = old_steps; + let limited = NativeCompiler::default().with_automatic_entry_checkpoints(); + let first = limited + .compile(request.clone().with_project(original)) + .unwrap(); + let input = request.with_project(edited); + let failure = limited.compile(input.clone()).err().unwrap().to_string(); + assert!(failure.contains("step limit exceeded"), "{failure}"); + assert_eq!(limited.latest().unwrap().revision(), first.revision()); + assert_eq!( + fs::read(cwd.join("job.pdf")).unwrap().as_slice(), + first.pdf.as_deref().unwrap() + ); + let full = NativeCompiler::default() + .compile(input) + .err() + .unwrap() + .to_string(); + assert_eq!(failure, full); + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() { let cwd = directory("settled-suffix");