Verify retained TeX accounting before reusing executed suffixes

This commit is contained in:
gloamxun committed 2026-11-29 08:23:58 +08:00
1 parent 0117449023
commit 57ce7116ad
8 files changed
+236 -15

No files matched your search

@@ -242,8 +242,10 @@ pub struct Executor {
in_csname: bool,
command_trace_mode: Option<&'static str>,
events: ExecutionEvents,
// Set before operations that inspect earlier events beyond their count.
// The PDF space probe inspects the actual paint of earlier pages.
reads_event_history: bool,
// Capacity recounts and tracing use the resource accounting traversal.
accounts_event_history: bool,
steps: usize,
ligature_carry: super::ligature::Carry,
current: Span,
@@ -538,6 +540,7 @@ impl Executor {
command_trace_mode: None,
events: ExecutionEvents::default(),
reads_event_history: false,
accounts_event_history: false,
steps: 0,
ligature_carry: super::ligature::Carry::default(),
current: Span::default(),
@@ -3534,6 +3537,7 @@ impl Executor {
events: self.events.into_vec(),
steps: self.steps,
reads_event_history: self.reads_event_history,
accounts_event_history: self.accounts_event_history,
})
}
fn check_input_character(&self, code: i32) -> Result<(), Error> {
@@ -4037,6 +4041,7 @@ impl Executor {
incoming_state,
steps: self.steps,
reads_event_history: self.reads_event_history,
accounts_event_history: self.accounts_event_history,
})
}
fn run_observed<F: SourceProvider>(
@@ -122,6 +122,11 @@ 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 && !current.equivalent_accounting_history(old) {
return None;
}
// The joined events are published results. Resumption always starts
// from a live checkpoint, whose original shared allocations stay intact.
let mut events = current.events.clone().into_vec();
events.extend_from_slice(tail);
Some(Execution {
@@ -145,6 +150,7 @@ impl EntryCheckpoint {
outgoing_state: completed.outgoing_state,
steps: completed.steps,
reads_event_history: false,
accounts_event_history: completed.accounts_event_history,
})
}
}
@@ -219,6 +225,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
writing,
stack_peaks,
alignment_balance,
accounts_event_history,
],
[
inputs,
@@ -25,7 +25,7 @@ impl Executor {
}
// Packing can move existing lists or replace an old register. Recount
// actual storage here, counting each shared list allocation once.
self.reads_event_history = true;
self.accounts_event_history = true;
let usage = self.collect_usage(shipping, None, Collector::for_capacity());
self.material_charge = usage
.active_material
@@ -41,7 +41,7 @@ impl Executor {
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
) -> ResourceUsage {
self.reads_event_history = true;
self.accounts_event_history = true;
self.collect_usage(shipping, host, Collector::default())
}
@@ -49,8 +49,19 @@ impl Executor {
&self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
mut c: Collector,
c: Collector,
) -> ResourceUsage {
let mut c = self.collect_live_usage(shipping, host, c);
Self::collect_event_usage(self.events.iter(), &mut c);
c.usage
}
fn collect_live_usage(
&self,
shipping: Option<&NativeBox>,
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();
@@ -122,7 +133,11 @@ impl Executor {
InputFrame::Boundary => {}
}
}
for e in self.events.iter() {
c
}
fn collect_event_usage<'a>(events: impl Iterator<Item = &'a Event>, c: &mut Collector) {
for e in events {
if matches!(e, Event::Statistics(_)) {
continue;
}
@@ -164,8 +179,30 @@ impl Executor {
_ => {}
}
}
c.usage
}
pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool {
// These containers may reintroduce previously retained allocations
// that are outside the accounting walk at this boundary.
let fully_visited = |engine: &Self| {
engine.state.pdf_forms.is_empty()
&& engine.native_page.as_ref().is_none_or(|page| page.insertions.held.is_empty())
};
if !fully_visited(self) || !fully_visited(old) {
return false;
}
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
let mut history = collector();
let mut old_history = collector();
Self::collect_event_usage(self.events.iter(), &mut history);
Self::collect_event_usage(old.events.iter(), &mut old_history);
let live = self.collect_live_usage(None, None, collector().tracking_aliases());
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
live.has_equivalent_history(&old_live, &history, &old_history)
})
}
pub(super) fn statistics_before_shipout(
&mut self,
b: &NativeBox,
@@ -671,6 +671,8 @@ pub struct Execution {
pub steps: usize,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
reads_event_history: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
accounts_event_history: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+12 -2
View File
@@ -1466,14 +1466,24 @@ impl State {
return;
}
c.usage.state.command_entries = self.commands.by_name.len();
for (name, meaning) in &self.commands.by_name {
if let CommandName::Control(name) = name.as_ref() {
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.by_name {
visit_command(name, meaning);
}
}
c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len();
c.usage.state.parameter_entries =
@@ -1,6 +1,9 @@
//! Measured native storage and execution resources, not invented TeX arena words.
use super::*;
use std::{collections::BTreeSet, sync::Arc};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct MaterialUsage {
@@ -147,12 +150,34 @@ pub(super) enum Ownership {
Active,
Retained,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Allocation {
Macro(usize),
Tokens(usize, usize),
Material(usize),
}
#[derive(Default)]
struct AliasVisits {
ordinals: BTreeMap<Allocation, usize>,
visits: Vec<(Allocation, usize)>,
}
impl AliasVisits {
fn record(&mut self, allocation: Allocation) {
let next = self.ordinals.len();
let ordinal = *self.ordinals.entry(allocation).or_insert(next);
self.visits.push((allocation, ordinal));
}
}
#[derive(Default)]
pub(super) struct Collector {
pub usage: ResourceUsage,
macros: BTreeSet<usize>,
token_lists: BTreeSet<(usize, usize)>,
shared_lists: Option<BTreeSet<usize>>,
aliases: Option<AliasVisits>,
}
impl Collector {
pub fn for_capacity() -> Self {
@@ -162,12 +187,61 @@ impl Collector {
}
}
pub(super) fn tracking_aliases(mut self) -> Self {
self.aliases = Some(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 {
match allocation {
Allocation::Macro(address) => self.macros.contains(&address),
Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)),
Allocation::Material(address) => self
.shared_lists
.as_ref()
.is_some_and(|lists| lists.contains(&address)),
}
}
/// 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 {
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
&& std::mem::discriminant(&new) == std::mem::discriminant(&old)
&& history.contains(new) == old_history.contains(old)
})
}
pub(super) fn material_only(&self) -> bool {
self.shared_lists.is_some()
}
pub fn macro_body(&mut self, m: &Arc<Macro>) {
if self.macros.insert(Arc::as_ptr(m) as usize) {
let address = Arc::as_ptr(m) as usize;
self.tracks_allocation(Allocation::Macro(address));
if self.macros.insert(address) {
self.usage.unique_macro_bodies += 1;
self.usage.macro_token_cells += m.prefix.len()
+ m.parameters.iter().map(Vec::len).sum::<usize>()
@@ -175,7 +249,11 @@ impl Collector {
}
}
pub fn shared_tokens(&mut self, t: &Arc<[Token]>) {
if self.token_lists.insert((t.as_ptr() as usize, t.len())) {
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();
}
}
@@ -312,9 +390,13 @@ impl Collector {
self.usage.active_material.ligature_work_items += b.ligature_work_items();
}
fn visit_shared<T: ?Sized>(&mut self, list: &Arc<T>) -> bool {
self.shared_lists.as_mut().is_none_or(|seen| {
seen.insert(Arc::as_ptr(list).cast::<()>() as usize)
})
let address = Arc::as_ptr(list).cast::<()>() as usize;
if self.shared_lists.is_some() {
self.tracks_allocation(Allocation::Material(address));
}
self.shared_lists
.as_mut()
.is_none_or(|seen| seen.insert(address))
}
pub fn shared_diagnostics(
@@ -350,3 +432,32 @@ impl Collector {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let first: Arc<[Token]> = Arc::from([token.clone()]);
let second: Arc<[Token]> = Arc::from([token.clone()]);
let unrelated: Arc<[Token]> = Arc::from([token]);
let collect = |tokens: &Arc<[Token]>, tracker: Collector| {
let mut collector = tracker;
collector.shared_tokens(tokens);
collector
};
let before = collect(&first, Collector::default());
let after = collect(&second, Collector::default());
assert_eq!(before.usage, after.usage);
let live = collect(&first, Collector::default().tracking_aliases());
let independent = collect(&second, Collector::default().tracking_aliases());
assert!(live.has_equivalent_history(&independent, &before, &after));
let detached = collect(&unrelated, Collector::default().tracking_aliases());
assert!(detached.has_equivalent_history(&detached, &before, &after));
assert!(!live.has_equivalent_history(&detached, &before, &after));
}
}