Refresh interactive TeX state across successive edits

This commit is contained in:
gloamxun committed 2026-11-19 16:19:29 +08:00
1 parent 38e4822370
commit 28668ea10f
7 files changed
+559 -133

No files matched your search

+267 -46
View File
@@ -28,11 +28,13 @@ 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,
}
pub(super) struct SelectedCheckpoint {
@@ -52,10 +54,12 @@ struct CaptureSchedule {
fixed_frontier: Option<usize>,
}
#[derive(Clone, Copy)]
struct CaptureSlots {
interval: usize,
early: bool,
page: bool,
next_page: usize,
}
impl CaptureSchedule {
@@ -79,6 +83,7 @@ impl CaptureSchedule {
interval: 0,
early: true,
page: false,
next_page: self.next_page,
});
}
if frontier >= self.bytes {
@@ -94,8 +99,109 @@ impl CaptureSchedule {
interval,
early,
page,
next_page: self.next_page,
})
}
fn retain(&mut self, checkpoint: &CachedCheckpoint) -> Option<CaptureSlots> {
let frontier = checkpoint.entry.frontier();
if frontier >= self.bytes {
return None;
}
let interval = (frontier - 1) / self.stride;
let early = 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,
..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],
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(),
changed: false,
}
}
fn retain(&mut self, slots: CaptureSlots, checkpoint: Arc<CachedCheckpoint>) {
if slots.early {
self.early[slots.interval] = 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, 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 mut entries: Vec<_> = self
.early
.into_iter()
.chain(self.shipped)
.flatten()
.collect();
entries.sort_by_key(|candidate| candidate.entry.completed_steps());
entries.dedup_by(|a, b| Arc::ptr_eq(a, b));
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,
}))
}
}
pub(super) fn can_stage(request: &CompileRequest) -> bool {
@@ -139,55 +245,18 @@ impl CheckpointCache {
Result<Arc<RevisionExecution>, RevisionFailure>,
Option<Arc<CheckpointSet>>,
) {
let entry_path = files
.resource_trace()
.reads
.first()
.map(|first| first.path.clone());
let initial = files.preparation().generated_initial.clone();
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier);
let mut early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS] = Default::default();
let mut shipped = early.clone();
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| {
let (Some((trace, replay_count)), Some(path), Some(initial)) =
(host.prefix(), entry_path.as_deref(), initial.as_ref())
else {
return;
};
let Ok(guard) = PrefixInputGuard::capture(request, path, trace, initial.clone())
else {
return;
};
let captured = Arc::new(CachedCheckpoint {
entry,
guard,
replay_count,
});
if slots.early {
early[slots.interval] = Some(captured.clone());
}
if slots.page {
shipped[slots.interval] = Some(captured);
}
},
|slots, entry, host| captures.capture(slots, entry, host),
);
let mut entries: Vec<_> = early.into_iter().chain(shipped).flatten().collect();
entries.sort_by_key(|candidate| candidate.entry.completed_steps());
entries.dedup_by(|a, b| Arc::ptr_eq(a, b));
let replay_count = entries.iter().map(|entry| entry.replay_count).max();
let next = if result.is_ok()
&& let Some(replay_count) = replay_count
{
recording.into_calls().map(|mut calls| {
calls.truncate(replay_count);
Arc::new(CheckpointSet { entries, calls })
})
let next = if result.is_ok() {
captures.finish(recording, self.minimum_frontier.is_none())
} else {
None
};
@@ -275,6 +344,7 @@ impl SelectedCheckpoint {
pub(super) fn resume(
self,
request: &CompileRequest,
job: RevisionJob,
source: SourceFile,
files: &mut Files,
@@ -287,14 +357,58 @@ impl SelectedCheckpoint {
CompileError,
> {
let checkpoint = &self.set.entries[self.index];
let result = job
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
.ok_or_else(|| CompileError::Host("prepared checkpoint prefix changed".into()))?;
let frontier = checkpoint.entry.frontier();
work.retained_checkpoints = self.set.entries.len();
work.reused_frontier = Some(checkpoint.entry.frontier());
work.reused_frontier = Some(frontier);
work.reused_steps = checkpoint.entry.completed_steps();
work.replayed_calls = checkpoint.replay_count;
Ok((result, self.set))
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 mut schedule = CaptureSchedule::new(source.data.len(), None);
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,
|offset, pages| {
if offset > frontier {
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))
}
}
}
@@ -970,6 +1084,113 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
);
}
#[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 first_edit = original.replace("width12pt", "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();
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("width17pt", "width27pt");
let second_project = edited_project
.with_file_edits(
3,
BTreeMap::from([(entry, Arc::from(second_edit.as_bytes()))]),
)
.unwrap();
let second_request = request.with_project(second_project);
let second = compiler.compile(second_request.clone()).unwrap();
let second_full = NativeCompiler::default().compile(second_request).unwrap();
let second_work = &second.entry_checkpoint_work;
assert!(second_work.reused_frontier.unwrap() > original.find("width12pt").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<_>>(),
[7],
);
}
#[test]
#[ignore = "requires the verified LaTeX format, A3 fixture and a dedicated output directory"]
fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() {