2107 lines
77 KiB
Rust
2107 lines
77 KiB
Rust
//! 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,
|
|
};
|
|
use texrra_tex_core::{
|
|
execution::EntryCheckpoint,
|
|
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<usize>,
|
|
/// Checkpoints in the selected or freshly captured set.
|
|
pub retained_checkpoints: usize,
|
|
pub reused_frontier: Option<usize>,
|
|
pub reused_steps: usize,
|
|
pub replayed_calls: usize,
|
|
pub rejection: Option<String>,
|
|
}
|
|
|
|
pub(super) struct CheckpointCache {
|
|
minimum_frontier: Option<usize>,
|
|
published: Mutex<Option<Arc<PublishedCheckpoints>>>,
|
|
}
|
|
|
|
pub(super) struct PublishedCheckpoints {
|
|
current: Arc<CheckpointSet>,
|
|
previous_body: Option<Arc<CheckpointSet>>,
|
|
}
|
|
|
|
struct CachedCheckpoint {
|
|
entry: EntryCheckpoint,
|
|
guard: PrefixInputGuard,
|
|
replay_count: usize,
|
|
slots: CaptureSlots,
|
|
}
|
|
|
|
pub(super) struct CheckpointSet {
|
|
entries: Vec<Arc<CachedCheckpoint>>,
|
|
calls: Vec<Call>,
|
|
refresh_on_resume: bool,
|
|
edit_frontier: Option<usize>,
|
|
}
|
|
|
|
pub(super) struct SelectedCheckpoint {
|
|
set: Arc<CheckpointSet>,
|
|
index: usize,
|
|
}
|
|
|
|
const SOURCE_INTERVALS: usize = 4;
|
|
|
|
// 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<usize>,
|
|
pending_edit_frontier: Option<usize>,
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
struct CaptureSlots {
|
|
interval: usize,
|
|
early: bool,
|
|
page: bool,
|
|
edit: bool,
|
|
next_page: usize,
|
|
}
|
|
|
|
impl CaptureSchedule {
|
|
fn new(bytes: usize, fixed_frontier: Option<usize>, edit_frontier: Option<usize>) -> 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,
|
|
}
|
|
}
|
|
|
|
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<CaptureSlots> {
|
|
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<CaptureSlots> {
|
|
let frontier = checkpoint.entry.frontier();
|
|
if frontier > self.bytes || (frontier == self.bytes && !checkpoint.slots.page) {
|
|
return None;
|
|
}
|
|
let interval = (frontier - 1) / self.stride;
|
|
let early = frontier < self.bytes
|
|
&& checkpoint.slots.early
|
|
&& !std::mem::replace(&mut self.seen[interval], true);
|
|
self.next_page = self.next_page.max(checkpoint.slots.next_page);
|
|
Some(CaptureSlots {
|
|
interval,
|
|
early,
|
|
edit: frontier < self.bytes
|
|
&& self.take_edit_frontier(frontier, early || checkpoint.slots.page),
|
|
..checkpoint.slots
|
|
})
|
|
}
|
|
}
|
|
|
|
struct CapturedEntries<'a> {
|
|
request: &'a CompileRequest,
|
|
entry_path: Option<PathBuf>,
|
|
initial: Option<GeneratedInitialState>,
|
|
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
|
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
|
edit: Option<Arc<CachedCheckpoint>>,
|
|
changed: bool,
|
|
}
|
|
|
|
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,
|
|
changed: false,
|
|
}
|
|
}
|
|
|
|
fn retain(&mut self, slots: CaptureSlots, checkpoint: Arc<CachedCheckpoint>) {
|
|
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: CaptureSlots, entry: EntryCheckpoint, host: &RecordingHost) {
|
|
let (Some((trace, replay_count)), Some(path), Some(initial)) = (
|
|
host.prefix(),
|
|
self.entry_path.as_deref(),
|
|
self.initial.as_ref(),
|
|
) else {
|
|
return;
|
|
};
|
|
let Ok(guard) = PrefixInputGuard::capture(
|
|
self.request,
|
|
path,
|
|
trace,
|
|
host.generated_outputs(),
|
|
initial.clone(),
|
|
) else {
|
|
return;
|
|
};
|
|
self.retain(
|
|
slots,
|
|
Arc::new(CachedCheckpoint {
|
|
entry,
|
|
guard,
|
|
replay_count,
|
|
slots,
|
|
}),
|
|
);
|
|
self.changed = true;
|
|
}
|
|
|
|
fn finish(
|
|
self,
|
|
recording: RecordingHost,
|
|
refresh_on_resume: bool,
|
|
) -> Option<Arc<CheckpointSet>> {
|
|
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)| {
|
|
!checkpoint.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);
|
|
}
|
|
let replay_count = entries.iter().map(|entry| entry.replay_count).max()?;
|
|
let mut calls = recording.into_calls()?;
|
|
calls.truncate(replay_count);
|
|
Some(Arc::new(CheckpointSet {
|
|
entries,
|
|
calls,
|
|
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<usize>) -> Self {
|
|
Self {
|
|
minimum_frontier,
|
|
published: Mutex::new(None),
|
|
}
|
|
}
|
|
|
|
pub(super) fn current(&self) -> Option<Arc<PublishedCheckpoints>> {
|
|
self.published
|
|
.lock()
|
|
.expect("native entry checkpoint cache poisoned")
|
|
.clone()
|
|
}
|
|
|
|
pub(super) fn set(&self, next: Option<Arc<CheckpointSet>>, 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()
|
|
.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| entry.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()
|
|
}
|
|
});
|
|
*published = Some(Arc::new(PublishedCheckpoints {
|
|
current: next,
|
|
previous_body,
|
|
}));
|
|
}
|
|
|
|
pub(super) fn capture(
|
|
&self,
|
|
request: &CompileRequest,
|
|
job: RevisionJob,
|
|
executor: Executor,
|
|
source: SourceFile,
|
|
files: &mut Files,
|
|
) -> (
|
|
Result<Arc<RevisionExecution>, RevisionFailure>,
|
|
Option<Arc<CheckpointSet>>,
|
|
) {
|
|
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 result = job.run_capturing_entries(
|
|
executor,
|
|
source,
|
|
&mut recording,
|
|
|frontier, pages| schedule.select(frontier, pages),
|
|
|slots, entry, host| captures.capture(slots, entry, host),
|
|
);
|
|
let next = if result.is_ok() {
|
|
captures.finish(recording, self.minimum_frontier.is_none())
|
|
} else {
|
|
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()))
|
|
.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| {
|
|
let checkpoint = &candidate.set.entries[candidate.index];
|
|
match checkpoint
|
|
.accept_entry(project)
|
|
.and_then(|()| checkpoint.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) {
|
|
let checkpoint = &candidate.set.entries[candidate.index];
|
|
match checkpoint
|
|
.accept_entry(project)
|
|
.and_then(|()| checkpoint.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 checkpoint = &selected.set.entries[selected.index];
|
|
for (index, call) in selected.set.calls[..checkpoint.replay_count].iter().enumerate() {
|
|
check(cancellation)?;
|
|
if let Err(error) = call(&mut prepared.files) {
|
|
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| {
|
|
!Arc::ptr_eq(&candidate.set, &selected.set)
|
|
|| candidate.set.entries[candidate.index].replay_count <= index
|
|
});
|
|
continue 'retry;
|
|
}
|
|
}
|
|
if let Err(error) = checkpoint.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<Arc<Self>> {
|
|
// 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| entry.slots.page)
|
|
.take(2)
|
|
.cloned()
|
|
.collect();
|
|
entries.reverse();
|
|
let replay_count = entries.last()?.replay_count;
|
|
Some(Arc::new(Self {
|
|
entries,
|
|
calls: self.calls[..replay_count].to_vec(),
|
|
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.last().map(|entry| entry.entry.frontier());
|
|
}
|
|
|
|
fn candidates(self: &Arc<Self>) -> impl Iterator<Item = SelectedCheckpoint> + '_ {
|
|
(0..self.entries.len())
|
|
.rev()
|
|
.map(|index| SelectedCheckpoint {
|
|
set: Arc::clone(self),
|
|
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());
|
|
}
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
impl SelectedCheckpoint {
|
|
fn completed_steps(&self) -> usize {
|
|
self.set.entries[self.index].entry.completed_steps()
|
|
}
|
|
|
|
pub(super) fn resume(
|
|
self,
|
|
request: &CompileRequest,
|
|
job: RevisionJob,
|
|
source: SourceFile,
|
|
files: &mut Files,
|
|
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
|
|
work: &mut EntryCheckpointWork,
|
|
) -> Result<
|
|
(
|
|
Result<Arc<RevisionExecution>, RevisionFailure>,
|
|
Arc<CheckpointSet>,
|
|
),
|
|
CompileError,
|
|
> {
|
|
let checkpoint = &self.set.entries[self.index];
|
|
let frontier = checkpoint.entry.frontier();
|
|
work.retained_checkpoints = self.set.entries.len();
|
|
work.reused_frontier = Some(frontier);
|
|
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));
|
|
}
|
|
|
|
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 captures = CapturedEntries::new(request, files);
|
|
// Share only calls and continuations from the prefix just replayed.
|
|
for previous in &self.set.entries[..=self.index] {
|
|
if previous.replay_count <= checkpoint.replay_count
|
|
&& previous.entry.frontier() <= frontier
|
|
&& let Some(slots) = schedule.retain(previous)
|
|
{
|
|
captures.retain(slots, previous.clone());
|
|
}
|
|
}
|
|
let mut recording =
|
|
RecordingHost::after_replay(files, &self.set.calls[..checkpoint.replay_count]);
|
|
let result = job
|
|
.resume_capturing_entries_after_host_replay(
|
|
&checkpoint.entry,
|
|
source,
|
|
&mut recording,
|
|
line_break_cache,
|
|
|offset, pages| {
|
|
// The loaded line may stay the same across several
|
|
// pages. A new sampled shipout is still forward progress.
|
|
if offset > frontier || (offset == frontier && pages >= schedule.next_page) {
|
|
schedule.select(offset, pages)
|
|
} else {
|
|
None
|
|
}
|
|
},
|
|
|slots, entry, host| captures.capture(slots, entry, host),
|
|
)
|
|
.ok_or_else(changed_prefix)?;
|
|
let next = if result.is_ok() {
|
|
captures.finish(recording, true)
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(next) = next {
|
|
next.report_capture(work);
|
|
Ok((result, next))
|
|
} else {
|
|
Ok((result, self.set))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
|
|
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 PrefixInputGuard {
|
|
original: AttemptRequest,
|
|
project: Arc<ProjectSnapshot>,
|
|
initial: GeneratedInitialState,
|
|
entry: PathBuf,
|
|
immutable: BTreeSet<PathBuf>,
|
|
immutable_stream_prefixes: BTreeMap<PathBuf, usize>,
|
|
generated: BTreeSet<PathBuf>,
|
|
lookups: Vec<ResourceLookup>,
|
|
stream_reads: Vec<ResourceReadRange>,
|
|
format_input_bindings: BTreeMap<PathBuf, PathBuf>,
|
|
clock_environment: Option<[Option<OsString>; 3]>,
|
|
}
|
|
|
|
fn date_environment() -> [Option<OsString>; 3] {
|
|
["TZ", "SOURCE_DATE_EPOCH", "FORCE_SOURCE_DATE"].map(std::env::var_os)
|
|
}
|
|
|
|
impl PrefixInputGuard {
|
|
fn capture(
|
|
request: &CompileRequest,
|
|
entry: &Path,
|
|
trace: &ResourceTrace,
|
|
written: &BTreeSet<PathBuf>,
|
|
initial: GeneratedInitialState,
|
|
) -> Result<Self, String> {
|
|
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::<PathBuf, usize>::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);
|
|
}
|
|
Ok(Self {
|
|
original: AttemptRequest::from(request),
|
|
project: project.clone(),
|
|
initial,
|
|
entry: entry.to_path_buf(),
|
|
immutable,
|
|
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 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());
|
|
}
|
|
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.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, &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(&mut files).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(&mut files).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(&mut files).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(&mut files).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::<BTreeSet<_>>().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::<Vec<_>>(),
|
|
[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<PathBuf> = 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<_>>(),
|
|
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;
|
|
}
|
|
}
|