Refresh interactive TeX state across successive edits
This commit is contained in:
1 parent
38e4822370
commit
28668ea10f
7 files changed
+559
-133
No files matched your search
@@ -242,6 +242,32 @@ impl EntryCheckpoint {
|
||||
source: SourceFile,
|
||||
files: &mut impl SourceProvider,
|
||||
cancellation: Cancellation,
|
||||
) -> Option<Result<Execution, ExecutionFailure>> {
|
||||
self.resume_observed(source, files, cancellation, |_, _, _| {})
|
||||
}
|
||||
|
||||
pub(super) fn resume_capturing_entries_after_host_replay<F: SourceProvider, S>(
|
||||
&self,
|
||||
source: SourceFile,
|
||||
files: &mut F,
|
||||
cancellation: Cancellation,
|
||||
select: impl FnMut(usize, usize) -> Option<S>,
|
||||
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||
) -> Option<Result<Execution, ExecutionFailure>> {
|
||||
self.resume_observed(
|
||||
source,
|
||||
files,
|
||||
cancellation,
|
||||
Executor::entry_observer(self.incoming_state, select, capture),
|
||||
)
|
||||
}
|
||||
|
||||
fn resume_observed<F: SourceProvider>(
|
||||
&self,
|
||||
source: SourceFile,
|
||||
files: &mut F,
|
||||
cancellation: Cancellation,
|
||||
capture_boundary: impl FnMut(&Executor, usize, &mut F),
|
||||
) -> Option<Result<Execution, ExecutionFailure>> {
|
||||
if !self.accepts_entry(&source) {
|
||||
return None;
|
||||
@@ -254,7 +280,7 @@ impl EntryCheckpoint {
|
||||
executor.sources[self.entry] = source;
|
||||
let result = executor
|
||||
.check_cancellation()
|
||||
.and_then(|_| executor.run_active_input(self.initial_depth, files, |_, _, _| {}));
|
||||
.and_then(|_| executor.run_active_input(self.initial_depth, files, capture_boundary));
|
||||
let result = executor.finish_observed_input(result, files);
|
||||
Some(executor.finish_execution(result, self.incoming_state))
|
||||
}
|
||||
@@ -2998,11 +3024,24 @@ impl Executor {
|
||||
mut self,
|
||||
file: SourceFile,
|
||||
files: &mut F,
|
||||
mut select: impl FnMut(usize, usize) -> Option<S>,
|
||||
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||
select: impl FnMut(usize, usize) -> Option<S>,
|
||||
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||
) -> Result<Execution, ExecutionFailure> {
|
||||
let incoming_state = self.state.fingerprint();
|
||||
let result = self.run_observed(file, files, |engine, initial_depth, files| {
|
||||
let result = self.run_observed(
|
||||
file,
|
||||
files,
|
||||
Self::entry_observer(incoming_state, select, capture),
|
||||
);
|
||||
self.finish_execution(result, incoming_state)
|
||||
}
|
||||
|
||||
fn entry_observer<F: SourceProvider, S>(
|
||||
incoming_state: u64,
|
||||
mut select: impl FnMut(usize, usize) -> Option<S>,
|
||||
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||
) -> impl FnMut(&Self, usize, &mut F) {
|
||||
move |engine, initial_depth, files| {
|
||||
if engine.job_ended {
|
||||
return;
|
||||
}
|
||||
@@ -3046,8 +3085,7 @@ impl Executor {
|
||||
frontier,
|
||||
};
|
||||
capture(slot, checkpoint, files);
|
||||
});
|
||||
self.finish_execution(result, incoming_state)
|
||||
}
|
||||
}
|
||||
fn finish_execution(
|
||||
mut self,
|
||||
|
||||
@@ -4,7 +4,8 @@ use crate::resources::{ResourceReadRange, ResourceVersion};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
path::Path,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 27;
|
||||
@@ -22,6 +23,17 @@ pub struct FormatImage {
|
||||
resources: Vec<ResourceVersion>,
|
||||
stream_reads: Vec<ResourceReadRange>,
|
||||
file_dates: Vec<FormatFileDate>,
|
||||
#[serde(skip)]
|
||||
input_checks: OnceLock<BTreeMap<PathBuf, InputChecks>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct InputChecks {
|
||||
sources: Vec<usize>,
|
||||
versions: Vec<usize>,
|
||||
ranges: Vec<usize>,
|
||||
// The same immutable allocation already passed this image's full checks.
|
||||
verified: Mutex<Option<Weak<[u8]>>>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
@@ -69,6 +81,7 @@ impl FormatImage {
|
||||
resources,
|
||||
stream_reads,
|
||||
file_dates,
|
||||
input_checks: OnceLock::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -198,84 +211,61 @@ impl FormatImage {
|
||||
input_profile: InputProfile,
|
||||
files: &mut F,
|
||||
mut read: impl FnMut(&mut F, &Path) -> Result<T, String>,
|
||||
date: impl FnMut(&mut F, &str, &str) -> Result<Option<String>, String>,
|
||||
) -> Result<(), String> {
|
||||
self.validate_inputs(
|
||||
profile,
|
||||
input_profile,
|
||||
files,
|
||||
|files, path, checks| self.check_input(path, checks, read(files, path)?.as_ref()),
|
||||
date,
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolve every format input in this job. Skip content checks only when
|
||||
/// the resolver returns the same immutable buffer already verified by this image.
|
||||
pub fn validate_shared_job_inputs<F>(
|
||||
&self,
|
||||
profile: Profile,
|
||||
input_profile: InputProfile,
|
||||
files: &mut F,
|
||||
mut read: impl FnMut(&mut F, &Path) -> Result<Arc<[u8]>, String>,
|
||||
date: impl FnMut(&mut F, &str, &str) -> Result<Option<String>, String>,
|
||||
) -> Result<(), String> {
|
||||
self.validate_inputs(
|
||||
profile,
|
||||
input_profile,
|
||||
files,
|
||||
|files, path, checks| {
|
||||
let data = read(files, path)?;
|
||||
let identity = Arc::downgrade(&data);
|
||||
let mut verified = checks
|
||||
.verified
|
||||
.lock()
|
||||
.map_err(|_| "native format input cache poisoned")?;
|
||||
if !verified.as_ref().is_some_and(|old| old.ptr_eq(&identity)) {
|
||||
self.check_input(path, checks, &data)?;
|
||||
*verified = Some(identity);
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
date,
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_inputs<F>(
|
||||
&self,
|
||||
profile: Profile,
|
||||
input_profile: InputProfile,
|
||||
files: &mut F,
|
||||
mut validate: impl FnMut(&mut F, &Path, &InputChecks) -> Result<(), String>,
|
||||
mut date: impl FnMut(&mut F, &str, &str) -> Result<Option<String>, String>,
|
||||
) -> Result<(), String> {
|
||||
if self.state.profile() != profile || self.state.input_profile() != input_profile {
|
||||
return Err("native format profile mismatch".into());
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Checks<'a> {
|
||||
sources: Vec<(usize, &'a SourceFile)>,
|
||||
versions: Vec<&'a ResourceVersion>,
|
||||
ranges: Vec<&'a ResourceReadRange>,
|
||||
}
|
||||
let mut checks = BTreeMap::<&Path, Checks<'_>>::new();
|
||||
for (id, source) in self.sources.iter().enumerate() {
|
||||
if !self.generated_inputs.contains_key(&id) {
|
||||
checks
|
||||
.entry(Path::new(&source.name))
|
||||
.or_default()
|
||||
.sources
|
||||
.push((id, source));
|
||||
}
|
||||
}
|
||||
for version in &self.resources {
|
||||
checks
|
||||
.entry(&version.path)
|
||||
.or_default()
|
||||
.versions
|
||||
.push(version);
|
||||
}
|
||||
for range in &self.stream_reads {
|
||||
checks.entry(&range.path).or_default().ranges.push(range);
|
||||
}
|
||||
for (path, checks) in checks {
|
||||
let data = read(files, path)?;
|
||||
let bytes = data.as_ref();
|
||||
for (id, source) in checks.sources {
|
||||
let valid = if self.stream_sources.contains(&id) {
|
||||
bytes.starts_with(&source.data)
|
||||
} else {
|
||||
bytes == source.data
|
||||
};
|
||||
if !valid {
|
||||
return Err(format!("native format source changed: {}", source.name));
|
||||
}
|
||||
}
|
||||
if !checks.versions.is_empty() {
|
||||
let sha256 = digest(bytes);
|
||||
if checks
|
||||
.versions
|
||||
.iter()
|
||||
.any(|version| bytes.len() as u64 != version.bytes || sha256 != version.sha256)
|
||||
{
|
||||
return Err(format!(
|
||||
"native format resource changed: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
for range in checks.ranges {
|
||||
let valid = if range.eof {
|
||||
bytes.len() as u64 == range.offset
|
||||
} else {
|
||||
let start = usize::try_from(range.offset).ok();
|
||||
let end = range
|
||||
.offset
|
||||
.checked_add(range.bytes)
|
||||
.and_then(|n| usize::try_from(n).ok());
|
||||
start
|
||||
.zip(end)
|
||||
.and_then(|(start, end)| bytes.get(start..end))
|
||||
.is_some_and(|bytes| digest(bytes) == range.sha256)
|
||||
};
|
||||
if !valid {
|
||||
return Err(format!(
|
||||
"native format stream dependency changed: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
for (path, checks) in self.input_checks.get_or_init(|| self.build_input_checks()) {
|
||||
validate(files, path, checks)?;
|
||||
}
|
||||
for observed in &self.file_dates {
|
||||
if date(files, &observed.name, &observed.from)? != observed.value {
|
||||
@@ -287,8 +277,143 @@ impl FormatImage {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_input_checks(&self) -> BTreeMap<PathBuf, InputChecks> {
|
||||
let mut checks = BTreeMap::<&Path, InputChecks>::new();
|
||||
for (id, source) in self.sources.iter().enumerate() {
|
||||
if !self.generated_inputs.contains_key(&id) {
|
||||
checks
|
||||
.entry(Path::new(&source.name))
|
||||
.or_default()
|
||||
.sources
|
||||
.push(id);
|
||||
}
|
||||
}
|
||||
for (id, version) in self.resources.iter().enumerate() {
|
||||
checks.entry(&version.path).or_default().versions.push(id);
|
||||
}
|
||||
for (id, range) in self.stream_reads.iter().enumerate() {
|
||||
checks.entry(&range.path).or_default().ranges.push(id);
|
||||
}
|
||||
checks
|
||||
.into_iter()
|
||||
.map(|(path, checks)| (path.to_path_buf(), checks))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn check_input(&self, path: &Path, checks: &InputChecks, bytes: &[u8]) -> Result<(), String> {
|
||||
for &id in &checks.sources {
|
||||
let source = &self.sources[id];
|
||||
let valid = if self.stream_sources.contains(&id) {
|
||||
bytes.starts_with(&source.data)
|
||||
} else {
|
||||
bytes == source.data
|
||||
};
|
||||
if !valid {
|
||||
return Err(format!("native format source changed: {}", source.name));
|
||||
}
|
||||
}
|
||||
if !checks.versions.is_empty() {
|
||||
let sha256 = digest(bytes);
|
||||
if checks.versions.iter().any(|&id| {
|
||||
let version = &self.resources[id];
|
||||
bytes.len() as u64 != version.bytes || sha256 != version.sha256
|
||||
}) {
|
||||
return Err(format!(
|
||||
"native format resource changed: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
for &id in &checks.ranges {
|
||||
let range = &self.stream_reads[id];
|
||||
let valid = if range.eof {
|
||||
bytes.len() as u64 == range.offset
|
||||
} else {
|
||||
let start = usize::try_from(range.offset).ok();
|
||||
let end = range
|
||||
.offset
|
||||
.checked_add(range.bytes)
|
||||
.and_then(|n| usize::try_from(n).ok());
|
||||
start
|
||||
.zip(end)
|
||||
.and_then(|(start, end)| bytes.get(start..end))
|
||||
.is_some_and(|bytes| digest(bytes) == range.sha256)
|
||||
};
|
||||
if !valid {
|
||||
return Err(format!(
|
||||
"native format stream dependency changed: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn digest(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_format_checks_track_live_lookups_and_reject_replaced_stream_bytes() {
|
||||
let path = PathBuf::from("stream.tex");
|
||||
let image = FormatImage {
|
||||
schema: SCHEMA,
|
||||
engine: ENGINE.into(),
|
||||
state: State::default(),
|
||||
sources: Vec::new(),
|
||||
stream_sources: BTreeSet::new(),
|
||||
generated_inputs: BTreeMap::new(),
|
||||
resources: Vec::new(),
|
||||
stream_reads: vec![ResourceReadRange {
|
||||
path: path.clone(),
|
||||
offset: 1,
|
||||
bytes: 2,
|
||||
sha256: digest(b"bc"),
|
||||
eof: false,
|
||||
}],
|
||||
file_dates: vec![FormatFileDate {
|
||||
name: "date.tex".into(),
|
||||
from: "stream.tex".into(),
|
||||
value: Some("observed date".into()),
|
||||
}],
|
||||
input_checks: OnceLock::new(),
|
||||
};
|
||||
let encoded = image.encode().unwrap();
|
||||
let mut bytes: Arc<[u8]> = Arc::from(&b"abcd"[..]);
|
||||
let mut seen = (0, 0);
|
||||
let mut check = |bytes: &Arc<[u8]>| {
|
||||
image.validate_shared_job_inputs(
|
||||
image.state.profile(),
|
||||
image.state.input_profile(),
|
||||
&mut seen,
|
||||
|seen, requested| {
|
||||
assert_eq!(requested, path);
|
||||
seen.0 += 1;
|
||||
Ok(bytes.clone())
|
||||
},
|
||||
|seen, name, from| {
|
||||
assert_eq!((name, from), ("date.tex", "stream.tex"));
|
||||
seen.1 += 1;
|
||||
Ok(Some("observed date".into()))
|
||||
},
|
||||
)
|
||||
};
|
||||
check(&bytes).unwrap();
|
||||
check(&bytes).unwrap();
|
||||
Arc::make_mut(&mut bytes)[1] = b'x';
|
||||
assert!(
|
||||
check(&bytes)
|
||||
.unwrap_err()
|
||||
.contains("stream dependency changed")
|
||||
);
|
||||
check(&Arc::from(&b"abc!"[..])).unwrap();
|
||||
assert_eq!(seen, (4, 3));
|
||||
assert_eq!(image.encode().unwrap(), encoded);
|
||||
}
|
||||
}
|
||||
@@ -197,6 +197,25 @@ impl RevisionJob {
|
||||
Some(self.finish_execution(executed, files))
|
||||
}
|
||||
|
||||
/// Resume a verified prefix and observe new boundaries in the executed suffix.
|
||||
pub fn resume_capturing_entries_after_host_replay<F: SourceProvider, S>(
|
||||
self,
|
||||
checkpoint: &EntryCheckpoint,
|
||||
source: SourceFile,
|
||||
files: &mut F,
|
||||
select: impl FnMut(usize, usize) -> Option<S>,
|
||||
capture: impl FnMut(S, EntryCheckpoint, &mut F),
|
||||
) -> Option<Result<Arc<RevisionExecution>, RevisionFailure>> {
|
||||
let executed = checkpoint.resume_capturing_entries_after_host_replay(
|
||||
source,
|
||||
files,
|
||||
self.cancellation.clone(),
|
||||
select,
|
||||
capture,
|
||||
)?;
|
||||
Some(self.finish_execution(executed, files))
|
||||
}
|
||||
|
||||
fn finish_execution(
|
||||
self,
|
||||
executed: Result<Execution, ExecutionFailure>,
|
||||
|
||||
@@ -220,6 +220,20 @@ SHA-256 为 `2bb2dd465e5a7f1c94f834d305b2405a03efadb2382db5c64cdfc9b151fcfdfc`
|
||||
发布。集成测试核对 11 种失败路径,包含原序列化字节、原有报告保护、错误
|
||||
保留及暂存清理。真实 CVPR 大报告的峰值内存还需重新测量。
|
||||
|
||||
### 连续编辑的检查点与格式验证
|
||||
|
||||
自动续跑在实际执行的新后缀采集检查点。只有当前修订成功发布才更新共享集合。
|
||||
从较早位置编辑后,下一次可在较晚位置继续。跨位置回归验证 PDF、页面差量、
|
||||
来源范围、实际资源观察和 aux 与同版本全量一致。原样 A3 与真实 schema25
|
||||
格式的两轮增量也再次通过独立全量校验。
|
||||
|
||||
实际 LaTeX 格式包含45583段流读取校验。格式镜像只复用已验证的同一不可变
|
||||
字节分配,依然为每一轮解析及记录实际依赖、校验新内容、查询文件日期。
|
||||
schema27 合并版本通过539项库、工作流和内核回归,零失败。日志
|
||||
`target/p4-revision-reuse-main/directed.log` 的 SHA-256 为
|
||||
`b0fb358eced953b0600e7e8cbbe2d65c075b63e64521c8588b1bd9206201dc69`。
|
||||
连续编辑的正式浏览器延迟仍待实测。
|
||||
|
||||
### schema27 与主线兼容性
|
||||
|
||||
合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。
|
||||
|
||||
+9
-4
@@ -753,7 +753,7 @@ fn prepare_checked(
|
||||
),
|
||||
};
|
||||
let executor = if kernel == KernelPreparation::Resume {
|
||||
image.validate_job_inputs(
|
||||
image.validate_shared_job_inputs(
|
||||
state.profile(),
|
||||
request.input_profile,
|
||||
&mut world,
|
||||
@@ -781,7 +781,7 @@ fn prepare_checked(
|
||||
None => {
|
||||
let image = FormatImage::decode(&loaded.data)?;
|
||||
let executor = if kernel == KernelPreparation::Resume {
|
||||
image.validate_job_inputs(
|
||||
image.validate_shared_job_inputs(
|
||||
state.profile(),
|
||||
request.input_profile,
|
||||
&mut world,
|
||||
@@ -969,8 +969,13 @@ impl CompileJob {
|
||||
let before = cache.work();
|
||||
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
|
||||
debug_assert!(executor.is_none());
|
||||
let (executed, next) =
|
||||
current.resume(self.job, source, files, &mut entry_checkpoint_work)?;
|
||||
let (executed, next) = current.resume(
|
||||
&request,
|
||||
self.job,
|
||||
source,
|
||||
files,
|
||||
&mut entry_checkpoint_work,
|
||||
)?;
|
||||
(executed, Some(next))
|
||||
} else {
|
||||
let executor = executor
|
||||
|
||||
+267
-46
@@ -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() {
|
||||
|
||||
@@ -10,7 +10,7 @@ use texrra_tex_core::{
|
||||
resources::{LoadedResource, ResourceKind},
|
||||
};
|
||||
|
||||
pub(super) type Call = Box<dyn Fn(&mut Files) -> Result<(), String> + Send + Sync>;
|
||||
pub(super) type Call = Arc<dyn Fn(&mut Files) -> Result<(), String> + Send + Sync>;
|
||||
const MAX_REPLAY_CALLS: usize = 65_536;
|
||||
|
||||
pub(super) struct RecordingHost<'a> {
|
||||
@@ -20,9 +20,13 @@ pub(super) struct RecordingHost<'a> {
|
||||
|
||||
impl<'a> RecordingHost<'a> {
|
||||
pub(super) fn new(files: &'a mut Files) -> Self {
|
||||
Self::after_replay(files, &[])
|
||||
}
|
||||
|
||||
pub(super) fn after_replay(files: &'a mut Files, prefix: &[Call]) -> Self {
|
||||
Self {
|
||||
files,
|
||||
calls: Some(Vec::new()),
|
||||
calls: Some(prefix.to_vec()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +58,7 @@ impl<'a> RecordingHost<'a> {
|
||||
return result;
|
||||
}
|
||||
let expected = evidence(&result);
|
||||
calls.push(Box::new(move |files| {
|
||||
calls.push(Arc::new(move |files| {
|
||||
let observed = evidence(&call(files));
|
||||
if observed == expected {
|
||||
Ok(())
|
||||
|
||||
Reference in new issue
Block a user