Experiment with verified child segment continuation reuse
This commit is contained in:
1 parent
51db480b34
commit
64adf51b20
9 files changed
+247
-23
No files matched your search
@@ -330,6 +330,8 @@ 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 in the same input.
|
||||
Advance(Arc<EntryCheckpoint>),
|
||||
Reuse(Box<Execution>),
|
||||
ReplayFailed(String),
|
||||
}
|
||||
@@ -507,6 +509,7 @@ impl EntryCheckpoint {
|
||||
}
|
||||
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error),
|
||||
Ok(CheckpointDecision::Continue) => Ok(()),
|
||||
Ok(CheckpointDecision::Advance(_)) => unreachable!("entry observer applies advances"),
|
||||
Err(error) => Err(error),
|
||||
};
|
||||
let result = executor.finish_observed_input(result, files);
|
||||
@@ -3986,7 +3989,17 @@ impl Executor {
|
||||
frontier,
|
||||
pages_processed,
|
||||
};
|
||||
capture(slot, checkpoint, files)
|
||||
match capture(slot, checkpoint, files) {
|
||||
CheckpointDecision::Advance(checkpoint) => {
|
||||
let cancellation = engine.cancellation.take();
|
||||
let line_break_cache = engine.line_break_cache.take();
|
||||
*engine = checkpoint.executor.clone();
|
||||
engine.cancellation = cancellation;
|
||||
engine.line_break_cache = line_break_cache;
|
||||
CheckpointDecision::Continue
|
||||
}
|
||||
decision => 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,52 @@ 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, prior: &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 = ¤t.sources[child];
|
||||
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.events.iter().eq(old.events.iter())
|
||||
|| !current.equivalent_accounting_history(old, Some(child))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut executor = later.executor.clone();
|
||||
executor.rebind_checkpoint_source(child, (**source).clone());
|
||||
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 +148,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 +171,7 @@ 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 && !current.equivalent_accounting_history(old, None) {
|
||||
return None;
|
||||
}
|
||||
// The joined events are published results. Resumption always starts
|
||||
@@ -155,7 +204,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 {
|
||||
@@ -253,7 +302,6 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
|
||||
}
|
||||
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 +312,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 +342,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))
|
||||
}
|
||||
@@ -181,7 +181,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| {
|
||||
@@ -198,7 +198,17 @@ impl Executor {
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
@@ -678,6 +685,37 @@ impl PublishedCheckpoints {
|
||||
}
|
||||
|
||||
impl CheckpointSet {
|
||||
fn advance_child(&self, current: &CachedCheckpoint) -> Option<(EntryCheckpoint, Option<Capture>)> {
|
||||
let boundary = current.child_boundary.as_ref()?;
|
||||
let child = current.guard.nested_source.as_ref()?;
|
||||
let Capture::Nested { file, interval: 0 } = current.slots else { return None; };
|
||||
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;
|
||||
}
|
||||
let advanced = current.entry.advance_within_child(&previous.entry, &later.entry)?;
|
||||
let bytes = usize::try_from(child.observed_size?).ok()?;
|
||||
// A valid advance can land before the new midpoint. Leave the
|
||||
// later slot available so the current run can capture it there.
|
||||
let retain = (advanced.frontier() > bytes.div_ceil(NESTED_INTERVALS)
|
||||
&& advanced.frontier() < bytes)
|
||||
.then_some(Capture::Nested { file, interval: 1 });
|
||||
Some((advanced, retain))
|
||||
})
|
||||
}
|
||||
|
||||
fn reserve_body(&self) -> Option<Arc<Self>> {
|
||||
// The reserve holds only recent shipped checkpoints and the host
|
||||
// call prefix they independently require.
|
||||
@@ -886,6 +924,20 @@ impl SelectedCheckpoint {
|
||||
|slots, entry, host| {
|
||||
let entry = Arc::new(entry);
|
||||
captures.capture(slots, entry.clone(), host);
|
||||
if let Capture::Nested { file, interval: 0 } = slots
|
||||
&& let Some(current) = captures.nested[file][0].as_ref()
|
||||
&& Arc::ptr_eq(¤t.entry, &entry)
|
||||
&& let Some((advanced, slots)) = self.set.advance_child(current)
|
||||
{
|
||||
let advanced = Arc::new(advanced);
|
||||
let reused = advanced.completed_steps() - entry.completed_steps();
|
||||
if let Some(slots) = slots {
|
||||
captures.capture(slots, advanced.clone(), host);
|
||||
}
|
||||
work.reused_steps += reused;
|
||||
work.reused_suffix_steps += reused;
|
||||
return CheckpointDecision::Advance(advanced);
|
||||
}
|
||||
let Capture::Settled { page, .. } = slots else {
|
||||
return CheckpointDecision::Continue;
|
||||
};
|
||||
@@ -916,8 +968,9 @@ 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))
|
||||
},
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -2861,6 +2861,89 @@ 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 replay_rejection_resumes_earlier_without_publishing_rejected_effects() {
|
||||
struct PublishedBeforeExecution(Vec<(PathBuf, Vec<u8>)>);
|
||||
|
||||
Reference in new issue
Block a user