diff --git a/crates/texrra-tex-core/src/execution/boxes.rs b/crates/texrra-tex-core/src/execution/boxes.rs index d1e112c..9d84c23 100644 --- a/crates/texrra-tex-core/src/execution/boxes.rs +++ b/crates/texrra-tex-core/src/execution/boxes.rs @@ -487,7 +487,7 @@ impl NativeBox { } } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(super) struct VerticalBuilder { pub nodes: Vec, pub prev_depth: i32, diff --git a/crates/texrra-tex-core/src/execution/dependency_reads.rs b/crates/texrra-tex-core/src/execution/dependency_reads.rs index b8415b4..fda105f 100644 --- a/crates/texrra-tex-core/src/execution/dependency_reads.rs +++ b/crates/texrra-tex-core/src/execution/dependency_reads.rs @@ -2,7 +2,7 @@ use super::Dependency; use std::collections::{BTreeSet, HashSet}; -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] pub(super) struct DependencyReads { byte_catcodes: [u64; 4], other: HashSet, diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index a05bcef..2082499 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -39,6 +39,7 @@ mod scanning; mod scheduling; mod specials; mod statistics; +mod continuation; mod xdv_annotation; #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] @@ -57,7 +58,7 @@ impl Default for Limits { } } -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq)] struct InputToken { token: Token, frozen: bool, @@ -131,7 +132,7 @@ enum InputFrame { }, Boundary, } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] enum TokenInputKind { Inserted, BackedUp, @@ -144,7 +145,7 @@ enum TheValue { Tokens(Vec), Text(std::string::String), } -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq)] struct Conditional { primitive: Primitive, inverted: bool, @@ -241,6 +242,8 @@ pub struct Executor { in_csname: bool, command_trace_mode: Option<&'static str>, events: ExecutionEvents, + // Set before operations that inspect earlier events beyond their count. + reads_event_history: bool, steps: usize, ligature_carry: super::ligature::Carry, current: Span, @@ -314,6 +317,15 @@ pub struct CheckpointSource<'a> { pub bytes: usize, pub frontier: usize, pub is_entry: bool, + pub output_returned: bool, +} + +/// Called only at a selected boundary. Reuse requires that the caller has +/// validated and replayed the previous suffix into this revision's draft. +pub enum CheckpointDecision { + Continue, + Reuse(Box), + ReplayFailed(String), } /// A live, in-memory kernel continuation at an entry-file command boundary. @@ -387,7 +399,9 @@ impl EntryCheckpoint { files: &mut impl SourceProvider, cancellation: Cancellation, ) -> Option> { - self.resume_observed(source, None, files, cancellation, None, None, |_, _, _, _| {}) + self.resume_observed(source, None, files, cancellation, None, None, + |_, _, _, _| CheckpointDecision::Continue) + .expect("ordinary resume cannot reject a cached suffix") } pub(super) fn resume_capturing_sources_after_host_replay( @@ -399,7 +413,7 @@ impl EntryCheckpoint { line_break_cache: std::sync::Arc, previous: Option<&Execution>, select: impl FnMut(CheckpointSource<'_>, usize) -> Option, - capture: impl FnMut(S, EntryCheckpoint, &mut F), + mut capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Option> { self.resume_observed( source, @@ -408,8 +422,27 @@ impl EntryCheckpoint { cancellation, Some(line_break_cache), previous, - Executor::entry_observer(self.incoming_state, select, capture), + Executor::entry_observer(self.incoming_state, select, |slot, entry, files| { + capture(slot, entry, files); + CheckpointDecision::Continue + }), ) + .expect("ordinary resume cannot reject a cached suffix") + } + + pub(super) fn resume_deciding_suffix( + &self, + source: SourceFile, + nested: Option, + files: &mut F, + cancellation: Cancellation, + line_break_cache: Arc, + previous: Option<&Execution>, + select: impl FnMut(CheckpointSource<'_>, usize) -> Option, + capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, + ) -> Result>, String> { + self.resume_observed(source, nested, files, cancellation, Some(line_break_cache), previous, + Executor::entry_observer(self.incoming_state, select, capture)) } fn resume_observed( @@ -420,15 +453,15 @@ impl EntryCheckpoint { cancellation: Cancellation, line_break_cache: Option>, previous: Option<&Execution>, - capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F), - ) -> Option> { + capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision, + ) -> Result>, String> { if !self.accepts_entry(&source) || match &nested { Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data), None => self.nested_source().is_some(), } { - return None; + return Ok(None); } let mut executor = self.executor.clone().with_cancellation(cancellation); executor.line_break_cache = line_break_cache; @@ -446,8 +479,16 @@ impl EntryCheckpoint { capture_boundary, ) }); + let result = match result { + Ok(CheckpointDecision::Reuse(execution)) => { + return Ok(Some(Ok(*execution))); + } + Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error), + Ok(CheckpointDecision::Continue) => Ok(()), + Err(error) => Err(error), + }; let result = executor.finish_observed_input(result, files); - Some(executor.finish_execution(result, self.incoming_state, previous)) + Ok(Some(executor.finish_execution(result, self.incoming_state, previous))) } } @@ -496,6 +537,7 @@ impl Executor { in_csname: false, command_trace_mode: None, events: ExecutionEvents::default(), + reads_event_history: false, steps: 0, ligature_carry: super::ligature::Carry::default(), current: Span::default(), @@ -3491,6 +3533,7 @@ impl Executor { reads, events: self.events.into_vec(), steps: self.steps, + reads_event_history: self.reads_event_history, }) } fn check_input_character(&self, code: i32) -> Result<(), Error> { @@ -3785,7 +3828,7 @@ impl Executor { files: &mut impl SourceProvider, ) -> Result { let incoming_state = self.state.fingerprint(); - let result = self.run_observed(file, files, |_, _, _, _| {}); + let result = self.run_observed(file, files, |_, _, _, _| CheckpointDecision::Continue); self.finish_execution(result, incoming_state, None) } /// Capture the first eligible entry command boundary at or beyond the @@ -3841,13 +3884,16 @@ impl Executor { file: SourceFile, files: &mut F, select: impl FnMut(CheckpointSource<'_>, usize) -> Option, - capture: impl FnMut(S, EntryCheckpoint, &mut F), + mut capture: impl FnMut(S, EntryCheckpoint, &mut F), ) -> Result { let incoming_state = self.state.fingerprint(); let result = self.run_observed( file, files, - Self::entry_observer(incoming_state, select, capture), + Self::entry_observer(incoming_state, select, |slot, entry, files| { + capture(slot, entry, files); + CheckpointDecision::Continue + }), ); self.finish_execution(result, incoming_state, None) } @@ -3855,17 +3901,17 @@ impl Executor { fn entry_observer( incoming_state: u64, mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option, - mut capture: impl FnMut(S, EntryCheckpoint, &mut F), - ) -> impl FnMut(&mut Self, usize, bool, &mut F) { + mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, + ) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision { move |engine, initial_depth, pages_processed, files| { if engine.job_ended { - return; + return CheckpointDecision::Continue; } let Some(InputFrame::Source { source: entry, eof_seen: false, pseudo_trace: None, .. }) = engine.inputs.first() else { - return; + return CheckpointDecision::Continue; }; // Retain the active scanner plus its suspended parents. A pseudo // input or an EOF hook has no replaceable physical byte prefix. @@ -3873,10 +3919,10 @@ impl Executor { source, mouth, eof_seen: false, pseudo_trace: None, .. }) = engine.inputs.iter().rev().find(|frame| matches!(frame, InputFrame::Source { .. })) else { - return; + return CheckpointDecision::Continue; }; let Some(frontier) = mouth.physical_frontier() else { - return; + return CheckpointDecision::Continue; }; let (entry, active_source) = (*entry, *source); let file = &engine.sources[active_source]; @@ -3886,14 +3932,15 @@ impl Executor { bytes: file.data.len(), frontier, is_entry: active_source == entry, + output_returned: engine.output_frame.is_none(), }; let Some(slot) = select(position, engine.shipped_pages) else { - return; + return CheckpointDecision::Continue; }; if engine.sources.iter().enumerate().any(|(index, other)| { index != active_source && other.name == file.name }) { - return; + return CheckpointDecision::Continue; } engine.events.seal_prefix(); let mut executor = engine.clone(); @@ -3908,7 +3955,7 @@ impl Executor { frontier, pages_processed, }; - capture(slot, checkpoint, files); + capture(slot, checkpoint, files) } } fn finish_execution( @@ -3989,19 +4036,22 @@ impl Executor { reads, incoming_state, steps: self.steps, + reads_event_history: self.reads_event_history, }) } fn run_observed( &mut self, file: SourceFile, files: &mut F, - capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F), + capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision, ) -> Result<(), Error> { self.check_cancellation()?; self.change_interaction_mode(self.interaction_mode, files)?; let result = self.prepare_input(file, files).and_then(|initial_depth| { self.emit_format_image_warnings(files)?; - self.run_active_input(initial_depth, false, files, capture_boundary) + self.run_active_input(initial_depth, false, files, capture_boundary).map(|action| { + debug_assert!(matches!(action, CheckpointDecision::Continue)); + }) }); self.finish_observed_input(result, files) } @@ -4116,20 +4166,26 @@ impl Executor { initial_depth: usize, mut pages_processed: bool, files: &mut F, - mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F), - ) -> Result<(), Error> { + mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision, + ) -> Result { let xe = self.state.input_profile() == InputProfile::XeTeX; loop { if !std::mem::take(&mut pages_processed) { self.check_box_capacity(None)?; - capture_boundary(self, initial_depth, false, files); + match capture_boundary(self, initial_depth, false, files) { + CheckpointDecision::Continue => {} + decision => return Ok(decision), + } let shipped_pages = self.shipped_pages; self.process_native_pages(files)?; self.check_box_capacity(None)?; if self.shipped_pages != shipped_pages { // A following expandable command can read an input before // the next main-loop iteration. - capture_boundary(self, initial_depth, true, files); + match capture_boundary(self, initial_depth, true, files) { + CheckpointDecision::Continue => {} + decision => return Ok(decision), + } } } let Some((input, meaning)) = self.expanded_with_meaning(files, false)? else { @@ -4611,7 +4667,7 @@ impl Executor { } } } - Ok(()) + Ok(CheckpointDecision::Continue) } fn assignment( &mut self, diff --git a/crates/texrra-tex-core/src/execution/engine/alignment.rs b/crates/texrra-tex-core/src/execution/engine/alignment.rs index 43e1a5f..1a9c104 100644 --- a/crates/texrra-tex-core/src/execution/engine/alignment.rs +++ b/crates/texrra-tex-core/src/execution/engine/alignment.rs @@ -4,7 +4,7 @@ use super::super::boxes::{self, PackSpec, VerticalBuilder}; use super::*; -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Boundary { Prefix, Entry, diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs new file mode 100644 index 0000000..a87b65f --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -0,0 +1,286 @@ +use super::*; + +impl InputFrame { + fn same_at_shipout(&self, other: &Self) -> bool { + match (self, other) { + ( + Self::Source { + source: a, + mouth: am, + eof_seen: ae, + pseudo_trace: at, + group_boundary: ag, + conditional_boundary: ac, + }, + Self::Source { + source: b, + mouth: bm, + eof_seen: be, + pseudo_trace: bt, + group_boundary: bg, + conditional_boundary: bc, + }, + ) => (a, ae, at, ag, ac) == (b, be, bt, bg, bc) && am.same_unread_input(bm), + ( + Self::Tokens { + tokens: a, + cursor: ac, + kind: ak, + }, + Self::Tokens { + tokens: b, + cursor: bc, + kind: bk, + }, + ) => (ac, ak) == (bc, bk) && a.iter().eq(b.iter()), + ( + Self::Macro { + definition: a, + name: an, + cursor: ac, + arguments: aa, + call: aspan, + }, + Self::Macro { + definition: b, + name: bn, + cursor: bc, + arguments: ba, + call: bspan, + }, + ) => (a, an, ac, aa, aspan) == (b, bn, bc, ba, bspan), + ( + Self::Argument { + tokens: a, + cursor: ac, + call: aspan, + }, + Self::Argument { + tokens: b, + cursor: bc, + call: bspan, + }, + ) => (a, ac, aspan) == (b, bc, bspan), + ( + Self::Hook { + parameter: a, + tokens: at, + cursor: ac, + }, + Self::Hook { + parameter: b, + tokens: bt, + cursor: bc, + }, + ) => (a, at, ac) == (b, bt, bc), + (Self::Boundary, Self::Boundary) => true, + _ => false, + } + } +} + +impl EntryCheckpoint { + /// 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 { + if self.entry != self.active_source + || prior.entry != prior.active_source + || self.entry != prior.entry + || self.initial_depth != prior.initial_depth + || self.incoming_state != prior.incoming_state + || self.frontier != prior.frontier + || self.pages_processed != prior.pages_processed + || completed.incoming_state != prior.incoming_state + || completed.reads_event_history + || completed.format_dumped + || completed.steps <= prior.completed_steps() + { + return None; + } + let current = &self.executor; + let old = &prior.executor; + if !same_kernel_continuation(current, old) { + return None; + } + if current.sources.len() != old.sources.len() + || current + .sources + .iter() + .zip(&old.sources) + .enumerate() + .any(|(id, (new, old))| { + if id == self.entry { + new.name != old.name || new.data.len() != old.data.len() + } else { + new != old + } + }) + || completed.sources.get(self.entry)? != &old.sources[self.entry] + { + return None; + } + let mut sources = completed.sources.clone(); + sources[self.entry] = current.sources[self.entry].clone(); + let tail = completed.events.get(old.events.len()..)?; + let mut events = current.events.clone().into_vec(); + events.extend_from_slice(tail); + Some(Execution { + format_dumped: completed.format_dumped, + format_pdf_images: completed.format_pdf_images.clone(), + job_name: completed.job_name.clone(), + interaction_mode: completed.interaction_mode, + native_page: completed.native_page.clone(), + split_discards: completed.split_discards.clone(), + after_assignment: completed.after_assignment.clone(), + events, + state: completed.state.clone(), + io: completed.io.clone(), + input_position: completed.input_position, + paragraph_mode: completed.paragraph_mode, + sources, + stream_sources: completed.stream_sources.clone(), + generated_inputs: completed.generated_inputs.clone(), + reads: completed.reads.clone(), + incoming_state: completed.incoming_state, + outgoing_state: completed.outgoing_state, + steps: completed.steps, + reads_event_history: false, + }) + } +} + +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. + macro_rules! same_values { + ([$($value:ident),+ $(,)?], [$($planned:ident),+ $(,)?], [$($runtime:ident),+ $(,)?]) => {{ + let Executor { + $($value,)+ + $($planned: _,)+ + $($runtime: _,)+ + #[cfg(all(target_os = "linux", target_env = "gnu"))] + pdf_last_match: _, + } = current; + true $(&& *$value == prior.$value)+ + }}; + } + if !same_values!( + [ + state, + limits, + interaction_mode, + stream_sources, + generated_inputs, + reads, + reads_tracing_macros, + conditionals, + in_csname, + command_trace_mode, + steps, + ligature_carry, + current, + expression_depth, + scanner_depth, + scanner_status, + expansion_depth, + io, + pdf_colors, + xdv_colors, + pdf_running_links, + pdf_interword_spaces, + pdf_space_font, + pdf_loaded_space_font, + pdf_virtual_fonts, + pdf_catalog_tokens, + pdf_outlines, + pdf_outline_payload, + pdf_info_tokens, + restored_pdf_image_count, + format_image_warnings, + pdf_force_pagebox_warned, + input_position, + vertical, + box_nodes_created, + material_charge, + mark_cells_created, + diagnostic_bytes, + after_assignment, + after_group_tokens, + math_tokens_processed, + native_page, + split_discards, + pending_shipouts, + shipped_pages, + job_ended, + fresh_job, + job_name, + format_loaded, + format_dumped, + writing, + stack_peaks, + alignment_balance, + ], + [ + inputs, + sources, + meaning_reads, + events, + reads_event_history, + xdv_annotations, + xdv_text, + pdf_navigation_geometry, + pdf_link_stack, + pdf_active_thread, + pdf_space_probe, + pdf_images, + paragraph, + box_frames, + math, + display, + output_frame, + alignments, + ], + [cancellation, line_break_cache] + ) { + 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) { + return false; + } + #[cfg(all(target_os = "linux", target_env = "gnu"))] + if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() { + return false; + } + current + .xdv_annotations + .same_idle_state(&prior.xdv_annotations) + && current.xdv_text.same_state(&prior.xdv_text) + && current + .pdf_navigation_geometry + .same_state(&prior.pdf_navigation_geometry) + && 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() + && current + .inputs + .iter() + .zip(&prior.inputs) + .all(|(a, b)| a.same_at_shipout(b)) +} diff --git a/crates/texrra-tex-core/src/execution/engine/page.rs b/crates/texrra-tex-core/src/execution/engine/page.rs index 0334443..c994392 100644 --- a/crates/texrra-tex-core/src/execution/engine/page.rs +++ b/crates/texrra-tex-core/src/execution/engine/page.rs @@ -1089,6 +1089,7 @@ impl Executor { .map_err(|e| self.error(e, self.current))?; let mut shared = self.pdf_space_probe.take().unwrap_or_default(); let prior = Arc::make_mut(&mut shared); + self.reads_event_history = true; for event in self.events.iter().skip(prior.observed_events) { let Event::Shipout(shipped) = event else { continue }; self.check_cancellation()?; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs index e942e73..cc17e5e 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_links.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_links.rs @@ -17,6 +17,13 @@ pub(super) struct NavigationGeometry { last_pdf_rect: [i64; 4], } +impl NavigationGeometry { + pub(super) fn same_state(&self, other: &Self) -> bool { + self.last_pdf_rect == other.last_pdf_rect + && self.matrix.map(|m| m.0.map(f64::to_bits)) == other.matrix.map(|m| m.0.map(f64::to_bits)) + } +} + #[derive(Clone)] pub(super) struct ActiveLink { layout: LinkStart, diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_match.rs b/crates/texrra-tex-core/src/execution/engine/pdf_match.rs index c673817..db2b238 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_match.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_match.rs @@ -4,6 +4,7 @@ use std::mem::MaybeUninit; use std::ops::Range; use std::ptr; +#[derive(PartialEq, Eq)] pub(super) struct PdfMatch { input: Vec, captures: Vec>>, diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 5c4633b..4e5c38c 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -25,6 +25,7 @@ impl Executor { } // Packing can move existing lists or replace an old register. Recount // actual storage here, counting each shared list allocation once. + self.reads_event_history = true; let usage = self.collect_usage(shipping, None, Collector::for_capacity()); self.material_charge = usage .active_material @@ -36,10 +37,11 @@ impl Executor { Ok(()) } fn resource_usage( - &self, + &mut self, shipping: Option<&NativeBox>, host: Option, ) -> ResourceUsage { + self.reads_event_history = true; self.collect_usage(shipping, host, Collector::default()) } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 6e68ff0..c1433bf 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -68,7 +68,7 @@ pub use case::CaseCode; pub use context::{ContextFrame, ContextKind, InputContext}; pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; -pub use engine::{CheckpointSource, EntryCheckpoint, Executor, Limits}; +pub use engine::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits}; pub use font_catalog::{ FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource, }; @@ -669,6 +669,8 @@ pub struct Execution { pub incoming_state: u64, pub outgoing_state: u64, pub steps: usize, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + reads_event_history: bool, } #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index 56c3ea1..6ef5af5 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use super::xe_encoding::{Character, Encoding}; -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq)] struct XePhysical { encoding: Encoding, autodetected: Option<(Encoding, usize)>, @@ -267,14 +267,14 @@ mod tests { assert_eq!(chars, "é界 B C "); } } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] enum LineState { New, Middle, Skip, } -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq)] enum LineBreaks { Physical, Generated(Option), @@ -297,6 +297,21 @@ pub(super) struct Mouth { } impl Mouth { + pub(super) fn same_unread_input(&self, other: &Self) -> bool { + self.source == other.source + && self.profile == other.profile + && self.offset == other.offset + && self.line == other.line + && self.cursor == other.cursor + && self.state == other.state + && self.end_after_line == other.end_after_line + && self.line_breaks == other.line_breaks + && self.line_number == other.line_number + && self.xe == other.xe + && self.invalid_utf8 == other.invalid_utf8 + && self.data[self.offset..] == other.data[other.offset..] + } + pub(super) fn physical_frontier(&self) -> Option { (matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0) .then_some(self.offset) diff --git a/crates/texrra-tex-core/src/execution/session.rs b/crates/texrra-tex-core/src/execution/session.rs index 0be2bd9..b12bb1c 100644 --- a/crates/texrra-tex-core/src/execution/session.rs +++ b/crates/texrra-tex-core/src/execution/session.rs @@ -196,7 +196,7 @@ impl RevisionJob { .map_err(|failure| failure.error) } pub fn run_detailed( - self, + &self, executor: Executor, source: SourceFile, files: &mut impl SourceProvider, @@ -224,7 +224,7 @@ impl RevisionJob { /// Capture selected physical source continuations, including child input. pub fn run_capturing_sources( - self, + &self, executor: Executor, source: SourceFile, files: &mut F, @@ -240,7 +240,7 @@ impl RevisionJob { /// Resume after the host has validated prefix dependencies and replayed /// their effects into the new revision's isolated file host. pub fn resume_entry_after_host_replay( - self, + &self, checkpoint: &EntryCheckpoint, source: SourceFile, files: &mut impl SourceProvider, @@ -270,7 +270,7 @@ impl RevisionJob { } pub fn resume_capturing_sources_after_host_replay( - self, + &self, checkpoint: &EntryCheckpoint, source: SourceFile, nested: Option, @@ -293,10 +293,31 @@ impl RevisionJob { Some(self.finish_execution(executed, files, previous.as_deref())) } + /// Resume normally unless the caller verifies and replays a matching suffix. + /// A rejected replay leaves publication untouched, so the caller can discard + /// the draft and execute again under the same revision. + pub fn resume_deciding_suffix( + &self, + checkpoint: &EntryCheckpoint, + source: SourceFile, + nested: Option, + files: &mut F, + line_break_cache: Arc, + select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option, + capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision, + ) -> Result, RevisionFailure>>, String> { + let previous = self.session.latest(); + let executed = checkpoint.resume_deciding_suffix( + source, nested, files, self.cancellation.clone(), line_break_cache, + previous.as_deref().map(|item| &item.execution), select, capture, + )?; + Ok(executed.map(|result| self.finish_execution(result, files, previous.as_deref()))) + } + /// Publish a completed result after the caller verifies the same inputs /// and replays every host call into the current revision's draft. pub fn reuse_completed_after_host_replay( - self, + &self, completed: &RevisionExecution, files: &impl SourceProvider, ) -> Result, RevisionFailure> { @@ -304,7 +325,7 @@ impl RevisionJob { } fn finish_execution( - self, + &self, executed: Result, files: &impl SourceProvider, previous: Option<&RevisionExecution>, diff --git a/crates/texrra-tex-core/src/execution/xe_encoding.rs b/crates/texrra-tex-core/src/execution/xe_encoding.rs index 75cb66b..6f3e08d 100644 --- a/crates/texrra-tex-core/src/execution/xe_encoding.rs +++ b/crates/texrra-tex-core/src/execution/xe_encoding.rs @@ -63,7 +63,7 @@ impl XeLineFraming { } } -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub(super) struct Character { pub value: char, pub start: usize, diff --git a/crates/texrra-tex-core/src/native_font/map.rs b/crates/texrra-tex-core/src/native_font/map.rs index 1222b4f..892c6c5 100644 --- a/crates/texrra-tex-core/src/native_font/map.rs +++ b/crates/texrra-tex-core/src/native_font/map.rs @@ -473,7 +473,7 @@ enum MapMode { Delete, } -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] struct MapTables { entries: Arc>>, // PDF inclusion addresses the PostScript name independently of the TFM. @@ -485,7 +485,7 @@ struct MapTables { const MAX_CACHED_DEFAULT_MAP_BYTES: usize = 512 * 1024; static DEFAULT_MAP: Mutex> = Mutex::new(None); -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] pub(super) struct JobFontMap { // Ordinary unevaluated pages can retain raw lists for hosts that only // need TeX layout. A map command or actual autoexpanded glyph activates diff --git a/crates/texrra-tex-core/src/native_font/sfd.rs b/crates/texrra-tex-core/src/native_font/sfd.rs index 6e3184e..06b8e79 100644 --- a/crates/texrra-tex-core/src/native_font/sfd.rs +++ b/crates/texrra-tex-core/src/native_font/sfd.rs @@ -18,12 +18,13 @@ pub(super) struct Subfont { pub(super) cmap: [u16; 2], } +#[derive(PartialEq, Eq)] pub(super) struct Definition { pub(super) version: Arc, pub(super) subfonts: Vec<(String, Codes)>, } -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] pub(super) struct Files(BTreeMap<(PathBuf, String), Arc>); impl Files { diff --git a/crates/texrra-tex-core/src/native_font/virtual_paint.rs b/crates/texrra-tex-core/src/native_font/virtual_paint.rs index 5caa9a6..5ecc93c 100644 --- a/crates/texrra-tex-core/src/native_font/virtual_paint.rs +++ b/crates/texrra-tex-core/src/native_font/virtual_paint.rs @@ -13,6 +13,7 @@ use std::{ sync::Arc, }; +#[derive(PartialEq, Eq)] struct LoadedVirtual { from: String, program: VirtualFont, @@ -37,7 +38,7 @@ impl Default for VirtualPaintState { } } -#[derive(Clone)] +#[derive(Clone, PartialEq, Eq)] enum Program { File { vf: Arc, @@ -46,7 +47,7 @@ enum Program { Letterspace(LetterspaceProgram), } -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq, Eq)] pub(crate) struct JobVirtualFonts { programs: BTreeMap>, font_map: JobFontMap, diff --git a/crates/texrra-tex-core/src/pdf_device/cmap.rs b/crates/texrra-tex-core/src/pdf_device/cmap.rs index 9ccdd17..5620d22 100644 --- a/crates/texrra-tex-core/src/pdf_device/cmap.rs +++ b/crates/texrra-tex-core/src/pdf_device/cmap.rs @@ -10,7 +10,7 @@ use crate::{ const MAX_CMAP_DEPTH: usize = 16; const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024; -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(crate) struct CMap { codespaces: [Vec<[u32; 2]>; 4], mappings: [BTreeMap; 4], @@ -24,19 +24,19 @@ pub(crate) struct CMap { pub(crate) resources: Vec, } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] struct Mapping { last: u32, destination: Destination, } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] struct CidRange { last: u32, cid: u16, } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] enum Destination { Sequential(Vec), Explicit(Vec>), diff --git a/crates/texrra-tex-core/src/pdf_device/color.rs b/crates/texrra-tex-core/src/pdf_device/color.rs index 0d02d5a..032c005 100644 --- a/crates/texrra-tex-core/src/pdf_device/color.rs +++ b/crates/texrra-tex-core/src/pdf_device/color.rs @@ -308,7 +308,7 @@ impl ShippedColor { } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] struct Stack { mode: PdfLiteralMode, replay_on_page: bool, @@ -325,7 +325,7 @@ impl Stack { } } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct PdfColorStacks(Vec); impl Default for PdfColorStacks { diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs b/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs index 6638896..d63c6ec 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_annotation.rs @@ -87,6 +87,13 @@ pub(crate) struct AnnotationState { enabled: bool, } +impl AnnotationState { + pub(crate) fn same_idle_state(&self, other: &Self) -> bool { + self.enabled == other.enabled && self.bounds.is_none() && other.bounds.is_none() + && self.active.is_none() && other.active.is_none() + } +} + impl Default for AnnotationState { fn default() -> Self { Self { diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_color.rs b/crates/texrra-tex-core/src/pdf_device/xdv_color.rs index d8c034d..6adaf1d 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_color.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_color.rs @@ -104,7 +104,7 @@ fn program(literal: String, resources: Vec) -> Arc, diff --git a/crates/texrra-tex-core/src/pdf_device/xdv_document.rs b/crates/texrra-tex-core/src/pdf_device/xdv_document.rs index 5c29945..e56efef 100644 --- a/crates/texrra-tex-core/src/pdf_device/xdv_document.rs +++ b/crates/texrra-tex-core/src/pdf_device/xdv_document.rs @@ -44,6 +44,13 @@ pub(crate) struct TextEncoding { } impl TextEncoding { + pub(crate) fn same_state(&self, other: &Self) -> bool { + self.tainted_literals == other.tainted_literals + && self.extra_keys == other.extra_keys + && self.map.as_deref() == other.map.as_deref() + } + + pub(crate) fn apply( &mut self, operands: &[u8], from: &str, files: &mut impl SourceProvider, ) -> Vec { diff --git a/crates/texrra-tex-core/src/virtual_font.rs b/crates/texrra-tex-core/src/virtual_font.rs index 997820d..ffa1558 100644 --- a/crates/texrra-tex-core/src/virtual_font.rs +++ b/crates/texrra-tex-core/src/virtual_font.rs @@ -1,7 +1,7 @@ //! VF file structure and the local DVI programs of individual characters. use std::collections::BTreeMap; -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(super) struct VirtualFont { pub checksum: u32, pub design_size: i64, @@ -11,7 +11,7 @@ pub(super) struct VirtualFont { pub packets: BTreeMap, } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(super) struct LocalFont { pub checksum: u32, pub name: String, @@ -19,19 +19,19 @@ pub(super) struct LocalFont { pub design_size: i64, } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(super) struct Packet { pub width: i32, pub commands: Vec, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Axis { Horizontal, Vertical, } -#[derive(Debug)] +#[derive(Debug, PartialEq, Eq)] pub(super) enum Command { Character { slot: u8, diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index b4f9913..9e4a4ed 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,41 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 输出例程返回后的后缀复用 + +自动会话在输出例程已返回的命令边界留存有限检查点。输入游标、 +当前行、未读字节、TeX 状态、设备和字体映射、资源、输出流和 +逻辑计数都核对后,才尝试复用已成功执行的后缀。当前编辑前缀 +及来源版本接入旧后缀结果。写入按原顺序进入当前隔离草稿。 +如果调用结果变化,释放旧草稿,在同一修订重新执行。编辑器 +观测同时报告前后缀复用、丢弃的试跑步骤和总实际执行步骤。 + +三页真实 TeX 作业从第 2 页编辑复用后续执行。随后添加一个 +此前不存在、只在后缀读取的文件,触发重放中途拒绝。已写入的 +草稿被释放,重新执行后的辅助文件没有重复写入。两次的 +完整 Execution、PDF、SVG、来源映射、资源、辅助文件和日志 +均同各自的独立全量一致。四项会话定向检查、七项统计回归以及 +编辑器优化构建通过。 + +同版原样 NeurIPS 在第 3 页的输出例程返回后,扫描位置到入口 +第 344 行,累计 14,936,044 步。诊断比较时双方文件流仅有草稿 +输出的物理 inode 差异。使用默认预算的标点编辑仍执行 +5,281,627 步,原文还原执行 0 步。两个修订只更新第 3 页, +完整 Execution、PDF、SVG、来源映射、读取、查找、流读取、 +辅助文件及日志与独立全量一致。 + +该样稿默认节点容量下发生保留材料重算,作业末尾还有实际 +资源统计。两者均访问先前输出的事件。仅用于定位的 400 万 +节点容量试跑仍触发末尾统计;正式默认容量与原测试保留。 +已有复用路径遇到这类历史读取会退回执行。下一批将从可验证的 +材料容量与末尾统计入手,闭合第 344 行之后约 463 万步的复用。 +浏览器可见延迟、冷启动成本及内存仍需同版验收。 + +额外盒测试 5 项通过,1 项保留节点容量断言失败。隔离的 f387b1d +控制组在同一断言返回同样的成功结果,原测试和两端的失败日志保留。 +证据在 target/p4-settled-output/,SHA256SUMS 指纹为 +fe49c26e6f893fa651607627850f096b997a0e4dd316439ec9f0b1f701db22dc。 + ## 2026-11-29 原文恢复复用与出页边界实测 自动检查点可保留两份最近的成功执行结果。恢复相同入口字节时, diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index 8a1771c..a523932 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -130,6 +130,9 @@ async function compile(edit, submitted, changes) { visibleMs: performance.now() - submitted, steps: result.steps, reusedSteps: result.reused_steps, + reusedSuffixSteps: result.reused_suffix_steps, + discardedSuffixAttemptSteps: result.discarded_suffix_attempt_steps, + executedSteps: result.executed_steps, reusedFrontier: result.reused_frontier, replayedCalls: result.replayed_calls, pendingPublication: result.pending_publication === true, diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 17476a3..1c1e860 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -138,6 +138,10 @@ impl EditorObserver { "phases": self.phases(compiled, ready), "steps": steps, "reused_steps": work.reused_steps, + "reused_suffix_steps": work.reused_suffix_steps, + "discarded_suffix_attempt_steps": work.discarded_suffix_attempt_steps, + "executed_steps": steps.saturating_sub(work.reused_steps) + .saturating_add(work.discarded_suffix_attempt_steps), "reused_frontier": work.reused_frontier, "replayed_calls": work.replayed_calls, }) diff --git a/src/native.rs b/src/native.rs index f716a0a..fa2dec6 100644 --- a/src/native.rs +++ b/src/native.rs @@ -992,15 +992,29 @@ impl CompileJob { } let mut evidence = AttemptEvidence::new(self.revision()); let summary = AttemptRequest::from(&request); - match self.compile_observed(request, &mut evidence) { + let mut suffix_failure = None; + let result = self.compile_observed(&request, &mut evidence, None, &mut suffix_failure); + let result = if let Some((error, discarded_steps)) = suffix_failure { + if self.job.cancellation().is_cancelled() { + Err(CompileError::Cancelled) + } else { + evidence = AttemptEvidence::new(self.revision()); + self.compile_observed(&request, &mut evidence, Some((error, discarded_steps)), &mut None) + } + } else { + result + }; + match result { Ok(document) => Ok(document), Err(error) => Err(evidence.failure(error, summary).persist_requested()), } } fn compile_observed( - self, - request: CompileRequest, + &self, + request: &CompileRequest, evidence: &mut AttemptEvidence, + retry_suffix: Option<(String, usize)>, + suffix_failure: &mut Option<(String, usize)>, ) -> Result, CompileError> { let cancellation = self.job.cancellation(); check(&cancellation)?; @@ -1020,6 +1034,11 @@ impl CompileJob { .filter(|_| checkpoint_guard::can_stage(&request)); let format_cache = &self.compiler.format_cache; let mut entry_checkpoint_work = EntryCheckpointWork::default(); + let allow_suffix = retry_suffix.is_none(); + if let Some((error, discarded_steps)) = retry_suffix { + entry_checkpoint_work.rejection = Some(error); + entry_checkpoint_work.discarded_suffix_attempt_steps = discarded_steps; + } let (active_checkpoint, prepared) = if let Some(available) = checkpoints.and_then(CheckpointCache::current) { match available.prepare(&request, format_cache, &cancellation, evidence) { @@ -1074,7 +1093,9 @@ impl CompileJob { files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?; } evidence.phase = AttemptPhase::Prepared; - notify(&request, revision, CompileStage::Prepared, &cancellation)?; + if allow_suffix { + notify(request, revision, CompileStage::Prepared, &cancellation)?; + } evidence.phase = AttemptPhase::Executing; let cache = &self.compiler.line_break_cache; let before = cache.work(); @@ -1082,11 +1103,13 @@ impl CompileJob { debug_assert!(executor.is_none()); let (executed, next) = current.resume( &request, - self.job, + &self.job, source, files, cache.clone(), &mut entry_checkpoint_work, + allow_suffix, + suffix_failure, )?; (executed, Some(next)) } else { @@ -1095,7 +1118,7 @@ impl CompileJob { .with_line_break_cache(cache.clone()); if let Some(cache) = checkpoints { let (executed, captured) = - cache.capture(&request, self.job, executor, source, files); + cache.capture(request, &self.job, executor, source, files); if let Some(snapshot) = &captured { snapshot.report_capture(&mut entry_checkpoint_work); } diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 6e7322c..b605dd1 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -9,7 +9,7 @@ use std::{ path::Path, }; use texrra_tex_core::{ - execution::{CheckpointSource, EntryCheckpoint}, + execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint}, resources::{ResourceKind, ResourceLookup, ResourceReadRange}, }; #[cfg(test)] @@ -27,6 +27,10 @@ pub struct EntryCheckpointWork { pub reused_steps: usize, /// The complete kernel result matched a previously successful input. pub reused_completion: bool, + /// Logical steps skipped after kernel and host state converged. + pub reused_suffix_steps: usize, + /// Executed work discarded when a replay failed before publication. + pub discarded_suffix_attempt_steps: usize, pub replayed_calls: usize, pub rejection: Option, } @@ -43,7 +47,7 @@ pub(super) struct PublishedCheckpoints { } struct CachedCheckpoint { - entry: EntryCheckpoint, + entry: Arc, guard: PrefixInputGuard, replay_count: usize, slots: Capture, @@ -54,6 +58,13 @@ struct CompletedExecution { result: Arc, guard: PrefixInputGuard, calls: Arc<[Call]>, + settled: BTreeMap, +} + +struct SettledCheckpoint { + entry: Arc, + host: crate::native_job::ReplayBoundary, + call_count: usize, } pub(super) struct CheckpointSet { @@ -85,6 +96,7 @@ struct CaptureSchedule { next_page: usize, fixed_frontier: Option, pending_edit_frontier: Option, + settled_page: usize, } #[derive(Clone, Copy)] @@ -103,6 +115,7 @@ const NESTED_INTERVALS: usize = 2; enum Capture { Entry(CaptureSlots), Nested { file: usize, interval: usize }, + Settled { page: usize, regular: Option }, } #[derive(Default)] @@ -151,9 +164,21 @@ impl CaptureSchedule { next_page: 1, fixed_frontier, pending_edit_frontier: edit_frontier, + settled_page: 0, } } + fn select_source(&mut self, source: CheckpointSource<'_>, pages: usize) -> Option { + let regular = self.select(source.frontier, pages); + if self.fixed_frontier.is_none() && source.output_returned + && pages > self.settled_page && pages <= 8 + { + self.settled_page = pages; + return Some(Capture::Settled { page: pages, regular }); + } + regular.map(Capture::Entry) + } + fn take_edit_frontier(&mut self, frontier: usize, ordinary_capture: bool) -> bool { let edit = self .pending_edit_frontier @@ -236,6 +261,7 @@ struct CapturedEntries<'a> { edit: Option>, nested: [[Option>; NESTED_INTERVALS]; NESTED_FILES], changed: bool, + settled: BTreeMap, } impl<'a> CapturedEntries<'a> { @@ -253,12 +279,14 @@ impl<'a> CapturedEntries<'a> { edit: None, nested: Default::default(), changed: false, + settled: BTreeMap::new(), } } fn retain(&mut self, slots: Capture, checkpoint: Arc) { let slots = match slots { Capture::Entry(slots) => slots, + Capture::Settled { .. } => unreachable!("settled observation is handled before retention"), Capture::Nested { file, interval } => { self.nested[file][interval] = Some(checkpoint); return; @@ -275,7 +303,21 @@ impl<'a> CapturedEntries<'a> { } } - fn capture(&mut self, slots: Capture, entry: EntryCheckpoint, host: &RecordingHost) { + fn capture(&mut self, slots: Capture, entry: Arc, host: &RecordingHost) { + let slots = if let Capture::Settled { page, regular } = slots { + if let Some((_, call_count)) = host.prefix() { + self.settled.insert(page, SettledCheckpoint { + entry: entry.clone(), + host: host.files().replay_boundary(), + call_count, + }); + self.changed = true; + } + let Some(regular) = regular else { return; }; + Capture::Entry(regular) + } else { + slots + }; let (Some((trace, replay_count)), Some(path), Some(initial)) = ( host.prefix(), self.entry_path.as_deref(), @@ -371,6 +413,7 @@ impl<'a> CapturedEntries<'a> { result: result.clone(), guard, calls: calls.clone(), + settled: self.settled, })); Some(Arc::new(CheckpointSet { entries, @@ -454,7 +497,7 @@ impl CheckpointCache { pub(super) fn capture( &self, request: &CompileRequest, - job: RevisionJob, + job: &RevisionJob, executor: Executor, source: SourceFile, files: &mut Files, @@ -473,14 +516,14 @@ impl CheckpointCache { &mut recording, |source, pages| { if source.is_entry { - schedule.select(source.frontier, pages).map(Capture::Entry) + schedule.select_source(source, pages) } else if self.minimum_frontier.is_none() { nested.select(source, cwd) } else { None } }, - |slots, entry, host| captures.capture(slots, entry, host), + |slots, entry, host| captures.capture(slots, Arc::new(entry), host), ); let next = result.as_ref().ok().and_then(|result| { captures.finish(recording, self.minimum_frontier.is_none(), result) @@ -702,11 +745,13 @@ impl SelectedCheckpoint { pub(super) fn resume( self, request: &CompileRequest, - job: RevisionJob, + job: &RevisionJob, source: SourceFile, files: &mut Files, line_break_cache: Arc, work: &mut EntryCheckpointWork, + allow_suffix: bool, + suffix_failure: &mut Option<(String, usize)>, ) -> Result< ( Result, RevisionFailure>, @@ -779,8 +824,10 @@ impl SelectedCheckpoint { files, &self.set.calls[..checkpoint.replay_count], current_nested.map(|file| &file.version), ); let cwd = &request.world.cwd; + let cancellation = job.cancellation(); + let completed = if allow_suffix { self.set.completion.as_deref() } else { None }; let result = job - .resume_capturing_sources_after_host_replay( + .resume_deciding_suffix( &checkpoint.entry, source, nested_source, @@ -792,7 +839,7 @@ impl SelectedCheckpoint { if source.frontier > entry_frontier || (source.frontier == entry_frontier && pages >= schedule.next_page) { - schedule.select(source.frontier, pages).map(Capture::Entry) + schedule.select_source(source, pages) } else { None } @@ -800,8 +847,46 @@ impl SelectedCheckpoint { nested_schedule.select(source, cwd) } }, - |slots, entry, host| captures.capture(slots, entry, host), + |slots, entry, host| { + let entry = Arc::new(entry); + captures.capture(slots, entry.clone(), host); + let Capture::Settled { page, .. } = slots else { + return CheckpointDecision::Continue; + }; + let Some((completed, old)) = + completed.and_then(|job| job.settled.get(&page).map(|old| (job, old))) + else { + return CheckpointDecision::Continue; + }; + let Some(new) = captures.settled.get(&page) else { + return CheckpointDecision::Continue; + }; + if old.call_count != new.call_count || old.host != new.host + || !can_replay_completed_suffix(completed, request, host.files()) + { + return CheckpointDecision::Continue; + } + let Some(execution) = entry.splice_settled_suffix(&old.entry, &completed.result.execution) + else { + return CheckpointDecision::Continue; + }; + let calls = &completed.calls[old.call_count..]; + let replayed = host.replay_suffix(calls, &cancellation) + .and_then(|()| completed.guard.verify_replayed_inputs( + host.files(), request.project.as_deref().expect("settled replay uses a project"), + ).map_err(|error| error.to_string())); + if let Err(error) = replayed { + let discarded = entry.completed_steps().saturating_sub(work.reused_steps); + *suffix_failure = Some((error.clone(), discarded)); + return CheckpointDecision::ReplayFailed(error); + } + work.reused_suffix_steps = execution.steps - entry.completed_steps(); + work.reused_steps += work.reused_suffix_steps; + work.replayed_calls += calls.len(); + CheckpointDecision::Reuse(Box::new(execution)) + }, ) + .map_err(CompileError::Host)? .ok_or_else(changed_prefix)?; let next = result.as_ref().ok().and_then(|result| { captures.finish(recording, true, result) @@ -815,6 +900,14 @@ impl SelectedCheckpoint { } } +fn can_replay_completed_suffix( + completed: &CompletedExecution, + request: &CompileRequest, + files: &Files, +) -> bool { + completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok() +} + fn changed_line_start(previous: &[u8], current: &[u8]) -> Option { if previous == current { return None; diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 9c2466e..dec394b 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -120,6 +120,23 @@ impl<'a> RecordingHost<'a> { .filter(|read| read.path == version.path).count() == source_reads + size_reads } + pub(super) fn files(&self) -> &Files { + self.files + } + + pub(super) fn replay_suffix(&mut self, calls: &[Call], 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())?; + call.replay(self.files, None)?; + } + recorded.extend_from_slice(calls); + Ok(()) + } + pub(super) fn generated_outputs(&self) -> &BTreeSet { self.files.generated_outputs() } diff --git a/src/native_job.rs b/src/native_job.rs index ce756da..c1dbc26 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -157,6 +157,20 @@ struct DraftLedger { staged: PreparedOutput, } +#[derive(PartialEq, Eq)] +pub(super) struct ReplayBoundary { + inputs: Vec<(u8, u64, PathBuf, u64, std::collections::VecDeque)>, + outputs: Vec<(u8, u64, PathBuf, u64)>, + next_handle: u64, + columns: [usize; 2], + terminal_enabled: bool, + generated_reads: BTreeMap, + generated_before: BTreeMap>, + generated_written: BTreeSet, + trace: texrra_tex_core::resources::ResourceTrace, + stream_events: Vec, +} + pub struct Files { world: FileWorld, #[cfg(all(target_os = "linux", target_env = "gnu"))] @@ -654,6 +668,47 @@ impl Files { .operation(name, path, result); } + pub(super) fn replay_boundary(&self) -> ReplayBoundary { + let mut trace = self.resource_trace().clone(); + trace.project_version = None; + // The caller compared the live scanner bytes and validates later + // whole-file reads separately. Keep this entry's path and length. + if let Some(entry) = trace.reads.first_mut() { + entry.sha256.clear(); + } + let mut stream_events = self.stream_io.events().to_vec(); + for event in &mut stream_events { + if let crate::native_stream::StreamEffect::OutputOpened { + descriptor: Ok(identity), .. + } = &mut event.effect + { + // A fresh draft has a different inode. The stream path, + // opening version, accepted bytes and handle remain in the journal. + identity.unix_identity = None; + } + } + ReplayBoundary { + inputs: self.inputs.iter().map(|(&index, input)| { + (index, input.handle, input.path.clone(), input.offset, input.xe_lookahead.clone()) + }).collect(), + outputs: self.outputs.iter().map(|(&index, output)| { + (index, output.handle, output.path.clone(), output.accepted) + }).collect(), + next_handle: self.next_handle, + columns: [self.log_column, self.terminal_column], + terminal_enabled: self.terminal_enabled, + generated_reads: self.generated_reads.clone(), + generated_before: self.generated_before.clone(), + generated_written: self.generated_written.clone(), + trace, + stream_events, + } + } + + pub(super) fn replay_world(&self) -> &FileWorld { + &self.world + } + pub(super) fn generated_outputs(&self) -> &BTreeSet { &self.generated_written } diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index a21fba8..a27cc43 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1572,6 +1572,83 @@ fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() { + let cwd = directory("settled-suffix"); + let entry = cwd.join("main.tex"); + let late = cwd.join("late.tex"); + let aux = cwd.join("job.aux"); + let missing_aux = b"Opened\nMissing\n"; + fs::write(&aux, missing_aux).unwrap(); + let body = |letter: char| format!(r" +\shipout\hbox{{Cover ABC}} +\setbox3=\hbox{{{letter}}} +\shipout\box3 +\immediate\openout1=job.aux +\immediate\write1{{Opened}} +\openin2=late.tex +\ifeof2 + \immediate\write1{{Missing}} +\else + \read2 to\late + \immediate\write1{{\late}} +\fi +\closein2 +\immediate\closeout1 +\shipout\hbox{{Unchanged}} +\end +"); + let mut definition = atomic_definition(&cwd, 1, &body('A')); + definition.generated.insert(aux.clone()); + let mut 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 mut previous = session.compile(request.clone().with_project(project.clone())).unwrap(); + assert_eq!(previous.pages.len(), 3); + + for (revision, letter) in [(2, 'B'), (3, 'C')] { + let mut edits = BTreeMap::from([( + entry.clone(), + Some(Arc::from(format!("{HEADER}{}", body(letter)).into_bytes())), + )]); + if revision == 3 { + edits.insert(late.clone(), Some(Arc::from(b"Found\n".as_slice()))); + } + project = project.with_file_changes(revision, edits).unwrap(); + let current = request.clone().with_project(project.clone()); + let updated = session.compile(current.clone()).unwrap(); + let work = &updated.entry_checkpoint_work; + if revision == 2 { + assert!(work.reused_suffix_steps > 0, "{work:?}"); + assert_eq!(work.discarded_suffix_attempt_steps, 0); + } else { + assert_eq!(work.reused_suffix_steps, 0); + assert!(work.discarded_suffix_attempt_steps > 0, "{work:?}"); + } + let changed: Vec<_> = updated.preview_since(Some(previous.revision())).unwrap() + .pages.into_iter().map(|page| page.index).collect(); + assert_eq!(changed, [1]); + let actual = fs::read(&aux).unwrap(); + let log = fs::read(cwd.join("job.log")).unwrap(); + let expected = if revision == 2 { missing_aux.as_slice() } else { b"Opened\nFound \n" }; + assert_eq!(actual, expected); + fs::write(&aux, missing_aux).unwrap(); + let full = NativeCompiler::default().compile(current).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!(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!(actual, fs::read(&aux).unwrap()); + assert_eq!(log, fs::read(cwd.join("job.log")).unwrap()); + previous = updated; + } + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn completed_checkpoint_replays_undo_and_rechecks_immutable_and_generated_inputs() { let cwd = directory("completed-undo");