Reuse exact hash input for shared macro meanings

This commit is contained in:
gloamxun committed 2026-12-02 01:35:49 +08:00
1 parent c4003c8dad
commit ed105bdd39
3 files changed
+320 -86

No files matched your search

+95 -86
View File
@@ -1,9 +1,14 @@
mod fingerprint;
pub(super) mod source_relocation; pub(super) mod source_relocation;
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
use hashbrown::HashMap; use hashbrown::HashMap;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; use std::hash::{BuildHasher, Hash, Hasher, RandomState};
use std::sync::{Arc, OnceLock}; #[cfg(test)]
use std::hash::DefaultHasher;
use std::sync::{Arc, Mutex, OnceLock};
use super::{ use super::{
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register, CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
@@ -856,6 +861,7 @@ struct CommandBindings {
revisions: [u64; COMMAND_SHARDS], revisions: [u64; COMMAND_SHARDS],
// 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>>,
} }
impl Default for CommandBindings { impl Default for CommandBindings {
@@ -867,6 +873,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(),
} }
} }
} }
@@ -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 { impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) { fn hash<H: Hasher>(&self, hasher: &mut H) {
let entries = self.ordered(); let entries = self.ordered();
@@ -988,11 +1011,29 @@ impl<'de> serde::Deserialize<'de> for 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)] #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State { pub struct State {
// Checkpoints share the table. A write copies just its command shard. // Checkpoints share the table. A write copies just its command shard.
// Formats and fingerprints use key order.
commands: Arc<CommandBindings>, 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>, catcodes: BTreeMap<char, CatCode>,
counts: BTreeMap<u16, i32>, counts: BTreeMap<u16, i32>,
toks: BTreeMap<u16, Vec<Token>>, toks: BTreeMap<u16, Vec<Token>>,
@@ -1075,84 +1116,6 @@ pub struct State {
pub(super) hyphenation: super::hyphenation::HyphenationData, 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] #[test]
fn buffered_fingerprint_matches_the_ordered_state_hash() { fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut state = State::initex().with_etex(); let mut state = State::initex().with_etex();
@@ -1178,6 +1141,57 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
check(&state); 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] #[test]
fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() { fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
let mut state = State::initex().with_etex(); 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)>) { pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
self.groups.push(Group { self.groups.push(Group {
kind, 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")
}
}
+30
View File
@@ -156,6 +156,36 @@ p50 分别为 33.2 和 33.3 ms,进程峰值 RSS 为 603,280 KiB。
`target/p4-a4-shard-relocation/`。下一轮继续压缩仍占主要时间的 `target/p4-a4-shard-relocation/`。下一轮继续压缩仍占主要时间的
状态指纹,并认证子文件耗尽后的前后缀资源读证据。 状态指纹,并认证子文件耗尽后的前后缀资源读证据。
## 2026-12-02 复用宏的指纹输入
状态指纹保持现有字段顺序、命令顺序与哈希输入。状态声明与专用
指纹遍历使用同一份字段清单,通用 `Hash` 继续由原有字段派生。
命令表的共享快照可复用完整宏含义写入的字节。缓存使用弱引用保留
分配身份,宏变更时按新分配计算。每个共享命令表的缓存受字节量与
条目数限制。锁占用及超限场景走原计算路径。格式镜像和对外执行
记录仍使用原来的字段。每套共享命令表最多保留 16 MiB 哈希字节
和 8,192 个宏条目。
7 项内核单测和 15 项管线回归通过。两版优化构建的三次冻结 A4
编辑全部与独立全量一致,六个输入和输出指纹逐项相同。两次成功
接缝仍各跳过 20,618 步,组装从 68.34、55.52 ms 降到 46.33、
37.34 ms。三次原生端到端时间有升有降。精确指纹与阶段数据在
`target/p4-a4-fingerprint-proof/direct-comparison.md`。
同机 Edge 对主文件和子文件各采样 30 次。全部 60 次的 PDF、SVG
和来源映射与上一候选逐项一致。主文件 29 次各跳过 20,618 步,
子文件仍执行后缀。服务峰值 RSS 为 619,944 KiB,上一候选为
603,116 KiB。
| A4 热编辑 | 主线可见 p50 / p95 | 上一候选 p50 / p95 | 本轮候选 p50 / p95 |
| --- | ---: | ---: | ---: |
| 主文件正文 | 230.3 / 256.3 ms | 285.4 / 497.4 ms | 264.8 / 493.9 ms |
| 子文件正文 | 184.1 / 241.5 ms | 188.4 / 337.5 ms | 196.8 / 329.7 ms |
100 ms 门槛仍开放。候选保存在 `perf/retained-history-suffix`。
此处两版均为 opt-level 1。实际样本和构建清单在
`target/p4-a4-fingerprint-proof/`。
## 2026-12-02 XeTeX 整行编辑复用 ## 2026-12-02 XeTeX 整行编辑复用
XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他 XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他