Expose optional checkpoint clone and suffix proof timings

This commit is contained in:
gloamxun committed 2026-12-02 02:38:43 +08:00
1 parent 67396827a9
commit c8f7a0cbe6
7 files changed
+170 -27

No files matched your search

+44 -7
View File
@@ -1,6 +1,8 @@
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::hash::{BuildHasher, RandomState};
use std::sync::Arc;
use std::time::{Duration, Instant};
use hashbrown::{HashMap, hash_map::RawEntryMut};
@@ -44,7 +46,9 @@ mod scheduling;
mod specials;
mod statistics;
mod continuation;
pub use continuation::{ClosedSourceChange, RelocatedShipoutSuffix, SuffixKernelTimings};
pub use continuation::{
ClosedSourceChange, RelocatedShipoutSuffix, SuffixKernelTimings, SuffixStateProofTimings,
};
mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -337,6 +341,14 @@ pub enum CheckpointDecision {
ReplayFailed(String),
}
/// Time spent cloning live kernel state while resuming or capturing checkpoints.
#[derive(Clone, Copy, Debug, Default)]
pub struct CheckpointCloneTimings {
pub restore: Duration,
pub capture: Duration,
pub captures: usize,
}
/// A live, in-memory kernel continuation at an entry-file command boundary.
/// The host must validate dependencies and replay all prefix effects before
/// resumption. The checkpoint itself validates the entry bytes already loaded.
@@ -437,7 +449,7 @@ impl EntryCheckpoint {
files: &mut impl SourceProvider,
cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed(source, None, files, cancellation, None, None,
self.resume_observed(source, None, files, cancellation, None, None, None,
|_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix")
}
@@ -460,7 +472,8 @@ impl EntryCheckpoint {
cancellation,
Some(line_break_cache),
previous,
Executor::entry_observer(self.incoming_state, select, |slot, entry, files| {
None,
Executor::entry_observer(self.incoming_state, None, select, |slot, entry, files| {
capture(slot, entry, files);
CheckpointDecision::Continue
}),
@@ -476,11 +489,19 @@ impl EntryCheckpoint {
cancellation: Cancellation,
line_break_cache: Arc<super::LineBreakCache>,
previous: Option<&Execution>,
timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
self.resume_observed(source, nested, files, cancellation, Some(line_break_cache), previous,
Executor::entry_observer(self.incoming_state, select, capture))
let measured = timings.is_some().then(Cell::default);
let result = self.resume_observed(
source, nested, files, cancellation, Some(line_break_cache), previous, measured.as_ref(),
Executor::entry_observer(self.incoming_state, measured.as_ref(), select, capture),
);
if let Some((timings, measured)) = timings.zip(measured) {
*timings = measured.into_inner();
}
result
}
fn resume_observed<F: SourceProvider>(
@@ -491,6 +512,7 @@ impl EntryCheckpoint {
cancellation: Cancellation,
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>,
timings: Option<&Cell<CheckpointCloneTimings>>,
capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
if !self.accepts_entry(&source)
@@ -501,7 +523,14 @@ impl EntryCheckpoint {
{
return Ok(None);
}
let mut executor = self.executor.clone().with_cancellation(cancellation);
let started = timings.is_some().then(Instant::now);
let executor = self.executor.clone();
if let Some((timings, started)) = timings.zip(started) {
let mut measured = timings.get();
measured.restore += started.elapsed();
timings.set(measured);
}
let mut executor = executor.with_cancellation(cancellation);
executor.reads.advance_epoch();
executor.line_break_cache = line_break_cache;
let previous_len = self.executor.sources[self.entry].data.len();
@@ -3962,7 +3991,7 @@ impl Executor {
let result = self.run_observed(
file,
files,
Self::entry_observer(incoming_state, select, |slot, entry, files| {
Self::entry_observer(incoming_state, None, select, |slot, entry, files| {
capture(slot, entry, files);
CheckpointDecision::Continue
}),
@@ -3972,6 +4001,7 @@ impl Executor {
fn entry_observer<F: SourceProvider, S>(
incoming_state: u64,
timings: Option<&Cell<CheckpointCloneTimings>>,
mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision {
@@ -4016,7 +4046,14 @@ impl Executor {
return CheckpointDecision::Continue;
}
engine.events.seal_prefix();
let started = timings.is_some().then(Instant::now);
let mut executor = engine.clone();
if let Some((timings, started)) = timings.zip(started) {
let mut measured = timings.get();
measured.capture += started.elapsed();
measured.captures += 1;
timings.set(measured);
}
// Any subsequent read belongs to the suffix, even if it
// happens before the next logical TeX execution step.
engine.reads.advance_epoch();
@@ -97,10 +97,40 @@ impl InputFrame {
#[derive(Clone, Copy, Debug, Default)]
pub struct SuffixKernelTimings {
pub state_comparison: Duration,
/// The caller can enable the more detailed checks without changing this path.
pub state_proof: Option<SuffixStateProofTimings>,
pub retained_accounting: Duration,
pub suffix_assembly: Duration,
}
/// Work within state comparison, which also checks the surrounding executor.
#[derive(Clone, Copy, Debug, Default)]
pub struct SuffixStateProofTimings {
pub attempts: usize,
pub matches: usize,
pub relocated_attempts: usize,
pub state_clone: Duration,
pub state_relocation: Duration,
pub exact_equality: Duration,
}
impl std::ops::AddAssign for SuffixKernelTimings {
fn add_assign(&mut self, attempt: Self) {
self.state_comparison += attempt.state_comparison;
self.retained_accounting += attempt.retained_accounting;
self.suffix_assembly += attempt.suffix_assembly;
if let Some(attempt) = attempt.state_proof {
let total = self.state_proof.get_or_insert_with(SuffixStateProofTimings::default);
total.attempts += attempt.attempts;
total.matches += attempt.matches;
total.relocated_attempts += attempt.relocated_attempts;
total.state_clone += attempt.state_clone;
total.state_relocation += attempt.state_relocation;
total.exact_equality += attempt.exact_equality;
}
}
}
/// Source coordinates for the shipouts copied from a moved execution suffix.
pub struct RelocatedShipoutSuffix {
first_page: usize,
@@ -339,9 +369,24 @@ impl EntryCheckpoint {
// Comparison and publication visit some of the same original
// allocations. Keep the checked relocations for this donor only.
let mut moved = relocation.as_ref().map(EventRelocation::new);
if !measure(timings.as_deref_mut().map(|timings| &mut timings.state_comparison), || {
same_kernel_continuation(current, old, moved.as_mut())
}) {
let states_match = if let Some(timings) = timings.as_deref_mut() {
let started = Instant::now();
if let Some(proof) = &mut timings.state_proof {
proof.attempts += 1;
proof.relocated_attempts += usize::from(moved.is_some());
}
let matched = same_kernel_continuation(
current, old, moved.as_mut(), timings.state_proof.as_mut(),
);
if let Some(proof) = &mut timings.state_proof {
proof.matches += usize::from(matched);
}
timings.state_comparison += started.elapsed();
matched
} else {
same_kernel_continuation(current, old, moved.as_mut(), None)
};
if !states_match {
return None;
}
let offset = StepOffset::new(old.steps, current.steps);
@@ -707,6 +752,7 @@ fn same_kernel_continuation(
current: &Executor,
prior: &Executor,
relocation: Option<&mut EventRelocation<'_>>,
timings: Option<&mut SuffixStateProofTimings>,
) -> bool {
// Every field belongs to one of these checks. Adding kernel state requires
// an explicit decision here before a later execution may be skipped.
@@ -824,9 +870,9 @@ fn same_kernel_continuation(
return false;
}
if let Some(relocation) = relocation {
return relocate::same_kernel_provenance(current, prior, relocation).unwrap_or(false);
return relocate::same_kernel_provenance(current, prior, relocation, timings).unwrap_or(false);
}
current.state == prior.state
measure(timings.map(|timings| &mut timings.exact_equality), || current.state == prior.state)
&& current.generated_inputs == prior.generated_inputs
&& current.conditionals == prior.conditionals
&& current.current == prior.current
@@ -5,6 +5,7 @@ pub(super) fn same_kernel_provenance(
current: &Executor,
prior: &Executor,
relocation: &mut EventRelocation<'_>,
mut timings: Option<&mut SuffixStateProofTimings>,
) -> Option<bool> {
let map = relocation.map();
if current.current != map.relocate_span(prior.current)?
@@ -98,9 +99,15 @@ pub(super) fn same_kernel_provenance(
return Some(false);
}
let mut state = prior.state.clone();
state.relocate_source(relocation)?;
Some(current.state == state)
let mut state = measure(
timings.as_deref_mut().map(|timings| &mut timings.state_clone),
|| prior.state.clone(),
);
measure(
timings.as_deref_mut().map(|timings| &mut timings.state_relocation),
|| state.relocate_source(relocation),
)?;
Some(measure(timings.map(|timings| &mut timings.exact_equality), || current.state == state))
}
pub(super) fn append_suffix(
+3 -3
View File
@@ -72,9 +72,9 @@ pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{
CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Executor, Limits,
RelocatedShipoutSuffix,
SuffixKernelTimings,
CheckpointCloneTimings, CheckpointDecision, CheckpointSource, ClosedSourceChange,
EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, SuffixKernelTimings,
SuffixStateProofTimings,
};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
@@ -3,7 +3,8 @@ use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex};
use super::{
Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, LineBreakCache,
Cancellation, CheckpointCloneTimings, EntryCheckpoint, Error, Execution, ExecutionFailure,
Executor, LineBreakCache,
SourceFile, SourceProvider,
};
@@ -305,11 +306,28 @@ impl RevisionJob {
line_break_cache: Arc<LineBreakCache>,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
self.resume_deciding_suffix_observed(
checkpoint, source, nested, files, line_break_cache, None, select, capture,
)
}
/// Resume with optional timing for the executor clones used by checkpoints.
pub fn resume_deciding_suffix_observed<F: SourceProvider, S>(
&self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
nested: Option<SourceFile>,
files: &mut F,
line_break_cache: Arc<LineBreakCache>,
timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<Arc<RevisionExecution>, 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,
previous.as_deref().map(|item| &item.execution), timings, select, capture,
)?;
Ok(executed.map(|result| self.finish_execution(result, files, previous.as_deref())))
}
+20 -1
View File
@@ -33,7 +33,8 @@ pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, Project
pub use texrra_tex_core::resources::{WorldFailure, WorldObservation};
use texrra_tex_core::{
execution::{
Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits,
Cancellation, CheckpointCloneTimings, ExecutionFailure, Executor, FormatImage, InputProfile,
JobTime, Limits,
NativeSession, Profile, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
SourceProvider, State, SuffixKernelTimings, WriteDestination,
},
@@ -102,6 +103,8 @@ pub struct CheckpointTimings {
/// Restoring the executor, running new commands, observing checkpoints,
/// and finishing the revision's kernel result.
pub resume: Duration,
/// Executor clone times within resume, including captures rejected by the host.
pub clones: CheckpointCloneTimings,
pub capture: Duration,
pub suffix_host_validation: Duration,
pub suffix_kernel_validation: Duration,
@@ -121,6 +124,22 @@ pub trait CompileObserver: Send + Sync {
/// Observe the work of a resumed native revision before layout begins.
fn checkpoint_timings(&self, _revision: u64, _timings: CheckpointTimings) {}
/// Opt in to executor clone timings and individual suffix candidate observations.
fn wants_checkpoint_details(&self) -> bool {
false
}
/// Observe one candidate that reached the kernel. Donors are numbered in
/// the order considered, starting at zero. Acceptance here precedes replay.
fn suffix_candidate_timing(
&self,
_revision: u64,
_page: usize,
_donor_index: usize,
_accepted: bool,
_timings: SuffixKernelTimings,
) {}
/// Called for a completed native draft before its staged files are synced
/// and installed. The caller can display these pages provisionally. The
/// compile result determines whether this revision actually published.
+22 -6
View File
@@ -982,15 +982,19 @@ impl SelectedCheckpoint {
let mut suffix_base = None;
let mut reused_layouts = None;
let mut timings = CheckpointTimings::default();
let timed = request.observer.is_some();
let observer = request.observer.as_deref();
let timed = observer.is_some();
let detailed_observer = observer.filter(|observer| observer.wants_checkpoint_details());
let mut clones = CheckpointCloneTimings::default();
let resume_started = timed.then(Instant::now);
let result = job
.resume_deciding_suffix(
.resume_deciding_suffix_observed(
&checkpoint.entry,
source,
nested_source,
&mut recording,
line_break_cache,
detailed_observer.is_some().then_some(&mut clones),
|source, pages| {
if source.is_entry {
// The loaded entry line can be shared by several shipouts.
@@ -1016,7 +1020,7 @@ impl SelectedCheckpoint {
let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else {
return CheckpointDecision::Continue;
};
let Some((completed, old, execution, layout, closed_source)) = suffixes.clone().find_map(|completed| {
let Some((completed, old, execution, layout, closed_source)) = suffixes.clone().enumerate().find_map(|(donor_index, completed)| {
let old = completed.settled.get(&page)?;
let closed_source = measure(&mut timings.suffix_host_validation, timed, || {
if old.call_count != new.call_count {
@@ -1031,8 +1035,12 @@ impl SelectedCheckpoint {
prove_closed_source_suffix(change, old, new, completed, request, host)
.map(Some)
})?;
let kernel_timings = timed.then_some(&mut timings.suffix_kernel);
let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || {
let mut attempt = detailed_observer.map(|_| SuffixKernelTimings {
state_proof: Some(Default::default()),
..SuffixKernelTimings::default()
});
let result = measure(&mut timings.suffix_kernel_validation, timed, || {
let kernel_timings = attempt.as_mut().or(timed.then_some(&mut timings.suffix_kernel));
if let Some(child) = &closed_source {
entry.splice_settled_closed_source_suffix_observed(
&old.entry,
@@ -1046,7 +1054,14 @@ impl SelectedCheckpoint {
&old.entry, &completed.result.execution, kernel_timings,
)
}
})?;
});
if let Some((observer, attempt)) = detailed_observer.zip(attempt) {
timings.suffix_kernel += attempt;
observer.suffix_candidate_timing(
job.revision(), page, donor_index, result.is_some(), attempt,
);
}
let (execution, layout) = result?;
Some((completed, old, execution, layout, closed_source))
}) else {
return CheckpointDecision::Continue;
@@ -1089,6 +1104,7 @@ impl SelectedCheckpoint {
.ok_or_else(changed_prefix)?;
if let Some(started) = resume_started {
timings.resume = started.elapsed();
timings.clones = clones;
}
let next = measure(&mut timings.retain, timed, || {
result.as_ref().ok().and_then(|result| captures.finish(recording, true, result, suffix_base))