Reduce macro copying during native suffix convergence

This commit is contained in:
gloamxun committed 2026-12-01 22:50:53 +08:00
1 parent 57c05d9635
commit c008c52964
9 files changed
+228 -110

No files matched your search

@@ -1,4 +1,6 @@
use super::super::source_relocation::SourceRelocation;
use super::super::{
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
};
use super::*;
mod material;
mod relocate;
@@ -171,7 +173,10 @@ impl EntryCheckpoint {
None if self.frontier == prior.frontier => None,
None => return None,
};
if !same_kernel_continuation(current, old, relocation.as_ref()) {
// Comparison and publication visit some of the same original
// allocations. Keep the checked relocations for this donor only.
let mut moved = relocation.as_ref().map(EventRelocation::new);
if !same_kernel_continuation(current, old, moved.as_mut()) {
return None;
}
let offset = StepOffset::new(old.steps, current.steps);
@@ -214,8 +219,11 @@ impl EntryCheckpoint {
reads_event_history: false,
accounts_event_history: completed.accounts_event_history,
};
if let Some((map, sizes)) = relocation.as_ref().zip(entry_sizes) {
relocate::append_suffix(&mut execution, tail, offset, map, sizes, old.sources.len())?;
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
relocate::append_suffix(&mut execution, tail, offset, moved, sizes, old.sources.len())?;
if execution.state != completed.state {
execution.outgoing_state = execution.state.fingerprint();
}
} else if offset.is_identity() {
execution.events.extend_from_slice(tail);
} else {
@@ -378,7 +386,7 @@ fn is_idle_continuation(e: &Executor) -> bool {
fn same_kernel_continuation(
current: &Executor,
prior: &Executor,
relocation: Option<&SourceRelocation>,
relocation: Option<&mut EventRelocation<'_>>,
) -> bool {
// Every field belongs to one of these checks. Adding kernel state requires
// an explicit decision here before a later execution may be skipped.
@@ -489,9 +497,10 @@ fn same_kernel_continuation(
{
return false;
}
let map = relocation.as_ref().map(|context| context.map());
let relocated;
let prior = if let Some(map) = relocation {
relocated = match relocate::kernel_continuation(prior, map) {
let prior = if let Some(context) = relocation {
relocated = match relocate::kernel_continuation(prior, context) {
Some(executor) => executor,
None => return false,
};
@@ -522,5 +531,5 @@ fn same_kernel_continuation(
.inputs
.iter()
.zip(&prior.inputs)
.all(|(a, b)| a.same_at_shipout(b, relocation))
.all(|(a, b)| a.same_at_shipout(b, map))
}
@@ -1,26 +1,26 @@
use super::*;
use crate::execution::{
source_relocation_events::EventRelocation, state::source_relocation::relocate_macro,
};
use crate::execution::source_relocation_events::EventRelocation;
pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> Option<Executor> {
pub(super) fn kernel_continuation(
prior: &Executor,
relocation: &mut EventRelocation<'_>,
) -> Option<Executor> {
let mut prior = prior.clone();
let mut relocation = EventRelocation::new(map);
let map = relocation.map();
prior.current = map.relocate_span(prior.current)?;
prior.state = prior.state.relocate_source(&mut relocation)?;
prior.state.relocate_source(relocation)?;
relocate_generated(&mut prior.generated_inputs, map)?;
for conditional in &mut prior.conditionals {
conditional.span = map.relocate_span(conditional.span)?;
}
let mut macros = std::collections::HashMap::new();
for frame in &mut prior.inputs {
match frame {
InputFrame::Tokens { tokens, .. } => match tokens {
InputTokens::One(token) => token.token = relocation.relocate_token(&token.token)?,
InputTokens::One(token) => relocation.relocate_token(&mut token.token)?,
InputTokens::Many(tokens) => {
for token in tokens {
token.token = relocation.relocate_token(&token.token)?;
relocation.relocate_token(&mut token.token)?;
}
}
},
@@ -30,7 +30,7 @@ pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> O
call,
..
} => {
*definition = relocate_macro(definition, &mut relocation, &mut macros)?;
*definition = relocation.relocate_macro(definition)?;
for tokens in arguments {
*tokens = relocation.relocate_tokens(tokens)?;
}
@@ -45,17 +45,17 @@ pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> O
InputFrame::Source { .. } | InputFrame::Boundary => {}
}
}
relocate_tokens(&mut prior.pdf_catalog_tokens, &mut relocation)?;
relocate_tokens(&mut prior.pdf_info_tokens, &mut relocation)?;
relocate_tokens(&mut prior.pdf_catalog_tokens, relocation)?;
relocate_tokens(&mut prior.pdf_info_tokens, relocation)?;
for outline in &mut prior.pdf_outlines {
relocate_tokens(&mut outline.attributes, &mut relocation)?;
relocate_tokens(&mut outline.attributes, relocation)?;
}
if let Some(token) = &mut prior.after_assignment {
*token = relocation.relocate_token(token)?;
relocation.relocate_token(token)?;
}
relocate_vertical(&mut prior.vertical.nodes, &mut relocation)?;
relocate_vertical(&mut prior.split_discards, &mut relocation)?;
relocate_page(&mut prior.native_page, &mut relocation)?;
relocate_vertical(&mut prior.vertical.nodes, relocation)?;
relocate_vertical(&mut prior.split_discards, relocation)?;
relocate_page(&mut prior.native_page, relocation)?;
for value in &mut prior.pending_shipouts {
*value = relocation.relocate_box(value)?;
}
@@ -66,11 +66,11 @@ pub(super) fn append_suffix(
execution: &mut Execution,
tail: &[Event],
offset: StepOffset,
map: &SourceRelocation,
relocation: &mut EventRelocation<'_>,
(previous_bytes, current_bytes): (usize, usize),
source_count: usize,
) -> Option<()> {
let mut relocation = EventRelocation::new(map);
let map = relocation.map();
for event in tail {
if let Event::Statistics(report) = event {
if let StatisticsPhase::Shipout { before, after } = &report.phase {
@@ -90,19 +90,15 @@ pub(super) fn append_suffix(
execution.events.push(relocation.relocate_event(event)?);
}
}
let state = execution.state.relocate_source(&mut relocation)?;
if state != execution.state {
execution.outgoing_state = state.fingerprint();
}
execution.state = state;
relocate_page(&mut execution.native_page, &mut relocation)?;
relocate_vertical(&mut execution.split_discards, &mut relocation)?;
execution.state.relocate_source(relocation)?;
relocate_page(&mut execution.native_page, relocation)?;
relocate_vertical(&mut execution.split_discards, relocation)?;
if let Some(token) = &mut execution.after_assignment {
*token = relocation.relocate_token(token)?;
relocation.relocate_token(token)?;
}
relocate_generated(&mut execution.generated_inputs, map)?;
for image in &mut execution.format_pdf_images {
relocate_tokens(&mut image.attributes, &mut relocation)?;
relocate_tokens(&mut image.attributes, relocation)?;
}
Some(())
}
@@ -132,7 +128,7 @@ fn relocate_page(
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
for token in tokens {
*token = relocation.relocate_token(token)?;
relocation.relocate_token(token)?;
}
Some(())
}
@@ -332,12 +332,12 @@ impl RevisionJob {
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
// Host observations can themselves supersede the revision. Do not
// invoke the host while holding the session publication lock.
let resources = files.execution_resource_trace().cloned();
let mut resources = files.execution_resource_trace().cloned();
let result = executed.map(|execution| {
Arc::new(RevisionExecution::with_previous_sources(
self.revision,
execution,
resources.clone(),
resources.take(),
previous,
))
});
@@ -359,13 +359,17 @@ impl RevisionJob {
completed_execution: None,
resources,
}),
Ok(result) if cancelled => Err(RevisionFailure {
revision: self.revision,
error: RevisionError::Cancelled,
failed_execution: None,
completed_execution: Some(result),
resources,
}),
Ok(result) if cancelled => {
drop(state);
let resources = result.execution_resources.clone();
Err(RevisionFailure {
revision: self.revision,
error: RevisionError::Cancelled,
failed_execution: None,
completed_execution: Some(result),
resources,
})
}
Ok(result) => {
state.latest = Some(Arc::clone(&result));
Ok(result)
@@ -11,12 +11,16 @@ use crate::{
},
provenance::PaintSource,
};
use std::{collections::HashMap, sync::Arc};
use std::{
collections::{HashMap, hash_map::Entry},
sync::Arc,
};
type Shared<T> = HashMap<*const T, Arc<T>>;
pub(super) struct EventRelocation<'a> {
map: &'a SourceRelocation,
macros: Shared<Macro>,
text_lists: Shared<Vec<TextNode>>,
vertical_lists: Shared<Vec<NativeVerticalNode>>,
diagnostic_lists: Shared<[DiagnosticNode]>,
@@ -28,6 +32,7 @@ impl<'a> EventRelocation<'a> {
pub(super) fn new(map: &'a SourceRelocation) -> Self {
Self {
map,
macros: HashMap::new(),
text_lists: HashMap::new(),
vertical_lists: HashMap::new(),
diagnostic_lists: HashMap::new(),
@@ -36,6 +41,10 @@ impl<'a> EventRelocation<'a> {
}
}
pub(super) fn map(&self) -> &'a SourceRelocation {
self.map
}
pub(super) fn relocate_event(&mut self, event: &Event) -> Option<Event> {
self.relocated(event)
}
@@ -51,8 +60,36 @@ impl<'a> EventRelocation<'a> {
self.relocated(node)
}
pub(super) fn relocate_token(&mut self, token: &Token) -> Option<Token> {
self.relocated(token)
pub(super) fn relocate_token(&mut self, token: &mut Token) -> Option<()> {
token.relocate(self)
}
pub(super) fn relocate_macro(&mut self, body: &Arc<Macro>) -> Option<Arc<Macro>> {
match self.macros.entry(Arc::as_ptr(body)) {
Entry::Occupied(entry) => Some(entry.get().clone()),
Entry::Vacant(entry) => {
let mut mapped = None;
for (index, part) in body.replacement.iter().enumerate() {
if let Replacement::Token(token) = part {
let previous = TokenOrigin::from(token);
let mut next = previous;
relocate_origin(&mut next, self.map)?;
if next != previous {
let replacement = &mut mapped
.get_or_insert_with(|| body.as_ref().clone())
.replacement[index];
let Replacement::Token(token) = replacement else {
unreachable!("cloned macro replacement retains its token kind");
};
token.span = next.span;
token.invocation = next.invocation;
}
}
}
let mapped = mapped.map_or_else(|| body.clone(), Arc::new);
Some(entry.insert(mapped).clone())
}
}
}
pub(super) fn relocate_tokens(&mut self, tokens: &Arc<[Token]>) -> Option<Arc<[Token]>> {
@@ -150,7 +187,20 @@ macro_rules! relocate_fields {
}
relocate_fields!(Token { span, invocation; kind });
relocate_fields!(TokenOrigin { span, invocation; });
impl Relocate for TokenOrigin {
fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> {
relocate_origin(self, context.map)
}
}
fn relocate_origin(origin: &mut TokenOrigin, map: &SourceRelocation) -> Option<()> {
let TokenOrigin { span, invocation } = origin;
*span = map.relocate_span(*span)?;
if let Some(invocation) = invocation {
*invocation = map.relocate_span(*invocation)?;
}
Some(())
}
relocate_fields!(PaintSource { tokens; derivations });
relocate_fields!(NativeRule { span, origin; derivation, width, height, depth });
relocate_fields!(NativeMark { span, tokens; class });
@@ -1,44 +1,42 @@
use super::*;
use crate::execution::source_relocation_events::EventRelocation;
use crate::pdf_device::forms::FormContents;
use std::collections::HashMap;
impl State {
/// Relocate the provenance stored in persistent kernel assignments. A
/// command shard or macro shared by aliases keeps its ownership structure.
pub(in crate::execution) fn relocate_source(
&self,
&mut self,
relocation: &mut EventRelocation<'_>,
) -> Option<Self> {
let mut state = self.clone();
let mut macros = HashMap::new();
) -> Option<()> {
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 self.commands.shards.iter().enumerate() {
for (index, shard) in commands.shards.iter().enumerate() {
for (name, meaning) in shard.iter() {
if let Meaning::Macro(body) = meaning {
let relocated = relocate_macro(body, relocation, &mut macros)?;
let relocated = relocation.relocate_macro(body)?;
if !Arc::ptr_eq(body, &relocated) {
let shard = &mut Arc::make_mut(&mut state.commands).shards[index];
let shard = &mut Arc::make_mut(&mut self.commands).shards[index];
Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated));
}
}
}
}
for tokens in state.toks.values_mut() {
for tokens in self.toks.values_mut() {
relocate_tokens(tokens, relocation)?;
}
for tokens in state
for tokens in self
.token_parameters
.values_mut()
.chain(state.xe_inter_char_tokens.values_mut())
.chain(self.xe_inter_char_tokens.values_mut())
{
*tokens = relocation.relocate_tokens(tokens)?;
}
for value in state.boxes.values_mut() {
for value in self.boxes.values_mut() {
*value = relocation.relocate_box(value)?;
}
for marks in state.page_marks.values_mut() {
for marks in self.page_marks.values_mut() {
for tokens in [&mut marks.top, &mut marks.first, &mut marks.bottom]
.into_iter()
.flatten()
@@ -46,11 +44,11 @@ impl State {
*tokens = relocation.relocate_tokens(tokens)?;
}
}
for marks in state.split_marks.values_mut() {
for marks in self.split_marks.values_mut() {
marks.first = relocation.relocate_tokens(&marks.first)?;
marks.bottom = relocation.relocate_tokens(&marks.bottom)?;
}
for form in state.pdf_forms.values_mut() {
for form in self.pdf_forms.values_mut() {
if let FormContents::Pending(body) = &mut form.contents {
let mut mapped = body.as_ref().clone();
mapped.box_node = relocation.relocate_box(&mapped.box_node)?;
@@ -61,12 +59,12 @@ impl State {
}
}
}
for group in &mut state.groups {
for group in &mut self.groups {
relocate_tokens(&mut group.after, relocation)?;
for saved in group.saved.values_mut() {
match saved {
Saved::Command(Some(Meaning::Macro(body))) => {
*body = relocate_macro(body, relocation, &mut macros)?;
*body = relocation.relocate_macro(body)?;
}
Saved::Tokens(Some(tokens)) => relocate_tokens(tokens, relocation)?,
Saved::Hook(Some(tokens)) | Saved::XeInterCharTokens(Some(tokens)) => {
@@ -94,39 +92,13 @@ impl State {
}
}
}
Some(state)
Some(())
}
}
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
for token in tokens {
*token = relocation.relocate_token(token)?;
relocation.relocate_token(token)?;
}
Some(())
}
pub(in crate::execution) fn relocate_macro(
body: &Arc<Macro>,
relocation: &mut EventRelocation<'_>,
cached: &mut HashMap<*const Macro, Arc<Macro>>,
) -> Option<Arc<Macro>> {
use std::collections::hash_map::Entry;
match cached.entry(Arc::as_ptr(body)) {
Entry::Occupied(entry) => Some(entry.get().clone()),
Entry::Vacant(entry) => {
let mut mapped = None;
for (index, part) in body.replacement.iter().enumerate() {
if let Replacement::Token(token) = part {
let next = relocation.relocate_token(token)?;
if next != *token {
mapped
.get_or_insert_with(|| body.as_ref().clone())
.replacement[index] = Replacement::Token(next);
}
}
}
let mapped = mapped.map_or_else(|| body.clone(), Arc::new);
Some(entry.insert(mapped).clone())
}
}
}
@@ -1,6 +1,6 @@
//! Failed observations are retained without publishing or claiming a checkpoint.
use sha2::{Digest, Sha256};
use std::cell::RefCell;
use std::{cell::RefCell, sync::Arc};
use texrra_tex_core::{execution::*, resources::ResourceTrace};
fn source(name: &str, text: &str) -> SourceFile {
@@ -52,7 +52,7 @@ fn failed_child_macro_keeps_actual_versions_meanings_events_and_state_boundary()
);
assert_eq!(host.messages, ["BEFORE"]);
let e = &failure.evidence;
assert_eq!(e.sources, [main, child]);
assert_eq!(e.sources, [Arc::new(main), Arc::new(child)]);
for (s, v) in e.sources.iter().zip(&e.source_versions) {
assert_eq!(v.sha256, format!("{:x}", Sha256::digest(&s.data)));
assert_eq!(v.bytes, s.data.len() as u64);
@@ -102,7 +102,7 @@ fn cancellation_preserves_observed_progress_but_prestart_does_not_invent_input()
};
let failure = run().run_detailed(main.clone(), &mut host).unwrap_err();
assert!(failure.error.message.contains("cancelled"));
assert_eq!(failure.evidence.sources, [main.clone()]);
assert_eq!(failure.evidence.sources, [Arc::new(main.clone())]);
assert!(failure.evidence.reads.contains(&Dependency::Source(0)));
assert_eq!(host.messages, ["FIRST"]);
let before = run().run_detailed(main, &mut host).unwrap_err();
@@ -145,6 +145,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() {
.start()
.run(executor(), source("old.tex", r"\count0=1\end"), &mut host)
.unwrap();
assert_eq!(previous.execution_resources, Some(host.trace.clone()));
host.armed = true;
let failure = session
.start()
@@ -156,6 +157,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() {
assert_eq!(completed.execution.state.count(0), 2);
assert_eq!(completed.revision, failure.revision);
assert_eq!(failure.resources, Some(host.trace.clone()));
assert_eq!(completed.execution_resources, failure.resources);
assert_eq!(session.latest().unwrap().revision, previous.revision);
assert!(host.pending.borrow().as_ref().unwrap().revision() > completed.revision);
host.pending.borrow_mut().take();
@@ -165,6 +167,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() {
.unwrap_err();
assert!(matches!(interrupted.error, RevisionError::Cancelled));
assert!(interrupted.completed_execution.is_none());
assert_eq!(interrupted.resources, Some(host.trace.clone()));
assert!(
interrupted
.failed_execution