Stage verified suffix previews before new state hashing

This commit is contained in:
gloamxun committed 2026-12-02 06:14:40 +08:00
1 parent 5927196149
commit f684872941
9 files changed
+350 -80

No files matched your search

@@ -1,6 +1,7 @@
//! Deduplicate execution reads before producing the ordered public evidence. //! Deduplicate execution reads before producing the ordered public evidence.
use super::Dependency; use super::Dependency;
use std::{ use std::{
cmp::Ordering,
collections::{BTreeSet, HashMap}, collections::{BTreeSet, HashMap},
sync::Arc, sync::Arc,
}; };
@@ -21,6 +22,54 @@ impl DependencyEvidence {
pub(super) fn epochs(&self) -> Option<&[u32]> { pub(super) fn epochs(&self) -> Option<&[u32]> {
self.0.as_deref() self.0.as_deref()
} }
pub(super) fn splice(
prefix: impl IntoIterator<Item = (Dependency, u32)>,
completed: &BTreeSet<Dependency>,
donor_epochs: &[u32],
prefix_epoch: u32,
donor_prefix_epoch: u32,
) -> Option<(BTreeSet<Dependency>, 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. // The same execution can be captured at different boundaries.
@@ -154,11 +203,7 @@ impl DependencyReads {
); );
} }
let mut ordered: Vec<_> = observations.collect(); let (reads, epochs) = ordered_unique_observations(observations).into_iter().unzip();
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();
(reads, DependencyEvidence::new(epochs)) (reads, DependencyEvidence::new(epochs))
} }
@@ -168,6 +213,16 @@ impl DependencyReads {
} }
} }
fn ordered_unique_observations(
observations: impl IntoIterator<Item = (Dependency, u32)>,
) -> 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( fn byte_catcode_observations(
epochs: impl Iterator<Item = u32>, epochs: impl Iterator<Item = u32>,
) -> impl Iterator<Item = (Dependency, u32)> { ) -> impl Iterator<Item = (Dependency, u32)> {
@@ -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::<BTreeSet<_>>());
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] #[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() { fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default(); let mut read = DependencyReads::default();
+32 -22
View File
@@ -337,12 +337,25 @@ pub struct CheckpointSource<'a> {
/// Called only at a selected boundary. Reuse requires that the caller has /// Called only at a selected boundary. Reuse requires that the caller has
/// validated and replayed the previous suffix into this revision's draft. /// validated and replayed the previous suffix into this revision's draft.
pub enum CheckpointDecision { pub enum CheckpointDecision<R = Execution> {
Continue, Continue,
Reuse(Box<Execution>), Reuse(Box<R>),
ReplayFailed(String), ReplayFailed(String),
} }
impl CheckpointDecision {
pub(super) fn into_prepared(self) -> CheckpointDecision<Execution<super::DeferredStateFingerprint>> {
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. /// Time spent cloning live kernel state while resuming or capturing checkpoints.
#[derive(Clone, Copy, Debug, Default)] #[derive(Clone, Copy, Debug, Default)]
pub struct CheckpointCloneTimings { pub struct CheckpointCloneTimings {
@@ -454,7 +467,7 @@ impl EntryCheckpoint {
self.resume_observed(source, None, files, cancellation, None, None, None, self.resume_observed(source, None, files, cancellation, None, None, None,
|_, _, _, _| CheckpointDecision::Continue) |_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix") .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<F: SourceProvider, S>( pub(super) fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>(
@@ -482,7 +495,7 @@ impl EntryCheckpoint {
}), }),
) )
.expect("ordinary resume cannot reject a cached suffix") .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<F: SourceProvider, S>( pub(super) fn resume_deciding_suffix<F: SourceProvider, S>(
@@ -495,7 +508,7 @@ impl EntryCheckpoint {
previous: Option<&Execution>, previous: Option<&Execution>,
timings: Option<&mut CheckpointCloneTimings>, timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>, select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision<Execution<super::DeferredStateFingerprint>>,
) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> { ) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> {
let measured = timings.is_some().then(Cell::default); let measured = timings.is_some().then(Cell::default);
let result = self.resume_observed( let result = self.resume_observed(
@@ -517,7 +530,7 @@ impl EntryCheckpoint {
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>, line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>, previous: Option<&Execution>,
timings: Option<&Cell<CheckpointCloneTimings>>, timings: Option<&Cell<CheckpointCloneTimings>>,
capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision, capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision<Execution<super::DeferredStateFingerprint>>,
) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> { ) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> {
if !self.accepts_entry(&source) if !self.accepts_entry(&source)
|| match &nested { || match &nested {
@@ -560,10 +573,7 @@ impl EntryCheckpoint {
) )
}); });
let result = match result { let result = match result {
Ok(CheckpointDecision::Reuse(execution)) => { Ok(CheckpointDecision::Reuse(execution)) => return Ok(Some(Ok(*execution))),
let fingerprint = super::DeferredStateFingerprint(Some(execution.outgoing_state));
return Ok(Some(Ok(execution.with_outgoing_state(fingerprint))));
}
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error), Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error),
Ok(CheckpointDecision::Continue) => Ok(()), Ok(CheckpointDecision::Continue) => Ok(()),
Err(error) => Err(error), Err(error) => Err(error),
@@ -4013,12 +4023,12 @@ impl Executor {
self.finish_execution(result, incoming_state, None) self.finish_execution(result, incoming_state, None)
} }
fn entry_observer<F: SourceProvider, S>( fn entry_observer<F: SourceProvider, S, R>(
incoming_state: u64, incoming_state: u64,
timings: Option<&Cell<CheckpointCloneTimings>>, timings: Option<&Cell<CheckpointCloneTimings>>,
mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>, mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision<R>,
) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision { ) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision<R> {
move |engine, initial_depth, pages_processed, files| { move |engine, initial_depth, pages_processed, files| {
if engine.job_ended { if engine.job_ended {
return CheckpointDecision::Continue; return CheckpointDecision::Continue;
@@ -4092,7 +4102,7 @@ impl Executor {
previous: Option<&Execution>, previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> { ) -> Result<Execution, ExecutionFailure> {
self.prepare_execution(result, incoming_state, previous) self.prepare_execution(result, incoming_state, previous)
.map(|execution| execution.finish_fingerprint(previous)) .map(|execution| execution.finish_fingerprint())
} }
fn prepare_execution( fn prepare_execution(
@@ -4149,11 +4159,11 @@ impl Executor {
} }
// An identical completed state has the same fingerprint. Compare // An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments. // the entire state, including token source spans and assignments.
let outgoing_state = super::DeferredStateFingerprint( let outgoing_state = if let Some(last) = previous.filter(|last| last.state == self.state) {
previous super::DeferredStateFingerprint::known(last.outgoing_state)
.filter(|last| last.state == self.state) } else {
.map(|last| last.outgoing_state), super::DeferredStateFingerprint::pending(previous.map(|last| &last.state))
); };
let format_pdf_images = self.captured_format_pdf_images(); let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution { Ok(Execution {
format_dumped: self.format_dumped, format_dumped: self.format_dumped,
@@ -4305,13 +4315,13 @@ impl Executor {
self.read_parameter(Parameter::Partokencontext).width() >= minimum self.read_parameter(Parameter::Partokencontext).width() >= minimum
} }
fn run_active_input<F: SourceProvider>( fn run_active_input<F: SourceProvider, R>(
&mut self, &mut self,
initial_depth: usize, initial_depth: usize,
mut pages_processed: bool, mut pages_processed: bool,
files: &mut F, files: &mut F,
mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision, mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision<R>,
) -> Result<CheckpointDecision, Error> { ) -> Result<CheckpointDecision<R>, Error> {
let xe = self.state.input_profile() == InputProfile::XeTeX; let xe = self.state.input_profile() == InputProfile::XeTeX;
loop { loop {
if !std::mem::take(&mut pages_processed) { if !std::mem::take(&mut pages_processed) {
@@ -1,5 +1,5 @@
use super::super::{ use super::super::{
dependency_reads::DependencyEvidence, DeferredStateFingerprint, dependency_reads::DependencyEvidence,
source_relocation::SourceRelocation, source_relocation_events::EventRelocation, source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize}, statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize},
}; };
@@ -290,6 +290,21 @@ impl EntryCheckpoint {
retained: Option<&RetainedStateFingerprint>, retained: Option<&RetainedStateFingerprint>,
timings: Option<&mut SuffixKernelTimings>, timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> { ) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
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<DeferredStateFingerprint>, Option<RelocatedShipoutSuffix>)> {
let (source_id, prefix_resource_reads) = match closed_source { let (source_id, prefix_resource_reads) = match closed_source {
Some((source_id, reads)) => { Some((source_id, reads)) => {
if reads == 0 || self.closed_source_change(prior, completed)?.source_id != source_id { if reads == 0 || self.closed_source_change(prior, completed)?.source_id != source_id {
@@ -299,7 +314,9 @@ impl EntryCheckpoint {
} }
None => (self.entry, 1), 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( fn splice_settled_sources(
@@ -309,8 +326,9 @@ impl EntryCheckpoint {
source_id: usize, source_id: usize,
prefix_resource_reads: usize, prefix_resource_reads: usize,
retained: Option<&RetainedStateFingerprint>, retained: Option<&RetainedStateFingerprint>,
defer_fingerprint: bool,
mut timings: Option<&mut SuffixKernelTimings>, mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> { ) -> Option<(Execution<DeferredStateFingerprint>, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source if self.entry != self.active_source
|| prior.entry != prior.active_source || prior.entry != prior.active_source
|| self.entry != prior.entry || self.entry != prior.entry
@@ -499,7 +517,7 @@ impl EntryCheckpoint {
dependency_evidence, dependency_evidence,
line_observations, line_observations,
incoming_state: completed.incoming_state, incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state, outgoing_state: DeferredStateFingerprint::known(completed.outgoing_state),
steps, steps,
box_nodes_created, box_nodes_created,
reads_event_history: false, reads_event_history: false,
@@ -514,9 +532,14 @@ impl EntryCheckpoint {
&& execution.state == retained.state && execution.state == retained.state
{ {
reused_final_fingerprint = true; reused_final_fingerprint = true;
retained.fingerprint DeferredStateFingerprint::known(retained.fingerprint)
} else { } 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() { } else if statistics.is_identity() {
@@ -701,21 +724,13 @@ fn splice_dependencies(
if let (Some(current_epoch), Some(donor_epoch), Some(donor)) = ( if let (Some(current_epoch), Some(donor_epoch), Some(donor)) = (
current.reads.epoch(), prior.reads.epoch(), completed.dependency_evidence.epochs(), current.reads.epoch(), prior.reads.epoch(), completed.dependency_evidence.epochs(),
) { ) {
if donor.len() != completed.reads.len() { return DependencyEvidence::splice(
return None; current.dependency_observations(),
} &completed.reads,
let mut observed: BTreeMap<Dependency, u32> = BTreeMap::new(); donor,
for (key, epoch) in current.dependency_observations() { current_epoch,
observed.entry(key).and_modify(|last| *last = (*last).max(epoch)).or_insert(epoch); donor_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)));
} }
// Restored records without epoch evidence can only preserve every // Restored records without epoch evidence can only preserve every
@@ -110,8 +110,8 @@ pub(super) fn same_kernel_provenance(
Some(measure(timings.map(|timings| &mut timings.exact_equality), || current.state == state)) Some(measure(timings.map(|timings| &mut timings.exact_equality), || current.state == state))
} }
pub(super) fn append_suffix( pub(super) fn append_suffix<F>(
execution: &mut Execution, execution: &mut Execution<F>,
tail: &[Event], tail: &[Event],
statistics: &SuffixStatistics, statistics: &SuffixStatistics,
relocation: &mut EventRelocation<'_>, relocation: &mut EventRelocation<'_>,
+35 -7
View File
@@ -703,8 +703,38 @@ pub struct Execution<F = u64> {
/// The exact final state is available for layout. Its fingerprint may still /// The exact final state is available for layout. Its fingerprint may still
/// require the canonical hash before a completed execution can be published. /// require the canonical hash before a completed execution can be published.
#[derive(Debug)] pub struct DeferredStateFingerprint(FingerprintState);
pub struct DeferredStateFingerprint(Option<u64>);
enum FingerprintState {
Known(u64),
NeedsHash(Option<state::CommandFingerprintBase>),
}
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<F> Execution<F> { impl<F> Execution<F> {
fn with_outgoing_state<T>(self, outgoing_state: T) -> Execution<T> { fn with_outgoing_state<T>(self, outgoing_state: T) -> Execution<T> {
@@ -739,13 +769,11 @@ impl<F> Execution<F> {
impl Execution<DeferredStateFingerprint> { impl Execution<DeferredStateFingerprint> {
fn needs_fingerprint(&self) -> bool { 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 { fn finish_fingerprint(self) -> Execution {
let fingerprint = self.outgoing_state.0.unwrap_or_else(|| { let fingerprint = self.outgoing_state.calculate(&self.state);
self.state.fingerprint_with_prior(previous.map(|prior| &prior.state))
});
self.with_outgoing_state(fingerprint) self.with_outgoing_state(fingerprint)
} }
} }
@@ -97,7 +97,6 @@ pub struct PreparedRevisionExecution {
execution: Execution<DeferredStateFingerprint>, execution: Execution<DeferredStateFingerprint>,
source_versions: Vec<SourceVersion>, source_versions: Vec<SourceVersion>,
resources: Option<ResourceTrace>, resources: Option<ResourceTrace>,
previous: Option<Arc<RevisionExecution>>,
} }
impl PreparedRevisionExecution { impl PreparedRevisionExecution {
@@ -115,9 +114,7 @@ impl PreparedRevisionExecution {
} }
pub fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> { pub fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> {
let execution = self.execution.finish_fingerprint( let execution = self.execution.finish_fingerprint();
self.previous.as_deref().map(|revision| &revision.execution),
);
let complete = Arc::new(RevisionExecution { let complete = Arc::new(RevisionExecution {
revision: self.job.revision, revision: self.job.revision,
execution, execution,
@@ -400,6 +397,27 @@ impl RevisionJob {
defer_fingerprint: bool, defer_fingerprint: bool,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>, select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision, capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<ResumedExecution, RevisionFailure>>, 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<F: SourceProvider, S>(
&self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
nested: Option<SourceFile>,
files: &mut F,
line_break_cache: Arc<LineBreakCache>,
timings: Option<&mut CheckpointCloneTimings>,
defer_fingerprint: bool,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision<Execution<DeferredStateFingerprint>>,
) -> Result<Option<Result<ResumedExecution, RevisionFailure>>, String> { ) -> Result<Option<Result<ResumedExecution, RevisionFailure>>, String> {
let previous = self.session.latest(); let previous = self.session.latest();
let executed = checkpoint.resume_deciding_suffix( let executed = checkpoint.resume_deciding_suffix(
@@ -423,13 +441,10 @@ impl RevisionJob {
execution, execution,
source_versions, source_versions,
resources, resources,
previous,
}))) })))
} }
result => { result => {
let executed = result.map(|execution| execution.finish_fingerprint( let executed = result.map(Execution::finish_fingerprint);
previous.as_deref().map(|item| &item.execution),
));
self.finish_execution(executed, files, previous.as_deref()) self.finish_execution(executed, files, previous.as_deref())
.map(ResumedExecution::Complete) .map(ResumedExecution::Complete)
} }
+16 -2
View File
@@ -1197,6 +1197,8 @@ impl<'de> serde::Deserialize<'de> for CommandBindings {
} }
} }
pub(super) struct CommandFingerprintBase(Arc<CommandBindings>);
// Derive the ordinary hash and emit the specialized fingerprint in the // Derive the ordinary hash and emit the specialized fingerprint in the
// same field order. Only the command meanings can reuse recorded hash input. // same field order. Only the command meanings can reuse recorded hash input.
macro_rules! define_state { macro_rules! define_state {
@@ -1213,9 +1215,21 @@ macro_rules! define_state {
self.fingerprint_with_prior(None) 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(); 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);)* $(self.$field.hash(&mut hash);)*
hash.finish() hash.finish()
} }
+7 -5
View File
@@ -1139,18 +1139,19 @@ impl SelectedCheckpoint {
let timed = observer.is_some(); let timed = observer.is_some();
let detailed_observer = observer.filter(|observer| observer.wants_checkpoint_details()); let detailed_observer = observer.filter(|observer| observer.wants_checkpoint_details());
let mut clones = CheckpointCloneTimings::default(); 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 resume_started = timed.then(Instant::now);
let result = job let result = job
.resume_deciding_suffix_prepared( .resume_deciding_suffix_staged(
&checkpoint.entry, &checkpoint.entry,
source, source,
nested_source, nested_source,
&mut recording, &mut recording,
line_break_cache, line_break_cache,
detailed_observer.is_some().then_some(&mut clones), detailed_observer.is_some().then_some(&mut clones),
observer.is_some_and(|observer| { defer_fingerprint,
observer.preview_before_export() && observer.preview_before_fingerprint()
}),
|source, pages| { |source, pages| {
if source.is_entry { if source.is_entry {
// The loaded entry line can be shared by several shipouts. // 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 result = measure(&mut timings.suffix_kernel_validation, timed, || {
let kernel_timings = attempt.as_mut().or(timed.then_some(&mut timings.suffix_kernel)); 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, &old.entry,
&completed.result.execution, &completed.result.execution,
closed_source.as_ref().map(|child| (child.source_id, child.prefix_resource_reads)), closed_source.as_ref().map(|child| (child.source_id, child.prefix_resource_reads)),
self.previous_fingerprint.as_deref(), self.previous_fingerprint.as_deref(),
defer_fingerprint,
kernel_timings, kernel_timings,
) )
}); });
+113 -8
View File
@@ -2081,11 +2081,8 @@ fn resized_entry_prefix_invalidates_an_executed_file_size_query() {
fs::remove_dir_all(cwd).unwrap(); fs::remove_dir_all(cwd).unwrap();
} }
#[test] fn resized_suffix_body(letter: char, note: &str, tail_query: &str) -> String {
fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { format!(r"
let cwd = directory("settled-resized-suffix");
let entry = cwd.join("main.tex");
let body = |letter, note, tail_query| format!(r"
\tracingstats=2 \tracingstats=2
\shipout\hbox{{Cover ABC}} \shipout\hbox{{Cover ABC}}
\setbox3=\hbox{{{letter}}}\relax%{note} \setbox3=\hbox{{{letter}}}\relax%{note}
@@ -2099,10 +2096,16 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() {
\relax \relax
\shipout\hbox{{Final}} \shipout\hbox{{Final}}
\end \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"] { for tail_query in ["", r"\count42=\pdffilesize{main.tex}\relax"] {
let mut project = ProjectSnapshot::new( 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(); ).unwrap();
let mut request = request(&cwd).observe_generated_initial(); let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration(); 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. // Only the current document can donate the suffix in either direction.
let session = NativeCompiler::default().with_automatic_entry_checkpoints(); let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let previous = session.compile(request.clone().with_project(project.clone())).unwrap(); 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 tail_offset = source.find("Suffix glyphs").unwrap();
let bytes = i32::try_from(source.len()).unwrap(); let bytes = i32::try_from(source.len()).unwrap();
project = project.with_file_edits( 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(); fs::remove_dir_all(cwd).unwrap();
} }
#[test]
fn preview_before_relocated_suffix_fingerprint_preserves_exact_publication() {
struct WatchDraft {
compiler: NativeCompiler,
previous: Arc<CompiledDocument>,
cancel: bool,
preview: Mutex<Option<PreviewUpdate>>,
}
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::<Vec<_>>(), [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] #[test]
fn whole_line_edits_reuse_the_settled_suffix_and_relocate_provenance() { fn whole_line_edits_reuse_the_settled_suffix_and_relocate_provenance() {
check_whole_line_suffix_edits("whole-line-safe-suffix", InputProfile::TeX8Bit, false); check_whole_line_suffix_edits("whole-line-safe-suffix", InputProfile::TeX8Bit, false);