Resume validated native checkpoints inside included sources

This commit is contained in:
gloamxun committed 2026-11-29 06:04:51 +08:00
1 parent fb5cb5ada9
commit 84ad682939
8 files changed
+537 -88

No files matched your search

+167 -36
View File
@@ -9,7 +9,7 @@ use std::{
path::Path,
};
use texrra_tex_core::{
execution::EntryCheckpoint,
execution::{CheckpointSource, EntryCheckpoint},
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
};
#[cfg(test)]
@@ -22,6 +22,8 @@ pub struct EntryCheckpointWork {
/// Checkpoints in the selected or freshly captured set.
pub retained_checkpoints: usize,
pub reused_frontier: Option<usize>,
/// Child input at the resume frontier, when the entry scanner was suspended.
pub reused_source: Option<PathBuf>,
pub reused_steps: usize,
pub replayed_calls: usize,
pub rejection: Option<String>,
@@ -41,7 +43,8 @@ struct CachedCheckpoint {
entry: EntryCheckpoint,
guard: PrefixInputGuard,
replay_count: usize,
slots: CaptureSlots,
slots: Capture,
}
pub(super) struct CheckpointSet {
@@ -78,6 +81,52 @@ struct CaptureSlots {
next_page: usize,
}
const NESTED_FILES: usize = 2;
const NESTED_INTERVALS: usize = 2;
#[derive(Clone, Copy)]
enum Capture {
Entry(CaptureSlots),
Nested { file: usize, interval: usize },
}
#[derive(Default)]
struct NestedSchedule {
sources: [Option<usize>; NESTED_FILES],
seen: [[bool; NESTED_INTERVALS]; NESTED_FILES],
recent: Option<(usize, Option<usize>)>,
}
impl NestedSchedule {
fn select(&mut self, source: CheckpointSource<'_>, cwd: &Path) -> Option<Capture> {
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<usize>, edit_frontier: Option<usize>) -> Self {
Self {
@@ -143,21 +192,22 @@ impl CaptureSchedule {
}
fn retain(&mut self, checkpoint: &CachedCheckpoint) -> Option<CaptureSlots> {
let Capture::Entry(slots) = checkpoint.slots else { return None; };
let frontier = checkpoint.entry.frontier();
if frontier > self.bytes || (frontier == self.bytes && !checkpoint.slots.page) {
if frontier > self.bytes || (frontier == self.bytes && !slots.page) {
return None;
}
let interval = (frontier - 1) / self.stride;
let early = frontier < self.bytes
&& checkpoint.slots.early
&& slots.early
&& !std::mem::replace(&mut self.seen[interval], true);
self.next_page = self.next_page.max(checkpoint.slots.next_page);
self.next_page = self.next_page.max(slots.next_page);
Some(CaptureSlots {
interval,
early,
edit: frontier < self.bytes
&& self.take_edit_frontier(frontier, early || checkpoint.slots.page),
..checkpoint.slots
&& self.take_edit_frontier(frontier, early || slots.page),
..slots
})
}
}
@@ -169,6 +219,7 @@ struct CapturedEntries<'a> {
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
edit: Option<Arc<CachedCheckpoint>>,
nested: [[Option<Arc<CachedCheckpoint>>; NESTED_INTERVALS]; NESTED_FILES],
changed: bool,
}
@@ -185,11 +236,19 @@ impl<'a> CapturedEntries<'a> {
early: Default::default(),
shipped: Default::default(),
edit: None,
nested: Default::default(),
changed: false,
}
}
fn retain(&mut self, slots: CaptureSlots, checkpoint: Arc<CachedCheckpoint>) {
fn retain(&mut self, slots: Capture, checkpoint: Arc<CachedCheckpoint>) {
let slots = match slots {
Capture::Entry(slots) => slots,
Capture::Nested { file, interval } => {
self.nested[file][interval] = Some(checkpoint);
return;
}
};
if slots.early {
self.early[slots.interval] = Some(checkpoint.clone());
}
@@ -201,7 +260,7 @@ impl<'a> CapturedEntries<'a> {
}
}
fn capture(&mut self, slots: CaptureSlots, entry: EntryCheckpoint, host: &RecordingHost) {
fn capture(&mut self, slots: Capture, entry: EntryCheckpoint, host: &RecordingHost) {
let (Some((trace, replay_count)), Some(path), Some(initial)) = (
host.prefix(),
self.entry_path.as_deref(),
@@ -209,7 +268,7 @@ impl<'a> CapturedEntries<'a> {
) else {
return;
};
let Ok(guard) = PrefixInputGuard::capture(
let Ok(mut guard) = PrefixInputGuard::capture(
self.request,
path,
trace,
@@ -218,6 +277,11 @@ impl<'a> CapturedEntries<'a> {
) 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 {
@@ -260,12 +324,14 @@ impl<'a> CapturedEntries<'a> {
.enumerate()
.skip(1)
.filter(|(_, checkpoint)| {
!checkpoint.slots.page && checkpoint.entry.frontier() != edit
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()?;
let mut calls = recording.into_calls()?;
calls.truncate(replay_count);
@@ -324,7 +390,7 @@ impl CheckpointCache {
.current
.entries
.iter()
.find(|entry| entry.slots.page)
.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
@@ -354,11 +420,21 @@ impl CheckpointCache {
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(
let mut nested = NestedSchedule::default();
let cwd = &request.world.cwd;
let result = job.run_capturing_sources(
executor,
source,
&mut recording,
|frontier, pages| schedule.select(frontier, pages),
|source, pages| {
if source.is_entry {
schedule.select(source.frontier, pages).map(Capture::Entry)
} else if self.minimum_frontier.is_none() {
nested.select(source, cwd)
} else {
None
}
},
|slots, entry, host| captures.capture(slots, entry, host),
);
let next = if result.is_ok() {
@@ -450,9 +526,11 @@ impl PublishedCheckpoints {
)?;
let selected = selected.expect("resume preparation chose a verified checkpoint");
let checkpoint = &selected.set.entries[selected.index];
let partial_source = checkpoint.guard.nested_source.as_deref()
.and_then(|path| project.file(path)).map(|file| &file.version);
for (index, call) in selected.set.calls[..checkpoint.replay_count].iter().enumerate() {
check(cancellation)?;
if let Err(error) = call(&mut prepared.files) {
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.
@@ -481,7 +559,7 @@ impl CheckpointSet {
.entries
.iter()
.rev()
.filter(|entry| entry.slots.page)
.filter(|entry| matches!(entry.slots, Capture::Entry(slots) if slots.page))
.take(2)
.cloned()
.collect();
@@ -497,7 +575,9 @@ impl CheckpointSet {
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());
work.captured_frontier = self.entries.iter().rev()
.find(|entry| matches!(entry.slots, Capture::Entry(_)))
.map(|entry| entry.entry.frontier());
}
fn candidates(self: &Arc<Self>) -> impl Iterator<Item = SelectedCheckpoint> + '_ {
@@ -521,6 +601,12 @@ impl CachedCheckpoint {
{
return Err("checkpoint entry prefix changed".into());
}
if let Some(path) = &self.guard.nested_source {
let child = project.file(path).ok_or("checkpoint child is unavailable")?;
if !self.entry.accepts_nested_source(&path.to_string_lossy(), &child.data) {
return Err("checkpoint child prefix changed".into());
}
}
Ok(())
}
}
@@ -549,6 +635,7 @@ impl SelectedCheckpoint {
let frontier = checkpoint.entry.frontier();
work.retained_checkpoints = self.set.entries.len();
work.reused_frontier = Some(frontier);
work.reused_source = checkpoint.guard.nested_source.clone();
work.reused_steps = checkpoint.entry.completed_steps();
work.replayed_calls = checkpoint.replay_count;
let changed_prefix = || CompileError::Host("prepared checkpoint prefix changed".into());
@@ -566,31 +653,57 @@ impl SelectedCheckpoint {
.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_deref()
.and_then(|path| request.project.as_ref()?.file(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);
// Share only calls and continuations from the prefix just replayed.
// Earlier retained positions refer only to calls already 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());
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]);
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 result = job
.resume_capturing_entries_after_host_replay(
.resume_capturing_sources_after_host_replay(
&checkpoint.entry,
source,
nested_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)
|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.frontier, pages).map(Capture::Entry)
} else {
None
}
} else {
None
nested_schedule.select(source, cwd)
}
},
|slots, entry, host| captures.capture(slots, entry, host),
@@ -637,6 +750,7 @@ struct PrefixInputGuard {
project: Arc<ProjectSnapshot>,
initial: GeneratedInitialState,
entry: PathBuf,
nested_source: Option<PathBuf>,
immutable: BTreeSet<PathBuf>,
immutable_stream_prefixes: BTreeMap<PathBuf, usize>,
generated: BTreeSet<PathBuf>,
@@ -745,6 +859,7 @@ impl PrefixInputGuard {
project: project.clone(),
initial,
entry: entry.to_path_buf(),
nested_source: None,
immutable,
immutable_stream_prefixes,
generated,
@@ -755,6 +870,21 @@ impl PrefixInputGuard {
})
}
fn allow_nested_source(&mut self, path: &Path, trace: &ResourceTrace, host: &RecordingHost<'_>) -> bool {
let Some(file) = self.project.file(path) else { return false };
// Presence and size queries can be replayed against the new bytes.
// All content reads other than the active scanner pin the old bytes.
if !host.source_read_is_rebindable(&file.version)
|| 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(path.to_path_buf());
true
}
fn verify_project<'a>(
&self,
request: &'a CompileRequest,
@@ -784,6 +914,7 @@ impl PrefixInputGuard {
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() == Some(path)
|| self.immutable_stream_prefixes.get(path).is_some_and(|&end| {
new.data.get(..end) == Some(&old.data[..end])
})
@@ -1086,7 +1217,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
)
.unwrap();
for call in &calls {
call(&mut files).unwrap();
call.replay(&mut files, None).unwrap();
}
assert_eq!(
files.resource_usage().unwrap().unwrap().open_outputs,
@@ -1130,7 +1261,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
)
.unwrap();
for call in &calls {
call(&mut files).unwrap();
call.replay(&mut files, None).unwrap();
}
let result = revision
.resume_entry_after_host_replay(&checkpoint, source, &mut files)
@@ -1250,7 +1381,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
)
.unwrap();
for call in &calls {
call(&mut files).unwrap();
call.replay(&mut files, None).unwrap();
}
let cancelled = Cancellation::default();
cancelled.cancel();
@@ -1276,7 +1407,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
.unwrap();
assert!(checkpoint.accepts_entry(&source));
for call in &calls {
call(&mut files).unwrap();
call.replay(&mut files, None).unwrap();
}
let resumed_usage: HostResourceUsage = files.resource_usage().unwrap().unwrap();
assert_eq!(resumed_usage.open_outputs, Some(1));
+114 -19
View File
@@ -7,10 +7,57 @@ use std::{fs, path::Path};
use texrra_tex_core::source_map::SourceMap;
use texrra_tex_core::{
execution::{Error, HostResourceUsage, WriteDestination},
resources::{LoadedResource, ResourceKind},
resources::{LoadedResource, ResourceKind, ResourceVersion},
};
pub(super) type Call = Arc<dyn Fn(&mut Files) -> Result<(), String> + Send + Sync>;
type CheckedCall = dyn Fn(&mut Files) -> Result<(), String> + Send + Sync;
#[derive(Clone)]
pub(super) enum Call {
Checked(Arc<CheckedCall>),
ReadSource(Arc<SourceRead>),
FileSize(Arc<SizeRead>),
}
pub(super) struct SourceRead {
name: String,
from: String,
expected: Result<ResourceVersion, String>,
}
pub(super) struct SizeRead {
name: String,
from: String,
observed: Result<Option<u64>, String>,
read: Option<ResourceVersion>,
}
impl Call {
pub(super) fn replay(&self, files: &mut Files, partial_source: Option<&ResourceVersion>) -> Result<(), String> {
match self {
Self::Checked(call) => call(files),
Self::FileSize(read) => {
let observed = files.file_size(&read.name, &read.from);
if observed == read.observed {
Ok(())
} else {
Err(format!("file size changed: expected {:?}, observed {observed:?}", read.observed))
}
}
Self::ReadSource(read) => {
let SourceRead { name, from, expected } = read.as_ref();
let observed = files.read_versioned_source(name, from).map(|(_, version)| version);
if &observed == expected || matches!((&observed, expected), (Ok(new), Ok(old))
if partial_source == Some(new) && new.path == old.path)
{
Ok(())
} else {
Err(format!("read changed: expected {expected:?}, observed {observed:?}"))
}
}
}
}
}
const MAX_REPLAY_CALLS: usize = 65_536;
pub(super) struct RecordingHost<'a> {
@@ -20,14 +67,30 @@ pub(super) struct RecordingHost<'a> {
impl<'a> RecordingHost<'a> {
pub(super) fn new(files: &'a mut Files) -> Self {
Self::after_replay(files, &[])
Self::after_replay(files, &[], None)
}
pub(super) fn after_replay(files: &'a mut Files, prefix: &[Call]) -> Self {
Self {
files,
calls: Some(prefix.to_vec()),
pub(super) fn after_replay(
files: &'a mut Files,
prefix: &[Call],
rebound: Option<&ResourceVersion>,
) -> Self {
let mut calls = prefix.to_vec();
if let Some(version) = rebound {
for call in &mut calls {
if let Call::ReadSource(read) = call
&& let Ok(prior) = &read.expected
&& prior.path == version.path && prior != version
{
*call = Call::ReadSource(Arc::new(SourceRead {
name: read.name.clone(),
from: read.from.clone(),
expected: Ok(version.clone()),
}));
}
}
}
Self { files, calls: Some(calls) }
}
#[cfg(test)]
@@ -42,6 +105,21 @@ impl<'a> RecordingHost<'a> {
(count < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), count))
}
pub(super) fn source_read_is_rebindable(&self, version: &ResourceVersion) -> bool {
let Some(calls) = &self.calls else { return false };
let mut source_reads = 0;
let mut size_reads = 0;
for call in calls {
match call {
Call::ReadSource(read) if read.expected.as_ref() == Ok(version) => source_reads += 1,
Call::FileSize(read) if read.read.as_ref().is_some_and(|r| r.path == version.path) => size_reads += 1,
_ => {}
}
}
source_reads == 1 && self.files.resource_trace().reads.iter()
.filter(|read| read.path == version.path).count() == source_reads + size_reads
}
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
self.files.generated_outputs()
}
@@ -62,7 +140,7 @@ impl<'a> RecordingHost<'a> {
return result;
}
let expected = evidence(&result);
calls.push(Arc::new(move |files| {
calls.push(Call::Checked(Arc::new(move |files| {
let observed = evidence(&call(files));
if observed == expected {
Ok(())
@@ -71,7 +149,7 @@ impl<'a> RecordingHost<'a> {
"{name} changed: expected {expected:?}, observed {observed:?}"
))
}
}));
})));
}
result
}
@@ -108,14 +186,17 @@ impl SourceProvider for RecordingHost<'_> {
call!(self, resource_usage())
}
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
let (name, from) = (name.to_owned(), from.to_owned());
self.record(
"read",
move |files| files.read_versioned_source(&name, &from),
|result| result.as_ref().map(|(_, version)| version.clone()).map_err(Clone::clone),
)
.map(|(source, _)| source)
let result = self.files.read_versioned_source(name, from);
if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS {
calls.push(Call::ReadSource(Arc::new(SourceRead {
name: name.to_owned(),
from: from.to_owned(),
expected: result.as_ref().map(|(_, version)| version.clone()).map_err(Clone::clone),
})));
}
result.map(|(source, _)| source)
}
fn resource(
&mut self,
kind: ResourceKind,
@@ -214,9 +295,23 @@ impl SourceProvider for RecordingHost<'_> {
})
}
fn file_size(&mut self, name: &str, from: &str) -> Result<Option<u64>, String> {
let (name, from) = (name.to_owned(), from.to_owned());
call!(self, file_size(&name, &from))
let previous_reads = self.files.resource_trace().reads.len();
let observed = self.files.file_size(name, from);
if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS {
let read = match &self.files.resource_trace().reads[previous_reads..] {
[read] => Some(read.clone()),
_ => None,
};
calls.push(Call::FileSize(Arc::new(SizeRead {
name: name.to_owned(),
from: from.to_owned(),
observed: observed.clone(),
read,
})));
}
observed
}
fn file_modification_date(&mut self, name: &str, from: &str) -> Result<Option<String>, String> {
let (name, from) = (name.to_owned(), from.to_owned());
call!(self, file_modification_date(&name, &from))
@@ -421,7 +516,7 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
changed_prefix.data[0] ^= 1;
assert!(!checkpoint.accepts_entry(&changed_prefix));
for (i, call) in calls.iter().enumerate() {
call(&mut files).unwrap_or_else(|error| panic!("replay action {i}: {error}"));
call.replay(&mut files, None).unwrap_or_else(|error| panic!("replay action {i}: {error}"));
}
let resumed = checkpoint
.resume_after_host_replay(source, &mut files, Cancellation::default())