Resume exact state fingerprints from ordered command checkpoints

This commit is contained in:
gloamxun committed 2026-12-02 03:55:50 +08:00
1 parent dc86f941b6
commit 3c09d6486d
5 files changed
+165 -21

No files matched your search

@@ -4126,9 +4126,10 @@ impl Executor {
} }
// An identical completed state has the same fingerprint. Compare // An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments. // the entire state, including token source spans and assignments.
let outgoing_state = previous let outgoing_state = match previous {
.filter(|last| last.state == self.state) Some(last) if last.state == self.state => last.outgoing_state,
.map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state); last => self.state.fingerprint_with_prior(last.map(|last| &last.state)),
};
let format_pdf_images = self.captured_format_pdf_images(); let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution { Ok(Execution {
format_dumped: self.format_dumped, format_dumped: self.format_dumped,
@@ -460,7 +460,8 @@ impl EntryCheckpoint {
&mut execution, tail, &statistics, moved, resize, old.sources.len(), &mut execution, tail, &statistics, moved, resize, old.sources.len(),
)?; )?;
if execution.state != completed.state { 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() { } else if statistics.is_identity() {
execution.events.extend_from_slice(tail); execution.events.extend_from_slice(tail);
+135 -15
View File
@@ -5,9 +5,7 @@ use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
use hashbrown::{HashMap, hash_map::RawEntryMut}; use hashbrown::{HashMap, hash_map::RawEntryMut};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::{BuildHasher, Hash, Hasher, RandomState}; use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
#[cfg(test)]
use std::hash::DefaultHasher;
use std::sync::{Arc, Mutex, OnceLock}; use std::sync::{Arc, Mutex, OnceLock};
use super::{ use super::{
@@ -878,6 +876,14 @@ impl PartialEq for CommandShard {
impl Eq for CommandShard {} impl Eq for CommandShard {}
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>; type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
const COMMAND_HASH_CHECKPOINT_STRIDE: usize = 128;
#[derive(Debug)]
struct CommandHashCheckpoints {
blocks: Vec<DefaultHasher>,
end: DefaultHasher,
}
pub(super) fn command_hasher() -> &'static RandomState { pub(super) fn command_hasher() -> &'static RandomState {
// Identical hashes feed the binding table and the executor's read cache. // Identical hashes feed the binding table and the executor's read cache.
// The seed and partition are private to this process. // 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. // Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames, ordered_names: OrderedCommandNames,
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>, fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
hash_checkpoints: OnceLock<Arc<CommandHashCheckpoints>>,
} }
impl Default for CommandBindings { impl Default for CommandBindings {
@@ -904,6 +911,7 @@ impl Default for CommandBindings {
revisions: [0; COMMAND_SHARDS], revisions: [0; COMMAND_SHARDS],
ordered_names: Arc::default(), ordered_names: Arc::default(),
fingerprint_inputs: 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 { fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard {
let index = Self::shard_index(command_hasher().hash_one(name)); let index = Self::shard_index(command_hasher().hash_one(name));
self.revisions[index] += 1; self.revisions[index] += 1;
self.hash_checkpoints.take();
Arc::make_mut(&mut self.shards[index]) Arc::make_mut(&mut self.shards[index])
} }
@@ -963,6 +972,7 @@ impl CommandBindings {
return; return;
} }
self.revisions[index] += 1; self.revisions[index] += 1;
self.hash_checkpoints.take();
if Arc::make_mut(shard).insert_hashed(name, meaning, hash).is_none() { if Arc::make_mut(shard).insert_hashed(name, meaning, hash).is_none() {
self.invalidate_order(); self.invalidate_order();
} }
@@ -1019,18 +1029,84 @@ impl CommandBindings {
} }
impl CommandBindings { impl CommandBindings {
fn hash_fingerprint(&self, hasher: &mut FingerprintHasher) { fn first_changed_binding(&self, prior: &Self) -> Option<usize> {
let Ok(mut inputs) = self.fingerprint_inputs.try_lock() else { // Value overwrites can retain the order object. Insertion and
self.hash(hasher); // removal replace it before a different ordered key set is used.
return; if !Arc::ptr_eq(&self.ordered_names, &prior.ordered_names) {
}; return None;
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);
} }
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 &current.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 { impl State {
pub fn fingerprint(&self) -> u64 { 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(); 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);)* $(self.$field.hash(&mut hash);)*
hash.finish() hash.finish()
} }
@@ -1193,6 +1273,45 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
check(&state); 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(&registers_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] #[test]
fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() { fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() {
use super::Span; 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); Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token);
state.define(first, Meaning::Macro(body), true); state.define(first, Meaning::Macro(body), true);
let uncached = check(&state); let uncached = check(&state);
state.command_bindings_mut().hash_checkpoints.take();
let _held = state.commands.fingerprint_inputs.lock().unwrap(); let _held = state.commands.fingerprint_inputs.lock().unwrap();
assert_eq!(state.fingerprint(), uncached); assert_eq!(state.fingerprint(), uncached);
} }
@@ -25,6 +25,21 @@ impl Default for FingerprintHasher {
} }
impl 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] #[inline]
fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) { fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) {
if N > self.buffer.len() - self.used { if N > self.buffer.len() - self.used {
@@ -22,8 +22,10 @@ impl State {
if let Meaning::Macro(body) = meaning { if let Meaning::Macro(body) = meaning {
let relocated = relocation.relocate_macro(body)?; let relocated = relocation.relocate_macro(body)?;
if !Arc::ptr_eq(body, &relocated) { if !Arc::ptr_eq(body, &relocated) {
let shard = &mut Arc::make_mut(&mut self.commands).shards[index]; let commands = self.command_bindings_mut();
Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated)); 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 }; let token_span = Span { source: 0, start: 8, end: 9 };
state.define(name.clone(), meaning(Some(token_span)), true); state.define(name.clone(), meaning(Some(token_span)), true);
assert_eq!(state.commands.shards[shard].source_bounds[&0], Some(9)); 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(); 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(); let mapped = map.relocate_span(token_span).unwrap();
assert_ne!(mapped, token_span); assert_ne!(mapped, token_span);
assert_eq!(state.meaning(&name), meaning(Some(mapped))); assert_eq!(state.meaning(&name), meaning(Some(mapped)));