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

+44 -6
View File
@@ -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>,