1053 lines
40 KiB
Rust
1053 lines
40 KiB
Rust
//! Measured native storage and execution resources, not invented TeX arena words.
|
|
use super::*;
|
|
use std::{
|
|
collections::{BTreeSet, HashMap, HashSet, hash_map::Entry},
|
|
sync::Arc,
|
|
};
|
|
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct MaterialUsage {
|
|
pub boxes: usize,
|
|
pub horizontal_nodes: usize,
|
|
pub vertical_nodes: usize,
|
|
pub math_nodes: usize,
|
|
pub geometry_items: usize,
|
|
pub diagnostic_nodes: usize,
|
|
pub ligature_work_items: usize,
|
|
}
|
|
impl MaterialUsage {
|
|
pub fn records(&self) -> usize {
|
|
self.boxes
|
|
+ self.horizontal_nodes
|
|
+ self.vertical_nodes
|
|
+ self.math_nodes
|
|
+ self.geometry_items
|
|
+ self.diagnostic_nodes
|
|
+ self.ligature_work_items
|
|
}
|
|
}
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct StateUsage {
|
|
pub command_entries: usize,
|
|
pub control_name_bytes: usize,
|
|
pub macro_bindings: usize,
|
|
pub token_registers: usize,
|
|
pub parameter_entries: usize,
|
|
pub register_entries: usize,
|
|
pub code_entries: usize,
|
|
pub save_entries: usize,
|
|
pub font_instances: usize,
|
|
pub font_parameter_cells: usize,
|
|
pub tfm_resources: usize,
|
|
/// Size of the actual TFM resource versions, not Rust heap allocation bytes.
|
|
pub tfm_resource_bytes: u64,
|
|
pub hyphenation_exceptions: usize,
|
|
pub hyphenation_trie_nodes: usize,
|
|
pub hyphenation_edges: usize,
|
|
pub pattern_weight_cells: usize,
|
|
}
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct StackUsage {
|
|
pub input_frames: usize,
|
|
pub groups: usize,
|
|
pub box_frames: usize,
|
|
pub math_frames: usize,
|
|
pub conditionals: usize,
|
|
pub scanner_depth: usize,
|
|
pub expansion_depth: usize,
|
|
}
|
|
impl StackUsage {
|
|
pub(super) fn include(&mut self, other: &Self) {
|
|
self.input_frames = self.input_frames.max(other.input_frames);
|
|
self.groups = self.groups.max(other.groups);
|
|
self.box_frames = self.box_frames.max(other.box_frames);
|
|
self.math_frames = self.math_frames.max(other.math_frames);
|
|
self.conditionals = self.conditionals.max(other.conditionals);
|
|
self.scanner_depth = self.scanner_depth.max(other.scanner_depth);
|
|
self.expansion_depth = self.expansion_depth.max(other.expansion_depth);
|
|
}
|
|
}
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct HostResourceUsage {
|
|
pub lookups: usize,
|
|
pub negative_lookups: usize,
|
|
pub failed_lookups: usize,
|
|
pub resource_reads: usize,
|
|
pub resource_bytes_read: u64,
|
|
pub stream_read_calls: usize,
|
|
pub stream_bytes_read: u64,
|
|
pub read_errors: usize,
|
|
pub open_inputs: Option<usize>,
|
|
pub open_outputs: Option<usize>,
|
|
}
|
|
impl HostResourceUsage {
|
|
pub fn rebind_entry_bytes(&mut self, previous: u64, current: u64) -> Option<()> {
|
|
self.resource_bytes_read = self.resource_bytes_read.checked_sub(previous)?.checked_add(current)?;
|
|
Some(())
|
|
}
|
|
|
|
pub fn from_trace(trace: &crate::resources::ResourceTrace) -> Self {
|
|
Self {
|
|
lookups: trace.lookups.len(),
|
|
negative_lookups: trace
|
|
.lookups
|
|
.iter()
|
|
.filter(|v| v.resolved.is_none() && v.error.is_none())
|
|
.count(),
|
|
failed_lookups: trace.lookups.iter().filter(|v| v.error.is_some()).count(),
|
|
resource_reads: trace.reads.len(),
|
|
resource_bytes_read: trace.reads.iter().map(|v| v.bytes).sum(),
|
|
stream_read_calls: trace.stream_reads.len(),
|
|
stream_bytes_read: trace.stream_reads.iter().map(|v| v.bytes).sum(),
|
|
read_errors: trace.read_errors.len(),
|
|
open_inputs: None,
|
|
open_outputs: None,
|
|
}
|
|
}
|
|
}
|
|
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct ResourceUsage {
|
|
pub steps: usize,
|
|
pub source_files: usize,
|
|
pub source_payload_bytes: usize,
|
|
pub mouth_payload_bytes: usize,
|
|
pub unique_macro_bodies: usize,
|
|
pub macro_token_cells: usize,
|
|
pub token_list_cells: usize,
|
|
pub state: StateUsage,
|
|
pub active_material: MaterialUsage,
|
|
pub retained_material: MaterialUsage,
|
|
/// Runtime events excluding statistics reports themselves.
|
|
pub retained_events: usize,
|
|
pub retained_shipouts: usize,
|
|
/// Cumulative node visits charged by packing and copying operations, including transfers.
|
|
pub box_nodes_created: usize,
|
|
pub diagnostic_bytes_generated: usize,
|
|
pub stacks: StackUsage,
|
|
pub stack_peaks: StackUsage,
|
|
pub step_limit: usize,
|
|
pub token_limit: usize,
|
|
pub input_depth_limit: usize,
|
|
/// None means this host does not supply resource telemetry; never fake zero.
|
|
pub host: Option<HostResourceUsage>,
|
|
}
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub enum StatisticsPhase {
|
|
Shipout {
|
|
before: ResourceUsage,
|
|
after: ResourceUsage,
|
|
},
|
|
End {
|
|
success: bool,
|
|
usage: ResourceUsage,
|
|
},
|
|
}
|
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
pub struct StatisticsReport {
|
|
pub phase: StatisticsPhase,
|
|
pub destination: WriteDestination,
|
|
pub text: String,
|
|
pub span: Span,
|
|
}
|
|
|
|
/// Maps monotone step counts after one command boundary onto another.
|
|
#[derive(Clone, Copy)]
|
|
pub struct StepOffset {
|
|
previous: usize,
|
|
current: usize,
|
|
}
|
|
|
|
impl StepOffset {
|
|
pub fn new(previous: usize, current: usize) -> Self {
|
|
Self { previous, current }
|
|
}
|
|
|
|
pub fn is_identity(self) -> bool {
|
|
self.previous == self.current
|
|
}
|
|
|
|
pub fn apply(self, steps: usize) -> Option<usize> {
|
|
self.current.checked_add(steps.checked_sub(self.previous)?)
|
|
}
|
|
}
|
|
|
|
/// Translate the cumulative, saturating count of box node visits.
|
|
#[derive(Clone, Copy)]
|
|
pub(super) struct BoxNodeOffset {
|
|
previous: usize,
|
|
current: usize,
|
|
}
|
|
|
|
impl BoxNodeOffset {
|
|
pub(super) fn new(previous: usize, current: usize) -> Self {
|
|
Self { previous, current }
|
|
}
|
|
|
|
pub(super) fn is_identity(self) -> bool {
|
|
self.previous == self.current
|
|
}
|
|
|
|
pub(super) fn apply(self, nodes: usize) -> Option<usize> {
|
|
let suffix_nodes = nodes.checked_sub(self.previous)?;
|
|
// A saturated donor does not reveal how much work would survive a decrease.
|
|
if self.current < self.previous && nodes == usize::MAX {
|
|
return None;
|
|
}
|
|
Some(self.current.saturating_add(suffix_nodes))
|
|
}
|
|
}
|
|
|
|
#[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(())
|
|
}
|
|
}
|
|
|
|
/// Byte counts affected by the sole changed physical source at convergence.
|
|
#[derive(Clone, Copy)]
|
|
pub(super) struct SuffixSourceResize {
|
|
pub(super) sizes: (usize, usize),
|
|
pub(super) active_at_anchor: bool,
|
|
pub(super) prefix_resource_reads: usize,
|
|
}
|
|
|
|
impl SuffixSourceResize {
|
|
pub(super) fn entry(sizes: (usize, usize)) -> Self {
|
|
Self {
|
|
sizes,
|
|
active_at_anchor: true,
|
|
prefix_resource_reads: 1,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl StatisticsReport {
|
|
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
|
|
let text = phase.text();
|
|
Self { phase, destination, text, span }
|
|
}
|
|
|
|
pub(super) fn resize_entry_payload(
|
|
&mut self,
|
|
previous: usize,
|
|
current: usize,
|
|
replayed_entry_bytes: Option<u64>,
|
|
) -> Option<()> {
|
|
// Closeout reports are produced only after resuming, never captured
|
|
// in an executable prefix. Shipout text does not print byte totals.
|
|
let StatisticsPhase::Shipout { before, after } = &mut self.phase else {
|
|
return None;
|
|
};
|
|
for usage in [before, after] {
|
|
if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() {
|
|
return None;
|
|
}
|
|
usage.resize_source_payload(SuffixSourceResize::entry((previous, current)), true)?;
|
|
}
|
|
debug_assert_eq!(self.text, self.phase.text());
|
|
Some(())
|
|
}
|
|
|
|
/// 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> {
|
|
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> {
|
|
self.with_execution_offsets(offset, BoxNodeOffset::new(0, 0))
|
|
}
|
|
|
|
pub(super) fn with_execution_offsets(
|
|
&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> {
|
|
self.with_source_resize(steps, boxes, entry_sizes.map(SuffixSourceResize::entry), history)
|
|
}
|
|
|
|
pub(super) fn with_source_resize(
|
|
&self,
|
|
steps: StepOffset,
|
|
boxes: BoxNodeOffset,
|
|
resize: Option<SuffixSourceResize>,
|
|
history: Option<&RetainedHistoryOffset>,
|
|
) -> Option<Self> {
|
|
let translate = |usage: &mut ResourceUsage| {
|
|
usage.steps = steps.apply(usage.steps)?;
|
|
usage.box_nodes_created = boxes.apply(usage.box_nodes_created)?;
|
|
Some(())
|
|
};
|
|
let mut phase = self.phase.clone();
|
|
match &mut phase {
|
|
StatisticsPhase::Shipout { before, after } => {
|
|
if history.is_some_and(|offset| !offset.is_identity()) {
|
|
return None;
|
|
}
|
|
for usage in [before, after] {
|
|
translate(usage)?;
|
|
if let Some(resize) = resize {
|
|
let active = resize.active_at_anchor && usage.mouth_payload_bytes == resize.sizes.0;
|
|
if resize.active_at_anchor && !active && usage.mouth_payload_bytes != 0 {
|
|
return None;
|
|
}
|
|
usage.resize_source_payload(resize, active)?;
|
|
}
|
|
}
|
|
}
|
|
StatisticsPhase::End { usage, .. } => {
|
|
translate(usage)?;
|
|
if let Some(resize) = resize {
|
|
if resize.active_at_anchor
|
|
&& (usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0)
|
|
{
|
|
return None;
|
|
}
|
|
usage.resize_source_payload(resize, false)?;
|
|
}
|
|
if let Some(offset) = history {
|
|
offset.replace_prefix(usage)?;
|
|
}
|
|
}
|
|
}
|
|
let report = Self::new(phase, self.destination, self.span);
|
|
report.within_diagnostic_budget().then_some(report)
|
|
}
|
|
|
|
fn within_diagnostic_budget(&self) -> bool {
|
|
match &self.phase {
|
|
StatisticsPhase::End { usage, .. } => usage
|
|
.diagnostic_bytes_generated
|
|
.checked_add(self.text.len())
|
|
.is_some_and(|bytes| bytes <= usage.token_limit),
|
|
StatisticsPhase::Shipout { .. } => true,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl ResourceUsage {
|
|
fn resize_source_payload(&mut self, resize: SuffixSourceResize, active: bool) -> Option<()> {
|
|
let (previous, current) = resize.sizes;
|
|
self.source_payload_bytes = self.source_payload_bytes.checked_sub(previous)?.checked_add(current)?;
|
|
if active {
|
|
self.mouth_payload_bytes = self.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?;
|
|
}
|
|
if let Some(host) = &mut self.host {
|
|
let reads = u64::try_from(resize.prefix_resource_reads).ok()?;
|
|
let previous = u64::try_from(previous).ok()?.checked_mul(reads)?;
|
|
let current = u64::try_from(current).ok()?.checked_mul(reads)?;
|
|
host.rebind_entry_bytes(previous, current)?;
|
|
}
|
|
Some(())
|
|
}
|
|
}
|
|
|
|
impl StatisticsPhase {
|
|
fn text(&self) -> String {
|
|
match self {
|
|
Self::Shipout { before, after } => {
|
|
format!(
|
|
"Route-D resources at shipout: active records {} -> {}; retained records {} -> {}; token cells {} -> {}; retained pages {}.\n",
|
|
before.active_material.records(),
|
|
after.active_material.records(),
|
|
before.retained_material.records(),
|
|
after.retained_material.records(),
|
|
before.macro_token_cells + before.token_list_cells,
|
|
after.macro_token_cells + after.token_list_cells,
|
|
after.retained_shipouts
|
|
)
|
|
}
|
|
Self::End { success, usage } => {
|
|
let mut text = format!(
|
|
"Route-D resource usage at core execution end ({}):\n {} steps out of {}\n {} source files, {} source payload bytes, {} active mouth payload bytes\n {} command entries, {} control-name bytes\n {} macro bindings, {} unique macro bodies, {} macro token cells\n {} token-list cells, {} saved entries\n {} active material records, {} retained material records, {} retained pages\n {} font instances, {} font parameter cells, {} TFM resources / {} source bytes\n {} hyphenation exceptions\n stack peaks: {} input, {} group, {} box, {} math, {} conditional, {} scanner, {} expansion\n",
|
|
if *success { "success" } else { "failure" },
|
|
usage.steps,
|
|
usage.step_limit,
|
|
usage.source_files,
|
|
usage.source_payload_bytes,
|
|
usage.mouth_payload_bytes,
|
|
usage.state.command_entries,
|
|
usage.state.control_name_bytes,
|
|
usage.state.macro_bindings,
|
|
usage.unique_macro_bodies,
|
|
usage.macro_token_cells,
|
|
usage.token_list_cells,
|
|
usage.state.save_entries,
|
|
usage.active_material.records(),
|
|
usage.retained_material.records(),
|
|
usage.retained_shipouts,
|
|
usage.state.font_instances,
|
|
usage.state.font_parameter_cells,
|
|
usage.state.tfm_resources,
|
|
usage.state.tfm_resource_bytes,
|
|
usage.state.hyphenation_exceptions,
|
|
usage.stack_peaks.input_frames,
|
|
usage.stack_peaks.groups,
|
|
usage.stack_peaks.box_frames,
|
|
usage.stack_peaks.math_frames,
|
|
usage.stack_peaks.conditionals,
|
|
usage.stack_peaks.scanner_depth,
|
|
usage.stack_peaks.expansion_depth
|
|
);
|
|
if let Some(h) = &usage.host {
|
|
text.push_str(&format!(" host resources: {} reads / {} bytes; {} lookups / {} misses / {} errors; {} stream reads / {} bytes\n",h.resource_reads,h.resource_bytes_read,h.lookups,h.negative_lookups,h.failed_lookups,h.stream_read_calls,h.stream_bytes_read));
|
|
} else {
|
|
text.push_str(" host resource telemetry unavailable\n");
|
|
}
|
|
text
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
pub(super) enum Ownership {
|
|
Active,
|
|
Retained,
|
|
}
|
|
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
|
|
enum Allocation {
|
|
Macro(usize),
|
|
Tokens(usize, usize),
|
|
Material(usize),
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct AliasVisits {
|
|
ordinals: HashMap<Allocation, usize>,
|
|
visits: Vec<(Allocation, usize)>,
|
|
}
|
|
|
|
impl AliasVisits {
|
|
fn record(&mut self, allocation: Allocation) -> bool {
|
|
let next = self.ordinals.len();
|
|
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,
|
|
// 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>>,
|
|
aliases: Option<AliasVisits>,
|
|
}
|
|
impl Collector {
|
|
pub fn for_capacity() -> Self {
|
|
Self {
|
|
shared_lists: Some(BTreeSet::new()),
|
|
..Self::default()
|
|
}
|
|
}
|
|
|
|
pub(super) fn tracking_aliases(mut self) -> Self {
|
|
self.aliases.get_or_insert_with(AliasVisits::default);
|
|
self
|
|
}
|
|
|
|
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)),
|
|
Allocation::Material(address) => self
|
|
.shared_lists
|
|
.as_ref()
|
|
.is_some_and(|lists| lists.contains(&address)),
|
|
}
|
|
}
|
|
|
|
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
|
|
&& 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>) {
|
|
let address = Arc::as_ptr(m) as usize;
|
|
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>()
|
|
+ m.replacement.len();
|
|
}
|
|
}
|
|
pub fn shared_tokens(&mut self, t: &Arc<[Token]>) {
|
|
let address = t.as_ptr() as usize;
|
|
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 {
|
|
match o {
|
|
Ownership::Active => &mut self.usage.active_material,
|
|
Ownership::Retained => &mut self.usage.retained_material,
|
|
}
|
|
}
|
|
pub fn output(&mut self, n: &OutputNode) {
|
|
if let OutputOperation::Write { tokens, .. }
|
|
| OutputOperation::PdfLiteral { tokens, .. }
|
|
| OutputOperation::Special { tokens, .. } = &n.operation
|
|
{
|
|
self.usage.token_list_cells += tokens.len();
|
|
}
|
|
}
|
|
pub fn native_box(&mut self, b: &NativeBox, o: Ownership) {
|
|
self.material(o).boxes += 1;
|
|
match &b.content {
|
|
BoxContent::Horizontal(v) if self.visit_shared(v) => self.text(v, o),
|
|
BoxContent::Vertical(v) if self.visit_shared(v) => self.vertical(v.iter(), o),
|
|
_ => {}
|
|
}
|
|
self.shared_diagnostics(&b.diagnostic, o);
|
|
}
|
|
pub fn horizontal_box(&mut self, b: &crate::HorizontalBox, o: Ownership) {
|
|
if let Some(b) = &b.native_box {
|
|
self.native_box(b, o);
|
|
}
|
|
if let Some(g) = &b.math_geometry {
|
|
self.material(o).geometry_items += g.items.len();
|
|
}
|
|
}
|
|
fn leader_pattern(&mut self, leader: &LeaderGlue, o: Ownership) {
|
|
match &leader.pattern {
|
|
LeaderPattern::Box(b) => self.native_box(b, o),
|
|
LeaderPattern::Rule(_) => self.material(o).geometry_items += 1,
|
|
}
|
|
}
|
|
pub fn text(&mut self, nodes: &[TextNode], o: Ownership) {
|
|
self.material(o).horizontal_nodes += nodes.len();
|
|
for n in nodes {
|
|
match n {
|
|
TextNode::Glyph { glyph, .. }
|
|
| TextNode::Box(glyph)
|
|
| TextNode::MathChar(glyph) => self.horizontal_box(glyph, o),
|
|
TextNode::Discretionary {
|
|
pre_break,
|
|
post_break,
|
|
..
|
|
} => {
|
|
self.text(pre_break, o);
|
|
self.text(post_break, o);
|
|
}
|
|
TextNode::Mark(m) => self.shared_tokens(&m.tokens),
|
|
TextNode::Adjustment(value) => self.vertical(&value.nodes, o),
|
|
TextNode::Insertion(n) => self.vertical(&n.nodes, o),
|
|
TextNode::Output(v) => self.output(v),
|
|
TextNode::Leaders(leader) => self.leader_pattern(leader, o),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
pub fn vertical<'a>(
|
|
&mut self,
|
|
nodes: impl IntoIterator<Item = &'a NativeVerticalNode>,
|
|
o: Ownership,
|
|
) {
|
|
for n in nodes {
|
|
self.material(o).vertical_nodes += 1;
|
|
match n {
|
|
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => self.native_box(b, o),
|
|
NativeVerticalNode::Mark(m) => self.shared_tokens(&m.tokens),
|
|
NativeVerticalNode::Insertion(n) => self.vertical(&n.nodes, o),
|
|
NativeVerticalNode::Output(v) => self.output(v),
|
|
NativeVerticalNode::Leaders(leader) => self.leader_pattern(leader, o),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
pub fn math(&mut self, nodes: &[MathNode], o: Ownership) {
|
|
self.material(o).math_nodes += nodes.len();
|
|
for n in nodes {
|
|
match n {
|
|
MathNode::Noad(n) => {
|
|
self.field(&n.nucleus, o);
|
|
if let Some(f) = &n.sub {
|
|
self.field(f, o);
|
|
}
|
|
if let Some(f) = &n.sup {
|
|
self.field(f, o);
|
|
}
|
|
}
|
|
MathNode::Fraction {
|
|
numerator,
|
|
denominator,
|
|
..
|
|
} => {
|
|
self.math(numerator, o);
|
|
self.math(denominator, o);
|
|
}
|
|
MathNode::Choice(branches) => {
|
|
for branch in branches.iter() {
|
|
self.math(branch, o);
|
|
}
|
|
}
|
|
MathNode::Discretionary(n) => self.text(std::slice::from_ref(n.as_ref()), o),
|
|
MathNode::Mark(m) => self.shared_tokens(&m.tokens),
|
|
MathNode::Adjustment(value) => self.vertical(&value.nodes, o),
|
|
MathNode::Insertion(n) => self.vertical(&n.nodes, o),
|
|
MathNode::Output(v) => self.output(v),
|
|
MathNode::Leaders(leader) => self.leader_pattern(leader, o),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
fn field(&mut self, f: &MathField, o: Ownership) {
|
|
match f {
|
|
MathField::List(v) => self.math(v, o),
|
|
MathField::Radical(_, nucleus) => self.field(nucleus, o),
|
|
MathField::Box(b) => self.native_box(b, o),
|
|
_ => {}
|
|
}
|
|
}
|
|
pub fn math_builder(&mut self, b: &super::math::MathBuilder) {
|
|
self.math(&b.nodes, Ownership::Active);
|
|
if let Some(fraction) = &b.numerator {
|
|
self.math(&fraction.numerator, Ownership::Active);
|
|
}
|
|
}
|
|
pub fn paragraph_builder(&mut self, b: &super::paragraph::Builder) {
|
|
self.text(&b.nodes, Ownership::Active);
|
|
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 let Some(aliases) = &mut self.aliases {
|
|
aliases.record(Allocation::Material(address)) && !seen.contains(&address)
|
|
} else {
|
|
seen.insert(address)
|
|
}
|
|
}
|
|
|
|
pub fn shared_diagnostics(
|
|
&mut self,
|
|
nodes: &Arc<[super::diagnostics::DiagnosticNode]>,
|
|
o: Ownership,
|
|
) {
|
|
if !nodes.is_empty() && self.visit_shared(nodes) {
|
|
self.diagnostics(nodes, o);
|
|
}
|
|
}
|
|
|
|
fn diagnostics(&mut self, nodes: &[super::diagnostics::DiagnosticNode], o: Ownership) {
|
|
use super::diagnostics::DiagnosticNode as D;
|
|
self.material(o).diagnostic_nodes += nodes.len();
|
|
for n in nodes {
|
|
match n {
|
|
D::Box(b) => self.shared_diagnostics(&b.nodes, o),
|
|
D::Leaders { pattern, .. } => {
|
|
self.diagnostics(std::slice::from_ref(pattern.as_ref()), o)
|
|
}
|
|
D::Discretionary { pre, post, .. } => {
|
|
self.diagnostics(pre, o);
|
|
self.diagnostics(post, o);
|
|
}
|
|
D::Mark(m) => self.shared_tokens(&m.tokens),
|
|
D::Adjustment { nodes, .. } | D::Insertion { nodes, .. } => {
|
|
self.diagnostics(nodes, o)
|
|
}
|
|
D::Output(v) => self.output(v),
|
|
_ => {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn box_node_offsets_require_an_exact_saturating_count() {
|
|
let max = usize::MAX;
|
|
assert_eq!(BoxNodeOffset::new(10, 12).apply(17), Some(19));
|
|
assert_eq!(BoxNodeOffset::new(12, 10).apply(17), Some(15));
|
|
assert_eq!(BoxNodeOffset::new(12, 10).apply(11), None);
|
|
assert_eq!(BoxNodeOffset::new(10, 12).apply(max - 1), Some(max));
|
|
assert_eq!(BoxNodeOffset::new(10, 12).apply(max), Some(max));
|
|
assert_eq!(BoxNodeOffset::new(10, 10).apply(max), Some(max));
|
|
assert_eq!(BoxNodeOffset::new(12, 10).apply(max), None);
|
|
}
|
|
|
|
#[test]
|
|
fn statistics_translate_box_counts_without_changing_the_transcript() {
|
|
let usage = |box_nodes_created| ResourceUsage {
|
|
box_nodes_created,
|
|
token_limit: 4096,
|
|
..ResourceUsage::default()
|
|
};
|
|
let translate = |old, expected| {
|
|
let report = StatisticsReport::new(old, WriteDestination::Log, Span::default());
|
|
let updated = report
|
|
.with_execution_offsets(StepOffset::new(0, 0), BoxNodeOffset::new(2, 7))
|
|
.unwrap();
|
|
assert_eq!(updated.phase, expected);
|
|
assert_eq!(updated.text, report.text);
|
|
};
|
|
translate(
|
|
StatisticsPhase::Shipout { before: usage(5), after: usage(8) },
|
|
StatisticsPhase::Shipout { before: usage(10), after: usage(13) },
|
|
);
|
|
translate(
|
|
StatisticsPhase::End { success: true, usage: usage(8) },
|
|
StatisticsPhase::End { success: true, usage: usage(13) },
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn suffix_adjustments_check_only_the_final_diagnostic_budget() {
|
|
let report = |usage| {
|
|
StatisticsReport::new(
|
|
StatisticsPhase::End { success: true, usage },
|
|
WriteDestination::Log,
|
|
Span::default(),
|
|
)
|
|
};
|
|
let mut usage = ResourceUsage {
|
|
steps: 9,
|
|
source_payload_bytes: 10,
|
|
..ResourceUsage::default()
|
|
};
|
|
usage.token_limit = report(usage.clone()).text.len();
|
|
let original = report(usage.clone());
|
|
let steps = StepOffset::new(0, 1);
|
|
assert!(original.with_step_offset(steps).is_none());
|
|
|
|
usage.steps = 10;
|
|
usage.source_payload_bytes = 9;
|
|
assert_eq!(
|
|
original.with_suffix_adjustments(
|
|
steps, BoxNodeOffset::new(0, 0), Some((10, 9)), None,
|
|
),
|
|
Some(report(usage))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn retained_history_offsets_require_shared_token_membership() {
|
|
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
|
|
let retained: Arc<[Token]> = Arc::from([token.clone()]);
|
|
let old_retained: Arc<[Token]> = Arc::from([token.clone()]);
|
|
let extra: Arc<[Token]> = Arc::from([token.clone(), token]);
|
|
let mut live = Collector::default().tracking_aliases();
|
|
live.shared_tokens(&retained);
|
|
let mut old_live = Collector::default().tracking_aliases();
|
|
old_live.shared_tokens(&old_retained);
|
|
let mut history = Collector::default();
|
|
history.shared_tokens(&retained);
|
|
history.shared_tokens(&extra);
|
|
history.usage.retained_events = 3;
|
|
history.usage.retained_material.horizontal_nodes = 5;
|
|
let mut old_history = Collector::default();
|
|
old_history.shared_tokens(&old_retained);
|
|
old_history.usage.retained_events = 2;
|
|
old_history.usage.retained_material.horizontal_nodes = 1;
|
|
|
|
assert!(!live.has_equivalent_history(&old_live, &history, &old_history));
|
|
let offset = live.retained_history_offset(&old_live, &history, &old_history).unwrap();
|
|
assert!(!offset.is_identity());
|
|
assert!(
|
|
old_live.retained_history_offset(&old_live, &history, &old_history).is_none()
|
|
);
|
|
|
|
let mut usage = ResourceUsage {
|
|
token_list_cells: 8,
|
|
retained_events: 4,
|
|
retained_material: MaterialUsage { horizontal_nodes: 3, ..MaterialUsage::default() },
|
|
token_limit: 4096,
|
|
..ResourceUsage::default()
|
|
};
|
|
let report = StatisticsReport::new(
|
|
StatisticsPhase::End { success: true, usage: usage.clone() },
|
|
WriteDestination::Log,
|
|
Span::default(),
|
|
);
|
|
usage.token_list_cells = 10;
|
|
usage.retained_events = 5;
|
|
usage.retained_material.horizontal_nodes = 7;
|
|
assert_eq!(
|
|
report.with_suffix_adjustments(
|
|
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), None, Some(&offset),
|
|
).unwrap(),
|
|
StatisticsReport::new(
|
|
StatisticsPhase::End { success: true, usage },
|
|
WriteDestination::Log,
|
|
Span::default(),
|
|
)
|
|
);
|
|
let overflow = StatisticsReport::new(
|
|
StatisticsPhase::End {
|
|
success: true,
|
|
usage: ResourceUsage {
|
|
retained_material: MaterialUsage {
|
|
boxes: usize::MAX - 1,
|
|
horizontal_nodes: 1,
|
|
..MaterialUsage::default()
|
|
},
|
|
token_limit: 4096,
|
|
..old_history.usage
|
|
},
|
|
},
|
|
WriteDestination::Log,
|
|
Span::default(),
|
|
);
|
|
assert!(overflow.with_suffix_adjustments(
|
|
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), None, Some(&offset),
|
|
).is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn closed_source_resize_counts_each_host_read_and_leaves_other_mouths() {
|
|
let usage = ResourceUsage {
|
|
source_payload_bytes: 50,
|
|
mouth_payload_bytes: 30,
|
|
host: Some(HostResourceUsage {
|
|
resource_reads: 5,
|
|
resource_bytes_read: 100,
|
|
..HostResourceUsage::default()
|
|
}),
|
|
token_limit: 4096,
|
|
..ResourceUsage::default()
|
|
};
|
|
let resize = SuffixSourceResize {
|
|
sizes: (8, 11),
|
|
active_at_anchor: false,
|
|
prefix_resource_reads: 3,
|
|
};
|
|
let report = StatisticsReport::new(
|
|
StatisticsPhase::Shipout { before: usage.clone(), after: usage },
|
|
WriteDestination::Log,
|
|
Span::default(),
|
|
);
|
|
let adjusted = report.with_source_resize(
|
|
StepOffset::new(0, 0), BoxNodeOffset::new(0, 0), Some(resize), None,
|
|
).unwrap();
|
|
assert_eq!(adjusted.text, report.text);
|
|
let StatisticsPhase::Shipout { before, after } = adjusted.phase else {
|
|
unreachable!();
|
|
};
|
|
for usage in [before, after] {
|
|
assert_eq!(usage.source_payload_bytes, 53);
|
|
assert_eq!(usage.mouth_payload_bytes, 30);
|
|
let host = usage.host.unwrap();
|
|
assert_eq!(host.resource_reads, 5);
|
|
assert_eq!(host.resource_bytes_read, 109);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn tracked_macro_counts_share_the_ordinal_index_without_losing_visits() {
|
|
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
|
|
let body = Arc::new(Macro {
|
|
prefix: Vec::new(),
|
|
parameters: Vec::new(),
|
|
parameter_chars: Vec::new(),
|
|
replacement: vec![Replacement::Token(token.clone())],
|
|
long: false,
|
|
outer: false,
|
|
protected: false,
|
|
});
|
|
let independent = Arc::new((*body).clone());
|
|
let tokens: Arc<[Token]> = Arc::from([token]);
|
|
let mut history = Collector::default();
|
|
let mut live = Collector::default().tracking_aliases();
|
|
for collector in [&mut history, &mut live] {
|
|
collector.macro_body(&body);
|
|
collector.shared_tokens(&tokens);
|
|
collector.macro_body(&body);
|
|
collector.macro_body(&independent);
|
|
}
|
|
|
|
assert_eq!(live.usage, history.usage);
|
|
assert_eq!(live.usage.unique_macro_bodies, 2);
|
|
assert!(live.macros.is_empty());
|
|
assert!(live.token_lists.is_empty());
|
|
let visits = &live.aliases.as_ref().unwrap().visits;
|
|
assert_eq!(visits.iter().map(|(_, ordinal)| *ordinal).collect::<Vec<_>>(), [0, 1, 0, 2]);
|
|
assert!(visits.iter().all(|(allocation, _)| {
|
|
history.contains(*allocation) && live.contains(*allocation)
|
|
}));
|
|
|
|
let mut previously_counted = history.clone().tracking_aliases();
|
|
previously_counted.macro_body(&body);
|
|
assert_eq!(previously_counted.usage, history.usage);
|
|
}
|
|
|
|
#[test]
|
|
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));
|
|
}
|
|
}
|