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. //! Deduplicate execution reads before producing the ordered public evidence.
use super::Dependency; use super::Dependency;
use std::collections::{BTreeSet, HashSet}; use std::{
collections::{BTreeSet, HashMap},
sync::Arc,
};
#[derive(Clone, Default, PartialEq, Eq)] const INITIAL_EPOCH: u32 = 1;
pub(super) struct DependencyReads { const DISABLED_EPOCH: u32 = u32::MAX;
byte_catcodes: [u64; 4],
other: HashSet<Dependency>, /// 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 { 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) { pub(super) fn catcode(&mut self, character: char) {
let index = character as usize; if let Some(epoch) = self.byte_catcodes.get_mut(character as usize) {
if let Some(bits) = self.byte_catcodes.get_mut(index / 64) { *epoch = self.current_epoch;
*bits |= 1 << (index % 64);
} else { } 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 { if let Dependency::CatCode(character) = dependency {
self.catcode(character); self.catcode(character);
} else { } else {
self.other.insert(dependency); self.other.insert(dependency, self.current_epoch);
} }
} }
pub(super) fn observed_statistics(&self) -> bool { 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 { pub(super) fn is_subset(&self, other: &Self) -> bool {
self.byte_catcodes self.other.len() <= other.other.len()
.iter() && self
.zip(other.byte_catcodes) .byte_catcodes
.all(|(&bits, permitted)| bits & !permitted == 0) .iter()
&& self.other.is_subset(&other.other) .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. /// Extend a completed execution with observations made only in the new prefix.
/// The caller has already checked that the prefix keeps all old observations. /// 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>) { pub(super) fn extend_ordered_delta(&self, prior: &Self, into: &mut BTreeSet<Dependency>) {
if self.byte_catcodes != prior.byte_catcodes { for (index, (&seen, &old)) in self
into.extend(byte_catcode_dependencies(std::array::from_fn(|index| { .byte_catcodes
self.byte_catcodes[index] & !prior.byte_catcodes[index] .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() { 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 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() .into_iter()
.chain(byte_catcode_dependencies(self.byte_catcodes)) .chain(byte_catcode_observations(self.byte_catcodes.into_iter()))
.collect() .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> { fn byte_catcode_observations(
(0..=u8::MAX) epochs: impl Iterator<Item = u32>,
.filter(move |&index| { ) -> impl Iterator<Item = (Dependency, u32)> {
let index = usize::from(index); epochs.enumerate().filter_map(|(index, epoch)| {
bits[index / 64] & (1 << (index % 64)) != 0 (epoch != 0).then(|| (Dependency::CatCode(char::from(index as u8)), epoch))
}) })
.map(|index| Dependency::CatCode(char::from(index)))
} }
impl Extend<Dependency> for DependencyReads { impl Extend<Dependency> for DependencyReads {
@@ -102,6 +210,40 @@ mod tests {
assert_eq!(reads, expected); 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] #[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() { fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default(); let mut read = DependencyReads::default();
+40 -11
View File
@@ -4,6 +4,7 @@ use std::sync::Arc;
use hashbrown::{HashMap, hash_map::RawEntryMut}; use hashbrown::{HashMap, hash_map::RawEntryMut};
use super::dependency_reads::DependencyEvidence;
use super::job::InputStream; use super::job::InputStream;
use super::mouth::Mouth; use super::mouth::Mouth;
use super::state::{GroupKind, Key, Replacement, command_hasher}; use super::state::{GroupKind, Key, Replacement, command_hasher};
@@ -238,9 +239,9 @@ pub struct Executor {
stream_sources: BTreeSet<usize>, stream_sources: BTreeSet<usize>,
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>, generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
reads: DependencyReads, reads: DependencyReads,
// Cache the resolved meaning alongside the already required read evidence. // Cache the resolved meaning alongside the last read epoch. A shard's
// A shard's revision is only valid on this executor's state history. // revision is only valid on this executor's state history.
meaning_reads: HashMap<CommandName, (u64, Meaning), RandomState>, meaning_reads: HashMap<CommandName, (u64, Meaning, u32), RandomState>,
reads_tracing_macros: bool, reads_tracing_macros: bool,
conditionals: Vec<Conditional>, conditionals: Vec<Conditional>,
in_csname: bool, in_csname: bool,
@@ -501,6 +502,7 @@ impl EntryCheckpoint {
return Ok(None); return Ok(None);
} }
let mut executor = self.executor.clone().with_cancellation(cancellation); let mut executor = self.executor.clone().with_cancellation(cancellation);
executor.reads.advance_epoch();
executor.line_break_cache = line_break_cache; executor.line_break_cache = line_break_cache;
let previous_len = self.executor.sources[self.entry].data.len(); let previous_len = self.executor.sources[self.entry].data.len();
let current_len = source.data.len(); let current_len = source.data.len();
@@ -821,10 +823,14 @@ impl Executor {
} }
} }
} }
fn take_dependency_reads(&mut self) -> BTreeSet<Dependency> { fn dependency_observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
let mut reads = std::mem::take(&mut self.reads).into_ordered(); self.reads.observations().chain(self.meaning_reads.iter()
reads.extend(self.meaning_reads.drain().map(|(name, _)| Dependency::Meaning(name))); .map(|(name, (_, _, epoch))| (Dependency::Meaning(name.clone()), *epoch)))
reads }
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 { fn meaning(&mut self, token: &Token) -> Meaning {
@@ -836,9 +842,11 @@ impl Executor {
fn lookup_meaning(&mut self, name: &CommandName) -> Meaning { fn lookup_meaning(&mut self, name: &CommandName) -> Meaning {
let hash = self.meaning_reads.hasher().hash_one(name); let hash = self.meaning_reads.hasher().hash_one(name);
let revision = self.state.command_revision(hash); 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) { match self.meaning_reads.raw_entry_mut().from_key_hashed_nocheck(hash, name) {
RawEntryMut::Occupied(mut entry) => { 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 { if *cached_revision != revision {
*meaning = self.state.meaning_hashed(name, hash); *meaning = self.state.meaning_hashed(name, hash);
*cached_revision = revision; *cached_revision = revision;
@@ -847,7 +855,7 @@ impl Executor {
} }
RawEntryMut::Vacant(entry) => { RawEntryMut::Vacant(entry) => {
let meaning = self.state.meaning_hashed(name, hash); 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 meaning
} }
} }
@@ -3567,7 +3575,7 @@ impl Executor {
for node in nodes { for node in nodes {
self.output_node(node, files)?; 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(); let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution { Ok(Execution {
format_dumped: self.format_dumped, format_dumped: self.format_dumped,
@@ -3591,6 +3599,7 @@ impl Executor {
stream_sources: self.stream_sources, stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs, generated_inputs: self.generated_inputs,
reads, reads,
dependency_evidence,
line_observations: Some(self.line_observations), line_observations: Some(self.line_observations),
events: self.events.into_vec(), events: self.events.into_vec(),
steps: self.steps, steps: self.steps,
@@ -4008,6 +4017,9 @@ impl Executor {
} }
engine.events.seal_prefix(); engine.events.seal_prefix();
let mut executor = engine.clone(); 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.cancellation = None;
executor.line_break_cache = None; executor.line_break_cache = None;
let checkpoint = EntryCheckpoint { let checkpoint = EntryCheckpoint {
@@ -4028,7 +4040,7 @@ impl Executor {
incoming_state: u64, incoming_state: u64,
previous: Option<&Execution>, previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> { ) -> Result<Execution, ExecutionFailure> {
let reads = self.take_dependency_reads(); let (reads, dependency_evidence) = self.take_dependency_reads();
let result = result.and_then(|()| { let result = result.and_then(|()| {
if self.shipped_pages > 0 && !self.format_dumped if self.shipped_pages > 0 && !self.format_dumped
&& let Some(objects) = self.state.pdf_objects.as_deref_mut() && let Some(objects) = self.state.pdf_objects.as_deref_mut()
@@ -4098,6 +4110,7 @@ impl Executor {
stream_sources: self.stream_sources, stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs, generated_inputs: self.generated_inputs,
reads, reads,
dependency_evidence,
line_observations: Some(self.line_observations), line_observations: Some(self.line_observations),
incoming_state, incoming_state,
steps: self.steps, 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::{ use super::super::{
dependency_reads::DependencyEvidence,
source_relocation::SourceRelocation, source_relocation_events::EventRelocation, source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::BoxNodeOffset, statistics::{BoxNodeOffset, RetainedHistoryOffset},
}; };
use super::*; use super::*;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -185,19 +186,18 @@ impl EntryCheckpoint {
None if box_offset.is_identity() => None, None if box_offset.is_identity() => None,
None => return None, None => return None,
}; };
if current.material_charge != old.material_charge { // A capacity recount can lower the running charge and observe
// A capacity recount can lower the running charge and change // the retained event history. Bound all future visits on both
// which storage TeX counts. Bound every future charge on both // runs before translating any unequal charge or history.
// histories so neither can enter that path. let no_suffix_recount = completed.box_nodes_created.is_some_and(|nodes| {
let donor = completed.box_nodes_created?; nodes != usize::MAX
if donor == usize::MAX { && nodes.checked_sub(old.box_nodes_created)
return None; .and_then(|remaining| current.material_charge.max(old.material_charge)
} .checked_add(remaining))
let remaining = donor.checked_sub(old.box_nodes_created)?; .is_some_and(|charge| charge <= current.limits.tokens)
let largest = current.material_charge.max(old.material_charge); });
if largest.checked_add(remaining)? > current.limits.tokens { if current.material_charge != old.material_charge && !no_suffix_recount {
return None; return None;
}
} }
let previous_bytes = &old.sources[self.entry].data; let previous_bytes = &old.sources[self.entry].data;
let current_bytes = &current.sources[self.entry].data; let current_bytes = &current.sources[self.entry].data;
@@ -254,28 +254,36 @@ impl EntryCheckpoint {
let mut sources = completed.sources.clone(); let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone(); sources[self.entry] = current.sources[self.entry].clone();
let tail = completed.events.get(old.events.len()..)?; let tail = completed.events.get(old.events.len()..)?;
if completed.accounts_event_history let retained_history = if completed.accounts_event_history {
&& !measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || { measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes) if current.events.len() == old.events.len()
}) && current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
{ {
return None; 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 // The joined events are published results. Resumption always starts
// from a live checkpoint, whose original shared allocations stay intact. // from a live checkpoint, whose original shared allocations stay intact.
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || { 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()); events.extend(current.events.iter().cloned());
let mut reads = completed.reads.clone(); let (reads, dependency_evidence) = splice_dependencies(current, old, completed)?;
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 mut execution = Execution { let mut execution = Execution {
format_dumped: completed.format_dumped, format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(), format_pdf_images: completed.format_pdf_images.clone(),
@@ -293,6 +301,7 @@ impl EntryCheckpoint {
stream_sources: completed.stream_sources.clone(), stream_sources: completed.stream_sources.clone(),
generated_inputs: completed.generated_inputs.clone(), generated_inputs: completed.generated_inputs.clone(),
reads, reads,
dependency_evidence,
line_observations, line_observations,
incoming_state: completed.incoming_state, incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state, outgoing_state: completed.outgoing_state,
@@ -303,18 +312,18 @@ impl EntryCheckpoint {
}; };
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) { if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
relocate::append_suffix( 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 { if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint(); 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); execution.events.extend_from_slice(tail);
} else { } else {
for event in tail { for event in tail {
execution.events.push(match event { execution.events.push(match event {
Event::Statistics(report) => Event::Statistics(Box::new( Event::Statistics(report) => Event::Statistics(Box::new(
report.with_execution_offsets(offset, box_offset)?, statistics.translate(report, None)?,
)), )),
_ => event.clone(), _ => event.clone(),
}); });
@@ -347,20 +356,21 @@ impl EntryCheckpoint {
let current = &self.executor; let current = &self.executor;
let old = &prior.executor; let old = &prior.executor;
// Later snapshots retain the donor's meaning cache and read history. // Later snapshots retain the donor's meaning cache and read history.
// A successful splice proved key inclusion, so equal lengths prove // Keeping them requires the same keys, even when the finished splice
// that no new meaning lookup would be lost by carrying the snapshot. // could publish a different set using exact suffix evidence.
if current.reads != old.reads if current.events.len() != old.events.len()
|| current.reads != old.reads
|| current.meaning_reads.len() != old.meaning_reads.len() || 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.box_nodes_created != old.box_nodes_created
|| current.material_charge != old.material_charge || current.material_charge != old.material_charge
{ {
return None; return None;
} }
// A restored checkpoint may later be asked to account for its // A carried executor needs the exact alias history before taking
// history, even if the job that furnished the suffix did not. // donor allocations from equal-valued events. Translating a final
if !completed.accounts_event_history // report proves only the published counts.
&& !self.executor.equivalent_accounting_history(&prior.executor) if completed.reads_event_history || !current.equivalent_accounting_history(old) {
{
return None; return None;
} }
// Keep the old allocations of unchanged material, including inside // Keep the old allocations of unchanged material, including inside
@@ -418,6 +428,9 @@ impl EntryCheckpoint {
} }
let mut executor = next.clone(); 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( executor.line_observations = splice_line_observations(
&current.line_observations, &old.line_observations, &next.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 { fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
let started = elapsed.is_some().then(Instant::now); let started = elapsed.is_some().then(Instant::now);
let value = action(); let value = action();
@@ -497,6 +553,28 @@ fn splice_line_observations(
Some(combined) 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> { fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
match event { match event {
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))), 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() { if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() {
return false; return false;
} }
if current.events.len() != prior.events.len() if current.inputs.len() != prior.inputs.len()
|| current.inputs.len() != prior.inputs.len()
// Statistics membership also constrains source rebinding. // Statistics membership also constrains source rebinding.
|| current.reads.observed_statistics() != prior.reads.observed_statistics() || 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; return false;
} }
@@ -1,5 +1,5 @@
use super::*; use super::*;
use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset}; use crate::execution::source_relocation_events::EventRelocation;
pub(super) fn same_kernel_provenance( pub(super) fn same_kernel_provenance(
current: &Executor, current: &Executor,
@@ -106,8 +106,7 @@ pub(super) fn same_kernel_provenance(
pub(super) fn append_suffix( pub(super) fn append_suffix(
execution: &mut Execution, execution: &mut Execution,
tail: &[Event], tail: &[Event],
offset: StepOffset, statistics: &SuffixStatistics,
boxes: BoxNodeOffset,
relocation: &mut EventRelocation<'_>, relocation: &mut EventRelocation<'_>,
(previous_bytes, current_bytes): (usize, usize), (previous_bytes, current_bytes): (usize, usize),
source_count: usize, source_count: usize,
@@ -123,9 +122,7 @@ pub(super) fn append_suffix(
return None; return None;
} }
} }
let mut report = report let mut report = statistics.translate(report, Some((previous_bytes, current_bytes)))?;
.with_execution_offsets(offset, boxes)?
.with_suffix_entry_resize(previous_bytes, current_bytes)?;
report.span = map.relocate_span(report.span)?; report.span = map.relocate_span(report.span)?;
execution.events.push(Event::Statistics(Box::new(report))); execution.events.push(Event::Statistics(Box::new(report)));
} else { } else {
@@ -1,6 +1,7 @@
use super::super::statistics::{ use super::super::statistics::{
Collector, Collector,
Ownership::{Active, Retained}, Ownership::{Active, Retained},
RetainedHistoryOffset,
}; };
use super::*; use super::*;
impl Executor { impl Executor {
@@ -239,6 +240,31 @@ impl Executor {
old: &Self, old: &Self,
entry_sizes: Option<(usize, usize)>, entry_sizes: Option<(usize, usize)>,
) -> bool { ) -> 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 // These containers may reintroduce previously retained allocations
// that are outside the accounting walk at this boundary. // that are outside the accounting walk at this boundary.
let fully_visited = |engine: &Self| { 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()) && engine.native_page.as_ref().is_none_or(|page| page.insertions.held.is_empty())
}; };
if !fully_visited(self) || !fully_visited(old) { if !fully_visited(self) || !fully_visited(old) {
return false; return None;
} }
let (history, old_history) =
[Collector::for_capacity, Collector::default].into_iter().all(|collector| { Self::collect_event_usage_pair(&self.events, &old.events, collector());
let (history, old_history) = let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
Self::collect_event_usage_pair(&self.events, &old.events, collector()); let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases()); // The splice translates the cumulative counters separately.
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases()); live.usage.steps = old_live.usage.steps;
// The splice translates the cumulative counters separately. live.usage.box_nodes_created = old_live.usage.box_nodes_created;
live.usage.steps = old_live.usage.steps; if let Some((previous, current)) = entry_sizes {
live.usage.box_nodes_created = old_live.usage.box_nodes_created; let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
if let Some((previous, current)) = entry_sizes { live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?;
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous); live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?;
let Some(source) = restore(live.usage.source_payload_bytes) else { return false; }; }
let Some(mouth) = restore(live.usage.mouth_payload_bytes) else { return false; }; Some((live, old_live, history, old_history))
live.usage.source_payload_bytes = source;
live.usage.mouth_payload_bytes = mouth;
}
live.has_equivalent_history(&old_live, &history, &old_history)
})
} }
pub(super) fn statistics_before_shipout( pub(super) fn statistics_before_shipout(
@@ -341,6 +362,57 @@ impl Executor {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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] #[test]
fn shared_event_prefix_keeps_tail_deduplication_and_membership() { 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>, pub stream_sources: BTreeSet<usize>,
#[serde(default)] #[serde(default)]
pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>, pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
/// Reads made during this execution, not a license to reuse output after /// Dependencies observed over the execution. Suffix reuse additionally
/// state changes. Incremental execution/cache reuse is a later milestone. /// validates the state and the reads that follow its checkpoint.
pub reads: BTreeSet<Dependency>, 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. /// Per-source observations distinguish suffix reads from identical prefix reads.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
line_observations: Option<BTreeMap<usize, usize>>, 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 { impl StatisticsReport {
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self { pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
let text = phase.text(); let text = phase.text();
@@ -227,26 +301,9 @@ impl StatisticsReport {
/// Recompute a report for a verified suffix after the initial entry read /// Recompute a report for a verified suffix after the initial entry read
/// changed size. The caller authenticates the entry scanner's lifetime. /// changed size. The caller authenticates the entry scanner's lifetime.
pub fn with_suffix_entry_resize(&self, previous: usize, current: usize) -> Option<Self> { pub fn with_suffix_entry_resize(&self, previous: usize, current: usize) -> Option<Self> {
let mut phase = self.phase.clone(); self.with_suffix_adjustments(
match &mut phase { StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some((previous, current)), None,
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)
} }
pub fn with_step_offset(&self, offset: StepOffset) -> Option<Self> { pub fn with_step_offset(&self, offset: StepOffset) -> Option<Self> {
@@ -257,6 +314,16 @@ impl StatisticsReport {
&self, &self,
steps: StepOffset, steps: StepOffset,
boxes: BoxNodeOffset, 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> { ) -> Option<Self> {
let translate = |usage: &mut ResourceUsage| { let translate = |usage: &mut ResourceUsage| {
usage.steps = steps.apply(usage.steps)?; usage.steps = steps.apply(usage.steps)?;
@@ -266,10 +333,32 @@ impl StatisticsReport {
let mut phase = self.phase.clone(); let mut phase = self.phase.clone();
match &mut phase { match &mut phase {
StatisticsPhase::Shipout { before, after } => { StatisticsPhase::Shipout { before, after } => {
translate(before)?; if history.is_some_and(|offset| !offset.is_identity()) {
translate(after)?; 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); let report = Self::new(phase, self.destination, self.span);
report.within_diagnostic_budget().then_some(report) 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( pub(super) fn has_equivalent_history(
&self, &self,
other: &Self, other: &Self,
history: &Self, history: &Self,
old_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 { ) -> bool {
let a = &self.aliases.as_ref().expect("live alias traversal").visits; let a = &self.aliases.as_ref().expect("live alias traversal").visits;
let b = &other.aliases.as_ref().expect("live alias traversal").visits; let b = &other.aliases.as_ref().expect("live alias traversal").visits;
self.usage == other.usage self.usage == other.usage
&& history.usage == old_history.usage
&& a.len() == b.len() && a.len() == b.len()
&& a.iter().zip(b).all(|(&(new, ni), &(old, oi))| { && a.iter().zip(b).all(|(&(new, ni), &(old, oi))| {
ni == 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] #[test]
fn history_equivalence_keeps_aliases_that_cross_the_boundary() { fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default()); let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
+36
View File
@@ -87,6 +87,42 @@ p50 分别为 33.2 和 33.3 ms,进程峰值 RSS 为 603,280 KiB。
原始样本、构建清单、机器状态和逐次输出对照在 原始样本、构建清单、机器状态和逐次输出对照在
`target/p4-a4-browser-recheck/`。 `target/p4-a4-browser-recheck/`。
## 2026-12-02 不等长事件历史的后缀复用
发页后即使两版的保留事件数量不同,内核也可以继续核对状态、实际
宿主效果和来源坐标。若后缀可能重算盒容量,或途中还会输出发页统计,
继续要求完全相同的记账历史。只有确认后缀不会重算容量、统计只在
收尾发生,而且跨接缝的分配共享关系一致时,才调整收尾报告中的保留
事件、材料和令牌计数。可继续执行的检查点仍需精确的记账等价证明。
检查点记录依赖最后一次被访问的区间,包含命中缓存的命令查询。
拼接结果保留新版前缀和实际跳过的后缀观测。只在旧前缀出现的观测
可以删除。旧记录缺少区间时继续采用保守规则。
十五项定向管线回归和五项内核单测通过。冻结 A4 的六次主文件改写与各自独立全量的
执行、PDF、SVG、来源、资源和生成文件均一致。五次各跳过 20,618
步后缀,实际执行 32,994 或 32,997 步,较同一组旧样本少约 38.5%。
首个改写仍执行完后缀。该批使用 opt-level 0,成功拼接的核对和
组装仍有额外耗时。原始样本在 `target/p4-a4-suffix-proof/run-tc4ag9tt/`。
### 候选分支的 Edge 复测
同一台机器和同一冻结 A4,主文件与子文件各 30 次实际页面更新。
主文件有 29 次各跳过 20,618 步后缀,子文件的 30 次仍执行后缀。
全部 60 次的 PDF、SVG 和来源映射与主线基线逐项相同。
| A4 热编辑 | 主线可见 p50 / p95 | 候选可见 p50 / p95 |
| --- | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 325.5 / 512.1 ms |
| 子文件正文 | 184.1 / 241.5 ms | 185.4 / 266.7 ms |
候选的主文件实际执行步数 p50 为 35,138,主线为 55,755。
主文件执行阶段 p50 升至 225.6 ms。用同一优化构建单次拆分,
状态比较 31.9 ms、保留记账 66.9 ms、结果组装 68.5 ms。
候选保存在 `perf/retained-history-suffix`。100 ms 门槛仍开放。
浏览器原始记录在 `target/p4-a4-retained-history/`,单次阶段
数据在 `target/p4-a4-suffix-proof/run-qcghpnrj/`。
## 2026-12-02 XeTeX 整行编辑复用 ## 2026-12-02 XeTeX 整行编辑复用
XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他 XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他
+65 -9
View File
@@ -1763,29 +1763,29 @@ fn settled_suffix_carries_a_verified_prefix_into_later_edits() {
} }
#[test] #[test]
fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() { fn settled_suffix_distinguishes_removed_prefix_reads_from_repeated_suffix_reads() {
use texrra_tex_core::execution::Dependency; use texrra_tex_core::execution::Dependency;
let cwd = directory("settled-prefix-dependencies"); let cwd = directory("settled-prefix-dependencies");
let entry = cwd.join("main.tex"); let entry = cwd.join("main.tex");
let body = |ignored| format!(r" let body = |ignored, repeat| format!(r"
\catcode64=9 \catcode63=9 \catcode64=9 \catcode63=9
?\relax ?\relax
\shipout\hbox{{Cover}}\relax \shipout\hbox{{Cover}}\relax
{ignored}\relax {ignored}\relax
\shipout\hbox{{Checkpoint}}\relax \shipout\hbox{{Checkpoint}}\relax
\shipout\hbox{{Suffix}}\relax {repeat}\relax\shipout\hbox{{Suffix}}\relax
\endinput\shipout\hbox{{Final}}\relax\end \endinput\shipout\hbox{{Final}}\relax\end
"); ");
for (before, after, reuse) in [('?', '@', true), ('@', '?', false)] { for (before, after, repeat) in [('?', '@', '?'), ('@', '?', '?'), ('@', '?', '@')] {
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap(); let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before, repeat))).unwrap();
let mut request = request(&cwd).observe_generated_initial(); let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration(); request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints(); let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let donor = session.compile(request.clone().with_project(project.clone())).unwrap(); let donor = session.compile(request.clone().with_project(project.clone())).unwrap();
let new_read = Dependency::CatCode('@'); let new_read = Dependency::CatCode('@');
assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@'); assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@' || repeat == '@');
let source = format!("{HEADER}{}", body(after)); let source = format!("{HEADER}{}", body(after, repeat));
let project = project.with_file_edits( let project = project.with_file_edits(
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(), 2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
).unwrap(); ).unwrap();
@@ -1793,8 +1793,8 @@ fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() {
let updated = session.compile(input.clone()).unwrap(); let updated = session.compile(input.clone()).unwrap();
let work = &updated.entry_checkpoint_work; let work = &updated.entry_checkpoint_work;
assert!(!work.reused_completion, "{work:?}"); assert!(!work.reused_completion, "{work:?}");
assert_eq!(work.reused_suffix_steps > 0, reuse, "{work:?}"); assert!(work.reused_suffix_steps > 0, "{work:?}");
assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@'); assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@' || repeat == '@');
let log = fs::read(cwd.join("job.log")).unwrap(); let log = fs::read(cwd.join("job.log")).unwrap();
let full = NativeCompiler::default().compile(input).unwrap(); let full = NativeCompiler::default().compile(input).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution); assert_eq!(updated.execution.execution, full.execution.execution);
@@ -1862,6 +1862,62 @@ fn settled_suffix_translates_cumulative_box_charges_in_both_directions() {
fs::remove_dir_all(cwd).unwrap(); fs::remove_dir_all(cwd).unwrap();
} }
#[test]
fn settled_suffix_translates_final_retained_statistics_for_unequal_histories() {
use texrra_tex_core::execution::{Event, StatisticsPhase};
let cwd = directory("settled-retained-history");
let entry = cwd.join("main.tex");
let body = |stats, text| format!(r"
\tracingstats={stats}
\shipout\hbox{{Cover with x}}\relax
\shipout\hbox{{{text}}}\relax
\shipout\hbox{{Suffix}}\relax
\endinput\shipout\hbox{{Final}}\relax\end
");
let retained = |document: &CompiledDocument| {
let Some(Event::Statistics(report)) = document.execution.execution.events.last() else {
panic!("missing final resource report");
};
let StatisticsPhase::End { usage, .. } = &report.phase else {
panic!("expected final resource report");
};
(usage.retained_events, usage.retained_material.horizontal_nodes)
};
for (stats, before, after, reuse) in [
(1, "x", "xxxxxxx", true),
(1, "xxxxxxx", "x", true),
(2, "x", "xxxxxxx", false),
] {
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(stats, before))).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let donor = session.compile(request.clone().with_project(project.clone())).unwrap();
let source = format!("{HEADER}{}", body(stats, after));
let project = project.with_file_edits(
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
).unwrap();
let input = request.with_project(project);
let updated = session.compile(input.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
assert!(!work.reused_completion, "{work:?}");
if reuse {
assert!(work.reused_suffix_steps > 0, "{work:?}");
}
assert_ne!(retained(&updated), retained(&donor));
let log = fs::read(cwd.join("job.log")).unwrap();
let full = NativeCompiler::default().compile(input).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution);
assert_eq!(updated.resources.trace, full.resources.trace);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
}
fs::remove_dir_all(cwd).unwrap();
}
#[test] #[test]
fn resized_entry_prefix_reuses_verified_statistics() { fn resized_entry_prefix_reuses_verified_statistics() {
let cwd = directory("resized-entry-statistics"); let cwd = directory("resized-entry-statistics");