Translate logical step counts when replaying native suffixes

This commit is contained in:
gloamxun committed 2026-12-01 21:16:41 +08:00
1 parent 9a6c162b46
commit 465a574124
8 files changed
+337 -86

No files matched your search

@@ -121,6 +121,13 @@ impl EntryCheckpoint {
{
return None;
}
let offset = StepOffset::new(old.steps, current.steps);
let steps = offset.apply(completed.steps)?;
// Kernel work only advances the step counter. A successful suffix
// remains within budget if its translated final count does.
if steps > current.limits.steps {
return None;
}
let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone();
let tail = completed.events.get(old.events.len()..)?;
@@ -130,7 +137,13 @@ impl EntryCheckpoint {
// 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);
if offset.is_identity() {
events.extend_from_slice(tail);
} else {
for event in tail {
events.push(offset_event_steps(event, offset)?);
}
}
Some(Execution {
format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(),
@@ -150,7 +163,7 @@ impl EntryCheckpoint {
reads: completed.reads.clone(),
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
steps: completed.steps,
steps,
reads_event_history: false,
accounts_event_history: completed.accounts_event_history,
})
@@ -162,7 +175,7 @@ impl EntryCheckpoint {
&'a self,
prior: &'a Self,
completed: &Execution,
) -> Option<impl Fn(&Self) -> Option<Self> + 'a> {
) -> Option<impl FnMut(&Self) -> Option<Self> + 'a> {
// 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
@@ -191,7 +204,8 @@ impl EntryCheckpoint {
}
}
}
Some(move |later: &Self| self.rebase_verified_suffix(prior, later, &prefix))
let mut adjusted_chunks = BTreeMap::new();
Some(move |later: &Self| self.rebase_verified_suffix(prior, later, &prefix, &mut adjusted_chunks))
}
fn rebase_verified_suffix(
@@ -199,14 +213,21 @@ impl EntryCheckpoint {
prior: &Self,
later: &Self,
prefix: &ExecutionEvents,
adjusted_chunks: &mut BTreeMap<usize, Arc<Vec<Event>>>,
) -> Option<Self> {
let old = &prior.executor;
let next = &later.executor;
let current = &self.executor;
let offset = StepOffset::new(old.steps, current.steps);
let steps = offset.apply(next.steps)?;
if later.entry != self.entry
|| later.active_source != self.entry
|| later.frontier < self.frontier
|| later.completed_steps() <= self.completed_steps()
|| steps <= current.steps
|| steps > current.limits.steps
// An active builder can hold a budget established before
// capture. Its limit cannot be translated by changing steps.
|| (!offset.is_identity() && !is_idle_continuation(next))
|| later.incoming_state != self.incoming_state
|| next.reads_event_history
|| !Arc::ptr_eq(&next.sources[later.entry], &old.sources[prior.entry])
@@ -220,9 +241,25 @@ impl EntryCheckpoint {
let mut events = prefix.clone();
// Checkpoint capture seals the event log. Share the old suffix
// chunks so all carried checkpoints keep the same allocation graph.
events.prefix.extend_from_slice(&next.events.prefix[old.events.prefix.len()..]);
for chunk in &next.events.prefix[old.events.prefix.len()..] {
if offset.is_identity() || !chunk.iter().any(|event| matches!(event, Event::Statistics(_))) {
events.prefix.push(chunk.clone());
continue;
}
let address = Arc::as_ptr(chunk) as usize;
let adjusted = match adjusted_chunks.entry(address) {
std::collections::btree_map::Entry::Occupied(entry) => entry.get().clone(),
std::collections::btree_map::Entry::Vacant(entry) => {
let events = chunk.iter().map(|event| offset_event_steps(event, offset))
.collect::<Option<Vec<_>>>()?;
entry.insert(Arc::new(events)).clone()
}
};
events.prefix.push(adjusted);
}
events.prefix_len += next.events.prefix_len - old.events.prefix_len;
executor.events = events;
executor.steps = steps;
executor.sources[self.entry] = current.sources[self.entry].clone();
let InputFrame::Source { source, mouth, .. } = executor.inputs.first_mut()? else {
return None;
@@ -248,6 +285,27 @@ impl EntryCheckpoint {
}
}
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
match event {
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))),
_ => Some(event.clone()),
}
}
fn is_idle_continuation(e: &Executor) -> bool {
e.output_frame.is_none()
&& e.paragraph.is_none()
&& e.box_frames.is_empty()
&& e.math.is_empty()
&& e.display.is_none()
&& e.alignments.is_empty()
&& e.pdf_link_stack.is_empty()
&& e.pdf_active_thread.is_none()
&& e.pdf_space_probe.is_none()
&& e.pdf_images.is_empty()
&& !e.reads_event_history
}
fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
// Every field belongs to one of these checks. Adding kernel state requires
// an explicit decision here before a later execution may be skipped.
@@ -275,7 +333,6 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
conditionals,
in_csname,
command_trace_mode,
steps,
ligature_carry,
current,
expression_depth,
@@ -323,6 +380,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
[
inputs,
sources,
steps,
meaning_reads,
events,
reads_event_history,
@@ -344,20 +402,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
) {
return false;
}
let idle = |e: &Executor| {
e.output_frame.is_none()
&& e.paragraph.is_none()
&& e.box_frames.is_empty()
&& e.math.is_empty()
&& e.display.is_none()
&& e.alignments.is_empty()
&& e.pdf_link_stack.is_empty()
&& e.pdf_active_thread.is_none()
&& e.pdf_space_probe.is_none()
&& e.pdf_images.is_empty()
&& !e.reads_event_history
};
if !idle(current) || !idle(prior) {
if !is_idle_continuation(current) || !is_idle_continuation(prior) {
return false;
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
@@ -197,8 +197,10 @@ impl Executor {
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 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.
live.usage.steps = old_live.usage.steps;
live.has_equivalent_history(&old_live, &history, &old_history)
})
}
@@ -229,20 +231,9 @@ impl Executor {
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
let after = self.resource_usage(None, host);
let text = 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.emit_statistics(
StatisticsPhase::Shipout { before, after },
WriteDestination::TerminalAndLog,
text,
files,
)
}
@@ -259,46 +250,9 @@ impl Executor {
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
let usage = self.resource_usage(None, host);
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");
}
self.emit_statistics(
StatisticsPhase::End { success, usage },
WriteDestination::Log,
text,
files,
)
}
@@ -306,23 +260,17 @@ impl Executor {
&mut self,
phase: StatisticsPhase,
destination: WriteDestination,
text: String,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(text.len());
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_diagnostic(destination, &text)
.observe_statistics(&report)
.map_err(|e| self.error(e, self.current))?;
self.events
.push(Event::Statistics(Box::new(StatisticsReport {
phase,
destination,
text,
span: self.current,
})));
self.events.push(Event::Statistics(Box::new(report)));
Ok(())
}
}