Reuse exact hash input for shared macro meanings
This commit is contained in:
1 parent
c4003c8dad
commit
ed105bdd39
3 files changed
+324
-90
No files matched your search
@@ -1,9 +1,14 @@
|
||||
mod fingerprint;
|
||||
pub(super) mod source_relocation;
|
||||
|
||||
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
|
||||
|
||||
use hashbrown::HashMap;
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::hash::{BuildHasher, Hash, Hasher, RandomState};
|
||||
#[cfg(test)]
|
||||
use std::hash::DefaultHasher;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use super::{
|
||||
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
|
||||
@@ -856,6 +861,7 @@ struct CommandBindings {
|
||||
revisions: [u64; COMMAND_SHARDS],
|
||||
// Cache names only so redefinitions can share the same order.
|
||||
ordered_names: OrderedCommandNames,
|
||||
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
|
||||
}
|
||||
|
||||
impl Default for CommandBindings {
|
||||
@@ -867,6 +873,7 @@ impl Default for CommandBindings {
|
||||
}),
|
||||
revisions: [0; COMMAND_SHARDS],
|
||||
ordered_names: Arc::default(),
|
||||
fingerprint_inputs: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -959,6 +966,22 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for CommandBindings {
|
||||
fn hash<H: Hasher>(&self, hasher: &mut H) {
|
||||
let entries = self.ordered();
|
||||
@@ -988,11 +1011,29 @@ impl<'de> serde::Deserialize<'de> for CommandBindings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct State {
|
||||
// Checkpoints share the table. A write copies just its command shard.
|
||||
// Formats and fingerprints use key order.
|
||||
commands: Arc<CommandBindings>,
|
||||
// Derive the ordinary hash and emit the specialized fingerprint in the
|
||||
// same field order. Only the command meanings can reuse recorded hash input.
|
||||
macro_rules! define_state {
|
||||
($( $(#[$metadata:meta])* $access:vis $field:ident: $ty:ty, )*) => {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct State {
|
||||
// Checkpoints share the table. A write copies just its command shard.
|
||||
commands: Arc<CommandBindings>,
|
||||
$( $(#[$metadata])* $access $field: $ty, )*
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn fingerprint(&self) -> u64 {
|
||||
let mut hash = FingerprintHasher::default();
|
||||
self.commands.hash_fingerprint(&mut hash);
|
||||
$(self.$field.hash(&mut hash);)*
|
||||
hash.finish()
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
define_state! {
|
||||
catcodes: BTreeMap<char, CatCode>,
|
||||
counts: BTreeMap<u16, i32>,
|
||||
toks: BTreeMap<u16, Vec<Token>>,
|
||||
@@ -1075,84 +1116,6 @@ pub struct State {
|
||||
pub(super) hyphenation: super::hyphenation::HyphenationData,
|
||||
}
|
||||
|
||||
// Batch the many small token and integer writes in a state fingerprint.
|
||||
// The ordered bytes still go through the native state fingerprint's hasher.
|
||||
struct FingerprintHasher {
|
||||
hasher: DefaultHasher,
|
||||
buffer: [u8; 4096],
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Default for FingerprintHasher {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hasher: DefaultHasher::new(),
|
||||
buffer: [0; 4096],
|
||||
used: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FingerprintHasher {
|
||||
#[inline]
|
||||
fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) {
|
||||
if N > self.buffer.len() - self.used {
|
||||
self.hasher.write(&self.buffer[..self.used]);
|
||||
self.used = 0;
|
||||
}
|
||||
let end = self.used + N;
|
||||
self.buffer[self.used..end].copy_from_slice(&bytes);
|
||||
self.used = end;
|
||||
}
|
||||
}
|
||||
|
||||
impl Hasher for FingerprintHasher {
|
||||
#[inline]
|
||||
fn write_u8(&mut self, value: u8) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u16(&mut self, value: u16) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u32(&mut self, value: u32) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u64(&mut self, value: u64) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_usize(&mut self, value: usize) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
if bytes.len() > self.buffer.len() - self.used {
|
||||
self.hasher.write(&self.buffer[..self.used]);
|
||||
self.used = 0;
|
||||
}
|
||||
if bytes.len() > self.buffer.len() {
|
||||
self.hasher.write(bytes);
|
||||
} else {
|
||||
let end = self.used + bytes.len();
|
||||
self.buffer[self.used..end].copy_from_slice(bytes);
|
||||
self.used = end;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
let mut hasher = self.hasher.clone();
|
||||
hasher.write(&self.buffer[..self.used]);
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffered_fingerprint_matches_the_ordered_state_hash() {
|
||||
let mut state = State::initex().with_etex();
|
||||
@@ -1178,6 +1141,57 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
|
||||
check(&state);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() {
|
||||
use super::Span;
|
||||
|
||||
let check = |state: &State| {
|
||||
let mut direct = DefaultHasher::new();
|
||||
state.hash(&mut direct);
|
||||
let fingerprint = state.fingerprint();
|
||||
assert_eq!(fingerprint, direct.finish());
|
||||
fingerprint
|
||||
};
|
||||
let first = CommandName::Control("测试命令".into());
|
||||
let alias = CommandName::Control("命令别名".into());
|
||||
let mut token = Token::new(
|
||||
TokenKind::Command(CommandName::Control("αβγ".into())),
|
||||
Span { source: 2, start: 40, end: 44 },
|
||||
);
|
||||
token.invocation = Some(Span { source: 3, start: 99, end: 101 });
|
||||
let mut body = Arc::new(Macro {
|
||||
prefix: vec![TokenKind::Character('木', CatCode::Letter)],
|
||||
parameters: vec![vec![TokenKind::Character('λ', CatCode::Other)]],
|
||||
parameter_chars: vec!['#'],
|
||||
replacement: vec![Replacement::Token(token.clone()); 80],
|
||||
long: true,
|
||||
outer: false,
|
||||
protected: true,
|
||||
});
|
||||
|
||||
let mut state = State::default();
|
||||
state.define(first.clone(), Meaning::Macro(body.clone()), true);
|
||||
state.define(alias, Meaning::Macro(body.clone()), true);
|
||||
let original = check(&state);
|
||||
assert_eq!(Arc::weak_count(&body), 1);
|
||||
assert_eq!(check(&state), original);
|
||||
let donor = state.clone();
|
||||
|
||||
token.invocation = Some(Span { source: 3, start: 111, end: 113 });
|
||||
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token.clone());
|
||||
state.define(first.clone(), Meaning::Macro(body.clone()), true);
|
||||
assert_ne!(check(&state), original);
|
||||
assert_eq!(check(&donor), original);
|
||||
assert_eq!(Arc::weak_count(&body), 1);
|
||||
|
||||
token.kind = TokenKind::Command(CommandName::Control("λ".repeat(40_000)));
|
||||
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token);
|
||||
state.define(first, Meaning::Macro(body), true);
|
||||
let uncached = check(&state);
|
||||
let _held = state.commands.fingerprint_inputs.lock().unwrap();
|
||||
assert_eq!(state.fingerprint(), uncached);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
|
||||
let mut state = State::initex().with_etex();
|
||||
@@ -2828,11 +2842,6 @@ impl State {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fingerprint(&self) -> u64 {
|
||||
let mut hash = FingerprintHasher::default();
|
||||
self.hash(&mut hash);
|
||||
hash.finish()
|
||||
}
|
||||
pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
|
||||
self.groups.push(Group {
|
||||
kind,
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
use super::{Macro, Meaning};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fmt,
|
||||
hash::{DefaultHasher, Hash, Hasher},
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
// Batch the many small token and integer writes in a state fingerprint.
|
||||
// The ordered bytes still go through the native state fingerprint's hasher.
|
||||
pub(super) struct FingerprintHasher {
|
||||
hasher: DefaultHasher,
|
||||
buffer: [u8; 4096],
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl Default for FingerprintHasher {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hasher: DefaultHasher::new(),
|
||||
buffer: [0; 4096],
|
||||
used: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FingerprintHasher {
|
||||
#[inline]
|
||||
fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) {
|
||||
if N > self.buffer.len() - self.used {
|
||||
self.hasher.write(&self.buffer[..self.used]);
|
||||
self.used = 0;
|
||||
}
|
||||
let end = self.used + N;
|
||||
self.buffer[self.used..end].copy_from_slice(&bytes);
|
||||
self.used = end;
|
||||
}
|
||||
}
|
||||
|
||||
impl Hasher for FingerprintHasher {
|
||||
#[inline]
|
||||
fn write_u8(&mut self, value: u8) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u16(&mut self, value: u16) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u32(&mut self, value: u32) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_u64(&mut self, value: u64) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn write_usize(&mut self, value: usize) {
|
||||
self.write_fixed(value.to_ne_bytes());
|
||||
}
|
||||
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
if bytes.len() > self.buffer.len() - self.used {
|
||||
self.hasher.write(&self.buffer[..self.used]);
|
||||
self.used = 0;
|
||||
}
|
||||
if bytes.len() > self.buffer.len() {
|
||||
self.hasher.write(bytes);
|
||||
} else {
|
||||
let end = self.used + bytes.len();
|
||||
self.buffer[self.used..end].copy_from_slice(bytes);
|
||||
self.used = end;
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
let mut hasher = self.hasher.clone();
|
||||
hasher.write(&self.buffer[..self.used]);
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_CACHED_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_CACHED_MACROS: usize = 8192;
|
||||
const MAX_RECORDED_BYTES: usize = 64 * 1024;
|
||||
const MIN_REPLACEMENT_TOKENS: usize = 8;
|
||||
|
||||
struct MacroInput {
|
||||
// Keep the allocation address reserved while its bytes are cached,
|
||||
// without keeping the definition or its token storage alive.
|
||||
body: Weak<Macro>,
|
||||
bytes: Option<Box<[u8]>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MacroFingerprintInputs {
|
||||
inputs: HashMap<usize, MacroInput>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl fmt::Debug for MacroFingerprintInputs {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("MacroFingerprintInputs")
|
||||
.field("entries", &self.inputs.len())
|
||||
.field("bytes", &self.bytes)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl MacroFingerprintInputs {
|
||||
fn full(&self) -> bool {
|
||||
self.bytes >= MAX_CACHED_BYTES || self.inputs.len() >= MAX_CACHED_MACROS
|
||||
}
|
||||
|
||||
pub(super) fn prune_if_full(&mut self) {
|
||||
if self.full() {
|
||||
self.inputs.retain(|_, input| {
|
||||
let live = input.body.strong_count() > 0;
|
||||
if !live {
|
||||
self.bytes -= input.bytes.as_deref().map_or(0, <[u8]>::len);
|
||||
}
|
||||
live
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn hash_meaning(&mut self, meaning: &Meaning, hasher: &mut FingerprintHasher) {
|
||||
let Meaning::Macro(body) = meaning else {
|
||||
meaning.hash(hasher);
|
||||
return;
|
||||
};
|
||||
if body.replacement.len() < MIN_REPLACEMENT_TOKENS {
|
||||
meaning.hash(hasher);
|
||||
return;
|
||||
}
|
||||
let key = Arc::as_ptr(body) as usize;
|
||||
if let Some(input) = self.inputs.get(&key) {
|
||||
if let Some(bytes) = &input.bytes {
|
||||
hasher.write(bytes);
|
||||
} else {
|
||||
meaning.hash(hasher);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.full() {
|
||||
meaning.hash(hasher);
|
||||
return;
|
||||
}
|
||||
|
||||
// Record the complete Meaning hash, including its enum tag. Replay
|
||||
// only to FingerprintHasher, whose integer, length, and string writes
|
||||
// consume the same ordered bytes as the recorder's default methods.
|
||||
let mut record = HashInput::default();
|
||||
meaning.hash(&mut record);
|
||||
let mut bytes = None;
|
||||
if record.overflow {
|
||||
meaning.hash(hasher);
|
||||
} else {
|
||||
hasher.write(&record.bytes);
|
||||
if record.bytes.len() <= MAX_CACHED_BYTES - self.bytes {
|
||||
self.bytes += record.bytes.len();
|
||||
bytes = Some(record.bytes.into_boxed_slice());
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.inputs.insert(key, MacroInput { body: Arc::downgrade(body), bytes });
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct HashInput {
|
||||
bytes: Vec<u8>,
|
||||
overflow: bool,
|
||||
}
|
||||
|
||||
impl Hasher for HashInput {
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
if !self.overflow {
|
||||
if bytes.len() > MAX_RECORDED_BYTES - self.bytes.len() {
|
||||
self.overflow = true;
|
||||
} else {
|
||||
self.bytes.extend_from_slice(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&self) -> u64 {
|
||||
unreachable!("recording a macro writes hash input without finishing a digest")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user