Files
texrra-engine/crates/texrra-tex-core/src/execution/engine/statistics.rs
T

460 lines
17 KiB
Rust

use super::super::statistics::{
Collector,
Ownership::{Active, Retained},
RetainedHistoryOffset, SuffixSourceResize,
};
use super::*;
impl Executor {
fn stack_usage(&self) -> StackUsage {
StackUsage {
input_frames: self.inputs.len(),
groups: self.state.group_depth(),
box_frames: self.box_frames.len(),
math_frames: self.math.len(),
conditionals: self.conditionals.len(),
scanner_depth: self.scanner_depth,
expansion_depth: self.expansion_depth,
}
}
pub(super) fn observe_resource_stacks(&mut self) {
self.stack_peaks.include(&self.stack_usage());
}
pub(super) fn check_box_capacity(&mut self, shipping: Option<&NativeBox>) -> Result<(), Error> {
if self.material_charge <= self.limits.tokens {
return Ok(());
}
// Packing can move existing lists or replace an old register. Recount
// actual storage here, counting each shared list allocation once.
self.accounts_event_history = true;
let usage = self.collect_usage(shipping, None, Collector::for_capacity());
self.material_charge = usage
.active_material
.records()
.saturating_add(usage.retained_material.records());
if self.material_charge > self.limits.tokens {
return self.fail("native box node capacity exceeded");
}
Ok(())
}
fn resource_usage(
&mut self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
) -> ResourceUsage {
self.accounts_event_history = true;
self.collect_usage(shipping, host, Collector::default())
}
fn collect_usage(
&self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
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
}
fn collect_live_usage(
&self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
mut c: Collector,
) -> Collector {
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();
c.usage.box_nodes_created = self.box_nodes_created;
c.usage.diagnostic_bytes_generated = self.diagnostic_bytes;
c.usage.step_limit = self.limits.steps;
c.usage.token_limit = self.limits.tokens;
c.usage.input_depth_limit = self.limits.input_depth;
c.usage.stacks = self.stack_usage();
c.usage.stack_peaks = self.stack_peaks.clone();
c.usage.stack_peaks.include(&c.usage.stacks);
c.usage.host = host;
if let Some(p) = &self.paragraph {
c.paragraph_builder(p);
}
c.vertical(&self.vertical.nodes, Active);
c.vertical(&self.split_discards, Active);
if let Some(d) = &self.display {
d.collect_statistics(&mut c);
}
for b in &self.box_frames {
b.collect_statistics(&mut c);
}
for a in &self.alignments {
a.collect_statistics(&mut c);
}
for m in &self.math {
c.math_builder(m);
}
if let Some(f) = &self.output_frame {
f.collect_statistics(&mut c);
}
if let Some(p) = &self.native_page {
c.vertical(&p.nodes, Active);
c.vertical(&p.contributions, Active);
c.vertical(&p.discards, Active);
}
for b in &self.pending_shipouts {
c.native_box(b, Active);
}
if let Some(b) = shipping {
c.native_box(b, Active);
}
if self.after_assignment.is_some() {
c.usage.token_list_cells += 1;
}
c.usage.token_list_cells += self.pdf_catalog_tokens.len()
+ self.pdf_outlines.iter().map(|entry| entry.attributes.len()).sum::<usize>();
for input in &self.inputs {
match input {
InputFrame::Source { mouth, .. } => {
c.usage.mouth_payload_bytes += mouth.payload_bytes()
}
InputFrame::Tokens { tokens, .. } => c.usage.token_list_cells += tokens.len(),
InputFrame::Macro {
definition,
arguments,
..
} => {
c.macro_body(definition);
for a in arguments {
c.shared_tokens(a);
}
}
InputFrame::Argument { tokens, .. } | InputFrame::Hook { tokens, .. } => {
c.shared_tokens(tokens)
}
InputFrame::Boundary => {}
}
}
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;
}
c.usage.retained_events += 1;
match e {
Event::Shipout(s) => {
c.usage.retained_shipouts += 1;
c.native_box(&s.box_node, Retained);
}
Event::VerticalMaterial(v) => c.vertical(v, Retained),
Event::BuiltParagraph(p) => {
c.text(&p.nodes, Retained);
for b in &p.line_boxes {
c.native_box(b, Retained);
}
for v in &p.line_adjustments {
c.vertical(v, Retained);
}
for b in &p.diagnostic_lines {
c.shared_diagnostics(&b.nodes, Retained);
}
for paragraph in &p.lines {
for line in &paragraph.lines {
for item in line {
c.usage.retained_material.horizontal_nodes += 1;
if let crate::HorizontalItem::Box(b) = item {
c.horizontal_box(b, Retained);
}
}
}
}
}
Event::BuiltMath(m) => {
c.math(&m.noads, Retained);
c.text(&m.horizontal, Retained);
}
Event::BuiltDisplay(d) => c.native_box(&d.box_, Retained),
Event::DeferredOutput(o) => c.output(o),
_ => {}
}
}
}
fn collect_event_usage_pair(
current: &ExecutionEvents,
prior: &ExecutionEvents,
mut history: Collector,
) -> (Collector, Collector) {
// Identical sealed chunks also own the same allocations. Copy the
// accounting state at this boundary so each tail still deduplicates
// its references against the whole prefix.
let shared = current
.prefix
.iter()
.zip(&prior.prefix)
.take_while(|(a, b)| Arc::ptr_eq(a, b))
.count();
Self::collect_event_usage(
current.prefix[..shared].iter().flat_map(|chunk| chunk.iter()),
&mut history,
);
let mut old_history = history.clone();
for (events, counts) in [(current, &mut history), (prior, &mut old_history)] {
Self::collect_event_usage(
events.prefix[shared..]
.iter()
.flat_map(|chunk| chunk.iter())
.chain(&events.tail),
counts,
);
}
(history, old_history)
}
pub(super) fn resize_entry_statistics(
&mut self,
previous: usize,
current: usize,
replayed_entry_bytes: Option<u64>,
) -> Option<()> {
let events = self.events.prefix.iter_mut()
.filter(|chunk| chunk.iter().any(|event| matches!(event, Event::Statistics(_))))
.flat_map(|chunk| Arc::make_mut(chunk).iter_mut())
.chain(&mut self.events.tail);
for event in events {
if let Event::Statistics(report) = event {
report.resize_entry_payload(previous, current, replayed_entry_bytes)?;
}
}
Some(())
}
pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool {
self.equivalent_accounting_history_with_source_resize(old, None)
}
pub(super) fn equivalent_accounting_history_with_source_resize(
&self,
old: &Self,
resize: Option<SuffixSourceResize>,
) -> bool {
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
self.collect_compared_accounting(old, resize, collector).is_some_and(
|(live, old_live, history, old_history)| {
live.has_equivalent_history(&old_live, &history, &old_history)
},
)
})
}
pub(super) fn retained_history_offset(
&self,
old: &Self,
resize: Option<SuffixSourceResize>,
) -> Option<RetainedHistoryOffset> {
let (live, old_live, history, old_history) =
self.collect_compared_accounting(old, resize, Collector::default)?;
live.retained_history_offset(&old_live, &history, &old_history)
}
fn collect_compared_accounting(
&self,
old: &Self,
resize: Option<SuffixSourceResize>,
collector: fn() -> Collector,
) -> Option<(Collector, Collector, Collector, Collector)> {
// These containers may reintroduce previously retained allocations
// 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 None;
}
let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector());
let (live, old_live) = self.state.collect_compared_statistics(
&old.state, collector().tracking_aliases(),
)?;
let mut live = self.collect_live_usage(None, None, live);
let old_live = old.collect_live_usage(None, None, old_live);
// The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
if let Some(resize) = resize {
let (previous, current) = resize.sizes;
let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous);
live.usage.source_payload_bytes = restore(live.usage.source_payload_bytes)?;
if resize.active_at_anchor {
live.usage.mouth_payload_bytes = restore(live.usage.mouth_payload_bytes)?;
}
}
Some((live, old_live, history, old_history))
}
pub(super) fn statistics_before_shipout(
&mut self,
b: &NativeBox,
files: &mut impl SourceProvider,
) -> Result<Option<ResourceUsage>, Error> {
if self.read_parameter(Parameter::Tracingstats).width() <= 1 {
return Ok(None);
}
self.reads.insert(Dependency::ResourceStatistics);
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
Ok(Some(self.resource_usage(Some(b), host)))
}
pub(super) fn statistics_after_shipout(
&mut self,
before: Option<ResourceUsage>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let Some(before) = before else {
return Ok(());
};
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
let after = self.resource_usage(None, host);
self.emit_statistics(
StatisticsPhase::Shipout { before, after },
WriteDestination::TerminalAndLog,
files,
)
}
pub(super) fn statistics_end(
&mut self,
success: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Tracingstats).width() <= 0 {
return Ok(());
}
self.reads.insert(Dependency::ResourceStatistics);
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
let usage = self.resource_usage(None, host);
self.emit_statistics(
StatisticsPhase::End { success, usage },
WriteDestination::Log,
files,
)
}
fn emit_statistics(
&mut self,
phase: StatisticsPhase,
destination: WriteDestination,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let report = StatisticsReport::new(phase, destination, self.current);
self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(report.text.len());
if self.diagnostic_bytes > self.limits.tokens {
return self.fail("native diagnostic output limit exceeded");
}
files
.observe_statistics(&report)
.map_err(|e| self.error(e, self.current))?;
self.events.push(Event::Statistics(Box::new(report)));
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::statistics::BoxNodeOffset;
#[test]
fn equal_mark_events_with_different_aliases_cannot_carry_a_checkpoint() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let shared: Arc<[Token]> = Arc::from([token.clone()]);
let independent: Arc<[Token]> = Arc::from([token]);
let mark = |tokens| {
Event::VerticalMaterial(vec![NativeVerticalNode::Mark(NativeMark {
class: 0,
tokens,
span: Span::default(),
})])
};
let mut old = Executor::default();
old.state.page_marks.insert(0, PageMarks {
top: Some(shared.clone()),
..PageMarks::default()
});
let mut current = old.clone();
old.events.push(mark(shared.clone()));
old.events.push(mark(shared.clone()));
current.events.push(mark(shared));
current.events.push(mark(independent));
// Rebase's value comparison alone would retain the old Arc sharing.
assert!(current.events.iter().eq(old.events.iter()));
assert!(!current.equivalent_accounting_history(&old));
let offset = current.retained_history_offset(&old, None).unwrap();
assert!(!offset.is_identity());
let end_report = |engine: &Executor| {
StatisticsReport::new(
StatisticsPhase::End {
success: true,
usage: engine.collect_usage(None, None, Collector::default()),
},
WriteDestination::Log,
Span::default(),
)
};
assert_eq!(
end_report(&old).with_suffix_adjustments(
StepOffset::new(0, 0),
BoxNodeOffset::new(0, 0),
None,
Some(&offset),
),
Some(end_report(&current))
);
}
#[test]
fn shared_event_prefix_keeps_tail_deduplication_and_membership() {
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 current = ExecutionEvents::default();
current.push(mark(shared.clone()));
current.seal_prefix();
let mut prior = current.clone();
current.push(mark(shared.clone()));
prior.push(mark(independent.clone()));
for collector in [Collector::for_capacity, Collector::default] {
let (history, old_history) =
Executor::collect_event_usage_pair(&current, &prior, collector());
assert_eq!(history.usage.token_list_cells, 1);
assert_eq!(old_history.usage.token_list_cells, 2);
let mut live = collector().tracking_aliases();
live.shared_tokens(&shared);
live.shared_tokens(&independent);
for (events, paired) in [(&current, history), (&prior, old_history)] {
let mut full = collector();
Executor::collect_event_usage(events.iter(), &mut full);
assert!(live.has_equivalent_history(&live, &paired, &full));
}
}
}
}