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;
}
@@ -1,5 +1,5 @@
use super::*;
use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset};
use crate::execution::source_relocation_events::EventRelocation;
pub(super) fn same_kernel_provenance(
current: &Executor,
@@ -106,8 +106,7 @@ pub(super) fn same_kernel_provenance(
pub(super) fn append_suffix(
execution: &mut Execution,
tail: &[Event],
offset: StepOffset,
boxes: BoxNodeOffset,
statistics: &SuffixStatistics,
relocation: &mut EventRelocation<'_>,
(previous_bytes, current_bytes): (usize, usize),
source_count: usize,
@@ -123,9 +122,7 @@ pub(super) fn append_suffix(
return None;
}
}
let mut report = report
.with_execution_offsets(offset, boxes)?
.with_suffix_entry_resize(previous_bytes, current_bytes)?;
let mut report = statistics.translate(report, Some((previous_bytes, current_bytes)))?;
report.span = map.relocate_span(report.span)?;
execution.events.push(Event::Statistics(Box::new(report)));
} else {
@@ -1,6 +1,7 @@
use super::super::statistics::{
Collector,
Ownership::{Active, Retained},
RetainedHistoryOffset,
};
use super::*;
impl Executor {
@@ -239,6 +240,31 @@ impl Executor {
old: &Self,
entry_sizes: Option<(usize, usize)>,
) -> bool {
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
self.collect_compared_accounting(old, entry_sizes, collector).is_some_and(
|(live, old_live, history, old_history)| {
live.has_equivalent_history(&old_live, &history, &old_history)
},
)
})
}
pub(super) fn retained_history_offset(
&self,
old: &Self,
entry_sizes: Option<(usize, usize)>,
) -> Option<RetainedHistoryOffset> {
let (live, old_live, history, old_history) =
self.collect_compared_accounting(old, entry_sizes, Collector::default)?;
live.retained_history_offset(&old_live, &history, &old_history)
}
fn collect_compared_accounting(
&self,
old: &Self,
entry_sizes: Option<(usize, usize)>,
collector: fn() -> Collector,
) -> Option<(Collector, Collector, Collector, Collector)> {
// These containers may reintroduce previously retained allocations
// that are outside the accounting walk at this boundary.
let fully_visited = |engine: &Self| {
@@ -246,26 +272,21 @@ impl Executor {
&& engine.native_page.as_ref().is_none_or(|page| page.insertions.held.is_empty())
};
if !fully_visited(self) || !fully_visited(old) {
return false;
return None;
}
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector());
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
// The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
if let Some((previous, current)) = entry_sizes {
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
let Some(source) = restore(live.usage.source_payload_bytes) else { return false; };
let Some(mouth) = restore(live.usage.mouth_payload_bytes) else { return false; };
live.usage.source_payload_bytes = source;
live.usage.mouth_payload_bytes = mouth;
}
live.has_equivalent_history(&old_live, &history, &old_history)
})
let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector());
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
// The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
if let Some((previous, current)) = entry_sizes {
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?;
live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?;
}
Some((live, old_live, history, old_history))
}
pub(super) fn statistics_before_shipout(
@@ -341,6 +362,57 @@ impl Executor {
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::statistics::BoxNodeOffset;
#[test]
fn equal_mark_events_with_different_aliases_cannot_carry_a_checkpoint() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let shared: Arc<[Token]> = Arc::from([token.clone()]);
let independent: Arc<[Token]> = Arc::from([token]);
let mark = |tokens| {
Event::VerticalMaterial(vec![NativeVerticalNode::Mark(NativeMark {
class: 0,
tokens,
span: Span::default(),
})])
};
let mut old = Executor::default();
old.state.page_marks.insert(0, PageMarks {
top: Some(shared.clone()),
..PageMarks::default()
});
let mut current = old.clone();
old.events.push(mark(shared.clone()));
old.events.push(mark(shared.clone()));
current.events.push(mark(shared));
current.events.push(mark(independent));
// Rebase's value comparison alone would retain the old Arc sharing.
assert!(current.events.iter().eq(old.events.iter()));
assert!(!current.equivalent_accounting_history(&old));
let offset = current.retained_history_offset(&old, None).unwrap();
assert!(!offset.is_identity());
let end_report = |engine: &Executor| {
StatisticsReport::new(
StatisticsPhase::End {
success: true,
usage: engine.collect_usage(None, None, Collector::default()),
},
WriteDestination::Log,
Span::default(),
)
};
assert_eq!(
end_report(&old).with_suffix_adjustments(
StepOffset::new(0, 0),
BoxNodeOffset::new(0, 0),
None,
Some(&offset),
),
Some(end_report(&current))
);
}
#[test]
fn shared_event_prefix_keeps_tail_deduplication_and_membership() {