Reuse settled suffixes after verified closed child edits

This commit is contained in:
gloamxun committed 2026-12-02 01:53:20 +08:00
1 parent 55c497dccd
commit e4d6e049f8
11 files changed
+565 -72

No files matched your search

@@ -44,7 +44,7 @@ mod scheduling;
mod specials;
mod statistics;
mod continuation;
pub use continuation::{RelocatedShipoutSuffix, SuffixKernelTimings};
pub use continuation::{ClosedSourceChange, RelocatedShipoutSuffix, SuffixKernelTimings};
mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -1,7 +1,7 @@
use super::super::{
dependency_reads::DependencyEvidence,
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::{BoxNodeOffset, RetainedHistoryOffset},
statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize},
};
use super::*;
use std::time::{Duration, Instant};
@@ -123,7 +123,71 @@ impl RelocatedShipoutSuffix {
}
}
/// One changed physical child whose scanner has already left the input stack.
pub struct ClosedSourceChange<'a> {
pub source_id: usize,
pub name: &'a str,
pub previous_bytes: usize,
pub current_bytes: usize,
}
impl EntryCheckpoint {
/// Identify a closed byte-framed child before the host verifies its path,
/// distinct file roles, read counts, and absence of later observations.
pub fn closed_source_change<'a>(
&'a self,
prior: &Self,
completed: &Execution,
) -> Option<ClosedSourceChange<'a>> {
let current = &self.executor;
let old = &prior.executor;
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
|| current.sources.len() != old.sources.len()
|| !matches!(current.state.input_profile(), InputProfile::TeX8Bit | InputProfile::UnicodeScalar)
|| current.state.input_profile() != old.state.input_profile()
{
return None;
}
let mut differences = current.sources.iter().zip(&old.sources).enumerate()
.filter(|(_, (new, old))| new != old);
let (source_id, (new, old_source)) = differences.next()?;
if differences.next().is_some()
|| source_id == self.entry
|| new.name != old_source.name
|| completed.sources.get(source_id)? != old_source
{
return None;
}
let uniquely_named = |sources: &[Arc<SourceFile>]| {
sources.iter().filter(|source| source.name == new.name).take(2).count() == 1
};
let is_closed = |executor: &Executor| {
!executor.stream_sources.contains(&source_id)
&& !executor.generated_inputs.contains_key(&source_id)
&& !executor.inputs.iter().any(|frame| matches!(
frame, InputFrame::Source { source, .. } if *source == source_id
))
};
if !uniquely_named(&old.sources)
|| !uniquely_named(&current.sources)
|| !uniquely_named(&completed.sources)
|| !is_closed(old)
|| !is_closed(current)
|| completed.stream_sources.contains(&source_id)
|| completed.generated_inputs.contains_key(&source_id)
{
return None;
}
Some(ClosedSourceChange {
source_id,
name: &new.name,
previous_bytes: old_source.data.len(),
current_bytes: new.data.len(),
})
}
/// Construct an execution with the current prefix and a previously
/// completed suffix. The host must still validate and replay that suffix.
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
@@ -146,6 +210,36 @@ impl EntryCheckpoint {
&self,
prior: &Self,
completed: &Execution,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.splice_settled_sources(prior, completed, self.entry, 1, timings)
}
/// Reuse a suffix after the caller has verified the actual host reads
/// of the changed child, including probes that only consumed its size.
/// The caller must reject later uses of this file and replay all effects.
pub fn splice_settled_closed_source_suffix_observed(
&self,
prior: &Self,
completed: &Execution,
source_id: usize,
prefix_resource_reads: usize,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if prefix_resource_reads == 0
|| self.closed_source_change(prior, completed)?.source_id != source_id
{
return None;
}
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, timings)
}
fn splice_settled_sources(
&self,
prior: &Self,
completed: &Execution,
source_id: usize,
prefix_resource_reads: usize,
mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source
@@ -170,7 +264,7 @@ impl EntryCheckpoint {
.zip(&old.sources)
.enumerate()
.any(|(id, (new, old))| {
if id == self.entry {
if id == source_id {
new.name != old.name
} else {
new != old
@@ -199,12 +293,15 @@ impl EntryCheckpoint {
if current.material_charge != old.material_charge && !no_suffix_recount {
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())
.then_some((previous_bytes.len(), current_bytes.len()));
let relocation = match entry_sizes {
Some(_) => {
let previous_bytes = &old.sources[source_id].data;
let current_bytes = &current.sources[source_id].data;
let resize = (previous_bytes.len() != current_bytes.len()).then_some(SuffixSourceResize {
sizes: (previous_bytes.len(), current_bytes.len()),
active_at_anchor: source_id == self.entry,
prefix_resource_reads,
});
let relocation = match resize {
Some(resize) if resize.active_at_anchor => {
let map = self.source_mouth(self.entry)
.relocation_from(prior.source_mouth(prior.entry))?;
if map.relocate_offset(prior.frontier) != Some(self.frontier) {
@@ -212,13 +309,16 @@ impl EntryCheckpoint {
}
Some(map)
}
Some(_) if self.frontier == prior.frontier => {
Some(SourceRelocation::new(source_id, previous_bytes, current_bytes)?)
}
None if self.frontier == prior.frontier => None,
None => return None,
_ => return None,
};
let observes_entry_line = completed.line_observations.as_ref().is_none_or(|observations| {
observations.get(&self.entry) != old.line_observations.get(&self.entry)
let observes_changed_line = completed.line_observations.as_ref().is_none_or(|observations| {
observations.get(&source_id) != old.line_observations.get(&source_id)
});
if observes_entry_line
if observes_changed_line
&& relocation.as_ref().map_or_else(
|| !SourceRelocation::same_line_breaks(previous_bytes, current_bytes),
|map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1,
@@ -252,12 +352,12 @@ impl EntryCheckpoint {
return None;
}
let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone();
sources[source_id] = current.sources[source_id].clone();
let tail = completed.events.get(old.events.len()..)?;
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)
&& current.equivalent_accounting_history_with_source_resize(old, resize)
{
return Some(None);
}
@@ -271,7 +371,7 @@ impl EntryCheckpoint {
{
return None;
}
let history = current.retained_history_offset(old, entry_sizes)?;
let history = current.retained_history_offset(old, resize)?;
Some((!history.is_identity()).then_some(history))
})?
} else {
@@ -310,9 +410,9 @@ impl EntryCheckpoint {
reads_event_history: false,
accounts_event_history: completed.accounts_event_history,
};
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
if let Some((moved, resize)) = moved.as_mut().zip(resize) {
relocate::append_suffix(
&mut execution, tail, &statistics, moved, sizes, old.sources.len(),
&mut execution, tail, &statistics, moved, resize, old.sources.len(),
)?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
@@ -355,6 +455,13 @@ impl EntryCheckpoint {
}
let current = &self.executor;
let old = &prior.executor;
// Rebased checkpoints retain the donor's closed-source bytes.
if current.sources.len() != old.sources.len()
|| current.sources.iter().zip(&old.sources).enumerate()
.any(|(id, (new, old))| id != self.entry && new != old)
{
return None;
}
// Later snapshots retain the donor's meaning cache and read history.
// Keeping them requires the same keys, even when the finished splice
// could publish a different set using exact suffix evidence.
@@ -567,10 +674,10 @@ impl SuffixStatistics {
fn translate(
&self,
report: &StatisticsReport,
entry_sizes: Option<(usize, usize)>,
resize: Option<SuffixSourceResize>,
) -> Option<StatisticsReport> {
report.with_suffix_adjustments(
self.steps, self.boxes, entry_sizes, self.retained_history.as_ref(),
report.with_source_resize(
self.steps, self.boxes, resize, self.retained_history.as_ref(),
)
}
}
@@ -108,13 +108,15 @@ pub(super) fn append_suffix(
tail: &[Event],
statistics: &SuffixStatistics,
relocation: &mut EventRelocation<'_>,
(previous_bytes, current_bytes): (usize, usize),
resize: SuffixSourceResize,
source_count: usize,
) -> Option<()> {
let map = relocation.map();
for event in tail {
if let Event::Statistics(report) = event {
if let StatisticsPhase::Shipout { before, after } = &report.phase {
if resize.active_at_anchor
&& let StatisticsPhase::Shipout { before, after } = &report.phase
{
// The active entry was the only source frame at convergence.
// If a report follows any later input open, its mouth payload
// alone cannot prove whether that frame is still present.
@@ -122,7 +124,7 @@ pub(super) fn append_suffix(
return None;
}
}
let mut report = statistics.translate(report, Some((previous_bytes, current_bytes)))?;
let mut report = statistics.translate(report, Some(resize))?;
report.span = map.relocate_span(report.span)?;
execution.events.push(Event::Statistics(Box::new(report)));
} else {
@@ -1,7 +1,7 @@
use super::super::statistics::{
Collector,
Ownership::{Active, Retained},
RetainedHistoryOffset,
RetainedHistoryOffset, SuffixSourceResize,
};
use super::*;
impl Executor {
@@ -232,16 +232,16 @@ impl Executor {
}
pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool {
self.equivalent_accounting_history_with_entry_sizes(old, None)
self.equivalent_accounting_history_with_source_resize(old, None)
}
pub(super) fn equivalent_accounting_history_with_entry_sizes(
pub(super) fn equivalent_accounting_history_with_source_resize(
&self,
old: &Self,
entry_sizes: Option<(usize, usize)>,
resize: Option<SuffixSourceResize>,
) -> bool {
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
self.collect_compared_accounting(old, entry_sizes, collector).is_some_and(
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)
},
@@ -252,17 +252,17 @@ impl Executor {
pub(super) fn retained_history_offset(
&self,
old: &Self,
entry_sizes: Option<(usize, usize)>,
resize: Option<SuffixSourceResize>,
) -> Option<RetainedHistoryOffset> {
let (live, old_live, history, old_history) =
self.collect_compared_accounting(old, entry_sizes, Collector::default)?;
self.collect_compared_accounting(old, resize, Collector::default)?;
live.retained_history_offset(&old_live, &history, &old_history)
}
fn collect_compared_accounting(
&self,
old: &Self,
entry_sizes: Option<(usize, usize)>,
resize: Option<SuffixSourceResize>,
collector: fn() -> Collector,
) -> Option<(Collector, Collector, Collector, Collector)> {
// These containers may reintroduce previously retained allocations
@@ -284,10 +284,13 @@ impl Executor {
// 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 {
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)?;
live.usage.mouth_payload_bytes = restore(live.usage.mouth_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))
}
+2 -1
View File
@@ -72,7 +72,8 @@ pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix,
CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Executor, Limits,
RelocatedShipoutSuffix,
SuffixKernelTimings,
};
pub use font_catalog::{
@@ -271,6 +271,24 @@ impl RetainedHistoryOffset {
}
}
/// 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();
@@ -292,7 +310,7 @@ impl StatisticsReport {
if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() {
return None;
}
usage.resize_entry_payload(previous, current, true)?;
usage.resize_source_payload(SuffixSourceResize::entry((previous, current)), true)?;
}
debug_assert_eq!(self.text, self.phase.text());
Some(())
@@ -324,6 +342,16 @@ impl StatisticsReport {
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)?;
@@ -338,22 +366,24 @@ impl StatisticsReport {
}
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 {
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_entry_payload(previous, current, active)?;
usage.resize_source_payload(resize, active)?;
}
}
}
StatisticsPhase::End { usage, .. } => {
translate(usage)?;
if let Some((previous, current)) = entry_sizes {
if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 {
if let Some(resize) = resize {
if resize.active_at_anchor
&& (usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0)
{
return None;
}
usage.resize_entry_payload(previous, current, false)?;
usage.resize_source_payload(resize, false)?;
}
if let Some(offset) = history {
offset.replace_prefix(usage)?;
@@ -376,18 +406,17 @@ impl StatisticsReport {
}
impl ResourceUsage {
fn resize_entry_payload(
&mut self,
previous: usize,
current: usize,
active: bool,
) -> Option<()> {
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 {
host.rebind_entry_bytes(u64::try_from(previous).ok()?, u64::try_from(current).ok()?)?;
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(())
}
@@ -920,6 +949,45 @@ mod tests {
).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());