Resume verified preambles while preparing desktop bibliographies

This commit is contained in:
gloamxun committed 2026-12-03 12:55:13 +08:00
1 parent 32cfd6240a
commit fd16e9a740
8 files changed
+270 -48

No files matched your search

+1 -1
View File
@@ -3237,7 +3237,7 @@ dependencies = [
[[package]] [[package]]
name = "texrra-desktop" name = "texrra-desktop"
version = "0.1.13" version = "0.1.14"
dependencies = [ dependencies = [
"serde_json", "serde_json",
"tauri", "tauri",
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "texrra-desktop" name = "texrra-desktop"
version = "0.1.13" version = "0.1.14"
edition = "2024" edition = "2024"
rust-version = "1.92" rust-version = "1.92"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "Texrra", "productName": "Texrra",
"version": "0.1.13", "version": "0.1.14",
"identifier": "org.texrra.desktop", "identifier": "org.texrra.desktop",
"build": { "build": {
"frontendDist": "../startup" "frontendDist": "../startup"
+75 -13
View File
@@ -18,7 +18,7 @@ use texrra_engine::native::{
CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, CheckpointTimings, CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage,
CompiledDocument, CompiledDocument,
DraftPreview, Entry, DraftPreview, Entry,
EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot, EntryCheckpointWork, NativeCompiler, OpeningPreamble, PreviewUpdate, ProjectDefinition, ProjectSnapshot,
job_time, job_time,
}; };
use texrra_tex_core::{ use texrra_tex_core::{
@@ -1305,12 +1305,15 @@ fn finish_prepare(
// The seed uses the same native compiler and actual package bytes. // The seed uses the same native compiler and actual package bytes.
let trace_preparation = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE") let trace_preparation = std::env::var_os("TEXRRA_EDITOR_PREPARATION_TRACE")
.is_some_and(|value| value == "1"); .is_some_and(|value| value == "1");
let compile_seed = |pass| -> Result<_, Box<dyn std::error::Error>> { let has_database = files.keys().any(|path| {
path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| ext.eq_ignore_ascii_case("bib"))
});
let compile_seed = |pass, previous: Option<&OpeningPreamble>| -> Result<_, Box<dyn std::error::Error>> {
let job = compiler.start(); let job = compiler.start();
check_current()?; check_current()?;
let started = Instant::now(); let started = Instant::now();
let (result, preamble) = if pass == 2 { let (result, preamble) = if has_database || pass == 2 {
job.compile_opening_seed(request.clone()) job.compile_opening_seed_with_preamble(request.clone(), previous)
} else { } else {
(job.compile_detailed(request.clone()), None) (job.compile_detailed(request.clone()), None)
}; };
@@ -1321,12 +1324,15 @@ fn finish_prepare(
"ms": started.elapsed().as_secs_f64() * 1000.0, "ms": started.elapsed().as_secs_f64() * 1000.0,
"format": result.as_ref().ok().and_then(|doc| doc.format_preparation.as_ref()) "format": result.as_ref().ok().and_then(|doc| doc.format_preparation.as_ref())
.map(|format| format!("{format:?}")), .map(|format| format!("{format:?}")),
"reused_steps": result.as_ref().ok().map(|doc| doc.entry_checkpoint_work.reused_steps),
"preamble_rejection": result.as_ref().ok()
.and_then(|doc| doc.entry_checkpoint_work.rejection.as_deref()),
"ok": result.is_ok(), "ok": result.is_ok(),
})); }));
} }
Ok((result, preamble)) Ok((result, preamble))
}; };
let (mut seed, mut preamble) = compile_seed(1)?; let (mut seed, mut preamble) = compile_seed(1, None)?;
check_current()?; check_current()?;
if let Some(preview) = preview { if let Some(preview) = preview {
let document = seed.as_ref().ok().filter(|document| !document.pages.is_empty()); let document = seed.as_ref().ok().filter(|document| !document.pages.is_empty());
@@ -1351,7 +1357,7 @@ fn finish_prepare(
copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?; copy_with_date(&path, &contents, Some(SystemTime::now()), &mut dates)?;
files.insert(path, contents); files.insert(path, contents);
bibliography = Some(plan); bibliography = Some(plan);
(seed, preamble) = compile_seed(2)?; (seed, preamble) = compile_seed(2, preamble.as_ref())?;
} }
Ok(None) => {} Ok(None) => {}
Err(error) => eprintln!("Editor bibliography: {error}"), Err(error) => eprintln!("Editor bibliography: {error}"),
@@ -1777,13 +1783,17 @@ mod opening_tests {
let entry = run.join("entry.tex"); let entry = run.join("entry.tex");
let package = run.join("width.sty"); let package = run.join("width.sty");
let aux = run.join("entry.aux"); let aux = run.join("entry.aux");
let bibliography = run.join("entry.bbl");
let override_package = run.join("override.sty");
let source = concat!( let source = concat!(
"\\catcode35=6 \\catcode123=1 \\catcode125=2 \\pdfoutput=1\n", "\\catcode35=6 \\catcode123=1 \\catcode125=2 \\pdfoutput=1\n",
"\\def\\begin#1{}\n", "\\def\\begin#1{}\n",
"\\input width.sty\n", "\\input width.sty\n",
"\\openin3=override.sty \\ifeof3 \\else \\read3 to\\width \\fi \\closein3\n",
"\\begin{document}\n", "\\begin{document}\n",
"\\def\\labelnumber{1}\n", "\\def\\labelnumber{1}\n",
"\\openin2=entry.aux \\ifeof2 \\else \\read2 to\\labelnumber \\fi \\closein2\n", "\\openin2=entry.aux \\ifeof2 \\else \\read2 to\\labelnumber \\fi \\closein2\n",
"\\openin4=entry.bbl \\ifeof4 \\else \\read4 to\\width \\fi \\closein4\n",
"\\count0=\\labelnumber\\relax \\advance\\count0 by 1\n", "\\count0=\\labelnumber\\relax \\advance\\count0 by 1\n",
"\\immediate\\openout1=entry.aux \\immediate\\write1{\\the\\count0} \\immediate\\closeout1\n", "\\immediate\\openout1=entry.aux \\immediate\\write1{\\the\\count0} \\immediate\\closeout1\n",
"\\shipout\\hbox{\\vrule width\\dimexpr\\labelnumber pt+\\width\\relax height1pt}\n", "\\shipout\\hbox{\\vrule width\\dimexpr\\labelnumber pt+\\width\\relax height1pt}\n",
@@ -1801,10 +1811,23 @@ mod opening_tests {
request.entry = Entry::Initex; request.entry = Entry::Initex;
request.etex = true; request.etex = true;
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
compiler.compile_detailed(request.clone()).unwrap(); let (first, preamble) = compiler.start().compile_opening_seed(request.clone());
let (seed, preamble) = compiler.start().compile_opening_seed(request.clone()); let first = first.unwrap();
let first_aux = fs::read(&aux).unwrap();
let bibliography_bytes = b"30pt\n";
fs::write(&bibliography, bibliography_bytes).unwrap();
let (seed, preamble) = compiler.start()
.compile_opening_seed_with_preamble(request.clone(), preamble.as_ref());
let seed = seed.unwrap(); let seed = seed.unwrap();
assert!(seed.entry_checkpoint_work.reused_steps > 0, "{:?}", seed.entry_checkpoint_work);
assert_ne!(first.pdf, seed.pdf);
let seed_aux = fs::read(&aux).unwrap(); let seed_aux = fs::read(&aux).unwrap();
fs::write(&aux, first_aux).unwrap();
let full_seed = NativeCompiler::default().compile_detailed(request.clone()).unwrap();
assert_eq!(seed.pdf, full_seed.pdf);
assert_eq!(seed.source_map.sources, full_seed.source_map.sources);
assert_eq!(seed.source_map.pages, full_seed.source_map.pages);
assert_eq!(seed_aux, fs::read(&aux).unwrap());
let project = ProjectSnapshot::new(ProjectDefinition { let project = ProjectSnapshot::new(ProjectDefinition {
configuration: world, configuration: world,
revision: 1, revision: 1,
@@ -1812,24 +1835,41 @@ mod opening_tests {
files: BTreeMap::from([ files: BTreeMap::from([
(entry, Arc::from(source.as_bytes())), (entry, Arc::from(source.as_bytes())),
(package, Arc::from(package_bytes.as_slice())), (package, Arc::from(package_bytes.as_slice())),
(bibliography, Arc::from(bibliography_bytes.as_slice())),
]), ]),
directories: BTreeSet::new(), directories: BTreeSet::new(),
aliases: BTreeMap::new(), aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([run]), generated_roots: BTreeSet::from([run]),
generated: BTreeSet::from([aux.clone()]), generated: BTreeSet::from([aux.clone()]),
}).unwrap(); }).unwrap();
let request = request.with_project(project); let atomic = request.clone().with_project(project);
compiler.retain_opening_preamble(preamble.unwrap(), &request); compiler.retain_opening_preamble(preamble.unwrap(), &atomic);
let resumed = compiler.compile_detailed(request.clone()).unwrap(); let resumed = compiler.compile_detailed(atomic.clone()).unwrap();
assert!(resumed.entry_checkpoint_work.reused_steps > 0, "{:?}", resumed.entry_checkpoint_work); assert!(resumed.entry_checkpoint_work.reused_steps > 0, "{:?}", resumed.entry_checkpoint_work);
assert_ne!(resumed.pdf, seed.pdf); assert_ne!(resumed.pdf, seed.pdf);
let resumed_aux = fs::read(&aux).unwrap(); let resumed_aux = fs::read(&aux).unwrap();
fs::write(&aux, seed_aux).unwrap(); fs::write(&aux, seed_aux).unwrap();
let fresh = NativeCompiler::default().compile_detailed(request).unwrap(); let fresh = NativeCompiler::default().compile_detailed(atomic).unwrap();
assert_eq!(resumed.pdf, fresh.pdf); assert_eq!(resumed.pdf, fresh.pdf);
assert_eq!(resumed.source_map.pages, fresh.source_map.pages); assert_eq!(resumed.source_map.pages, fresh.source_map.pages);
assert_eq!(resumed.preview_since(None).unwrap().pages, fresh.preview_since(None).unwrap().pages); assert_eq!(resumed.preview_since(None).unwrap().pages, fresh.preview_since(None).unwrap().pages);
assert_eq!(resumed_aux, fs::read(aux).unwrap()); assert_eq!(resumed_aux, fs::read(&aux).unwrap());
// An optional lookup in the preamble itself must observe a new file.
let (previous, preamble) = compiler.start().compile_opening_seed(request.clone());
assert!(previous.is_ok() && preamble.is_some());
let before_override = fs::read(&aux).unwrap();
fs::write(&override_package, b"40pt\n").unwrap();
let (changed, _) = compiler.start()
.compile_opening_seed_with_preamble(request.clone(), preamble.as_ref());
let changed = changed.unwrap();
assert_eq!(changed.entry_checkpoint_work.reused_steps, 0);
assert!(changed.entry_checkpoint_work.rejection.is_some());
assert!(changed.resources.trace.lookups.iter()
.any(|lookup| lookup.resolved.as_ref() == Some(&override_package)));
fs::write(&aux, before_override).unwrap();
let full_changed = NativeCompiler::default().compile_detailed(request).unwrap();
assert_eq!(changed.pdf, full_changed.pdf);
} }
#[test] #[test]
@@ -1885,6 +1925,28 @@ mod opening_tests {
} }
} }
#[test]
fn confirmed_ctex_dependency_prepares_before_retry() {
for (label, name, prepare_new_resources, status, prepare) in [
("ctex-external", "ctex.sty", true, 409, true),
("ctex-old-client", "ctex.sty", false, 200, false),
("ctex-absent", "absent/ctex.sty", true, 422, false),
] {
let (run, editor, compiler, _) = prepare_with_packages(
label, "", &[("ctex.sty", "\\relax\n")],
);
let source = format!("{XETEX_HEADER}\\input {name}\n{RULE}\n");
let mut session = EditorSession::new(run, editor, compiler, None);
session.mode_choice = Some(ModeChoice {
preference: CompileMode::Unicode,
effective: CompileMode::Unicode,
});
let (actual, body) = submit_with_discovery(&mut session, 2, Some(source), prepare_new_resources);
assert_eq!(actual, status, "{body}");
assert_eq!(body.get("prepare_resources"), prepare.then_some(&Value::Bool(true)));
}
}
#[test] #[test]
fn missing_opentype_input_remains_a_preview_error() { fn missing_opentype_input_remains_a_preview_error() {
let (run, editor, compiler, _) = prepare_with_packages( let (run, editor, compiler, _) = prepare_with_packages(
+12 -3
View File
@@ -25,11 +25,12 @@ pub(super) fn read_with_date(path: &Path) -> io::Result<(Vec<u8>, Option<SystemT
#[derive(Default)] #[derive(Default)]
pub(super) struct PackageDiscovery { pub(super) struct PackageDiscovery {
expansions: u8, expansions: u8,
prepare_ctex: bool,
} }
impl PackageDiscovery { impl PackageDiscovery {
pub(super) fn needs_preparation(&self) -> bool { pub(super) fn needs_preparation(&self) -> bool {
self.expansions >= 2 self.prepare_ctex || self.expansions >= 2
} }
} }
@@ -79,6 +80,7 @@ impl ResourceCapture {
let mut added = BTreeMap::new(); let mut added = BTreeMap::new();
let mut dates = BTreeMap::new(); let mut dates = BTreeMap::new();
let mut added_package_file = false; let mut added_package_file = false;
let mut added_ctex = false;
for lookup in trace for lookup in trace
.lookups .lookups
.iter() .iter()
@@ -107,6 +109,12 @@ impl ResourceCapture {
["sty", "cls", "clo", "def", "cfg", "fd", "ldf"] ["sty", "cls", "clo", "def", "cfg", "fd", "ldf"]
.iter().any(|known| extension.eq_ignore_ascii_case(known)) .iter().any(|known| extension.eq_ignore_ascii_case(known))
}); });
added_ctex |= lookup.kind == ResourceKind::Tex
&& lookup.error.is_none()
&& Path::new(&lookup.name).file_name().and_then(|name| name.to_str())
.is_some_and(|name| name.eq_ignore_ascii_case("ctex.sty"))
&& path.file_name().and_then(|name| name.to_str())
.is_some_and(|name| name.eq_ignore_ascii_case("ctex.sty"));
added.insert(path, Arc::from(bytes)); added.insert(path, Arc::from(bytes));
} }
} }
@@ -117,8 +125,9 @@ impl ResourceCapture {
if let Some(discovery) = package_discovery if let Some(discovery) = package_discovery
&& added_package_file && added_package_file
{ {
// A single missing input can be captured in place. Another // CTeX brings a package tree. Other packages can first retry
// package-file miss after a retry can indicate a new package tree. // with a single capture before preparing a new tree.
discovery.prepare_ctex |= added_ctex;
discovery.expansions += 1; discovery.expansions += 1;
if discovery.needs_preparation() { if discovery.needs_preparation() {
return None; return None;
+68 -12
View File
@@ -463,6 +463,21 @@ impl From<&CompileRequest> for AttemptRequest {
} }
} }
} }
impl AttemptRequest {
fn matches_checkpoint_job(&self, request: &CompileRequest) -> bool {
self.input == request.input
&& self.output == request.output
&& self.entry == request.entry
&& self.target == request.target
&& self.etex == request.etex
&& self.input_profile == request.input_profile
&& self.translation_file == request.translation_file
&& self.time == request.time
&& self.limits == request.limits
&& self.terminal == request.terminal
}
}
impl std::fmt::Display for CompileFailure { impl std::fmt::Display for CompileFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.error.fmt(f) self.error.fmt(f)
@@ -1095,6 +1110,11 @@ fn report(files: &Files, request: &CompileRequest) -> Result<(), CompileError> {
Ok(()) Ok(())
} }
struct OpeningSeed<'a> {
previous: Option<&'a OpeningPreamble>,
captured: &'a mut Option<OpeningPreamble>,
}
impl CompileJob { impl CompileJob {
pub fn revision(&self) -> u64 { pub fn revision(&self) -> u64 {
self.job.revision() self.job.revision()
@@ -1115,9 +1135,21 @@ impl CompileJob {
pub fn compile_opening_seed( pub fn compile_opening_seed(
self, self,
request: CompileRequest, request: CompileRequest,
) -> (Result<Arc<CompiledDocument>, CompileFailure>, Option<OpeningPreamble>) {
self.compile_opening_seed_with_preamble(request, None)
}
/// Continue from a prior live seed if the current host verifies the prefix.
pub fn compile_opening_seed_with_preamble(
self,
request: CompileRequest,
previous: Option<&OpeningPreamble>,
) -> (Result<Arc<CompiledDocument>, CompileFailure>, Option<OpeningPreamble>) { ) -> (Result<Arc<CompiledDocument>, CompileFailure>, Option<OpeningPreamble>) {
let mut preamble = None; let mut preamble = None;
let result = self.compile_attempt_with_preamble(request, Some(&mut preamble)); let result = self.compile_attempt_with_preamble(
request,
Some(OpeningSeed { previous, captured: &mut preamble }),
);
if result.is_err() { if result.is_err() {
preamble = None; preamble = None;
} }
@@ -1155,7 +1187,7 @@ impl CompileJob {
fn compile_attempt_with_preamble( fn compile_attempt_with_preamble(
&self, &self,
mut request: CompileRequest, mut request: CompileRequest,
preamble: Option<&mut Option<OpeningPreamble>>, preamble: Option<OpeningSeed<'_>>,
) -> Result<Arc<CompiledDocument>, CompileFailure> { ) -> Result<Arc<CompiledDocument>, CompileFailure> {
if self.compiler.entry_checkpoints.is_some() if self.compiler.entry_checkpoints.is_some()
&& checkpoint_guard::can_stage(&request) && checkpoint_guard::can_stage(&request)
@@ -1208,7 +1240,7 @@ impl CompileJob {
evidence: &mut AttemptEvidence, evidence: &mut AttemptEvidence,
retry_suffix: Option<(String, usize)>, retry_suffix: Option<(String, usize)>,
suffix_failure: &mut Option<(String, usize)>, suffix_failure: &mut Option<(String, usize)>,
opening_preamble: Option<&mut Option<OpeningPreamble>>, opening_preamble: Option<OpeningSeed<'_>>,
) -> Result<Arc<CompiledDocument>, CompileError> { ) -> Result<Arc<CompiledDocument>, CompileError> {
let cancellation = self.job.cancellation(); let cancellation = self.job.cancellation();
check(&cancellation)?; check(&cancellation)?;
@@ -1226,6 +1258,15 @@ impl CompileJob {
.entry_checkpoints .entry_checkpoints
.as_deref() .as_deref()
.filter(|_| checkpoint_guard::can_stage(&request)); .filter(|_| checkpoint_guard::can_stage(&request));
let opening_preamble = opening_preamble.filter(|_| {
self.compiler.entry_checkpoints.is_some()
&& request.inputs.is_none()
&& request.project.is_none()
&& request.target == Target::Shipouts
&& !request.terminal
&& request.resource_manifest.is_none()
&& request.layout_manifest.is_none()
});
let format_cache = &self.compiler.format_cache; let format_cache = &self.compiler.format_cache;
let mut entry_checkpoint_work = EntryCheckpointWork::default(); let mut entry_checkpoint_work = EntryCheckpointWork::default();
let allow_suffix = retry_suffix.is_none(); let allow_suffix = retry_suffix.is_none();
@@ -1233,7 +1274,7 @@ impl CompileJob {
entry_checkpoint_work.rejection = Some(error); entry_checkpoint_work.rejection = Some(error);
entry_checkpoint_work.discarded_suffix_attempt_steps = discarded_steps; entry_checkpoint_work.discarded_suffix_attempt_steps = discarded_steps;
} }
let (active_checkpoint, prepared) = let (active_checkpoint, mut prepared) =
if let Some(available) = checkpoints.and_then(CheckpointCache::current) { if let Some(available) = checkpoints.and_then(CheckpointCache::current) {
match available.prepare(&request, format_cache, &cancellation, evidence) { match available.prepare(&request, format_cache, &cancellation, evidence) {
Ok((selected, prepared)) => (Some(selected), Some(prepared)), Ok((selected, prepared)) => (Some(selected), Some(prepared)),
@@ -1247,6 +1288,20 @@ impl CompileJob {
} else { } else {
(None, None) (None, None)
}; };
let mut opening_resume = None;
if let Some(previous) = opening_preamble.as_ref().and_then(|seed| seed.previous) {
match previous.prepare_next(request, revision, format_cache, &cancellation, evidence) {
Ok((preamble, host)) => {
opening_resume = Some(preamble);
prepared = Some(host);
}
Err(error) => {
check(&cancellation)?;
*evidence = AttemptEvidence::new(revision);
entry_checkpoint_work.rejection = Some(error.to_string());
}
}
}
let PreparedJob { let PreparedJob {
executor, executor,
format_preparation, format_preparation,
@@ -1308,6 +1363,13 @@ impl CompileJob {
suffix_failure, suffix_failure,
)?; )?;
(executed, None, Some(next), reused_layouts) (executed, None, Some(next), reused_layouts)
} else if let Some(preamble) = opening_resume {
debug_assert!(executor.is_none());
let executed = preamble.resume(
&self.job, source, files, cache.clone(), &mut entry_checkpoint_work,
);
*opening_preamble.expect("resumed an opening seed").captured = Some(preamble);
(executed.map(ResumedExecution::Complete), None, None, None)
} else { } else {
let executor = executor let executor = executor
.expect("fresh native job has an executor") .expect("fresh native job has an executor")
@@ -1319,16 +1381,10 @@ impl CompileJob {
snapshot.report_capture(&mut entry_checkpoint_work); snapshot.report_capture(&mut entry_checkpoint_work);
} }
(executed.map(ResumedExecution::Complete), captured, None, None) (executed.map(ResumedExecution::Complete), captured, None, None)
} else if let Some(preamble) = opening_preamble } else if let Some(preamble) = opening_preamble {
&& self.compiler.entry_checkpoints.is_some()
&& request.inputs.is_none()
&& request.project.is_none()
&& request.target == Target::Shipouts
&& !request.terminal
{
let (executed, captured) = let (executed, captured) =
OpeningPreamble::discover(request, &self.job, executor, source, files); OpeningPreamble::discover(request, &self.job, executor, source, files);
*preamble = captured; *preamble.captured = captured;
(executed.map(ResumedExecution::Complete), None, None, None) (executed.map(ResumedExecution::Complete), None, None, None)
} else { } else {
(self.job.run_detailed(executor, source, files).map(ResumedExecution::Complete), (self.job.run_detailed(executor, source, files).map(ResumedExecution::Complete),
+104 -17
View File
@@ -52,11 +52,12 @@ pub struct OpeningPreamble {
} }
struct OpeningBoundary { struct OpeningBoundary {
entry: EntryCheckpoint, entry: Arc<EntryCheckpoint>,
slots: CaptureSlots, slots: CaptureSlots,
trace: ResourceTrace, trace: ResourceTrace,
written: BTreeSet<PathBuf>, written: BTreeSet<PathBuf>,
call_count: usize, call_count: usize,
live: Option<crate::native_job::ReplayBoundary>,
} }
impl OpeningPreamble { impl OpeningPreamble {
@@ -91,18 +92,28 @@ impl OpeningPreamble {
return None; return None;
} }
match schedule.select_source(source, pages) { match schedule.select_source(source, pages) {
Some(Capture::Entry(slots)) if slots.preamble || slots.preamble_after_input => Some(slots), Some(Capture::Entry(slots)) if slots.preamble || slots.preamble_after_input => {
Some((slots, pages == 0))
}
_ => None, _ => None,
} }
}, },
|slots, entry, host| { |(slots, before_shipout), entry, host| {
if let Some((trace, calls)) = host.prefix() { if let Some((trace, calls)) = host.prefix() {
let live = if before_shipout && trace.read_errors.is_empty()
&& trace.namespace_capture_failures.is_empty()
{
host.files().opening_replay_boundary()
} else {
None
};
entries.push(OpeningBoundary { entries.push(OpeningBoundary {
entry, entry: Arc::new(entry),
slots, slots,
trace: trace.clone(), trace: trace.clone(),
written: host.generated_outputs().clone(), written: host.generated_outputs().clone(),
call_count: calls.len(), call_count: calls.len(),
live,
}); });
} }
}, },
@@ -122,6 +133,93 @@ impl OpeningPreamble {
(result, preamble) (result, preamble)
} }
pub(super) fn prepare_next(
&self,
request: &CompileRequest,
revision: u64,
cache: &FormatCache,
cancellation: &Cancellation,
evidence: &mut AttemptEvidence,
) -> Result<(Self, PreparedJob), CompileError> {
if self.original.world != request.world
|| !self.original.matches_checkpoint_job(request)
|| !matches!(self.original.generated_inputs, GeneratedInputPolicy::Observe)
|| !matches!(request.generated_inputs, GeneratedInputPolicy::Observe)
{
return Err("opening preamble job parameters changed".to_owned().into());
}
let mut rejected = "no read-only opening preamble retained".to_owned();
for boundary in self.entries.iter().rev() {
let Some(previous_host) = &boundary.live else { continue; };
let mut attempt = AttemptEvidence::new(revision);
attempt.phase = evidence.phase;
let mut prepared = prepare_checked(
request, false, Some(cache), cancellation, &mut attempt, None,
EffectMode::Live, KernelPreparation::Resume,
)?;
let files = &mut prepared.files;
if files.resource_trace().reads.first() != boundary.trace.reads.first()
|| !boundary.entry.accepts_entry_bytes(&prepared.source.name, &prepared.source.data)
{
return Err("opening preamble entry changed".to_owned().into());
}
let calls = &self.calls[..boundary.call_count];
let replay = calls.iter().try_for_each(|call| {
check(cancellation)?;
call.replay(files, None).map_err(CompileError::Host)
});
if let Err(error) = replay {
rejected = error.to_string();
continue;
}
// The host compares what the prefix actually observed. An AUX
// created by the earlier pass can change the initial ledger
// without changing anything read by this preamble.
let live = files.opening_replay_boundary();
if live.as_ref() != Some(previous_host) {
rejected = "opening preamble observations changed".into();
continue;
}
let initial = files.preparation().generated_initial.clone()
.ok_or("opening replay requires observed generated inputs".to_owned())?;
let next = Self {
revision,
original: AttemptRequest::from(request),
entry_path: self.entry_path.clone(),
initial,
entries: vec![OpeningBoundary {
entry: boundary.entry.clone(),
slots: boundary.slots,
trace: files.resource_trace().clone(),
written: BTreeSet::new(),
call_count: calls.len(),
live,
}],
calls: calls.to_vec(),
};
*evidence = attempt;
return Ok((next, prepared));
}
Err(rejected.into())
}
pub(super) fn resume(
&self,
job: &RevisionJob,
source: SourceFile,
files: &mut Files,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
work: &mut EntryCheckpointWork,
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
let entry = &self.entries[0].entry;
work.reused_frontier = Some(entry.frontier());
work.reused_steps = entry.completed_steps();
work.replayed_calls = self.calls.len();
job.resume_capturing_sources_after_host_replay(
entry, source, None, files, line_break_cache, |_, _| None::<()>, |(), _, _| {},
).expect("the opening checkpoint already accepted the complete entry")
}
pub(super) fn bind(self, request: &CompileRequest) -> Option<Arc<CheckpointSet>> { pub(super) fn bind(self, request: &CompileRequest) -> Option<Arc<CheckpointSet>> {
if request.world != self.original.world { if request.world != self.original.world {
return None; return None;
@@ -140,7 +238,7 @@ impl OpeningPreamble {
) { ) {
guard.original = self.original.clone(); guard.original = self.original.clone();
entries.push(Arc::new(CachedCheckpoint { entries.push(Arc::new(CachedCheckpoint {
entry: Arc::new(boundary.entry), entry: boundary.entry,
guard, guard,
replay_count: boundary.call_count, replay_count: boundary.call_count,
slots: Capture::Entry(boundary.slots), slots: Capture::Entry(boundary.slots),
@@ -1885,18 +1983,7 @@ impl PrefixInputGuard {
request: &'a CompileRequest, request: &'a CompileRequest,
closed_source: Option<&Path>, closed_source: Option<&Path>,
) -> Result<&'a ProjectSnapshot, String> { ) -> Result<&'a ProjectSnapshot, String> {
let old = &self.original; if !self.original.matches_checkpoint_job(request) {
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()); return Err("checkpoint job parameters changed".into());
} }
let current = request let current = request
+8
View File
@@ -759,6 +759,14 @@ impl Files {
ReplayBoundary { entry_bytes, state } ReplayBoundary { entry_bytes, state }
} }
pub(super) fn opening_replay_boundary(&self) -> Option<ReplayBoundary> {
// An attempted open can already have touched a file even if it
// ultimately reports a failure. Live replay may only write its log.
self.stream_io.events().iter().all(|event| {
!matches!(event.effect, StreamEffect::OpenOutputRequested { .. })
}).then(|| self.replay_boundary())
}
pub(super) fn replay_world(&self) -> &FileWorld { pub(super) fn replay_world(&self) -> &FileWorld {
&self.world &self.world
} }