Defer child replay accounting and reuse verified macro aliases

This commit is contained in:
gloamxun committed 2026-11-29 12:06:32 +08:00
1 parent 64adf51b20
commit d98d7b44c1
10 files changed
+364 -33

No files matched your search

+44 -4
View File
@@ -1,6 +1,6 @@
use std::collections::{BTreeSet, VecDeque};
use std::hash::{BuildHasher, RandomState};
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use hashbrown::{HashMap, hash_map::RawEntryMut};
@@ -249,6 +249,7 @@ pub struct Executor {
reads_event_history: bool,
// Capacity recounts and tracing use the resource accounting traversal.
accounts_event_history: bool,
deferred_accounting: Option<Arc<DeferredAccounting>>,
steps: usize,
ligature_carry: super::ligature::Carry,
current: Span,
@@ -336,6 +337,29 @@ pub enum CheckpointDecision {
ReplayFailed(String),
}
#[derive(Debug)]
pub enum CheckpointReplayError {
Host(String),
Accounting { steps: usize },
}
struct DeferredAccounting {
current: Arc<EntryCheckpoint>,
basis: Arc<EntryCheckpoint>,
child: usize,
verified: OnceLock<bool>,
}
impl DeferredAccounting {
fn verify(&self) -> bool {
*self.verified.get_or_init(|| {
self.current.executor.equivalent_accounting_history(
&self.basis.executor, Some(self.child),
)
})
}
}
/// A live, in-memory kernel continuation at an entry-file command boundary.
/// The host must validate dependencies and replay all prefix effects before
/// resumption. The checkpoint itself validates the entry bytes already loaded.
@@ -374,6 +398,12 @@ impl EntryCheckpoint {
== earlier.executor.sources[earlier.entry].data.len()))
}
pub fn can_resume_accounting(&self, allow_deferred: bool) -> bool {
self.executor.deferred_accounting.as_ref().is_none_or(|proof| {
proof.verified.get().copied().unwrap_or(allow_deferred)
})
}
pub fn accepts_entry(&self, source: &SourceFile) -> bool {
self.accepts_entry_bytes(&source.name, &source.data)
}
@@ -423,6 +453,9 @@ impl EntryCheckpoint {
files: &mut impl SourceProvider,
cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> {
if !self.can_resume_accounting(false) {
return None;
}
self.resume_observed(source, None, files, cancellation, None, None,
|_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix")
@@ -439,6 +472,9 @@ impl EntryCheckpoint {
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Option<Result<Execution, ExecutionFailure>> {
if !self.can_resume_accounting(false) {
return None;
}
self.resume_observed(
source,
nested,
@@ -464,7 +500,7 @@ impl EntryCheckpoint {
previous: Option<&Execution>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
) -> Result<Option<Result<Execution, ExecutionFailure>>, CheckpointReplayError> {
self.resume_observed(source, nested, files, cancellation, Some(line_break_cache), previous,
Executor::entry_observer(self.incoming_state, select, capture))
}
@@ -478,7 +514,7 @@ impl EntryCheckpoint {
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>,
capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
) -> Result<Option<Result<Execution, ExecutionFailure>>, CheckpointReplayError> {
if !self.accepts_entry(&source)
|| match &nested {
Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data),
@@ -493,6 +529,7 @@ impl EntryCheckpoint {
if let Some(nested) = nested {
executor.rebind_checkpoint_source(self.active_source, nested);
}
executor.check_accounting_replay()?;
let result = executor
.check_cancellation()
.and_then(|_| {
@@ -507,12 +544,14 @@ impl EntryCheckpoint {
Ok(CheckpointDecision::Reuse(execution)) => {
return Ok(Some(Ok(*execution)));
}
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error),
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(CheckpointReplayError::Host(error)),
Ok(CheckpointDecision::Continue) => Ok(()),
Ok(CheckpointDecision::Advance(_)) => unreachable!("entry observer applies advances"),
Err(error) => Err(error),
};
executor.check_accounting_replay()?;
let result = executor.finish_observed_input(result, files);
executor.check_accounting_replay()?;
Ok(Some(executor.finish_execution(result, self.incoming_state, previous)))
}
}
@@ -564,6 +603,7 @@ impl Executor {
events: ExecutionEvents::default(),
reads_event_history: false,
accounts_event_history: false,
deferred_accounting: None,
steps: 0,
ligature_carry: super::ligature::Carry::default(),
current: Span::default(),
@@ -86,7 +86,7 @@ impl EntryCheckpoint {
/// Move through commands already executed on unchanged loaded child bytes.
/// The host must prove that the earlier host states agree and that the
/// skipped interval contains no host calls. The current source stays bound.
pub fn advance_within_child(&self, prior: &Self, later: &Self) -> Option<Self> {
pub fn advance_within_child(self: &Arc<Self>, prior: &Arc<Self>, later: &Self) -> Option<Self> {
let child = self.nested_source_id()?;
let scope = |checkpoint: &Self| {
(checkpoint.entry, checkpoint.active_source, checkpoint.initial_depth,
@@ -104,6 +104,29 @@ impl EntryCheckpoint {
let current = &self.executor;
let old = &prior.executor;
let source = &current.sources[child];
if current.deferred_accounting.is_some() || old.deferred_accounting.is_some()
|| later.executor.accounts_event_history
{
return None;
}
let basis = match &later.executor.deferred_accounting {
None => Arc::clone(prior),
Some(proof) if proof.verified.get() == Some(&true) => Arc::clone(prior),
// Reusing the child again retains the original accounting basis.
// The two early snapshots held by a proof never hold other proofs.
Some(proof) if proof.verified.get().is_none() && Arc::ptr_eq(&proof.current, prior) => {
Arc::clone(&proof.basis)
}
_ => return None,
};
let input_macros = current.inputs.iter().zip(&old.inputs).filter_map(|(current, old)| {
match (current, old) {
(InputFrame::Macro { definition: current, .. }, InputFrame::Macro { definition: old, .. }) => {
Some((current, old))
}
_ => None,
}
});
if later.executor.sources != old.sources
|| later.executor.shipped_pages != old.shipped_pages
|| current.sources.len() != old.sources.len()
@@ -111,13 +134,19 @@ impl EntryCheckpoint {
.any(|(id, (a, b))| id != child && a != b)
|| !later.accepts_nested_source(&source.name, &source.data)
|| !same_kernel_continuation(current, old, Some(child))
|| !current.state.same_macro_aliases(&old.state, input_macros)
|| !current.events.iter().eq(old.events.iter())
|| !current.equivalent_accounting_history(old, Some(child))
{
return None;
}
let mut executor = later.executor.clone();
executor.rebind_checkpoint_source(child, (**source).clone());
executor.deferred_accounting = Some(Arc::new(DeferredAccounting {
current: Arc::clone(self),
basis,
child,
verified: OnceLock::new(),
}));
Some(Self {
executor,
entry: later.entry,
@@ -171,7 +200,10 @@ impl EntryCheckpoint {
let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone();
let tail = completed.events.get(old.events.len()..)?;
if completed.accounts_event_history && !current.equivalent_accounting_history(old, None) {
if completed.accounts_event_history
&& (!self.can_resume_accounting(false)
|| !current.equivalent_accounting_history(old, None))
{
return None;
}
// The joined events are published results. Resumption always starts
@@ -296,7 +328,7 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor, changed_child:
output_frame,
alignments,
],
[cancellation, line_break_cache]
[cancellation, line_break_cache, deferred_accounting]
) {
return false;
}
@@ -19,10 +19,28 @@ impl Executor {
self.stack_peaks.include(&self.stack_usage());
}
fn verify_accounting(&mut self) -> Result<(), Error> {
if let Some(proof) = &self.deferred_accounting {
if !proof.verify() {
return self.fail("child continuation accounting differs");
}
self.deferred_accounting = None;
}
Ok(())
}
pub(super) fn check_accounting_replay(&self) -> Result<(), CheckpointReplayError> {
if self.deferred_accounting.as_ref().is_some_and(|proof| proof.verified.get() == Some(&false)) {
return Err(CheckpointReplayError::Accounting { steps: self.steps });
}
Ok(())
}
pub(super) fn check_box_capacity(&mut self, shipping: Option<&NativeBox>) -> Result<(), Error> {
if self.material_charge <= self.limits.tokens {
return Ok(());
}
self.verify_accounting()?;
// Packing can move existing lists or replace an old register. Recount
// actual storage here, counting each shared list allocation once.
self.accounts_event_history = true;
@@ -192,7 +210,17 @@ impl Executor {
return false;
}
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
[Collector::for_capacity, Collector::default].into_iter().all(|new_collector| {
let collector = || {
let c = new_collector();
if rebound.is_some() {
// Child convergence already proved the live and saved
// macro identity relation, including active input frames.
c.with_verified_macro_aliases()
} else {
c
}
};
let mut history = collector();
let mut old_history = collector();
Self::collect_event_usage(self.events.iter(), &mut history);
@@ -221,6 +249,7 @@ impl Executor {
if self.read_parameter(Parameter::Tracingstats).width() <= 1 {
return Ok(None);
}
self.verify_accounting()?;
self.reads.insert(Dependency::ResourceStatistics);
let host = files
.resource_usage()
@@ -235,6 +264,7 @@ impl Executor {
let Some(before) = before else {
return Ok(());
};
self.verify_accounting()?;
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
@@ -264,6 +294,7 @@ impl Executor {
if self.read_parameter(Parameter::Tracingstats).width() <= 0 {
return Ok(());
}
self.verify_accounting()?;
self.reads.insert(Dependency::ResourceStatistics);
let host = files
.resource_usage()
+1 -1
View File
@@ -68,7 +68,7 @@ pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits};
pub use engine::{CheckpointDecision, CheckpointReplayError, CheckpointSource, EntryCheckpoint, Executor, Limits};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
};
@@ -305,7 +305,7 @@ impl RevisionJob {
line_break_cache: Arc<LineBreakCache>,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, super::CheckpointReplayError> {
let previous = self.session.latest();
let executed = checkpoint.resume_deciding_suffix(
source, nested, files, self.cancellation.clone(), line_break_cache,
+79 -18
View File
@@ -1536,6 +1536,65 @@ impl Default for State {
}
impl State {
// Called after value equality. e-TeX can also observe whether two live
// or restorable bindings share one macro, even with tracingstats disabled.
pub(super) fn same_macro_aliases<'a>(
&self,
other: &Self,
input_macros: impl Iterator<Item = (&'a Arc<Macro>, &'a Arc<Macro>)>,
) -> bool {
let mut forward = std::collections::HashMap::new();
let mut reverse = std::collections::HashMap::new();
let mut fixed = Vec::new();
let mut match_alias = |current: &Arc<Macro>, old: &Arc<Macro>| {
let current = Arc::as_ptr(current);
let old = Arc::as_ptr(old);
if current == old {
fixed.push(current);
return true;
}
*forward.entry(current).or_insert(old) == old
&& *reverse.entry(old).or_insert(current) == current
};
for (current, old) in self.commands.shards.iter().zip(&other.commands.shards) {
if Arc::ptr_eq(current, old) {
continue;
}
for (name, meaning) in current.iter() {
let Meaning::Macro(current) = meaning else { continue; };
let Some(Meaning::Macro(old)) = old.get(name) else { return false; };
if !match_alias(current, old) {
return false;
}
}
}
for (current, old) in self.groups.iter().zip(&other.groups) {
for (current, old) in current.saved.values().zip(old.saved.values()) {
if let (Saved::Command(Some(Meaning::Macro(current))),
Saved::Command(Some(Meaning::Macro(old)))) = (current, old)
&& !match_alias(current, old)
{
return false;
}
}
}
if !input_macros.into_iter().all(|(current, old)| match_alias(current, old)) {
return false;
}
if forward.is_empty() {
return true;
}
let is_fixed = |p| !forward.contains_key(&p) && !reverse.contains_key(&p);
fixed.into_iter().all(is_fixed)
&& self.commands.shards.iter().zip(&other.commands.shards)
.filter(|(current, old)| Arc::ptr_eq(current, old))
.flat_map(|(shard, _)| shard.values())
.all(|meaning| match meaning {
Meaning::Macro(body) => is_fixed(Arc::as_ptr(body)),
_ => true,
})
}
pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) {
use super::statistics::Ownership::Active;
for b in self.boxes.values() {
@@ -1549,24 +1608,26 @@ impl State {
}
return;
}
c.usage.state.command_entries = self.commands.len();
let track_aliases = c.tracks_aliases();
let mut visit_command = |name: &CommandName, meaning: &Meaning| {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
};
if track_aliases {
for (name, meaning) in self.commands.ordered() {
visit_command(name, meaning);
}
} else {
for (name, meaning) in self.commands.iter() {
visit_command(name, meaning);
if !c.macro_aliases_verified() {
c.usage.state.command_entries = self.commands.len();
let track_aliases = c.tracks_aliases();
let mut visit_command = |name: &CommandName, meaning: &Meaning| {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
};
if track_aliases {
for (name, meaning) in self.commands.ordered() {
visit_command(name, meaning);
}
} else {
for (name, meaning) in self.commands.iter() {
visit_command(name, meaning);
}
}
}
c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len();
@@ -178,6 +178,7 @@ pub(super) struct Collector {
token_lists: BTreeSet<(usize, usize)>,
shared_lists: Option<BTreeSet<usize>>,
aliases: Option<AliasVisits>,
verified_macro_aliases: bool,
}
impl Collector {
pub fn for_capacity() -> Self {
@@ -192,6 +193,15 @@ impl Collector {
self
}
pub(super) fn with_verified_macro_aliases(mut self) -> Self {
self.verified_macro_aliases = true;
self
}
pub(super) fn macro_aliases_verified(&self) -> bool {
self.verified_macro_aliases
}
pub(super) fn tracks_aliases(&self) -> bool {
self.aliases.is_some()
}
@@ -239,6 +249,9 @@ impl Collector {
}
pub fn macro_body(&mut self, m: &Arc<Macro>) {
if self.verified_macro_aliases {
return;
}
let address = Arc::as_ptr(m) as usize;
self.tracks_allocation(Allocation::Macro(address));
if self.macros.insert(address) {