From 3c09d6486def746d3c3c132db0f0c36260c44aa5 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Wed, 2 Dec 2026 03:55:50 +0800 Subject: [PATCH] Resume exact state fingerprints from ordered command checkpoints --- .../texrra-tex-core/src/execution/engine.rs | 7 +- .../src/execution/engine/continuation.rs | 3 +- crates/texrra-tex-core/src/execution/state.rs | 150 ++++++++++++++++-- .../src/execution/state/fingerprint.rs | 15 ++ .../src/execution/state/source_relocation.rs | 11 +- 5 files changed, 165 insertions(+), 21 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 22ca6aa..358b9dc 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -4126,9 +4126,10 @@ impl Executor { } // An identical completed state has the same fingerprint. Compare // the entire state, including token source spans and assignments. - let outgoing_state = previous - .filter(|last| last.state == self.state) - .map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state); + let outgoing_state = match previous { + Some(last) if last.state == self.state => last.outgoing_state, + last => self.state.fingerprint_with_prior(last.map(|last| &last.state)), + }; let format_pdf_images = self.captured_format_pdf_images(); Ok(Execution { format_dumped: self.format_dumped, diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index c8c1739..3672483 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -460,7 +460,8 @@ impl EntryCheckpoint { &mut execution, tail, &statistics, moved, resize, old.sources.len(), )?; if execution.state != completed.state { - execution.outgoing_state = execution.state.fingerprint(); + execution.outgoing_state = execution.state + .fingerprint_with_prior(Some(&completed.state)); } } else if statistics.is_identity() { execution.events.extend_from_slice(tail); diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 1fcc1bf..094b040 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -5,9 +5,7 @@ use fingerprint::{FingerprintHasher, MacroFingerprintInputs}; use hashbrown::{HashMap, hash_map::RawEntryMut}; use std::collections::BTreeMap; -use std::hash::{BuildHasher, Hash, Hasher, RandomState}; -#[cfg(test)] -use std::hash::DefaultHasher; +use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; use std::sync::{Arc, Mutex, OnceLock}; use super::{ @@ -878,6 +876,14 @@ impl PartialEq for CommandShard { impl Eq for CommandShard {} type OrderedCommandNames = Arc, u64)>>>; +const COMMAND_HASH_CHECKPOINT_STRIDE: usize = 128; + +#[derive(Debug)] +struct CommandHashCheckpoints { + blocks: Vec, + end: DefaultHasher, +} + pub(super) fn command_hasher() -> &'static RandomState { // Identical hashes feed the binding table and the executor's read cache. // The seed and partition are private to this process. @@ -892,6 +898,7 @@ struct CommandBindings { // Cache names only so redefinitions can share the same order. ordered_names: OrderedCommandNames, fingerprint_inputs: Arc>, + hash_checkpoints: OnceLock>, } impl Default for CommandBindings { @@ -904,6 +911,7 @@ impl Default for CommandBindings { revisions: [0; COMMAND_SHARDS], ordered_names: Arc::default(), fingerprint_inputs: Arc::default(), + hash_checkpoints: OnceLock::new(), } } } @@ -944,6 +952,7 @@ impl CommandBindings { fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard { let index = Self::shard_index(command_hasher().hash_one(name)); self.revisions[index] += 1; + self.hash_checkpoints.take(); Arc::make_mut(&mut self.shards[index]) } @@ -963,6 +972,7 @@ impl CommandBindings { return; } self.revisions[index] += 1; + self.hash_checkpoints.take(); if Arc::make_mut(shard).insert_hashed(name, meaning, hash).is_none() { self.invalidate_order(); } @@ -1019,18 +1029,84 @@ impl CommandBindings { } impl CommandBindings { - fn hash_fingerprint(&self, hasher: &mut FingerprintHasher) { - let Ok(mut inputs) = self.fingerprint_inputs.try_lock() else { - self.hash(hasher); - return; - }; - inputs.prune_if_full(); - let entries = self.ordered(); - entries.len().hash(hasher); - for (name, meaning) in entries { - name.hash(hasher); - inputs.hash_meaning(meaning, hasher); + fn first_changed_binding(&self, prior: &Self) -> Option { + // Value overwrites can retain the order object. Insertion and + // removal replace it before a different ordered key set is used. + if !Arc::ptr_eq(&self.ordered_names, &prior.ordered_names) { + return None; } + let names = prior.ordered_names.get()?; + let mut first = None; + for (current, old) in self.shards.iter().zip(&prior.shards) { + if Arc::ptr_eq(current, old) { + continue; + } + for (name, meaning) in ¤t.entries { + if first.is_some_and(|first| name >= first) { + continue; + } + let unchanged = match (meaning, old.entries.get(name)?) { + (Meaning::Macro(current), Meaning::Macro(old)) => Arc::ptr_eq(current, old), + (current, old) => current == old, + }; + if !unchanged { + first = Some(name); + } + } + } + match first { + Some(name) => names.binary_search_by(|(key, _)| key.cmp(name)).ok(), + None => Some(names.len()), + } + } + + fn hash_fingerprint(&self, hasher: &mut FingerprintHasher, prior: Option<&Self>) { + if let Some(checkpoints) = self.hash_checkpoints.get() { + hasher.restore(&checkpoints.end); + return; + } + let entries = self.ordered(); + let count = entries.len(); + let donor = prior.and_then(|prior| { + let checkpoints = prior.hash_checkpoints.get()?; + Some((self.first_changed_binding(prior)?, checkpoints)) + }); + if let Some((first, donor)) = donor + && first == count + { + hasher.restore(&donor.end); + let _ = self.hash_checkpoints.set(donor.clone()); + return; + } + + let mut blocks = Vec::with_capacity(count / COMMAND_HASH_CHECKPOINT_STRIDE + 1); + let offset = if let Some((first, donor)) = donor { + let index = first / COMMAND_HASH_CHECKPOINT_STRIDE; + blocks.extend_from_slice(&donor.blocks[..=index]); + hasher.restore(&donor.blocks[index]); + index * COMMAND_HASH_CHECKPOINT_STRIDE + } else { + count.hash(hasher); + blocks.push(hasher.checkpoint()); + 0 + }; + let mut inputs = self.fingerprint_inputs.try_lock().ok(); + if let Some(inputs) = &mut inputs { + inputs.prune_if_full(); + } + for (index, (name, meaning)) in entries.enumerate().skip(offset) { + name.hash(hasher); + if let Some(inputs) = &mut inputs { + inputs.hash_meaning(meaning, hasher); + } else { + meaning.hash(hasher); + } + if (index + 1) % COMMAND_HASH_CHECKPOINT_STRIDE == 0 { + blocks.push(hasher.checkpoint()); + } + } + let end = hasher.checkpoint(); + let _ = self.hash_checkpoints.set(Arc::new(CommandHashCheckpoints { blocks, end })); } } @@ -1076,8 +1152,12 @@ macro_rules! define_state { impl State { pub fn fingerprint(&self) -> u64 { + self.fingerprint_with_prior(None) + } + + pub(super) fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 { let mut hash = FingerprintHasher::default(); - self.commands.hash_fingerprint(&mut hash); + self.commands.hash_fingerprint(&mut hash, prior.map(|prior| prior.commands.as_ref())); $(self.$field.hash(&mut hash);)* hash.finish() } @@ -1193,6 +1273,45 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() { check(&state); } +#[test] +fn state_fingerprint_resumes_before_the_first_changed_binding() { + let direct = |state: &State| { + let mut hasher = DefaultHasher::new(); + state.hash(&mut hasher); + hasher.finish() + }; + let mut original = State { commands: Arc::default(), ..State::default() }; + let stride = COMMAND_HASH_CHECKPOINT_STRIDE; + let name = |index| CommandName::Control(format!("binding-{index:04}")); + for index in 0..stride * 3 { + original.define(name(index), Meaning::Count(0), true); + } + let original_hash = original.fingerprint(); + let mut registers_only = original.clone(); + registers_only.counts.insert(101, 7); + assert_eq!(registers_only.fingerprint(), direct(®isters_only)); + assert_ne!(registers_only.fingerprint(), original_hash); + + let mut revised = original.clone(); + let edited = stride * 2 + 3; + revised.define(name(edited), Meaning::Count(1), true); + assert!(revised.commands.hash_checkpoints.get().is_none()); + assert_eq!(revised.commands.first_changed_binding(&original.commands), Some(edited)); + let revised_hash = revised.fingerprint_with_prior(Some(&original)); + assert_eq!(revised_hash, direct(&revised)); + assert_ne!(revised_hash, original_hash); + assert_eq!(revised.fingerprint(), revised_hash); + assert_eq!(original.fingerprint(), original_hash); + + // A mutation in place must clear the computed checkpoints as well. + revised.define(name(0), Meaning::Count(2), true); + assert!(revised.commands.hash_checkpoints.get().is_none()); + assert_eq!(revised.fingerprint_with_prior(Some(&original)), direct(&revised)); + revised.command_bindings_mut().remove(&name(0)); + assert!(revised.commands.first_changed_binding(&original.commands).is_none()); + assert_eq!(revised.fingerprint_with_prior(Some(&original)), direct(&revised)); +} + #[test] fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() { use super::Span; @@ -1240,6 +1359,7 @@ fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() { Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token); state.define(first, Meaning::Macro(body), true); let uncached = check(&state); + state.command_bindings_mut().hash_checkpoints.take(); let _held = state.commands.fingerprint_inputs.lock().unwrap(); assert_eq!(state.fingerprint(), uncached); } diff --git a/crates/texrra-tex-core/src/execution/state/fingerprint.rs b/crates/texrra-tex-core/src/execution/state/fingerprint.rs index f2a25ce..cfb6fcb 100644 --- a/crates/texrra-tex-core/src/execution/state/fingerprint.rs +++ b/crates/texrra-tex-core/src/execution/state/fingerprint.rs @@ -25,6 +25,21 @@ impl Default for FingerprintHasher { } impl FingerprintHasher { + // The checkpoint represents exactly the bytes already written, including + // the partial buffer. It is always resumed at a complete binding boundary. + pub(super) fn checkpoint(&mut self) -> DefaultHasher { + if self.used > 0 { + self.hasher.write(&self.buffer[..self.used]); + self.used = 0; + } + self.hasher.clone() + } + + pub(super) fn restore(&mut self, checkpoint: &DefaultHasher) { + self.hasher = checkpoint.clone(); + self.used = 0; + } + #[inline] fn write_fixed(&mut self, bytes: [u8; N]) { if N > self.buffer.len() - self.used { diff --git a/crates/texrra-tex-core/src/execution/state/source_relocation.rs b/crates/texrra-tex-core/src/execution/state/source_relocation.rs index 8fc91c5..d14d592 100644 --- a/crates/texrra-tex-core/src/execution/state/source_relocation.rs +++ b/crates/texrra-tex-core/src/execution/state/source_relocation.rs @@ -22,8 +22,10 @@ impl State { if let Meaning::Macro(body) = meaning { let relocated = relocation.relocate_macro(body)?; if !Arc::ptr_eq(body, &relocated) { - let shard = &mut Arc::make_mut(&mut self.commands).shards[index]; - Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated)); + let commands = self.command_bindings_mut(); + commands.hash_checkpoints.take(); + Arc::make_mut(&mut commands.shards[index]) + .insert(name.clone(), Meaning::Macro(relocated)); } } } @@ -170,7 +172,12 @@ fn command_bounds_track_redefinitions_and_invocation_origins() { let token_span = Span { source: 0, start: 8, end: 9 }; state.define(name.clone(), meaning(Some(token_span)), true); assert_eq!(state.commands.shards[shard].source_bounds[&0], Some(9)); + let prior_hash = state.fingerprint(); + let donor = state.clone(); state.relocate_source(&mut EventRelocation::new(&map)).unwrap(); + assert!(state.commands.hash_checkpoints.get().is_none()); + assert_ne!(state.fingerprint_with_prior(Some(&donor)), prior_hash); + assert_eq!(donor.fingerprint(), prior_hash); let mapped = map.relocate_span(token_span).unwrap(); assert_ne!(mapped, token_span); assert_eq!(state.meaning(&name), meaning(Some(mapped)));