Reduce and measure native suffix convergence work

This commit is contained in:
gloamxun committed 2026-12-01 23:15:17 +08:00
1 parent c008c52964
commit b081c951af
10 files changed
+330 -97

No files matched your search

@@ -43,7 +43,7 @@ mod scheduling;
mod specials;
mod statistics;
mod continuation;
pub use continuation::RelocatedShipoutSuffix;
pub use continuation::{RelocatedShipoutSuffix, SuffixKernelTimings};
mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -2,6 +2,7 @@ use super::super::{
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
};
use super::*;
use std::time::{Duration, Instant};
mod material;
mod relocate;
use material::MaterialReuse;
@@ -89,6 +90,15 @@ impl InputFrame {
}
}
/// Work done inside an observed suffix splice. A rejected candidate can
/// contribute to the checks it reached.
#[derive(Clone, Copy, Debug, Default)]
pub struct SuffixKernelTimings {
pub state_comparison: Duration,
pub retained_accounting: Duration,
pub suffix_assembly: Duration,
}
/// Source coordinates for the shipouts copied from a moved execution suffix.
pub struct RelocatedShipoutSuffix {
first_page: usize,
@@ -125,6 +135,16 @@ impl EntryCheckpoint {
&self,
prior: &Self,
completed: &Execution,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.splice_settled_suffix_observed(prior, completed, None)
}
/// Splice a completed suffix and optionally record its kernel checks.
pub fn splice_settled_suffix_observed(
&self,
prior: &Self,
completed: &Execution,
mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source
|| prior.entry != prior.active_source
@@ -176,7 +196,9 @@ impl EntryCheckpoint {
// Comparison and publication visit some of the same original
// allocations. Keep the checked relocations for this donor only.
let mut moved = relocation.as_ref().map(EventRelocation::new);
if !same_kernel_continuation(current, old, moved.as_mut()) {
if !measure(timings.as_deref_mut().map(|timings| &mut timings.state_comparison), || {
same_kernel_continuation(current, old, moved.as_mut())
}) {
return None;
}
let offset = StepOffset::new(old.steps, current.steps);
@@ -190,47 +212,52 @@ impl EntryCheckpoint {
sources[self.entry] = current.sources[self.entry].clone();
let tail = completed.events.get(old.events.len()..)?;
if completed.accounts_event_history
&& !current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
&& !measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes)
})
{
return None;
}
// The joined events are published results. Resumption always starts
// from a live checkpoint, whose original shared allocations stay intact.
let mut execution = Execution {
format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(),
job_name: completed.job_name.clone(),
interaction_mode: completed.interaction_mode,
native_page: completed.native_page.clone(),
split_discards: completed.split_discards.clone(),
after_assignment: completed.after_assignment.clone(),
events: current.events.clone().into_vec(),
state: completed.state.clone(),
io: completed.io.clone(),
input_position: completed.input_position,
paragraph_mode: completed.paragraph_mode,
sources,
stream_sources: completed.stream_sources.clone(),
generated_inputs: completed.generated_inputs.clone(),
reads: completed.reads.clone(),
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
steps,
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())?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || {
let mut execution = Execution {
format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(),
job_name: completed.job_name.clone(),
interaction_mode: completed.interaction_mode,
native_page: completed.native_page.clone(),
split_discards: completed.split_discards.clone(),
after_assignment: completed.after_assignment.clone(),
events: current.events.clone().into_vec(),
state: completed.state.clone(),
io: completed.io.clone(),
input_position: completed.input_position,
paragraph_mode: completed.paragraph_mode,
sources,
stream_sources: completed.stream_sources.clone(),
generated_inputs: completed.generated_inputs.clone(),
reads: completed.reads.clone(),
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
steps,
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())?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
}
} else if offset.is_identity() {
execution.events.extend_from_slice(tail);
} else {
for event in tail {
execution.events.push(offset_event_steps(event, offset)?);
}
}
} else if offset.is_identity() {
execution.events.extend_from_slice(tail);
} else {
for event in tail {
execution.events.push(offset_event_steps(event, offset)?);
}
}
Some(execution)
})?;
let layout = relocation.map(|map| RelocatedShipoutSuffix {
// The executor records one top-level shipout event whenever
// this count advances. Form canvases do not enter this sequence.
@@ -362,6 +389,15 @@ impl EntryCheckpoint {
}
}
fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
let started = elapsed.is_some().then(Instant::now);
let value = action();
if let (Some(elapsed), Some(started)) = (elapsed, started) {
*elapsed += started.elapsed();
}
value
}
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)?))),
@@ -497,17 +533,15 @@ fn same_kernel_continuation(
{
return false;
}
let map = relocation.as_ref().map(|context| context.map());
let relocated;
let prior = if let Some(context) = relocation {
relocated = match relocate::kernel_continuation(prior, context) {
Some(executor) => executor,
None => return false,
};
&relocated
} else {
prior
};
if !current.xdv_annotations.same_idle_state(&prior.xdv_annotations)
|| !current.xdv_text.same_state(&prior.xdv_text)
|| !current.pdf_navigation_geometry.same_state(&prior.pdf_navigation_geometry)
{
return false;
}
if let Some(relocation) = relocation {
return relocate::same_kernel_provenance(current, prior, relocation).unwrap_or(false);
}
current.state == prior.state
&& current.generated_inputs == prior.generated_inputs
&& current.conditionals == prior.conditionals
@@ -520,16 +554,9 @@ fn same_kernel_continuation(
&& current.native_page == prior.native_page
&& current.split_discards == prior.split_discards
&& current.pending_shipouts == prior.pending_shipouts
&& current
.xdv_annotations
.same_idle_state(&prior.xdv_annotations)
&& current.xdv_text.same_state(&prior.xdv_text)
&& current
.pdf_navigation_geometry
.same_state(&prior.pdf_navigation_geometry)
&& current
.inputs
.iter()
.zip(&prior.inputs)
.all(|(a, b)| a.same_at_shipout(b, map))
.all(|(a, b)| a.same_at_shipout(b, None))
}
@@ -1,21 +1,24 @@
use super::*;
use crate::execution::source_relocation_events::EventRelocation;
pub(super) fn kernel_continuation(
pub(super) fn same_kernel_provenance(
current: &Executor,
prior: &Executor,
relocation: &mut EventRelocation<'_>,
) -> Option<Executor> {
let mut prior = prior.clone();
) -> Option<bool> {
let map = relocation.map();
prior.current = map.relocate_span(prior.current)?;
prior.state.relocate_source(relocation)?;
relocate_generated(&mut prior.generated_inputs, map)?;
for conditional in &mut prior.conditionals {
conditional.span = map.relocate_span(conditional.span)?;
if current.current != map.relocate_span(prior.current)? {
return Some(false);
}
for frame in &mut prior.inputs {
match frame {
for (current, prior) in current.inputs.iter().zip(&prior.inputs) {
if matches!(prior, InputFrame::Source { .. } | InputFrame::Boundary) {
if !current.same_at_shipout(prior, Some(map)) {
return Some(false);
}
continue;
}
let mut frame = prior.clone();
match &mut frame {
InputFrame::Tokens { tokens, .. } => match tokens {
InputTokens::One(token) => relocation.relocate_token(&mut token.token)?,
InputTokens::Many(tokens) => {
@@ -41,25 +44,60 @@ pub(super) fn kernel_continuation(
*call = map.relocate_span(*call)?;
}
InputFrame::Hook { tokens, .. } => *tokens = relocation.relocate_tokens(tokens)?,
// Keep the old raw scanners for the byte and decoder comparison.
InputFrame::Source { .. } | InputFrame::Boundary => {}
InputFrame::Source { .. } | InputFrame::Boundary => unreachable!(),
}
if !current.same_at_shipout(&frame, None) {
return Some(false);
}
}
relocate_tokens(&mut prior.pdf_catalog_tokens, relocation)?;
relocate_tokens(&mut prior.pdf_info_tokens, relocation)?;
for outline in &mut prior.pdf_outlines {
// Compare only the fields that can hold changed source coordinates.
// The unchanged caches and counters never need an owned copy.
let mut generated = prior.generated_inputs.clone();
relocate_generated(&mut generated, map)?;
let mut conditionals = prior.conditionals.clone();
for conditional in &mut conditionals {
conditional.span = map.relocate_span(conditional.span)?;
}
let mut catalog = prior.pdf_catalog_tokens.clone();
let mut info = prior.pdf_info_tokens.clone();
let mut outlines = prior.pdf_outlines.clone();
relocate_tokens(&mut catalog, relocation)?;
relocate_tokens(&mut info, relocation)?;
for outline in &mut outlines {
relocate_tokens(&mut outline.attributes, relocation)?;
}
if let Some(token) = &mut prior.after_assignment {
let mut after_assignment = prior.after_assignment.clone();
if let Some(token) = &mut after_assignment {
relocation.relocate_token(token)?;
}
relocate_vertical(&mut prior.vertical.nodes, relocation)?;
relocate_vertical(&mut prior.split_discards, relocation)?;
relocate_page(&mut prior.native_page, relocation)?;
for value in &mut prior.pending_shipouts {
let mut vertical = prior.vertical.clone();
let mut discards = prior.split_discards.clone();
let mut native_page = prior.native_page.clone();
let mut pending_shipouts = prior.pending_shipouts.clone();
relocate_vertical(&mut vertical.nodes, relocation)?;
relocate_vertical(&mut discards, relocation)?;
relocate_page(&mut native_page, relocation)?;
for value in &mut pending_shipouts {
*value = relocation.relocate_box(value)?;
}
Some(prior)
if current.generated_inputs != generated
|| current.conditionals != conditionals
|| current.pdf_catalog_tokens != catalog
|| current.pdf_info_tokens != info
|| current.pdf_outlines != outlines
|| current.after_assignment != after_assignment
|| current.vertical != vertical
|| current.split_discards != discards
|| current.native_page != native_page
|| current.pending_shipouts != pending_shipouts
{
return Some(false);
}
let mut state = prior.state.clone();
state.relocate_source(relocation)?;
Some(current.state == state)
}
pub(super) fn append_suffix(
@@ -181,6 +181,37 @@ impl Executor {
}
}
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,
@@ -219,10 +250,8 @@ impl Executor {
}
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
let mut history = collector();
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 (history, old_history) =
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.
@@ -307,3 +336,45 @@ impl Executor {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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));
}
}
}
}
@@ -73,6 +73,7 @@ pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix,
SuffixKernelTimings,
};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
+82 -11
View File
@@ -801,6 +801,7 @@ enum PdftexRevision {
const COMMAND_SHARDS: usize = 32;
type CommandShard = HashMap<Arc<CommandName>, Meaning, RandomState>;
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
pub(super) fn command_hasher() -> &'static RandomState {
// Identical hashes feed the binding table and the executor's read cache.
@@ -813,6 +814,8 @@ pub(super) fn command_hasher() -> &'static RandomState {
struct CommandBindings {
shards: [Arc<CommandShard>; COMMAND_SHARDS],
revisions: [u64; COMMAND_SHARDS],
// Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames,
}
impl Default for CommandBindings {
@@ -821,6 +824,7 @@ impl Default for CommandBindings {
Self {
shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hasher.clone()))),
revisions: [0; COMMAND_SHARDS],
ordered_names: Arc::default(),
}
}
}
@@ -857,15 +861,32 @@ impl CommandBindings {
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) {
self.shard_mut(&name).insert(name, meaning);
if self.shard_mut(&name).insert(name, meaning).is_none() {
self.invalidate_order();
}
}
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
self.shard_mut(&name).entry(name.into()).or_insert(meaning);
if let hashbrown::hash_map::Entry::Vacant(entry) =
self.shard_mut(&name).entry(name.into())
{
entry.insert(meaning);
self.invalidate_order();
}
}
fn remove(&mut self, name: &CommandName) {
self.shard_mut(name).remove(name);
if self.shard_mut(name).remove(name).is_some() {
self.invalidate_order();
}
}
fn invalidate_order(&mut self) {
if let Some(order) = Arc::get_mut(&mut self.ordered_names) {
order.take();
} else {
self.ordered_names = Arc::default();
}
}
fn len(&self) -> usize {
@@ -876,23 +897,37 @@ impl CommandBindings {
self.shards.iter().flat_map(|shard| shard.iter())
}
fn ordered(&self) -> Vec<(&Arc<CommandName>, &Meaning)> {
let mut entries = Vec::with_capacity(self.len());
entries.extend(self.iter());
entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
entries
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> {
self.ordered_names
.get_or_init(|| {
let hasher = command_hasher();
let mut names = Vec::with_capacity(self.len());
names.extend(
self.iter()
.map(|(name, _)| (name.clone(), hasher.hash_one(name))),
);
names.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
names
})
.iter()
.map(|(name, hash)| {
let meaning = self
.get_hashed(name, *hash)
.expect("ordered command names match the binding table");
(name, meaning)
})
}
}
impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.ordered().hash(hasher);
self.ordered().collect::<Vec<_>>().hash(hasher);
}
}
impl serde::Serialize for CommandBindings {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serde::Serialize::serialize(&self.ordered(), serializer)
serializer.collect_seq(self.ordered())
}
}
@@ -1066,6 +1101,7 @@ fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
let mut state = State::initex().with_etex();
let name = CommandName::Control("checkpointbinding".into());
state.define(name.clone(), Meaning::Count(3), true);
let fingerprint = state.fingerprint();
let snapshot = state.clone();
state.define(name.clone(), Meaning::Count(7), true);
assert_eq!(snapshot.meaning(&name), Meaning::Count(3));
@@ -1073,10 +1109,45 @@ fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
let shared = state.commands.shards.iter().zip(&snapshot.commands.shards)
.filter(|(current, saved)| Arc::ptr_eq(current, saved)).count();
assert_eq!(shared, COMMAND_SHARDS - 1);
assert!(Arc::ptr_eq(
&state.commands.ordered_names,
&snapshot.commands.ordered_names,
));
let (_, redefined) = state
.commands
.ordered()
.find(|(key, _)| key.as_ref() == &name)
.unwrap();
assert_eq!(*redefined, Meaning::Count(7));
let added = CommandName::Control("checkpointorderadded".into());
let bindings = state.command_bindings_mut();
let before_insertion = bindings.clone();
bindings.insert_if_absent(name.clone(), Meaning::Count(100));
assert!(Arc::ptr_eq(
&bindings.ordered_names,
&before_insertion.ordered_names,
));
bindings.insert_if_absent(added.clone(), Meaning::Count(9));
assert!(!Arc::ptr_eq(
&bindings.ordered_names,
&before_insertion.ordered_names,
));
let ordered: BTreeMap<_, _> = bindings.iter().collect();
let expected: Vec<_> = ordered.into_iter().collect();
assert!(bindings.ordered().eq(expected.iter().copied()));
assert_eq!(
serde_json::to_vec(bindings).unwrap(),
serde_json::to_vec(&expected).unwrap(),
);
let with_added = bindings.clone();
bindings.remove(&added);
assert!(bindings.ordered().eq(before_insertion.ordered()));
assert!(with_added.ordered().any(|(key, _)| key.as_ref() == &added));
state.define(name, Meaning::Count(3), true);
assert_eq!(state, snapshot);
assert_eq!(state.fingerprint(), snapshot.fingerprint());
assert_eq!(state.fingerprint(), fingerprint);
assert_eq!(serde_json::to_vec(&state).unwrap(), serde_json::to_vec(&snapshot).unwrap());
}
@@ -335,7 +335,7 @@ enum Allocation {
Material(usize),
}
#[derive(Default)]
#[derive(Clone, Default)]
struct AliasVisits {
ordinals: BTreeMap<Allocation, usize>,
visits: Vec<(Allocation, usize)>,
@@ -349,7 +349,7 @@ impl AliasVisits {
}
}
#[derive(Default)]
#[derive(Clone, Default)]
pub(super) struct Collector {
pub usage: ResourceUsage,
macros: BTreeSet<usize>,