diff --git a/crates/texrra-tex-core/src/execution/dependency_reads.rs b/crates/texrra-tex-core/src/execution/dependency_reads.rs index cb81222..8c62ac9 100644 --- a/crates/texrra-tex-core/src/execution/dependency_reads.rs +++ b/crates/texrra-tex-core/src/execution/dependency_reads.rs @@ -1,6 +1,7 @@ //! Deduplicate execution reads before producing the ordered public evidence. use super::Dependency; use std::{ + cmp::Ordering, collections::{BTreeSet, HashMap}, sync::Arc, }; @@ -21,6 +22,54 @@ impl DependencyEvidence { pub(super) fn epochs(&self) -> Option<&[u32]> { self.0.as_deref() } + + pub(super) fn splice( + prefix: impl IntoIterator, + completed: &BTreeSet, + donor_epochs: &[u32], + prefix_epoch: u32, + donor_prefix_epoch: u32, + ) -> Option<(BTreeSet, Self)> { + if donor_epochs.len() != completed.len() { + return None; + } + let prefix = ordered_unique_observations(prefix); + let mut suffix = completed + .iter() + .zip(donor_epochs.iter().copied()) + .filter(|(_, epoch)| *epoch > donor_prefix_epoch) + .peekable(); + let translate = |epoch| prefix_epoch.checked_add(epoch - donor_prefix_epoch); + let mut reads = Vec::with_capacity(prefix.len()); + let mut epochs = Vec::with_capacity(prefix.len()); + + for (key, mut epoch) in prefix { + while let Some(&(donor_key, donor_epoch)) = suffix.peek() { + match donor_key.cmp(&key) { + Ordering::Less => { + reads.push(donor_key.clone()); + epochs.push(translate(donor_epoch)?); + suffix.next(); + } + Ordering::Equal => { + // A repeated read belongs to the suffix. Keep the + // prefix's owned key and update its observation. + epoch = translate(donor_epoch)?; + suffix.next(); + break; + } + Ordering::Greater => break, + } + } + reads.push(key); + epochs.push(epoch); + } + for (key, epoch) in suffix { + reads.push(key.clone()); + epochs.push(translate(epoch)?); + } + Some((reads.into_iter().collect(), Self::new(epochs))) + } } // The same execution can be captured at different boundaries. @@ -154,11 +203,7 @@ impl DependencyReads { ); } - let mut ordered: Vec<_> = observations.collect(); - ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae))); - // A diagnostic can record a meaning also present in the lookup cache. - ordered.dedup_by(|a, b| a.0 == b.0); - let (reads, epochs) = ordered.into_iter().unzip(); + let (reads, epochs) = ordered_unique_observations(observations).into_iter().unzip(); (reads, DependencyEvidence::new(epochs)) } @@ -168,6 +213,16 @@ impl DependencyReads { } } +fn ordered_unique_observations( + observations: impl IntoIterator, +) -> Vec<(Dependency, u32)> { + let mut ordered: Vec<_> = observations.into_iter().collect(); + ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae))); + // A diagnostic can record a meaning also present in the lookup cache. + ordered.dedup_by(|a, b| a.0 == b.0); + ordered +} + fn byte_catcode_observations( epochs: impl Iterator, ) -> impl Iterator { @@ -244,6 +299,32 @@ mod tests { ); } + #[test] + fn suffix_splice_preserves_last_observation_for_each_ordered_dependency() { + let prefix = [ + (Dependency::Count(3), 4), + (Dependency::Count(1), 2), + (Dependency::Count(3), 6), + (Dependency::Count(5), 7), + (Dependency::Count(4), 8), + ]; + let completed: BTreeSet<_> = [0, 2, 3, 4, 6].into_iter().map(Dependency::Count).collect(); + let donor_epochs = [2, 4, 1, 5, 7]; + let (reads, evidence) = + DependencyEvidence::splice(prefix.clone(), &completed, &donor_epochs, 8, 2).unwrap(); + assert_eq!(reads, (1..=6).map(Dependency::Count).collect::>()); + assert_eq!(evidence.epochs().unwrap(), [2, 10, 6, 11, 7, 13]); + + assert!( + DependencyEvidence::splice(prefix.clone(), &completed, &donor_epochs[..4], 8, 2) + .is_none() + ); + assert!( + DependencyEvidence::splice(prefix, &completed, &donor_epochs, u32::MAX - 2, 2) + .is_none() + ); + } + #[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 97c3e13..6b6a0cb 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -337,12 +337,25 @@ pub struct CheckpointSource<'a> { /// 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 { +pub enum CheckpointDecision { Continue, - Reuse(Box), + Reuse(Box), ReplayFailed(String), } +impl CheckpointDecision { + pub(super) fn into_prepared(self) -> CheckpointDecision> { + match self { + Self::Continue => CheckpointDecision::Continue, + Self::ReplayFailed(error) => CheckpointDecision::ReplayFailed(error), + Self::Reuse(execution) => { + let fingerprint = super::DeferredStateFingerprint::known(execution.outgoing_state); + CheckpointDecision::Reuse(Box::new(execution.with_outgoing_state(fingerprint))) + } + } + } +} + /// Time spent cloning live kernel state while resuming or capturing checkpoints. #[derive(Clone, Copy, Debug, Default)] pub struct CheckpointCloneTimings { @@ -454,7 +467,7 @@ impl EntryCheckpoint { self.resume_observed(source, None, files, cancellation, None, None, None, |_, _, _, _| CheckpointDecision::Continue) .expect("ordinary resume cannot reject a cached suffix") - .map(|result| result.map(|execution| execution.finish_fingerprint(None))) + .map(|result| result.map(|execution| execution.finish_fingerprint())) } pub(super) fn resume_capturing_sources_after_host_replay( @@ -482,7 +495,7 @@ impl EntryCheckpoint { }), ) .expect("ordinary resume cannot reject a cached suffix") - .map(|result| result.map(|execution| execution.finish_fingerprint(previous))) + .map(|result| result.map(|execution| execution.finish_fingerprint())) } pub(super) fn resume_deciding_suffix( @@ -495,7 +508,7 @@ impl EntryCheckpoint { previous: Option<&Execution>, timings: Option<&mut CheckpointCloneTimings>, select: impl FnMut(CheckpointSource<'_>, usize) -> Option, - capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, + capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision>, ) -> Result, ExecutionFailure>>, String> { let measured = timings.is_some().then(Cell::default); let result = self.resume_observed( @@ -517,7 +530,7 @@ impl EntryCheckpoint { line_break_cache: Option>, previous: Option<&Execution>, timings: Option<&Cell>, - capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision, + capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision>, ) -> Result, ExecutionFailure>>, String> { if !self.accepts_entry(&source) || match &nested { @@ -560,10 +573,7 @@ impl EntryCheckpoint { ) }); let result = match result { - Ok(CheckpointDecision::Reuse(execution)) => { - let fingerprint = super::DeferredStateFingerprint(Some(execution.outgoing_state)); - return Ok(Some(Ok(execution.with_outgoing_state(fingerprint)))); - } + Ok(CheckpointDecision::Reuse(execution)) => return Ok(Some(Ok(*execution))), Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error), Ok(CheckpointDecision::Continue) => Ok(()), Err(error) => Err(error), @@ -4013,12 +4023,12 @@ impl Executor { self.finish_execution(result, incoming_state, None) } - fn entry_observer( + fn entry_observer( incoming_state: u64, timings: Option<&Cell>, mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option, - mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, - ) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision { + 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 CheckpointDecision::Continue; @@ -4092,7 +4102,7 @@ impl Executor { previous: Option<&Execution>, ) -> Result { self.prepare_execution(result, incoming_state, previous) - .map(|execution| execution.finish_fingerprint(previous)) + .map(|execution| execution.finish_fingerprint()) } fn prepare_execution( @@ -4149,11 +4159,11 @@ impl Executor { } // An identical completed state has the same fingerprint. Compare // the entire state, including token source spans and assignments. - let outgoing_state = super::DeferredStateFingerprint( - previous - .filter(|last| last.state == self.state) - .map(|last| last.outgoing_state), - ); + let outgoing_state = if let Some(last) = previous.filter(|last| last.state == self.state) { + super::DeferredStateFingerprint::known(last.outgoing_state) + } else { + super::DeferredStateFingerprint::pending(previous.map(|last| &last.state)) + }; let format_pdf_images = self.captured_format_pdf_images(); Ok(Execution { format_dumped: self.format_dumped, @@ -4305,13 +4315,13 @@ impl Executor { self.read_parameter(Parameter::Partokencontext).width() >= minimum } - fn run_active_input( + fn run_active_input( &mut self, initial_depth: usize, mut pages_processed: bool, files: &mut F, - mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision, - ) -> Result { + mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision, + ) -> Result, Error> { let xe = self.state.input_profile() == InputProfile::XeTeX; loop { if !std::mem::take(&mut pages_processed) { diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index 42344ce..dc42c41 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -1,5 +1,5 @@ use super::super::{ - dependency_reads::DependencyEvidence, + DeferredStateFingerprint, dependency_reads::DependencyEvidence, source_relocation::SourceRelocation, source_relocation_events::EventRelocation, statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize}, }; @@ -290,6 +290,21 @@ impl EntryCheckpoint { retained: Option<&RetainedStateFingerprint>, timings: Option<&mut SuffixKernelTimings>, ) -> Option<(Execution, Option)> { + self.prepare_settled_suffix(prior, completed, closed_source, retained, false, timings) + .map(|(execution, layout)| (execution.finish_fingerprint(), layout)) + } + + /// Assemble the proved kernel suffix. The host must replay its recorded + /// effects before passing this output to the revision job for a draft. + pub fn prepare_settled_suffix( + &self, + prior: &Self, + completed: &Execution, + closed_source: Option<(usize, usize)>, + retained: Option<&RetainedStateFingerprint>, + defer_fingerprint: bool, + timings: Option<&mut SuffixKernelTimings>, + ) -> Option<(Execution, Option)> { let (source_id, prefix_resource_reads) = match closed_source { Some((source_id, reads)) => { if reads == 0 || self.closed_source_change(prior, completed)?.source_id != source_id { @@ -299,7 +314,9 @@ impl EntryCheckpoint { } None => (self.entry, 1), }; - self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, retained, timings) + self.splice_settled_sources( + prior, completed, source_id, prefix_resource_reads, retained, defer_fingerprint, timings, + ) } fn splice_settled_sources( @@ -309,8 +326,9 @@ impl EntryCheckpoint { source_id: usize, prefix_resource_reads: usize, retained: Option<&RetainedStateFingerprint>, + defer_fingerprint: bool, mut timings: Option<&mut SuffixKernelTimings>, - ) -> Option<(Execution, Option)> { + ) -> Option<(Execution, Option)> { if self.entry != self.active_source || prior.entry != prior.active_source || self.entry != prior.entry @@ -499,7 +517,7 @@ impl EntryCheckpoint { dependency_evidence, line_observations, incoming_state: completed.incoming_state, - outgoing_state: completed.outgoing_state, + outgoing_state: DeferredStateFingerprint::known(completed.outgoing_state), steps, box_nodes_created, reads_event_history: false, @@ -514,9 +532,14 @@ impl EntryCheckpoint { && execution.state == retained.state { reused_final_fingerprint = true; - retained.fingerprint + DeferredStateFingerprint::known(retained.fingerprint) } else { - execution.state.fingerprint_with_prior(Some(&completed.state)) + let pending = DeferredStateFingerprint::pending(Some(&completed.state)); + if defer_fingerprint { + pending + } else { + DeferredStateFingerprint::known(pending.calculate(&execution.state)) + } }; } } else if statistics.is_identity() { @@ -701,21 +724,13 @@ fn splice_dependencies( if let (Some(current_epoch), Some(donor_epoch), Some(donor)) = ( current.reads.epoch(), prior.reads.epoch(), completed.dependency_evidence.epochs(), ) { - if donor.len() != completed.reads.len() { - return None; - } - let mut observed: BTreeMap = BTreeMap::new(); - for (key, epoch) in current.dependency_observations() { - observed.entry(key).and_modify(|last| *last = (*last).max(epoch)).or_insert(epoch); - } - for (key, &epoch) in completed.reads.iter().zip(donor) { - if epoch > donor_epoch { - let translated = current_epoch.checked_add(epoch - donor_epoch)?; - observed.insert(key.clone(), translated); - } - } - let (reads, epochs) = observed.into_iter().unzip(); - return Some((reads, DependencyEvidence::new(epochs))); + return DependencyEvidence::splice( + current.dependency_observations(), + &completed.reads, + donor, + current_epoch, + donor_epoch, + ); } // Restored records without epoch evidence can only preserve every 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 7597bf1..565e7ea 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs @@ -110,8 +110,8 @@ pub(super) fn same_kernel_provenance( Some(measure(timings.map(|timings| &mut timings.exact_equality), || current.state == state)) } -pub(super) fn append_suffix( - execution: &mut Execution, +pub(super) fn append_suffix( + execution: &mut Execution, tail: &[Event], statistics: &SuffixStatistics, relocation: &mut EventRelocation<'_>, diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 65b43fc..0efb0c1 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -703,8 +703,38 @@ pub struct Execution { /// The exact final state is available for layout. Its fingerprint may still /// require the canonical hash before a completed execution can be published. -#[derive(Debug)] -pub struct DeferredStateFingerprint(Option); +pub struct DeferredStateFingerprint(FingerprintState); + +enum FingerprintState { + Known(u64), + NeedsHash(Option), +} + +impl fmt::Debug for DeferredStateFingerprint { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + FingerprintState::Known(value) => formatter.debug_tuple("Known").field(&value).finish(), + FingerprintState::NeedsHash(_) => formatter.write_str("NeedsHash"), + } + } +} + +impl DeferredStateFingerprint { + fn known(value: u64) -> Self { + Self(FingerprintState::Known(value)) + } + + fn pending(prior: Option<&State>) -> Self { + Self(FingerprintState::NeedsHash(prior.map(State::command_fingerprint_base))) + } + + fn calculate(&self, state: &State) -> u64 { + match &self.0 { + FingerprintState::Known(value) => *value, + FingerprintState::NeedsHash(prior) => state.fingerprint_with_base(prior.as_ref()), + } + } +} impl Execution { fn with_outgoing_state(self, outgoing_state: T) -> Execution { @@ -739,13 +769,11 @@ impl Execution { impl Execution { fn needs_fingerprint(&self) -> bool { - self.outgoing_state.0.is_none() + matches!(self.outgoing_state.0, FingerprintState::NeedsHash(_)) } - fn finish_fingerprint(self, previous: Option<&Execution>) -> Execution { - let fingerprint = self.outgoing_state.0.unwrap_or_else(|| { - self.state.fingerprint_with_prior(previous.map(|prior| &prior.state)) - }); + fn finish_fingerprint(self) -> Execution { + let fingerprint = self.outgoing_state.calculate(&self.state); self.with_outgoing_state(fingerprint) } } diff --git a/crates/texrra-tex-core/src/execution/session.rs b/crates/texrra-tex-core/src/execution/session.rs index 48faa78..5d16caf 100644 --- a/crates/texrra-tex-core/src/execution/session.rs +++ b/crates/texrra-tex-core/src/execution/session.rs @@ -97,7 +97,6 @@ pub struct PreparedRevisionExecution { execution: Execution, source_versions: Vec, resources: Option, - previous: Option>, } impl PreparedRevisionExecution { @@ -115,9 +114,7 @@ impl PreparedRevisionExecution { } pub fn finish(self) -> Result, RevisionFailure> { - let execution = self.execution.finish_fingerprint( - self.previous.as_deref().map(|revision| &revision.execution), - ); + let execution = self.execution.finish_fingerprint(); let complete = Arc::new(RevisionExecution { revision: self.job.revision, execution, @@ -400,6 +397,27 @@ impl RevisionJob { defer_fingerprint: bool, select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option, capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision, + ) -> Result>, String> { + let mut capture = capture; + self.resume_deciding_suffix_staged( + checkpoint, source, nested, files, line_break_cache, timings, defer_fingerprint, select, + |slot, entry, files| capture(slot, entry, files).into_prepared(), + ) + } + + /// Resume with a typed, host-verified suffix assembly. New fingerprints + /// may be finalized after the editor consumes the prepared page data. + pub fn resume_deciding_suffix_staged( + &self, + checkpoint: &EntryCheckpoint, + source: SourceFile, + nested: Option, + files: &mut F, + line_break_cache: Arc, + timings: Option<&mut CheckpointCloneTimings>, + defer_fingerprint: bool, + select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option, + capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision>, ) -> Result>, String> { let previous = self.session.latest(); let executed = checkpoint.resume_deciding_suffix( @@ -423,13 +441,10 @@ impl RevisionJob { execution, source_versions, resources, - previous, }))) } result => { - let executed = result.map(|execution| execution.finish_fingerprint( - previous.as_deref().map(|item| &item.execution), - )); + let executed = result.map(Execution::finish_fingerprint); self.finish_execution(executed, files, previous.as_deref()) .map(ResumedExecution::Complete) } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 7f87d97..1562527 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1197,6 +1197,8 @@ impl<'de> serde::Deserialize<'de> for CommandBindings { } } +pub(super) struct CommandFingerprintBase(Arc); + // Derive the ordinary hash and emit the specialized fingerprint in the // same field order. Only the command meanings can reuse recorded hash input. macro_rules! define_state { @@ -1213,9 +1215,21 @@ macro_rules! define_state { self.fingerprint_with_prior(None) } - pub(super) fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 { + fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 { + self.fingerprint_with_bindings(prior.map(|prior| prior.commands.as_ref())) + } + + pub(super) fn command_fingerprint_base(&self) -> CommandFingerprintBase { + CommandFingerprintBase(self.commands.clone()) + } + + pub(super) fn fingerprint_with_base(&self, prior: Option<&CommandFingerprintBase>) -> u64 { + self.fingerprint_with_bindings(prior.map(|prior| prior.0.as_ref())) + } + + fn fingerprint_with_bindings(&self, prior: Option<&CommandBindings>) -> u64 { let mut hash = FingerprintHasher::default(); - self.commands.hash_fingerprint(&mut hash, prior.map(|prior| prior.commands.as_ref())); + self.commands.hash_fingerprint(&mut hash, prior); $(self.$field.hash(&mut hash);)* hash.finish() } diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 701e194..5764c21 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -1139,18 +1139,19 @@ impl SelectedCheckpoint { let timed = observer.is_some(); let detailed_observer = observer.filter(|observer| observer.wants_checkpoint_details()); let mut clones = CheckpointCloneTimings::default(); + let defer_fingerprint = observer.is_some_and(|observer| { + observer.preview_before_export() && observer.preview_before_fingerprint() + }); let resume_started = timed.then(Instant::now); let result = job - .resume_deciding_suffix_prepared( + .resume_deciding_suffix_staged( &checkpoint.entry, source, nested_source, &mut recording, line_break_cache, detailed_observer.is_some().then_some(&mut clones), - observer.is_some_and(|observer| { - observer.preview_before_export() && observer.preview_before_fingerprint() - }), + defer_fingerprint, |source, pages| { if source.is_entry { // The loaded entry line can be shared by several shipouts. @@ -1197,11 +1198,12 @@ impl SelectedCheckpoint { }); let result = measure(&mut timings.suffix_kernel_validation, timed, || { let kernel_timings = attempt.as_mut().or(timed.then_some(&mut timings.suffix_kernel)); - entry.splice_settled_suffix_with_fingerprint( + entry.prepare_settled_suffix( &old.entry, &completed.result.execution, closed_source.as_ref().map(|child| (child.source_id, child.prefix_resource_reads)), self.previous_fingerprint.as_deref(), + defer_fingerprint, kernel_timings, ) }); diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index ec2b0ac..e887c82 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -2081,11 +2081,8 @@ fn resized_entry_prefix_invalidates_an_executed_file_size_query() { fs::remove_dir_all(cwd).unwrap(); } -#[test] -fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { - let cwd = directory("settled-resized-suffix"); - let entry = cwd.join("main.tex"); - let body = |letter, note, tail_query| format!(r" +fn resized_suffix_body(letter: char, note: &str, tail_query: &str) -> String { + format!(r" \tracingstats=2 \shipout\hbox{{Cover ABC}} \setbox3=\hbox{{{letter}}}\relax%{note} @@ -2099,10 +2096,16 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { \relax \shipout\hbox{{Final}} \end -"); +") +} + +#[test] +fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { + let cwd = directory("settled-resized-suffix"); + let entry = cwd.join("main.tex"); for tail_query in ["", r"\count42=\pdffilesize{main.tex}\relax"] { let mut project = ProjectSnapshot::new( - atomic_definition(&cwd, 1, &body('A', "medium", tail_query)), + atomic_definition(&cwd, 1, &resized_suffix_body('A', "medium", tail_query)), ).unwrap(); let mut request = request(&cwd).observe_generated_initial(); request.world = project.configuration(); @@ -2110,7 +2113,7 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { // Only the current document can donate the suffix in either direction. let session = NativeCompiler::default().with_automatic_entry_checkpoints(); let previous = session.compile(request.clone().with_project(project.clone())).unwrap(); - let source = format!("{HEADER}{}", body(letter, note, tail_query)); + let source = format!("{HEADER}{}", resized_suffix_body(letter, note, tail_query)); let tail_offset = source.find("Suffix glyphs").unwrap(); let bytes = i32::try_from(source.len()).unwrap(); project = project.with_file_edits( @@ -2151,6 +2154,108 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { fs::remove_dir_all(cwd).unwrap(); } +#[test] +fn preview_before_relocated_suffix_fingerprint_preserves_exact_publication() { + struct WatchDraft { + compiler: NativeCompiler, + previous: Arc, + cancel: bool, + preview: Mutex>, + } + + impl CompileObserver for WatchDraft { + fn stage(&self, _: u64, _: CompileStage) -> Result<(), String> { + Ok(()) + } + + fn preview_before_export(&self) -> bool { + true + } + + fn preview_before_fingerprint(&self) -> bool { + true + } + + fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> { + let work = draft.entry_checkpoint_work(); + assert!(work.reused_suffix_steps > 0 && !work.reused_completion, "{work:?}"); + assert!(draft.state_fingerprint_pending(), "{work:?}"); + assert!(Arc::ptr_eq(&self.previous, &self.compiler.latest().unwrap())); + let update = draft.preview_since(Some(self.previous.revision()))?; + assert_eq!(update.pages.iter().map(|page| page.index).collect::>(), [1]); + assert!(self.preview.lock().unwrap().replace(update).is_none()); + if self.cancel { + self.compiler.start(); + } + Ok(()) + } + } + + let cwd = directory("preview-before-relocated-suffix-fingerprint"); + let original = resized_suffix_body('A', "medium", ""); + let edited = resized_suffix_body('B', "expanded comment", ""); + assert_ne!(original.find("Suffix glyphs"), edited.find("Suffix glyphs")); + let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &original)).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let previous = compiler.compile(request.clone().with_project(project.clone())).unwrap(); + let paths = ["job.pdf", "job.log"].map(|name| cwd.join(name)); + let original_artifacts = paths.each_ref().map(|path| fs::read(path).unwrap()); + + let source = format!("{HEADER}{edited}"); + let project = project.with_file_edits( + 2, + [(cwd.join("main.tex"), Arc::from(source.into_bytes()))].into(), + ).unwrap(); + let request = request.with_project(project); + let mut cancelled = None; + for cancel in [true, false] { + let observer = Arc::new(WatchDraft { + compiler: compiler.clone(), + previous: previous.clone(), + cancel, + preview: Mutex::new(None), + }); + let mut observed = request.clone(); + observed.observer = Some(observer.clone()); + let result = compiler.compile_detailed(observed); + let draft = observer.preview.lock().unwrap().take().unwrap(); + if cancel { + let failure = result.err().unwrap(); + assert!(matches!(failure.error, CompileError::Cancelled)); + assert_eq!(failure.phase, AttemptPhase::Export); + assert!(Arc::ptr_eq(&previous, &compiler.latest().unwrap())); + assert_eq!(paths.each_ref().map(|path| fs::read(path).unwrap()), original_artifacts); + cancelled = Some((failure.completed_execution.unwrap(), draft)); + continue; + } + + let published = result.unwrap(); + assert!(Arc::ptr_eq(&published, &compiler.latest().unwrap())); + assert_eq!(draft, published.preview_since(Some(previous.revision())).unwrap()); + let (cancelled_execution, cancelled_draft) = cancelled.as_ref().unwrap(); + assert_eq!(draft.pages, cancelled_draft.pages); + let artifacts = paths.each_ref().map(|path| fs::read(path).unwrap()); + assert_eq!(published.output, file_version(&paths[0]).unwrap()); + + let full = NativeCompiler::default().compile(request.clone()).unwrap(); + assert!(full.execution.execution.state != previous.execution.execution.state); + assert_eq!(cancelled_execution.execution, full.execution.execution); + assert_eq!(published.execution.execution, full.execution.execution); + assert_eq!(published.execution.source_versions, full.execution.source_versions); + assert_eq!(published.execution.execution_resources, full.execution.execution_resources); + assert_eq!(published.output, full.output); + assert_eq!(published.pdf, full.pdf); + assert_eq!(published.pages, full.pages); + assert_eq!(published.source_map.sources, full.source_map.sources); + assert_eq!(published.source_map.pages, full.source_map.pages); + assert_eq!(published.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + assert_eq!(paths.each_ref().map(|path| fs::read(path).unwrap()), artifacts); + } + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn whole_line_edits_reuse_the_settled_suffix_and_relocate_provenance() { check_whole_line_suffix_edits("whole-line-safe-suffix", InputProfile::TeX8Bit, false);