Reuse exact final fingerprints of distinct published states

This commit is contained in:
gloamxun committed 2026-12-02 04:41:41 +08:00
1 parent af8f38bb78
commit 841198615a
5 files changed
+98 -23

No files matched your search

@@ -47,7 +47,8 @@ mod specials;
mod statistics; mod statistics;
mod continuation; mod continuation;
pub use continuation::{ pub use continuation::{
ClosedSourceChange, RelocatedShipoutSuffix, SuffixKernelTimings, SuffixStateProofTimings, ClosedSourceChange, RelocatedShipoutSuffix, RetainedStateFingerprint, SuffixKernelTimings,
SuffixStateProofTimings,
}; };
mod xdv_annotation; mod xdv_annotation;
@@ -101,6 +101,8 @@ pub struct SuffixKernelTimings {
pub state_proof: Option<SuffixStateProofTimings>, pub state_proof: Option<SuffixStateProofTimings>,
pub retained_accounting: Duration, pub retained_accounting: Duration,
pub suffix_assembly: Duration, pub suffix_assembly: Duration,
/// Exact matches with an earlier distinct completed state.
pub reused_final_fingerprints: usize,
} }
/// Work within state comparison, which also checks the surrounding executor. /// Work within state comparison, which also checks the surrounding executor.
@@ -119,6 +121,7 @@ impl std::ops::AddAssign for SuffixKernelTimings {
self.state_comparison += attempt.state_comparison; self.state_comparison += attempt.state_comparison;
self.retained_accounting += attempt.retained_accounting; self.retained_accounting += attempt.retained_accounting;
self.suffix_assembly += attempt.suffix_assembly; self.suffix_assembly += attempt.suffix_assembly;
self.reused_final_fingerprints += attempt.reused_final_fingerprints;
if let Some(attempt) = attempt.state_proof { if let Some(attempt) = attempt.state_proof {
let total = self.state_proof.get_or_insert_with(SuffixStateProofTimings::default); let total = self.state_proof.get_or_insert_with(SuffixStateProofTimings::default);
total.attempts += attempt.attempts; total.attempts += attempt.attempts;
@@ -131,6 +134,22 @@ impl std::ops::AddAssign for SuffixKernelTimings {
} }
} }
/// The final state and exact fingerprint of a completed execution.
pub struct RetainedStateFingerprint {
state: State,
fingerprint: u64,
}
impl Execution {
/// Retain just the state needed to compare a future splice.
pub fn retain_final_state_fingerprint(&self) -> RetainedStateFingerprint {
RetainedStateFingerprint {
state: self.state.clone(),
fingerprint: self.outgoing_state,
}
}
}
/// Source coordinates for the shipouts copied from a moved execution suffix. /// Source coordinates for the shipouts copied from a moved execution suffix.
pub struct RelocatedShipoutSuffix { pub struct RelocatedShipoutSuffix {
first_page: usize, first_page: usize,
@@ -242,7 +261,7 @@ impl EntryCheckpoint {
completed: &Execution, completed: &Execution,
timings: Option<&mut SuffixKernelTimings>, timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> { ) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.splice_settled_sources(prior, completed, self.entry, 1, timings) self.splice_settled_suffix_with_fingerprint(prior, completed, None, None, timings)
} }
/// Reuse a suffix after the caller has verified the actual host reads /// Reuse a suffix after the caller has verified the actual host reads
@@ -256,12 +275,31 @@ impl EntryCheckpoint {
prefix_resource_reads: usize, prefix_resource_reads: usize,
timings: Option<&mut SuffixKernelTimings>, timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> { ) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if prefix_resource_reads == 0 self.splice_settled_suffix_with_fingerprint(
|| self.closed_source_change(prior, completed)?.source_id != source_id prior, completed, Some((source_id, prefix_resource_reads)), None, timings,
{ )
}
/// Verify a settled suffix with an optional prior state used only for
/// its final fingerprint. The usual kernel and host proofs still apply.
pub fn splice_settled_suffix_with_fingerprint(
&self,
prior: &Self,
completed: &Execution,
closed_source: Option<(usize, usize)>,
retained: Option<&RetainedStateFingerprint>,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
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 {
return None; return None;
} }
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, timings) (source_id, reads)
}
None => (self.entry, 1),
};
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, retained, timings)
} }
fn splice_settled_sources( fn splice_settled_sources(
@@ -270,6 +308,7 @@ impl EntryCheckpoint {
completed: &Execution, completed: &Execution,
source_id: usize, source_id: usize,
prefix_resource_reads: usize, prefix_resource_reads: usize,
retained: Option<&RetainedStateFingerprint>,
mut timings: Option<&mut SuffixKernelTimings>, mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> { ) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source if self.entry != self.active_source
@@ -425,7 +464,8 @@ impl EntryCheckpoint {
let statistics = SuffixStatistics { steps: offset, boxes: box_offset, retained_history }; let statistics = SuffixStatistics { steps: offset, boxes: box_offset, retained_history };
// The joined events are published results. Resumption always starts // The joined events are published results. Resumption always starts
// from a live checkpoint, whose original shared allocations stay intact. // from a live checkpoint, whose original shared allocations stay intact.
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || { let mut reused_final_fingerprint = false;
let execution = measure(timings.as_deref_mut().map(|timings| &mut timings.suffix_assembly), || {
let mut events = Vec::with_capacity(current.events.len().checked_add(tail.len())?); let mut events = Vec::with_capacity(current.events.len().checked_add(tail.len())?);
events.extend(current.events.iter().cloned()); events.extend(current.events.iter().cloned());
let (reads, dependency_evidence) = splice_dependencies(current, old, completed)?; let (reads, dependency_evidence) = splice_dependencies(current, old, completed)?;
@@ -460,8 +500,14 @@ impl EntryCheckpoint {
&mut execution, tail, &statistics, moved, resize, old.sources.len(), &mut execution, tail, &statistics, moved, resize, old.sources.len(),
)?; )?;
if execution.state != completed.state { if execution.state != completed.state {
execution.outgoing_state = execution.state execution.outgoing_state = if let Some(retained) = retained
.fingerprint_with_prior(Some(&completed.state)); && execution.state == retained.state
{
reused_final_fingerprint = true;
retained.fingerprint
} else {
execution.state.fingerprint_with_prior(Some(&completed.state))
};
} }
} else if statistics.is_identity() { } else if statistics.is_identity() {
execution.events.extend_from_slice(tail); execution.events.extend_from_slice(tail);
@@ -477,6 +523,9 @@ impl EntryCheckpoint {
} }
Some(execution) Some(execution)
})?; })?;
if let Some(timings) = timings {
timings.reused_final_fingerprints += usize::from(reused_final_fingerprint);
}
let layout = relocation.map(|map| RelocatedShipoutSuffix { let layout = relocation.map(|map| RelocatedShipoutSuffix {
// The executor records one top-level shipout event whenever // The executor records one top-level shipout event whenever
// this count advances. Form canvases do not enter this sequence. // this count advances. Form canvases do not enter this sequence.
+1 -1
View File
@@ -73,7 +73,7 @@ pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{ pub use engine::{
CheckpointCloneTimings, CheckpointDecision, CheckpointSource, ClosedSourceChange, CheckpointCloneTimings, CheckpointDecision, CheckpointSource, ClosedSourceChange,
EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, SuffixKernelTimings, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, RetainedStateFingerprint, SuffixKernelTimings,
SuffixStateProofTimings, SuffixStateProofTimings,
}; };
pub use font_catalog::{ pub use font_catalog::{
+15 -2
View File
@@ -8,12 +8,13 @@ use std::{
path::{Component, Path, PathBuf}, path::{Component, Path, PathBuf},
sync::{ sync::{
Arc, Condvar, Mutex, mpsc, Arc, Condvar, Mutex, mpsc,
atomic::{AtomicBool, AtomicU64, Ordering}, atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
}, },
time::Instant, time::Instant,
}; };
use texrra_engine::native::{ use texrra_engine::native::{
CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, DraftPreview, Entry, CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage,
DraftPreview, Entry,
EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot, EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot,
job_time, job_time,
}; };
@@ -98,6 +99,7 @@ struct StageTiming {
struct EditorObserver { struct EditorObserver {
started: Instant, started: Instant,
initial_worker_usage: Option<ThreadUsage>, initial_worker_usage: Option<ThreadUsage>,
reused_final_fingerprints: AtomicUsize,
ended: Mutex<[StageTiming; 5]>, ended: Mutex<[StageTiming; 5]>,
queue: Arc<Queue>, queue: Arc<Queue>,
respond_to: Mutex<Option<PreviewReply>>, respond_to: Mutex<Option<PreviewReply>>,
@@ -120,6 +122,15 @@ impl CompileObserver for EditorObserver {
Ok(()) Ok(())
} }
fn checkpoint_timings(&self, _: u64, timings: CheckpointTimings) {
if self.initial_worker_usage.is_some() {
self.reused_final_fingerprints.store(
timings.suffix_kernel.reused_final_fingerprints,
Ordering::Relaxed,
);
}
}
fn preview_before_export(&self) -> bool { fn preview_before_export(&self) -> bool {
self.preview_draft self.preview_draft
} }
@@ -223,6 +234,7 @@ impl EditorObserver {
"layout_and_fonts": ThreadUsage::between(executed.worker, fonts.worker), "layout_and_fonts": ThreadUsage::between(executed.worker, fonts.worker),
"export": ThreadUsage::between(fonts.worker, exported.worker), "export": ThreadUsage::between(fonts.worker, exported.worker),
"ready": ThreadUsage::between(Some(initial), ready.worker), "ready": ThreadUsage::between(Some(initial), ready.worker),
"reused_final_fingerprints": self.reused_final_fingerprints.load(Ordering::Relaxed),
}); });
} }
payload payload
@@ -944,6 +956,7 @@ fn worker(queue: &Arc<Queue>) {
let observer = Arc::new(EditorObserver { let observer = Arc::new(EditorObserver {
started: Instant::now(), started: Instant::now(),
initial_worker_usage: measure_worker.then(ThreadUsage::current).flatten(), initial_worker_usage: measure_worker.then(ThreadUsage::current).flatten(),
reused_final_fingerprints: AtomicUsize::new(0),
ended: Mutex::new([StageTiming::default(); 5]), ended: Mutex::new([StageTiming::default(); 5]),
queue: queue.clone(), queue: queue.clone(),
respond_to: Mutex::new(Some(respond_to)), respond_to: Mutex::new(Some(respond_to)),
+23 -11
View File
@@ -10,7 +10,7 @@ use std::{
time::Instant, time::Instant,
}; };
use texrra_tex_core::{ use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport}, execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, RetainedStateFingerprint, StatisticsPhase, StatisticsReport},
resources::{ResourceKind, ResourceLookup, ResourceReadRange}, resources::{ResourceKind, ResourceLookup, ResourceReadRange},
}; };
#[cfg(test)] #[cfg(test)]
@@ -45,6 +45,7 @@ pub(super) struct PublishedCheckpoints {
current: Arc<CheckpointSet>, current: Arc<CheckpointSet>,
previous_body: Option<Arc<CheckpointSet>>, previous_body: Option<Arc<CheckpointSet>>,
previous_completion: Option<Arc<CompletedExecution>>, previous_completion: Option<Arc<CompletedExecution>>,
previous_fingerprint: Option<Arc<RetainedStateFingerprint>>,
} }
struct CachedCheckpoint { struct CachedCheckpoint {
@@ -90,6 +91,7 @@ pub(super) struct CheckpointSet {
pub(super) struct SelectedCheckpoint { pub(super) struct SelectedCheckpoint {
set: Arc<CheckpointSet>, set: Arc<CheckpointSet>,
candidate: ExecutionCandidate, candidate: ExecutionCandidate,
previous_fingerprint: Option<Arc<RetainedStateFingerprint>>,
} }
pub(super) struct ReusedShipoutLayouts { pub(super) struct ReusedShipoutLayouts {
@@ -627,10 +629,23 @@ impl CheckpointCache {
let previous_completion = published.as_ref().and_then(|published| { let previous_completion = published.as_ref().and_then(|published| {
published.current.completion.clone().or_else(|| published.previous_completion.clone()) published.current.completion.clone().or_else(|| published.previous_completion.clone())
}); });
let previous_fingerprint = published.as_ref().and_then(|published| {
if let Some((before, after)) = published.current.completion.as_ref().zip(next.completion.as_ref()) {
let before = &before.result.execution;
let after = &after.result.execution;
// Equal results should not evict the other distinct state.
// A hash mismatch proves distinctness, but a match does not prove equality.
if before.outgoing_state != after.outgoing_state || before.state != after.state {
return Some(Arc::new(before.retain_final_state_fingerprint()));
}
}
published.previous_fingerprint.clone()
});
*published = Some(Arc::new(PublishedCheckpoints { *published = Some(Arc::new(PublishedCheckpoints {
current: next, current: next,
previous_body, previous_body,
previous_completion, previous_completion,
previous_fingerprint,
})); }));
} }
@@ -692,6 +707,7 @@ impl PublishedCheckpoints {
SelectedCheckpoint { SelectedCheckpoint {
set: self.current.clone(), set: self.current.clone(),
candidate: ExecutionCandidate::Completed(result.clone()), candidate: ExecutionCandidate::Completed(result.clone()),
previous_fingerprint: None,
} }
})) }))
.collect(); .collect();
@@ -761,7 +777,7 @@ impl PublishedCheckpoints {
EffectMode::Draft, EffectMode::Draft,
KernelPreparation::Resume, KernelPreparation::Resume,
)?; )?;
let selected = selected.expect("resume preparation chose a verified checkpoint"); let mut selected = selected.expect("resume preparation chose a verified checkpoint");
let guard = selected.guard(); let guard = selected.guard();
let partial_source = guard.nested_source.as_ref() let partial_source = guard.nested_source.as_ref()
.and_then(|source| project.file(&source.path)).map(|file| &file.version); .and_then(|source| project.file(&source.path)).map(|file| &file.version);
@@ -783,6 +799,7 @@ impl PublishedCheckpoints {
continue; continue;
} }
*evidence = attempt; *evidence = attempt;
selected.previous_fingerprint = self.previous_fingerprint.clone();
return Ok((selected, prepared)); return Ok((selected, prepared));
} }
} }
@@ -825,6 +842,7 @@ impl CheckpointSet {
.map(|index| SelectedCheckpoint { .map(|index| SelectedCheckpoint {
set: Arc::clone(self), set: Arc::clone(self),
candidate: ExecutionCandidate::Boundary(index), candidate: ExecutionCandidate::Boundary(index),
previous_fingerprint: None,
}) })
} }
} }
@@ -1041,19 +1059,13 @@ 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));
if let Some(child) = &closed_source { entry.splice_settled_suffix_with_fingerprint(
entry.splice_settled_closed_source_suffix_observed(
&old.entry, &old.entry,
&completed.result.execution, &completed.result.execution,
child.source_id, closed_source.as_ref().map(|child| (child.source_id, child.prefix_resource_reads)),
child.prefix_resource_reads, self.previous_fingerprint.as_deref(),
kernel_timings, kernel_timings,
) )
} else {
entry.splice_settled_suffix_observed(
&old.entry, &completed.result.execution, kernel_timings,
)
}
}); });
if let Some((observer, attempt)) = detailed_observer.zip(attempt) { if let Some((observer, attempt)) = detailed_observer.zip(attempt) {
timings.suffix_kernel += attempt; timings.suffix_kernel += attempt;