16 changed files with 2086 additions and 300 deletions

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()
&& self
.byte_catcodes
.iter() .iter()
.zip(other.byte_catcodes) .zip(&other.byte_catcodes)
.all(|(&bits, permitted)| bits & !permitted == 0) .all(|(&seen, &permitted)| seen == 0 || permitted != 0)
&& self.other.is_subset(&other.other) && 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();
+41 -12
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};
@@ -43,7 +44,7 @@ mod scheduling;
mod specials; mod specials;
mod statistics; mod statistics;
mod continuation; mod continuation;
pub use continuation::{RelocatedShipoutSuffix, SuffixKernelTimings}; pub use continuation::{ClosedSourceChange, RelocatedShipoutSuffix, SuffixKernelTimings};
mod xdv_annotation; mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -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, SuffixSourceResize},
}; };
use super::*; use super::*;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
@@ -122,7 +123,71 @@ impl RelocatedShipoutSuffix {
} }
} }
/// One changed physical child whose scanner has already left the input stack.
pub struct ClosedSourceChange<'a> {
pub source_id: usize,
pub name: &'a str,
pub previous_bytes: usize,
pub current_bytes: usize,
}
impl EntryCheckpoint { impl EntryCheckpoint {
/// Identify a closed byte-framed child before the host verifies its path,
/// distinct file roles, read counts, and absence of later observations.
pub fn closed_source_change<'a>(
&'a self,
prior: &Self,
completed: &Execution,
) -> Option<ClosedSourceChange<'a>> {
let current = &self.executor;
let old = &prior.executor;
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
|| current.sources.len() != old.sources.len()
|| !matches!(current.state.input_profile(), InputProfile::TeX8Bit | InputProfile::UnicodeScalar)
|| current.state.input_profile() != old.state.input_profile()
{
return None;
}
let mut differences = current.sources.iter().zip(&old.sources).enumerate()
.filter(|(_, (new, old))| new != old);
let (source_id, (new, old_source)) = differences.next()?;
if differences.next().is_some()
|| source_id == self.entry
|| new.name != old_source.name
|| completed.sources.get(source_id)? != old_source
{
return None;
}
let uniquely_named = |sources: &[Arc<SourceFile>]| {
sources.iter().filter(|source| source.name == new.name).take(2).count() == 1
};
let is_closed = |executor: &Executor| {
!executor.stream_sources.contains(&source_id)
&& !executor.generated_inputs.contains_key(&source_id)
&& !executor.inputs.iter().any(|frame| matches!(
frame, InputFrame::Source { source, .. } if *source == source_id
))
};
if !uniquely_named(&old.sources)
|| !uniquely_named(&current.sources)
|| !uniquely_named(&completed.sources)
|| !is_closed(old)
|| !is_closed(current)
|| completed.stream_sources.contains(&source_id)
|| completed.generated_inputs.contains_key(&source_id)
{
return None;
}
Some(ClosedSourceChange {
source_id,
name: &new.name,
previous_bytes: old_source.data.len(),
current_bytes: new.data.len(),
})
}
/// Construct an execution with the current prefix and a previously /// Construct an execution with the current prefix and a previously
/// completed suffix. The host must still validate and replay that suffix. /// completed suffix. The host must still validate and replay that suffix.
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> { pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
@@ -145,6 +210,36 @@ impl EntryCheckpoint {
&self, &self,
prior: &Self, prior: &Self,
completed: &Execution, completed: &Execution,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.splice_settled_sources(prior, completed, self.entry, 1, timings)
}
/// Reuse a suffix after the caller has verified the actual host reads
/// of the changed child, including probes that only consumed its size.
/// The caller must reject later uses of this file and replay all effects.
pub fn splice_settled_closed_source_suffix_observed(
&self,
prior: &Self,
completed: &Execution,
source_id: usize,
prefix_resource_reads: usize,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if prefix_resource_reads == 0
|| self.closed_source_change(prior, completed)?.source_id != source_id
{
return None;
}
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, timings)
}
fn splice_settled_sources(
&self,
prior: &Self,
completed: &Execution,
source_id: usize,
prefix_resource_reads: usize,
mut timings: Option<&mut SuffixKernelTimings>, mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> { ) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source if self.entry != self.active_source
@@ -169,7 +264,7 @@ impl EntryCheckpoint {
.zip(&old.sources) .zip(&old.sources)
.enumerate() .enumerate()
.any(|(id, (new, old))| { .any(|(id, (new, old))| {
if id == self.entry { if id == source_id {
new.name != old.name new.name != old.name
} else { } else {
new != old new != old
@@ -185,26 +280,28 @@ 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)
.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; return None;
} }
let remaining = donor.checked_sub(old.box_nodes_created)?; let previous_bytes = &old.sources[source_id].data;
let largest = current.material_charge.max(old.material_charge); let current_bytes = &current.sources[source_id].data;
if largest.checked_add(remaining)? > current.limits.tokens { let resize = (previous_bytes.len() != current_bytes.len()).then_some(SuffixSourceResize {
return None; sizes: (previous_bytes.len(), current_bytes.len()),
} active_at_anchor: source_id == self.entry,
} prefix_resource_reads,
let previous_bytes = &old.sources[self.entry].data; });
let current_bytes = &current.sources[self.entry].data; let relocation = match resize {
let entry_sizes = (previous_bytes.len() != current_bytes.len()) Some(resize) if resize.active_at_anchor => {
.then_some((previous_bytes.len(), current_bytes.len()));
let relocation = match entry_sizes {
Some(_) => {
let map = self.source_mouth(self.entry) let map = self.source_mouth(self.entry)
.relocation_from(prior.source_mouth(prior.entry))?; .relocation_from(prior.source_mouth(prior.entry))?;
if map.relocate_offset(prior.frontier) != Some(self.frontier) { if map.relocate_offset(prior.frontier) != Some(self.frontier) {
@@ -212,13 +309,16 @@ impl EntryCheckpoint {
} }
Some(map) Some(map)
} }
Some(_) if self.frontier == prior.frontier => {
Some(SourceRelocation::new(source_id, previous_bytes, current_bytes)?)
}
None if self.frontier == prior.frontier => None, None if self.frontier == prior.frontier => None,
None => return None, _ => return None,
}; };
let observes_entry_line = completed.line_observations.as_ref().is_none_or(|observations| { let observes_changed_line = completed.line_observations.as_ref().is_none_or(|observations| {
observations.get(&self.entry) != old.line_observations.get(&self.entry) observations.get(&source_id) != old.line_observations.get(&source_id)
}); });
if observes_entry_line if observes_changed_line
&& relocation.as_ref().map_or_else( && relocation.as_ref().map_or_else(
|| !SourceRelocation::same_line_breaks(previous_bytes, current_bytes), || !SourceRelocation::same_line_breaks(previous_bytes, current_bytes),
|map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1, |map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1,
@@ -252,30 +352,38 @@ impl EntryCheckpoint {
return None; return None;
} }
let mut sources = completed.sources.clone(); let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone(); sources[source_id] = current.sources[source_id].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_source_resize(old, resize)
{
return Some(None);
}
// Shipout reports also contribute to later diagnostic
// counters. Only translate the final report here.
let has_final_report = matches!(tail.last(),
Some(Event::Statistics(report)) if matches!(report.phase, StatisticsPhase::End { .. })
);
if !no_suffix_recount || !has_final_report
|| tail[..tail.len() - 1].iter().any(|event| matches!(event, Event::Statistics(_)))
{ {
return None; return None;
} }
let history = current.retained_history_offset(old, resize)?;
Some((!history.is_identity()).then_some(history))
})?
} else {
None
};
let statistics = SuffixStatistics { steps: offset, boxes: box_offset, retained_history };
// The joined events are published results. Resumption always starts // 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 +401,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,
@@ -301,20 +410,20 @@ impl EntryCheckpoint {
reads_event_history: false, reads_event_history: false,
accounts_event_history: completed.accounts_event_history, accounts_event_history: completed.accounts_event_history,
}; };
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) { if let Some((moved, resize)) = moved.as_mut().zip(resize) {
relocate::append_suffix( relocate::append_suffix(
&mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(), &mut execution, tail, &statistics, moved, resize, 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(),
}); });
@@ -346,21 +455,29 @@ impl EntryCheckpoint {
} }
let current = &self.executor; let current = &self.executor;
let old = &prior.executor; let old = &prior.executor;
// Rebased checkpoints retain the donor's closed-source bytes.
if current.sources.len() != old.sources.len()
|| current.sources.iter().zip(&old.sources).enumerate()
.any(|(id, (new, old))| id != self.entry && new != old)
{
return None;
}
// Later snapshots retain the donor's meaning cache and read history. // 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 +535,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 +588,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 +660,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,
resize: Option<SuffixSourceResize>,
) -> Option<StatisticsReport> {
report.with_source_resize(
self.steps, self.boxes, resize, self.retained_history.as_ref(),
)
}
}
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> { 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 +811,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,16 +106,17 @@ 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), resize: SuffixSourceResize,
source_count: usize, source_count: usize,
) -> Option<()> { ) -> Option<()> {
let map = relocation.map(); let map = relocation.map();
for event in tail { for event in tail {
if let Event::Statistics(report) = event { if let Event::Statistics(report) = event {
if let StatisticsPhase::Shipout { before, after } = &report.phase { if resize.active_at_anchor
&& let StatisticsPhase::Shipout { before, after } = &report.phase
{
// The active entry was the only source frame at convergence. // The active entry was the only source frame at convergence.
// If a report follows any later input open, its mouth payload // If a report follows any later input open, its mouth payload
// alone cannot prove whether that frame is still present. // alone cannot prove whether that frame is still present.
@@ -123,9 +124,7 @@ pub(super) fn append_suffix(
return None; return None;
} }
} }
let mut report = report let mut report = statistics.translate(report, Some(resize))?;
.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, SuffixSourceResize,
}; };
use super::*; use super::*;
impl Executor { impl Executor {
@@ -49,8 +50,9 @@ impl Executor {
&self, &self,
shipping: Option<&NativeBox>, shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>, host: Option<HostResourceUsage>,
c: Collector, mut c: Collector,
) -> ResourceUsage { ) -> ResourceUsage {
self.state.collect_statistics(&mut c);
let mut c = self.collect_live_usage(shipping, host, c); let mut c = self.collect_live_usage(shipping, host, c);
Self::collect_event_usage(self.events.iter(), &mut c); Self::collect_event_usage(self.events.iter(), &mut c);
c.usage c.usage
@@ -62,7 +64,6 @@ impl Executor {
host: Option<HostResourceUsage>, host: Option<HostResourceUsage>,
mut c: Collector, mut c: Collector,
) -> Collector { ) -> Collector {
self.state.collect_statistics(&mut c);
c.usage.steps = self.steps; c.usage.steps = self.steps;
c.usage.source_files = self.sources.len(); c.usage.source_files = self.sources.len();
c.usage.source_payload_bytes = self.sources.iter().map(|s| s.data.len()).sum(); c.usage.source_payload_bytes = self.sources.iter().map(|s| s.data.len()).sum();
@@ -231,14 +232,39 @@ impl Executor {
} }
pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool { pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool {
self.equivalent_accounting_history_with_entry_sizes(old, None) self.equivalent_accounting_history_with_source_resize(old, None)
} }
pub(super) fn equivalent_accounting_history_with_entry_sizes( pub(super) fn equivalent_accounting_history_with_source_resize(
&self, &self,
old: &Self, old: &Self,
entry_sizes: Option<(usize, usize)>, resize: Option<SuffixSourceResize>,
) -> bool { ) -> bool {
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
self.collect_compared_accounting(old, resize, 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,
resize: Option<SuffixSourceResize>,
) -> Option<RetainedHistoryOffset> {
let (live, old_live, history, old_history) =
self.collect_compared_accounting(old, resize, Collector::default)?;
live.retained_history_offset(&old_live, &history, &old_history)
}
fn collect_compared_accounting(
&self,
old: &Self,
resize: Option<SuffixSourceResize>,
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,27 @@ 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;
} }
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
let (history, old_history) = let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector()); Self::collect_event_usage_pair(&self.events, &old.events, collector());
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases()); let (live, old_live) = self.state.collect_compared_statistics(
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases()); &old.state, collector().tracking_aliases(),
)?;
let mut live = self.collect_live_usage(None, None, live);
let old_live = old.collect_live_usage(None, None, old_live);
// The splice translates the cumulative counters separately. // The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps; live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created; live.usage.box_nodes_created = old_live.usage.box_nodes_created;
if let Some((previous, current)) = entry_sizes { if let Some(resize) = resize {
let (previous, current) = resize.sizes;
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous); let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
let Some(source) = restore(live.usage.source_payload_bytes) else { return false; }; live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?;
let Some(mouth) = restore(live.usage.mouth_payload_bytes) else { return false; }; if resize.active_at_anchor {
live.usage.source_payload_bytes = source; live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?;
live.usage.mouth_payload_bytes = mouth;
} }
live.has_equivalent_history(&old_live, &history, &old_history) }
}) Some((live, old_live, history, old_history))
} }
pub(super) fn statistics_before_shipout( pub(super) fn statistics_before_shipout(
@@ -341,6 +368,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() {
+7 -3
View File
@@ -72,7 +72,8 @@ pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial}; pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{ pub use engine::{
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Executor, Limits,
RelocatedShipoutSuffix,
SuffixKernelTimings, SuffixKernelTimings,
}; };
pub use font_catalog::{ pub use font_catalog::{
@@ -678,9 +679,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>>,
@@ -220,6 +220,12 @@ impl SourceRelocation {
} }
} }
/// A shard whose ranges end strictly before the edit can retain every
/// span, including zero-width points at those earlier positions.
pub(super) fn preserves_prefix_through(&self, end: usize) -> bool {
end < self.unchanged_prefix
}
pub(super) fn relocate_span(&self, span: Span) -> Option<Span> { pub(super) fn relocate_span(&self, span: Span) -> Option<Span> {
if span.source != self.source { if span.source != self.source {
return Some(span); return Some(span);
+261 -81
View File
@@ -1,9 +1,14 @@
mod fingerprint;
pub(super) mod source_relocation; pub(super) mod source_relocation;
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
use hashbrown::HashMap; use hashbrown::HashMap;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; use std::hash::{BuildHasher, Hash, Hasher, RandomState};
use std::sync::{Arc, OnceLock}; #[cfg(test)]
use std::hash::DefaultHasher;
use std::sync::{Arc, Mutex, OnceLock};
use super::{ use super::{
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register, CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
@@ -800,7 +805,47 @@ enum PdftexRevision {
} }
const COMMAND_SHARDS: usize = 32; const COMMAND_SHARDS: usize = 32;
type CommandShard = HashMap<Arc<CommandName>, Meaning, RandomState>; type CommandEntries = HashMap<Arc<CommandName>, Meaning, RandomState>;
#[derive(Clone, Debug)]
struct CommandShard {
entries: CommandEntries,
// Bounds may retain ranges of replaced or removed entries. Their only
// use is to prove that every surviving token is before an edit.
source_bounds: OnceLock<BTreeMap<usize, Option<usize>>>,
}
impl CommandShard {
fn new(entries: CommandEntries) -> Self {
Self { entries, source_bounds: OnceLock::new() }
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) -> Option<Meaning> {
if let Some(bounds) = self.source_bounds.get_mut() {
source_relocation::include_meaning_bounds(bounds, &meaning);
}
self.entries.insert(name, meaning)
}
fn insert_if_absent(&mut self, name: Arc<CommandName>, meaning: Meaning) -> bool {
let hashbrown::hash_map::Entry::Vacant(entry) = self.entries.entry(name) else {
return false;
};
if let Some(bounds) = self.source_bounds.get_mut() {
source_relocation::include_meaning_bounds(bounds, &meaning);
}
entry.insert(meaning);
true
}
}
impl PartialEq for CommandShard {
fn eq(&self, other: &Self) -> bool {
self.entries == other.entries
}
}
impl Eq for CommandShard {}
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>; type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
pub(super) fn command_hasher() -> &'static RandomState { pub(super) fn command_hasher() -> &'static RandomState {
@@ -816,15 +861,19 @@ struct CommandBindings {
revisions: [u64; COMMAND_SHARDS], revisions: [u64; COMMAND_SHARDS],
// Cache names only so redefinitions can share the same order. // Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames, ordered_names: OrderedCommandNames,
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
} }
impl Default for CommandBindings { impl Default for CommandBindings {
fn default() -> Self { fn default() -> Self {
let hasher = command_hasher(); let hasher = command_hasher();
Self { Self {
shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hasher.clone()))), shards: std::array::from_fn(|_| {
Arc::new(CommandShard::new(CommandEntries::with_hasher(hasher.clone())))
}),
revisions: [0; COMMAND_SHARDS], revisions: [0; COMMAND_SHARDS],
ordered_names: Arc::default(), ordered_names: Arc::default(),
fingerprint_inputs: Arc::default(),
} }
} }
} }
@@ -849,6 +898,7 @@ impl CommandBindings {
fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> { fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> {
self.shards[Self::shard_index(hash)] self.shards[Self::shard_index(hash)]
.entries
.raw_entry() .raw_entry()
.from_key_hashed_nocheck(hash, name) .from_key_hashed_nocheck(hash, name)
.map(|(_, meaning)| meaning) .map(|(_, meaning)| meaning)
@@ -867,16 +917,13 @@ impl CommandBindings {
} }
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) { fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
if let hashbrown::hash_map::Entry::Vacant(entry) = if self.shard_mut(&name).insert_if_absent(name.into(), meaning) {
self.shard_mut(&name).entry(name.into())
{
entry.insert(meaning);
self.invalidate_order(); self.invalidate_order();
} }
} }
fn remove(&mut self, name: &CommandName) { fn remove(&mut self, name: &CommandName) {
if self.shard_mut(name).remove(name).is_some() { if self.shard_mut(name).entries.remove(name).is_some() {
self.invalidate_order(); self.invalidate_order();
} }
} }
@@ -890,11 +937,11 @@ impl CommandBindings {
} }
fn len(&self) -> usize { fn len(&self) -> usize {
self.shards.iter().map(|shard| shard.len()).sum() self.shards.iter().map(|shard| shard.entries.len()).sum()
} }
fn iter(&self) -> impl Iterator<Item = (&Arc<CommandName>, &Meaning)> { fn iter(&self) -> impl Iterator<Item = (&Arc<CommandName>, &Meaning)> {
self.shards.iter().flat_map(|shard| shard.iter()) self.shards.iter().flat_map(|shard| shard.entries.iter())
} }
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> { fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> {
@@ -919,9 +966,29 @@ impl CommandBindings {
} }
} }
impl CommandBindings {
fn hash_fingerprint(&self, hasher: &mut FingerprintHasher) {
let Ok(mut inputs) = self.fingerprint_inputs.try_lock() else {
self.hash(hasher);
return;
};
inputs.prune_if_full();
let entries = self.ordered();
entries.len().hash(hasher);
for (name, meaning) in entries {
name.hash(hasher);
inputs.hash_meaning(meaning, hasher);
}
}
}
impl Hash for CommandBindings { impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) { fn hash<H: Hasher>(&self, hasher: &mut H) {
self.ordered().collect::<Vec<_>>().hash(hasher); let entries = self.ordered();
entries.len().hash(hasher);
for entry in entries {
entry.hash(hasher);
}
} }
} }
@@ -944,11 +1011,29 @@ impl<'de> serde::Deserialize<'de> for CommandBindings {
} }
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] // Derive the ordinary hash and emit the specialized fingerprint in the
pub struct State { // same field order. Only the command meanings can reuse recorded hash input.
macro_rules! define_state {
($( $(#[$metadata:meta])* $access:vis $field:ident: $ty:ty, )*) => {
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies just its command shard. // Checkpoints share the table. A write copies just its command shard.
// Formats and fingerprints use key order.
commands: Arc<CommandBindings>, commands: Arc<CommandBindings>,
$( $(#[$metadata])* $access $field: $ty, )*
}
impl State {
pub fn fingerprint(&self) -> u64 {
let mut hash = FingerprintHasher::default();
self.commands.hash_fingerprint(&mut hash);
$(self.$field.hash(&mut hash);)*
hash.finish()
}
}
};
}
define_state! {
catcodes: BTreeMap<char, CatCode>, catcodes: BTreeMap<char, CatCode>,
counts: BTreeMap<u16, i32>, counts: BTreeMap<u16, i32>,
toks: BTreeMap<u16, Vec<Token>>, toks: BTreeMap<u16, Vec<Token>>,
@@ -1031,46 +1116,6 @@ pub struct State {
pub(super) hyphenation: super::hyphenation::HyphenationData, pub(super) hyphenation: super::hyphenation::HyphenationData,
} }
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl Hasher for FingerprintHasher {
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
#[test] #[test]
fn buffered_fingerprint_matches_the_ordered_state_hash() { fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut state = State::initex().with_etex(); let mut state = State::initex().with_etex();
@@ -1096,6 +1141,101 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
check(&state); check(&state);
} }
#[test]
fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() {
use super::Span;
let check = |state: &State| {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
let fingerprint = state.fingerprint();
assert_eq!(fingerprint, direct.finish());
fingerprint
};
let first = CommandName::Control("测试命令".into());
let alias = CommandName::Control("命令别名".into());
let mut token = Token::new(
TokenKind::Command(CommandName::Control("αβγ".into())),
Span { source: 2, start: 40, end: 44 },
);
token.invocation = Some(Span { source: 3, start: 99, end: 101 });
let mut body = Arc::new(Macro {
prefix: vec![TokenKind::Character('木', CatCode::Letter)],
parameters: vec![vec![TokenKind::Character('λ', CatCode::Other)]],
parameter_chars: vec!['#'],
replacement: vec![Replacement::Token(token.clone()); 80],
long: true,
outer: false,
protected: true,
});
let mut state = State::default();
state.define(first.clone(), Meaning::Macro(body.clone()), true);
state.define(alias, Meaning::Macro(body.clone()), true);
let original = check(&state);
assert_eq!(Arc::weak_count(&body), 1);
assert_eq!(check(&state), original);
let donor = state.clone();
token.invocation = Some(Span { source: 3, start: 111, end: 113 });
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token.clone());
state.define(first.clone(), Meaning::Macro(body.clone()), true);
assert_ne!(check(&state), original);
assert_eq!(check(&donor), original);
assert_eq!(Arc::weak_count(&body), 1);
token.kind = TokenKind::Command(CommandName::Control("λ".repeat(40_000)));
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token);
state.define(first, Meaning::Macro(body), true);
let uncached = check(&state);
let _held = state.commands.fingerprint_inputs.lock().unwrap();
assert_eq!(state.fingerprint(), uncached);
}
#[test]
fn paired_statistics_keep_aliases_from_changed_to_shared_command_shards() {
use super::statistics::Collector;
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: Vec::new(),
long: false,
outer: false,
protected: false,
});
let independent = Arc::new(body.as_ref().clone());
let first = CommandName::Control("common-definition".into());
let second = CommandName::Control("other-common-definition".into());
let shard = |name: &CommandName| CommandBindings::shard_index(command_hasher().hash_one(name));
let shared_shards = [shard(&first), shard(&second)];
let edited = (0..128)
.map(|index| CommandName::Control(format!("edited-alias-{index}")))
.find(|name| !shared_shards.contains(&shard(name)))
.unwrap();
let mut prior = State::default();
prior.define(first, Meaning::Macro(body.clone()), true);
prior.define(second, Meaning::Macro(independent.clone()), true);
prior.define(edited.clone(), Meaning::Macro(body), true);
let mut current = prior.clone();
current.define(edited, Meaning::Macro(independent), true);
assert_eq!(current, prior);
let history = Collector::default();
let (new_counts, old_counts) = current
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
assert_eq!(new_counts.usage, old_counts.usage);
assert!(!new_counts.has_equivalent_history(&old_counts, &history, &history));
let (same, old_counts) = prior
.collect_compared_statistics(&prior, Collector::default().tracking_aliases())
.unwrap();
assert!(same.has_equivalent_history(&old_counts, &history, &history));
}
#[test] #[test]
fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() { fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
let mut state = State::initex().with_etex(); let mut state = State::initex().with_etex();
@@ -1610,6 +1750,71 @@ impl Default for State {
impl State { impl State {
pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) { pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) {
if !c.material_only() {
c.usage.state.command_entries = self.commands.len();
for (name, meaning) in self.commands.iter() {
Self::collect_command_statistics(c, name, meaning);
}
}
self.collect_state_storage(c);
}
pub(super) fn collect_compared_statistics(
&self,
old: &Self,
mut current_usage: super::statistics::Collector,
) -> Option<(super::statistics::Collector, super::statistics::Collector)> {
let mut old_usage = if current_usage.material_only() {
current_usage.clone()
} else {
let pairs = self.commands.shards.iter().zip(&old.commands.shards);
current_usage.usage.state.command_entries = old.commands.len();
for (current, prior) in pairs.clone() {
if current.entries.len() != prior.entries.len() {
return None;
}
if Arc::ptr_eq(current, prior) {
for (name, meaning) in &prior.entries {
Self::collect_command_statistics(&mut current_usage, name, meaning);
}
}
}
// Both alias walks start with the exact same live allocations.
// Copy their ordinals before counting the remaining bindings so
// a later alias to a shared macro still has the original ordinal.
let mut old_usage = current_usage.clone();
for (current, prior) in pairs {
if !Arc::ptr_eq(current, prior) {
for (name, old_meaning) in &prior.entries {
let meaning = current.entries.get(name)?;
Self::collect_command_statistics(&mut current_usage, name, meaning);
Self::collect_command_statistics(&mut old_usage, name, old_meaning);
}
}
}
old_usage
};
self.collect_state_storage(&mut current_usage);
old.collect_state_storage(&mut old_usage);
Some((current_usage, old_usage))
}
fn collect_command_statistics(
c: &mut super::statistics::Collector,
name: &CommandName,
meaning: &Meaning,
) {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
}
fn collect_state_storage(&self, c: &mut super::statistics::Collector) {
use super::statistics::Ownership::Active; use super::statistics::Ownership::Active;
for b in self.boxes.values() { for b in self.boxes.values() {
c.native_box(b, Active); c.native_box(b, Active);
@@ -1622,26 +1827,6 @@ impl State {
} }
return; return;
} }
c.usage.state.command_entries = self.commands.len();
let track_aliases = c.tracks_aliases();
let mut visit_command = |name: &CommandName, meaning: &Meaning| {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
};
if track_aliases {
for (name, meaning) in self.commands.ordered() {
visit_command(name, meaning);
}
} else {
for (name, meaning) in self.commands.iter() {
visit_command(name, meaning);
}
}
c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len(); c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len();
c.usage.state.parameter_entries = c.usage.state.parameter_entries =
self.parameters.len() + self.token_parameters.len() + self.job_parameters.len(); self.parameters.len() + self.token_parameters.len() + self.job_parameters.len();
@@ -2485,7 +2670,7 @@ impl State {
Arc::unwrap_or_clone(state.commands) Arc::unwrap_or_clone(state.commands)
.shards .shards
.into_iter() .into_iter()
.flat_map(Arc::unwrap_or_clone) .flat_map(|shard| Arc::unwrap_or_clone(shard).entries)
.filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) { .filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) {
CommandName::Control(name) => Some((name, meaning)), CommandName::Control(name) => Some((name, meaning)),
_ => None, _ => None,
@@ -2712,11 +2897,6 @@ impl State {
} }
} }
pub fn fingerprint(&self) -> u64 {
let mut hash = FingerprintHasher::default();
self.hash(&mut hash);
hash.finish()
}
pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) { pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
self.groups.push(Group { self.groups.push(Group {
kind, kind,
@@ -0,0 +1,195 @@
use super::{Macro, Meaning};
use std::{
collections::HashMap,
fmt,
hash::{DefaultHasher, Hash, Hasher},
sync::{Arc, Weak},
};
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
pub(super) struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl FingerprintHasher {
#[inline]
fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) {
if N > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
let end = self.used + N;
self.buffer[self.used..end].copy_from_slice(&bytes);
self.used = end;
}
}
impl Hasher for FingerprintHasher {
#[inline]
fn write_u8(&mut self, value: u8) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u16(&mut self, value: u16) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u32(&mut self, value: u32) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u64(&mut self, value: u64) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_usize(&mut self, value: usize) {
self.write_fixed(value.to_ne_bytes());
}
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
const MAX_CACHED_BYTES: usize = 16 * 1024 * 1024;
const MAX_CACHED_MACROS: usize = 8192;
const MAX_RECORDED_BYTES: usize = 64 * 1024;
const MIN_REPLACEMENT_TOKENS: usize = 8;
struct MacroInput {
// Keep the allocation address reserved while its bytes are cached,
// without keeping the definition or its token storage alive.
body: Weak<Macro>,
bytes: Option<Box<[u8]>>,
}
#[derive(Default)]
pub(super) struct MacroFingerprintInputs {
inputs: HashMap<usize, MacroInput>,
bytes: usize,
}
impl fmt::Debug for MacroFingerprintInputs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MacroFingerprintInputs")
.field("entries", &self.inputs.len())
.field("bytes", &self.bytes)
.finish()
}
}
impl MacroFingerprintInputs {
fn full(&self) -> bool {
self.bytes >= MAX_CACHED_BYTES || self.inputs.len() >= MAX_CACHED_MACROS
}
pub(super) fn prune_if_full(&mut self) {
if self.full() {
self.inputs.retain(|_, input| {
let live = input.body.strong_count() > 0;
if !live {
self.bytes -= input.bytes.as_deref().map_or(0, <[u8]>::len);
}
live
});
}
}
pub(super) fn hash_meaning(&mut self, meaning: &Meaning, hasher: &mut FingerprintHasher) {
let Meaning::Macro(body) = meaning else {
meaning.hash(hasher);
return;
};
if body.replacement.len() < MIN_REPLACEMENT_TOKENS {
meaning.hash(hasher);
return;
}
let key = Arc::as_ptr(body) as usize;
if let Some(input) = self.inputs.get(&key) {
if let Some(bytes) = &input.bytes {
hasher.write(bytes);
} else {
meaning.hash(hasher);
}
return;
}
if self.full() {
meaning.hash(hasher);
return;
}
// Record the complete Meaning hash, including its enum tag. Replay
// only to FingerprintHasher, whose integer, length, and string writes
// consume the same ordered bytes as the recorder's default methods.
let mut record = HashInput::default();
meaning.hash(&mut record);
let mut bytes = None;
if record.overflow {
meaning.hash(hasher);
} else {
hasher.write(&record.bytes);
if record.bytes.len() <= MAX_CACHED_BYTES - self.bytes {
self.bytes += record.bytes.len();
bytes = Some(record.bytes.into_boxed_slice());
} else {
return;
}
}
self.inputs.insert(key, MacroInput { body: Arc::downgrade(body), bytes });
}
}
#[derive(Default)]
struct HashInput {
bytes: Vec<u8>,
overflow: bool,
}
impl Hasher for HashInput {
fn write(&mut self, bytes: &[u8]) {
if !self.overflow {
if bytes.len() > MAX_RECORDED_BYTES - self.bytes.len() {
self.overflow = true;
} else {
self.bytes.extend_from_slice(bytes);
}
}
}
fn finish(&self) -> u64 {
unreachable!("recording a macro writes hash input without finishing a digest")
}
}
@@ -1,5 +1,7 @@
use super::*; use super::*;
use crate::execution::source_relocation_events::EventRelocation; use crate::execution::{
Span, source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
};
use crate::pdf_device::forms::FormContents; use crate::pdf_device::forms::FormContents;
impl State { impl State {
@@ -13,7 +15,10 @@ impl State {
// Copy only shards with a relocated macro. Ordinary format macros // Copy only shards with a relocated macro. Ordinary format macros
// and macros from the byte-identical prefix keep their allocations. // and macros from the byte-identical prefix keep their allocations.
for (index, shard) in commands.shards.iter().enumerate() { for (index, shard) in commands.shards.iter().enumerate() {
for (name, meaning) in shard.iter() { if shard.preserves_source_spans(relocation.map()) {
continue;
}
for (name, meaning) in &shard.entries {
if let Meaning::Macro(body) = meaning { if let Meaning::Macro(body) = meaning {
let relocated = relocation.relocate_macro(body)?; let relocated = relocation.relocate_macro(body)?;
if !Arc::ptr_eq(body, &relocated) { if !Arc::ptr_eq(body, &relocated) {
@@ -97,9 +102,84 @@ impl State {
} }
} }
impl CommandShard {
fn preserves_source_spans(&self, relocation: &SourceRelocation) -> bool {
let bounds = self.source_bounds.get_or_init(|| {
let mut bounds = BTreeMap::<usize, Option<usize>>::new();
for meaning in self.entries.values() {
include_meaning_bounds(&mut bounds, meaning);
}
bounds
});
bounds.get(&relocation.source()).is_none_or(|end| {
end.is_some_and(|end| relocation.preserves_prefix_through(end))
})
}
}
pub(super) fn include_meaning_bounds(
bounds: &mut BTreeMap<usize, Option<usize>>,
meaning: &Meaning,
) {
let Meaning::Macro(body) = meaning else {
return;
};
let mut include = |span: Span| {
let end = bounds.entry(span.source).or_insert(Some(0));
*end = end.filter(|_| span.start <= span.end).map(|end| end.max(span.end));
};
for part in &body.replacement {
if let Replacement::Token(token) = part {
include(token.span);
if let Some(invocation) = token.invocation {
include(invocation);
}
}
}
}
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> { fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
for token in tokens { for token in tokens {
relocation.relocate_token(token)?; relocation.relocate_token(token)?;
} }
Some(()) Some(())
} }
#[test]
fn command_bounds_track_redefinitions_and_invocation_origins() {
use crate::execution::CatCode;
let map = SourceRelocation::new(0, b"First\nx\nKeep\n", b"First\nlonger\nKeep\n").unwrap();
let name = CommandName::Control("boundtest".into());
let meaning = |invocation| {
let mut token = Token::new(
TokenKind::Character('x', CatCode::Letter),
Span { source: 0, start: 0, end: 1 },
);
token.invocation = invocation;
Meaning::Macro(Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: vec![Replacement::Token(token)],
long: false,
outer: false,
protected: false,
}))
};
let mut state = State::default();
state.define(name.clone(), meaning(None), true);
state.relocate_source(&mut EventRelocation::new(&map)).unwrap();
let before = state.clone();
let token_span = Span { source: 0, start: 8, end: 9 };
state.define(name.clone(), meaning(Some(token_span)), true);
state.relocate_source(&mut EventRelocation::new(&map)).unwrap();
let mapped = map.relocate_span(token_span).unwrap();
assert_ne!(mapped, token_span);
assert_eq!(state.meaning(&name), meaning(Some(mapped)));
assert_eq!(before.meaning(&name), meaning(None));
state.define(name, meaning(Some(Span { source: 0, start: 2, end: 1 })), true);
assert!(state.relocate_source(&mut EventRelocation::new(&map)).is_none());
}
@@ -1,7 +1,7 @@
//! Measured native storage and execution resources, not invented TeX arena words. //! Measured native storage and execution resources, not invented TeX arena words.
use super::*; use super::*;
use std::{ use std::{
collections::{BTreeMap, BTreeSet, HashSet}, collections::{BTreeSet, HashMap, HashSet, hash_map::Entry},
sync::Arc, sync::Arc,
}; };
@@ -197,6 +197,98 @@ 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(())
}
}
/// Byte counts affected by the sole changed physical source at convergence.
#[derive(Clone, Copy)]
pub(super) struct SuffixSourceResize {
pub(super) sizes: (usize, usize),
pub(super) active_at_anchor: bool,
pub(super) prefix_resource_reads: usize,
}
impl SuffixSourceResize {
pub(super) fn entry(sizes: (usize, usize)) -> Self {
Self {
sizes,
active_at_anchor: true,
prefix_resource_reads: 1,
}
}
}
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();
@@ -218,7 +310,7 @@ impl StatisticsReport {
if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() { if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() {
return None; return None;
} }
usage.resize_entry_payload(previous, current, true)?; usage.resize_source_payload(SuffixSourceResize::entry((previous, current)), true)?;
} }
debug_assert_eq!(self.text, self.phase.text()); debug_assert_eq!(self.text, self.phase.text());
Some(()) Some(())
@@ -227,26 +319,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 +332,26 @@ 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> {
self.with_source_resize(steps, boxes, entry_sizes.map(SuffixSourceResize::entry), history)
}
pub(super) fn with_source_resize(
&self,
steps: StepOffset,
boxes: BoxNodeOffset,
resize: Option<SuffixSourceResize>,
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 +361,34 @@ 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(resize) = resize {
let active = resize.active_at_anchor && usage.mouth_payload_bytes == resize.sizes.0;
if resize.active_at_anchor && !active && usage.mouth_payload_bytes != 0 {
return None;
}
usage.resize_source_payload(resize, active)?;
}
}
}
StatisticsPhase::End { usage, .. } => {
translate(usage)?;
if let Some(resize) = resize {
if resize.active_at_anchor
&& (usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0)
{
return None;
}
usage.resize_source_payload(resize, 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)
@@ -287,18 +406,17 @@ impl StatisticsReport {
} }
impl ResourceUsage { impl ResourceUsage {
fn resize_entry_payload( fn resize_source_payload(&mut self, resize: SuffixSourceResize, active: bool) -> Option<()> {
&mut self, let (previous, current) = resize.sizes;
previous: usize,
current: usize,
active: bool,
) -> Option<()> {
self.source_payload_bytes = self.source_payload_bytes.checked_sub(previous)?.checked_add(current)?; self.source_payload_bytes = self.source_payload_bytes.checked_sub(previous)?.checked_add(current)?;
if active { if active {
self.mouth_payload_bytes = self.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?; self.mouth_payload_bytes = self.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?;
} }
if let Some(host) = &mut self.host { if let Some(host) = &mut self.host {
host.rebind_entry_bytes(u64::try_from(previous).ok()?, u64::try_from(current).ok()?)?; let reads = u64::try_from(resize.prefix_resource_reads).ok()?;
let previous = u64::try_from(previous).ok()?.checked_mul(reads)?;
let current = u64::try_from(current).ok()?.checked_mul(reads)?;
host.rebind_entry_bytes(previous, current)?;
} }
Some(()) Some(())
} }
@@ -367,7 +485,7 @@ pub(super) enum Ownership {
Active, Active,
Retained, Retained,
} }
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Allocation { enum Allocation {
Macro(usize), Macro(usize),
Tokens(usize, usize), Tokens(usize, usize),
@@ -376,22 +494,27 @@ enum Allocation {
#[derive(Clone, Default)] #[derive(Clone, Default)]
struct AliasVisits { struct AliasVisits {
ordinals: BTreeMap<Allocation, usize>, ordinals: HashMap<Allocation, usize>,
visits: Vec<(Allocation, usize)>, visits: Vec<(Allocation, usize)>,
} }
impl AliasVisits { impl AliasVisits {
fn record(&mut self, allocation: Allocation) { fn record(&mut self, allocation: Allocation) -> bool {
let next = self.ordinals.len(); let next = self.ordinals.len();
let ordinal = *self.ordinals.entry(allocation).or_insert(next); let (ordinal, first) = match self.ordinals.entry(allocation) {
Entry::Occupied(entry) => (*entry.get(), false),
Entry::Vacant(entry) => (*entry.insert(next), true),
};
self.visits.push((allocation, ordinal)); self.visits.push((allocation, ordinal));
first
} }
} }
#[derive(Clone, Default)] #[derive(Clone, Default)]
pub(super) struct Collector { pub(super) struct Collector {
pub usage: ResourceUsage, pub usage: ResourceUsage,
// Alias visits keep traversal order separately from this membership index. // A tracked visit uses its ordinal index for deduplication. The
// membership sets cover normal collection and any visits before tracking.
macros: HashSet<usize>, macros: HashSet<usize>,
token_lists: BTreeSet<(usize, usize)>, token_lists: BTreeSet<(usize, usize)>,
shared_lists: Option<BTreeSet<usize>>, shared_lists: Option<BTreeSet<usize>>,
@@ -406,21 +529,14 @@ impl Collector {
} }
pub(super) fn tracking_aliases(mut self) -> Self { pub(super) fn tracking_aliases(mut self) -> Self {
self.aliases = Some(AliasVisits::default()); self.aliases.get_or_insert_with(AliasVisits::default);
self self
} }
pub(super) fn tracks_aliases(&self) -> bool {
self.aliases.is_some()
}
fn tracks_allocation(&mut self, allocation: Allocation) {
if let Some(aliases) = &mut self.aliases {
aliases.record(allocation);
}
}
fn contains(&self, allocation: Allocation) -> bool { fn contains(&self, allocation: Allocation) -> bool {
if self.aliases.as_ref().is_some_and(|aliases| aliases.ordinals.contains_key(&allocation)) {
return true;
}
match allocation { match allocation {
Allocation::Macro(address) => self.macros.contains(&address), Allocation::Macro(address) => self.macros.contains(&address),
Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)), Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)),
@@ -431,19 +547,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
@@ -458,8 +602,13 @@ impl Collector {
pub fn macro_body(&mut self, m: &Arc<Macro>) { pub fn macro_body(&mut self, m: &Arc<Macro>) {
let address = Arc::as_ptr(m) as usize; let address = Arc::as_ptr(m) as usize;
self.tracks_allocation(Allocation::Macro(address)); let first = if let Some(aliases) = &mut self.aliases {
if self.macros.insert(address) { aliases.record(Allocation::Macro(address))
&& (self.macros.is_empty() || !self.macros.contains(&address))
} else {
self.macros.insert(address)
};
if first {
self.usage.unique_macro_bodies += 1; self.usage.unique_macro_bodies += 1;
self.usage.macro_token_cells += m.prefix.len() self.usage.macro_token_cells += m.prefix.len()
+ m.parameters.iter().map(Vec::len).sum::<usize>() + m.parameters.iter().map(Vec::len).sum::<usize>()
@@ -468,11 +617,15 @@ impl Collector {
} }
pub fn shared_tokens(&mut self, t: &Arc<[Token]>) { pub fn shared_tokens(&mut self, t: &Arc<[Token]>) {
let address = t.as_ptr() as usize; let address = t.as_ptr() as usize;
if !t.is_empty() { let len = t.len();
self.tracks_allocation(Allocation::Tokens(address, t.len())); let first = if let Some(aliases) = &mut self.aliases && len != 0 {
} aliases.record(Allocation::Tokens(address, len))
if self.token_lists.insert((address, t.len())) { && !self.token_lists.contains(&(address, len))
self.usage.token_list_cells += t.len(); } else {
self.token_lists.insert((address, len))
};
if first {
self.usage.token_list_cells += len;
} }
} }
fn material(&mut self, o: Ownership) -> &mut MaterialUsage { fn material(&mut self, o: Ownership) -> &mut MaterialUsage {
@@ -608,13 +761,15 @@ impl Collector {
self.usage.active_material.ligature_work_items += b.ligature_work_items(); self.usage.active_material.ligature_work_items += b.ligature_work_items();
} }
fn visit_shared<T: ?Sized>(&mut self, list: &Arc<T>) -> bool { fn visit_shared<T: ?Sized>(&mut self, list: &Arc<T>) -> bool {
let Some(seen) = &mut self.shared_lists else {
return true;
};
let address = Arc::as_ptr(list).cast::<()>() as usize; let address = Arc::as_ptr(list).cast::<()>() as usize;
if self.shared_lists.is_some() { if let Some(aliases) = &mut self.aliases {
self.tracks_allocation(Allocation::Material(address)); aliases.record(Allocation::Material(address)) && !seen.contains(&address)
} else {
seen.insert(address)
} }
self.shared_lists
.as_mut()
.is_none_or(|seen| seen.insert(address))
} }
pub fn shared_diagnostics( pub fn shared_diagnostics(
@@ -692,6 +847,185 @@ 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 closed_source_resize_counts_each_host_read_and_leaves_other_mouths() {
let usage = ResourceUsage {
source_payload_bytes: 50,
mouth_payload_bytes: 30,
host: Some(HostResourceUsage {
resource_reads: 5,
resource_bytes_read: 100,
..HostResourceUsage::default()
}),
token_limit: 4096,
..ResourceUsage::default()
};
let resize = SuffixSourceResize {
sizes: (8, 11),
active_at_anchor: false,
prefix_resource_reads: 3,
};
let report = StatisticsReport::new(
StatisticsPhase::Shipout { before: usage.clone(), after: usage },
WriteDestination::Log,
Span::default(),
);
let adjusted = report.with_source_resize(
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some(resize), None,
).unwrap();
assert_eq!(adjusted.text, report.text);
let StatisticsPhase::Shipout { before, after } = adjusted.phase else {
unreachable!();
};
for usage in [before, after] {
assert_eq!(usage.source_payload_bytes, 53);
assert_eq!(usage.mouth_payload_bytes, 30);
let host = usage.host.unwrap();
assert_eq!(host.resource_reads, 5);
assert_eq!(host.resource_bytes_read, 109);
}
}
#[test]
fn tracked_macro_counts_share_the_ordinal_index_without_losing_visits() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: vec![Replacement::Token(token.clone())],
long: false,
outer: false,
protected: false,
});
let independent = Arc::new((*body).clone());
let tokens: Arc<[Token]> = Arc::from([token]);
let mut history = Collector::default();
let mut live = Collector::default().tracking_aliases();
for collector in [&mut history, &mut live] {
collector.macro_body(&body);
collector.shared_tokens(&tokens);
collector.macro_body(&body);
collector.macro_body(&independent);
}
assert_eq!(live.usage, history.usage);
assert_eq!(live.usage.unique_macro_bodies, 2);
assert!(live.macros.is_empty());
assert!(live.token_lists.is_empty());
let visits = &live.aliases.as_ref().unwrap().visits;
assert_eq!(visits.iter().map(|(_, ordinal)| *ordinal).collect::<Vec<_>>(), [0, 1, 0, 2]);
assert!(visits.iter().all(|(allocation, _)| {
history.contains(*allocation) && live.contains(*allocation)
}));
let mut previously_counted = history.clone().tracking_aliases();
previously_counted.macro_body(&body);
assert_eq!(previously_counted.usage, history.usage);
}
#[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());
+212
View File
@@ -87,6 +87,218 @@ 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 降低后缀会合的遍历成本
沿候选分支保留不等长事件历史的复用。旧优化版 A4 的带采样诊断
显示,一次成功接缝的记账有约 88 ms 花在两遍实时状态统计,组装
中重算最终指纹约 56 ms,比较中的状态来源换算约 26 ms。原始
作用域数据在 `target/p4-a4-suffix-proof/release-profile/`。
命令表分片保留宏替换文本和调用位置的来源范围。范围严格早于
修改位置时,沿用共享分片。涉及修改区或有异常范围时,继续逐个
换算来源。写入新定义同步扩展范围。匹配两版记账时,字段和命令
键保持逐项对应,用同一遍历顺序核对别名。首次访问和分配去重
共用同一份索引。状态指纹仍按原有命令顺序和字节序列计算。
8 项内核单测和 15 项管线回归通过。冻结 A4 原生对照在两个同配置
优化构建上各跑 3 次,全部与各自独立全量一致,且两版 PDF 指纹相同。
两次成功接缝都跳过 20,618 步。保留记账分别从 64.38 降至 18.65 ms、
从 38.73 降至 18.30 ms。状态比较仍约 30–32 ms,组装仍约 58–64 ms。
阶段原始数据在 `target/p4-a4-shard-relocation/a4-main-only/`。
同机 Edge 实测主文件、子文件各 30 次。主文件 29 次各跳过
20,618 步,子文件仍执行后缀。全部 60 次的 PDF、SVG 和来源映射
指纹与主线基线逐项一致。进程峰值 RSS 为 603,116 KiB。
| A4 热编辑 | 主线可见 p50 / p95 | 上一候选 p50 / p95 | 本轮候选 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 325.5 / 512.1 ms | 285.4 / 497.4 ms |
| 子文件正文 | 184.1 / 241.5 ms | 185.4 / 266.7 ms | 188.4 / 337.5 ms |
本轮候选继续保存在 `perf/retained-history-suffix`。浏览器 100 ms
门槛仍开放。性能记录、构建指纹和逐次结果在
`target/p4-a4-shard-relocation/`。下一轮继续压缩仍占主要时间的
状态指纹,并认证子文件耗尽后的前后缀资源读证据。
## 2026-12-02 复用宏的指纹输入
状态指纹保持现有字段顺序、命令顺序与哈希输入。状态声明与专用
指纹遍历使用同一份字段清单,通用 `Hash` 继续由原有字段派生。
命令表的共享快照可复用完整宏含义写入的字节。缓存使用弱引用保留
分配身份,宏变更时按新分配计算。每个共享命令表的缓存受字节量与
条目数限制。锁占用及超限场景走原计算路径。格式镜像和对外执行
记录仍使用原来的字段。每套共享命令表最多保留 16 MiB 哈希字节
和 8,192 个宏条目。
7 项内核单测和 15 项管线回归通过。两版优化构建的三次冻结 A4
编辑全部与独立全量一致,六个输入和输出指纹逐项相同。两次成功
接缝仍各跳过 20,618 步,组装从 68.34、55.52 ms 降到 46.33、
37.34 ms。三次原生端到端时间有升有降。精确指纹与阶段数据在
`target/p4-a4-fingerprint-proof/direct-comparison.md`。
同机 Edge 对主文件和子文件各采样 30 次。全部 60 次的 PDF、SVG
和来源映射与上一候选逐项一致。主文件 29 次各跳过 20,618 步,
子文件仍执行后缀。服务峰值 RSS 为 619,944 KiB,上一候选为
603,116 KiB。
| A4 热编辑 | 主线可见 p50 / p95 | 上一候选 p50 / p95 | 本轮候选 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 285.4 / 497.4 ms | 264.8 / 493.9 ms |
| 子文件正文 | 184.1 / 241.5 ms | 188.4 / 337.5 ms | 196.8 / 329.7 ms |
100 ms 门槛仍开放。候选保存在 `perf/retained-history-suffix`。
此处两版均为 opt-level 1。实际样本和构建清单在
`target/p4-a4-fingerprint-proof/`。
## 2026-12-02 默认发布优化与页面呈现
用提交 `ed105bd` 构建 opt-level 3,内核和引擎均核对了实际编译
参数。15 项定向管线回归通过。与同一提交的 opt-level 1 做冻结
A4 三次原生对照。各次均与独立全量的执行、资源、PDF、SVG、
来源映射和生成文件相同,两种构建的实际状态指纹与执行步数也
逐项一致。两次成功复用各跳过 20,618 步。内核接缝耗时从
94.42 和 82.39 ms 降至 93.83 和 81.57 ms,原生端到端有升有降。
原始对照在 `target/p4-a4-release-opt3/a4-main-only/`。
Edge 同机、同格式和资源,主文件与子文件各 30 次。原有绘制确认
计时与上一批一致,60 次的 PDF、SVG、来源映射、变更页逐项相同。
主文件 29 次各跳过 20,618 步,子文件继续执行后缀。
进程峰值 RSS 为 618,988 KiB。
| A4 热编辑 | Opt1 可见 p50 / p95 | Opt3 可见 p50 / p95 | Opt3 呈现诊断 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 264.8 / 493.9 ms | 249.8 / 287.1 ms | 248.5 / 294.7 ms |
| 子文件正文 | 196.8 / 329.7 ms | 180.9 / 214.1 ms | 184.1 / 223.8 ms |
呈现诊断从浏览器读取带当前修订标识的实际替换页时间。两组 30 次
都有有效时间。浏览器报告呈现的中位时间比两帧确认晚 5.7 和
3.4 ms,两种记录均高于 100 ms。正式门槛仍开放。原生内核收益
小于浏览器 p95 差额,不能把整段差额归于编译级别。构建、环境与
逐次记录在 `target/p4-a4-release-opt3/`。
[Element Timing 规范草案](https://w3c.github.io/element-timing/)
## 2026-12-02 已关闭子文件的后缀复用
已完成读取的一个按字节分行子文件可在入口不变时参与后缀复用。
内核核对唯一源编号、其他来源与活动扫描器,并按实际文件变化
迁移来源坐标。宿主验证同一个规范路径与两版内容版本,核对
一次正文读取及已执行的大小查询,检查后缀没有新的子文件访问,
并重放真实效果。源码总字节按一次变动更新,宿主读取总量按
实际读取次数更新。已关闭的子文件不进入活动扫描器字节数。
新用例包含两次实际大小查询、一次正文读取和后缀引用子文件内
定义。连同入口长度变化和 XeTeX 整行编辑在内的五项管线测试
与两项记账单测均通过。变化后的 PDF、SVG、页面、日志、来源映射及宿主资源轨迹
均与独立全量一致。
冻结 A4 只改子文件的三次实测也与各自独立全量逐项相同,每次
都读取该子文件五次,流式读取为零。第一次执行 78,475 步,后两次
各跳过 20,618 步后缀,实际执行 57,863 和 57,857 步。
子文件 185 → 188 → 185 字节,最终源码字节相应 ±3,宿主读量
±15,最终扫描器字节为零,宿主读取次数保持 93。当前样本使用
诊断构建。原始核对在 `target/p4-child-source-splice/a4-child-only/`。
浏览器 100 ms 条件仍待在发布构建上实测。
## 2026-12-02 子文件发布实测与响应残差
提交 `e4d6e04` 的 opt-level 3 发布构建通过五项定向管线测试。
原样 A4 三次只改子文件均与独立全量一致,且与诊断构建的实际
指纹、来源、输出和步数相同。后两次各跳过 20,618 步。
成功接缝的内核检查和组装共 62.06、59.49 ms。原生逐次证据在
`target/p4-a4-child-release/a4-child-only/`。
Edge 仍保留原有确认计时,同时记录实际替换页呈现时间,主、子文件
各 30 次。全部 60 次的 PDF、SVG、来源映射与上一 opt-level 3 基线
逐项一致。主文件 29 次、子文件 30 次各跳过 20,618 步。
子文件实际执行中位数从 78,489 降到 57,871,执行耗时中位数从
84.2 ms 升至 103.2 ms,复用的证明成本仍需降低。
| A4 热编辑 | 上一版可见 p50 / p95 | 子文件复用版可见 p50 / p95 | 本轮呈现诊断 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 249.8 / 287.1 ms | 212.4 / 246.0 ms | 214.5 / 248.1 ms |
| 子文件正文 | 180.9 / 214.1 ms | 195.9 / 222.3 ms | 204.9 / 233.9 ms |
同一隔离服务、同一套真实子文件编辑,Linux 与 Windows 的 curl
各测六次复用连接的热响应。对应 SVG 字节相同。扣除处理与队列
耗时后,从发送请求至响应头的中位残差分别为 2.46 和 1.81 ms。
同批 Edge 子文件中位残差为 35.15 ms。直连试验的两端残差均低于 3 ms,
Edge 的余量需继续按浏览器请求和响应调度分解。
峰值 RSS 为 618,732 KiB。100 ms 门槛仍开放。
原始浏览器、构建和直连对照在 `target/p4-a4-child-release/`。
## 2026-12-02 共享命令分片的记账
事件历史与执行状态的跨接缝证明仍核对分配别名。两版共享同一
命令分片时只走一次已共享绑定,再从该遍历的别名序号出发分别
统计两版独立分片和活动状态。单测证明两版宏值及计数完全相等时,
跨分片别名指向另一个同值宏仍会拒绝复用。五项内核单测及五项管线
回归通过,覆盖重复子文件读取、盒计数、不同长度的事件历史、
连续检查点和 XeTeX UTF-16 整行编辑。验证原始记录在
`target/p4-shared-shard-accounting/`。
`ccb278f` 的 opt-level 3 发布构建完成。与 `e4d6e04` 同配置的冻结
A4 子文件编辑各三次,全部通过独立全量核验。两版的状态指纹、PDF、
SVG、aux 和实际读取轨迹一致,后两次均各跳过 20,618 步。
两次记账分别由 21.30 降到 15.25 ms、由 21.03 降到 20.40 ms。
前一批较空闲的基线分别为 19.17、19.44 ms。收益集中在其中一次。
原生对照在 `target/p4-a4-shared-accounting-release/a4-child-only/`。
本轮启动项目 Web `e14b7aa` 的文件树和编辑页,使用 Windows
Edge 无头浏览器输入真实编辑。以前的 60 次样本来自内核自带简版
编辑页,可比较同一输入的输出。新版 60 次 PDF、SVG、来源映射
和变更页与其逐项一致。主文件 29 次、子文件 30 次各跳过
20,618 步。
| A4 项目 Web 热编辑 | 样本 | 可见确认 p50 / p95 | 替换页首帧 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 30 | 205.3 / 511.8 ms | 204.4 / 512.1 ms |
| 子文件正文 | 30 | 196.5 / 345.2 ms | 203.4 / 351.4 ms |
Edge 的网络记录匹配全部 60 次请求,全部复用连接。发完请求
至收到响应头(扣除服务处理和排队)的中位残差为主文件 36.97 ms、
子文件 36.74 ms。发送和解析响应头各不足 0.2 ms(中位数),
响应体完成约 1 ms。一次主文件编辑收到响应后约 300.5 ms 才
确认呈现。运行前后 WSL 的整机 I/O 压力 10 秒均值分别为
6.09% 和 11.24%。内核服务峰值 RSS 为 619,024 KiB。100 ms
条件仍开放。完整输入、输出与时序在
`target/p4-a4-shared-accounting-release/edge-a4-6tx6u3sb/`。
## 2026-12-02 XeTeX 整行编辑复用 ## 2026-12-02 XeTeX 整行编辑复用
XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他 XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他
+118 -18
View File
@@ -1,5 +1,5 @@
//! Reuse a recorded entry prefix only after validating the current job host. //! Reuse a recorded entry prefix only after validating the current job host.
use super::checkpoint_probe::{Call, RecordingHost}; use super::checkpoint_probe::{Call, ClosedSourceUsageOffset, RecordingHost, closed_source_reads};
use super::*; use super::*;
#[cfg(test)] #[cfg(test)]
use std::fs; use std::fs;
@@ -10,7 +10,7 @@ use std::{
time::Instant, time::Instant,
}; };
use texrra_tex_core::{ use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport}, execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport},
resources::{ResourceKind, ResourceLookup, ResourceReadRange}, resources::{ResourceKind, ResourceLookup, ResourceReadRange},
}; };
#[cfg(test)] #[cfg(test)]
@@ -59,9 +59,17 @@ struct CompletedExecution {
result: Arc<RevisionExecution>, result: Arc<RevisionExecution>,
guard: PrefixInputGuard, guard: PrefixInputGuard,
calls: Arc<[Call]>, calls: Arc<[Call]>,
trace: ResourceTrace,
settled: BTreeMap<usize, SettledCheckpoint>, settled: BTreeMap<usize, SettledCheckpoint>,
} }
struct ClosedSourceSuffix {
source_id: usize,
prefix_resource_reads: usize,
version: ResourceVersion,
usage: ClosedSourceUsageOffset,
}
struct SettledCheckpoint { struct SettledCheckpoint {
entry: Arc<EntryCheckpoint>, entry: Arc<EntryCheckpoint>,
host: crate::native_job::ReplayBoundary, host: crate::native_job::ReplayBoundary,
@@ -417,6 +425,7 @@ impl<'a> CapturedEntries<'a> {
prior: &SettledCheckpoint, prior: &SettledCheckpoint,
completed: &CompletedExecution, completed: &CompletedExecution,
end_statistics: Option<&StatisticsReport>, end_statistics: Option<&StatisticsReport>,
closed_source: Option<&ClosedSourceSuffix>,
host: &mut RecordingHost, host: &mut RecordingHost,
cancellation: &Cancellation, cancellation: &Cancellation,
) -> Result<(), String> { ) -> Result<(), String> {
@@ -426,9 +435,10 @@ impl<'a> CapturedEntries<'a> {
let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len(); let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len();
let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1); let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1);
let mut later = [const { None }; SOURCE_INTERVALS]; let mut later = [const { None }; SOURCE_INTERVALS];
// Untranslated live continuations and their source intervals still // Carried checkpoints still carry the donor's scanner and source
// refer to the old entry when its length changed. // allocations. An exhausted child edit also changes that history.
if previous_bytes == bytes if closed_source.is_none()
&& previous_bytes == bytes
&& let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) && let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution)
{ {
// Keep the deepest compatible settled continuation per source interval. // Keep the deepest compatible settled continuation per source interval.
@@ -451,7 +461,7 @@ impl<'a> CapturedEntries<'a> {
let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { let Some(calls) = completed.calls.get(replayed..anchor.call_count) else {
continue; continue;
}; };
host.replay_suffix(calls, end_statistics, cancellation)?; host.replay_suffix(calls, end_statistics, None, cancellation)?;
replayed = anchor.call_count; replayed = anchor.call_count;
if anchor.host == host.files().replay_boundary() { if anchor.host == host.files().replay_boundary() {
let regular = CaptureSlots { let regular = CaptureSlots {
@@ -464,7 +474,16 @@ impl<'a> CapturedEntries<'a> {
self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host);
} }
} }
host.replay_suffix(&completed.calls[replayed..], end_statistics, cancellation)?; host.replay_suffix(
&completed.calls[replayed..], end_statistics, closed_source.map(|child| child.usage),
cancellation,
)?;
if let Some(child) = closed_source {
let (trace, calls) = host.prefix().ok_or("child suffix host observations are unavailable")?;
if closed_source_reads(&child.version, trace, calls) != Some(child.prefix_resource_reads) {
return Err("completed suffix observed the changed child again".into());
}
}
completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string())
} }
@@ -521,17 +540,18 @@ impl<'a> CapturedEntries<'a> {
recording.generated_outputs(), recording.generated_outputs(),
self.initial?, self.initial?,
).ok()?; ).ok()?;
Some(guard) Some((guard, trace.clone()))
}).flatten(); }).flatten();
let mut calls = recording.into_calls()?; let mut calls = recording.into_calls()?;
if completion.is_none() { if completion.is_none() {
calls.truncate(replay_count); calls.truncate(replay_count);
} }
let calls = Arc::<[Call]>::from(calls); let calls = Arc::<[Call]>::from(calls);
let completion = completion.map(|guard| Arc::new(CompletedExecution { let completion = completion.map(|(guard, trace)| Arc::new(CompletedExecution {
result: result.clone(), result: result.clone(),
guard, guard,
calls: calls.clone(), calls: calls.clone(),
trace,
settled: self.settled, settled: self.settled,
})); }));
Some(Arc::new(CheckpointSet { Some(Arc::new(CheckpointSet {
@@ -996,23 +1016,38 @@ impl SelectedCheckpoint {
let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else { let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else {
return CheckpointDecision::Continue; return CheckpointDecision::Continue;
}; };
let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| { let Some((completed, old, execution, layout, closed_source)) = suffixes.clone().find_map(|completed| {
let old = completed.settled.get(&page)?; let old = completed.settled.get(&page)?;
let host_matches = measure(&mut timings.suffix_host_validation, timed, || { let closed_source = measure(&mut timings.suffix_host_validation, timed, || {
old.call_count == new.call_count if old.call_count != new.call_count {
&& new.host.matches_for_suffix(&old.host)
&& can_replay_completed_suffix(completed, request, host.files())
});
if !host_matches {
return None; return None;
} }
if new.host.matches_for_suffix(&old.host)
&& can_replay_completed_suffix(completed, request, host.files())
{
return Some(None);
}
let change = entry.closed_source_change(&old.entry, &completed.result.execution)?;
prove_closed_source_suffix(change, old, new, completed, request, host)
.map(Some)
})?;
let kernel_timings = timed.then_some(&mut timings.suffix_kernel); let kernel_timings = timed.then_some(&mut timings.suffix_kernel);
let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || { let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || {
if let Some(child) = &closed_source {
entry.splice_settled_closed_source_suffix_observed(
&old.entry,
&completed.result.execution,
child.source_id,
child.prefix_resource_reads,
kernel_timings,
)
} else {
entry.splice_settled_suffix_observed( entry.splice_settled_suffix_observed(
&old.entry, &completed.result.execution, kernel_timings, &old.entry, &completed.result.execution, kernel_timings,
) )
}
})?; })?;
Some((completed, old, execution, layout)) Some((completed, old, execution, layout, closed_source))
}) else { }) else {
return CheckpointDecision::Continue; return CheckpointDecision::Continue;
}; };
@@ -1024,7 +1059,8 @@ impl SelectedCheckpoint {
}); });
let replayed = measure(&mut timings.suffix_host_replay, timed, || { let replayed = measure(&mut timings.suffix_host_replay, timed, || {
captures.replay_settled_suffix( captures.replay_settled_suffix(
page, &entry, old, completed, end_statistics, host, &cancellation, page, &entry, old, completed, end_statistics,
closed_source.as_ref(), host, &cancellation,
) )
}); });
if let Err(error) = replayed { if let Err(error) = replayed {
@@ -1090,6 +1126,61 @@ fn can_replay_completed_suffix(
completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok() completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok()
} }
fn prove_closed_source_suffix(
change: ClosedSourceChange<'_>,
old: &SettledCheckpoint,
current: &SettledCheckpoint,
completed: &CompletedExecution,
request: &CompileRequest,
host: &RecordingHost<'_>,
) -> Option<ClosedSourceSuffix> {
let path = Path::new(change.name);
let guard = &completed.guard;
let next_project = request.project.as_deref()?;
if path == guard.entry || !guard.immutable.contains(path) || guard.generated.contains(path)
|| !guard.project.immutable_paths().eq(next_project.immutable_paths())
{
return None;
}
// The child route cannot simultaneously relocate or replace the entry.
if guard.project.file(&guard.entry)?.version != next_project.file(&guard.entry)?.version {
return None;
}
let previous = &guard.project.file(path)?.version;
let current_version = &next_project.file(path)?.version;
if previous == current_version || previous.path != path || current_version.path != path
|| previous.bytes != u64::try_from(change.previous_bytes).ok()?
|| current_version.bytes != u64::try_from(change.current_bytes).ok()?
{
return None;
}
let (trace, calls) = host.prefix()?;
if calls.len() != current.call_count || trace.project_version.as_ref() != Some(next_project.version()) {
return None;
}
let prefix_resource_reads = closed_source_reads(
previous, old.host.trace_for_suffix(), completed.calls.get(..old.call_count)?,
)?;
// In the donor's whole job, the only observations of the child must
// be the reads already present at the splice. The live prefix has
// actually made the same count of allowed observations of its new version.
if closed_source_reads(previous, &completed.trace, &completed.calls)? != prefix_resource_reads
|| closed_source_reads(current_version, trace, calls)? != prefix_resource_reads
|| !current.host.matches_for_closed_source_suffix(&old.host, previous, current_version)
{
return None;
}
let files = host.files();
let project = guard.verify_project_with_closed_source(request, Some(path)).ok()?;
guard.verify_host(project, files.replay_world(), files.preparation()).ok()?;
Some(ClosedSourceSuffix {
source_id: change.source_id,
prefix_resource_reads,
version: current_version.clone(),
usage: ClosedSourceUsageOffset::new(previous.bytes, current_version.bytes, prefix_resource_reads)?,
})
}
fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> { fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
if previous == current { if previous == current {
return None; return None;
@@ -1317,6 +1408,14 @@ impl PrefixInputGuard {
fn verify_project<'a>( fn verify_project<'a>(
&self, &self,
request: &'a CompileRequest, request: &'a CompileRequest,
) -> Result<&'a ProjectSnapshot, String> {
self.verify_project_with_closed_source(request, None)
}
fn verify_project_with_closed_source<'a>(
&self,
request: &'a CompileRequest,
closed_source: Option<&Path>,
) -> Result<&'a ProjectSnapshot, String> { ) -> Result<&'a ProjectSnapshot, String> {
let old = &self.original; let old = &self.original;
if old.input != request.input if old.input != request.input
@@ -1354,6 +1453,7 @@ impl PrefixInputGuard {
let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and( let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and(
|(old, new)| { |(old, new)| {
old.version == new.version old.version == new.version
|| closed_source == Some(path.as_path())
|| self.nested_source.as_ref().is_some_and(|source| &source.path == path) || self.nested_source.as_ref().is_some_and(|source| &source.path == path)
|| self.immutable_sizes.get(path) == Some(&new.version.bytes) || self.immutable_sizes.get(path) == Some(&new.version.bytes)
|| self.immutable_stream_prefixes.get(path).is_some_and(|&end| { || self.immutable_stream_prefixes.get(path).is_some_and(|&end| {
+82
View File
@@ -42,6 +42,75 @@ pub(super) struct RebindableSourceObservations {
pub(super) size: Option<u64>, pub(super) size: Option<u64>,
} }
#[derive(Clone, Copy)]
pub(super) struct ClosedSourceUsageOffset {
previous: u64,
current: u64,
}
impl ClosedSourceUsageOffset {
pub(super) fn new(previous: u64, current: u64, reads: usize) -> Option<Self> {
let reads = u64::try_from(reads).ok()?;
Some(Self {
previous: previous.checked_mul(reads)?,
current: current.checked_mul(reads)?,
})
}
}
/// Return the entire byte-read count of a closed immutable child, including
/// typed size queries. Every other observation of the child rules out reuse.
pub(super) fn closed_source_reads(
version: &ResourceVersion,
trace: &ResourceTrace,
calls: &[Call],
) -> Option<usize> {
let path = &version.path;
if trace.stream_reads.iter().any(|read| &read.path == path)
|| trace.file_modifications.iter().any(|item| &item.path == path)
|| trace.generated_lookups.iter().any(|lookup| &lookup.target == path)
|| trace.format_input_bindings.iter().any(|(old, current)| old == path || current == path)
|| trace.read_errors.iter().any(|(read, _)| read == path)
|| !trace.namespace_capture_failures.is_empty()
{
return None;
}
let mut sources = 0usize;
let mut sizes = 0usize;
for call in calls {
match call {
Call::ReadSource(source) => {
if let Ok(read) = &source.expected
&& &read.path == path
{
if read != version {
return None;
}
sources += 1;
}
}
Call::FileSize(size) if size.read.as_ref().is_some_and(|read| &read.path == path) => {
// A size query can have been replayed from an equal-sized
// earlier source. Its exact path and numeric result are
// evidence, while the actual trace authenticates the bytes.
if call.observed_file_size() != Some((path.as_path(), version.bytes)) {
return None;
}
sizes += 1;
}
_ => {}
}
}
let count = sources.checked_add(sizes)?;
let mut actual = trace.reads.iter().filter(|read| &read.path == path);
if sources != 1 || actual.clone().count() != count || !actual.all(|read| read == version) {
return None;
}
let mut lookups = trace.lookups.iter().filter(|lookup| lookup.resolved.as_ref() == Some(path));
(lookups.clone().count() == count && lookups.all(|item| item.kind == ResourceKind::Tex))
.then_some(count)
}
impl Call { impl Call {
pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> { pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> {
let Self::FileSize(read) = self else { return None }; let Self::FileSize(read) = self else { return None };
@@ -178,6 +247,7 @@ impl<'a> RecordingHost<'a> {
&mut self, &mut self,
calls: &[Call], calls: &[Call],
end_statistics: Option<&StatisticsReport>, end_statistics: Option<&StatisticsReport>,
closed_source: Option<ClosedSourceUsageOffset>,
cancellation: &Cancellation, cancellation: &Cancellation,
) -> Result<(), String> { ) -> Result<(), String> {
let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?; let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?;
@@ -196,6 +266,18 @@ impl<'a> RecordingHost<'a> {
Call::EndStatistics(Arc::new(translated.clone())) Call::EndStatistics(Arc::new(translated.clone()))
} }
} }
Call::ResourceUsage(read) if closed_source.is_some_and(|bytes| bytes.previous != bytes.current) => {
let bytes = closed_source.expect("checked closed source adjustment");
let mut observed = read.observed.clone();
if let Some(usage) = &mut observed {
usage.rebind_entry_bytes(bytes.previous, bytes.current)
.ok_or("invalid replayed child resource usage")?;
}
Call::ResourceUsage(Arc::new(ResourceUsageRead {
observed,
entry_bytes: read.entry_bytes,
}))
}
call => call.clone(), call => call.clone(),
}; };
call.replay(self.files, None)?; call.replay(self.files, None)?;
+36
View File
@@ -169,6 +169,42 @@ impl ReplayBoundary {
pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool { pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool {
self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state
} }
pub(super) fn trace_for_suffix(&self) -> &texrra_tex_core::resources::ResourceTrace {
&self.state.trace
}
/// The caller proves that all reads of this canonical path are the
/// closed source or its typed size queries, and that none are in the tail.
pub(super) fn matches_for_closed_source_suffix(
&self,
prior: &Self,
previous: &ResourceVersion,
current: &ResourceVersion,
) -> bool {
if self.entry_bytes.is_none() || self.entry_bytes != prior.entry_bytes {
return false;
}
let ReplayState {
inputs, outputs, next_handle, columns, terminal_enabled, generated_reads,
generated_before, generated_written, trace, stream_events,
} = &self.state;
let old = &prior.state;
if inputs != &old.inputs || outputs != &old.outputs || next_handle != &old.next_handle
|| columns != &old.columns || terminal_enabled != &old.terminal_enabled
|| generated_reads != &old.generated_reads || generated_before != &old.generated_before
|| generated_written != &old.generated_written || stream_events != &old.stream_events
{
return false;
}
let mut old_trace = old.trace.clone();
for read in &mut old_trace.reads {
if read == previous {
*read = current.clone();
}
}
*trace == old_trace
}
} }
#[derive(PartialEq, Eq)] #[derive(PartialEq, Eq)]
+137 -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,134 @@ 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]
fn settled_suffix_reuses_an_exhausted_child_and_adjusts_repeated_resource_reads() {
use texrra_tex_core::execution::{Event, ResourceUsage, StatisticsPhase};
let cwd = directory("closed-child-suffix");
let child = cwd.join("chapter.tex");
let body = r"
\tracingstats=1
\shipout\hbox{Cover}\relax
\begingroup
\count0=\pdffilesize{chapter.tex}\relax
\count0=\pdffilesize{chapter.tex}\relax
\endgroup
\input chapter.tex
\shipout\hbox{Page with \childtext}\relax
\shipout\hbox{Suffix with \childtext}\relax
\endinput\shipout\hbox{Final}\relax\end
";
let child_source = |comment| format!("% {comment}\n\\def\\childtext{{Body}}\n").into_bytes();
let previous_bytes = child_source("old");
let current_bytes = child_source("the expanded frozen comment");
let extra = current_bytes.len() - previous_bytes.len();
let end_usage = |result: &CompiledDocument| -> ResourceUsage {
let Some(Event::Statistics(report)) = result.execution.execution.events.last() else {
panic!("missing final resource report");
};
let StatisticsPhase::End { usage, .. } = &report.phase else {
panic!("expected final resource report");
};
usage.clone()
};
let mut definition = atomic_definition(&cwd, 1, body);
definition.files.insert(child.clone(), Arc::from(previous_bytes));
let project = ProjectSnapshot::new(definition).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let original = session.compile(request.clone().with_project(project.clone())).unwrap();
let project = project.with_file_edits(
2, [(child.clone(), Arc::from(current_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.reused_suffix_steps > 0, "{work:?}");
let actual_child_reads = updated.resources.trace.reads.iter().filter(|read| read.path == child).count();
assert_eq!(actual_child_reads, 3);
let before = end_usage(&original);
let after = end_usage(&updated);
assert_eq!(after.source_payload_bytes, before.source_payload_bytes + extra);
assert_eq!(after.mouth_payload_bytes, before.mouth_payload_bytes);
assert_eq!(
after.host.unwrap().resource_bytes_read,
before.host.unwrap().resource_bytes_read + (actual_child_reads * extra) as u64,
);
assert_ne!(updated.source_map.pages, original.source_map.pages);
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.resources.stream_io, full.resources.stream_io);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.pages, full.pages);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().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");