894 lines
35 KiB
Rust
894 lines
35 KiB
Rust
use super::super::{
|
|
dependency_reads::DependencyEvidence,
|
|
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
|
|
statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize},
|
|
};
|
|
use super::*;
|
|
use std::time::{Duration, Instant};
|
|
mod material;
|
|
mod relocate;
|
|
use material::MaterialReuse;
|
|
|
|
impl InputFrame {
|
|
fn same_at_shipout(&self, other: &Self, relocation: Option<&SourceRelocation>) -> bool {
|
|
match (self, other) {
|
|
(
|
|
Self::Source {
|
|
source: a,
|
|
mouth: am,
|
|
eof_seen: ae,
|
|
pseudo_trace: at,
|
|
group_boundary: ag,
|
|
conditional_boundary: ac,
|
|
},
|
|
Self::Source {
|
|
source: b,
|
|
mouth: bm,
|
|
eof_seen: be,
|
|
pseudo_trace: bt,
|
|
group_boundary: bg,
|
|
conditional_boundary: bc,
|
|
},
|
|
) => (a, ae, at, ag, ac) == (b, be, bt, bg, bc)
|
|
&& match relocation.filter(|map| map.source() == *a) {
|
|
Some(map) => am.same_unread_input_relocated(bm, map),
|
|
None => am.same_unread_input(bm),
|
|
},
|
|
(
|
|
Self::Tokens {
|
|
tokens: a,
|
|
cursor: ac,
|
|
kind: ak,
|
|
},
|
|
Self::Tokens {
|
|
tokens: b,
|
|
cursor: bc,
|
|
kind: bk,
|
|
},
|
|
) => (ac, ak) == (bc, bk) && a.iter().eq(b.iter()),
|
|
(
|
|
Self::Macro {
|
|
definition: a,
|
|
name: an,
|
|
cursor: ac,
|
|
arguments: aa,
|
|
call: aspan,
|
|
},
|
|
Self::Macro {
|
|
definition: b,
|
|
name: bn,
|
|
cursor: bc,
|
|
arguments: ba,
|
|
call: bspan,
|
|
},
|
|
) => (a, an, ac, aa, aspan) == (b, bn, bc, ba, bspan),
|
|
(
|
|
Self::Argument {
|
|
tokens: a,
|
|
cursor: ac,
|
|
call: aspan,
|
|
},
|
|
Self::Argument {
|
|
tokens: b,
|
|
cursor: bc,
|
|
call: bspan,
|
|
},
|
|
) => (a, ac, aspan) == (b, bc, bspan),
|
|
(
|
|
Self::Hook {
|
|
parameter: a,
|
|
tokens: at,
|
|
cursor: ac,
|
|
},
|
|
Self::Hook {
|
|
parameter: b,
|
|
tokens: bt,
|
|
cursor: bc,
|
|
},
|
|
) => (a, at, ac) == (b, bt, bc),
|
|
(Self::Boundary, Self::Boundary) => true,
|
|
_ => false,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Work done inside an observed suffix splice. A rejected candidate can
|
|
/// contribute to the checks it reached.
|
|
#[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,
|
|
map: SourceRelocation,
|
|
}
|
|
|
|
impl RelocatedShipoutSuffix {
|
|
/// Relocate a raw local layout from the exact donor execution at the
|
|
/// given zero-based shipout index. The host must match that execution
|
|
/// before supplying a cached list.
|
|
pub fn relocate_layout(
|
|
&self,
|
|
index: usize,
|
|
layout: &crate::render::DisplayList,
|
|
) -> Option<crate::render::DisplayList> {
|
|
if index < self.first_page {
|
|
return None;
|
|
}
|
|
layout.relocate_sources(|span| self.map.relocate_span(span))
|
|
}
|
|
}
|
|
|
|
/// One changed physical child whose scanner has already left the input stack.
|
|
pub struct ClosedSourceChange<'a> {
|
|
pub source_id: usize,
|
|
pub name: &'a str,
|
|
pub previous_bytes: usize,
|
|
pub current_bytes: usize,
|
|
}
|
|
|
|
impl EntryCheckpoint {
|
|
/// Identify a closed byte-framed child before the host verifies its path,
|
|
/// distinct file roles, read counts, and absence of later observations.
|
|
pub fn closed_source_change<'a>(
|
|
&'a self,
|
|
prior: &Self,
|
|
completed: &Execution,
|
|
) -> Option<ClosedSourceChange<'a>> {
|
|
let current = &self.executor;
|
|
let old = &prior.executor;
|
|
if self.entry != self.active_source
|
|
|| prior.entry != prior.active_source
|
|
|| self.entry != prior.entry
|
|
|| current.sources.len() != old.sources.len()
|
|
|| !matches!(current.state.input_profile(), InputProfile::TeX8Bit | InputProfile::UnicodeScalar)
|
|
|| current.state.input_profile() != old.state.input_profile()
|
|
{
|
|
return None;
|
|
}
|
|
let mut differences = current.sources.iter().zip(&old.sources).enumerate()
|
|
.filter(|(_, (new, old))| new != old);
|
|
let (source_id, (new, old_source)) = differences.next()?;
|
|
if differences.next().is_some()
|
|
|| source_id == self.entry
|
|
|| new.name != old_source.name
|
|
|| completed.sources.get(source_id)? != old_source
|
|
{
|
|
return None;
|
|
}
|
|
let uniquely_named = |sources: &[Arc<SourceFile>]| {
|
|
sources.iter().filter(|source| source.name == new.name).take(2).count() == 1
|
|
};
|
|
let is_closed = |executor: &Executor| {
|
|
!executor.stream_sources.contains(&source_id)
|
|
&& !executor.generated_inputs.contains_key(&source_id)
|
|
&& !executor.inputs.iter().any(|frame| matches!(
|
|
frame, InputFrame::Source { source, .. } if *source == source_id
|
|
))
|
|
};
|
|
if !uniquely_named(&old.sources)
|
|
|| !uniquely_named(¤t.sources)
|
|
|| !uniquely_named(&completed.sources)
|
|
|| !is_closed(old)
|
|
|| !is_closed(current)
|
|
|| completed.stream_sources.contains(&source_id)
|
|
|| completed.generated_inputs.contains_key(&source_id)
|
|
{
|
|
return None;
|
|
}
|
|
Some(ClosedSourceChange {
|
|
source_id,
|
|
name: &new.name,
|
|
previous_bytes: old_source.data.len(),
|
|
current_bytes: new.data.len(),
|
|
})
|
|
}
|
|
|
|
/// Construct an execution with the current prefix and a previously
|
|
/// completed suffix. The host must still validate and replay that suffix.
|
|
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
|
|
self.splice_settled_suffix_with_layout(prior, completed)
|
|
.map(|(execution, _)| execution)
|
|
}
|
|
|
|
/// Also return the coordinate mapping for copied shipouts whose cached
|
|
/// local layouts belong to the supplied completed execution.
|
|
pub fn splice_settled_suffix_with_layout(
|
|
&self,
|
|
prior: &Self,
|
|
completed: &Execution,
|
|
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
|
|
self.splice_settled_suffix_observed(prior, completed, None)
|
|
}
|
|
|
|
/// Splice a completed suffix and optionally record its kernel checks.
|
|
pub fn splice_settled_suffix_observed(
|
|
&self,
|
|
prior: &Self,
|
|
completed: &Execution,
|
|
timings: Option<&mut SuffixKernelTimings>,
|
|
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
|
|
self.splice_settled_sources(prior, completed, self.entry, 1, timings)
|
|
}
|
|
|
|
/// Reuse a suffix after the caller has verified the actual host reads
|
|
/// of the changed child, including probes that only consumed its size.
|
|
/// The caller must reject later uses of this file and replay all effects.
|
|
pub fn splice_settled_closed_source_suffix_observed(
|
|
&self,
|
|
prior: &Self,
|
|
completed: &Execution,
|
|
source_id: usize,
|
|
prefix_resource_reads: usize,
|
|
timings: Option<&mut SuffixKernelTimings>,
|
|
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
|
|
if prefix_resource_reads == 0
|
|
|| self.closed_source_change(prior, completed)?.source_id != source_id
|
|
{
|
|
return None;
|
|
}
|
|
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, timings)
|
|
}
|
|
|
|
fn splice_settled_sources(
|
|
&self,
|
|
prior: &Self,
|
|
completed: &Execution,
|
|
source_id: usize,
|
|
prefix_resource_reads: usize,
|
|
mut timings: Option<&mut SuffixKernelTimings>,
|
|
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
|
|
if self.entry != self.active_source
|
|
|| prior.entry != prior.active_source
|
|
|| self.entry != prior.entry
|
|
|| self.initial_depth != prior.initial_depth
|
|
|| self.incoming_state != prior.incoming_state
|
|
|| self.pages_processed != prior.pages_processed
|
|
|| completed.incoming_state != prior.incoming_state
|
|
|| completed.reads_event_history
|
|
|| completed.format_dumped
|
|
|| completed.steps <= prior.completed_steps()
|
|
{
|
|
return None;
|
|
}
|
|
let current = &self.executor;
|
|
let old = &prior.executor;
|
|
if current.sources.len() != old.sources.len()
|
|
|| current
|
|
.sources
|
|
.iter()
|
|
.zip(&old.sources)
|
|
.enumerate()
|
|
.any(|(id, (new, old))| {
|
|
if id == source_id {
|
|
new.name != old.name
|
|
} else {
|
|
new != old
|
|
}
|
|
})
|
|
|| completed.sources.get(self.entry)? != &old.sources[self.entry]
|
|
{
|
|
return None;
|
|
}
|
|
let box_offset = BoxNodeOffset::new(old.box_nodes_created, current.box_nodes_created);
|
|
let box_nodes_created = match completed.box_nodes_created {
|
|
Some(donor) => Some(box_offset.apply(donor)?),
|
|
None if box_offset.is_identity() => None,
|
|
None => return None,
|
|
};
|
|
// A capacity recount can lower the running charge and observe
|
|
// the retained event history. Bound all future visits on both
|
|
// runs before translating any unequal charge or history.
|
|
let no_suffix_recount = completed.box_nodes_created.is_some_and(|nodes| {
|
|
nodes != usize::MAX
|
|
&& nodes.checked_sub(old.box_nodes_created)
|
|
.and_then(|remaining| current.material_charge.max(old.material_charge)
|
|
.checked_add(remaining))
|
|
.is_some_and(|charge| charge <= current.limits.tokens)
|
|
});
|
|
if current.material_charge != old.material_charge && !no_suffix_recount {
|
|
return None;
|
|
}
|
|
let previous_bytes = &old.sources[source_id].data;
|
|
let current_bytes = ¤t.sources[source_id].data;
|
|
let resize = (previous_bytes.len() != current_bytes.len()).then_some(SuffixSourceResize {
|
|
sizes: (previous_bytes.len(), current_bytes.len()),
|
|
active_at_anchor: source_id == self.entry,
|
|
prefix_resource_reads,
|
|
});
|
|
let relocation = match resize {
|
|
Some(resize) if resize.active_at_anchor => {
|
|
let map = self.source_mouth(self.entry)
|
|
.relocation_from(prior.source_mouth(prior.entry))?;
|
|
if map.relocate_offset(prior.frontier) != Some(self.frontier) {
|
|
return None;
|
|
}
|
|
Some(map)
|
|
}
|
|
Some(_) if self.frontier == prior.frontier => {
|
|
Some(SourceRelocation::new(source_id, previous_bytes, current_bytes)?)
|
|
}
|
|
None if self.frontier == prior.frontier => None,
|
|
_ => return None,
|
|
};
|
|
let observes_changed_line = completed.line_observations.as_ref().is_none_or(|observations| {
|
|
observations.get(&source_id) != old.line_observations.get(&source_id)
|
|
});
|
|
if observes_changed_line
|
|
&& relocation.as_ref().map_or_else(
|
|
|| !SourceRelocation::same_line_breaks(previous_bytes, current_bytes),
|
|
|map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1,
|
|
)
|
|
{
|
|
// The old line number can be embedded in outputs. Equal byte
|
|
// offsets can also mean different lines if a newline moved.
|
|
// In wide encodings even a same-line edit can change the number
|
|
// of raw CR/LF bytes counted by byte-based diagnostic fallbacks.
|
|
return None;
|
|
}
|
|
let line_observations = match &completed.line_observations {
|
|
Some(later) => Some(splice_line_observations(
|
|
¤t.line_observations, &old.line_observations, later,
|
|
)?),
|
|
None => None,
|
|
};
|
|
// 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);
|
|
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);
|
|
let steps = offset.apply(completed.steps)?;
|
|
// Kernel work only advances the step counter. A successful suffix
|
|
// remains within budget if its translated final count does.
|
|
if steps > current.limits.steps {
|
|
return None;
|
|
}
|
|
let mut sources = completed.sources.clone();
|
|
sources[source_id] = current.sources[source_id].clone();
|
|
let tail = completed.events.get(old.events.len()..)?;
|
|
let retained_history = if completed.accounts_event_history {
|
|
measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
|
|
if current.events.len() == old.events.len()
|
|
&& current.equivalent_accounting_history_with_source_resize(old, resize)
|
|
{
|
|
return Some(None);
|
|
}
|
|
// Shipout reports also contribute to later diagnostic
|
|
// counters. Only translate the final report here.
|
|
let has_final_report = matches!(tail.last(),
|
|
Some(Event::Statistics(report)) if matches!(report.phase, StatisticsPhase::End { .. })
|
|
);
|
|
if !no_suffix_recount || !has_final_report
|
|
|| tail[..tail.len() - 1].iter().any(|event| matches!(event, Event::Statistics(_)))
|
|
{
|
|
return None;
|
|
}
|
|
let history = current.retained_history_offset(old, resize)?;
|
|
Some((!history.is_identity()).then_some(history))
|
|
})?
|
|
} else {
|
|
None
|
|
};
|
|
let statistics = SuffixStatistics { steps: offset, boxes: box_offset, retained_history };
|
|
// The joined events are published results. Resumption always starts
|
|
// from a live checkpoint, whose original shared allocations stay intact.
|
|
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || {
|
|
let mut events = Vec::with_capacity(current.events.len().checked_add(tail.len())?);
|
|
events.extend(current.events.iter().cloned());
|
|
let (reads, dependency_evidence) = splice_dependencies(current, old, completed)?;
|
|
let mut execution = Execution {
|
|
format_dumped: completed.format_dumped,
|
|
format_pdf_images: completed.format_pdf_images.clone(),
|
|
job_name: completed.job_name.clone(),
|
|
interaction_mode: completed.interaction_mode,
|
|
native_page: completed.native_page.clone(),
|
|
split_discards: completed.split_discards.clone(),
|
|
after_assignment: completed.after_assignment.clone(),
|
|
events,
|
|
state: completed.state.clone(),
|
|
io: completed.io.clone(),
|
|
input_position: completed.input_position,
|
|
paragraph_mode: completed.paragraph_mode,
|
|
sources,
|
|
stream_sources: completed.stream_sources.clone(),
|
|
generated_inputs: completed.generated_inputs.clone(),
|
|
reads,
|
|
dependency_evidence,
|
|
line_observations,
|
|
incoming_state: completed.incoming_state,
|
|
outgoing_state: completed.outgoing_state,
|
|
steps,
|
|
box_nodes_created,
|
|
reads_event_history: false,
|
|
accounts_event_history: completed.accounts_event_history,
|
|
};
|
|
if let Some((moved, resize)) = moved.as_mut().zip(resize) {
|
|
relocate::append_suffix(
|
|
&mut execution, tail, &statistics, moved, resize, old.sources.len(),
|
|
)?;
|
|
if execution.state != completed.state {
|
|
execution.outgoing_state = execution.state
|
|
.fingerprint_with_prior(Some(&completed.state));
|
|
}
|
|
} else if statistics.is_identity() {
|
|
execution.events.extend_from_slice(tail);
|
|
} else {
|
|
for event in tail {
|
|
execution.events.push(match event {
|
|
Event::Statistics(report) => Event::Statistics(Box::new(
|
|
statistics.translate(report, None)?,
|
|
)),
|
|
_ => event.clone(),
|
|
});
|
|
}
|
|
}
|
|
Some(execution)
|
|
})?;
|
|
let layout = relocation.map(|map| RelocatedShipoutSuffix {
|
|
// The executor records one top-level shipout event whenever
|
|
// this count advances. Form canvases do not enter this sequence.
|
|
first_page: old.shipped_pages,
|
|
map,
|
|
});
|
|
Some((execution, layout))
|
|
}
|
|
/// Carry later checkpoints from the suffix accepted by
|
|
/// splice_settled_suffix into this revision. The host must still replay
|
|
/// each prefix and verify the resulting I/O boundary before keeping it.
|
|
pub fn prepare_suffix_rebase<'a>(
|
|
&'a self,
|
|
prior: &'a Self,
|
|
completed: &Execution,
|
|
) -> Option<impl FnMut(&Self) -> Option<Self> + 'a> {
|
|
// A carried executor still contains scanner positions from the old source.
|
|
if self.executor.sources[self.entry].data.len()
|
|
!= prior.executor.sources[prior.entry].data.len()
|
|
{
|
|
return None;
|
|
}
|
|
let current = &self.executor;
|
|
let old = &prior.executor;
|
|
// Rebased checkpoints retain the donor's closed-source bytes.
|
|
if current.sources.len() != old.sources.len()
|
|
|| current.sources.iter().zip(&old.sources).enumerate()
|
|
.any(|(id, (new, old))| id != self.entry && new != old)
|
|
{
|
|
return None;
|
|
}
|
|
// Later snapshots retain the donor's meaning cache and read history.
|
|
// Keeping them requires the same keys, even when the finished splice
|
|
// could publish a different set using exact suffix evidence.
|
|
if current.events.len() != old.events.len()
|
|
|| current.reads != old.reads
|
|
|| current.meaning_reads.len() != old.meaning_reads.len()
|
|
|| !old.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|
|
|| current.box_nodes_created != old.box_nodes_created
|
|
|| current.material_charge != old.material_charge
|
|
{
|
|
return None;
|
|
}
|
|
// A carried executor needs the exact alias history before taking
|
|
// donor allocations from equal-valued events. Translating a final
|
|
// report proves only the published counts.
|
|
if completed.reads_event_history || !current.equivalent_accounting_history(old) {
|
|
return None;
|
|
}
|
|
// Keep the old allocations of unchanged material, including inside
|
|
// edited events, since later snapshots can still refer to them.
|
|
let mut prefix = prior.executor.events.clone();
|
|
let mut current = self.executor.events.iter();
|
|
let mut material = MaterialReuse::default();
|
|
for chunk in &mut prefix.prefix {
|
|
let changes: Vec<_> = chunk.iter().zip(current.by_ref()).enumerate()
|
|
.filter(|(_, (old, new))| !std::ptr::eq(*old, *new) && old != new)
|
|
.map(|(index, (old, new))| {
|
|
let mut new = new.clone();
|
|
material.event(old, &mut new);
|
|
(index, new)
|
|
})
|
|
.collect();
|
|
if !changes.is_empty() {
|
|
let events = Arc::make_mut(chunk);
|
|
for (index, event) in changes {
|
|
events[index] = event;
|
|
}
|
|
}
|
|
}
|
|
let mut adjusted_chunks = BTreeMap::new();
|
|
Some(move |later: &Self| self.rebase_verified_suffix(prior, later, &prefix, &mut adjusted_chunks))
|
|
}
|
|
|
|
fn rebase_verified_suffix(
|
|
&self,
|
|
prior: &Self,
|
|
later: &Self,
|
|
prefix: &ExecutionEvents,
|
|
adjusted_chunks: &mut BTreeMap<usize, Arc<Vec<Event>>>,
|
|
) -> Option<Self> {
|
|
let old = &prior.executor;
|
|
let next = &later.executor;
|
|
let current = &self.executor;
|
|
let offset = StepOffset::new(old.steps, current.steps);
|
|
let steps = offset.apply(next.steps)?;
|
|
if later.entry != self.entry
|
|
|| later.active_source != self.entry
|
|
|| later.frontier < self.frontier
|
|
|| steps <= current.steps
|
|
|| steps > current.limits.steps
|
|
// An active builder can hold a budget established before
|
|
// capture. Its limit cannot be translated by changing steps.
|
|
|| (!offset.is_identity() && !is_idle_continuation(next))
|
|
|| later.incoming_state != self.incoming_state
|
|
|| next.reads_event_history
|
|
|| !Arc::ptr_eq(&next.sources[later.entry], &old.sources[prior.entry])
|
|
|| old.events.prefix.len() > next.events.prefix.len()
|
|
|| !old.events.prefix.iter().zip(&next.events.prefix).all(|(a, b)| Arc::ptr_eq(a, b))
|
|
{
|
|
return None;
|
|
}
|
|
|
|
let mut executor = next.clone();
|
|
// These carried snapshots still have the right cumulative keys.
|
|
// The donor's private timestamps alone cannot date the new prefix.
|
|
executor.reads.disable_epochs();
|
|
executor.line_observations = splice_line_observations(
|
|
¤t.line_observations, &old.line_observations, &next.line_observations,
|
|
)?;
|
|
let mut events = prefix.clone();
|
|
// Checkpoint capture seals the event log. Share the old suffix
|
|
// chunks so all carried checkpoints keep the same allocation graph.
|
|
for chunk in &next.events.prefix[old.events.prefix.len()..] {
|
|
if offset.is_identity() || !chunk.iter().any(|event| matches!(event, Event::Statistics(_))) {
|
|
events.prefix.push(chunk.clone());
|
|
continue;
|
|
}
|
|
let address = Arc::as_ptr(chunk) as usize;
|
|
let adjusted = match adjusted_chunks.entry(address) {
|
|
std::collections::btree_map::Entry::Occupied(entry) => entry.get().clone(),
|
|
std::collections::btree_map::Entry::Vacant(entry) => {
|
|
let events = chunk.iter().map(|event| offset_event_steps(event, offset))
|
|
.collect::<Option<Vec<_>>>()?;
|
|
entry.insert(Arc::new(events)).clone()
|
|
}
|
|
};
|
|
events.prefix.push(adjusted);
|
|
}
|
|
events.prefix_len += next.events.prefix_len - old.events.prefix_len;
|
|
executor.events = events;
|
|
executor.steps = steps;
|
|
executor.sources[self.entry] = current.sources[self.entry].clone();
|
|
let InputFrame::Source { source, mouth, .. } = executor.inputs.first_mut()? else {
|
|
return None;
|
|
};
|
|
if *source != self.entry || !mouth.rebind_after_convergence(self.source_mouth(self.entry)) {
|
|
return None;
|
|
}
|
|
// A later edit can turn on tracing or force a capacity recount.
|
|
// Keep a live checkpoint only if the merged history preserves
|
|
// the sharing relationships needed by either accounting path.
|
|
if !executor.equivalent_accounting_history(next) {
|
|
return None;
|
|
}
|
|
Some(Self {
|
|
executor,
|
|
entry: later.entry,
|
|
active_source: later.active_source,
|
|
initial_depth: later.initial_depth,
|
|
incoming_state: later.incoming_state,
|
|
frontier: later.frontier,
|
|
pages_processed: later.pages_processed,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn splice_dependencies(
|
|
current: &Executor,
|
|
prior: &Executor,
|
|
completed: &Execution,
|
|
) -> Option<(BTreeSet<Dependency>, DependencyEvidence)> {
|
|
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<Dependency, u32> = 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)));
|
|
}
|
|
|
|
// Restored records without epoch evidence can only preserve every
|
|
// previous prefix key. Removing one could erase a repeated suffix read.
|
|
if !prior.reads.is_subset(¤t.reads)
|
|
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|
|
{
|
|
return None;
|
|
}
|
|
let mut reads = completed.reads.clone();
|
|
current.reads.extend_ordered_delta(&prior.reads, &mut reads);
|
|
if current.meaning_reads.len() != prior.meaning_reads.len() {
|
|
reads.extend(current.meaning_reads.keys()
|
|
.filter(|name| !prior.meaning_reads.contains_key(*name))
|
|
.map(|name| Dependency::Meaning(name.as_ref().clone())));
|
|
}
|
|
Some((reads, DependencyEvidence::default()))
|
|
}
|
|
|
|
fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
|
|
let started = elapsed.is_some().then(Instant::now);
|
|
let value = action();
|
|
if let (Some(elapsed), Some(started)) = (elapsed, started) {
|
|
*elapsed += started.elapsed();
|
|
}
|
|
value
|
|
}
|
|
|
|
// Counts describe reads observed on a particular execution history.
|
|
fn splice_line_observations(
|
|
current: &BTreeMap<usize, usize>,
|
|
prior: &BTreeMap<usize, usize>,
|
|
later: &BTreeMap<usize, usize>,
|
|
) -> Option<BTreeMap<usize, usize>> {
|
|
if prior.keys().any(|source| !later.contains_key(source)) {
|
|
return None;
|
|
}
|
|
let mut combined = current.clone();
|
|
for (&source, &count) in later {
|
|
let suffix = count.checked_sub(prior.get(&source).copied().unwrap_or_default())?;
|
|
if suffix != 0 {
|
|
let total = combined.entry(source).or_default();
|
|
*total = total.checked_add(suffix)?;
|
|
}
|
|
}
|
|
Some(combined)
|
|
}
|
|
|
|
struct SuffixStatistics {
|
|
steps: StepOffset,
|
|
boxes: BoxNodeOffset,
|
|
retained_history: Option<RetainedHistoryOffset>,
|
|
}
|
|
|
|
impl SuffixStatistics {
|
|
fn is_identity(&self) -> bool {
|
|
self.steps.is_identity() && self.boxes.is_identity() && self.retained_history.is_none()
|
|
}
|
|
|
|
fn translate(
|
|
&self,
|
|
report: &StatisticsReport,
|
|
resize: Option<SuffixSourceResize>,
|
|
) -> Option<StatisticsReport> {
|
|
report.with_source_resize(
|
|
self.steps, self.boxes, resize, self.retained_history.as_ref(),
|
|
)
|
|
}
|
|
}
|
|
|
|
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
|
|
match event {
|
|
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))),
|
|
_ => Some(event.clone()),
|
|
}
|
|
}
|
|
|
|
fn is_idle_continuation(e: &Executor) -> bool {
|
|
e.output_frame.is_none()
|
|
&& e.paragraph.is_none()
|
|
&& e.box_frames.is_empty()
|
|
&& e.math.is_empty()
|
|
&& e.display.is_none()
|
|
&& e.alignments.is_empty()
|
|
&& e.pdf_link_stack.is_empty()
|
|
&& e.pdf_active_thread.is_none()
|
|
&& e.pdf_space_probe.is_none()
|
|
&& e.pdf_images.is_empty()
|
|
&& !e.reads_event_history
|
|
}
|
|
|
|
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.
|
|
macro_rules! same_values {
|
|
([$($value:ident),+ $(,)?], [$($planned:ident),+ $(,)?], [$($runtime:ident),+ $(,)?]) => {{
|
|
let Executor {
|
|
$($value,)+
|
|
$($planned: _,)+
|
|
$($runtime: _,)+
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
pdf_last_match: _,
|
|
} = current;
|
|
true $(&& *$value == prior.$value)+
|
|
}};
|
|
}
|
|
if !is_idle_continuation(current) || !is_idle_continuation(prior) {
|
|
return false;
|
|
}
|
|
if !same_values!(
|
|
[
|
|
limits,
|
|
interaction_mode,
|
|
stream_sources,
|
|
reads_tracing_macros,
|
|
in_csname,
|
|
command_trace_mode,
|
|
ligature_carry,
|
|
expression_depth,
|
|
scanner_depth,
|
|
scanner_status,
|
|
expansion_depth,
|
|
io,
|
|
pdf_colors,
|
|
xdv_colors,
|
|
pdf_running_links,
|
|
pdf_interword_spaces,
|
|
pdf_space_font,
|
|
pdf_loaded_space_font,
|
|
pdf_virtual_fonts,
|
|
pdf_outline_payload,
|
|
restored_pdf_image_count,
|
|
format_image_warnings,
|
|
pdf_force_pagebox_warned,
|
|
mark_cells_created,
|
|
diagnostic_bytes,
|
|
after_group_tokens,
|
|
math_tokens_processed,
|
|
shipped_pages,
|
|
job_ended,
|
|
fresh_job,
|
|
job_name,
|
|
format_loaded,
|
|
format_dumped,
|
|
writing,
|
|
stack_peaks,
|
|
alignment_balance,
|
|
accounts_event_history,
|
|
],
|
|
[
|
|
state,
|
|
generated_inputs,
|
|
conditionals,
|
|
current,
|
|
input_position,
|
|
line_observations,
|
|
pdf_catalog_tokens,
|
|
pdf_outlines,
|
|
pdf_info_tokens,
|
|
vertical,
|
|
after_assignment,
|
|
native_page,
|
|
split_discards,
|
|
pending_shipouts,
|
|
inputs,
|
|
sources,
|
|
steps,
|
|
box_nodes_created,
|
|
material_charge,
|
|
reads,
|
|
meaning_reads,
|
|
events,
|
|
reads_event_history,
|
|
xdv_annotations,
|
|
xdv_text,
|
|
pdf_navigation_geometry,
|
|
pdf_link_stack,
|
|
pdf_active_thread,
|
|
pdf_space_probe,
|
|
pdf_images,
|
|
paragraph,
|
|
box_frames,
|
|
math,
|
|
display,
|
|
output_frame,
|
|
alignments,
|
|
],
|
|
[cancellation, line_break_cache]
|
|
) {
|
|
return false;
|
|
}
|
|
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
|
if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() {
|
|
return false;
|
|
}
|
|
if current.inputs.len() != prior.inputs.len()
|
|
// Statistics membership also constrains source rebinding.
|
|
|| current.reads.observed_statistics() != prior.reads.observed_statistics()
|
|
{
|
|
return false;
|
|
}
|
|
if !current.xdv_annotations.same_idle_state(&prior.xdv_annotations)
|
|
|| !current.xdv_text.same_state(&prior.xdv_text)
|
|
|| !current.pdf_navigation_geometry.same_state(&prior.pdf_navigation_geometry)
|
|
{
|
|
return false;
|
|
}
|
|
if let Some(relocation) = relocation {
|
|
return relocate::same_kernel_provenance(current, prior, relocation, timings).unwrap_or(false);
|
|
}
|
|
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
|
|
&& current.input_position == prior.input_position
|
|
&& current.pdf_catalog_tokens == prior.pdf_catalog_tokens
|
|
&& current.pdf_outlines == prior.pdf_outlines
|
|
&& current.pdf_info_tokens == prior.pdf_info_tokens
|
|
&& current.vertical == prior.vertical
|
|
&& current.after_assignment == prior.after_assignment
|
|
&& current.native_page == prior.native_page
|
|
&& current.split_discards == prior.split_discards
|
|
&& current.pending_shipouts == prior.pending_shipouts
|
|
&& current
|
|
.inputs
|
|
.iter()
|
|
.zip(&prior.inputs)
|
|
.all(|(a, b)| a.same_at_shipout(b, None))
|
|
}
|