Copy native command bindings through smaller persistent shards

This commit is contained in:
gloamxun committed 2026-12-02 04:19:06 +08:00
1 parent a7c2a571c1
commit 37a42c82c8
2 files changed
+100 -49

No files matched your search

+96 -43
View File
@@ -802,9 +802,11 @@ enum PdftexRevision {
R24,
}
// A single definition after a checkpoint copies its shard. Smaller shards
// keep that copy proportional to the modified part of the command table.
const COMMAND_SHARDS: usize = 128;
// The first write after a checkpoint copies one directory group and one
// small shard. The group's local revisions remain cheap to read and copy.
const COMMAND_SHARD_GROUPS: usize = 32;
const COMMAND_SHARDS_PER_GROUP: usize = 16;
const COMMAND_SHARDS: usize = COMMAND_SHARD_GROUPS * COMMAND_SHARDS_PER_GROUP;
type CommandEntries = HashMap<Arc<CommandName>, Meaning, RandomState>;
#[derive(Clone, Debug)]
@@ -819,7 +821,10 @@ struct CommandShard {
impl CommandShard {
fn new(hasher: RandomState) -> Self {
Self { entries: CommandEntries::with_hasher(hasher), source_bounds: BTreeMap::new() }
Self {
entries: CommandEntries::with_hasher(hasher),
source_bounds: BTreeMap::new(),
}
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) -> Option<Meaning> {
@@ -843,12 +848,14 @@ impl CommandShard {
}
}
fn insert_if_absent(&mut self, name: Arc<CommandName>, meaning: Meaning) -> bool {
let hashbrown::hash_map::Entry::Vacant(entry) = self.entries.entry(name) else {
fn insert_if_absent(&mut self, name: Arc<CommandName>, meaning: Meaning, hash: u64) -> bool {
let RawEntryMut::Vacant(entry) =
self.entries.raw_entry_mut().from_key_hashed_nocheck(hash, name.as_ref())
else {
return false;
};
source_relocation::include_meaning_bounds(&mut self.source_bounds, &meaning);
entry.insert(meaning);
entry.insert_hashed_nocheck(hash, name, meaning);
true
}
}
@@ -874,6 +881,21 @@ impl PartialEq for CommandShard {
}
impl Eq for CommandShard {}
#[derive(Clone, Debug)]
struct CommandShardGroup {
shards: [Arc<CommandShard>; COMMAND_SHARDS_PER_GROUP],
revisions: [u64; COMMAND_SHARDS_PER_GROUP],
}
impl PartialEq for CommandShardGroup {
fn eq(&self, other: &Self) -> bool {
self.shards == other.shards
}
}
impl Eq for CommandShardGroup {}
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
const COMMAND_HASH_CHECKPOINT_STRIDE: usize = 128;
@@ -893,8 +915,7 @@ pub(super) fn command_hasher() -> &'static RandomState {
#[derive(Clone, Debug)]
struct CommandBindings {
shards: [Arc<CommandShard>; COMMAND_SHARDS],
revisions: [u64; COMMAND_SHARDS],
shard_groups: [Arc<CommandShardGroup>; COMMAND_SHARD_GROUPS],
// Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames,
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
@@ -905,10 +926,10 @@ impl Default for CommandBindings {
fn default() -> Self {
let hasher = command_hasher();
Self {
shards: std::array::from_fn(|_| {
Arc::new(CommandShard::new(hasher.clone()))
}),
revisions: [0; COMMAND_SHARDS],
shard_groups: std::array::from_fn(|_| Arc::new(CommandShardGroup {
shards: std::array::from_fn(|_| Arc::new(CommandShard::new(hasher.clone()))),
revisions: [0; COMMAND_SHARDS_PER_GROUP],
})),
ordered_names: Arc::default(),
fingerprint_inputs: Arc::default(),
hash_checkpoints: OnceLock::new(),
@@ -918,7 +939,7 @@ impl Default for CommandBindings {
impl PartialEq for CommandBindings {
fn eq(&self, other: &Self) -> bool {
self.shards == other.shards
self.shard_groups == other.shard_groups
}
}
@@ -930,6 +951,14 @@ impl CommandBindings {
((hash >> 32) as usize) % COMMAND_SHARDS
}
fn shard(&self, index: usize) -> &Arc<CommandShard> {
&self.shard_groups[index / COMMAND_SHARDS_PER_GROUP].shards[index % COMMAND_SHARDS_PER_GROUP]
}
fn shards(&self) -> impl Iterator<Item = &Arc<CommandShard>> {
self.shard_groups.iter().flat_map(|group| &group.shards)
}
fn get(&self, name: &CommandName) -> Option<&Meaning> {
self.get_hashed(name, command_hasher().hash_one(name))
}
@@ -943,26 +972,38 @@ impl CommandBindings {
name: &CommandName,
hash: u64,
) -> Option<(&Arc<CommandName>, &Meaning)> {
self.shards[Self::shard_index(hash)]
self.shard(Self::shard_index(hash))
.entries
.raw_entry()
.from_key_hashed_nocheck(hash, name)
}
fn shard_mut(&mut self, name: &CommandName) -> &mut CommandShard {
let index = Self::shard_index(command_hasher().hash_one(name));
self.revisions[index] += 1;
fn shard_group_mut(&mut self, index: usize) -> &mut CommandShardGroup {
self.hash_checkpoints.take();
Arc::make_mut(&mut self.shards[index])
Arc::make_mut(&mut self.shard_groups[index / COMMAND_SHARDS_PER_GROUP])
}
fn shard_mut(&mut self, index: usize) -> &mut CommandShard {
let group = self.shard_group_mut(index);
Arc::make_mut(&mut group.shards[index % COMMAND_SHARDS_PER_GROUP])
}
fn revise_shard(&mut self, hash: u64) -> &mut CommandShard {
let index = Self::shard_index(hash);
let group = self.shard_group_mut(index);
let slot = index % COMMAND_SHARDS_PER_GROUP;
group.revisions[slot] += 1;
Arc::make_mut(&mut group.shards[slot])
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) {
let hash = command_hasher().hash_one(name.as_ref());
let index = Self::shard_index(hash);
let shard = &mut self.shards[index];
// The caller already saved or cleared the group entry. The shared
// shard can stay in place when the installed binding is identical.
if Arc::strong_count(shard) > 1
let group = &self.shard_groups[index / COMMAND_SHARDS_PER_GROUP];
let shard = &group.shards[index % COMMAND_SHARDS_PER_GROUP];
// The caller already saved or cleared the TeX group entry. Either
// level of sharing can make an identical installation avoid a copy.
if (Arc::strong_count(group) > 1 || Arc::strong_count(shard) > 1)
&& shard.entries.raw_entry().from_key_hashed_nocheck(hash, name.as_ref())
.is_some_and(|(_, previous)| match (previous, &meaning) {
(Meaning::Macro(previous), Meaning::Macro(body)) => Arc::ptr_eq(previous, body),
@@ -971,21 +1012,24 @@ impl CommandBindings {
{
return;
}
self.revisions[index] += 1;
self.hash_checkpoints.take();
if Arc::make_mut(shard).insert_hashed(name, meaning, hash).is_none() {
if self.revise_shard(hash).insert_hashed(name, meaning, hash).is_none() {
self.invalidate_order();
}
}
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
if self.shard_mut(&name).insert_if_absent(name.into(), meaning) {
let hash = command_hasher().hash_one(&name);
if self.revise_shard(hash).insert_if_absent(name.into(), meaning, hash) {
self.invalidate_order();
}
}
fn remove(&mut self, name: &CommandName) {
if self.shard_mut(name).entries.remove(name).is_some() {
let hash = command_hasher().hash_one(name);
if let RawEntryMut::Occupied(entry) =
self.revise_shard(hash).entries.raw_entry_mut().from_key_hashed_nocheck(hash, name)
{
entry.remove();
self.invalidate_order();
}
}
@@ -999,11 +1043,11 @@ impl CommandBindings {
}
fn len(&self) -> usize {
self.shards.iter().map(|shard| shard.entries.len()).sum()
self.shards().map(|shard| shard.entries.len()).sum()
}
fn iter(&self) -> impl Iterator<Item = (&Arc<CommandName>, &Meaning)> {
self.shards.iter().flat_map(|shard| shard.entries.iter())
self.shards().flat_map(|shard| shard.entries.iter())
}
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> {
@@ -1037,7 +1081,9 @@ impl CommandBindings {
}
let names = prior.ordered_names.get()?;
let mut first = None;
for (current, old) in self.shards.iter().zip(&prior.shards) {
let changed_groups = self.shard_groups.iter().zip(&prior.shard_groups)
.filter(|(current, old)| !Arc::ptr_eq(current, old));
for (current, old) in changed_groups.flat_map(|(current, old)| current.shards.iter().zip(&old.shards)) {
if Arc::ptr_eq(current, old) {
continue;
}
@@ -1447,12 +1493,12 @@ fn paired_statistics_keep_aliases_within_changed_command_shards() {
prior.define(name.clone(), Meaning::Count(0), true);
}
let original = &prior.commands.shards[index];
let original = prior.commands.shard(index);
let mut matching = prior.clone();
let matching_shard = Arc::make_mut(&mut matching.command_bindings_mut().shards[index]);
let matching_shard = matching.command_bindings_mut().shard_mut(index);
assert!(original.entries.keys().eq(matching_shard.entries.keys()));
let mut reordered = matching.clone();
let changed = Arc::make_mut(&mut reordered.command_bindings_mut().shards[index]);
let changed = reordered.command_bindings_mut().shard_mut(index);
for capacity in [32, 64, 128, 256, 512, 1024] {
changed.entries.reserve(capacity);
if !original.entries.keys().eq(changed.entries.keys()) {
@@ -1473,11 +1519,11 @@ fn paired_statistics_keep_aliases_within_changed_command_shards() {
live.has_equivalent_history(&old_live, &history, &history)
};
for (mut current, expect_same_order) in [(matching, true), (reordered, false)] {
assert!(!Arc::ptr_eq(original, &current.commands.shards[index]));
assert!(!Arc::ptr_eq(original, current.commands.shard(index)));
assert_eq!(current, prior);
assert!(counts(&current));
let changed = Arc::make_mut(&mut current.command_bindings_mut().shards[index]);
let changed = current.command_bindings_mut().shard_mut(index);
*changed.entries.get_mut(edited).unwrap() = Meaning::Macro(second_body.clone());
assert_eq!(original.entries.keys().eq(changed.entries.keys()), expect_same_order);
assert_eq!(current, prior);
@@ -1550,12 +1596,12 @@ fn reinstalling_a_shared_binding_preserves_its_allocation_and_epoch() {
assert!(Arc::ptr_eq(&key, &state.cache_meaning_hashed(&name, hash).0));
state.define(name.clone(), Meaning::Macro(body.clone()), true);
assert!(Arc::ptr_eq(&state.commands.shards[index], &prior.commands.shards[index]));
assert!(Arc::ptr_eq(state.commands.shard(index), prior.commands.shard(index)));
assert_eq!(state.command_revision(hash), prior.command_revision(hash));
let independent = Arc::new(body.as_ref().clone());
state.define(name.clone(), Meaning::Macro(independent.clone()), true);
assert!(!Arc::ptr_eq(&state.commands.shards[index], &prior.commands.shards[index]));
assert!(!Arc::ptr_eq(state.commands.shard(index), prior.commands.shard(index)));
assert_eq!(state.command_revision(hash), prior.command_revision(hash) + 1);
let Meaning::Macro(installed) = state.meaning(&name) else { panic!("expected macro") };
assert!(Arc::ptr_eq(&installed, &independent));
@@ -1567,7 +1613,7 @@ fn reinstalling_a_shared_binding_preserves_its_allocation_and_epoch() {
let saved = Key::Command(name.clone());
assert!(state.groups.last().unwrap().saved.contains_key(&saved));
state.define(name, Meaning::Count(5), true);
assert!(Arc::ptr_eq(&state.commands.shards[index], &local.commands.shards[index]));
assert!(Arc::ptr_eq(state.commands.shard(index), local.commands.shard(index)));
assert!(!state.groups.last().unwrap().saved.contains_key(&saved));
}
@@ -1581,9 +1627,14 @@ fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
state.define(name.clone(), Meaning::Count(7), true);
assert_eq!(snapshot.meaning(&name), Meaning::Count(3));
assert_eq!(state.meaning(&name), Meaning::Count(7));
let shared = state.commands.shards.iter().zip(&snapshot.commands.shards)
let shared = state.commands.shards().zip(snapshot.commands.shards())
.filter(|(current, saved)| Arc::ptr_eq(current, saved)).count();
assert_eq!(shared, COMMAND_SHARDS - 1);
let shared_groups = state.commands.shard_groups.iter().zip(&snapshot.commands.shard_groups)
.filter(|(current, saved)| Arc::ptr_eq(current, saved)).count();
assert_eq!(shared_groups, COMMAND_SHARD_GROUPS - 1);
let hash = command_hasher().hash_one(&name);
assert_eq!(state.command_revision(hash), snapshot.command_revision(hash) + 1);
assert!(Arc::ptr_eq(
&state.commands.ordered_names,
&snapshot.commands.ordered_names,
@@ -2104,7 +2155,7 @@ impl State {
} else {
current_usage.usage.state.command_entries = old.commands.len();
let mut changed_macros = Vec::new();
for (current, prior) in self.commands.shards.iter().zip(&old.commands.shards) {
for (current, prior) in self.commands.shards().zip(old.commands.shards()) {
if current.entries.len() != prior.entries.len() {
return None;
}
@@ -3026,8 +3077,9 @@ impl State {
let state = Self::initex().with_input_profile(self.input_profile);
let state = if extended { state.with_etex() } else { state };
Arc::unwrap_or_clone(state.commands)
.shards
.shard_groups
.into_iter()
.flat_map(|group| Arc::unwrap_or_clone(group).shards)
.flat_map(|shard| Arc::unwrap_or_clone(shard).entries)
.filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) {
CommandName::Control(name) => Some((name, meaning)),
@@ -3044,7 +3096,8 @@ impl State {
}
pub(super) fn command_revision(&self, hash: u64) -> u64 {
self.commands.revisions[CommandBindings::shard_index(hash)]
let index = CommandBindings::shard_index(hash);
self.commands.shard_groups[index / COMMAND_SHARDS_PER_GROUP].revisions[index % COMMAND_SHARDS_PER_GROUP]
}
pub fn meaning(&self, name: &CommandName) -> Meaning {
@@ -14,7 +14,7 @@ impl State {
let commands = self.commands.clone();
// Copy only shards with a relocated macro. Ordinary format macros
// and macros from the byte-identical prefix keep their allocations.
for (index, shard) in commands.shards.iter().enumerate() {
for (index, shard) in commands.shards().enumerate() {
if shard.preserves_source_spans(relocation.map()) {
continue;
}
@@ -22,9 +22,7 @@ impl State {
if let Meaning::Macro(body) = meaning {
let relocated = relocation.relocate_macro(body)?;
if !Arc::ptr_eq(body, &relocated) {
let commands = self.command_bindings_mut();
commands.hash_checkpoints.take();
Arc::make_mut(&mut commands.shards[index])
self.command_bindings_mut().shard_mut(index)
.insert(name.clone(), Meaning::Macro(relocated));
}
}
@@ -166,12 +164,12 @@ fn command_bounds_track_redefinitions_and_invocation_origins() {
let mut state = State::default();
state.define(name.clone(), meaning(None), true);
let shard = CommandBindings::shard_index(command_hasher().hash_one(&name));
assert_eq!(state.commands.shards[shard].source_bounds[&0], Some(1));
assert_eq!(state.commands.shard(shard).source_bounds[&0], Some(1));
let before = state.clone();
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));
assert_eq!(state.commands.shard(shard).source_bounds[&0], Some(9));
let prior_hash = state.fingerprint();
let donor = state.clone();
state.relocate_source(&mut EventRelocation::new(&map)).unwrap();