Reuse verified native suffixes after settled output routines

This commit is contained in:
gloamxun committed 2026-11-29 07:51:37 +08:00
1 parent f387b1db61
commit 0117449023
30 files changed
+791 -77

No files matched your search

@@ -487,7 +487,7 @@ impl NativeBox {
} }
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct VerticalBuilder { pub(super) struct VerticalBuilder {
pub nodes: Vec<NativeVerticalNode>, pub nodes: Vec<NativeVerticalNode>,
pub prev_depth: i32, pub prev_depth: i32,
@@ -2,7 +2,7 @@
use super::Dependency; use super::Dependency;
use std::collections::{BTreeSet, HashSet}; use std::collections::{BTreeSet, HashSet};
#[derive(Clone, Default)] #[derive(Clone, Default, PartialEq, Eq)]
pub(super) struct DependencyReads { pub(super) struct DependencyReads {
byte_catcodes: [u64; 4], byte_catcodes: [u64; 4],
other: HashSet<Dependency>, other: HashSet<Dependency>,
+85 -29
View File
@@ -39,6 +39,7 @@ mod scanning;
mod scheduling; mod scheduling;
mod specials; mod specials;
mod statistics; mod statistics;
mod continuation;
mod xdv_annotation; mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -57,7 +58,7 @@ impl Default for Limits {
} }
} }
#[derive(Clone)] #[derive(Clone, PartialEq, Eq)]
struct InputToken { struct InputToken {
token: Token, token: Token,
frozen: bool, frozen: bool,
@@ -131,7 +132,7 @@ enum InputFrame {
}, },
Boundary, Boundary,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy, PartialEq, Eq)]
enum TokenInputKind { enum TokenInputKind {
Inserted, Inserted,
BackedUp, BackedUp,
@@ -144,7 +145,7 @@ enum TheValue {
Tokens(Vec<Token>), Tokens(Vec<Token>),
Text(std::string::String), Text(std::string::String),
} }
#[derive(Clone)] #[derive(Clone, PartialEq, Eq)]
struct Conditional { struct Conditional {
primitive: Primitive, primitive: Primitive,
inverted: bool, inverted: bool,
@@ -241,6 +242,8 @@ pub struct Executor {
in_csname: bool, in_csname: bool,
command_trace_mode: Option<&'static str>, command_trace_mode: Option<&'static str>,
events: ExecutionEvents, events: ExecutionEvents,
// Set before operations that inspect earlier events beyond their count.
reads_event_history: bool,
steps: usize, steps: usize,
ligature_carry: super::ligature::Carry, ligature_carry: super::ligature::Carry,
current: Span, current: Span,
@@ -314,6 +317,15 @@ pub struct CheckpointSource<'a> {
pub bytes: usize, pub bytes: usize,
pub frontier: usize, pub frontier: usize,
pub is_entry: bool, pub is_entry: bool,
pub output_returned: bool,
}
/// Called only at a selected boundary. Reuse requires that the caller has
/// validated and replayed the previous suffix into this revision's draft.
pub enum CheckpointDecision {
Continue,
Reuse(Box<Execution>),
ReplayFailed(String),
} }
/// A live, in-memory kernel continuation at an entry-file command boundary. /// A live, in-memory kernel continuation at an entry-file command boundary.
@@ -387,7 +399,9 @@ impl EntryCheckpoint {
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
cancellation: Cancellation, cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> { ) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed(source, None, files, cancellation, None, None, |_, _, _, _| {}) self.resume_observed(source, None, files, cancellation, None, None,
|_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix")
} }
pub(super) fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>( pub(super) fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>(
@@ -399,7 +413,7 @@ impl EntryCheckpoint {
line_break_cache: std::sync::Arc<super::LineBreakCache>, line_break_cache: std::sync::Arc<super::LineBreakCache>,
previous: Option<&Execution>, previous: Option<&Execution>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>, select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F), mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Option<Result<Execution, ExecutionFailure>> { ) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed( self.resume_observed(
source, source,
@@ -408,8 +422,27 @@ impl EntryCheckpoint {
cancellation, cancellation,
Some(line_break_cache), Some(line_break_cache),
previous, previous,
Executor::entry_observer(self.incoming_state, select, capture), Executor::entry_observer(self.incoming_state, select, |slot, entry, files| {
capture(slot, entry, files);
CheckpointDecision::Continue
}),
) )
.expect("ordinary resume cannot reject a cached suffix")
}
pub(super) fn resume_deciding_suffix<F: SourceProvider, S>(
&self,
source: SourceFile,
nested: Option<SourceFile>,
files: &mut F,
cancellation: Cancellation,
line_break_cache: Arc<super::LineBreakCache>,
previous: Option<&Execution>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
self.resume_observed(source, nested, files, cancellation, Some(line_break_cache), previous,
Executor::entry_observer(self.incoming_state, select, capture))
} }
fn resume_observed<F: SourceProvider>( fn resume_observed<F: SourceProvider>(
@@ -420,15 +453,15 @@ impl EntryCheckpoint {
cancellation: Cancellation, cancellation: Cancellation,
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>, line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>, previous: Option<&Execution>,
capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F), capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision,
) -> Option<Result<Execution, ExecutionFailure>> { ) -> Result<Option<Result<Execution, ExecutionFailure>>, String> {
if !self.accepts_entry(&source) if !self.accepts_entry(&source)
|| match &nested { || match &nested {
Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data), Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data),
None => self.nested_source().is_some(), None => self.nested_source().is_some(),
} }
{ {
return None; return Ok(None);
} }
let mut executor = self.executor.clone().with_cancellation(cancellation); let mut executor = self.executor.clone().with_cancellation(cancellation);
executor.line_break_cache = line_break_cache; executor.line_break_cache = line_break_cache;
@@ -446,8 +479,16 @@ impl EntryCheckpoint {
capture_boundary, capture_boundary,
) )
}); });
let result = match result {
Ok(CheckpointDecision::Reuse(execution)) => {
return Ok(Some(Ok(*execution)));
}
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error),
Ok(CheckpointDecision::Continue) => Ok(()),
Err(error) => Err(error),
};
let result = executor.finish_observed_input(result, files); let result = executor.finish_observed_input(result, files);
Some(executor.finish_execution(result, self.incoming_state, previous)) Ok(Some(executor.finish_execution(result, self.incoming_state, previous)))
} }
} }
@@ -496,6 +537,7 @@ impl Executor {
in_csname: false, in_csname: false,
command_trace_mode: None, command_trace_mode: None,
events: ExecutionEvents::default(), events: ExecutionEvents::default(),
reads_event_history: false,
steps: 0, steps: 0,
ligature_carry: super::ligature::Carry::default(), ligature_carry: super::ligature::Carry::default(),
current: Span::default(), current: Span::default(),
@@ -3491,6 +3533,7 @@ impl Executor {
reads, reads,
events: self.events.into_vec(), events: self.events.into_vec(),
steps: self.steps, steps: self.steps,
reads_event_history: self.reads_event_history,
}) })
} }
fn check_input_character(&self, code: i32) -> Result<(), Error> { fn check_input_character(&self, code: i32) -> Result<(), Error> {
@@ -3785,7 +3828,7 @@ impl Executor {
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
) -> Result<Execution, ExecutionFailure> { ) -> Result<Execution, ExecutionFailure> {
let incoming_state = self.state.fingerprint(); let incoming_state = self.state.fingerprint();
let result = self.run_observed(file, files, |_, _, _, _| {}); let result = self.run_observed(file, files, |_, _, _, _| CheckpointDecision::Continue);
self.finish_execution(result, incoming_state, None) self.finish_execution(result, incoming_state, None)
} }
/// Capture the first eligible entry command boundary at or beyond the /// Capture the first eligible entry command boundary at or beyond the
@@ -3841,13 +3884,16 @@ impl Executor {
file: SourceFile, file: SourceFile,
files: &mut F, files: &mut F,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>, select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F), mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Result<Execution, ExecutionFailure> { ) -> Result<Execution, ExecutionFailure> {
let incoming_state = self.state.fingerprint(); let incoming_state = self.state.fingerprint();
let result = self.run_observed( let result = self.run_observed(
file, file,
files, files,
Self::entry_observer(incoming_state, select, capture), Self::entry_observer(incoming_state, select, |slot, entry, files| {
capture(slot, entry, files);
CheckpointDecision::Continue
}),
); );
self.finish_execution(result, incoming_state, None) self.finish_execution(result, incoming_state, None)
} }
@@ -3855,17 +3901,17 @@ impl Executor {
fn entry_observer<F: SourceProvider, S>( fn entry_observer<F: SourceProvider, S>(
incoming_state: u64, incoming_state: u64,
mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>, mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F), mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> impl FnMut(&mut Self, usize, bool, &mut F) { ) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision {
move |engine, initial_depth, pages_processed, files| { move |engine, initial_depth, pages_processed, files| {
if engine.job_ended { if engine.job_ended {
return; return CheckpointDecision::Continue;
} }
let Some(InputFrame::Source { let Some(InputFrame::Source {
source: entry, eof_seen: false, pseudo_trace: None, .. source: entry, eof_seen: false, pseudo_trace: None, ..
}) = engine.inputs.first() }) = engine.inputs.first()
else { else {
return; return CheckpointDecision::Continue;
}; };
// Retain the active scanner plus its suspended parents. A pseudo // Retain the active scanner plus its suspended parents. A pseudo
// input or an EOF hook has no replaceable physical byte prefix. // input or an EOF hook has no replaceable physical byte prefix.
@@ -3873,10 +3919,10 @@ impl Executor {
source, mouth, eof_seen: false, pseudo_trace: None, .. source, mouth, eof_seen: false, pseudo_trace: None, ..
}) = engine.inputs.iter().rev().find(|frame| matches!(frame, InputFrame::Source { .. })) }) = engine.inputs.iter().rev().find(|frame| matches!(frame, InputFrame::Source { .. }))
else { else {
return; return CheckpointDecision::Continue;
}; };
let Some(frontier) = mouth.physical_frontier() else { let Some(frontier) = mouth.physical_frontier() else {
return; return CheckpointDecision::Continue;
}; };
let (entry, active_source) = (*entry, *source); let (entry, active_source) = (*entry, *source);
let file = &engine.sources[active_source]; let file = &engine.sources[active_source];
@@ -3886,14 +3932,15 @@ impl Executor {
bytes: file.data.len(), bytes: file.data.len(),
frontier, frontier,
is_entry: active_source == entry, is_entry: active_source == entry,
output_returned: engine.output_frame.is_none(),
}; };
let Some(slot) = select(position, engine.shipped_pages) else { let Some(slot) = select(position, engine.shipped_pages) else {
return; return CheckpointDecision::Continue;
}; };
if engine.sources.iter().enumerate().any(|(index, other)| { if engine.sources.iter().enumerate().any(|(index, other)| {
index != active_source && other.name == file.name index != active_source && other.name == file.name
}) { }) {
return; return CheckpointDecision::Continue;
} }
engine.events.seal_prefix(); engine.events.seal_prefix();
let mut executor = engine.clone(); let mut executor = engine.clone();
@@ -3908,7 +3955,7 @@ impl Executor {
frontier, frontier,
pages_processed, pages_processed,
}; };
capture(slot, checkpoint, files); capture(slot, checkpoint, files)
} }
} }
fn finish_execution( fn finish_execution(
@@ -3989,19 +4036,22 @@ impl Executor {
reads, reads,
incoming_state, incoming_state,
steps: self.steps, steps: self.steps,
reads_event_history: self.reads_event_history,
}) })
} }
fn run_observed<F: SourceProvider>( fn run_observed<F: SourceProvider>(
&mut self, &mut self,
file: SourceFile, file: SourceFile,
files: &mut F, files: &mut F,
capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F), capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<(), Error> { ) -> Result<(), Error> {
self.check_cancellation()?; self.check_cancellation()?;
self.change_interaction_mode(self.interaction_mode, files)?; self.change_interaction_mode(self.interaction_mode, files)?;
let result = self.prepare_input(file, files).and_then(|initial_depth| { let result = self.prepare_input(file, files).and_then(|initial_depth| {
self.emit_format_image_warnings(files)?; self.emit_format_image_warnings(files)?;
self.run_active_input(initial_depth, false, files, capture_boundary) self.run_active_input(initial_depth, false, files, capture_boundary).map(|action| {
debug_assert!(matches!(action, CheckpointDecision::Continue));
})
}); });
self.finish_observed_input(result, files) self.finish_observed_input(result, files)
} }
@@ -4116,20 +4166,26 @@ impl Executor {
initial_depth: usize, initial_depth: usize,
mut pages_processed: bool, mut pages_processed: bool,
files: &mut F, files: &mut F,
mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F), mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<(), Error> { ) -> Result<CheckpointDecision, Error> {
let xe = self.state.input_profile() == InputProfile::XeTeX; let xe = self.state.input_profile() == InputProfile::XeTeX;
loop { loop {
if !std::mem::take(&mut pages_processed) { if !std::mem::take(&mut pages_processed) {
self.check_box_capacity(None)?; self.check_box_capacity(None)?;
capture_boundary(self, initial_depth, false, files); match capture_boundary(self, initial_depth, false, files) {
CheckpointDecision::Continue => {}
decision => return Ok(decision),
}
let shipped_pages = self.shipped_pages; let shipped_pages = self.shipped_pages;
self.process_native_pages(files)?; self.process_native_pages(files)?;
self.check_box_capacity(None)?; self.check_box_capacity(None)?;
if self.shipped_pages != shipped_pages { if self.shipped_pages != shipped_pages {
// A following expandable command can read an input before // A following expandable command can read an input before
// the next main-loop iteration. // the next main-loop iteration.
capture_boundary(self, initial_depth, true, files); match capture_boundary(self, initial_depth, true, files) {
CheckpointDecision::Continue => {}
decision => return Ok(decision),
}
} }
} }
let Some((input, meaning)) = self.expanded_with_meaning(files, false)? else { let Some((input, meaning)) = self.expanded_with_meaning(files, false)? else {
@@ -4611,7 +4667,7 @@ impl Executor {
} }
} }
} }
Ok(()) Ok(CheckpointDecision::Continue)
} }
fn assignment( fn assignment(
&mut self, &mut self,
@@ -4,7 +4,7 @@
use super::super::boxes::{self, PackSpec, VerticalBuilder}; use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*; use super::*;
#[derive(Clone, Copy)] #[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Boundary { pub(super) enum Boundary {
Prefix, Prefix,
Entry, Entry,
@@ -0,0 +1,286 @@
use super::*;
impl InputFrame {
fn same_at_shipout(&self, other: &Self) -> bool {
match (self, other) {
(
Self::Source {
source: a,
mouth: am,
eof_seen: ae,
pseudo_trace: at,
group_boundary: ag,
conditional_boundary: ac,
},
Self::Source {
source: b,
mouth: bm,
eof_seen: be,
pseudo_trace: bt,
group_boundary: bg,
conditional_boundary: bc,
},
) => (a, ae, at, ag, ac) == (b, be, bt, bg, bc) && am.same_unread_input(bm),
(
Self::Tokens {
tokens: a,
cursor: ac,
kind: ak,
},
Self::Tokens {
tokens: b,
cursor: bc,
kind: bk,
},
) => (ac, ak) == (bc, bk) && a.iter().eq(b.iter()),
(
Self::Macro {
definition: a,
name: an,
cursor: ac,
arguments: aa,
call: aspan,
},
Self::Macro {
definition: b,
name: bn,
cursor: bc,
arguments: ba,
call: bspan,
},
) => (a, an, ac, aa, aspan) == (b, bn, bc, ba, bspan),
(
Self::Argument {
tokens: a,
cursor: ac,
call: aspan,
},
Self::Argument {
tokens: b,
cursor: bc,
call: bspan,
},
) => (a, ac, aspan) == (b, bc, bspan),
(
Self::Hook {
parameter: a,
tokens: at,
cursor: ac,
},
Self::Hook {
parameter: b,
tokens: bt,
cursor: bc,
},
) => (a, at, ac) == (b, bt, bc),
(Self::Boundary, Self::Boundary) => true,
_ => false,
}
}
}
impl EntryCheckpoint {
/// 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> {
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
|| self.initial_depth != prior.initial_depth
|| self.incoming_state != prior.incoming_state
|| self.frontier != prior.frontier
|| self.pages_processed != prior.pages_processed
|| completed.incoming_state != prior.incoming_state
|| completed.reads_event_history
|| completed.format_dumped
|| completed.steps <= prior.completed_steps()
{
return None;
}
let current = &self.executor;
let old = &prior.executor;
if !same_kernel_continuation(current, old) {
return None;
}
if current.sources.len() != old.sources.len()
|| current
.sources
.iter()
.zip(&old.sources)
.enumerate()
.any(|(id, (new, old))| {
if id == self.entry {
new.name != old.name || new.data.len() != old.data.len()
} else {
new != old
}
})
|| completed.sources.get(self.entry)? != &old.sources[self.entry]
{
return None;
}
let mut sources = completed.sources.clone();
sources[self.entry] = current.sources[self.entry].clone();
let tail = completed.events.get(old.events.len()..)?;
let mut events = current.events.clone().into_vec();
events.extend_from_slice(tail);
Some(Execution {
format_dumped: completed.format_dumped,
format_pdf_images: completed.format_pdf_images.clone(),
job_name: completed.job_name.clone(),
interaction_mode: completed.interaction_mode,
native_page: completed.native_page.clone(),
split_discards: completed.split_discards.clone(),
after_assignment: completed.after_assignment.clone(),
events,
state: completed.state.clone(),
io: completed.io.clone(),
input_position: completed.input_position,
paragraph_mode: completed.paragraph_mode,
sources,
stream_sources: completed.stream_sources.clone(),
generated_inputs: completed.generated_inputs.clone(),
reads: completed.reads.clone(),
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
steps: completed.steps,
reads_event_history: false,
})
}
}
fn same_kernel_continuation(current: &Executor, prior: &Executor) -> 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 {
([$($value:ident),+ $(,)?], [$($planned:ident),+ $(,)?], [$($runtime:ident),+ $(,)?]) => {{
let Executor {
$($value,)+
$($planned: _,)+
$($runtime: _,)+
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: _,
} = current;
true $(&& *$value == prior.$value)+
}};
}
if !same_values!(
[
state,
limits,
interaction_mode,
stream_sources,
generated_inputs,
reads,
reads_tracing_macros,
conditionals,
in_csname,
command_trace_mode,
steps,
ligature_carry,
current,
expression_depth,
scanner_depth,
scanner_status,
expansion_depth,
io,
pdf_colors,
xdv_colors,
pdf_running_links,
pdf_interword_spaces,
pdf_space_font,
pdf_loaded_space_font,
pdf_virtual_fonts,
pdf_catalog_tokens,
pdf_outlines,
pdf_outline_payload,
pdf_info_tokens,
restored_pdf_image_count,
format_image_warnings,
pdf_force_pagebox_warned,
input_position,
vertical,
box_nodes_created,
material_charge,
mark_cells_created,
diagnostic_bytes,
after_assignment,
after_group_tokens,
math_tokens_processed,
native_page,
split_discards,
pending_shipouts,
shipped_pages,
job_ended,
fresh_job,
job_name,
format_loaded,
format_dumped,
writing,
stack_peaks,
alignment_balance,
],
[
inputs,
sources,
meaning_reads,
events,
reads_event_history,
xdv_annotations,
xdv_text,
pdf_navigation_geometry,
pdf_link_stack,
pdf_active_thread,
pdf_space_probe,
pdf_images,
paragraph,
box_frames,
math,
display,
output_frame,
alignments,
],
[cancellation, line_break_cache]
) {
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()
&& e.alignments.is_empty()
&& e.pdf_link_stack.is_empty()
&& e.pdf_active_thread.is_none()
&& e.pdf_space_probe.is_none()
&& e.pdf_images.is_empty()
&& !e.reads_event_history
};
if !idle(current) || !idle(prior) {
return false;
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() {
return false;
}
current
.xdv_annotations
.same_idle_state(&prior.xdv_annotations)
&& current.xdv_text.same_state(&prior.xdv_text)
&& current
.pdf_navigation_geometry
.same_state(&prior.pdf_navigation_geometry)
&& current.events.len() == prior.events.len()
&& current.meaning_reads.len() == prior.meaning_reads.len()
&& current
.meaning_reads
.keys()
.all(|name| prior.meaning_reads.contains_key(name))
&& current.inputs.len() == prior.inputs.len()
&& current
.inputs
.iter()
.zip(&prior.inputs)
.all(|(a, b)| a.same_at_shipout(b))
}
@@ -1089,6 +1089,7 @@ impl Executor {
.map_err(|e| self.error(e, self.current))?; .map_err(|e| self.error(e, self.current))?;
let mut shared = self.pdf_space_probe.take().unwrap_or_default(); let mut shared = self.pdf_space_probe.take().unwrap_or_default();
let prior = Arc::make_mut(&mut shared); let prior = Arc::make_mut(&mut shared);
self.reads_event_history = true;
for event in self.events.iter().skip(prior.observed_events) { for event in self.events.iter().skip(prior.observed_events) {
let Event::Shipout(shipped) = event else { continue }; let Event::Shipout(shipped) = event else { continue };
self.check_cancellation()?; self.check_cancellation()?;
@@ -17,6 +17,13 @@ pub(super) struct NavigationGeometry {
last_pdf_rect: [i64; 4], last_pdf_rect: [i64; 4],
} }
impl NavigationGeometry {
pub(super) fn same_state(&self, other: &Self) -> bool {
self.last_pdf_rect == other.last_pdf_rect
&& self.matrix.map(|m| m.0.map(f64::to_bits)) == other.matrix.map(|m| m.0.map(f64::to_bits))
}
}
#[derive(Clone)] #[derive(Clone)]
pub(super) struct ActiveLink { pub(super) struct ActiveLink {
layout: LinkStart, layout: LinkStart,
@@ -4,6 +4,7 @@ use std::mem::MaybeUninit;
use std::ops::Range; use std::ops::Range;
use std::ptr; use std::ptr;
#[derive(PartialEq, Eq)]
pub(super) struct PdfMatch { pub(super) struct PdfMatch {
input: Vec<u8>, input: Vec<u8>,
captures: Vec<Option<Range<usize>>>, captures: Vec<Option<Range<usize>>>,
@@ -25,6 +25,7 @@ impl Executor {
} }
// Packing can move existing lists or replace an old register. Recount // Packing can move existing lists or replace an old register. Recount
// actual storage here, counting each shared list allocation once. // actual storage here, counting each shared list allocation once.
self.reads_event_history = true;
let usage = self.collect_usage(shipping, None, Collector::for_capacity()); let usage = self.collect_usage(shipping, None, Collector::for_capacity());
self.material_charge = usage self.material_charge = usage
.active_material .active_material
@@ -36,10 +37,11 @@ impl Executor {
Ok(()) Ok(())
} }
fn resource_usage( fn resource_usage(
&self, &mut self,
shipping: Option<&NativeBox>, shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>, host: Option<HostResourceUsage>,
) -> ResourceUsage { ) -> ResourceUsage {
self.reads_event_history = true;
self.collect_usage(shipping, host, Collector::default()) self.collect_usage(shipping, host, Collector::default())
} }
+3 -1
View File
@@ -68,7 +68,7 @@ pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext}; pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial}; pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{CheckpointSource, EntryCheckpoint, Executor, Limits}; pub use engine::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits};
pub use font_catalog::{ pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource, FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
}; };
@@ -669,6 +669,8 @@ pub struct Execution {
pub incoming_state: u64, pub incoming_state: u64,
pub outgoing_state: u64, pub outgoing_state: u64,
pub steps: usize, pub steps: usize,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
reads_event_history: bool,
} }
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+18 -3
View File
@@ -3,7 +3,7 @@ use std::sync::Arc;
use super::xe_encoding::{Character, Encoding}; use super::xe_encoding::{Character, Encoding};
#[derive(Clone)] #[derive(Clone, PartialEq, Eq)]
struct XePhysical { struct XePhysical {
encoding: Encoding, encoding: Encoding,
autodetected: Option<(Encoding, usize)>, autodetected: Option<(Encoding, usize)>,
@@ -267,14 +267,14 @@ mod tests {
assert_eq!(chars, "é界 B C "); assert_eq!(chars, "é界 B C ");
} }
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy, PartialEq, Eq)]
enum LineState { enum LineState {
New, New,
Middle, Middle,
Skip, Skip,
} }
#[derive(Clone)] #[derive(Clone, PartialEq, Eq)]
enum LineBreaks { enum LineBreaks {
Physical, Physical,
Generated(Option<char>), Generated(Option<char>),
@@ -297,6 +297,21 @@ pub(super) struct Mouth {
} }
impl Mouth { impl Mouth {
pub(super) fn same_unread_input(&self, other: &Self) -> bool {
self.source == other.source
&& self.profile == other.profile
&& self.offset == other.offset
&& self.line == other.line
&& self.cursor == other.cursor
&& self.state == other.state
&& self.end_after_line == other.end_after_line
&& self.line_breaks == other.line_breaks
&& self.line_number == other.line_number
&& self.xe == other.xe
&& self.invalid_utf8 == other.invalid_utf8
&& self.data[self.offset..] == other.data[other.offset..]
}
pub(super) fn physical_frontier(&self) -> Option<usize> { pub(super) fn physical_frontier(&self) -> Option<usize> {
(matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0) (matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0)
.then_some(self.offset) .then_some(self.offset)
@@ -196,7 +196,7 @@ impl RevisionJob {
.map_err(|failure| failure.error) .map_err(|failure| failure.error)
} }
pub fn run_detailed( pub fn run_detailed(
self, &self,
executor: Executor, executor: Executor,
source: SourceFile, source: SourceFile,
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
@@ -224,7 +224,7 @@ impl RevisionJob {
/// Capture selected physical source continuations, including child input. /// Capture selected physical source continuations, including child input.
pub fn run_capturing_sources<F: SourceProvider, S>( pub fn run_capturing_sources<F: SourceProvider, S>(
self, &self,
executor: Executor, executor: Executor,
source: SourceFile, source: SourceFile,
files: &mut F, files: &mut F,
@@ -240,7 +240,7 @@ impl RevisionJob {
/// Resume after the host has validated prefix dependencies and replayed /// Resume after the host has validated prefix dependencies and replayed
/// their effects into the new revision's isolated file host. /// their effects into the new revision's isolated file host.
pub fn resume_entry_after_host_replay( pub fn resume_entry_after_host_replay(
self, &self,
checkpoint: &EntryCheckpoint, checkpoint: &EntryCheckpoint,
source: SourceFile, source: SourceFile,
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
@@ -270,7 +270,7 @@ impl RevisionJob {
} }
pub fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>( pub fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>(
self, &self,
checkpoint: &EntryCheckpoint, checkpoint: &EntryCheckpoint,
source: SourceFile, source: SourceFile,
nested: Option<SourceFile>, nested: Option<SourceFile>,
@@ -293,10 +293,31 @@ impl RevisionJob {
Some(self.finish_execution(executed, files, previous.as_deref())) Some(self.finish_execution(executed, files, previous.as_deref()))
} }
/// Resume normally unless the caller verifies and replays a matching suffix.
/// A rejected replay leaves publication untouched, so the caller can discard
/// the draft and execute again under the same revision.
pub fn resume_deciding_suffix<F: SourceProvider, S>(
&self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
nested: Option<SourceFile>,
files: &mut F,
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> {
let previous = self.session.latest();
let executed = checkpoint.resume_deciding_suffix(
source, nested, files, self.cancellation.clone(), line_break_cache,
previous.as_deref().map(|item| &item.execution), select, capture,
)?;
Ok(executed.map(|result| self.finish_execution(result, files, previous.as_deref())))
}
/// Publish a completed result after the caller verifies the same inputs /// Publish a completed result after the caller verifies the same inputs
/// and replays every host call into the current revision's draft. /// and replays every host call into the current revision's draft.
pub fn reuse_completed_after_host_replay( pub fn reuse_completed_after_host_replay(
self, &self,
completed: &RevisionExecution, completed: &RevisionExecution,
files: &impl SourceProvider, files: &impl SourceProvider,
) -> Result<Arc<RevisionExecution>, RevisionFailure> { ) -> Result<Arc<RevisionExecution>, RevisionFailure> {
@@ -304,7 +325,7 @@ impl RevisionJob {
} }
fn finish_execution( fn finish_execution(
self, &self,
executed: Result<Execution, ExecutionFailure>, executed: Result<Execution, ExecutionFailure>,
files: &impl SourceProvider, files: &impl SourceProvider,
previous: Option<&RevisionExecution>, previous: Option<&RevisionExecution>,
@@ -63,7 +63,7 @@ impl XeLineFraming {
} }
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy, PartialEq, Eq)]
pub(super) struct Character { pub(super) struct Character {
pub value: char, pub value: char,
pub start: usize, pub start: usize,
@@ -473,7 +473,7 @@ enum MapMode {
Delete, Delete,
} }
#[derive(Clone, Default)] #[derive(Clone, Default, PartialEq, Eq)]
struct MapTables { struct MapTables {
entries: Arc<BTreeMap<String, Arc<MapEntry>>>, entries: Arc<BTreeMap<String, Arc<MapEntry>>>,
// PDF inclusion addresses the PostScript name independently of the TFM. // PDF inclusion addresses the PostScript name independently of the TFM.
@@ -485,7 +485,7 @@ struct MapTables {
const MAX_CACHED_DEFAULT_MAP_BYTES: usize = 512 * 1024; const MAX_CACHED_DEFAULT_MAP_BYTES: usize = 512 * 1024;
static DEFAULT_MAP: Mutex<Option<(ResourceVersion, MapTables)>> = Mutex::new(None); static DEFAULT_MAP: Mutex<Option<(ResourceVersion, MapTables)>> = Mutex::new(None);
#[derive(Clone, Default)] #[derive(Clone, Default, PartialEq, Eq)]
pub(super) struct JobFontMap { pub(super) struct JobFontMap {
// Ordinary unevaluated pages can retain raw lists for hosts that only // Ordinary unevaluated pages can retain raw lists for hosts that only
// need TeX layout. A map command or actual autoexpanded glyph activates // need TeX layout. A map command or actual autoexpanded glyph activates
@@ -18,12 +18,13 @@ pub(super) struct Subfont {
pub(super) cmap: [u16; 2], pub(super) cmap: [u16; 2],
} }
#[derive(PartialEq, Eq)]
pub(super) struct Definition { pub(super) struct Definition {
pub(super) version: Arc<ResourceVersion>, pub(super) version: Arc<ResourceVersion>,
pub(super) subfonts: Vec<(String, Codes)>, pub(super) subfonts: Vec<(String, Codes)>,
} }
#[derive(Clone, Default)] #[derive(Clone, Default, PartialEq, Eq)]
pub(super) struct Files(BTreeMap<(PathBuf, String), Arc<Definition>>); pub(super) struct Files(BTreeMap<(PathBuf, String), Arc<Definition>>);
impl Files { impl Files {
@@ -13,6 +13,7 @@ use std::{
sync::Arc, sync::Arc,
}; };
#[derive(PartialEq, Eq)]
struct LoadedVirtual { struct LoadedVirtual {
from: String, from: String,
program: VirtualFont, program: VirtualFont,
@@ -37,7 +38,7 @@ impl Default for VirtualPaintState {
} }
} }
#[derive(Clone)] #[derive(Clone, PartialEq, Eq)]
enum Program { enum Program {
File { File {
vf: Arc<LoadedVirtual>, vf: Arc<LoadedVirtual>,
@@ -46,7 +47,7 @@ enum Program {
Letterspace(LetterspaceProgram), Letterspace(LetterspaceProgram),
} }
#[derive(Clone, Default)] #[derive(Clone, Default, PartialEq, Eq)]
pub(crate) struct JobVirtualFonts { pub(crate) struct JobVirtualFonts {
programs: BTreeMap<FontId, Option<Program>>, programs: BTreeMap<FontId, Option<Program>>,
font_map: JobFontMap, font_map: JobFontMap,
@@ -10,7 +10,7 @@ use crate::{
const MAX_CMAP_DEPTH: usize = 16; const MAX_CMAP_DEPTH: usize = 16;
const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024; const MAX_CMAP_BYTES: usize = 16 * 1024 * 1024;
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
pub(crate) struct CMap { pub(crate) struct CMap {
codespaces: [Vec<[u32; 2]>; 4], codespaces: [Vec<[u32; 2]>; 4],
mappings: [BTreeMap<u32, Mapping>; 4], mappings: [BTreeMap<u32, Mapping>; 4],
@@ -24,19 +24,19 @@ pub(crate) struct CMap {
pub(crate) resources: Vec<ResourceVersion>, pub(crate) resources: Vec<ResourceVersion>,
} }
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
struct Mapping { struct Mapping {
last: u32, last: u32,
destination: Destination, destination: Destination,
} }
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
struct CidRange { struct CidRange {
last: u32, last: u32,
cid: u16, cid: u16,
} }
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
enum Destination { enum Destination {
Sequential(Vec<u8>), Sequential(Vec<u8>),
Explicit(Vec<Vec<u8>>), Explicit(Vec<Vec<u8>>),
@@ -308,7 +308,7 @@ impl ShippedColor {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, PartialEq, Eq)]
struct Stack { struct Stack {
mode: PdfLiteralMode, mode: PdfLiteralMode,
replay_on_page: bool, replay_on_page: bool,
@@ -325,7 +325,7 @@ impl Stack {
} }
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PdfColorStacks(Vec<Stack>); pub(crate) struct PdfColorStacks(Vec<Stack>);
impl Default for PdfColorStacks { impl Default for PdfColorStacks {
@@ -87,6 +87,13 @@ pub(crate) struct AnnotationState {
enabled: bool, enabled: bool,
} }
impl AnnotationState {
pub(crate) fn same_idle_state(&self, other: &Self) -> bool {
self.enabled == other.enabled && self.bounds.is_none() && other.bounds.is_none()
&& self.active.is_none() && other.active.is_none()
}
}
impl Default for AnnotationState { impl Default for AnnotationState {
fn default() -> Self { fn default() -> Self {
Self { Self {
@@ -104,7 +104,7 @@ fn program(literal: String, resources: Vec<XdvColorResource>) -> Arc<PdfColorPro
}) })
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ColorState { pub(crate) struct ColorState {
base: Colors, base: Colors,
saved: Vec<Colors>, saved: Vec<Colors>,
@@ -44,6 +44,13 @@ pub(crate) struct TextEncoding {
} }
impl TextEncoding { impl TextEncoding {
pub(crate) fn same_state(&self, other: &Self) -> bool {
self.tainted_literals == other.tainted_literals
&& self.extra_keys == other.extra_keys
&& self.map.as_deref() == other.map.as_deref()
}
pub(crate) fn apply( pub(crate) fn apply(
&mut self, operands: &[u8], from: &str, files: &mut impl SourceProvider, &mut self, operands: &[u8], from: &str, files: &mut impl SourceProvider,
) -> Vec<String> { ) -> Vec<String> {
+5 -5
View File
@@ -1,7 +1,7 @@
//! VF file structure and the local DVI programs of individual characters. //! VF file structure and the local DVI programs of individual characters.
use std::collections::BTreeMap; use std::collections::BTreeMap;
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
pub(super) struct VirtualFont { pub(super) struct VirtualFont {
pub checksum: u32, pub checksum: u32,
pub design_size: i64, pub design_size: i64,
@@ -11,7 +11,7 @@ pub(super) struct VirtualFont {
pub packets: BTreeMap<u8, Packet>, pub packets: BTreeMap<u8, Packet>,
} }
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
pub(super) struct LocalFont { pub(super) struct LocalFont {
pub checksum: u32, pub checksum: u32,
pub name: String, pub name: String,
@@ -19,19 +19,19 @@ pub(super) struct LocalFont {
pub design_size: i64, pub design_size: i64,
} }
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
pub(super) struct Packet { pub(super) struct Packet {
pub width: i32, pub width: i32,
pub commands: Vec<Command>, pub commands: Vec<Command>,
} }
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Axis { pub(super) enum Axis {
Horizontal, Horizontal,
Vertical, Vertical,
} }
#[derive(Debug)] #[derive(Debug, PartialEq, Eq)]
pub(super) enum Command { pub(super) enum Command {
Character { Character {
slot: u8, slot: u8,
+35
View File
@@ -18,6 +18,41 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-29 输出例程返回后的后缀复用
自动会话在输出例程已返回的命令边界留存有限检查点。输入游标、
当前行、未读字节、TeX 状态、设备和字体映射、资源、输出流和
逻辑计数都核对后,才尝试复用已成功执行的后缀。当前编辑前缀
及来源版本接入旧后缀结果。写入按原顺序进入当前隔离草稿。
如果调用结果变化,释放旧草稿,在同一修订重新执行。编辑器
观测同时报告前后缀复用、丢弃的试跑步骤和总实际执行步骤。
三页真实 TeX 作业从第 2 页编辑复用后续执行。随后添加一个
此前不存在、只在后缀读取的文件,触发重放中途拒绝。已写入的
草稿被释放,重新执行后的辅助文件没有重复写入。两次的
完整 Execution、PDF、SVG、来源映射、资源、辅助文件和日志
均同各自的独立全量一致。四项会话定向检查、七项统计回归以及
编辑器优化构建通过。
同版原样 NeurIPS 在第 3 页的输出例程返回后,扫描位置到入口
第 344 行,累计 14,936,044 步。诊断比较时双方文件流仅有草稿
输出的物理 inode 差异。使用默认预算的标点编辑仍执行
5,281,627 步,原文还原执行 0 步。两个修订只更新第 3 页,
完整 Execution、PDF、SVG、来源映射、读取、查找、流读取、
辅助文件及日志与独立全量一致。
该样稿默认节点容量下发生保留材料重算,作业末尾还有实际
资源统计。两者均访问先前输出的事件。仅用于定位的 400 万
节点容量试跑仍触发末尾统计;正式默认容量与原测试保留。
已有复用路径遇到这类历史读取会退回执行。下一批将从可验证的
材料容量与末尾统计入手,闭合第 344 行之后约 463 万步的复用。
浏览器可见延迟、冷启动成本及内存仍需同版验收。
额外盒测试 5 项通过,1 项保留节点容量断言失败。隔离的 f387b1d
控制组在同一断言返回同样的成功结果,原测试和两端的失败日志保留。
证据在 target/p4-settled-output/,SHA256SUMS 指纹为
fe49c26e6f893fa651607627850f096b997a0e4dd316439ec9f0b1f701db22dc。
## 2026-11-29 原文恢复复用与出页边界实测 ## 2026-11-29 原文恢复复用与出页边界实测
自动检查点可保留两份最近的成功执行结果。恢复相同入口字节时, 自动检查点可保留两份最近的成功执行结果。恢复相同入口字节时,
+3
View File
@@ -130,6 +130,9 @@ async function compile(edit, submitted, changes) {
visibleMs: performance.now() - submitted, visibleMs: performance.now() - submitted,
steps: result.steps, steps: result.steps,
reusedSteps: result.reused_steps, reusedSteps: result.reused_steps,
reusedSuffixSteps: result.reused_suffix_steps,
discardedSuffixAttemptSteps: result.discarded_suffix_attempt_steps,
executedSteps: result.executed_steps,
reusedFrontier: result.reused_frontier, reusedFrontier: result.reused_frontier,
replayedCalls: result.replayed_calls, replayedCalls: result.replayed_calls,
pendingPublication: result.pending_publication === true, pendingPublication: result.pending_publication === true,
+4
View File
@@ -138,6 +138,10 @@ impl EditorObserver {
"phases": self.phases(compiled, ready), "phases": self.phases(compiled, ready),
"steps": steps, "steps": steps,
"reused_steps": work.reused_steps, "reused_steps": work.reused_steps,
"reused_suffix_steps": work.reused_suffix_steps,
"discarded_suffix_attempt_steps": work.discarded_suffix_attempt_steps,
"executed_steps": steps.saturating_sub(work.reused_steps)
.saturating_add(work.discarded_suffix_attempt_steps),
"reused_frontier": work.reused_frontier, "reused_frontier": work.reused_frontier,
"replayed_calls": work.replayed_calls, "replayed_calls": work.replayed_calls,
}) })
+29 -6
View File
@@ -992,15 +992,29 @@ impl CompileJob {
} }
let mut evidence = AttemptEvidence::new(self.revision()); let mut evidence = AttemptEvidence::new(self.revision());
let summary = AttemptRequest::from(&request); let summary = AttemptRequest::from(&request);
match self.compile_observed(request, &mut evidence) { let mut suffix_failure = None;
let result = self.compile_observed(&request, &mut evidence, None, &mut suffix_failure);
let result = if let Some((error, discarded_steps)) = suffix_failure {
if self.job.cancellation().is_cancelled() {
Err(CompileError::Cancelled)
} else {
evidence = AttemptEvidence::new(self.revision());
self.compile_observed(&request, &mut evidence, Some((error, discarded_steps)), &mut None)
}
} else {
result
};
match result {
Ok(document) => Ok(document), Ok(document) => Ok(document),
Err(error) => Err(evidence.failure(error, summary).persist_requested()), Err(error) => Err(evidence.failure(error, summary).persist_requested()),
} }
} }
fn compile_observed( fn compile_observed(
self, &self,
request: CompileRequest, request: &CompileRequest,
evidence: &mut AttemptEvidence, evidence: &mut AttemptEvidence,
retry_suffix: Option<(String, usize)>,
suffix_failure: &mut Option<(String, usize)>,
) -> Result<Arc<CompiledDocument>, CompileError> { ) -> Result<Arc<CompiledDocument>, CompileError> {
let cancellation = self.job.cancellation(); let cancellation = self.job.cancellation();
check(&cancellation)?; check(&cancellation)?;
@@ -1020,6 +1034,11 @@ impl CompileJob {
.filter(|_| checkpoint_guard::can_stage(&request)); .filter(|_| checkpoint_guard::can_stage(&request));
let format_cache = &self.compiler.format_cache; let format_cache = &self.compiler.format_cache;
let mut entry_checkpoint_work = EntryCheckpointWork::default(); let mut entry_checkpoint_work = EntryCheckpointWork::default();
let allow_suffix = retry_suffix.is_none();
if let Some((error, discarded_steps)) = retry_suffix {
entry_checkpoint_work.rejection = Some(error);
entry_checkpoint_work.discarded_suffix_attempt_steps = discarded_steps;
}
let (active_checkpoint, prepared) = let (active_checkpoint, prepared) =
if let Some(available) = checkpoints.and_then(CheckpointCache::current) { 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) {
@@ -1074,7 +1093,9 @@ impl CompileJob {
files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?; files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?;
} }
evidence.phase = AttemptPhase::Prepared; evidence.phase = AttemptPhase::Prepared;
notify(&request, revision, CompileStage::Prepared, &cancellation)?; if allow_suffix {
notify(request, revision, CompileStage::Prepared, &cancellation)?;
}
evidence.phase = AttemptPhase::Executing; evidence.phase = AttemptPhase::Executing;
let cache = &self.compiler.line_break_cache; let cache = &self.compiler.line_break_cache;
let before = cache.work(); let before = cache.work();
@@ -1082,11 +1103,13 @@ impl CompileJob {
debug_assert!(executor.is_none()); debug_assert!(executor.is_none());
let (executed, next) = current.resume( let (executed, next) = current.resume(
&request, &request,
self.job, &self.job,
source, source,
files, files,
cache.clone(), cache.clone(),
&mut entry_checkpoint_work, &mut entry_checkpoint_work,
allow_suffix,
suffix_failure,
)?; )?;
(executed, Some(next)) (executed, Some(next))
} else { } else {
@@ -1095,7 +1118,7 @@ impl CompileJob {
.with_line_break_cache(cache.clone()); .with_line_break_cache(cache.clone());
if let Some(cache) = checkpoints { if let Some(cache) = checkpoints {
let (executed, captured) = let (executed, captured) =
cache.capture(&request, self.job, executor, source, files); cache.capture(request, &self.job, executor, source, files);
if let Some(snapshot) = &captured { if let Some(snapshot) = &captured {
snapshot.report_capture(&mut entry_checkpoint_work); snapshot.report_capture(&mut entry_checkpoint_work);
} }
+103 -10
View File
@@ -9,7 +9,7 @@ use std::{
path::Path, path::Path,
}; };
use texrra_tex_core::{ use texrra_tex_core::{
execution::{CheckpointSource, EntryCheckpoint}, execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint},
resources::{ResourceKind, ResourceLookup, ResourceReadRange}, resources::{ResourceKind, ResourceLookup, ResourceReadRange},
}; };
#[cfg(test)] #[cfg(test)]
@@ -27,6 +27,10 @@ pub struct EntryCheckpointWork {
pub reused_steps: usize, pub reused_steps: usize,
/// The complete kernel result matched a previously successful input. /// The complete kernel result matched a previously successful input.
pub reused_completion: bool, pub reused_completion: bool,
/// Logical steps skipped after kernel and host state converged.
pub reused_suffix_steps: usize,
/// Executed work discarded when a replay failed before publication.
pub discarded_suffix_attempt_steps: usize,
pub replayed_calls: usize, pub replayed_calls: usize,
pub rejection: Option<String>, pub rejection: Option<String>,
} }
@@ -43,7 +47,7 @@ pub(super) struct PublishedCheckpoints {
} }
struct CachedCheckpoint { struct CachedCheckpoint {
entry: EntryCheckpoint, entry: Arc<EntryCheckpoint>,
guard: PrefixInputGuard, guard: PrefixInputGuard,
replay_count: usize, replay_count: usize,
slots: Capture, slots: Capture,
@@ -54,6 +58,13 @@ struct CompletedExecution {
result: Arc<RevisionExecution>, result: Arc<RevisionExecution>,
guard: PrefixInputGuard, guard: PrefixInputGuard,
calls: Arc<[Call]>, calls: Arc<[Call]>,
settled: BTreeMap<usize, SettledCheckpoint>,
}
struct SettledCheckpoint {
entry: Arc<EntryCheckpoint>,
host: crate::native_job::ReplayBoundary,
call_count: usize,
} }
pub(super) struct CheckpointSet { pub(super) struct CheckpointSet {
@@ -85,6 +96,7 @@ struct CaptureSchedule {
next_page: usize, next_page: usize,
fixed_frontier: Option<usize>, fixed_frontier: Option<usize>,
pending_edit_frontier: Option<usize>, pending_edit_frontier: Option<usize>,
settled_page: usize,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -103,6 +115,7 @@ const NESTED_INTERVALS: usize = 2;
enum Capture { enum Capture {
Entry(CaptureSlots), Entry(CaptureSlots),
Nested { file: usize, interval: usize }, Nested { file: usize, interval: usize },
Settled { page: usize, regular: Option<CaptureSlots> },
} }
#[derive(Default)] #[derive(Default)]
@@ -151,9 +164,21 @@ impl CaptureSchedule {
next_page: 1, next_page: 1,
fixed_frontier, fixed_frontier,
pending_edit_frontier: edit_frontier, pending_edit_frontier: edit_frontier,
settled_page: 0,
} }
} }
fn select_source(&mut self, source: CheckpointSource<'_>, pages: usize) -> Option<Capture> {
let regular = self.select(source.frontier, pages);
if self.fixed_frontier.is_none() && source.output_returned
&& pages > self.settled_page && pages <= 8
{
self.settled_page = pages;
return Some(Capture::Settled { page: pages, regular });
}
regular.map(Capture::Entry)
}
fn take_edit_frontier(&mut self, frontier: usize, ordinary_capture: bool) -> bool { fn take_edit_frontier(&mut self, frontier: usize, ordinary_capture: bool) -> bool {
let edit = self let edit = self
.pending_edit_frontier .pending_edit_frontier
@@ -236,6 +261,7 @@ struct CapturedEntries<'a> {
edit: Option<Arc<CachedCheckpoint>>, edit: Option<Arc<CachedCheckpoint>>,
nested: [[Option<Arc<CachedCheckpoint>>; NESTED_INTERVALS]; NESTED_FILES], nested: [[Option<Arc<CachedCheckpoint>>; NESTED_INTERVALS]; NESTED_FILES],
changed: bool, changed: bool,
settled: BTreeMap<usize, SettledCheckpoint>,
} }
impl<'a> CapturedEntries<'a> { impl<'a> CapturedEntries<'a> {
@@ -253,12 +279,14 @@ impl<'a> CapturedEntries<'a> {
edit: None, edit: None,
nested: Default::default(), nested: Default::default(),
changed: false, changed: false,
settled: BTreeMap::new(),
} }
} }
fn retain(&mut self, slots: Capture, checkpoint: Arc<CachedCheckpoint>) { fn retain(&mut self, slots: Capture, checkpoint: Arc<CachedCheckpoint>) {
let slots = match slots { let slots = match slots {
Capture::Entry(slots) => slots, Capture::Entry(slots) => slots,
Capture::Settled { .. } => unreachable!("settled observation is handled before retention"),
Capture::Nested { file, interval } => { Capture::Nested { file, interval } => {
self.nested[file][interval] = Some(checkpoint); self.nested[file][interval] = Some(checkpoint);
return; return;
@@ -275,7 +303,21 @@ impl<'a> CapturedEntries<'a> {
} }
} }
fn capture(&mut self, slots: Capture, entry: EntryCheckpoint, host: &RecordingHost) { fn capture(&mut self, slots: Capture, entry: Arc<EntryCheckpoint>, host: &RecordingHost) {
let slots = if let Capture::Settled { page, regular } = slots {
if let Some((_, call_count)) = host.prefix() {
self.settled.insert(page, SettledCheckpoint {
entry: entry.clone(),
host: host.files().replay_boundary(),
call_count,
});
self.changed = true;
}
let Some(regular) = regular else { return; };
Capture::Entry(regular)
} else {
slots
};
let (Some((trace, replay_count)), Some(path), Some(initial)) = ( let (Some((trace, replay_count)), Some(path), Some(initial)) = (
host.prefix(), host.prefix(),
self.entry_path.as_deref(), self.entry_path.as_deref(),
@@ -371,6 +413,7 @@ impl<'a> CapturedEntries<'a> {
result: result.clone(), result: result.clone(),
guard, guard,
calls: calls.clone(), calls: calls.clone(),
settled: self.settled,
})); }));
Some(Arc::new(CheckpointSet { Some(Arc::new(CheckpointSet {
entries, entries,
@@ -454,7 +497,7 @@ impl CheckpointCache {
pub(super) fn capture( pub(super) fn capture(
&self, &self,
request: &CompileRequest, request: &CompileRequest,
job: RevisionJob, job: &RevisionJob,
executor: Executor, executor: Executor,
source: SourceFile, source: SourceFile,
files: &mut Files, files: &mut Files,
@@ -473,14 +516,14 @@ impl CheckpointCache {
&mut recording, &mut recording,
|source, pages| { |source, pages| {
if source.is_entry { if source.is_entry {
schedule.select(source.frontier, pages).map(Capture::Entry) schedule.select_source(source, pages)
} else if self.minimum_frontier.is_none() { } else if self.minimum_frontier.is_none() {
nested.select(source, cwd) nested.select(source, cwd)
} else { } else {
None None
} }
}, },
|slots, entry, host| captures.capture(slots, entry, host), |slots, entry, host| captures.capture(slots, Arc::new(entry), host),
); );
let next = result.as_ref().ok().and_then(|result| { let next = result.as_ref().ok().and_then(|result| {
captures.finish(recording, self.minimum_frontier.is_none(), result) captures.finish(recording, self.minimum_frontier.is_none(), result)
@@ -702,11 +745,13 @@ impl SelectedCheckpoint {
pub(super) fn resume( pub(super) fn resume(
self, self,
request: &CompileRequest, request: &CompileRequest,
job: RevisionJob, job: &RevisionJob,
source: SourceFile, source: SourceFile,
files: &mut Files, files: &mut Files,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>, line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
work: &mut EntryCheckpointWork, work: &mut EntryCheckpointWork,
allow_suffix: bool,
suffix_failure: &mut Option<(String, usize)>,
) -> Result< ) -> Result<
( (
Result<Arc<RevisionExecution>, RevisionFailure>, Result<Arc<RevisionExecution>, RevisionFailure>,
@@ -779,8 +824,10 @@ impl SelectedCheckpoint {
files, &self.set.calls[..checkpoint.replay_count], current_nested.map(|file| &file.version), files, &self.set.calls[..checkpoint.replay_count], current_nested.map(|file| &file.version),
); );
let cwd = &request.world.cwd; let cwd = &request.world.cwd;
let cancellation = job.cancellation();
let completed = if allow_suffix { self.set.completion.as_deref() } else { None };
let result = job let result = job
.resume_capturing_sources_after_host_replay( .resume_deciding_suffix(
&checkpoint.entry, &checkpoint.entry,
source, source,
nested_source, nested_source,
@@ -792,7 +839,7 @@ impl SelectedCheckpoint {
if source.frontier > entry_frontier if source.frontier > entry_frontier
|| (source.frontier == entry_frontier && pages >= schedule.next_page) || (source.frontier == entry_frontier && pages >= schedule.next_page)
{ {
schedule.select(source.frontier, pages).map(Capture::Entry) schedule.select_source(source, pages)
} else { } else {
None None
} }
@@ -800,8 +847,46 @@ impl SelectedCheckpoint {
nested_schedule.select(source, cwd) nested_schedule.select(source, cwd)
} }
}, },
|slots, entry, host| captures.capture(slots, entry, host), |slots, entry, host| {
let entry = Arc::new(entry);
captures.capture(slots, entry.clone(), host);
let Capture::Settled { page, .. } = slots else {
return CheckpointDecision::Continue;
};
let Some((completed, old)) =
completed.and_then(|job| job.settled.get(&page).map(|old| (job, old)))
else {
return CheckpointDecision::Continue;
};
let Some(new) = captures.settled.get(&page) else {
return CheckpointDecision::Continue;
};
if old.call_count != new.call_count || old.host != new.host
|| !can_replay_completed_suffix(completed, request, host.files())
{
return CheckpointDecision::Continue;
}
let Some(execution) = entry.splice_settled_suffix(&old.entry, &completed.result.execution)
else {
return CheckpointDecision::Continue;
};
let calls = &completed.calls[old.call_count..];
let replayed = host.replay_suffix(calls, &cancellation)
.and_then(|()| completed.guard.verify_replayed_inputs(
host.files(), request.project.as_deref().expect("settled replay uses a project"),
).map_err(|error| error.to_string()));
if let Err(error) = replayed {
let discarded = entry.completed_steps().saturating_sub(work.reused_steps);
*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;
work.replayed_calls += calls.len();
CheckpointDecision::Reuse(Box::new(execution))
},
) )
.map_err(CompileError::Host)?
.ok_or_else(changed_prefix)?; .ok_or_else(changed_prefix)?;
let next = result.as_ref().ok().and_then(|result| { let next = result.as_ref().ok().and_then(|result| {
captures.finish(recording, true, result) captures.finish(recording, true, result)
@@ -815,6 +900,14 @@ impl SelectedCheckpoint {
} }
} }
fn can_replay_completed_suffix(
completed: &CompletedExecution,
request: &CompileRequest,
files: &Files,
) -> bool {
completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok()
}
fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> { fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
if previous == current { if previous == current {
return None; return None;
+17
View File
@@ -120,6 +120,23 @@ impl<'a> RecordingHost<'a> {
.filter(|read| read.path == version.path).count() == source_reads + size_reads .filter(|read| read.path == version.path).count() == source_reads + size_reads
} }
pub(super) fn files(&self) -> &Files {
self.files
}
pub(super) fn replay_suffix(&mut self, calls: &[Call], cancellation: &Cancellation) -> Result<(), String> {
let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?;
if recorded.len() + calls.len() >= MAX_REPLAY_CALLS {
return Err("completed suffix exceeds the host recording budget".into());
}
for call in calls {
check(cancellation).map_err(|error| error.to_string())?;
call.replay(self.files, None)?;
}
recorded.extend_from_slice(calls);
Ok(())
}
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> { pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
self.files.generated_outputs() self.files.generated_outputs()
} }
+55
View File
@@ -157,6 +157,20 @@ struct DraftLedger {
staged: PreparedOutput, staged: PreparedOutput,
} }
#[derive(PartialEq, Eq)]
pub(super) struct ReplayBoundary {
inputs: Vec<(u8, u64, PathBuf, u64, std::collections::VecDeque<u8>)>,
outputs: Vec<(u8, u64, PathBuf, u64)>,
next_handle: u64,
columns: [usize; 2],
terminal_enabled: bool,
generated_reads: BTreeMap<PathBuf, ResourceVersion>,
generated_before: BTreeMap<PathBuf, Option<ResourceVersion>>,
generated_written: BTreeSet<PathBuf>,
trace: texrra_tex_core::resources::ResourceTrace,
stream_events: Vec<crate::native_stream::StreamEvent>,
}
pub struct Files { pub struct Files {
world: FileWorld, world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))] #[cfg(all(target_os = "linux", target_env = "gnu"))]
@@ -654,6 +668,47 @@ impl Files {
.operation(name, path, result); .operation(name, path, result);
} }
pub(super) fn replay_boundary(&self) -> ReplayBoundary {
let mut trace = self.resource_trace().clone();
trace.project_version = None;
// The caller compared the live scanner bytes and validates later
// whole-file reads separately. Keep this entry's path and length.
if let Some(entry) = trace.reads.first_mut() {
entry.sha256.clear();
}
let mut stream_events = self.stream_io.events().to_vec();
for event in &mut stream_events {
if let crate::native_stream::StreamEffect::OutputOpened {
descriptor: Ok(identity), ..
} = &mut event.effect
{
// A fresh draft has a different inode. The stream path,
// opening version, accepted bytes and handle remain in the journal.
identity.unix_identity = None;
}
}
ReplayBoundary {
inputs: self.inputs.iter().map(|(&index, input)| {
(index, input.handle, input.path.clone(), input.offset, input.xe_lookahead.clone())
}).collect(),
outputs: self.outputs.iter().map(|(&index, output)| {
(index, output.handle, output.path.clone(), output.accepted)
}).collect(),
next_handle: self.next_handle,
columns: [self.log_column, self.terminal_column],
terminal_enabled: self.terminal_enabled,
generated_reads: self.generated_reads.clone(),
generated_before: self.generated_before.clone(),
generated_written: self.generated_written.clone(),
trace,
stream_events,
}
}
pub(super) fn replay_world(&self) -> &FileWorld {
&self.world
}
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> { pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
&self.generated_written &self.generated_written
} }
+77
View File
@@ -1572,6 +1572,83 @@ fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() {
fs::remove_dir_all(p).unwrap(); fs::remove_dir_all(p).unwrap();
} }
#[test]
fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() {
let cwd = directory("settled-suffix");
let entry = cwd.join("main.tex");
let late = cwd.join("late.tex");
let aux = cwd.join("job.aux");
let missing_aux = b"Opened\nMissing\n";
fs::write(&aux, missing_aux).unwrap();
let body = |letter: char| format!(r"
\shipout\hbox{{Cover ABC}}
\setbox3=\hbox{{{letter}}}
\shipout\box3
\immediate\openout1=job.aux
\immediate\write1{{Opened}}
\openin2=late.tex
\ifeof2
\immediate\write1{{Missing}}
\else
\read2 to\late
\immediate\write1{{\late}}
\fi
\closein2
\immediate\closeout1
\shipout\hbox{{Unchanged}}
\end
");
let mut definition = atomic_definition(&cwd, 1, &body('A'));
definition.generated.insert(aux.clone());
let mut project = ProjectSnapshot::new(definition).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let mut previous = session.compile(request.clone().with_project(project.clone())).unwrap();
assert_eq!(previous.pages.len(), 3);
for (revision, letter) in [(2, 'B'), (3, 'C')] {
let mut edits = BTreeMap::from([(
entry.clone(),
Some(Arc::from(format!("{HEADER}{}", body(letter)).into_bytes())),
)]);
if revision == 3 {
edits.insert(late.clone(), Some(Arc::from(b"Found\n".as_slice())));
}
project = project.with_file_changes(revision, edits).unwrap();
let current = request.clone().with_project(project.clone());
let updated = session.compile(current.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
if revision == 2 {
assert!(work.reused_suffix_steps > 0, "{work:?}");
assert_eq!(work.discarded_suffix_attempt_steps, 0);
} else {
assert_eq!(work.reused_suffix_steps, 0);
assert!(work.discarded_suffix_attempt_steps > 0, "{work:?}");
}
let changed: Vec<_> = updated.preview_since(Some(previous.revision())).unwrap()
.pages.into_iter().map(|page| page.index).collect();
assert_eq!(changed, [1]);
let actual = fs::read(&aux).unwrap();
let log = fs::read(cwd.join("job.log")).unwrap();
let expected = if revision == 2 { missing_aux.as_slice() } else { b"Opened\nFound \n" };
assert_eq!(actual, expected);
fs::write(&aux, missing_aux).unwrap();
let full = NativeCompiler::default().compile(current).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution);
assert_eq!(updated.resources.trace, full.resources.trace);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.pages, full.pages);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages);
assert_eq!(actual, fs::read(&aux).unwrap());
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
previous = updated;
}
fs::remove_dir_all(cwd).unwrap();
}
#[test] #[test]
fn completed_checkpoint_replays_undo_and_rechecks_immutable_and_generated_inputs() { fn completed_checkpoint_replays_undo_and_rechecks_immutable_and_generated_inputs() {
let cwd = directory("completed-undo"); let cwd = directory("completed-undo");