Preserve read evidence and box accounting in settled suffix reuse

This commit is contained in:
gloamxun committed 2026-12-02 00:47:50 +08:00
1 parent 473b3beace
commit f78aff25c5
12 files changed
+381 -46

No files matched your search

@@ -30,15 +30,42 @@ impl DependencyReads {
self.other.contains(&Dependency::ResourceStatistics)
}
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
let byte_catcodes = (0..=u8::MAX)
.filter(|&index| {
let index = usize::from(index);
self.byte_catcodes[index / 64] & (1 << (index % 64)) != 0
})
.map(|index| Dependency::CatCode(char::from(index)));
self.other.into_iter().chain(byte_catcodes).collect()
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)
}
/// 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]
})));
}
if self.other.len() != prior.other.len() {
into.extend(self.other.difference(&prior.other).cloned());
}
}
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
self.other
.into_iter()
.chain(byte_catcode_dependencies(self.byte_catcodes))
.collect()
}
}
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)))
}
impl Extend<Dependency> for DependencyReads {
@@ -53,6 +80,28 @@ impl Extend<Dependency> for DependencyReads {
mod tests {
use super::*;
#[test]
fn prefix_delta_keeps_old_suffix_observations() {
let mut prior = DependencyReads::default();
prior.extend([Dependency::CatCode('A'), Dependency::EndLineChar]);
let mut current = prior.clone();
current.extend([
Dependency::CatCode('ÿ'),
Dependency::CatCode('文'),
Dependency::ParagraphToken,
]);
assert!(prior.is_subset(&current));
assert!(!current.is_subset(&prior));
let mut reads = prior.clone().into_ordered();
reads.insert(Dependency::EscapeChar);
current.extend_ordered_delta(&prior, &mut reads);
let mut expected = current.into_ordered();
expected.insert(Dependency::EscapeChar);
assert_eq!(reads, expected);
}
#[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default();
@@ -3594,6 +3594,7 @@ impl Executor {
line_observations: Some(self.line_observations),
events: self.events.into_vec(),
steps: self.steps,
box_nodes_created: Some(self.box_nodes_created),
reads_event_history: self.reads_event_history,
accounts_event_history: self.accounts_event_history,
})
@@ -4100,6 +4101,7 @@ impl Executor {
line_observations: Some(self.line_observations),
incoming_state,
steps: self.steps,
box_nodes_created: Some(self.box_nodes_created),
reads_event_history: self.reads_event_history,
accounts_event_history: self.accounts_event_history,
})
@@ -1,5 +1,6 @@
use super::super::{
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::BoxNodeOffset,
};
use super::*;
use std::time::{Duration, Instant};
@@ -178,6 +179,26 @@ impl EntryCheckpoint {
{
return None;
}
let box_offset = BoxNodeOffset::new(old.box_nodes_created, current.box_nodes_created);
let box_nodes_created = match completed.box_nodes_created {
Some(donor) => Some(box_offset.apply(donor)?),
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;
}
}
let previous_bytes = &old.sources[self.entry].data;
let current_bytes = &current.sources[self.entry].data;
let entry_sizes = (previous_bytes.len() != current_bytes.len())
@@ -245,6 +266,16 @@ impl EntryCheckpoint {
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || {
let mut events = Vec::with_capacity(completed.events.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 mut execution = Execution {
format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(),
@@ -261,24 +292,32 @@ impl EntryCheckpoint {
sources,
stream_sources: completed.stream_sources.clone(),
generated_inputs: completed.generated_inputs.clone(),
reads: completed.reads.clone(),
reads,
line_observations,
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
steps,
box_nodes_created,
reads_event_history: false,
accounts_event_history: completed.accounts_event_history,
};
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
relocate::append_suffix(&mut execution, tail, offset, moved, sizes, old.sources.len())?;
relocate::append_suffix(
&mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(),
)?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
}
} else if offset.is_identity() {
} else if offset.is_identity() && box_offset.is_identity() {
execution.events.extend_from_slice(tail);
} else {
for event in tail {
execution.events.push(offset_event_steps(event, offset)?);
execution.events.push(match event {
Event::Statistics(report) => Event::Statistics(Box::new(
report.with_execution_offsets(offset, box_offset)?,
)),
_ => event.clone(),
});
}
}
Some(execution)
@@ -305,6 +344,18 @@ impl EntryCheckpoint {
{
return None;
}
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
|| current.meaning_reads.len() != old.meaning_reads.len()
|| 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
@@ -494,7 +545,6 @@ fn same_kernel_continuation(
limits,
interaction_mode,
stream_sources,
reads,
reads_tracing_macros,
in_csname,
command_trace_mode,
@@ -515,8 +565,6 @@ fn same_kernel_continuation(
restored_pdf_image_count,
format_image_warnings,
pdf_force_pagebox_warned,
box_nodes_created,
material_charge,
mark_cells_created,
diagnostic_bytes,
after_group_tokens,
@@ -550,6 +598,9 @@ fn same_kernel_continuation(
inputs,
sources,
steps,
box_nodes_created,
material_charge,
reads,
meaning_reads,
events,
reads_event_history,
@@ -576,9 +627,12 @@ fn same_kernel_continuation(
return false;
}
if current.events.len() != prior.events.len()
|| current.meaning_reads.len() != prior.meaning_reads.len()
|| !current.meaning_reads.keys().all(|name| prior.meaning_reads.contains_key(name))
|| current.inputs.len() != prior.inputs.len()
// Statistics membership also constrains source rebinding.
|| current.reads.observed_statistics() != prior.reads.observed_statistics()
|| !prior.reads.is_subset(&current.reads)
|| prior.meaning_reads.len() > current.meaning_reads.len()
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
{
return false;
}
@@ -1,5 +1,5 @@
use super::*;
use crate::execution::source_relocation_events::EventRelocation;
use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset};
pub(super) fn same_kernel_provenance(
current: &Executor,
@@ -107,6 +107,7 @@ pub(super) fn append_suffix(
execution: &mut Execution,
tail: &[Event],
offset: StepOffset,
boxes: BoxNodeOffset,
relocation: &mut EventRelocation<'_>,
(previous_bytes, current_bytes): (usize, usize),
source_count: usize,
@@ -123,7 +124,7 @@ pub(super) fn append_suffix(
}
}
let mut report = report
.with_step_offset(offset)?
.with_execution_offsets(offset, boxes)?
.with_suffix_entry_resize(previous_bytes, current_bytes)?;
report.span = map.relocate_span(report.span)?;
execution.events.push(Event::Statistics(Box::new(report)));
@@ -254,8 +254,9 @@ impl Executor {
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 steps separately and checks the job limit.
// 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; };
@@ -687,6 +687,9 @@ pub struct Execution {
pub incoming_state: u64,
pub outgoing_state: u64,
pub steps: usize,
/// Completed charge count for proving remaining box capacity at a splice.
#[serde(default, skip_serializing_if = "Option::is_none")]
box_nodes_created: Option<usize>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
reads_event_history: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
@@ -171,6 +171,32 @@ impl StepOffset {
}
}
/// 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))
}
}
impl StatisticsReport {
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
let text = phase.text();
@@ -224,13 +250,26 @@ impl StatisticsReport {
}
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> {
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 } => {
before.steps = offset.apply(before.steps)?;
after.steps = offset.apply(after.steps)?;
translate(before)?;
translate(after)?;
}
StatisticsPhase::End { usage, .. } => usage.steps = offset.apply(usage.steps)?,
StatisticsPhase::End { usage, .. } => translate(usage)?,
}
let report = Self::new(phase, self.destination, self.span);
report.within_diagnostic_budget().then_some(report)
@@ -616,6 +655,43 @@ impl Collector {
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 history_equivalence_keeps_aliases_that_cross_the_boundary() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
+6 -3
View File
@@ -1,6 +1,6 @@
//! pdfTeX-profile glyph-name mappings. Values retain PDF hex strings, including
//! explicitly supplied UTF-16 code units; they are not Rust Unicode labels.
use std::collections::BTreeMap;
use std::{collections::BTreeMap, sync::Arc};
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
enum Mapping {
@@ -10,7 +10,7 @@ enum Mapping {
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct GlyphUnicodeMap {
entries: BTreeMap<String, Mapping>,
entries: Arc<BTreeMap<String, Mapping>>,
}
fn upper_hex(s: &str) -> bool {
@@ -69,7 +69,7 @@ impl GlyphUnicodeMap {
}
}
};
self.entries.insert(glyph, mapping);
Arc::make_mut(&mut self.entries).insert(glyph, mapping);
warning
}
/// Resolve against the actual TFM namespace and encoding glyph name. An
@@ -185,10 +185,13 @@ mod tests {
] {
assert_eq!(map.lookup(font, name).as_deref(), expected, "{font}/{name}");
}
let snapshot = map.clone();
assert!(map.define("A".into(), "03b1").is_some());
assert!(Arc::ptr_eq(&map.entries, &snapshot.entries));
assert_eq!(map.lookup("g", "A").as_deref(), Some("0041"));
assert!(map.define("tfm:f/A".into(), "110000").is_some());
assert_eq!(map.lookup("f", "A"), None);
assert_eq!(snapshot.lookup("f", "A").as_deref(), Some("D83DDE00"));
assert_eq!(map.lookup("g", "A").as_deref(), Some("0041"));
}
}