//! Reuse a recorded entry prefix only after validating the current job host. use super::checkpoint_probe::{Call, RecordingHost}; use super::*; #[cfg(test)] use std::fs; use std::{ collections::{BTreeMap, BTreeSet, VecDeque}, ffi::OsString, path::Path, time::Instant, }; use texrra_tex_core::{ execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, RelocatedShipoutSuffix}, resources::{ResourceKind, ResourceLookup, ResourceReadRange}, }; #[cfg(test)] use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy}; /// Work actually performed by the optional entry-checkpoint path. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct EntryCheckpointWork { pub captured_frontier: Option, /// Checkpoints in the selected or freshly captured set. pub retained_checkpoints: usize, pub reused_frontier: Option, /// Child input at the resume frontier, when the entry scanner was suspended. pub reused_source: Option, pub reused_steps: usize, /// The complete kernel result matched a previously successful input. 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 rejection: Option, } pub(super) struct CheckpointCache { minimum_frontier: Option, published: Mutex>>, } pub(super) struct PublishedCheckpoints { current: Arc, previous_body: Option>, previous_completion: Option>, } struct CachedCheckpoint { entry: Arc, guard: PrefixInputGuard, replay_count: usize, slots: Capture, } struct CompletedExecution { result: Arc, guard: PrefixInputGuard, calls: Arc<[Call]>, settled: BTreeMap, } struct SettledCheckpoint { entry: Arc, host: crate::native_job::ReplayBoundary, call_count: usize, } pub(super) struct CheckpointSet { entries: Vec>, calls: Arc<[Call]>, completion: Option>, // An earlier run can still supply boundaries beyond the point where this // run stopped executing. Its checkpoints remain comparison inputs only. suffix_base: Option>, refresh_on_resume: bool, edit_frontier: Option, } pub(super) struct SelectedCheckpoint { set: Arc, candidate: ExecutionCandidate, } pub(super) struct ReusedShipoutLayouts { pub(super) donor: Arc, pub(super) suffix: RelocatedShipoutSuffix, } enum ExecutionCandidate { Boundary(usize), Completed(Arc), } const SOURCE_INTERVALS: usize = 4; const DENSE_SETTLED_PAGES: usize = 4; const SPARSE_SETTLED_SLOTS: usize = 4; fn settled_page_stride(page: usize) -> usize { page.saturating_sub(DENSE_SETTLED_PAGES) .div_ceil(SPARSE_SETTLED_SLOTS) .max(1) .next_power_of_two() } // Each interval can keep an early command boundary and a more advanced // boundary after actual shipout. Larger jobs sample pages at wider intervals. struct CaptureSchedule { bytes: usize, stride: usize, seen: [bool; SOURCE_INTERVALS], next_page: usize, fixed_frontier: Option, pending_edit_frontier: Option, pending_line_end: Option<(usize, usize, usize)>, settled_page: usize, } #[derive(Clone, Copy)] struct CaptureSlots { interval: usize, early: bool, page: bool, edit: bool, next_page: usize, } const NESTED_FILES: usize = 2; const NESTED_INTERVALS: usize = 2; #[derive(Clone, Copy)] enum Capture { Entry(CaptureSlots), LineEnd { interval: usize }, Nested { file: usize, interval: usize }, Settled { page: usize, regular: Option }, } #[derive(Default)] struct NestedSchedule { sources: [Option; NESTED_FILES], seen: [[bool; NESTED_INTERVALS]; NESTED_FILES], recent: Option<(usize, Option)>, } impl NestedSchedule { fn select(&mut self, source: CheckpointSource<'_>, cwd: &Path) -> Option { let file = if let Some((id, file)) = self.recent && id == source.id { file } else { let file = if Path::new(source.name).starts_with(cwd) { self.sources.iter().position(|id| *id == Some(source.id)) .or_else(|| self.sources.iter().position(Option::is_none)) } else { None }; self.recent = Some((source.id, file)); file }?; if source.frontier >= source.bytes { return None; } let stride = source.bytes.div_ceil(NESTED_INTERVALS); let interval = (source.frontier - 1) / stride; self.sources[file] = Some(source.id); (!std::mem::replace(&mut self.seen[file][interval], true)) .then_some(Capture::Nested { file, interval }) } fn retain(&mut self, file: usize, interval: usize, source: usize) { self.sources[file] = Some(source); self.seen[file][interval] = true; } } impl CaptureSchedule { fn new(bytes: usize, fixed_frontier: Option, edit_frontier: Option) -> Self { Self { bytes, stride: bytes.div_ceil(SOURCE_INTERVALS).max(1), seen: [false; SOURCE_INTERVALS], next_page: 1, fixed_frontier, pending_edit_frontier: edit_frontier, pending_line_end: None, settled_page: 0, } } fn select_source(&mut self, source: CheckpointSource<'_>, pages: usize) -> Option { let regular = self.select(source.frontier, pages); let mut line_end = None; if self.fixed_frontier.is_none() { if let Some(slots) = regular.filter(|slots| slots.early) { self.pending_line_end = (!source.line_consumed) .then_some((source.frontier, slots.interval, pages)); } else if let Some((frontier, interval, before_pages)) = self.pending_line_end { if frontier != source.frontier { self.pending_line_end = None; } else if source.line_consumed { self.pending_line_end = None; if pages == before_pages { line_end = Some(Capture::LineEnd { interval }); } } } } if self.fixed_frontier.is_none() && source.output_returned && pages > self.settled_page { self.settled_page = pages; // A wider grid is a subset of the earlier grid, so a new run // still visits any checkpoint retained by a completed run. if pages.saturating_sub(DENSE_SETTLED_PAGES) % settled_page_stride(pages) == 0 { return Some(Capture::Settled { page: pages, regular }); } } regular.map(Capture::Entry).or(line_end) } fn take_edit_frontier(&mut self, frontier: usize, ordinary_capture: bool) -> bool { let edit = self .pending_edit_frontier .take_if(|pending| *pending == frontier) .is_some(); if edit && !ordinary_capture { // Move a later byte-interval capture to the active editing line. // Keep the earlier prefix and all shipout capture opportunities. let next_interval = (frontier - 1) / self.stride + 1; if let Some(seen) = self.seen.get_mut(next_interval) { *seen = true; } } edit } fn select(&mut self, frontier: usize, pages: usize) -> Option { if let Some(minimum) = self.fixed_frontier { if self.seen[0] || frontier < minimum { return None; } self.seen[0] = true; return Some(CaptureSlots { interval: 0, early: true, page: false, edit: false, next_page: self.next_page, }); } if frontier == 0 || frontier > self.bytes { return None; } let interval = (frontier - 1) / self.stride; let entry_complete = frontier == self.bytes; // A loaded final line can start closeout hooks or produce several // pages. Keep page boundaries after the last earlier source anchor. let early = !entry_complete && !std::mem::replace(&mut self.seen[interval], true); let page = pages >= self.next_page; if page { self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two()); } let edit = !entry_complete && self.take_edit_frontier(frontier, early || page); (early || page || edit).then_some(CaptureSlots { interval, early, page, edit, next_page: self.next_page, }) } fn retain(&mut self, checkpoint: &CachedCheckpoint) -> Option { let Capture::Entry(slots) = checkpoint.slots else { return None; }; let frontier = checkpoint.entry.frontier(); if frontier > self.bytes || (frontier == self.bytes && !slots.page) { return None; } let interval = (frontier - 1) / self.stride; let early = frontier < self.bytes && slots.early && !std::mem::replace(&mut self.seen[interval], true); self.next_page = self.next_page.max(slots.next_page); Some(CaptureSlots { interval, early, edit: frontier < self.bytes && self.take_edit_frontier(frontier, early || slots.page), ..slots }) } } struct CapturedEntries<'a> { request: &'a CompileRequest, entry_path: Option, initial: Option, early: [Option>; SOURCE_INTERVALS], shipped: [Option>; SOURCE_INTERVALS], edit: Option>, nested: [[Option>; NESTED_INTERVALS]; NESTED_FILES], changed: bool, settled: BTreeMap, } impl<'a> CapturedEntries<'a> { fn new(request: &'a CompileRequest, files: &Files) -> Self { Self { request, entry_path: files .resource_trace() .reads .first() .map(|first| first.path.clone()), initial: files.preparation().generated_initial.clone(), early: Default::default(), shipped: Default::default(), edit: None, nested: Default::default(), changed: false, settled: BTreeMap::new(), } } fn retain(&mut self, slots: Capture, checkpoint: Arc) { let slots = match slots { Capture::Entry(slots) => slots, Capture::LineEnd { .. } | Capture::Settled { .. } => { unreachable!("observation is handled before retention") } Capture::Nested { file, interval } => { self.nested[file][interval] = Some(checkpoint); return; } }; if slots.early { self.early[slots.interval] = Some(checkpoint.clone()); } if slots.edit { self.edit = Some(checkpoint.clone()); } if slots.page { self.shipped[slots.interval] = Some(checkpoint); } } fn capture(&mut self, slots: Capture, entry: Arc, host: &RecordingHost) { let slots = match slots { Capture::Settled { page, regular } => { if let Some((_, calls)) = host.prefix() { let stride = settled_page_stride(page); self.settled.retain(|&old, _| { old.saturating_sub(DENSE_SETTLED_PAGES) % stride == 0 }); self.settled.insert(page, SettledCheckpoint { entry: entry.clone(), host: host.files().replay_boundary(), call_count: calls.len(), }); self.changed = true; } let Some(regular) = regular else { return; }; Capture::Entry(regular) } Capture::LineEnd { interval } => { let Some(earlier) = &self.early[interval] else { return; }; // With the same host prefix, finishing an already loaded // line narrows no resource dependency or replay opportunity. if !host.prefix().is_some_and(|(_, calls)| calls.len() == earlier.replay_count) || !entry.can_advance_entry_anchor(&earlier.entry) { return; } let Capture::Entry(slots) = earlier.slots else { unreachable!() }; Capture::Entry(CaptureSlots { page: false, ..slots }) } other => other, }; let (Some((trace, calls)), Some(path), Some(initial)) = ( host.prefix(), self.entry_path.as_deref(), self.initial.as_ref(), ) else { return; }; let Ok(mut guard) = PrefixInputGuard::capture( self.request, path, trace, calls, host.generated_outputs(), initial.clone(), ) else { return; }; if let Some(source) = entry.nested_source() && !guard.allow_nested_source(Path::new(source), trace, host) { return; } self.retain( slots, Arc::new(CachedCheckpoint { entry, guard, replay_count: calls.len(), slots, }), ); self.changed = true; } fn replay_settled_suffix( &mut self, page: usize, current: &EntryCheckpoint, prior: &SettledCheckpoint, completed: &CompletedExecution, host: &mut RecordingHost, cancellation: &Cancellation, ) -> Result<(), String> { let project = self.request.project.as_deref().expect("settled replay uses a project"); let path = &completed.guard.entry; let bytes = project.file(path).expect("settled entry").data.len(); let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len(); let resize = (previous_bytes != bytes).then_some((previous_bytes, bytes)); let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1); let offset = texrra_tex_core::execution::StepOffset::new( prior.entry.completed_steps(), current.completed_steps(), ); let mut later = [const { None }; SOURCE_INTERVALS]; // Untranslated live continuations and their source intervals still // refer to the old entry when its length changed. if resize.is_none() && let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) { // Keep the deepest compatible settled continuation per source interval. for (&page, anchor) in completed.settled.range((std::ops::Bound::Excluded(page), std::ops::Bound::Unbounded)).rev() { let interval = (anchor.entry.frontier() - 1) / stride; if later[interval].is_some() { continue; } check(cancellation).map_err(|error| error.to_string())?; if let Some(entry) = rebase(&anchor.entry) { later[interval] = Some((page, anchor, entry)); } } } let mut replayed = prior.call_count; for (interval, (page, anchor, entry)) in later.into_iter().enumerate() .filter_map(|(interval, anchor)| anchor.map(|anchor| (interval, anchor))) { let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { continue; }; host.replay_suffix(calls, offset, None, cancellation)?; replayed = anchor.call_count; if anchor.host == host.files().replay_boundary() { let regular = CaptureSlots { interval, early: false, page: true, edit: false, next_page: page.saturating_add(1), }; self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); } } host.replay_suffix(&completed.calls[replayed..], offset, resize, cancellation)?; completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) } fn finish( self, recording: RecordingHost, refresh_on_resume: bool, result: &Arc, suffix_base: Option>, ) -> Option> { if !self.changed { return None; } let edit_frontier = self .edit .as_ref() .map(|checkpoint| checkpoint.entry.frontier()); let mut entries: Vec<_> = self .early .into_iter() .chain(self.shipped) .flatten() .chain(self.edit) .collect(); entries.sort_by_key(|candidate| candidate.entry.completed_steps()); entries.dedup_by(|a, b| Arc::ptr_eq(a, b)); if entries.len() > 2 * SOURCE_INTERVALS { let edit = edit_frontier.expect("an edit checkpoint can fill the remaining slot"); // Preserve the earliest continuation and the page checkpoints. // Displace the ordinary continuation closest to the edited line. let (index, _) = entries .iter() .enumerate() .skip(1) .filter(|(_, checkpoint)| { matches!(checkpoint.slots, Capture::Entry(slots) if !slots.page) && checkpoint.entry.frontier() != edit }) .min_by_key(|(_, checkpoint)| checkpoint.entry.frontier().abs_diff(edit)) .expect("the full schedule has ordinary continuations"); entries.remove(index); } entries.extend(self.nested.into_iter().flatten().flatten()); entries.sort_by_key(|candidate| candidate.entry.completed_steps()); let replay_count = entries.iter().map(|entry| entry.replay_count).max()?; // Only automatic sessions retain completed jobs, and only when the // recorder reached actual closeout without filling its call budget. let completion = refresh_on_resume.then(|| { let (trace, calls) = recording.prefix()?; let guard = PrefixInputGuard::capture( self.request, self.entry_path.as_deref()?, trace, calls, recording.generated_outputs(), self.initial?, ).ok()?; Some(guard) }).flatten(); let mut calls = recording.into_calls()?; if completion.is_none() { calls.truncate(replay_count); } let calls = Arc::<[Call]>::from(calls); let completion = completion.map(|guard| Arc::new(CompletedExecution { result: result.clone(), guard, calls: calls.clone(), settled: self.settled, })); Some(Arc::new(CheckpointSet { entries, calls, completion, suffix_base, refresh_on_resume, edit_frontier, })) } } pub(super) fn can_stage(request: &CompileRequest) -> bool { request.project.is_some() && request.target == Target::Shipouts && !request.terminal && request.resource_manifest.is_none() && request.layout_manifest.is_none() } impl CheckpointCache { pub(super) fn new(minimum_frontier: Option) -> Self { Self { minimum_frontier, published: Mutex::new(None), } } pub(super) fn current(&self) -> Option> { self.published .lock() .expect("native entry checkpoint cache poisoned") .clone() } pub(super) fn set(&self, next: Option>, request: &CompileRequest) { let mut published = self .published .lock() .expect("native entry checkpoint cache poisoned"); let Some(next) = next else { *published = None; return; }; if published.as_ref().is_some_and(|set| Arc::ptr_eq(&set.current, &next)) { return; } if published .as_ref() .and_then(|set| set.previous_body.as_ref()) .is_some_and(|previous| Arc::ptr_eq(previous, &next)) { return; } let previous_body = published.as_ref().and_then(|published| { if next.refresh_on_resume && let Some(project) = request.project.as_deref() && published .current .entries .iter() .find(|entry| matches!(entry.slots, Capture::Entry(slots) if slots.page)) .is_some_and(|entry| entry.accept_entry(project).is_err()) { // Keep useful continuations from before a change to the first // shipped prefix. Later edits keep that same reserve. published.current.reserve_body() } else { published.previous_body.clone() } }); let previous_completion = published.as_ref().and_then(|published| { published.current.completion.clone().or_else(|| published.previous_completion.clone()) }); *published = Some(Arc::new(PublishedCheckpoints { current: next, previous_body, previous_completion, })); } pub(super) fn capture( &self, request: &CompileRequest, job: &RevisionJob, executor: Executor, source: SourceFile, files: &mut Files, ) -> ( Result, RevisionFailure>, Option>, ) { let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None); let mut captures = CapturedEntries::new(request, files); let mut recording = RecordingHost::new(files); let mut nested = NestedSchedule::default(); let cwd = &request.world.cwd; let result = job.run_capturing_sources( executor, source, &mut recording, |source, pages| { if source.is_entry { schedule.select_source(source, pages) } else if self.minimum_frontier.is_none() { nested.select(source, cwd) } else { None } }, |slots, entry, host| captures.capture(slots, Arc::new(entry), host), ); let next = result.as_ref().ok().and_then(|result| { captures.finish(recording, self.minimum_frontier.is_none(), result, None) }); (result, next) } } impl PublishedCheckpoints { pub(super) fn prepare( &self, request: &CompileRequest, cache: &FormatCache, cancellation: &Cancellation, evidence: &mut AttemptEvidence, ) -> Result<(SelectedCheckpoint, PreparedJob), CompileError> { let project = request .project .as_deref() .ok_or_else(|| CompileError::Host("checkpoint requires an atomic project".into()))?; let mut candidates: Vec<_> = self .current .candidates() .chain(self.previous_body.iter().flat_map(|body| body.candidates())) .chain(self.current.completion.iter().chain(&self.previous_completion).map(|result| { SelectedCheckpoint { set: self.current.clone(), candidate: ExecutionCandidate::Completed(result.clone()), } })) .collect(); candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.completed_steps())); let mut candidates = VecDeque::from(candidates); let mut guard_rejection = None; let mut replay_rejection = None; 'retry: loop { check(cancellation)?; let first = std::iter::from_fn(|| candidates.pop_front()) .find(|candidate| { match candidate .accept_entry(project) .and_then(|()| candidate.guard().verify_project(request)) { Ok(_) => true, Err(error) => { guard_rejection.get_or_insert(error); false } } }) .ok_or_else(|| { replay_rejection .take() .or_else(|| guard_rejection.take().map(CompileError::Host)) .unwrap_or_else(|| CompileError::Host("no entry checkpoint retained".into())) })?; // Each replay owns a separate draft and observes the generated // initial state under the job lock before writing any effects. let mut selected = None; let mut attempt = AttemptEvidence::new(evidence.revision); attempt.phase = evidence.phase; let mut prepared = prepare_checked( request, false, Some(cache), cancellation, &mut attempt, Some(Box::new(|world, preparation| { let mut rejection = None; let remaining = std::iter::from_fn(|| candidates.pop_front()); for candidate in std::iter::once(first).chain(remaining) { match candidate .accept_entry(project) .and_then(|()| candidate.guard().verify(request, world, preparation)) { Ok(()) => { selected = Some(candidate); return Ok(()); } Err(error) => { rejection.get_or_insert(error); } } } Err(rejection.unwrap_or_else(|| "no entry checkpoint retained".into())) })), EffectMode::Draft, KernelPreparation::Resume, )?; let selected = selected.expect("resume preparation chose a verified checkpoint"); let guard = selected.guard(); let partial_source = guard.nested_source.as_ref() .and_then(|source| project.file(&source.path)).map(|file| &file.version); for (index, call) in selected.calls().iter().enumerate() { check(cancellation)?; if let Err(error) = call.replay(&mut prepared.files, partial_source) { replay_rejection.get_or_insert(CompileError::Host(error)); // Other checkpoints sharing this call cannot use the // invalidated prefix either. Drop the draft on retry. candidates.retain(|candidate| { let calls = candidate.calls(); calls.len() <= index || !std::ptr::eq(calls.as_ptr(), selected.calls().as_ptr()) }); continue 'retry; } } if let Err(error) = guard.verify_replayed_inputs(&prepared.files, project) { replay_rejection.get_or_insert(error); continue; } *evidence = attempt; return Ok((selected, prepared)); } } } impl CheckpointSet { fn reserve_body(&self) -> Option> { // The reserve holds only recent shipped checkpoints and the host // call prefix they independently require. let mut entries: Vec<_> = self .entries .iter() .rev() .filter(|entry| matches!(entry.slots, Capture::Entry(slots) if slots.page)) .take(2) .cloned() .collect(); entries.reverse(); let replay_count = entries.last()?.replay_count; Some(Arc::new(Self { entries, calls: Arc::from(&self.calls[..replay_count]), completion: None, suffix_base: None, refresh_on_resume: self.refresh_on_resume, edit_frontier: self.edit_frontier, })) } pub(super) fn report_capture(&self, work: &mut EntryCheckpointWork) { work.retained_checkpoints = self.entries.len(); work.captured_frontier = self.entries.iter().rev() .find(|entry| matches!(entry.slots, Capture::Entry(_))) .map(|entry| entry.entry.frontier()); } fn candidates(self: &Arc) -> impl Iterator + '_ { (0..self.entries.len()) .rev() .map(|index| SelectedCheckpoint { set: Arc::clone(self), candidate: ExecutionCandidate::Boundary(index), }) } } impl CachedCheckpoint { fn accept_entry(&self, project: &ProjectSnapshot) -> Result<(), String> { let entry = project .file(&self.guard.entry) .ok_or("checkpoint entry is unavailable")?; if !self .entry .accepts_entry_bytes(&self.guard.entry.to_string_lossy(), &entry.data) { return Err("checkpoint entry prefix changed".into()); } if let Some(source) = &self.guard.nested_source { let child = project.file(&source.path).ok_or("checkpoint child is unavailable")?; if !self.entry.accepts_nested_source(&source.path.to_string_lossy(), &child.data) { return Err("checkpoint child prefix changed".into()); } } Ok(()) } } impl SelectedCheckpoint { fn completed_steps(&self) -> usize { match &self.candidate { ExecutionCandidate::Boundary(index) => self.set.entries[*index].entry.completed_steps(), ExecutionCandidate::Completed(job) => job.result.execution.steps, } } fn guard(&self) -> &PrefixInputGuard { match &self.candidate { ExecutionCandidate::Boundary(index) => &self.set.entries[*index].guard, ExecutionCandidate::Completed(job) => &job.guard, } } fn accept_entry(&self, project: &ProjectSnapshot) -> Result<(), String> { match &self.candidate { ExecutionCandidate::Boundary(index) => self.set.entries[*index].accept_entry(project), ExecutionCandidate::Completed(job) => { let path = &job.guard.entry; if job.guard.project.file(path).zip(project.file(path)) .is_some_and(|(old, new)| old.version == new.version && old.data == new.data) { Ok(()) } else { Err("completed checkpoint entry changed".into()) } } } } fn calls(&self) -> &[Call] { match &self.candidate { ExecutionCandidate::Boundary(index) => { &self.set.calls[..self.set.entries[*index].replay_count] } ExecutionCandidate::Completed(job) => &job.calls, } } pub(super) fn resume( self, request: &CompileRequest, job: &RevisionJob, source: SourceFile, files: &mut Files, line_break_cache: Arc, work: &mut EntryCheckpointWork, allow_suffix: bool, suffix_failure: &mut Option<(String, usize)>, ) -> Result< ( Result, RevisionFailure>, Arc, Option, ), CompileError, > { let index = match &self.candidate { ExecutionCandidate::Boundary(index) => *index, ExecutionCandidate::Completed(completed) => { work.retained_checkpoints = self.set.entries.len(); work.reused_frontier = Some(source.data.len()); work.reused_steps = completed.result.execution.steps; work.reused_completion = true; work.replayed_calls = completed.calls.len(); return Ok(( job.reuse_completed_after_host_replay(&completed.result, files), self.set, None, )); } }; let checkpoint = &self.set.entries[index]; let frontier = checkpoint.entry.frontier(); work.retained_checkpoints = self.set.entries.len(); work.reused_frontier = Some(frontier); work.reused_source = checkpoint.guard.nested_source.as_ref().map(|source| source.path.clone()); work.reused_steps = checkpoint.entry.completed_steps(); work.replayed_calls = checkpoint.replay_count; let changed_prefix = || CompileError::Host("prepared checkpoint prefix changed".into()); if !self.set.refresh_on_resume { let result = job .resume_entry_after_host_replay(&checkpoint.entry, source, files) .ok_or_else(changed_prefix)?; return Ok((result, self.set, None)); } let previous = checkpoint .guard .project .file(&checkpoint.guard.entry) .expect("a checkpoint records its source"); let edit = changed_line_start(&previous.data, &source.data).or(self.set.edit_frontier); let mut schedule = CaptureSchedule::new(source.data.len(), None, edit); let mut nested_schedule = NestedSchedule::default(); let entry_frontier = checkpoint.entry.entry_frontier(); let current_nested = checkpoint.guard.nested_source.as_ref() .and_then(|source| request.project.as_ref()?.file(&source.path)); let nested_source = current_nested.map(|file| SourceFile { name: file.version.path.display().to_string(), data: file.data.to_vec(), }); let mut captures = CapturedEntries::new(request, files); // Earlier retained positions refer only to calls already replayed. for previous in &self.set.entries[..=index] { if previous.replay_count > checkpoint.replay_count { continue; } match previous.slots { Capture::Entry(_) if previous.entry.frontier() <= entry_frontier => { if let Some(slots) = schedule.retain(previous) { captures.retain(Capture::Entry(slots), previous.clone()); } } Capture::Nested { file, interval } => { let id = previous.entry.nested_source_id().expect("nested checkpoint source"); nested_schedule.retain(file, interval, id); captures.retain(previous.slots, previous.clone()); } _ => {} } } let mut recording = RecordingHost::after_replay( files, &self.set.calls[..checkpoint.replay_count], current_nested.map(|file| &file.version), ); let cwd = &request.world.cwd; let cancellation = job.cancellation(); let suffixes = self.set.completion.iter().chain(&self.set.suffix_base); let mut suffix_base = None; let mut reused_layouts = None; let mut timings = CheckpointTimings::default(); let timed = request.observer.is_some(); let resume_started = timed.then(Instant::now); let result = job .resume_deciding_suffix( &checkpoint.entry, source, nested_source, &mut recording, line_break_cache, |source, pages| { if source.is_entry { // The loaded entry line can be shared by several shipouts. if source.frontier > entry_frontier || (source.frontier == entry_frontier && pages >= schedule.next_page) { schedule.select_source(source, pages) } else { None } } else { nested_schedule.select(source, cwd) } }, |slots, entry, host| { let entry = Arc::new(entry); measure(&mut timings.capture, timed, || { captures.capture(slots, entry.clone(), host); }); let Capture::Settled { page, .. } = slots else { return CheckpointDecision::Continue; }; let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else { return CheckpointDecision::Continue; }; let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| { let old = completed.settled.get(&page)?; let host_matches = measure(&mut timings.suffix_host_validation, timed, || { old.call_count == new.call_count && new.host.matches_for_suffix(&old.host) && can_replay_completed_suffix(completed, request, host.files()) }); if !host_matches { return None; } let kernel_timings = timed.then_some(&mut timings.suffix_kernel); let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || { entry.splice_settled_suffix_observed( &old.entry, &completed.result.execution, kernel_timings, ) })?; Some((completed, old, execution, layout)) }) else { return CheckpointDecision::Continue; }; let calls = &completed.calls[old.call_count..]; let replayed = measure(&mut timings.suffix_host_replay, timed, || { captures.replay_settled_suffix(page, &entry, old, completed, host, &cancellation) }); 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); } // Keep a single comparison run with the furthest recorded // boundary. Do not chain older completed runs. suffix_base = suffixes.clone() .max_by_key(|candidate| { (candidate.settled.keys().next_back().copied(), Arc::ptr_eq(candidate, completed)) }) .cloned(); work.reused_suffix_steps = execution.steps - entry.completed_steps(); work.reused_steps += work.reused_suffix_steps; work.replayed_calls += calls.len(); reused_layouts = layout.map(|suffix| ReusedShipoutLayouts { donor: Arc::clone(&completed.result), suffix, }); CheckpointDecision::Reuse(Box::new(execution)) }, ) .map_err(CompileError::Host)? .ok_or_else(changed_prefix)?; if let Some(started) = resume_started { timings.resume = started.elapsed(); } let next = measure(&mut timings.retain, timed, || { result.as_ref().ok().and_then(|result| captures.finish(recording, true, result, suffix_base)) }); if result.is_ok() { if let Some(observer) = &request.observer { observer.checkpoint_timings(job.revision(), timings); } } else { reused_layouts = None; } if let Some(next) = next { next.report_capture(work); Ok((result, next, reused_layouts)) } else { Ok((result, self.set, reused_layouts)) } } } fn measure(elapsed: &mut Duration, enabled: bool, action: impl FnOnce() -> T) -> T { let started = enabled.then(Instant::now); let value = action(); if let Some(started) = started { *elapsed += started.elapsed(); } value } 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 { if previous == current { return None; } let common = previous .iter() .zip(current) .take_while(|(old, new)| old == new) .count(); let mut prefix = ¤t[..common]; // A CR followed by LF is one physical line ending. if prefix.ends_with(b"\r") && current.get(common) == Some(&b'\n') { prefix = &prefix[..prefix.len() - 1]; } Some( prefix .iter() .rposition(|byte| matches!(*byte, b'\r' | b'\n')) .map_or(0, |offset| offset + 1), ) } struct NestedSourceGuard { path: PathBuf, observed_size: Option, } struct PrefixInputGuard { original: AttemptRequest, project: Arc, initial: GeneratedInitialState, entry: PathBuf, nested_source: Option, immutable: BTreeSet, immutable_sizes: BTreeMap, immutable_stream_prefixes: BTreeMap, generated: BTreeSet, lookups: Vec, stream_reads: Vec, format_input_bindings: BTreeMap, clock_environment: Option<[Option; 3]>, } fn size_only_inputs( project: &ProjectSnapshot, trace: &ResourceTrace, calls: &[Call], ) -> BTreeMap { #[derive(Default)] struct Observations { sizes: usize, reads: usize, lookups: usize, } let mut counts = BTreeMap::<&Path, Observations>::new(); for (path, size) in calls.iter().filter_map(Call::observed_file_size) { if project.file(path).is_some_and(|file| file.version.bytes == size) { counts.entry(path).or_default().sizes += 1; } } if counts.is_empty() { return BTreeMap::new(); } // A size call records one complete host read and one successful lookup. // Any other consumer keeps its own stronger dependency on this path. for version in &trace.reads { if let Some(count) = counts.get_mut(version.path.as_path()) { count.reads += 1; } } for path in trace.lookups.iter().filter_map(|item| item.resolved.as_deref()) { if let Some(count) = counts.get_mut(path) { count.lookups += 1; } } for path in trace.stream_reads.iter().map(|read| &read.path) .chain(trace.file_modifications.iter().map(|read| &read.path)) .chain(trace.generated_lookups.iter().map(|read| &read.target)) .chain(trace.format_input_bindings.values()) { counts.remove(path.as_path()); } counts.into_iter() .filter(|(_, count)| count.sizes == count.reads && count.sizes == count.lookups) .map(|(path, _)| (path.to_owned(), project.file(path).unwrap().version.bytes)) .collect() } fn date_environment() -> [Option; 3] { ["TZ", "SOURCE_DATE_EPOCH", "FORCE_SOURCE_DATE"].map(std::env::var_os) } impl PrefixInputGuard { fn capture( request: &CompileRequest, entry: &Path, trace: &ResourceTrace, calls: &[Call], written: &BTreeSet, initial: GeneratedInitialState, ) -> Result { let project = request .project .as_ref() .ok_or("checkpoint requires an atomic project")?; let source = project .file(entry) .ok_or("checkpoint entry was not immutable")?; if trace.project_version.as_ref() != Some(project.version()) || trace.reads.first() != Some(&source.version) || !trace.lookups.first().is_some_and(|lookup| { lookup.kind == ResourceKind::Tex && lookup.resolved.as_deref() == Some(entry) }) { return Err("checkpoint trace does not begin at its actual project entry".into()); } if !trace.read_errors.is_empty() || !trace.namespace_capture_failures.is_empty() { return Err("checkpoint contains incomplete resource observations".into()); } let tracked = trace .lookups .iter() .skip(1) .filter_map(|item| item.resolved.as_deref()) .chain(trace.reads.iter().skip(1).map(|item| item.path.as_path())) .chain(trace.stream_reads.iter().map(|item| item.path.as_path())) .chain( trace .generated_lookups .iter() .map(|item| item.target.as_path()), ); let mut immutable = BTreeSet::new(); let mut generated = BTreeSet::new(); for path in tracked { if project.file(path).is_some() { immutable.insert(path.to_path_buf()); } else if initial.files().contains_key(path) { generated.insert(path.to_path_buf()); } else { return Err(format!( "checkpoint input has no stable initial role: {}", path.display() )); } } // Opening a generated output observes its pre-write version. generated.extend( written .iter() .filter(|path| initial.files().contains_key(*path)) .cloned(), ); for observed in &trace.file_modifications { if project.file(&observed.path).is_none() { return Err("checkpoint file date requires a captured immutable resource".into()); } immutable.insert(observed.path.clone()); } // A stream can have unconsumed bytes even though the host pinned a // complete buffer. Whole-file consumers, dates and observed EOF // still require the immutable input version. let whole_files: BTreeSet<_> = trace .reads .iter() .map(|version| version.path.as_path()) .chain(trace.file_modifications.iter().map(|item| item.path.as_path())) .chain(trace.stream_reads.iter().filter(|item| item.eof).map(|item| item.path.as_path())) .collect(); let mut immutable_stream_prefixes = BTreeMap::::new(); for range in &trace.stream_reads { if !immutable.contains(&range.path) || whole_files.contains(range.path.as_path()) { continue; } let end = range .offset .checked_add(range.bytes) .and_then(|end| usize::try_from(end).ok()) .filter(|&end| project.file(&range.path).is_some_and(|file| end <= file.data.len())) .ok_or("checkpoint stream range exceeds its captured input")?; let prefix = immutable_stream_prefixes.entry(range.path.clone()).or_default(); *prefix = (*prefix).max(end); } let immutable_sizes = size_only_inputs(project, trace, calls); Ok(Self { original: AttemptRequest::from(request), project: project.clone(), initial, entry: entry.to_path_buf(), nested_source: None, immutable, immutable_sizes, immutable_stream_prefixes, generated, lookups: trace.lookups.clone(), stream_reads: trace.stream_reads.clone(), format_input_bindings: trace.format_input_bindings.clone(), clock_environment: (!trace.file_modifications.is_empty()).then(date_environment), }) } fn allow_nested_source(&mut self, path: &Path, trace: &ResourceTrace, host: &RecordingHost<'_>) -> bool { let Some(file) = self.project.file(path) else { return false }; // The scanner pins its loaded prefix. A size query also pins the // observed byte count. Other content reads still pin the full input. let Some(observations) = host.rebindable_source_observations(&file.version) else { return false; }; if trace.stream_reads.iter().any(|read| read.path == path) || trace.file_modifications.iter().any(|read| read.path == path) || trace.generated_lookups.iter().any(|read| read.target == path) { return false; } self.nested_source = Some(NestedSourceGuard { path: path.to_path_buf(), observed_size: observations.size, }); true } fn verify_project<'a>( &self, request: &'a CompileRequest, ) -> Result<&'a ProjectSnapshot, String> { let old = &self.original; if old.input != request.input || old.output != request.output || old.entry != request.entry || old.target != request.target || old.etex != request.etex || old.input_profile != request.input_profile || old.translation_file != request.translation_file || old.time != request.time || old.limits != request.limits || old.terminal != request.terminal { return Err("checkpoint job parameters changed".into()); } let current = request .project .as_deref() .ok_or("checkpoint requires an atomic project")?; if !self.project.same_lookup_configuration(current)? { return Err("checkpoint lookup configuration changed".into()); } // An immutable source's recorded size can rule out the checkpoint // before drafting or replay. A changed namespace still goes through // the live lookup and all successful candidates replay their calls. if let Some(source) = &self.nested_source && let Some(expected) = source.observed_size && let Some(file) = current.file(&source.path) && file.version.bytes != expected && self.project.immutable_paths().eq(current.immutable_paths()) { return Err(format!("checkpoint file size changed: {}", source.path.display())); } for path in &self.immutable { let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and( |(old, new)| { old.version == new.version || self.nested_source.as_ref().is_some_and(|source| &source.path == path) || self.immutable_sizes.get(path) == Some(&new.version.bytes) || self.immutable_stream_prefixes.get(path).is_some_and(|&end| { new.data.get(..end) == Some(&old.data[..end]) }) }, ); if !same_bytes || self.project.modification_time(path) != current.modification_time(path) { return Err(format!( "checkpoint observed input changed: {}", path.display() )); } } if self .clock_environment .as_ref() .is_some_and(|old| *old != date_environment()) { return Err("checkpoint file-date environment changed".into()); } Ok(current) } fn verify_replayed_inputs(&self, files: &Files, current: &ProjectSnapshot) -> Result<(), CompileError> { if files.resource_trace().stream_reads != self.stream_reads { return Err(CompileError::Host("checkpoint replayed stream reads changed".into())); } if !self.project.immutable_paths().eq(current.immutable_paths()) { self.verify_replayed_lookups(files)?; } Ok(()) } fn verify_replayed_lookups(&self, files: &Files) -> Result<(), CompileError> { let trace = files.resource_trace(); if trace.lookups != self.lookups || !trace.read_errors.is_empty() || !trace.namespace_capture_failures.is_empty() { return Err(CompileError::Host( "checkpoint replayed lookup changed".into(), )); } Ok(()) } fn verify( &self, request: &CompileRequest, world: &FileWorld, preparation: &HostPreparation, ) -> Result<(), String> { let current = self.verify_project(request)?; if self.format_input_bindings != world.trace().format_input_bindings { return Err("checkpoint format input bindings changed".into()); } if world.trace().reads.first() != current.file(&self.entry).map(|file| &file.version) { return Err("checkpoint entry resolved to a different path".into()); } let current = preparation .generated_initial .as_ref() .ok_or("checkpoint requires generated versions observed under the job lock")?; if self.initial.cwd() != current.cwd() { return Err("generated initial workdir differs from the actual host".into()); } for path in self.initial.files().keys().chain(current.files().keys()) { let before = self.initial.files().get(path); let after = current.files().get(path); let same_presence = before.map(Option::is_some) == after.map(Option::is_some); if !same_presence || (self.generated.contains(path) && before != after) { return Err(format!( "generated initial role or version mismatch: {}", path.display() )); } } Ok(()) } } #[cfg(test)] const PREFIX: &str = concat!( "\\catcode123=1 \\catcode125=2\n", "\\input library.tex\n", "\\openin3=optional.tex \\ifeof3 \\message{MISSING}\\else \\message{PRESENT}\\fi \\closein3\n", "\\immediate\\openout1=entry.aux\n", "\\pdfcatalog{/Lang (en)}\n", "\\immediate\\write1{\\value}\\relax\n", "\\message{CHECKPOINT}\\relax\n", ); #[cfg(test)] const TAIL: &str = concat!( "\\immediate\\write1{old tail}\n", "\\openin2=entry.aux \\read2 to\\firstline \\read2 to\\secondline \\closein2\\relax\n", "\\openin4=seed.aux \\read4 to\\seedline \\closein4\\relax\n", "\\message{SEED: \\seedline}\\relax\n", "\\pdfcatalog{/PageLayout /SinglePage}\n", "\\message{READ: \\firstline/\\secondline}\\relax\n", "\\shipout\\hbox{\\vrule width2pt height1pt}\n", "\\immediate\\closeout1 \\end\n", ); #[test] fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejection() { let cwd = std::env::temp_dir().join(format!("texrra-guard-{}", std::process::id())); fs::create_dir(&cwd).unwrap(); let cwd = cwd.canonicalize().unwrap(); let entry = cwd.join("entry.tex"); let library = cwd.join("library.tex"); let unrelated = cwd.join("unread.tex"); let aux = cwd.join("entry.aux"); let seed = cwd.join("seed.aux"); fs::write(&seed, b"prior job\n").unwrap(); let output_paths = || ["entry.aux", "entry.log", "entry.pdf"].map(|name| fs::read(cwd.join(name)).unwrap()); let mut world = WorldConfig::new(&cwd); world.input_policy = InputPolicy::Tex; let definition = ProjectDefinition { configuration: world.clone(), revision: 1, roots: BTreeSet::from([cwd.clone()]), files: BTreeMap::from([ ( entry.clone(), Arc::from(format!("{PREFIX}{TAIL}").into_bytes()), ), (library.clone(), Arc::from(br"\def\value{A}".as_slice())), (unrelated.clone(), Arc::from(b"unread original".as_slice())), ]), directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([cwd.clone()]), generated: BTreeSet::from([aux.clone(), seed.clone()]), }; let project = ProjectSnapshot::new(definition.clone()).unwrap(); let mut request = CompileRequest::new( world, "entry.tex", "entry.pdf", JobTime::new(2026, 11, 18, 1000) .unwrap() .with_pdf_clock(0, 0) .unwrap(), ) .with_project(project.clone()) .observe_generated_initial(); request.entry = Entry::Initex; NativeCompiler::default().compile(request.clone()).unwrap(); let cancellation = Cancellation::default(); let PreparedJob { executor, source, mut files, .. } = prepare( &request, false, None, &cancellation, &mut AttemptEvidence::new(1), ) .unwrap(); let initial = files.preparation().generated_initial.clone().unwrap(); let mut recording = checkpoint_probe::RecordingHost::new(&mut files); let (executed, checkpoint) = executor .unwrap() .run_capturing_entry(source, &mut recording, PREFIX.len() - 25, |host| { ( host.capture(), host.resource_usage().unwrap().unwrap(), host.generated_outputs().clone(), ) }); assert!(executed.is_ok()); let (checkpoint, (recorded, usage, written)) = checkpoint.unwrap(); let (calls, trace) = recorded.unwrap(); assert_eq!(usage.open_outputs, Some(1)); assert!( trace .lookups .iter() .any(|lookup| lookup.name == "optional.tex" && lookup.resolved.is_none()) ); let guard = PrefixInputGuard::capture(&request, &entry, &trace, &calls, &written, initial).unwrap(); assert!(guard.generated.contains(&aux)); assert!(!guard.generated.contains(&seed)); assert!(guard.immutable.contains(&library)); assert!(!guard.immutable.contains(&unrelated)); assert!(!guard.immutable.contains(&entry)); files.finish().unwrap(); drop(files); let guarded = |candidate: &CompileRequest, evidence: &mut AttemptEvidence, effects| { prepare_checked( candidate, false, None, &cancellation, evidence, Some(Box::new(|world, prep| { guard.verify(candidate, world, prep)?; let source = world.project().unwrap().file(&entry).unwrap(); if !checkpoint.accepts_entry_bytes(&entry.to_string_lossy(), &source.data) { return Err("checkpoint entry prefix changed".into()); } Ok(()) })), effects, KernelPreparation::Resume, ) }; let rejected = |candidate: &CompileRequest, reason: &str| { let saved = output_paths(); let mut evidence = AttemptEvidence::new(2); let error = guarded(candidate, &mut evidence, EffectMode::Draft) .err() .unwrap(); assert!(error.to_string().contains(reason), "{error}"); assert_eq!( evidence.host_preparation.phase, HostPreparationPhase::GeneratedInitial ); assert_eq!(output_paths(), saved); eprintln!("rejected before transcript and generated writes: {error}"); }; let changed_library = project .with_file_edits( 2, BTreeMap::from([(library.clone(), Arc::from(br"\def\value{B}".as_slice()))]), ) .unwrap(); rejected( &request.clone().with_project(changed_library.clone()), "observed input changed", ); let changed_prefix = project .with_file_edits( 5, BTreeMap::from([( entry.clone(), Arc::from( format!("{}{TAIL}", PREFIX.replace("CHECKPOINT", "CHECKFORGE")).into_bytes(), ), )]), ) .unwrap(); rejected( &request.clone().with_project(changed_prefix), "entry prefix changed", ); let mut changed_namespace = definition; changed_namespace.revision = 3; changed_namespace .directories .insert(cwd.join("new-directory")); rejected( &request .clone() .with_project(ProjectSnapshot::new(changed_namespace).unwrap()), "lookup configuration changed", ); let mut changed_clock = request.clone(); changed_clock.time = JobTime::new(2026, 11, 18, 1001).unwrap(); rejected(&changed_clock, "job parameters changed"); let old_aux = fs::read(&aux).unwrap(); fs::write(&aux, b"externally edited auxiliary file").unwrap(); rejected(&request, "generated initial role or version mismatch"); fs::write(&aux, &old_aux).unwrap(); let edited = project .with_file_edits( 4, BTreeMap::from([ ( entry.clone(), Arc::from( format!( "{PREFIX}{}", TAIL.replace("old tail", "new tail") .replace("width2pt", "width3pt") ) .into_bytes(), ), ), (unrelated, Arc::from(b"unread modified".as_slice())), ]), ) .unwrap(); let edited_request = request.clone().with_project(edited); let saved = output_paths(); let PreparedJob { source, mut files, .. } = guarded( &edited_request, &mut AttemptEvidence::new(3), EffectMode::Draft, ) .unwrap(); for call in &calls { call.replay(&mut files, None).unwrap(); } assert_eq!( files.resource_usage().unwrap().unwrap().open_outputs, Some(1) ); assert_eq!(output_paths(), saved); let draft_execution = checkpoint .resume_after_host_replay(source, &mut files, cancellation.clone()) .unwrap() .unwrap(); let draft_trace = files.resource_trace().clone(); files.finish().unwrap(); let draft_paths = files.draft_paths(); assert_eq!(draft_paths.len(), 3); assert_eq!(output_paths(), saved); let draft_aux = fs::read(&draft_paths[&aux]).unwrap(); let draft_log = fs::read(&draft_paths[&cwd.join("entry.log")]).unwrap(); let (ledger, draft_ledger) = draft_paths .iter() .find(|(dest, _)| { dest.extension() .is_some_and(|extension| extension == "json") }) .unwrap(); let saved_ledger = fs::read(ledger).unwrap(); let draft_ledger = fs::read(draft_ledger).unwrap(); assert_ne!(draft_ledger, saved_ledger); drop(files); assert!(draft_paths.values().all(|path| !path.exists())); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), saved_ledger); let stage_revision = |session: &NativeSession| { let revision = session.start(); let PreparedJob { source, mut files, .. } = guarded( &edited_request, &mut AttemptEvidence::new(revision.revision()), EffectMode::Draft, ) .unwrap(); for call in &calls { call.replay(&mut files, None).unwrap(); } let result = revision .resume_entry_after_host_replay(&checkpoint, source, &mut files) .unwrap() .unwrap(); assert_eq!(result.execution, draft_execution); let pages = result.execution.shipout_display_lists().unwrap(); let source_map = texrra_tex_core::source_map::SourceMap::from_revision(&result, &pages).unwrap(); let pdf = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document( &pages, result.execution.state.pdf_final_options(), ) .unwrap(); assert!(pdf.diagnostics.is_empty(), "{:?}", pdf.diagnostics); files.finish().unwrap(); let prepared_pdf = PreparedOutput::write(&cwd.join("entry.pdf"), &pdf.bytes).unwrap(); let staged = files .seal_draft( Some(prepared_pdf), &DraftSyncQueue::default(), &Cancellation::default(), ) .unwrap() .unwrap(); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), saved_ledger); (result, source_map, pdf.bytes, staged) }; let session = NativeSession::default(); let (stale, _, _, staged) = stage_revision(&session); assert!(session.start().revision() > stale.revision); let unexpected_publication = || -> u64 { panic!("rejected draft exposed a document") }; assert_eq!( staged .publish_current(&session, stale.revision, unexpected_publication) .unwrap(), None ); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), saved_ledger); let (cancelled, _, _, staged) = stage_revision(&session); session.cancel(cancelled.revision); assert_eq!( staged .publish_current(&session, cancelled.revision, unexpected_publication) .unwrap(), None ); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), saved_ledger); let (conflicted, _, _, staged) = stage_revision(&session); fs::write(ledger, b"external ledger edit").unwrap(); let error = staged .publish_current(&session, conflicted.revision, unexpected_publication) .unwrap_err(); assert!( error.contains("native draft destination changed"), "{error}" ); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), b"external ledger edit"); fs::write(ledger, &saved_ledger).unwrap(); let (conflicted, _, _, staged) = stage_revision(&session); fs::write(&seed, b"external input edit\n").unwrap(); let error = staged .publish_current(&session, conflicted.revision, unexpected_publication) .unwrap_err(); assert!(error.contains("native draft input changed"), "{error}"); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), saved_ledger); assert_eq!(fs::read(&seed).unwrap(), b"external input edit\n"); fs::write(&seed, b"prior job\n").unwrap(); let (current, resumed_source_map, resumed_pdf, staged) = stage_revision(&session); let lock_error = guarded( &edited_request, &mut AttemptEvidence::new(current.revision), EffectMode::Draft, ) .err() .unwrap(); assert!( lock_error.to_string().contains("already in use"), "{lock_error}" ); let exposed = staged .publish_current(&session, current.revision, || { assert_eq!(fs::read(cwd.join("entry.pdf")).unwrap(), resumed_pdf); current.revision }) .unwrap(); assert_eq!(exposed, Some(current.revision)); let resumed_output = output_paths(); assert_eq!(resumed_output[0], draft_aux); assert_eq!(resumed_output[1], draft_log); assert_eq!(resumed_output[2], resumed_pdf); assert_ne!(resumed_output[2], saved[2]); assert_eq!(fs::read(ledger).unwrap(), draft_ledger); for (name, bytes) in ["entry.aux", "entry.log", "entry.pdf"] .into_iter() .zip(&saved) { fs::write(cwd.join(name), bytes).unwrap(); } fs::write(ledger, &saved_ledger).unwrap(); let PreparedJob { source, mut files, .. } = guarded( &edited_request, &mut AttemptEvidence::new(4), EffectMode::Draft, ) .unwrap(); for call in &calls { call.replay(&mut files, None).unwrap(); } let cancelled = Cancellation::default(); cancelled.cancel(); let error = checkpoint .resume_after_host_replay(source, &mut files, cancelled) .unwrap() .unwrap_err(); assert!(error.error.message.contains("cancelled"), "{error:?}"); assert!(files.finish_failed().is_empty()); let discarded = files.draft_paths(); drop(files); assert!(discarded.values().all(|path| !path.exists())); assert_eq!(output_paths(), saved); assert_eq!(fs::read(ledger).unwrap(), saved_ledger); let PreparedJob { source, mut files, .. } = guarded( &edited_request, &mut AttemptEvidence::new(5), EffectMode::Live, ) .unwrap(); assert!(checkpoint.accepts_entry(&source)); for call in &calls { call.replay(&mut files, None).unwrap(); } let resumed_usage: HostResourceUsage = files.resource_usage().unwrap().unwrap(); assert_eq!(resumed_usage.open_outputs, Some(1)); let resumed = checkpoint .resume_after_host_replay(source, &mut files, cancellation.clone()) .unwrap() .unwrap(); let trace = files.resource_trace().clone(); files.finish().unwrap(); drop(files); let resumed_aux = fs::read(&aux).unwrap(); let resumed_log = fs::read(cwd.join("entry.log")).unwrap(); assert_eq!(resumed_aux, b"A\nnew tail\n"); fs::write(&aux, &old_aux).unwrap(); let full = NativeCompiler::default() .compile(edited_request.clone()) .unwrap(); assert_eq!(resumed, full.execution.execution); assert_eq!(Some(trace), full.execution.execution_resources); assert_eq!(resumed.shipout_display_lists().unwrap(), full.pages); assert_eq!(resumed_aux, fs::read(&aux).unwrap()); assert_eq!(resumed_log, fs::read(cwd.join("entry.log")).unwrap()); assert_eq!(draft_execution, full.execution.execution); assert_eq!(Some(draft_trace), full.execution.execution_resources); assert_eq!(draft_aux, resumed_aux); assert_eq!(draft_log, resumed_log); assert_eq!(draft_ledger, fs::read(ledger).unwrap()); assert_eq!(resumed_pdf.as_slice(), full.pdf.as_deref().unwrap()); assert_eq!(resumed_source_map.sources, full.source_map.sources); assert_eq!(resumed_source_map.pages, full.source_map.pages); assert_eq!(resumed_output, output_paths()); let fallback = NativeCompiler::default() .compile(request.clone().with_project(changed_library.clone())) .unwrap(); assert_eq!(fallback.pages.len(), 1); assert_eq!(fs::read(&aux).unwrap(), b"B\nold tail\n"); fs::write(&aux, &old_aux).unwrap(); let compiler = NativeCompiler::default().with_entry_checkpoints(PREFIX.len() - 25); let first = compiler.compile(request.clone()).unwrap(); assert!(first.entry_checkpoint_work.captured_frontier.is_some()); struct Supersede(NativeCompiler); impl CompileObserver for Supersede { fn stage(&self, _: u64, stage: CompileStage) -> Result<(), String> { if stage == CompileStage::ReadyToPublish { self.0.start(); } Ok(()) } } let before = output_paths(); let mut cancelled_request = edited_request.clone(); cancelled_request.observer = Some(Arc::new(Supersede(compiler.clone()))); let failure = compiler.compile_detailed(cancelled_request).err().unwrap(); assert!(matches!(failure.error, CompileError::Cancelled)); assert!(Arc::ptr_eq(&compiler.latest().unwrap(), &first)); assert_eq!(output_paths(), before); let resumed = compiler.compile(edited_request.clone()).unwrap(); assert!(resumed.entry_checkpoint_work.reused_steps > 0); assert_eq!(resumed.entry_checkpoint_work.replayed_calls, calls.len()); assert_eq!(resumed.pdf, full.pdf); let pdf = lopdf::Document::load_mem(resumed.pdf.as_deref().unwrap()).unwrap(); let catalog = pdf.catalog().unwrap(); assert_eq!(catalog.get(b"Lang").unwrap().as_str().unwrap(), b"en"); assert_eq!( catalog.get(b"PageLayout").unwrap().as_name().unwrap(), b"SinglePage" ); assert_eq!(resumed.pages, full.pages); assert_eq!(resumed.source_map.pages, full.source_map.pages); assert!(Arc::ptr_eq(&compiler.latest().unwrap(), &resumed)); let rebuilt = compiler .compile(request.clone().with_project(changed_library)) .unwrap(); assert_eq!(rebuilt.entry_checkpoint_work.reused_steps, 0); assert!( rebuilt .entry_checkpoint_work .rejection .as_deref() .unwrap() .contains("observed input changed") ); assert_eq!(rebuilt.execution.execution, fallback.execution.execution); assert_eq!(fs::read(&aux).unwrap(), b"B\nold tail\n"); fs::write(&aux, &old_aux).unwrap(); let automatic = NativeCompiler::default().with_automatic_entry_checkpoints(); let seeded = automatic.compile(request.clone()).unwrap(); let latest = seeded.entry_checkpoint_work.captured_frontier.unwrap(); let edited = automatic.compile(edited_request).unwrap(); let selected = edited.entry_checkpoint_work.reused_frontier.unwrap(); assert!( selected < latest, "selected {selected} from latest {latest}" ); assert!(edited.entry_checkpoint_work.reused_steps > 0); assert_eq!(edited.pdf, full.pdf); assert_eq!(edited.source_map.pages, full.source_map.pages); let before_first = request .project .as_ref() .unwrap() .with_file_edits( 6, BTreeMap::from([( entry, Arc::from(format!("% preface\n{PREFIX}{TAIL}").into_bytes()), )]), ) .unwrap(); let early_request = request.with_project(before_first); let early = automatic.compile(early_request.clone()).unwrap(); assert_eq!(early.entry_checkpoint_work.reused_frontier, None); assert!( early .entry_checkpoint_work .rejection .as_deref() .unwrap() .contains("entry prefix changed") ); let independent = NativeCompiler::default().compile(early_request).unwrap(); assert_eq!(early.pdf, independent.pdf); assert_eq!(early.source_map.pages, independent.source_map.pages); eprintln!( "accepted edited suffix and unread resource, replayed {} actual host calls, full fallback consumes changed library", calls.len() ); } #[test] fn immutable_file_creation_and_removal_replay_real_lookup_results() { use texrra_tex_core::resources::SearchPath; let cwd = std::env::temp_dir().join(format!("texrra-file-revisions-{}", std::process::id())); fs::create_dir(&cwd).unwrap(); let cwd = cwd.canonicalize().unwrap(); let vendor = cwd.join("vendor"); let entry = cwd.join("entry.tex"); let aux = cwd.join("entry.aux"); let extra = cwd.join("unread.tex"); let settings = cwd.join("settings.tex"); let vendor_settings = vendor.join("settings.tex"); let tag = cwd.join("tag.tex"); let vendor_tag = vendor.join("tag.tex"); let prefix = concat!( "\\catcode123=1 \\catcode125=2\n", "\\def\\value{10}\n", "\\openin3=settings.tex \\ifeof3\\else\\input settings.tex \\fi\\closein3\n", "\\edef\\filesize{\\pdffilesize{tag.tex}}\n", "\\immediate\\openout1=entry.aux\n", "\\immediate\\write1{unchanged journal}\\relax\n", "\\message{CHECKPOINT}\\relax\n", ); let tail = "\\shipout\\hbox{\\vrule width\\value pt height1pt}\n\\immediate\\closeout1\\end\n"; let world = { let mut world = WorldConfig::new(&cwd); world.paths.insert( ResourceKind::Tex, vec![ SearchPath::directory(&cwd, false), SearchPath::directory(&vendor, false), ], ); world }; let mut project = ProjectSnapshot::new(ProjectDefinition { configuration: world.clone(), revision: 1, roots: BTreeSet::from([cwd.clone()]), files: BTreeMap::from([ ( entry.clone(), Arc::from(format!("{prefix}{tail}").into_bytes()), ), (vendor_tag.clone(), Arc::from(b"42".as_slice())), ]), directories: BTreeSet::from([vendor]), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([cwd.clone()]), generated: BTreeSet::from([aux.clone()]), }) .unwrap(); assert!( project .with_file_changes( 2, BTreeMap::from([(aux.clone(), Some(Arc::from(b"source collision".as_slice())))]), ) .is_err() ); assert!( project .with_file_changes( 2, BTreeMap::from([(cwd.join("missing-parent/entry.tex"), Some(Arc::from([])))]), ) .is_err() ); let mut request = CompileRequest::new( world, "entry.tex", "entry.pdf", JobTime::new(2026, 11, 20, 540) .unwrap() .with_pdf_clock(0, 0) .unwrap(), ) .observe_generated_initial(); request.entry = Entry::Initex; request.etex = true; NativeCompiler::default() .compile(request.clone().with_project(project.clone())) .unwrap(); let journal = fs::read(&aux).unwrap(); let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() - 2); let revisions = [ ("cold", None, false, None, 10), ( "unrelated appeared", Some((&extra, Some(b"unused".as_slice()))), true, None, 10, ), ("unrelated removed", Some((&extra, None)), true, None, 10), ( "missing dependency appeared", Some((&vendor_settings, Some(br"\def\value{20}".as_slice()))), false, Some("open_in changed"), 20, ), ( "higher priority dependency appeared", Some((&settings, Some(br"\def\value{30}".as_slice()))), false, Some("open_in changed"), 30, ), ( "dependency edited", Some((&settings, Some(br"\def\value{40}".as_slice()))), false, Some("observed input changed"), 40, ), ( "removed dependency exposes fallback", Some((&settings, None)), false, Some("observed input changed"), 20, ), ( "removed fallback", Some((&vendor_settings, None)), false, Some("observed input changed"), 10, ), ( "equal-size result came from a new path", Some((&tag, Some(b"59".as_slice()))), false, Some("replayed lookup changed"), 10, ), ( "unrelated file appeared again", Some((&extra, Some(b"new unused".as_slice()))), true, None, 10, ), ]; let mut pdfs = BTreeMap::new(); for (index, (label, edit, reuse, rejection, width)) in revisions.into_iter().enumerate() { if let Some((path, bytes)) = edit { let previous = project.clone(); project = project .with_file_changes( index as u64 + 1, BTreeMap::from([(path.clone(), bytes.map(Arc::from))]), ) .unwrap(); if label == "unrelated appeared" { assert!(previous.file(path).is_none()); assert!(project.file(path).is_some()); } } let next = request.clone().with_project(project.clone()); let result = compiler.compile(next.clone()).unwrap(); let work = &result.entry_checkpoint_work; assert_eq!(work.reused_steps > 0, reuse, "{label}: {work:?}"); if let Some(expect) = rejection { assert!( work.rejection .as_deref() .is_some_and(|e| e.contains(expect)), "{label}: {work:?}" ); } assert_eq!(fs::read(&aux).unwrap(), journal, "{label}"); let full = NativeCompiler::default().compile(next).unwrap(); assert_eq!(full.entry_checkpoint_work.reused_steps, 0, "{label}"); assert_eq!(result.pdf, full.pdf, "{label}"); assert_eq!(result.source_map.pages, full.source_map.pages, "{label}"); assert_eq!( result.source_map.sources, full.source_map.sources, "{label}" ); assert_eq!( result.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages, "{label}", ); assert_eq!( result.execution.execution, full.execution.execution, "{label}" ); assert_eq!( result.resources.trace.lookups, full.resources.trace.lookups, "{label}" ); assert_eq!(fs::read(&aux).unwrap(), journal, "{label}"); if let Some(previous) = pdfs.insert(width, result.pdf.clone()) { assert_eq!(previous, result.pdf, "{label}"); } eprintln!("{label}: {work:?}"); } assert_eq!(pdfs.values().collect::>().len(), 4); } #[test] fn automatic_checkpoints_refresh_the_previous_edit_line_after_a_child_edit() { let mut schedule = CaptureSchedule::new(400, None, Some(290)); assert!(schedule.select(215, 0).unwrap().early); let edit = schedule.select(290, 0).unwrap(); assert!(edit.edit && !edit.early); assert!(schedule.select(345, 0).is_none()); assert!(schedule.select(345, 1).unwrap().page); let cwd = std::env::temp_dir().join(format!("texrra-edit-line-{}", std::process::id())); fs::create_dir(&cwd).unwrap(); let cwd = cwd.canonicalize().unwrap(); let entry = cwd.join("main.tex"); let child = cwd.join("child.tex"); let source_prefix = format!( "\\catcode123=1 \\catcode125=2\n{}\\input child.tex\n{}", "\\advance\\count0 by 1\\relax\n".repeat(40), "\\advance\\count2 by 1\\relax\n".repeat(18), ); let edited_line_start = source_prefix.len(); let original = format!( "{source_prefix}\\shipout\\hbox{{\\vrule width1pt height\\heightfromchild pt}}\n{}\\end\n", "\\advance\\count1 by 1\\relax\n".repeat(5), ); let mut world = WorldConfig::new(&cwd); world.input_policy = InputPolicy::Tex; let project = ProjectSnapshot::new(ProjectDefinition { configuration: world.clone(), revision: 1, roots: BTreeSet::from([cwd.clone()]), files: BTreeMap::from([ (entry.clone(), Arc::from(original.as_bytes())), ( child.clone(), Arc::from(b"\\def\\heightfromchild{1}\n".as_slice()), ), ]), directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([cwd.clone()]), generated: BTreeSet::new(), }) .unwrap(); let mut request = CompileRequest::new( world, "main.tex", "main.pdf", JobTime::new(2026, 11, 20, 540) .unwrap() .with_pdf_clock(0, 0) .unwrap(), ) .with_project(project.clone()) .observe_generated_initial(); request.entry = Entry::Initex; NativeCompiler::default().compile(request.clone()).unwrap(); let session = NativeCompiler::default().with_automatic_entry_checkpoints(); session.compile(request.clone()).unwrap(); let entry_edit = project .with_file_edits( 2, BTreeMap::from([( entry.clone(), Arc::from(original.replace("width1pt", "width2pt").into_bytes()), )]), ) .unwrap(); session .compile(request.clone().with_project(entry_edit.clone())) .unwrap(); let child_edit = entry_edit .with_file_edits( 3, BTreeMap::from([(child, Arc::from(b"\\def\\heightfromchild{3}\n".as_slice()))]), ) .unwrap(); let child_result = session .compile(request.clone().with_project(child_edit.clone())) .unwrap(); let child_work = &child_result.entry_checkpoint_work; assert!( child_work.reused_frontier.unwrap() < edited_line_start, "{child_work:?}" ); let revision = child_edit .with_file_edits( 4, BTreeMap::from([( entry, Arc::from(original.replace("width1pt", "width4pt").into_bytes()), )]), ) .unwrap(); let request = request.with_project(revision); let updated = session.compile(request.clone()).unwrap(); let full = NativeCompiler::default().compile(request).unwrap(); let work = &updated.entry_checkpoint_work; assert_eq!(work.reused_frontier, Some(edited_line_start), "{work:?}"); assert!(work.reused_steps > child_work.reused_steps, "{work:?}"); assert!( work.retained_checkpoints <= 2 * SOURCE_INTERVALS, "{work:?}" ); assert!(updated.pages[0].items.iter().any(|item| matches!( item, texrra_tex_core::render::DisplayItem::Rule { width, height, .. } if (*width, *height) == (4 * 65_536, 3 * 65_536) ))); assert_eq!(updated.pdf, full.pdf); assert_eq!(updated.source_map.sources, full.source_map.sources); assert_eq!(updated.source_map.pages, full.source_map.pages); assert!(updated.execution.execution == full.execution.execution); } #[test] fn generated_input_change_uses_a_checkpoint_before_the_read() { let cwd = std::env::temp_dir().join(format!("texrra-generated-prefix-{}", std::process::id())); fs::create_dir(&cwd).unwrap(); let cwd = cwd.canonicalize().unwrap(); let entry = cwd.join("main.tex"); let aux = cwd.join("observed.aux"); fs::write(&aux, b"\\def\\widthfromaux{11}\n").unwrap(); let source = format!( "\\catcode123=1 \\catcode125=2\n{}\\input observed.aux\n{}\\shipout\\hbox{{\\vrule width\\widthfromaux pt height1pt}}\n\\end", "\\advance\\count0 by 1\\relax\n".repeat(20), "\\advance\\count0 by 1\\relax\n".repeat(12), ); let input_offset = source.find("\\input observed.aux").unwrap(); let mut world = WorldConfig::new(&cwd); world.input_policy = texrra_tex_core::resources::InputPolicy::Tex; let project = ProjectSnapshot::new(ProjectDefinition { configuration: world.clone(), revision: 1, roots: BTreeSet::from([cwd.clone()]), files: BTreeMap::from([(entry, Arc::from(source.into_bytes()))]), directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([cwd.clone()]), generated: BTreeSet::from([aux.clone()]), }) .unwrap(); let mut request = CompileRequest::new( world, "main.tex", "main.pdf", JobTime::new(2026, 11, 20, 540) .unwrap() .with_pdf_clock(0, 0) .unwrap(), ) .with_project(project) .observe_generated_initial(); request.entry = Entry::Initex; let session = NativeCompiler::default().with_automatic_entry_checkpoints(); let original = session.compile(request.clone()).unwrap(); let last = original.entry_checkpoint_work.captured_frontier.unwrap(); assert!(last > input_offset); fs::write(&aux, b"\\def\\widthfromaux{22}\n").unwrap(); let updated = session.compile(request.clone()).unwrap(); let full = NativeCompiler::default().compile(request).unwrap(); let work = &updated.entry_checkpoint_work; assert!(work.reused_steps > 0, "{work:?}"); assert!(work.reused_frontier.unwrap() < last, "{work:?}"); for (document, width) in [(&original, 11_i64), (&updated, 22)] { let rules: Vec<_> = document .pages .iter() .flat_map(|page| &page.items) .filter_map(|item| match item { texrra_tex_core::render::DisplayItem::Rule { width, height, .. } => { Some((*width, *height)) } _ => None, }) .collect(); assert_eq!(rules, [(width * 65_536, 65_536)]); } assert_ne!(updated.pdf, original.pdf); assert_eq!(updated.pdf, full.pdf); assert_eq!(updated.source_map.sources, full.source_map.sources); assert_eq!(updated.source_map.pages, full.source_map.pages); assert!(updated.execution.execution == full.execution.execution); let aux_source = |result: &CompiledDocument| { let (id, source) = result.execution.execution.sources.iter().enumerate() .find(|(_, source)| Path::new(&source.name) == aux).unwrap(); (source.clone(), result.execution.source_versions[id].clone()) }; let (old_source, old_version) = aux_source(&original); let (current_source, current_version) = aux_source(&updated); assert!(!Arc::ptr_eq(&old_source, ¤t_source)); assert_eq!(old_source.data, b"\\def\\widthfromaux{11}\n"); assert_eq!(current_source.data, b"\\def\\widthfromaux{22}\n"); assert_ne!(old_version, current_version); assert_eq!(fs::read(&aux).unwrap(), b"\\def\\widthfromaux{22}\n"); } #[test] fn automatic_checkpoints_follow_successive_edits_at_different_frontiers() { let cwd = std::env::temp_dir().join(format!("texrra-rolling-{}", std::process::id())); fs::create_dir(&cwd).unwrap(); let cwd = cwd.canonicalize().unwrap(); let entry = cwd.join("rolling.tex"); let aux = cwd.join("rolling.aux"); let mut original = "\\catcode123=1 \\catcode125=2\n\\immediate\\openout1=rolling.aux\n".to_owned(); let mut stable_aux = String::new(); for width in 10..20 { original.push_str(&format!( "\\immediate\\write1{{page {width}}}\n\\shipout\\hbox{{\\vrule width{width}pt height1pt}}\n" )); stable_aux.push_str(&format!("page {width}\n")); } original.push_str("\\immediate\\closeout1 \\end\n"); fs::write(&aux, &stable_aux).unwrap(); let mut world = WorldConfig::new(&cwd); world.input_policy = InputPolicy::Tex; let project = ProjectSnapshot::new(ProjectDefinition { configuration: world.clone(), revision: 1, roots: BTreeSet::from([cwd.clone()]), files: BTreeMap::from([(entry.clone(), Arc::from(original.as_bytes()))]), directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([cwd.clone()]), generated: BTreeSet::from([aux.clone()]), }) .unwrap(); let mut request = CompileRequest::new( world, "rolling.tex", "rolling.pdf", JobTime::new(2026, 11, 18, 1000) .unwrap() .with_pdf_clock(0, 0) .unwrap(), ) .with_project(project.clone()) .observe_generated_initial(); request.entry = Entry::Initex; let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); let original_result = compiler.compile(request.clone()).unwrap(); assert_eq!(original_result.pages.len(), 10); let one_page_changed = ShipoutLayoutWork { lowered_pages: 1, reused_pages: 9, }; let first_edit = original.replace("width10pt", "width22pt"); let edited_project = project .with_file_edits( 2, BTreeMap::from([(entry.clone(), Arc::from(first_edit.as_bytes()))]), ) .unwrap(); let first_request = request.clone().with_project(edited_project.clone()); let first = compiler.compile(first_request.clone()).unwrap(); let first_full = NativeCompiler::default().compile(first_request).unwrap(); assert_eq!(first.shipout_layout_work, one_page_changed); assert_eq!(first.pages, first_full.pages); let first_work = &first.entry_checkpoint_work; let first_frontier = first_work.reused_frontier.unwrap(); assert!(first_work.captured_frontier.unwrap() > first_frontier); assert!(first_work.replayed_calls > 0); assert!(first.execution.execution == first_full.execution.execution); assert_eq!(first.pdf, first_full.pdf); assert_eq!(first.source_map.pages, first_full.source_map.pages); assert_eq!(fs::read_to_string(&aux).unwrap(), stable_aux); let second_edit = first_edit.replace("width19pt", "width29pt"); let second_project = edited_project .with_file_edits( 3, BTreeMap::from([(entry.clone(), Arc::from(second_edit.as_bytes()))]), ) .unwrap(); let second_request = request.clone().with_project(second_project.clone()); let second = compiler.compile(second_request.clone()).unwrap(); let second_full = NativeCompiler::default().compile(second_request).unwrap(); assert_eq!(second.shipout_layout_work, one_page_changed); assert_eq!(second.pages, second_full.pages); assert_eq!(second_full.shipout_layout_work.reused_pages, 0); assert_eq!(second_full.shipout_layout_work.lowered_pages, second_full.pages.len()); let second_work = &second.entry_checkpoint_work; assert!(second_work.reused_frontier.unwrap() > original.find("width10pt").unwrap()); assert!(second_work.reused_steps > first_work.reused_steps); assert!(second_work.replayed_calls > first_work.replayed_calls); assert!((2..=2 * SOURCE_INTERVALS).contains(&second_work.retained_checkpoints)); assert_eq!(second.entry_checkpoint_work.rejection, None); assert!(second.execution.execution == second_full.execution.execution); assert_eq!( second.execution.source_versions, second_full.execution.source_versions ); assert_eq!( second.execution.execution_resources, second_full.execution.execution_resources ); assert_eq!(second.pdf, second_full.pdf); assert_eq!(second.source_map.pages, second_full.source_map.pages); assert_eq!(fs::read_to_string(&aux).unwrap(), stable_aux); assert_eq!( second .preview_since(Some(first.revision())) .unwrap() .pages .iter() .map(|page| page.index) .collect::>(), [9], ); let reverted = original.replace("width19pt", "width29pt"); let third_project = second_project .with_file_edits( 4, BTreeMap::from([(entry, Arc::from(reverted.into_bytes()))]), ) .unwrap(); let third_request = request.with_project(third_project); let third = compiler.compile(third_request.clone()).unwrap(); let third_full = NativeCompiler::default().compile(third_request).unwrap(); assert!( third.entry_checkpoint_work.reused_steps > first_work.reused_steps, "{:?}", third.entry_checkpoint_work ); assert_eq!(third.pdf, third_full.pdf); assert_eq!(third.source_map.pages, third_full.source_map.pages); assert_eq!(fs::read_to_string(&aux).unwrap(), stable_aux); } #[test] #[ignore = "requires the verified LaTeX format, A3 fixture and a dedicated output directory"] fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() { let cwd = PathBuf::from(std::env::var_os("TEXRRA_A3_CHECKPOINT_WORK").unwrap()); fs::create_dir(&cwd).unwrap(); let cwd = cwd.canonicalize().unwrap(); let format = PathBuf::from(std::env::var_os("TEXRRA_A3_CHECKPOINT_FORMAT").unwrap()); let resource_file = std::env::var_os("TEXRRA_A3_CHECKPOINT_FORMAT_RESOURCES").unwrap(); let manifest: serde_json::Value = serde_json::from_slice(&fs::read(resource_file).unwrap()).unwrap(); let roots: Vec = serde_json::from_value(manifest["texmf_roots"].clone()).unwrap(); let source = Path::new(env!("CARGO_MANIFEST_DIR")) .join("examples/native-format-stage/a3-pages/main.tex"); let original = fs::read_to_string(source).unwrap(); let marker = "This explicit page follows the naturally paginated material."; assert_eq!(original.matches(marker).count(), 1); let frontier = original.find(marker).unwrap(); let entry = cwd.join("main.tex"); fs::write(&entry, &original).unwrap(); let mut world = WorldConfig::from_environment(&cwd, roots.clone()).unwrap(); world.input_policy = InputPolicy::Tex; let mut request = CompileRequest::new( world.clone(), "main.tex", "main.pdf", JobTime::new(2026, 11, 18, 1000) .unwrap() .with_pdf_clock(0, 0) .unwrap(), ); request.entry = Entry::Format(format); request.etex = true; request.limits.steps = 600_000_000; let seed = NativeCompiler::default().compile(request.clone()).unwrap(); let mut files = BTreeMap::from([(entry.clone(), Arc::from(original.as_bytes()))]); for (path, captured) in seed.inputs.files() { if !path.starts_with(&cwd) { files.insert(path.to_owned(), captured.unwrap().data.clone()); } } for lookup in &seed.resources.trace.lookups { if let Some(path) = &lookup.resolved && !path.starts_with(&cwd) && !files.contains_key(path) { files.insert(path.clone(), Arc::from(fs::read(path).unwrap())); } } let mut coverage = BTreeSet::from_iter(roots); coverage.insert(cwd.clone()); for path in files.keys() { if !coverage.iter().any(|root| path.starts_with(root)) { coverage.insert(path.parent().unwrap().to_owned()); } } let aux = cwd.join("main.aux"); let project = ProjectSnapshot::new(ProjectDefinition { configuration: world, revision: 1, roots: coverage, files, directories: BTreeSet::new(), aliases: BTreeMap::new(), generated_roots: BTreeSet::from([cwd.clone()]), generated: BTreeSet::from([aux.clone()]), }) .unwrap(); let request = request .with_project(project.clone()) .observe_generated_initial(); let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); let mut previous = compiler.compile(request.clone()).unwrap(); assert!( (2..=2 * SOURCE_INTERVALS).contains(&previous.entry_checkpoint_work.retained_checkpoints), "{:?}", previous.entry_checkpoint_work, ); assert!(previous.entry_checkpoint_work.captured_frontier.unwrap() > frontier); assert_eq!(previous.pages.len(), 8); assert!(previous.pages == seed.pages); let mut visible = previous.preview_since(None).unwrap().pages; let baseline_aux = fs::read(&aux).unwrap(); for (index, replacement) in [ "This edited page follows the naturally paginated material.", "This revised page also uses the same open auxiliary stream.", ] .into_iter() .enumerate() { let edited = project .with_file_edits( index as u64 + 2, BTreeMap::from([( entry.clone(), Arc::from(original.replace(marker, replacement).into_bytes()), )]), ) .unwrap(); let edit_request = request.clone().with_project(edited); let resumed = compiler.compile(edit_request.clone()).unwrap(); let work = &resumed.entry_checkpoint_work; assert!( work.reused_steps > 700_000 && work.replayed_calls > 0, "{work:?}" ); assert!(work.rejection.is_none(), "{work:?}"); assert_eq!(work.reused_frontier, Some(frontier)); assert_eq!( resumed.pdf.as_deref().unwrap(), fs::read(cwd.join("main.pdf")).unwrap() ); assert_eq!(baseline_aux, fs::read(&aux).unwrap()); let log = fs::read(cwd.join("main.log")).unwrap(); let update = resumed.preview_since(Some(previous.revision())).unwrap(); assert_eq!(update.base_revision, Some(previous.revision())); assert_eq!(update.page_count, 8); assert_eq!( update.pages.iter().map(|p| p.index).collect::>(), vec![6] ); for page in update.pages { let index = page.index; visible[index] = page; } let full = NativeCompiler::default().compile(edit_request).unwrap(); assert!(resumed.execution.execution == full.execution.execution); assert_eq!( resumed.execution.source_versions, full.execution.source_versions ); assert_eq!( resumed.execution.execution_resources, full.execution.execution_resources ); assert!(resumed.pages == full.pages); assert_eq!(resumed.source_map.sources, full.source_map.sources); assert_eq!(resumed.source_map.pages, full.source_map.pages); assert_eq!(resumed.pdf, full.pdf); assert_eq!(visible, full.preview_since(None).unwrap().pages); assert_eq!(log, fs::read(cwd.join("main.log")).unwrap()); eprintln!( "A3 edit {} picked byte {} from {} checkpoints, skips {} of {} steps, replays {} host calls and replaces only page 7", index + 1, work.reused_frontier.unwrap(), work.retained_checkpoints, work.reused_steps, resumed.execution.execution.steps, work.replayed_calls ); previous = resumed; } }