Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55c497dccd | ||
|
|
ed105bdd39 | ||
|
|
c4003c8dad | ||
|
|
1ff049737f |
No files matched your search
@@ -1,20 +1,85 @@
|
||||
//! Deduplicate execution reads before producing the ordered public evidence.
|
||||
use super::Dependency;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::{
|
||||
collections::{BTreeSet, HashMap},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
pub(super) struct DependencyReads {
|
||||
byte_catcodes: [u64; 4],
|
||||
other: HashSet<Dependency>,
|
||||
const INITIAL_EPOCH: u32 = 1;
|
||||
const DISABLED_EPOCH: u32 = u32::MAX;
|
||||
|
||||
/// Last observation of each dependency, in the completed read set's order.
|
||||
/// The clock records capture boundaries and has no public execution semantics.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) struct DependencyEvidence(Option<Arc<[u32]>>);
|
||||
|
||||
impl DependencyEvidence {
|
||||
pub(super) fn new(epochs: Vec<u32>) -> Self {
|
||||
Self(Some(epochs.into()))
|
||||
}
|
||||
|
||||
pub(super) fn epochs(&self) -> Option<&[u32]> {
|
||||
self.0.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
// The same execution can be captured at different boundaries.
|
||||
impl PartialEq for DependencyEvidence {
|
||||
fn eq(&self, _other: &Self) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Eq for DependencyEvidence {}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct DependencyReads {
|
||||
pub(super) current_epoch: u32,
|
||||
byte_catcodes: [u32; 256],
|
||||
other: HashMap<Dependency, u32>,
|
||||
}
|
||||
|
||||
impl Default for DependencyReads {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
current_epoch: INITIAL_EPOCH,
|
||||
byte_catcodes: [0; 256],
|
||||
other: HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for DependencyReads {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.other.len() == other.other.len()
|
||||
&& self
|
||||
.byte_catcodes
|
||||
.iter()
|
||||
.zip(&other.byte_catcodes)
|
||||
.all(|(&left, &right)| (left == 0) == (right == 0))
|
||||
&& self.other.keys().all(|key| other.other.contains_key(key))
|
||||
}
|
||||
}
|
||||
impl Eq for DependencyReads {}
|
||||
|
||||
impl DependencyReads {
|
||||
pub(super) fn epoch(&self) -> Option<u32> {
|
||||
(self.current_epoch != DISABLED_EPOCH).then_some(self.current_epoch)
|
||||
}
|
||||
|
||||
pub(super) fn advance_epoch(&mut self) {
|
||||
self.current_epoch = self.current_epoch.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(super) fn disable_epochs(&mut self) {
|
||||
self.current_epoch = DISABLED_EPOCH;
|
||||
}
|
||||
|
||||
pub(super) fn catcode(&mut self, character: char) {
|
||||
let index = character as usize;
|
||||
if let Some(bits) = self.byte_catcodes.get_mut(index / 64) {
|
||||
*bits |= 1 << (index % 64);
|
||||
if let Some(epoch) = self.byte_catcodes.get_mut(character as usize) {
|
||||
*epoch = self.current_epoch;
|
||||
} else {
|
||||
self.other.insert(Dependency::CatCode(character));
|
||||
self.other
|
||||
.insert(Dependency::CatCode(character), self.current_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,50 +87,93 @@ impl DependencyReads {
|
||||
if let Dependency::CatCode(character) = dependency {
|
||||
self.catcode(character);
|
||||
} else {
|
||||
self.other.insert(dependency);
|
||||
self.other.insert(dependency, self.current_epoch);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn observed_statistics(&self) -> bool {
|
||||
self.other.contains(&Dependency::ResourceStatistics)
|
||||
self.other.contains_key(&Dependency::ResourceStatistics)
|
||||
}
|
||||
|
||||
pub(super) fn is_subset(&self, other: &Self) -> bool {
|
||||
self.byte_catcodes
|
||||
.iter()
|
||||
.zip(other.byte_catcodes)
|
||||
.all(|(&bits, permitted)| bits & !permitted == 0)
|
||||
&& self.other.is_subset(&other.other)
|
||||
self.other.len() <= other.other.len()
|
||||
&& self
|
||||
.byte_catcodes
|
||||
.iter()
|
||||
.zip(&other.byte_catcodes)
|
||||
.all(|(&seen, &permitted)| seen == 0 || permitted != 0)
|
||||
&& self.other.keys().all(|key| other.other.contains_key(key))
|
||||
}
|
||||
|
||||
/// Extend a completed execution with observations made only in the new prefix.
|
||||
/// The caller has already checked that the prefix keeps all old observations.
|
||||
pub(super) fn extend_ordered_delta(&self, prior: &Self, into: &mut BTreeSet<Dependency>) {
|
||||
if self.byte_catcodes != prior.byte_catcodes {
|
||||
into.extend(byte_catcode_dependencies(std::array::from_fn(|index| {
|
||||
self.byte_catcodes[index] & !prior.byte_catcodes[index]
|
||||
})));
|
||||
for (index, (&seen, &old)) in self
|
||||
.byte_catcodes
|
||||
.iter()
|
||||
.zip(&prior.byte_catcodes)
|
||||
.enumerate()
|
||||
{
|
||||
if seen != 0 && old == 0 {
|
||||
into.insert(Dependency::CatCode(char::from(index as u8)));
|
||||
}
|
||||
}
|
||||
if self.other.len() != prior.other.len() {
|
||||
into.extend(self.other.difference(&prior.other).cloned());
|
||||
into.extend(
|
||||
self.other
|
||||
.keys()
|
||||
.filter(|key| !prior.other.contains_key(*key))
|
||||
.cloned(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
|
||||
pub(super) fn observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
|
||||
self.other
|
||||
.iter()
|
||||
.map(|(key, &epoch)| (key.clone(), epoch))
|
||||
.chain(byte_catcode_observations(
|
||||
self.byte_catcodes.iter().copied(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(super) fn into_evidence(
|
||||
self,
|
||||
meanings: impl Iterator<Item = (Dependency, u32)>,
|
||||
) -> (BTreeSet<Dependency>, DependencyEvidence) {
|
||||
let has_captures = self.epoch().is_some_and(|epoch| epoch > INITIAL_EPOCH);
|
||||
let observations = self
|
||||
.other
|
||||
.into_iter()
|
||||
.chain(byte_catcode_dependencies(self.byte_catcodes))
|
||||
.collect()
|
||||
.chain(byte_catcode_observations(self.byte_catcodes.into_iter()))
|
||||
.chain(meanings);
|
||||
if !has_captures {
|
||||
return (
|
||||
observations.map(|(read, _)| read).collect(),
|
||||
DependencyEvidence::default(),
|
||||
);
|
||||
}
|
||||
|
||||
let mut ordered: Vec<_> = observations.collect();
|
||||
ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae)));
|
||||
// A diagnostic can record a meaning also present in the lookup cache.
|
||||
ordered.dedup_by(|a, b| a.0 == b.0);
|
||||
let (reads, epochs) = ordered.into_iter().unzip();
|
||||
(reads, DependencyEvidence::new(epochs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
|
||||
self.into_evidence(std::iter::empty()).0
|
||||
}
|
||||
}
|
||||
|
||||
fn byte_catcode_dependencies(bits: [u64; 4]) -> impl Iterator<Item = Dependency> {
|
||||
(0..=u8::MAX)
|
||||
.filter(move |&index| {
|
||||
let index = usize::from(index);
|
||||
bits[index / 64] & (1 << (index % 64)) != 0
|
||||
})
|
||||
.map(|index| Dependency::CatCode(char::from(index)))
|
||||
fn byte_catcode_observations(
|
||||
epochs: impl Iterator<Item = u32>,
|
||||
) -> impl Iterator<Item = (Dependency, u32)> {
|
||||
epochs.enumerate().filter_map(|(index, epoch)| {
|
||||
(epoch != 0).then(|| (Dependency::CatCode(char::from(index as u8)), epoch))
|
||||
})
|
||||
}
|
||||
|
||||
impl Extend<Dependency> for DependencyReads {
|
||||
@@ -102,6 +210,40 @@ mod tests {
|
||||
assert_eq!(reads, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn evidence_keeps_the_last_read_across_capture_boundaries() {
|
||||
let mut reads = DependencyReads::default();
|
||||
reads.extend([
|
||||
Dependency::CatCode('A'),
|
||||
Dependency::CatCode('文'),
|
||||
Dependency::EndLineChar,
|
||||
Dependency::EscapeChar,
|
||||
]);
|
||||
let original = reads.clone();
|
||||
let boundary_epoch = reads.epoch().unwrap();
|
||||
reads.advance_epoch();
|
||||
reads.extend([
|
||||
Dependency::CatCode('A'),
|
||||
Dependency::CatCode('文'),
|
||||
Dependency::EndLineChar,
|
||||
]);
|
||||
assert!(reads == original);
|
||||
let (ordered, evidence) = reads.into_evidence(std::iter::empty());
|
||||
let repeated: BTreeSet<_> = ordered
|
||||
.into_iter()
|
||||
.zip(evidence.epochs().unwrap())
|
||||
.filter_map(|(read, &epoch)| (epoch > boundary_epoch).then_some(read))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
repeated,
|
||||
BTreeSet::from([
|
||||
Dependency::CatCode('A'),
|
||||
Dependency::CatCode('文'),
|
||||
Dependency::EndLineChar,
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloned_record_preserves_byte_and_unicode_dependencies() {
|
||||
let mut read = DependencyReads::default();
|
||||
|
||||
@@ -4,6 +4,7 @@ use std::sync::Arc;
|
||||
|
||||
use hashbrown::{HashMap, hash_map::RawEntryMut};
|
||||
|
||||
use super::dependency_reads::DependencyEvidence;
|
||||
use super::job::InputStream;
|
||||
use super::mouth::Mouth;
|
||||
use super::state::{GroupKind, Key, Replacement, command_hasher};
|
||||
@@ -238,9 +239,9 @@ pub struct Executor {
|
||||
stream_sources: BTreeSet<usize>,
|
||||
generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
|
||||
reads: DependencyReads,
|
||||
// Cache the resolved meaning alongside the already required read evidence.
|
||||
// A shard's revision is only valid on this executor's state history.
|
||||
meaning_reads: HashMap<CommandName, (u64, Meaning), RandomState>,
|
||||
// Cache the resolved meaning alongside the last read epoch. A shard's
|
||||
// revision is only valid on this executor's state history.
|
||||
meaning_reads: HashMap<CommandName, (u64, Meaning, u32), RandomState>,
|
||||
reads_tracing_macros: bool,
|
||||
conditionals: Vec<Conditional>,
|
||||
in_csname: bool,
|
||||
@@ -501,6 +502,7 @@ impl EntryCheckpoint {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut executor = self.executor.clone().with_cancellation(cancellation);
|
||||
executor.reads.advance_epoch();
|
||||
executor.line_break_cache = line_break_cache;
|
||||
let previous_len = self.executor.sources[self.entry].data.len();
|
||||
let current_len = source.data.len();
|
||||
@@ -821,10 +823,14 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
}
|
||||
fn take_dependency_reads(&mut self) -> BTreeSet<Dependency> {
|
||||
let mut reads = std::mem::take(&mut self.reads).into_ordered();
|
||||
reads.extend(self.meaning_reads.drain().map(|(name, _)| Dependency::Meaning(name)));
|
||||
reads
|
||||
fn dependency_observations(&self) -> impl Iterator<Item = (Dependency, u32)> + '_ {
|
||||
self.reads.observations().chain(self.meaning_reads.iter()
|
||||
.map(|(name, (_, _, epoch))| (Dependency::Meaning(name.clone()), *epoch)))
|
||||
}
|
||||
|
||||
fn take_dependency_reads(&mut self) -> (BTreeSet<Dependency>, DependencyEvidence) {
|
||||
std::mem::take(&mut self.reads).into_evidence(self.meaning_reads.drain()
|
||||
.map(|(name, (_, _, epoch))| (Dependency::Meaning(name), epoch)))
|
||||
}
|
||||
|
||||
fn meaning(&mut self, token: &Token) -> Meaning {
|
||||
@@ -836,9 +842,11 @@ impl Executor {
|
||||
fn lookup_meaning(&mut self, name: &CommandName) -> Meaning {
|
||||
let hash = self.meaning_reads.hasher().hash_one(name);
|
||||
let revision = self.state.command_revision(hash);
|
||||
let epoch = self.reads.current_epoch;
|
||||
match self.meaning_reads.raw_entry_mut().from_key_hashed_nocheck(hash, name) {
|
||||
RawEntryMut::Occupied(mut entry) => {
|
||||
let (cached_revision, meaning) = entry.get_mut();
|
||||
let (cached_revision, meaning, last_read) = entry.get_mut();
|
||||
*last_read = epoch;
|
||||
if *cached_revision != revision {
|
||||
*meaning = self.state.meaning_hashed(name, hash);
|
||||
*cached_revision = revision;
|
||||
@@ -847,7 +855,7 @@ impl Executor {
|
||||
}
|
||||
RawEntryMut::Vacant(entry) => {
|
||||
let meaning = self.state.meaning_hashed(name, hash);
|
||||
entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone()));
|
||||
entry.insert_hashed_nocheck(hash, name.clone(), (revision, meaning.clone(), epoch));
|
||||
meaning
|
||||
}
|
||||
}
|
||||
@@ -3567,7 +3575,7 @@ impl Executor {
|
||||
for node in nodes {
|
||||
self.output_node(node, files)?;
|
||||
}
|
||||
let reads = self.take_dependency_reads();
|
||||
let (reads, dependency_evidence) = self.take_dependency_reads();
|
||||
let format_pdf_images = self.captured_format_pdf_images();
|
||||
Ok(Execution {
|
||||
format_dumped: self.format_dumped,
|
||||
@@ -3591,6 +3599,7 @@ impl Executor {
|
||||
stream_sources: self.stream_sources,
|
||||
generated_inputs: self.generated_inputs,
|
||||
reads,
|
||||
dependency_evidence,
|
||||
line_observations: Some(self.line_observations),
|
||||
events: self.events.into_vec(),
|
||||
steps: self.steps,
|
||||
@@ -4008,6 +4017,9 @@ impl Executor {
|
||||
}
|
||||
engine.events.seal_prefix();
|
||||
let mut executor = engine.clone();
|
||||
// Any subsequent read belongs to the suffix, even if it
|
||||
// happens before the next logical TeX execution step.
|
||||
engine.reads.advance_epoch();
|
||||
executor.cancellation = None;
|
||||
executor.line_break_cache = None;
|
||||
let checkpoint = EntryCheckpoint {
|
||||
@@ -4028,7 +4040,7 @@ impl Executor {
|
||||
incoming_state: u64,
|
||||
previous: Option<&Execution>,
|
||||
) -> Result<Execution, ExecutionFailure> {
|
||||
let reads = self.take_dependency_reads();
|
||||
let (reads, dependency_evidence) = self.take_dependency_reads();
|
||||
let result = result.and_then(|()| {
|
||||
if self.shipped_pages > 0 && !self.format_dumped
|
||||
&& let Some(objects) = self.state.pdf_objects.as_deref_mut()
|
||||
@@ -4098,6 +4110,7 @@ impl Executor {
|
||||
stream_sources: self.stream_sources,
|
||||
generated_inputs: self.generated_inputs,
|
||||
reads,
|
||||
dependency_evidence,
|
||||
line_observations: Some(self.line_observations),
|
||||
incoming_state,
|
||||
steps: self.steps,
|
||||
@@ -5275,3 +5288,19 @@ impl Executor {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_meaning_reads_are_observed_again_after_a_capture() {
|
||||
let name = CommandName::Control("relax".into());
|
||||
let read = Dependency::Meaning(name.clone());
|
||||
let mut executor = Executor::new(State::default(), Limits::default());
|
||||
executor.reads.insert(read.clone());
|
||||
assert_eq!(executor.lookup_meaning(&name), Meaning::Primitive(Primitive::Relax));
|
||||
let boundary_epoch = executor.reads.epoch().unwrap();
|
||||
executor.reads.advance_epoch();
|
||||
assert_eq!(executor.lookup_meaning(&name), Meaning::Primitive(Primitive::Relax));
|
||||
|
||||
let (reads, evidence) = executor.take_dependency_reads();
|
||||
assert_eq!(reads, BTreeSet::from([read]));
|
||||
assert_eq!(evidence.epochs().unwrap(), [boundary_epoch + 1]);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::super::{
|
||||
dependency_reads::DependencyEvidence,
|
||||
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
|
||||
statistics::BoxNodeOffset,
|
||||
statistics::{BoxNodeOffset, RetainedHistoryOffset},
|
||||
};
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
@@ -185,19 +186,18 @@ impl EntryCheckpoint {
|
||||
None if box_offset.is_identity() => None,
|
||||
None => return None,
|
||||
};
|
||||
if current.material_charge != old.material_charge {
|
||||
// A capacity recount can lower the running charge and change
|
||||
// which storage TeX counts. Bound every future charge on both
|
||||
// histories so neither can enter that path.
|
||||
let donor = completed.box_nodes_created?;
|
||||
if donor == usize::MAX {
|
||||
return None;
|
||||
}
|
||||
let remaining = donor.checked_sub(old.box_nodes_created)?;
|
||||
let largest = current.material_charge.max(old.material_charge);
|
||||
if largest.checked_add(remaining)? > current.limits.tokens {
|
||||
return None;
|
||||
}
|
||||
// A capacity recount can lower the running charge and observe
|
||||
// the retained event history. Bound all future visits on both
|
||||
// runs before translating any unequal charge or history.
|
||||
let no_suffix_recount = completed.box_nodes_created.is_some_and(|nodes| {
|
||||
nodes != usize::MAX
|
||||
&& nodes.checked_sub(old.box_nodes_created)
|
||||
.and_then(|remaining| current.material_charge.max(old.material_charge)
|
||||
.checked_add(remaining))
|
||||
.is_some_and(|charge| charge <= current.limits.tokens)
|
||||
});
|
||||
if current.material_charge != old.material_charge && !no_suffix_recount {
|
||||
return None;
|
||||
}
|
||||
let previous_bytes = &old.sources[self.entry].data;
|
||||
let current_bytes = ¤t.sources[self.entry].data;
|
||||
@@ -254,28 +254,36 @@ impl EntryCheckpoint {
|
||||
let mut sources = completed.sources.clone();
|
||||
sources[self.entry] = current.sources[self.entry].clone();
|
||||
let tail = completed.events.get(old.events.len()..)?;
|
||||
if completed.accounts_event_history
|
||||
&& !measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
|
||||
current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
|
||||
})
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let retained_history = if completed.accounts_event_history {
|
||||
measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
|
||||
if current.events.len() == old.events.len()
|
||||
&& current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
|
||||
{
|
||||
return Some(None);
|
||||
}
|
||||
// Shipout reports also contribute to later diagnostic
|
||||
// counters. Only translate the final report here.
|
||||
let has_final_report = matches!(tail.last(),
|
||||
Some(Event::Statistics(report)) if matches!(report.phase, StatisticsPhase::End { .. })
|
||||
);
|
||||
if !no_suffix_recount || !has_final_report
|
||||
|| tail[..tail.len() - 1].iter().any(|event| matches!(event, Event::Statistics(_)))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let history = current.retained_history_offset(old, entry_sizes)?;
|
||||
Some((!history.is_identity()).then_some(history))
|
||||
})?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let statistics = SuffixStatistics { steps: offset, boxes: box_offset, retained_history };
|
||||
// The joined events are published results. Resumption always starts
|
||||
// from a live checkpoint, whose original shared allocations stay intact.
|
||||
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || {
|
||||
let mut events = Vec::with_capacity(completed.events.len());
|
||||
let mut events = Vec::with_capacity(current.events.len().checked_add(tail.len())?);
|
||||
events.extend(current.events.iter().cloned());
|
||||
let mut reads = completed.reads.clone();
|
||||
current.reads.extend_ordered_delta(&old.reads, &mut reads);
|
||||
if current.meaning_reads.len() != old.meaning_reads.len() {
|
||||
reads.extend(
|
||||
current.meaning_reads.keys()
|
||||
.filter(|name| !old.meaning_reads.contains_key(*name))
|
||||
.cloned()
|
||||
.map(Dependency::Meaning),
|
||||
);
|
||||
}
|
||||
let (reads, dependency_evidence) = splice_dependencies(current, old, completed)?;
|
||||
let mut execution = Execution {
|
||||
format_dumped: completed.format_dumped,
|
||||
format_pdf_images: completed.format_pdf_images.clone(),
|
||||
@@ -293,6 +301,7 @@ impl EntryCheckpoint {
|
||||
stream_sources: completed.stream_sources.clone(),
|
||||
generated_inputs: completed.generated_inputs.clone(),
|
||||
reads,
|
||||
dependency_evidence,
|
||||
line_observations,
|
||||
incoming_state: completed.incoming_state,
|
||||
outgoing_state: completed.outgoing_state,
|
||||
@@ -303,18 +312,18 @@ impl EntryCheckpoint {
|
||||
};
|
||||
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
|
||||
relocate::append_suffix(
|
||||
&mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(),
|
||||
&mut execution, tail, &statistics, moved, sizes, old.sources.len(),
|
||||
)?;
|
||||
if execution.state != completed.state {
|
||||
execution.outgoing_state = execution.state.fingerprint();
|
||||
}
|
||||
} else if offset.is_identity() && box_offset.is_identity() {
|
||||
} else if statistics.is_identity() {
|
||||
execution.events.extend_from_slice(tail);
|
||||
} else {
|
||||
for event in tail {
|
||||
execution.events.push(match event {
|
||||
Event::Statistics(report) => Event::Statistics(Box::new(
|
||||
report.with_execution_offsets(offset, box_offset)?,
|
||||
statistics.translate(report, None)?,
|
||||
)),
|
||||
_ => event.clone(),
|
||||
});
|
||||
@@ -347,20 +356,21 @@ impl EntryCheckpoint {
|
||||
let current = &self.executor;
|
||||
let old = &prior.executor;
|
||||
// Later snapshots retain the donor's meaning cache and read history.
|
||||
// A successful splice proved key inclusion, so equal lengths prove
|
||||
// that no new meaning lookup would be lost by carrying the snapshot.
|
||||
if current.reads != old.reads
|
||||
// Keeping them requires the same keys, even when the finished splice
|
||||
// could publish a different set using exact suffix evidence.
|
||||
if current.events.len() != old.events.len()
|
||||
|| current.reads != old.reads
|
||||
|| current.meaning_reads.len() != old.meaning_reads.len()
|
||||
|| !old.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|
||||
|| current.box_nodes_created != old.box_nodes_created
|
||||
|| current.material_charge != old.material_charge
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// A restored checkpoint may later be asked to account for its
|
||||
// history, even if the job that furnished the suffix did not.
|
||||
if !completed.accounts_event_history
|
||||
&& !self.executor.equivalent_accounting_history(&prior.executor)
|
||||
{
|
||||
// A carried executor needs the exact alias history before taking
|
||||
// donor allocations from equal-valued events. Translating a final
|
||||
// report proves only the published counts.
|
||||
if completed.reads_event_history || !current.equivalent_accounting_history(old) {
|
||||
return None;
|
||||
}
|
||||
// Keep the old allocations of unchanged material, including inside
|
||||
@@ -418,6 +428,9 @@ impl EntryCheckpoint {
|
||||
}
|
||||
|
||||
let mut executor = next.clone();
|
||||
// These carried snapshots still have the right cumulative keys.
|
||||
// The donor's private timestamps alone cannot date the new prefix.
|
||||
executor.reads.disable_epochs();
|
||||
executor.line_observations = splice_line_observations(
|
||||
¤t.line_observations, &old.line_observations, &next.line_observations,
|
||||
)?;
|
||||
@@ -468,6 +481,49 @@ impl EntryCheckpoint {
|
||||
}
|
||||
}
|
||||
|
||||
fn splice_dependencies(
|
||||
current: &Executor,
|
||||
prior: &Executor,
|
||||
completed: &Execution,
|
||||
) -> Option<(BTreeSet<Dependency>, DependencyEvidence)> {
|
||||
if let (Some(current_epoch), Some(donor_epoch), Some(donor)) = (
|
||||
current.reads.epoch(), prior.reads.epoch(), completed.dependency_evidence.epochs(),
|
||||
) {
|
||||
if donor.len() != completed.reads.len() {
|
||||
return None;
|
||||
}
|
||||
let mut observed: BTreeMap<Dependency, u32> = BTreeMap::new();
|
||||
for (key, epoch) in current.dependency_observations() {
|
||||
observed.entry(key).and_modify(|last| *last = (*last).max(epoch)).or_insert(epoch);
|
||||
}
|
||||
for (key, &epoch) in completed.reads.iter().zip(donor) {
|
||||
if epoch > donor_epoch {
|
||||
let translated = current_epoch.checked_add(epoch - donor_epoch)?;
|
||||
observed.insert(key.clone(), translated);
|
||||
}
|
||||
}
|
||||
let (reads, epochs) = observed.into_iter().unzip();
|
||||
return Some((reads, DependencyEvidence::new(epochs)));
|
||||
}
|
||||
|
||||
// Restored records without epoch evidence can only preserve every
|
||||
// previous prefix key. Removing one could erase a repeated suffix read.
|
||||
if !prior.reads.is_subset(¤t.reads)
|
||||
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut reads = completed.reads.clone();
|
||||
current.reads.extend_ordered_delta(&prior.reads, &mut reads);
|
||||
if current.meaning_reads.len() != prior.meaning_reads.len() {
|
||||
reads.extend(current.meaning_reads.keys()
|
||||
.filter(|name| !prior.meaning_reads.contains_key(*name))
|
||||
.cloned()
|
||||
.map(Dependency::Meaning));
|
||||
}
|
||||
Some((reads, DependencyEvidence::default()))
|
||||
}
|
||||
|
||||
fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
|
||||
let started = elapsed.is_some().then(Instant::now);
|
||||
let value = action();
|
||||
@@ -497,6 +553,28 @@ fn splice_line_observations(
|
||||
Some(combined)
|
||||
}
|
||||
|
||||
struct SuffixStatistics {
|
||||
steps: StepOffset,
|
||||
boxes: BoxNodeOffset,
|
||||
retained_history: Option<RetainedHistoryOffset>,
|
||||
}
|
||||
|
||||
impl SuffixStatistics {
|
||||
fn is_identity(&self) -> bool {
|
||||
self.steps.is_identity() && self.boxes.is_identity() && self.retained_history.is_none()
|
||||
}
|
||||
|
||||
fn translate(
|
||||
&self,
|
||||
report: &StatisticsReport,
|
||||
entry_sizes: Option<(usize, usize)>,
|
||||
) -> Option<StatisticsReport> {
|
||||
report.with_suffix_adjustments(
|
||||
self.steps, self.boxes, entry_sizes, self.retained_history.as_ref(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
|
||||
match event {
|
||||
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))),
|
||||
@@ -626,13 +704,9 @@ fn same_kernel_continuation(
|
||||
if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() {
|
||||
return false;
|
||||
}
|
||||
if current.events.len() != prior.events.len()
|
||||
|| current.inputs.len() != prior.inputs.len()
|
||||
if current.inputs.len() != prior.inputs.len()
|
||||
// Statistics membership also constrains source rebinding.
|
||||
|| current.reads.observed_statistics() != prior.reads.observed_statistics()
|
||||
|| !prior.reads.is_subset(¤t.reads)
|
||||
|| prior.meaning_reads.len() > current.meaning_reads.len()
|
||||
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset};
|
||||
use crate::execution::source_relocation_events::EventRelocation;
|
||||
|
||||
pub(super) fn same_kernel_provenance(
|
||||
current: &Executor,
|
||||
@@ -106,8 +106,7 @@ pub(super) fn same_kernel_provenance(
|
||||
pub(super) fn append_suffix(
|
||||
execution: &mut Execution,
|
||||
tail: &[Event],
|
||||
offset: StepOffset,
|
||||
boxes: BoxNodeOffset,
|
||||
statistics: &SuffixStatistics,
|
||||
relocation: &mut EventRelocation<'_>,
|
||||
(previous_bytes, current_bytes): (usize, usize),
|
||||
source_count: usize,
|
||||
@@ -123,9 +122,7 @@ pub(super) fn append_suffix(
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut report = report
|
||||
.with_execution_offsets(offset, boxes)?
|
||||
.with_suffix_entry_resize(previous_bytes, current_bytes)?;
|
||||
let mut report = statistics.translate(report, Some((previous_bytes, current_bytes)))?;
|
||||
report.span = map.relocate_span(report.span)?;
|
||||
execution.events.push(Event::Statistics(Box::new(report)));
|
||||
} else {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::super::statistics::{
|
||||
Collector,
|
||||
Ownership::{Active, Retained},
|
||||
RetainedHistoryOffset,
|
||||
};
|
||||
use super::*;
|
||||
impl Executor {
|
||||
@@ -49,8 +50,9 @@ impl Executor {
|
||||
&self,
|
||||
shipping: Option<&NativeBox>,
|
||||
host: Option<HostResourceUsage>,
|
||||
c: Collector,
|
||||
mut c: Collector,
|
||||
) -> ResourceUsage {
|
||||
self.state.collect_statistics(&mut c);
|
||||
let mut c = self.collect_live_usage(shipping, host, c);
|
||||
Self::collect_event_usage(self.events.iter(), &mut c);
|
||||
c.usage
|
||||
@@ -62,7 +64,6 @@ impl Executor {
|
||||
host: Option<HostResourceUsage>,
|
||||
mut c: Collector,
|
||||
) -> Collector {
|
||||
self.state.collect_statistics(&mut c);
|
||||
c.usage.steps = self.steps;
|
||||
c.usage.source_files = self.sources.len();
|
||||
c.usage.source_payload_bytes = self.sources.iter().map(|s| s.data.len()).sum();
|
||||
@@ -239,6 +240,31 @@ impl Executor {
|
||||
old: &Self,
|
||||
entry_sizes: Option<(usize, usize)>,
|
||||
) -> bool {
|
||||
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
|
||||
self.collect_compared_accounting(old, entry_sizes, collector).is_some_and(
|
||||
|(live, old_live, history, old_history)| {
|
||||
live.has_equivalent_history(&old_live, &history, &old_history)
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn retained_history_offset(
|
||||
&self,
|
||||
old: &Self,
|
||||
entry_sizes: Option<(usize, usize)>,
|
||||
) -> Option<RetainedHistoryOffset> {
|
||||
let (live, old_live, history, old_history) =
|
||||
self.collect_compared_accounting(old, entry_sizes, Collector::default)?;
|
||||
live.retained_history_offset(&old_live, &history, &old_history)
|
||||
}
|
||||
|
||||
fn collect_compared_accounting(
|
||||
&self,
|
||||
old: &Self,
|
||||
entry_sizes: Option<(usize, usize)>,
|
||||
collector: fn() -> Collector,
|
||||
) -> Option<(Collector, Collector, Collector, Collector)> {
|
||||
// These containers may reintroduce previously retained allocations
|
||||
// that are outside the accounting walk at this boundary.
|
||||
let fully_visited = |engine: &Self| {
|
||||
@@ -246,26 +272,24 @@ impl Executor {
|
||||
&& engine.native_page.as_ref().is_none_or(|page| page.insertions.held.is_empty())
|
||||
};
|
||||
if !fully_visited(self) || !fully_visited(old) {
|
||||
return false;
|
||||
return None;
|
||||
}
|
||||
|
||||
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
|
||||
let (history, old_history) =
|
||||
Self::collect_event_usage_pair(&self.events, &old.events, collector());
|
||||
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
|
||||
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
|
||||
// The splice translates the cumulative counters separately.
|
||||
live.usage.steps = old_live.usage.steps;
|
||||
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
|
||||
if let Some((previous, current)) = entry_sizes {
|
||||
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
|
||||
let Some(source) = restore(live.usage.source_payload_bytes) else { return false; };
|
||||
let Some(mouth) = restore(live.usage.mouth_payload_bytes) else { return false; };
|
||||
live.usage.source_payload_bytes = source;
|
||||
live.usage.mouth_payload_bytes = mouth;
|
||||
}
|
||||
live.has_equivalent_history(&old_live, &history, &old_history)
|
||||
})
|
||||
let (history, old_history) =
|
||||
Self::collect_event_usage_pair(&self.events, &old.events, collector());
|
||||
let mut live = collector().tracking_aliases();
|
||||
let mut old_live = collector().tracking_aliases();
|
||||
self.state.collect_compared_statistics(&old.state, &mut live, &mut old_live)?;
|
||||
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.
|
||||
live.usage.steps = old_live.usage.steps;
|
||||
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
|
||||
if let Some((previous, current)) = entry_sizes {
|
||||
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
|
||||
live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?;
|
||||
live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?;
|
||||
}
|
||||
Some((live, old_live, history, old_history))
|
||||
}
|
||||
|
||||
pub(super) fn statistics_before_shipout(
|
||||
@@ -341,6 +365,57 @@ impl Executor {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::execution::statistics::BoxNodeOffset;
|
||||
|
||||
#[test]
|
||||
fn equal_mark_events_with_different_aliases_cannot_carry_a_checkpoint() {
|
||||
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
|
||||
let shared: Arc<[Token]> = Arc::from([token.clone()]);
|
||||
let independent: Arc<[Token]> = Arc::from([token]);
|
||||
let mark = |tokens| {
|
||||
Event::VerticalMaterial(vec![NativeVerticalNode::Mark(NativeMark {
|
||||
class: 0,
|
||||
tokens,
|
||||
span: Span::default(),
|
||||
})])
|
||||
};
|
||||
let mut old = Executor::default();
|
||||
old.state.page_marks.insert(0, PageMarks {
|
||||
top: Some(shared.clone()),
|
||||
..PageMarks::default()
|
||||
});
|
||||
let mut current = old.clone();
|
||||
old.events.push(mark(shared.clone()));
|
||||
old.events.push(mark(shared.clone()));
|
||||
current.events.push(mark(shared));
|
||||
current.events.push(mark(independent));
|
||||
|
||||
// Rebase's value comparison alone would retain the old Arc sharing.
|
||||
assert!(current.events.iter().eq(old.events.iter()));
|
||||
assert!(!current.equivalent_accounting_history(&old));
|
||||
|
||||
let offset = current.retained_history_offset(&old, None).unwrap();
|
||||
assert!(!offset.is_identity());
|
||||
let end_report = |engine: &Executor| {
|
||||
StatisticsReport::new(
|
||||
StatisticsPhase::End {
|
||||
success: true,
|
||||
usage: engine.collect_usage(None, None, Collector::default()),
|
||||
},
|
||||
WriteDestination::Log,
|
||||
Span::default(),
|
||||
)
|
||||
};
|
||||
assert_eq!(
|
||||
end_report(&old).with_suffix_adjustments(
|
||||
StepOffset::new(0, 0),
|
||||
BoxNodeOffset::new(0, 0),
|
||||
None,
|
||||
Some(&offset),
|
||||
),
|
||||
Some(end_report(¤t))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_event_prefix_keeps_tail_deduplication_and_membership() {
|
||||
|
||||
@@ -678,9 +678,12 @@ pub struct Execution {
|
||||
pub stream_sources: BTreeSet<usize>,
|
||||
#[serde(default)]
|
||||
pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
|
||||
/// Reads made during this execution, not a license to reuse output after
|
||||
/// state changes. Incremental execution/cache reuse is a later milestone.
|
||||
/// Dependencies observed over the execution. Suffix reuse additionally
|
||||
/// validates the state and the reads that follow its checkpoint.
|
||||
pub reads: BTreeSet<Dependency>,
|
||||
/// Internal epochs relate active checkpoint cuts to repeated reads.
|
||||
#[serde(skip)]
|
||||
dependency_evidence: dependency_reads::DependencyEvidence,
|
||||
/// Per-source observations distinguish suffix reads from identical prefix reads.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
line_observations: Option<BTreeMap<usize, usize>>,
|
||||
|
||||
@@ -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> {
|
||||
if span.source != self.source {
|
||||
return Some(span);
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
mod fingerprint;
|
||||
pub(super) mod source_relocation;
|
||||
|
||||
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
|
||||
|
||||
use hashbrown::HashMap;
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::hash::{BuildHasher, Hash, Hasher, RandomState};
|
||||
#[cfg(test)]
|
||||
use std::hash::DefaultHasher;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use super::{
|
||||
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
|
||||
@@ -800,7 +805,47 @@ enum PdftexRevision {
|
||||
}
|
||||
|
||||
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)>>>;
|
||||
|
||||
pub(super) fn command_hasher() -> &'static RandomState {
|
||||
@@ -816,15 +861,19 @@ struct CommandBindings {
|
||||
revisions: [u64; COMMAND_SHARDS],
|
||||
// Cache names only so redefinitions can share the same order.
|
||||
ordered_names: OrderedCommandNames,
|
||||
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
|
||||
}
|
||||
|
||||
impl Default for CommandBindings {
|
||||
fn default() -> Self {
|
||||
let hasher = command_hasher();
|
||||
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],
|
||||
ordered_names: Arc::default(),
|
||||
fingerprint_inputs: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -849,6 +898,7 @@ impl CommandBindings {
|
||||
|
||||
fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> {
|
||||
self.shards[Self::shard_index(hash)]
|
||||
.entries
|
||||
.raw_entry()
|
||||
.from_key_hashed_nocheck(hash, name)
|
||||
.map(|(_, meaning)| meaning)
|
||||
@@ -867,16 +917,13 @@ impl CommandBindings {
|
||||
}
|
||||
|
||||
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
|
||||
if let hashbrown::hash_map::Entry::Vacant(entry) =
|
||||
self.shard_mut(&name).entry(name.into())
|
||||
{
|
||||
entry.insert(meaning);
|
||||
if self.shard_mut(&name).insert_if_absent(name.into(), meaning) {
|
||||
self.invalidate_order();
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -890,11 +937,11 @@ impl CommandBindings {
|
||||
}
|
||||
|
||||
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)> {
|
||||
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)> {
|
||||
@@ -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 {
|
||||
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)]
|
||||
pub struct State {
|
||||
// Checkpoints share the table. A write copies just its command shard.
|
||||
// Formats and fingerprints use key order.
|
||||
commands: Arc<CommandBindings>,
|
||||
// Derive the ordinary hash and emit the specialized fingerprint in the
|
||||
// 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.
|
||||
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>,
|
||||
counts: BTreeMap<u16, i32>,
|
||||
toks: BTreeMap<u16, Vec<Token>>,
|
||||
@@ -1031,46 +1116,6 @@ pub struct State {
|
||||
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]
|
||||
fn buffered_fingerprint_matches_the_ordered_state_hash() {
|
||||
let mut state = State::initex().with_etex();
|
||||
@@ -1096,6 +1141,57 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
|
||||
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 command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
|
||||
let mut state = State::initex().with_etex();
|
||||
@@ -1610,6 +1706,60 @@ impl Default for State {
|
||||
|
||||
impl State {
|
||||
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,
|
||||
current_usage: &mut super::statistics::Collector,
|
||||
old_usage: &mut super::statistics::Collector,
|
||||
) -> Option<()> {
|
||||
if !current_usage.material_only() {
|
||||
let entries = old.commands.len();
|
||||
current_usage.usage.state.command_entries = entries;
|
||||
old_usage.usage.state.command_entries = entries;
|
||||
// The alias proof needs corresponding visits, so both sides
|
||||
// walk the donor's binding order. Hashing and serialization
|
||||
// still use the independent, sorted command order.
|
||||
for (current, prior) in self.commands.shards.iter().zip(&old.commands.shards) {
|
||||
if current.entries.len() != prior.entries.len() {
|
||||
return None;
|
||||
}
|
||||
let shared = Arc::ptr_eq(current, prior);
|
||||
for (name, old_meaning) in &prior.entries {
|
||||
let meaning = if shared { old_meaning } else { current.entries.get(name)? };
|
||||
Self::collect_command_statistics(current_usage, name, meaning);
|
||||
Self::collect_command_statistics(old_usage, name, old_meaning);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.collect_state_storage(current_usage);
|
||||
old.collect_state_storage(old_usage);
|
||||
Some(())
|
||||
}
|
||||
|
||||
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;
|
||||
for b in self.boxes.values() {
|
||||
c.native_box(b, Active);
|
||||
@@ -1622,26 +1772,6 @@ impl State {
|
||||
}
|
||||
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.parameter_entries =
|
||||
self.parameters.len() + self.token_parameters.len() + self.job_parameters.len();
|
||||
@@ -2485,7 +2615,7 @@ impl State {
|
||||
Arc::unwrap_or_clone(state.commands)
|
||||
.shards
|
||||
.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) {
|
||||
CommandName::Control(name) => Some((name, meaning)),
|
||||
_ => None,
|
||||
@@ -2712,11 +2842,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)>) {
|
||||
self.groups.push(Group {
|
||||
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 crate::execution::source_relocation_events::EventRelocation;
|
||||
use crate::execution::{
|
||||
Span, source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
|
||||
};
|
||||
use crate::pdf_device::forms::FormContents;
|
||||
|
||||
impl State {
|
||||
@@ -13,7 +15,10 @@ impl State {
|
||||
// Copy only shards with a relocated macro. Ordinary format macros
|
||||
// and macros from the byte-identical prefix keep their allocations.
|
||||
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 {
|
||||
let relocated = relocation.relocate_macro(body)?;
|
||||
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<()> {
|
||||
for token in tokens {
|
||||
relocation.relocate_token(token)?;
|
||||
}
|
||||
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.
|
||||
use super::*;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, HashSet},
|
||||
collections::{BTreeSet, HashMap, HashSet, hash_map::Entry},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
@@ -197,6 +197,80 @@ impl BoxNodeOffset {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default, PartialEq, Eq)]
|
||||
struct RetainedHistoryUsage {
|
||||
material: MaterialUsage,
|
||||
events: usize,
|
||||
shipouts: usize,
|
||||
token_list_cells: usize,
|
||||
}
|
||||
|
||||
impl RetainedHistoryUsage {
|
||||
fn take_from(usage: &mut ResourceUsage) -> Self {
|
||||
Self {
|
||||
material: std::mem::take(&mut usage.retained_material),
|
||||
events: std::mem::take(&mut usage.retained_events),
|
||||
shipouts: std::mem::take(&mut usage.retained_shipouts),
|
||||
token_list_cells: std::mem::take(&mut usage.token_list_cells),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The contribution of the replaced prefix to the final resource report.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct RetainedHistoryOffset {
|
||||
previous: RetainedHistoryUsage,
|
||||
current: RetainedHistoryUsage,
|
||||
}
|
||||
|
||||
impl RetainedHistoryOffset {
|
||||
pub(super) fn is_identity(&self) -> bool {
|
||||
self.previous == self.current
|
||||
}
|
||||
|
||||
fn replace_prefix(&self, usage: &mut ResourceUsage) -> Option<()> {
|
||||
fn replace(total: usize, previous: usize, current: usize) -> Option<usize> {
|
||||
total.checked_sub(previous)?.checked_add(current)
|
||||
}
|
||||
let previous = &self.previous;
|
||||
let current = &self.current;
|
||||
let material = &usage.retained_material;
|
||||
let old = &previous.material;
|
||||
let new = ¤t.material;
|
||||
let material = MaterialUsage {
|
||||
boxes: replace(material.boxes, old.boxes, new.boxes)?,
|
||||
horizontal_nodes: replace(material.horizontal_nodes, old.horizontal_nodes, new.horizontal_nodes)?,
|
||||
vertical_nodes: replace(material.vertical_nodes, old.vertical_nodes, new.vertical_nodes)?,
|
||||
math_nodes: replace(material.math_nodes, old.math_nodes, new.math_nodes)?,
|
||||
geometry_items: replace(material.geometry_items, old.geometry_items, new.geometry_items)?,
|
||||
diagnostic_nodes: replace(material.diagnostic_nodes, old.diagnostic_nodes, new.diagnostic_nodes)?,
|
||||
ligature_work_items: replace(material.ligature_work_items, old.ligature_work_items, new.ligature_work_items)?,
|
||||
};
|
||||
// The final report formats the aggregate with MaterialUsage::records.
|
||||
[
|
||||
material.boxes,
|
||||
material.horizontal_nodes,
|
||||
material.vertical_nodes,
|
||||
material.math_nodes,
|
||||
material.geometry_items,
|
||||
material.diagnostic_nodes,
|
||||
material.ligature_work_items,
|
||||
]
|
||||
.into_iter()
|
||||
.try_fold(0usize, usize::checked_add)?;
|
||||
let events = replace(usage.retained_events, previous.events, current.events)?;
|
||||
let shipouts = replace(usage.retained_shipouts, previous.shipouts, current.shipouts)?;
|
||||
let tokens = replace(
|
||||
usage.token_list_cells, previous.token_list_cells, current.token_list_cells,
|
||||
)?;
|
||||
usage.retained_material = material;
|
||||
usage.retained_events = events;
|
||||
usage.retained_shipouts = shipouts;
|
||||
usage.token_list_cells = tokens;
|
||||
Some(())
|
||||
}
|
||||
}
|
||||
|
||||
impl StatisticsReport {
|
||||
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
|
||||
let text = phase.text();
|
||||
@@ -227,26 +301,9 @@ impl StatisticsReport {
|
||||
/// Recompute a report for a verified suffix after the initial entry read
|
||||
/// changed size. The caller authenticates the entry scanner's lifetime.
|
||||
pub fn with_suffix_entry_resize(&self, previous: usize, current: usize) -> Option<Self> {
|
||||
let mut phase = self.phase.clone();
|
||||
match &mut phase {
|
||||
StatisticsPhase::Shipout { before, after } => {
|
||||
for usage in [before, after] {
|
||||
let active = usage.mouth_payload_bytes == previous;
|
||||
if !active && usage.mouth_payload_bytes != 0 {
|
||||
return None;
|
||||
}
|
||||
usage.resize_entry_payload(previous, current, active)?;
|
||||
}
|
||||
}
|
||||
StatisticsPhase::End { usage, .. } => {
|
||||
if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 {
|
||||
return None;
|
||||
}
|
||||
usage.resize_entry_payload(previous, current, false)?;
|
||||
}
|
||||
}
|
||||
let report = Self::new(phase, self.destination, self.span);
|
||||
report.within_diagnostic_budget().then_some(report)
|
||||
self.with_suffix_adjustments(
|
||||
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some((previous, current)), None,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn with_step_offset(&self, offset: StepOffset) -> Option<Self> {
|
||||
@@ -257,6 +314,16 @@ impl StatisticsReport {
|
||||
&self,
|
||||
steps: StepOffset,
|
||||
boxes: BoxNodeOffset,
|
||||
) -> Option<Self> {
|
||||
self.with_suffix_adjustments(steps, boxes, None, None)
|
||||
}
|
||||
|
||||
pub(super) fn with_suffix_adjustments(
|
||||
&self,
|
||||
steps: StepOffset,
|
||||
boxes: BoxNodeOffset,
|
||||
entry_sizes: Option<(usize, usize)>,
|
||||
history: Option<&RetainedHistoryOffset>,
|
||||
) -> Option<Self> {
|
||||
let translate = |usage: &mut ResourceUsage| {
|
||||
usage.steps = steps.apply(usage.steps)?;
|
||||
@@ -266,10 +333,32 @@ impl StatisticsReport {
|
||||
let mut phase = self.phase.clone();
|
||||
match &mut phase {
|
||||
StatisticsPhase::Shipout { before, after } => {
|
||||
translate(before)?;
|
||||
translate(after)?;
|
||||
if history.is_some_and(|offset| !offset.is_identity()) {
|
||||
return None;
|
||||
}
|
||||
for usage in [before, after] {
|
||||
translate(usage)?;
|
||||
if let Some((previous, current)) = entry_sizes {
|
||||
let active = usage.mouth_payload_bytes == previous;
|
||||
if !active && usage.mouth_payload_bytes != 0 {
|
||||
return None;
|
||||
}
|
||||
usage.resize_entry_payload(previous, current, active)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
StatisticsPhase::End { usage, .. } => {
|
||||
translate(usage)?;
|
||||
if let Some((previous, current)) = entry_sizes {
|
||||
if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 {
|
||||
return None;
|
||||
}
|
||||
usage.resize_entry_payload(previous, current, false)?;
|
||||
}
|
||||
if let Some(offset) = history {
|
||||
offset.replace_prefix(usage)?;
|
||||
}
|
||||
}
|
||||
StatisticsPhase::End { usage, .. } => translate(usage)?,
|
||||
}
|
||||
let report = Self::new(phase, self.destination, self.span);
|
||||
report.within_diagnostic_budget().then_some(report)
|
||||
@@ -367,7 +456,7 @@ pub(super) enum Ownership {
|
||||
Active,
|
||||
Retained,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
||||
enum Allocation {
|
||||
Macro(usize),
|
||||
Tokens(usize, usize),
|
||||
@@ -376,22 +465,27 @@ enum Allocation {
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct AliasVisits {
|
||||
ordinals: BTreeMap<Allocation, usize>,
|
||||
ordinals: HashMap<Allocation, usize>,
|
||||
visits: Vec<(Allocation, usize)>,
|
||||
}
|
||||
|
||||
impl AliasVisits {
|
||||
fn record(&mut self, allocation: Allocation) {
|
||||
fn record(&mut self, allocation: Allocation) -> bool {
|
||||
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));
|
||||
first
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Collector {
|
||||
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>,
|
||||
token_lists: BTreeSet<(usize, usize)>,
|
||||
shared_lists: Option<BTreeSet<usize>>,
|
||||
@@ -406,21 +500,14 @@ impl Collector {
|
||||
}
|
||||
|
||||
pub(super) fn tracking_aliases(mut self) -> Self {
|
||||
self.aliases = Some(AliasVisits::default());
|
||||
self.aliases.get_or_insert_with(AliasVisits::default);
|
||||
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 {
|
||||
if self.aliases.as_ref().is_some_and(|aliases| aliases.ordinals.contains_key(&allocation)) {
|
||||
return true;
|
||||
}
|
||||
match allocation {
|
||||
Allocation::Macro(address) => self.macros.contains(&address),
|
||||
Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)),
|
||||
@@ -431,19 +518,47 @@ impl Collector {
|
||||
}
|
||||
}
|
||||
|
||||
/// Check the live allocation correspondence and each allocation's
|
||||
/// membership in the retained history. Counting a later event can
|
||||
/// encounter older storage only through these surviving references.
|
||||
pub(super) fn has_equivalent_history(
|
||||
&self,
|
||||
other: &Self,
|
||||
history: &Self,
|
||||
old_history: &Self,
|
||||
) -> bool {
|
||||
history.usage == old_history.usage && self.same_live_history(other, history, old_history)
|
||||
}
|
||||
|
||||
/// Compare separately collected live state and retained events. The
|
||||
/// caller must prove that the suffix cannot recount capacity.
|
||||
pub(super) fn retained_history_offset(
|
||||
&self,
|
||||
other: &Self,
|
||||
history: &Self,
|
||||
old_history: &Self,
|
||||
) -> Option<RetainedHistoryOffset> {
|
||||
if self.material_only() || other.material_only()
|
||||
|| history.material_only() || old_history.material_only()
|
||||
|| !self.same_live_history(other, history, old_history)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut usage = history.usage.clone();
|
||||
let mut old_usage = old_history.usage.clone();
|
||||
let current = RetainedHistoryUsage::take_from(&mut usage);
|
||||
let previous = RetainedHistoryUsage::take_from(&mut old_usage);
|
||||
(usage == old_usage).then_some(RetainedHistoryOffset { previous, current })
|
||||
}
|
||||
|
||||
/// Later events can reach old storage only through allocations that
|
||||
/// survive in live state. Keep both their alias order and history membership.
|
||||
fn same_live_history(
|
||||
&self,
|
||||
other: &Self,
|
||||
history: &Self,
|
||||
old_history: &Self,
|
||||
) -> bool {
|
||||
let a = &self.aliases.as_ref().expect("live alias traversal").visits;
|
||||
let b = &other.aliases.as_ref().expect("live alias traversal").visits;
|
||||
self.usage == other.usage
|
||||
&& history.usage == old_history.usage
|
||||
&& a.len() == b.len()
|
||||
&& a.iter().zip(b).all(|(&(new, ni), &(old, oi))| {
|
||||
ni == oi
|
||||
@@ -458,8 +573,13 @@ impl Collector {
|
||||
|
||||
pub fn macro_body(&mut self, m: &Arc<Macro>) {
|
||||
let address = Arc::as_ptr(m) as usize;
|
||||
self.tracks_allocation(Allocation::Macro(address));
|
||||
if self.macros.insert(address) {
|
||||
let first = if let Some(aliases) = &mut self.aliases {
|
||||
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.macro_token_cells += m.prefix.len()
|
||||
+ m.parameters.iter().map(Vec::len).sum::<usize>()
|
||||
@@ -468,11 +588,15 @@ impl Collector {
|
||||
}
|
||||
pub fn shared_tokens(&mut self, t: &Arc<[Token]>) {
|
||||
let address = t.as_ptr() as usize;
|
||||
if !t.is_empty() {
|
||||
self.tracks_allocation(Allocation::Tokens(address, t.len()));
|
||||
}
|
||||
if self.token_lists.insert((address, t.len())) {
|
||||
self.usage.token_list_cells += t.len();
|
||||
let len = t.len();
|
||||
let first = if let Some(aliases) = &mut self.aliases && len != 0 {
|
||||
aliases.record(Allocation::Tokens(address, len))
|
||||
&& !self.token_lists.contains(&(address, len))
|
||||
} else {
|
||||
self.token_lists.insert((address, len))
|
||||
};
|
||||
if first {
|
||||
self.usage.token_list_cells += len;
|
||||
}
|
||||
}
|
||||
fn material(&mut self, o: Ownership) -> &mut MaterialUsage {
|
||||
@@ -608,13 +732,15 @@ impl Collector {
|
||||
self.usage.active_material.ligature_work_items += b.ligature_work_items();
|
||||
}
|
||||
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;
|
||||
if self.shared_lists.is_some() {
|
||||
self.tracks_allocation(Allocation::Material(address));
|
||||
if let Some(aliases) = &mut self.aliases {
|
||||
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(
|
||||
@@ -692,6 +818,146 @@ 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 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]
|
||||
fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
|
||||
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
|
||||
|
||||
@@ -87,6 +87,132 @@ p50 分别为 33.2 和 33.3 ms,进程峰值 RSS 为 603,280 KiB。
|
||||
原始样本、构建清单、机器状态和逐次输出对照在
|
||||
`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 整行编辑复用
|
||||
|
||||
XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他
|
||||
|
||||
@@ -1763,29 +1763,29 @@ fn settled_suffix_carries_a_verified_prefix_into_later_edits() {
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
let cwd = directory("settled-prefix-dependencies");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |ignored| format!(r"
|
||||
let body = |ignored, repeat| format!(r"
|
||||
\catcode64=9 \catcode63=9
|
||||
?\relax
|
||||
\shipout\hbox{{Cover}}\relax
|
||||
{ignored}\relax
|
||||
\shipout\hbox{{Checkpoint}}\relax
|
||||
\shipout\hbox{{Suffix}}\relax
|
||||
{repeat}\relax\shipout\hbox{{Suffix}}\relax
|
||||
\endinput\shipout\hbox{{Final}}\relax\end
|
||||
");
|
||||
for (before, after, reuse) in [('?', '@', true), ('@', '?', false)] {
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap();
|
||||
for (before, after, repeat) in [('?', '@', '?'), ('@', '?', '?'), ('@', '?', '@')] {
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before, repeat))).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 new_read = Dependency::CatCode('@');
|
||||
assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@');
|
||||
let source = format!("{HEADER}{}", body(after));
|
||||
assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@' || repeat == '@');
|
||||
let source = format!("{HEADER}{}", body(after, repeat));
|
||||
let project = project.with_file_edits(
|
||||
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
|
||||
).unwrap();
|
||||
@@ -1793,8 +1793,8 @@ fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() {
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(!work.reused_completion, "{work:?}");
|
||||
assert_eq!(work.reused_suffix_steps > 0, reuse, "{work:?}");
|
||||
assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@');
|
||||
assert!(work.reused_suffix_steps > 0, "{work:?}");
|
||||
assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@' || repeat == '@');
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let full = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(updated.execution.execution, full.execution.execution);
|
||||
@@ -1862,6 +1862,62 @@ fn settled_suffix_translates_cumulative_box_charges_in_both_directions() {
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[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 resized_entry_prefix_reuses_verified_statistics() {
|
||||
let cwd = directory("resized-entry-statistics");
|
||||
|
||||
Reference in new issue
Block a user