Prove suffix reuse across unequal retained histories

This commit is contained in:
gloamxun committed 2026-12-02 01:06:03 +08:00
1 parent f78aff25c5
commit 1ff049737f
9 files changed
+781 -153

No files matched your search

@@ -1,6 +1,7 @@
use super::super::{
dependency_reads::DependencyEvidence,
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::BoxNodeOffset,
statistics::{BoxNodeOffset, RetainedHistoryOffset},
};
use super::*;
use std::time::{Duration, Instant};
@@ -185,19 +186,18 @@ impl EntryCheckpoint {
None if box_offset.is_identity() => None,
None => return None,
};
if current.material_charge != old.material_charge {
// A capacity recount can lower the running charge and change
// which storage TeX counts. Bound every future charge on both
// histories so neither can enter that path.
let donor = completed.box_nodes_created?;
if donor == usize::MAX {
return None;
}
let remaining = donor.checked_sub(old.box_nodes_created)?;
let largest = current.material_charge.max(old.material_charge);
if largest.checked_add(remaining)? > current.limits.tokens {
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[self.entry].data;
let current_bytes = &current.sources[self.entry].data;
@@ -254,28 +254,36 @@ impl EntryCheckpoint {
let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone();
let tail = completed.events.get(old.events.len()..)?;
if completed.accounts_event_history
&& !measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
})
{
return None;
}
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_entry_sizes(old, entry_sizes)
{
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, entry_sizes)?;
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(completed.events.len());
let mut events = Vec::with_capacity(current.events.len().checked_add(tail.len())?);
events.extend(current.events.iter().cloned());
let mut reads = completed.reads.clone();
current.reads.extend_ordered_delta(&old.reads, &mut reads);
if current.meaning_reads.len() != old.meaning_reads.len() {
reads.extend(
current.meaning_reads.keys()
.filter(|name| !old.meaning_reads.contains_key(*name))
.cloned()
.map(Dependency::Meaning),
);
}
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(),
@@ -293,6 +301,7 @@ impl EntryCheckpoint {
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,
@@ -303,18 +312,18 @@ impl EntryCheckpoint {
};
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
relocate::append_suffix(
&mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(),
&mut execution, tail, &statistics, moved, sizes, old.sources.len(),
)?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
}
} else if offset.is_identity() && box_offset.is_identity() {
} 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(
report.with_execution_offsets(offset, box_offset)?,
statistics.translate(report, None)?,
)),
_ => event.clone(),
});
@@ -347,20 +356,21 @@ impl EntryCheckpoint {
let current = &self.executor;
let old = &prior.executor;
// Later snapshots retain the donor's meaning cache and read history.
// A successful splice proved key inclusion, so equal lengths prove
// that no new meaning lookup would be lost by carrying the snapshot.
if current.reads != old.reads
// 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 restored checkpoint may later be asked to account for its
// history, even if the job that furnished the suffix did not.
if !completed.accounts_event_history
&& !self.executor.equivalent_accounting_history(&prior.executor)
{
// 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
@@ -418,6 +428,9 @@ impl EntryCheckpoint {
}
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(
&current.line_observations, &old.line_observations, &next.line_observations,
)?;
@@ -468,6 +481,49 @@ impl EntryCheckpoint {
}
}
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(&current.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))
.cloned()
.map(Dependency::Meaning));
}
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();
@@ -497,6 +553,28 @@ fn splice_line_observations(
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,
entry_sizes: Option<(usize, usize)>,
) -> Option<StatisticsReport> {
report.with_suffix_adjustments(
self.steps, self.boxes, entry_sizes, 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)?))),
@@ -626,13 +704,9 @@ fn same_kernel_continuation(
if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() {
return false;
}
if current.events.len() != prior.events.len()
|| current.inputs.len() != prior.inputs.len()
if current.inputs.len() != prior.inputs.len()
// Statistics membership also constrains source rebinding.
|| current.reads.observed_statistics() != prior.reads.observed_statistics()
|| !prior.reads.is_subset(&current.reads)
|| prior.meaning_reads.len() > current.meaning_reads.len()
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
{
return false;
}