14 changed files with 608 additions and 57 deletions

No files matched your search

+65 -10
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,
@@ -330,10 +331,35 @@ pub struct CheckpointSource<'a> {
/// validated and replayed the previous suffix into this revision's draft.
pub enum CheckpointDecision {
Continue,
/// Move to a validated later command boundary and select captures there.
Advance(Box<EntryCheckpoint>),
Reuse(Box<Execution>),
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.
@@ -372,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)
}
@@ -421,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")
@@ -437,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,
@@ -462,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))
}
@@ -476,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),
@@ -491,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(|_| {
@@ -505,23 +544,29 @@ 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)))
}
}
impl Executor {
fn rebind_checkpoint_source(&mut self, id: usize, file: SourceFile) {
let mouth = self.inputs.iter_mut().rev().find_map(|frame| match frame {
fn source_mouth_mut(&mut self, id: usize) -> &mut Mouth {
self.inputs.iter_mut().rev().find_map(|frame| match frame {
InputFrame::Source { source, mouth, .. } if *source == id => Some(mouth),
_ => None,
}).expect("checkpoint retains the active scanner");
}).expect("checkpoint retains the source scanner")
}
fn rebind_checkpoint_source(&mut self, id: usize, file: SourceFile) {
if self.sources[id].as_ref() != &file {
mouth.rebind_loaded_prefix(file.data.clone());
self.source_mouth_mut(id).rebind_loaded_prefix(file.data.clone());
self.sources[id] = Arc::new(file);
}
}
@@ -561,6 +606,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(),
@@ -3933,7 +3979,7 @@ impl Executor {
mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision {
move |engine, initial_depth, pages_processed, files| {
move |engine, initial_depth, pages_processed, files| loop {
if engine.job_ended {
return CheckpointDecision::Continue;
}
@@ -3986,7 +4032,16 @@ impl Executor {
frontier,
pages_processed,
};
capture(slot, checkpoint, files)
match capture(slot, checkpoint, files) {
CheckpointDecision::Advance(checkpoint) => {
debug_assert!(checkpoint.completed_steps() > engine.steps);
let mut advanced = checkpoint.executor;
advanced.cancellation = engine.cancellation.take();
advanced.line_break_cache = engine.line_break_cache.take();
*engine = advanced;
}
decision => return decision,
}
}
}
fn finish_execution(
@@ -1,7 +1,7 @@
use super::*;
impl InputFrame {
fn same_at_shipout(&self, other: &Self) -> bool {
fn same_continuation(&self, other: &Self, changed_child: Option<usize>) -> bool {
match (self, other) {
(
Self::Source {
@@ -20,7 +20,10 @@ impl InputFrame {
group_boundary: bg,
conditional_boundary: bc,
},
) => (a, ae, at, ag, ac) == (b, be, bt, bg, bc) && am.same_unread_input(bm),
) => {
(a, ae, at, ag, ac) == (b, be, bt, bg, bc)
&& am.same_unread_input(bm, changed_child != Some(*a))
}
(
Self::Tokens {
tokens: a,
@@ -80,6 +83,82 @@ impl InputFrame {
}
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: &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,
checkpoint.incoming_state, checkpoint.pages_processed)
};
if scope(self) != scope(prior)
|| scope(prior) != scope(later)
|| self.pages_processed
|| self.frontier != prior.frontier
|| later.frontier <= prior.frontier
|| later.completed_steps() <= prior.completed_steps()
{
return None;
}
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()
|| current.sources.iter().zip(&old.sources).enumerate()
.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())
{
return None;
}
let mut executor = later.executor.clone();
executor.source_mouth_mut(child).share_loaded_source(self.source_mouth(child));
executor.sources[child] = Arc::clone(source);
executor.deferred_accounting = Some(Arc::new(DeferredAccounting {
current: Arc::clone(self),
basis,
child,
verified: OnceLock::new(),
}));
Some(Self {
executor,
entry: later.entry,
active_source: child,
initial_depth: later.initial_depth,
incoming_state: later.incoming_state,
frontier: later.frontier,
pages_processed: false,
})
}
/// Construct an execution with the current prefix and a previously
/// completed suffix. The host must still validate and replay that suffix.
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
@@ -99,7 +178,7 @@ impl EntryCheckpoint {
}
let current = &self.executor;
let old = &prior.executor;
if !same_kernel_continuation(current, old) {
if !same_kernel_continuation(current, old, None) {
return None;
}
if current.sources.len() != old.sources.len()
@@ -122,7 +201,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) {
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
@@ -155,7 +237,7 @@ impl EntryCheckpoint {
}
}
fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
fn same_kernel_continuation(current: &Executor, prior: &Executor, changed_child: Option<usize>) -> bool {
// Every field belongs to one of these checks. Adding kernel state requires
// an explicit decision here before a later execution may be skipped.
macro_rules! same_values {
@@ -247,13 +329,12 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
output_frame,
alignments,
],
[cancellation, line_break_cache]
[cancellation, line_break_cache, deferred_accounting]
) {
return false;
}
let idle = |e: &Executor| {
e.output_frame.is_none()
&& e.paragraph.is_none()
&& e.box_frames.is_empty()
&& e.math.is_empty()
&& e.display.is_none()
@@ -264,7 +345,12 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
&& e.pdf_images.is_empty()
&& !e.reads_event_history
};
if !idle(current) || !idle(prior) {
if !idle(current) || !idle(prior)
|| match changed_child {
Some(_) => current.paragraph != prior.paragraph,
None => current.paragraph.is_some() || prior.paragraph.is_some(),
}
{
return false;
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
@@ -289,5 +375,5 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
.inputs
.iter()
.zip(&prior.inputs)
.all(|(a, b)| a.same_at_shipout(b))
.all(|(a, b)| a.same_continuation(b, changed_child))
}
@@ -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;
@@ -181,7 +199,7 @@ impl Executor {
}
}
pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool {
pub(super) fn equivalent_accounting_history(&self, old: &Self, rebound: Option<usize>) -> bool {
// These containers may reintroduce previously retained allocations
// that are outside the accounting walk at this boundary.
let fully_visited = |engine: &Self| {
@@ -192,13 +210,33 @@ 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);
Self::collect_event_usage(old.events.iter(), &mut old_history);
let live = self.collect_live_usage(None, None, collector().tracking_aliases());
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
let mut old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
if let Some(child) = rebound {
// This live scanner and source slot are about to hold the
// new bytes. Compare the rest of the ownership and history.
let earlier = old.sources[child].data.len();
let current = self.sources[child].data.len();
old_live.usage.source_payload_bytes =
old_live.usage.source_payload_bytes - earlier + current;
old_live.usage.mouth_payload_bytes =
old_live.usage.mouth_payload_bytes - earlier + current;
}
live.has_equivalent_history(&old_live, &history, &old_history)
})
}
@@ -211,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()
@@ -225,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))?;
@@ -254,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()
@@ -12,7 +12,7 @@ pub(super) struct Component {
pub origin: Span,
pub source: PaintSource,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Glyph {
pub slot: u8,
pub components: Vec<Component>,
@@ -38,7 +38,7 @@ pub(super) struct Carry {
left: bool,
right: bool,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
struct Right {
glyph: Glyph,
raw: bool,
@@ -79,7 +79,7 @@ impl Right {
}
}
}
#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Machine {
started: bool,
left: Option<Glyph>,
+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,
};
@@ -297,7 +297,7 @@ pub(super) struct Mouth {
}
impl Mouth {
pub(super) fn same_unread_input(&self, other: &Self) -> bool {
pub(super) fn same_unread_input(&self, other: &Self, compare_unread: bool) -> bool {
self.source == other.source
&& self.profile == other.profile
&& self.offset == other.offset
@@ -309,7 +309,7 @@ impl Mouth {
&& self.line_number == other.line_number
&& self.xe == other.xe
&& self.invalid_utf8 == other.invalid_utf8
&& self.data[self.offset..] == other.data[other.offset..]
&& (!compare_unread || self.data[self.offset..] == other.data[other.offset..])
}
pub(super) fn physical_frontier(&self) -> Option<usize> {
@@ -350,6 +350,11 @@ impl Mouth {
debug_assert!(self.matches_loaded_prefix(&data));
self.data = Arc::new(data);
}
pub(super) fn share_loaded_source(&mut self, current: &Self) {
debug_assert!(self.matches_loaded_prefix(&current.data));
self.data = Arc::clone(&current.data);
}
pub(super) fn payload_bytes(&self) -> usize {
self.data.len()
}
@@ -123,13 +123,13 @@ pub struct NativeParagraph {
pub hyphen_min: (usize, usize),
pub missing_glyphs: Vec<(FontId, u8, Span)>,
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct XeCharRun {
pub previous: u16,
pub last_ignored: bool,
}
#[derive(Clone, Debug, Default)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Builder {
pub initial_language: HyphenationLanguage,
pub current_language: HyphenationLanguage,
@@ -149,13 +149,13 @@ pub(super) struct Builder {
pub vertical_start: usize,
pub previous_lines: usize,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
struct FontRun {
font: std::sync::Arc<crate::native_font::NativeFont>,
machine: super::ligature::Machine,
hyphen_char: Option<char>,
}
#[derive(Clone, Debug)]
#[derive(Clone, Debug, PartialEq, Eq)]
struct PendingOpenType {
font: Arc<OpenTypeFont>,
text: String,
@@ -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) {
+1 -1
View File
@@ -1041,7 +1041,7 @@ impl CompileJob {
}
let (active_checkpoint, prepared) =
if let Some(available) = checkpoints.and_then(CheckpointCache::current) {
match available.prepare(&request, format_cache, &cancellation, evidence) {
match available.prepare(&request, format_cache, &cancellation, evidence, allow_suffix) {
Ok((selected, prepared)) => (Some(selected), Some(prepared)),
Err(error) => {
check(&cancellation)?;
+63 -5
View File
@@ -9,7 +9,7 @@ use std::{
path::Path,
};
use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint},
execution::{CheckpointDecision, CheckpointReplayError, CheckpointSource, EntryCheckpoint},
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
};
#[cfg(test)]
@@ -51,7 +51,7 @@ struct CachedCheckpoint {
guard: PrefixInputGuard,
replay_count: usize,
slots: Capture,
child_boundary: Option<crate::native_job::ReplayBoundary>,
}
struct CompletedExecution {
@@ -374,6 +374,12 @@ impl<'a> CapturedEntries<'a> {
{
return;
}
let child_boundary = match slots {
Capture::Nested { interval: 0, .. } => guard.nested_source.as_ref()
.filter(|source| source.observed_size.is_some())
.map(|source| host.files().replay_boundary_with_child(Some(&source.path))),
_ => None,
};
self.retain(
slots,
Arc::new(CachedCheckpoint {
@@ -381,6 +387,7 @@ impl<'a> CapturedEntries<'a> {
guard,
replay_count: calls.len(),
slots,
child_boundary,
}),
);
self.changed = true;
@@ -575,6 +582,7 @@ impl PublishedCheckpoints {
cache: &FormatCache,
cancellation: &Cancellation,
evidence: &mut AttemptEvidence,
allow_deferred: bool,
) -> Result<(SelectedCheckpoint, PreparedJob), CompileError> {
let project = request
.project
@@ -590,6 +598,7 @@ impl PublishedCheckpoints {
candidate: ExecutionCandidate::Completed(result.clone()),
}
}))
.filter(|candidate| candidate.can_resume_accounting(allow_deferred))
.collect();
candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.completed_steps()));
let mut candidates = VecDeque::from(candidates);
@@ -678,6 +687,29 @@ impl PublishedCheckpoints {
}
impl CheckpointSet {
fn advance_child(&self, current: &CachedCheckpoint) -> Option<EntryCheckpoint> {
let boundary = current.child_boundary.as_ref()?;
let child = current.guard.nested_source.as_ref()?;
let previous = self.entries.iter().find(|candidate| {
matches!(candidate.slots, Capture::Nested { interval: 0, .. })
&& candidate.entry.frontier() == current.entry.frontier()
&& candidate.replay_count == current.replay_count
&& candidate.child_boundary.as_ref() == Some(boundary)
&& candidate.guard.nested_source.as_ref().is_some_and(|old| {
old.path == child.path && old.observed_size != child.observed_size
})
})?;
self.entries.iter().rev().find_map(|later| {
if !matches!(later.slots, Capture::Nested { interval: 1, .. })
|| later.replay_count != previous.replay_count
|| !later.guard.nested_source.as_ref().is_some_and(|old| old.path == child.path)
{
return None;
}
current.entry.advance_within_child(&previous.entry, &later.entry)
})
}
fn reserve_body(&self) -> Option<Arc<Self>> {
// The reserve holds only recent shipped checkpoints and the host
// call prefix they independently require.
@@ -739,6 +771,14 @@ impl CachedCheckpoint {
}
impl SelectedCheckpoint {
fn can_resume_accounting(&self, allow_deferred: bool) -> bool {
match &self.candidate {
ExecutionCandidate::Boundary(index) =>
self.set.entries[*index].entry.can_resume_accounting(allow_deferred),
ExecutionCandidate::Completed(_) => true,
}
}
fn completed_steps(&self) -> usize {
match &self.candidate {
ExecutionCandidate::Boundary(index) => self.set.entries[*index].entry.completed_steps(),
@@ -886,6 +926,16 @@ impl SelectedCheckpoint {
|slots, entry, host| {
let entry = Arc::new(entry);
captures.capture(slots, entry.clone(), host);
if allow_suffix && let Capture::Nested { file, interval: 0 } = slots
&& let Some(current) = captures.nested[file][0].as_ref()
&& Arc::ptr_eq(&current.entry, &entry)
&& let Some(advanced) = self.set.advance_child(current)
{
let reused = advanced.completed_steps() - entry.completed_steps();
work.reused_steps += reused;
work.reused_suffix_steps += reused;
return CheckpointDecision::Advance(Box::new(advanced));
}
let Capture::Settled { page, .. } = slots else {
return CheckpointDecision::Continue;
};
@@ -916,13 +966,21 @@ impl SelectedCheckpoint {
*suffix_failure = Some((error.clone(), discarded));
return CheckpointDecision::ReplayFailed(error);
}
work.reused_suffix_steps = execution.steps - entry.completed_steps();
work.reused_steps += work.reused_suffix_steps;
let reused = execution.steps - entry.completed_steps();
work.reused_suffix_steps += reused;
work.reused_steps += reused;
work.replayed_calls += calls.len();
CheckpointDecision::Reuse(Box::new(execution))
},
)
.map_err(CompileError::Host)?
.map_err(|error| match error {
CheckpointReplayError::Host(error) => CompileError::Host(error),
CheckpointReplayError::Accounting { steps } => {
let message = "child continuation accounting differs".to_owned();
*suffix_failure = Some((message.clone(), steps.saturating_sub(work.reused_steps)));
CompileError::Host(message)
}
})?
.ok_or_else(changed_prefix)?;
let next = result.as_ref().ok().and_then(|result| {
captures.finish(recording, true, result)
+12
View File
@@ -669,6 +669,10 @@ impl Files {
}
pub(super) fn replay_boundary(&self) -> ReplayBoundary {
self.replay_boundary_with_child(None)
}
pub(super) fn replay_boundary_with_child(&self, rebound: Option<&Path>) -> ReplayBoundary {
let mut trace = self.resource_trace().clone();
trace.project_version = None;
// The caller compared the live scanner bytes and validates later
@@ -676,6 +680,14 @@ impl Files {
if let Some(entry) = trace.reads.first_mut() {
entry.sha256.clear();
}
if let Some(path) = rebound {
// The host actually ran the size queries and opened the rebound
// source. Their old versions are history, not live stream state.
for read in trace.reads.iter_mut().filter(|read| read.path == path) {
read.sha256.clear();
read.bytes = 0;
}
}
let mut stream_events = self.stream_io.events().to_vec();
for event in &mut stream_events {
if let crate::native_stream::StreamEffect::OutputOpened {
+220
View File
@@ -2861,6 +2861,226 @@ fn finished_entry_line_is_reused_after_a_child_size_change() {
fs::remove_dir_all(cwd).unwrap();
}
#[test]
fn child_segments_reuse_only_after_live_state_and_inputs_converge() {
for (label, retain_size, host_call, change_prefix) in [
("converged", false, false, false),
("different-state", true, false, false),
("different-prefix", false, false, true),
("host-effect", false, true, false),
] {
let root = directory(label).canonicalize().unwrap();
let entry = root.join("main.tex");
let child = root.join("child.tex");
let mut world = WorldConfig::new(&root);
world.input_policy = texrra_tex_core::resources::InputPolicy::Tex;
let retain = if retain_size { r"\global\count7=\measured\relax" } else { "" };
let main = format!(
"\\catcode123=1 \\catcode125=2\n\\begingroup\\edef\\measured{{\\pdffilesize{{child.tex}}}}{retain}\n\
\\ifnum\\measured>0 \\relax\\else\\errmessage{{empty child}}\\fi\\endgroup\n\
\\input child.tex\n\
\\shipout\\hbox{{\\vrule width\\the\\numexpr\\count0+\\count7\\relax pt height2pt}}\\end\n"
);
let effect = if host_call { "\\message{child effect}\n" } else { "" };
let middle = "\\advance\\count0 by 1\\relax\n".repeat(160);
let prefix = format!("\\relax{{}}\n{effect}{middle}");
let original = format!("{prefix}\\relax\n");
let prefix = if change_prefix {
prefix.replacen(r"\advance\count0 by 1", r"\advance\count0 by 2", 1)
} else {
prefix
};
let revised = format!("{prefix}\\relax\\advance\\count0 by 2\\relax\n");
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: [root.clone()].into(),
files: [
(entry, Arc::from(main.into_bytes())),
(child.clone(), Arc::from(original.into_bytes())),
]
.into(),
directories: Default::default(),
aliases: Default::default(),
generated_roots: [root.clone()].into(),
generated: Default::default(),
})
.unwrap();
let mut request = CompileRequest::new(
world,
"main.tex",
"job.pdf",
JobTime::new(2026, 11, 29, 0)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
)
.observe_generated_initial();
request.entry = Entry::Initex;
request.etex = true;
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let original = session
.compile(request.clone().with_project(project.clone()))
.unwrap();
let project = project
.with_file_edits(2, [(child, Arc::from(revised.into_bytes()))].into())
.unwrap();
let request = request.with_project(project);
let edited = session.compile(request.clone()).unwrap();
let full = NativeCompiler::default().compile(request).unwrap();
let work = &edited.entry_checkpoint_work;
if label == "converged" {
assert!(work.reused_suffix_steps > 500, "{work:?}");
} else {
assert_eq!(work.reused_suffix_steps, 0, "{label}: {work:?}");
}
assert_ne!(edited.pdf, original.pdf, "{label}");
assert_eq!(edited.pdf, full.pdf, "{label}");
assert_eq!(edited.execution.execution, full.execution.execution, "{label}");
assert_eq!(edited.source_map.pages, full.source_map.pages, "{label}");
assert_eq!(edited.source_map.sources, full.source_map.sources, "{label}");
assert_eq!(edited.resources.trace, full.resources.trace, "{label}");
fs::remove_dir_all(root).unwrap();
}
}
#[test]
fn deferred_child_accounting_revalidates_before_statistics_or_capacity() {
struct PublishedAux {
path: PathBuf,
bytes: Vec<u8>,
checks: AtomicU64,
}
impl CompileObserver for PublishedAux {
fn stage(&self, _revision: u64, stage: CompileStage) -> Result<(), String> {
if matches!(stage, CompileStage::Prepared | CompileStage::Executed) {
assert_eq!(fs::read(&self.path).unwrap(), self.bytes);
self.checks.fetch_add(1, Ordering::Relaxed);
}
Ok(())
}
}
for (label, form, capacity) in [
("verified-statistics", false, false),
("retried-statistics", true, false),
("retried-capacity", true, true),
] {
let root = directory(label).canonicalize().unwrap();
let entry = root.join("main.tex");
let child = root.join("child.tex");
let aux = root.join("child.aux");
let mut world = WorldConfig::new(&root);
world.input_policy = texrra_tex_core::resources::InputPolicy::Tex;
let register_form = if form { r"\setbox0=\hbox{\vrule width2pt height1pt}\pdfxform0\relax" } else { "" };
let form_ref = if form { r"\pdfrefxform\pdflastxform" } else { "" };
let main = format!(
r"\catcode123=1 \catcode125=2
\pdfoutput=1 {register_form}
\def\material{{\setbox1=\hbox{{\vrule width1pt height1pt}}}}
\def\repeatmaterial{{\material\ifnum\count1<300
\advance\count1 by 1\relax\expandafter\repeatmaterial\fi}}
\begingroup\edef\measured{{\pdffilesize{{child.tex}}}}
\ifnum\measured>0 \relax\else\errmessage{{empty child}}\fi\endgroup
\input child.tex
\immediate\openout3=child.aux
\immediate\write3{{\the\count0}}\immediate\closeout3
\shipout\hbox{{{form_ref}\vrule width\count0 pt height2pt}}\end
"
);
let middle = "\\advance\\count0 by 1\\relax\n".repeat(160);
let prefix = format!("\\relax{{}}\n{middle}");
let tail = "\\tracingstats=0\\relax\\ifnum0=1 \\repeatmaterial\\fi\n";
let original = format!("{prefix}{tail}");
let grown = format!("{prefix}{tail}\\advance\\count0 by 2\\relax\n");
let observed = if capacity {
grown.replace("\\ifnum0=1", "\\ifnum1=1")
} else {
grown.replace("\\tracingstats=0", "\\tracingstats=1")
}
.replace("\\count0 by 2", "\\count0 by 3");
assert_eq!(grown.len(), observed.len());
let mut project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: [root.clone()].into(),
files: [
(entry, Arc::from(main.into_bytes())),
(child.clone(), Arc::from(original.into_bytes())),
]
.into(),
directories: Default::default(),
aliases: Default::default(),
generated_roots: [root.clone()].into(),
generated: [aux.clone()].into(),
})
.unwrap();
let mut request = CompileRequest::new(
world,
"main.tex",
"job.pdf",
JobTime::new(2026, 11, 29, 0)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
)
.observe_generated_initial();
request.entry = Entry::Initex;
request.etex = true;
if capacity {
request.limits.tokens = 250;
}
let seed = request.clone().with_project(project.clone());
NativeCompiler::default().compile(seed.clone()).unwrap();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
session.compile(seed).unwrap();
project = project
.with_file_edits(2, [(child.clone(), Arc::from(grown.into_bytes()))].into())
.unwrap();
let grown = session.compile(request.clone().with_project(project.clone())).unwrap();
assert!(grown.entry_checkpoint_work.reused_suffix_steps > 500, "{label}: {:?}", grown.entry_checkpoint_work);
let initial_aux = fs::read(&aux).unwrap();
assert_eq!(initial_aux, b"162\n");
let observer = Arc::new(PublishedAux {
path: aux.clone(),
bytes: initial_aux.clone(),
checks: AtomicU64::new(0),
});
project = project
.with_file_edits(3, [(child.clone(), Arc::from(observed.into_bytes()))].into())
.unwrap();
let request = request.with_project(project);
let mut watched = request.clone();
watched.observer = Some(observer.clone());
let edited = session.compile(watched).unwrap();
let work = &edited.entry_checkpoint_work;
assert_eq!(observer.checks.load(Ordering::Relaxed), 2, "{label}: {work:?}");
if form {
assert_eq!(work.rejection.as_deref(), Some("child continuation accounting differs"), "{work:?}");
assert!(work.discarded_suffix_attempt_steps > 0, "{work:?}");
} else {
assert!(work.rejection.is_none(), "{work:?}");
assert_eq!(work.reused_source.as_deref(), Some(child.as_path()));
assert!(work.reused_frontier.unwrap() > 1000, "{work:?}");
}
let out_aux = fs::read(&aux).unwrap();
assert_eq!(out_aux, b"163\n");
fs::write(&aux, initial_aux).unwrap();
let full = NativeCompiler::default().compile(request).unwrap();
assert_eq!(fs::read(&aux).unwrap(), out_aux);
assert_eq!(edited.pdf, full.pdf, "{label}");
assert_eq!(edited.execution.execution, full.execution.execution, "{label}");
assert_eq!(edited.source_map.pages, full.source_map.pages, "{label}");
assert_eq!(edited.source_map.sources, full.source_map.sources, "{label}");
assert_eq!(edited.resources.trace.reads, full.resources.trace.reads, "{label}");
assert_eq!(edited.resources.trace.lookups, full.resources.trace.lookups, "{label}");
fs::remove_dir_all(root).unwrap();
}
}
#[test]
fn replay_rejection_resumes_earlier_without_publishing_rejected_effects() {
struct PublishedBeforeExecution(Vec<(PathBuf, Vec<u8>)>);