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,20 +1,85 @@
//! Deduplicate execution reads before producing the ordered public evidence.
use super::Dependency;
use std::collections::{BTreeSet, HashSet};
use std::{
collections::{BTreeSet, HashMap},
sync::Arc,
};
#[derive(Clone, Default, PartialEq, Eq)]
pub(super) struct DependencyReads {
byte_catcodes: [u64; 4],
other: HashSet<Dependency>,
const INITIAL_EPOCH: u32 = 1;
const DISABLED_EPOCH: u32 = u32::MAX;
/// Last observation of each dependency, in the completed read set's order.
/// The clock records capture boundaries and has no public execution semantics.
#[derive(Clone, Debug, Default)]
pub(super) struct DependencyEvidence(Option<Arc<[u32]>>);
impl DependencyEvidence {
pub(super) fn new(epochs: Vec<u32>) -> Self {
Self(Some(epochs.into()))
}
pub(super) fn epochs(&self) -> Option<&[u32]> {
self.0.as_deref()
}
}
// The same execution can be captured at different boundaries.
impl PartialEq for DependencyEvidence {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for DependencyEvidence {}
#[derive(Clone)]
pub(super) struct DependencyReads {
pub(super) current_epoch: u32,
byte_catcodes: [u32; 256],
other: HashMap<Dependency, u32>,
}
impl Default for DependencyReads {
fn default() -> Self {
Self {
current_epoch: INITIAL_EPOCH,
byte_catcodes: [0; 256],
other: HashMap::new(),
}
}
}
impl PartialEq for DependencyReads {
fn eq(&self, other: &Self) -> bool {
self.other.len() == other.other.len()
&& self
.byte_catcodes
.iter()
.zip(&other.byte_catcodes)
.all(|(&left, &right)| (left == 0) == (right == 0))
&& self.other.keys().all(|key| other.other.contains_key(key))
}
}
impl Eq for DependencyReads {}
impl DependencyReads {
pub(super) fn epoch(&self) -> Option<u32> {
(self.current_epoch != DISABLED_EPOCH).then_some(self.current_epoch)
}
pub(super) fn advance_epoch(&mut self) {
self.current_epoch = self.current_epoch.saturating_add(1);
}
pub(super) fn disable_epochs(&mut self) {
self.current_epoch = DISABLED_EPOCH;
}
pub(super) fn catcode(&mut self, character: char) {
let index = character as usize;
if let Some(bits) = self.byte_catcodes.get_mut(index / 64) {
*bits |= 1 << (index % 64);
if let Some(epoch) = self.byte_catcodes.get_mut(character as usize) {
*epoch = self.current_epoch;
} else {
self.other.insert(Dependency::CatCode(character));
self.other
.insert(Dependency::CatCode(character), self.current_epoch);
}
}
@@ -22,50 +87,93 @@ impl DependencyReads {
if let Dependency::CatCode(character) = dependency {
self.catcode(character);
} else {
self.other.insert(dependency);
self.other.insert(dependency, self.current_epoch);
}
}
pub(super) fn observed_statistics(&self) -> bool {
self.other.contains(&Dependency::ResourceStatistics)
self.other.contains_key(&Dependency::ResourceStatistics)
}
pub(super) fn is_subset(&self, other: &Self) -> bool {
self.byte_catcodes
.iter()
.zip(other.byte_catcodes)
.all(|(&bits, permitted)| bits & !permitted == 0)
&& self.other.is_subset(&other.other)
self.other.len() <= other.other.len()
&& self
.byte_catcodes
.iter()
.zip(&other.byte_catcodes)
.all(|(&seen, &permitted)| seen == 0 || permitted != 0)
&& self.other.keys().all(|key| other.other.contains_key(key))
}
/// Extend a completed execution with observations made only in the new prefix.
/// The caller has already checked that the prefix keeps all old observations.
pub(super) fn extend_ordered_delta(&self, prior: &Self, into: &mut BTreeSet<Dependency>) {
if self.byte_catcodes != prior.byte_catcodes {
into.extend(byte_catcode_dependencies(std::array::from_fn(|index| {
self.byte_catcodes[index] & !prior.byte_catcodes[index]
})));
for (index, (&seen, &old)) in self
.byte_catcodes
.iter()
.zip(&prior.byte_catcodes)
.enumerate()
{
if seen != 0 && old == 0 {
into.insert(Dependency::CatCode(char::from(index as u8)));
}
}
if self.other.len() != prior.other.len() {
into.extend(self.other.difference(&prior.other).cloned());
into.extend(
self.other
.keys()
.filter(|key| !prior.other.contains_key(*key))
.cloned(),
);
}
}
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
pub(super) fn observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
self.other
.iter()
.map(|(key, &epoch)| (key.clone(), epoch))
.chain(byte_catcode_observations(
self.byte_catcodes.iter().copied(),
))
}
pub(super) fn into_evidence(
self,
meanings: impl Iterator<Item = (Dependency, u32)>,
) -> (BTreeSet<Dependency>, DependencyEvidence) {
let has_captures = self.epoch().is_some_and(|epoch| epoch > INITIAL_EPOCH);
let observations = self
.other
.into_iter()
.chain(byte_catcode_dependencies(self.byte_catcodes))
.collect()
.chain(byte_catcode_observations(self.byte_catcodes.into_iter()))
.chain(meanings);
if !has_captures {
return (
observations.map(|(read, _)| read).collect(),
DependencyEvidence::default(),
);
}
let mut ordered: Vec<_> = observations.collect();
ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae)));
// A diagnostic can record a meaning also present in the lookup cache.
ordered.dedup_by(|a, b| a.0 == b.0);
let (reads, epochs) = ordered.into_iter().unzip();
(reads, DependencyEvidence::new(epochs))
}
#[cfg(test)]
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
self.into_evidence(std::iter::empty()).0
}
}
fn byte_catcode_dependencies(bits: [u64; 4]) -> impl Iterator<Item = Dependency> {
(0..=u8::MAX)
.filter(move |&index| {
let index = usize::from(index);
bits[index / 64] & (1 << (index % 64)) != 0
})
.map(|index| Dependency::CatCode(char::from(index)))
fn byte_catcode_observations(
epochs: impl Iterator<Item = u32>,
) -> impl Iterator<Item = (Dependency, u32)> {
epochs.enumerate().filter_map(|(index, epoch)| {
(epoch != 0).then(|| (Dependency::CatCode(char::from(index as u8)), epoch))
})
}
impl Extend<Dependency> for DependencyReads {
@@ -102,6 +210,40 @@ mod tests {
assert_eq!(reads, expected);
}
#[test]
fn evidence_keeps_the_last_read_across_capture_boundaries() {
let mut reads = DependencyReads::default();
reads.extend([
Dependency::CatCode('A'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
Dependency::EscapeChar,
]);
let original = reads.clone();
let boundary_epoch = reads.epoch().unwrap();
reads.advance_epoch();
reads.extend([
Dependency::CatCode('A'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
]);
assert!(reads == original);
let (ordered, evidence) = reads.into_evidence(std::iter::empty());
let repeated: BTreeSet<_> = ordered
.into_iter()
.zip(evidence.epochs().unwrap())
.filter_map(|(read, &epoch)| (epoch > boundary_epoch).then_some(read))
.collect();
assert_eq!(
repeated,
BTreeSet::from([
Dependency::CatCode('A'),
Dependency::CatCode('文'),
Dependency::EndLineChar,
])
);
}
#[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default();
+40 -11
View File
@@ -4,6 +4,7 @@ use std::sync::Arc;
use hashbrown::{HashMap, hash_map::RawEntryMut};
use super::dependency_reads::DependencyEvidence;
use super::job::InputStream;
use super::mouth::Mouth;
use super::state::{GroupKind, Key, Replacement, command_hasher};
@@ -238,9 +239,9 @@ pub struct Executor {
stream_sources: BTreeSet<usize>,
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
reads: DependencyReads,
// Cache the resolved meaning alongside the already required read evidence.
// A shard's revision is only valid on this executor's state history.
meaning_reads: HashMap<CommandName, (u64, Meaning), RandomState>,
// Cache the resolved meaning alongside the last read epoch. A shard's
// revision is only valid on this executor's state history.
meaning_reads: HashMap<CommandName, (u64, Meaning, u32), RandomState>,
reads_tracing_macros: bool,
conditionals: Vec<Conditional>,
in_csname: bool,
@@ -501,6 +502,7 @@ impl EntryCheckpoint {
return Ok(None);
}
let mut executor = self.executor.clone().with_cancellation(cancellation);
executor.reads.advance_epoch();
executor.line_break_cache = line_break_cache;
let previous_len = self.executor.sources[self.entry].data.len();
let current_len = source.data.len();
@@ -821,10 +823,14 @@ impl Executor {
}
}
}
fn take_dependency_reads(&mut self) -> BTreeSet<Dependency> {
let mut reads = std::mem::take(&mut self.reads).into_ordered();
reads.extend(self.meaning_reads.drain().map(|(name, _)| Dependency::Meaning(name)));
reads
fn dependency_observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
self.reads.observations().chain(self.meaning_reads.iter()
.map(|(name, (_, _, epoch))| (Dependency::Meaning(name.clone()), *epoch)))
}
fn take_dependency_reads(&mut self) -> (BTreeSet<Dependency>, DependencyEvidence) {
std::mem::take(&mut self.reads).into_evidence(self.meaning_reads.drain()
.map(|(name, (_, _, epoch))| (Dependency::Meaning(name), epoch)))
}
fn meaning(&mut self, token: &Token) -> Meaning {
@@ -836,9 +842,11 @@ impl Executor {
fn lookup_meaning(&mut self, name: &CommandName) -> Meaning {
let hash = self.meaning_reads.hasher().hash_one(name);
let revision = self.state.command_revision(hash);
let epoch = self.reads.current_epoch;
match self.meaning_reads.raw_entry_mut().from_key_hashed_nocheck(hash, name) {
RawEntryMut::Occupied(mut entry) => {
let (cached_revision, meaning) = entry.get_mut();
let (cached_revision, meaning, last_read) = entry.get_mut();
*last_read = epoch;
if *cached_revision != revision {
*meaning = self.state.meaning_hashed(name, hash);
*cached_revision = revision;
@@ -847,7 +855,7 @@ impl Executor {
}
RawEntryMut::Vacant(entry) => {
let meaning = self.state.meaning_hashed(name, hash);
entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone()));
entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone(), epoch));
meaning
}
}
@@ -3567,7 +3575,7 @@ impl Executor {
for node in nodes {
self.output_node(node, files)?;
}
let reads = self.take_dependency_reads();
let (reads, dependency_evidence) = self.take_dependency_reads();
let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution {
format_dumped: self.format_dumped,
@@ -3591,6 +3599,7 @@ impl Executor {
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads,
dependency_evidence,
line_observations: Some(self.line_observations),
events: self.events.into_vec(),
steps: self.steps,
@@ -4008,6 +4017,9 @@ impl Executor {
}
engine.events.seal_prefix();
let mut executor = engine.clone();
// Any subsequent read belongs to the suffix, even if it
// happens before the next logical TeX execution step.
engine.reads.advance_epoch();
executor.cancellation = None;
executor.line_break_cache = None;
let checkpoint = EntryCheckpoint {
@@ -4028,7 +4040,7 @@ impl Executor {
incoming_state: u64,
previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> {
let reads = self.take_dependency_reads();
let (reads, dependency_evidence) = self.take_dependency_reads();
let result = result.and_then(|()| {
if self.shipped_pages > 0 && !self.format_dumped
&& let Some(objects) = self.state.pdf_objects.as_deref_mut()
@@ -4098,6 +4110,7 @@ impl Executor {
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads,
dependency_evidence,
line_observations: Some(self.line_observations),
incoming_state,
steps: self.steps,
@@ -5275,3 +5288,19 @@ impl Executor {
})
}
}
#[test]
fn cached_meaning_reads_are_observed_again_after_a_capture() {
let name = CommandName::Control("relax".into());
let read = Dependency::Meaning(name.clone());
let mut executor = Executor::new(State::default(), Limits::default());
executor.reads.insert(read.clone());
assert_eq!(executor.lookup_meaning(&name), Meaning::Primitive(Primitive::Relax));
let boundary_epoch = executor.reads.epoch().unwrap();
executor.reads.advance_epoch();
assert_eq!(executor.lookup_meaning(&name), Meaning::Primitive(Primitive::Relax));
let (reads, evidence) = executor.take_dependency_reads();
assert_eq!(reads, BTreeSet::from([read]));
assert_eq!(evidence.epochs().unwrap(), [boundary_epoch + 1]);
}
@@ -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() {
+5 -2
View File
@@ -678,9 +678,12 @@ pub struct Execution {
pub stream_sources: BTreeSet<usize>,
#[serde(default)]
pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
/// Reads made during this execution, not a license to reuse output after
/// state changes. Incremental execution/cache reuse is a later milestone.
/// Dependencies observed over the execution. Suffix reuse additionally
/// validates the state and the reads that follow its checkpoint.
pub reads: BTreeSet<Dependency>,
/// Internal epochs relate active checkpoint cuts to repeated reads.
#[serde(skip)]
dependency_evidence: dependency_reads::DependencyEvidence,
/// Per-source observations distinguish suffix reads from identical prefix reads.
#[serde(default, skip_serializing_if = "Option::is_none")]
line_observations: Option<BTreeMap<usize, usize>>,
@@ -197,6 +197,80 @@ impl BoxNodeOffset {
}
}
#[derive(Clone, Default, PartialEq, Eq)]
struct RetainedHistoryUsage {
material: MaterialUsage,
events: usize,
shipouts: usize,
token_list_cells: usize,
}
impl RetainedHistoryUsage {
fn take_from(usage: &mut ResourceUsage) -> Self {
Self {
material: std::mem::take(&mut usage.retained_material),
events: std::mem::take(&mut usage.retained_events),
shipouts: std::mem::take(&mut usage.retained_shipouts),
token_list_cells: std::mem::take(&mut usage.token_list_cells),
}
}
}
/// The contribution of the replaced prefix to the final resource report.
#[derive(Clone, Default)]
pub(super) struct RetainedHistoryOffset {
previous: RetainedHistoryUsage,
current: RetainedHistoryUsage,
}
impl RetainedHistoryOffset {
pub(super) fn is_identity(&self) -> bool {
self.previous == self.current
}
fn replace_prefix(&self, usage: &mut ResourceUsage) -> Option<()> {
fn replace(total: usize, previous: usize, current: usize) -> Option<usize> {
total.checked_sub(previous)?.checked_add(current)
}
let previous = &self.previous;
let current = &self.current;
let material = &usage.retained_material;
let old = &previous.material;
let new = &current.material;
let material = MaterialUsage {
boxes: replace(material.boxes, old.boxes, new.boxes)?,
horizontal_nodes: replace(material.horizontal_nodes, old.horizontal_nodes, new.horizontal_nodes)?,
vertical_nodes: replace(material.vertical_nodes, old.vertical_nodes, new.vertical_nodes)?,
math_nodes: replace(material.math_nodes, old.math_nodes, new.math_nodes)?,
geometry_items: replace(material.geometry_items, old.geometry_items, new.geometry_items)?,
diagnostic_nodes: replace(material.diagnostic_nodes, old.diagnostic_nodes, new.diagnostic_nodes)?,
ligature_work_items: replace(material.ligature_work_items, old.ligature_work_items, new.ligature_work_items)?,
};
// The final report formats the aggregate with MaterialUsage::records.
[
material.boxes,
material.horizontal_nodes,
material.vertical_nodes,
material.math_nodes,
material.geometry_items,
material.diagnostic_nodes,
material.ligature_work_items,
]
.into_iter()
.try_fold(0usize, usize::checked_add)?;
let events = replace(usage.retained_events, previous.events, current.events)?;
let shipouts = replace(usage.retained_shipouts, previous.shipouts, current.shipouts)?;
let tokens = replace(
usage.token_list_cells, previous.token_list_cells, current.token_list_cells,
)?;
usage.retained_material = material;
usage.retained_events = events;
usage.retained_shipouts = shipouts;
usage.token_list_cells = tokens;
Some(())
}
}
impl StatisticsReport {
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
let text = phase.text();
@@ -227,26 +301,9 @@ impl StatisticsReport {
/// Recompute a report for a verified suffix after the initial entry read
/// changed size. The caller authenticates the entry scanner's lifetime.
pub fn with_suffix_entry_resize(&self, previous: usize, current: usize) -> Option<Self> {
let mut phase = self.phase.clone();
match &mut phase {
StatisticsPhase::Shipout { before, after } => {
for usage in [before, after] {
let active = usage.mouth_payload_bytes == previous;
if !active && usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_entry_payload(previous, current, active)?;
}
}
StatisticsPhase::End { usage, .. } => {
if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_entry_payload(previous, current, false)?;
}
}
let report = Self::new(phase, self.destination, self.span);
report.within_diagnostic_budget().then_some(report)
self.with_suffix_adjustments(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some((previous, current)), None,
)
}
pub fn with_step_offset(&self, offset: StepOffset) -> Option<Self> {
@@ -257,6 +314,16 @@ impl StatisticsReport {
&self,
steps: StepOffset,
boxes: BoxNodeOffset,
) -> Option<Self> {
self.with_suffix_adjustments(steps, boxes, None, None)
}
pub(super) fn with_suffix_adjustments(
&self,
steps: StepOffset,
boxes: BoxNodeOffset,
entry_sizes: Option<(usize, usize)>,
history: Option<&RetainedHistoryOffset>,
) -> Option<Self> {
let translate = |usage: &mut ResourceUsage| {
usage.steps = steps.apply(usage.steps)?;
@@ -266,10 +333,32 @@ impl StatisticsReport {
let mut phase = self.phase.clone();
match &mut phase {
StatisticsPhase::Shipout { before, after } => {
translate(before)?;
translate(after)?;
if history.is_some_and(|offset| !offset.is_identity()) {
return None;
}
for usage in [before, after] {
translate(usage)?;
if let Some((previous, current)) = entry_sizes {
let active = usage.mouth_payload_bytes == previous;
if !active && usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_entry_payload(previous, current, active)?;
}
}
}
StatisticsPhase::End { usage, .. } => {
translate(usage)?;
if let Some((previous, current)) = entry_sizes {
if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_entry_payload(previous, current, false)?;
}
if let Some(offset) = history {
offset.replace_prefix(usage)?;
}
}
StatisticsPhase::End { usage, .. } => translate(usage)?,
}
let report = Self::new(phase, self.destination, self.span);
report.within_diagnostic_budget().then_some(report)
@@ -431,19 +520,47 @@ impl Collector {
}
}
/// Check the live allocation correspondence and each allocation's
/// membership in the retained history. Counting a later event can
/// encounter older storage only through these surviving references.
pub(super) fn has_equivalent_history(
&self,
other: &Self,
history: &Self,
old_history: &Self,
) -> bool {
history.usage == old_history.usage && self.same_live_history(other, history, old_history)
}
/// Compare separately collected live state and retained events. The
/// caller must prove that the suffix cannot recount capacity.
pub(super) fn retained_history_offset(
&self,
other: &Self,
history: &Self,
old_history: &Self,
) -> Option<RetainedHistoryOffset> {
if self.material_only() || other.material_only()
|| history.material_only() || old_history.material_only()
|| !self.same_live_history(other, history, old_history)
{
return None;
}
let mut usage = history.usage.clone();
let mut old_usage = old_history.usage.clone();
let current = RetainedHistoryUsage::take_from(&mut usage);
let previous = RetainedHistoryUsage::take_from(&mut old_usage);
(usage == old_usage).then_some(RetainedHistoryOffset { previous, current })
}
/// Later events can reach old storage only through allocations that
/// survive in live state. Keep both their alias order and history membership.
fn same_live_history(
&self,
other: &Self,
history: &Self,
old_history: &Self,
) -> bool {
let a = &self.aliases.as_ref().expect("live alias traversal").visits;
let b = &other.aliases.as_ref().expect("live alias traversal").visits;
self.usage == other.usage
&& history.usage == old_history.usage
&& a.len() == b.len()
&& a.iter().zip(b).all(|(&(new, ni), &(old, oi))| {
ni == oi
@@ -692,6 +809,108 @@ mod tests {
);
}
#[test]
fn suffix_adjustments_check_only_the_final_diagnostic_budget() {
let report = |usage| {
StatisticsReport::new(
StatisticsPhase::End { success: true, usage },
WriteDestination::Log,
Span::default(),
)
};
let mut usage = ResourceUsage {
steps: 9,
source_payload_bytes: 10,
..ResourceUsage::default()
};
usage.token_limit = report(usage.clone()).text.len();
let original = report(usage.clone());
let steps = StepOffset::new(0, 1);
assert!(original.with_step_offset(steps).is_none());
usage.steps = 10;
usage.source_payload_bytes = 9;
assert_eq!(
original.with_suffix_adjustments(
steps, BoxNodeOffset::new(0, 0), Some((10, 9)), None,
),
Some(report(usage))
);
}
#[test]
fn retained_history_offsets_require_shared_token_membership() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let retained: Arc<[Token]> = Arc::from([token.clone()]);
let old_retained: Arc<[Token]> = Arc::from([token.clone()]);
let extra: Arc<[Token]> = Arc::from([token.clone(), token]);
let mut live = Collector::default().tracking_aliases();
live.shared_tokens(&retained);
let mut old_live = Collector::default().tracking_aliases();
old_live.shared_tokens(&old_retained);
let mut history = Collector::default();
history.shared_tokens(&retained);
history.shared_tokens(&extra);
history.usage.retained_events = 3;
history.usage.retained_material.horizontal_nodes = 5;
let mut old_history = Collector::default();
old_history.shared_tokens(&old_retained);
old_history.usage.retained_events = 2;
old_history.usage.retained_material.horizontal_nodes = 1;
assert!(!live.has_equivalent_history(&old_live, &history, &old_history));
let offset = live.retained_history_offset(&old_live, &history, &old_history).unwrap();
assert!(!offset.is_identity());
assert!(
old_live.retained_history_offset(&old_live, &history, &old_history).is_none()
);
let mut usage = ResourceUsage {
token_list_cells: 8,
retained_events: 4,
retained_material: MaterialUsage { horizontal_nodes: 3, ..MaterialUsage::default() },
token_limit: 4096,
..ResourceUsage::default()
};
let report = StatisticsReport::new(
StatisticsPhase::End { success: true, usage: usage.clone() },
WriteDestination::Log,
Span::default(),
);
usage.token_list_cells = 10;
usage.retained_events = 5;
usage.retained_material.horizontal_nodes = 7;
assert_eq!(
report.with_suffix_adjustments(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), None, Some(&offset),
).unwrap(),
StatisticsReport::new(
StatisticsPhase::End { success: true, usage },
WriteDestination::Log,
Span::default(),
)
);
let overflow = StatisticsReport::new(
StatisticsPhase::End {
success: true,
usage: ResourceUsage {
retained_material: MaterialUsage {
boxes: usize::MAX - 1,
horizontal_nodes: 1,
..MaterialUsage::default()
},
token_limit: 4096,
..old_history.usage
},
},
WriteDestination::Log,
Span::default(),
);
assert!(overflow.with_suffix_adjustments(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), None, Some(&offset),
).is_none());
}
#[test]
fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());