Resume native editor jobs through verified checkpoints
This commit is contained in:
1 parent
31364ae33e
commit
0abf700817
19 files changed
+2311
-93
No files matched your search
@@ -0,0 +1,359 @@
|
||||
//! Capture and verify the native host calls made by an entry prefix.
|
||||
use super::*;
|
||||
use std::fmt::Debug;
|
||||
#[cfg(test)]
|
||||
use std::{fs, path::Path};
|
||||
#[cfg(test)]
|
||||
use texrra_tex_core::source_map::SourceMap;
|
||||
use texrra_tex_core::{
|
||||
execution::{Error, HostResourceUsage, WriteDestination},
|
||||
resources::{LoadedResource, ResourceKind},
|
||||
};
|
||||
|
||||
pub(super) type Call = Box<dyn Fn(&mut Files) -> Result<(), String> + Send + Sync>;
|
||||
const MAX_REPLAY_CALLS: usize = 65_536;
|
||||
|
||||
pub(super) struct RecordingHost<'a> {
|
||||
files: &'a mut Files,
|
||||
calls: Option<Vec<Call>>,
|
||||
}
|
||||
|
||||
impl<'a> RecordingHost<'a> {
|
||||
pub(super) fn new(files: &'a mut Files) -> Self {
|
||||
Self {
|
||||
files,
|
||||
calls: Some(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn capture(&mut self) -> Option<(Vec<Call>, ResourceTrace)> {
|
||||
Some((self.calls.take()?, self.files.resource_trace().clone()))
|
||||
}
|
||||
|
||||
fn record<T, K: Debug + PartialEq + Send + Sync + 'static>(
|
||||
&mut self,
|
||||
name: &'static str,
|
||||
call: impl Fn(&mut Files) -> T + Send + Sync + 'static,
|
||||
evidence: impl Fn(&T) -> K + Send + Sync + 'static,
|
||||
) -> T {
|
||||
let result = call(self.files);
|
||||
if let Some(calls) = &mut self.calls {
|
||||
if calls.len() == MAX_REPLAY_CALLS {
|
||||
self.calls = None;
|
||||
return result;
|
||||
}
|
||||
let expected = evidence(&result);
|
||||
calls.push(Box::new(move |files| {
|
||||
let observed = evidence(&call(files));
|
||||
if observed == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!(
|
||||
"{name} changed: expected {expected:?}, observed {observed:?}"
|
||||
))
|
||||
}
|
||||
}));
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! call {
|
||||
($host:ident, $method:ident($($arg:expr),*); $evidence:expr) => {
|
||||
$host.record(stringify!($method), move |files| files.$method($($arg),*), $evidence)
|
||||
};
|
||||
($host:ident, $method:ident($($arg:expr),*)) => {
|
||||
call!($host, $method($($arg),*); Clone::clone)
|
||||
};
|
||||
}
|
||||
|
||||
impl SourceProvider for RecordingHost<'_> {
|
||||
fn execution_resource_trace(&self) -> Option<&ResourceTrace> {
|
||||
self.files.execution_resource_trace()
|
||||
}
|
||||
fn set_interaction_mode(&mut self, mode: u8) -> Result<(), String> {
|
||||
call!(self, set_interaction_mode(mode))
|
||||
}
|
||||
fn resource_usage(&mut self) -> Result<Option<HostResourceUsage>, String> {
|
||||
call!(self, resource_usage())
|
||||
}
|
||||
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, read(&name, &from); |result| {
|
||||
result.as_ref().map(|file| (file.name.clone(), digest(&file.data))).map_err(Clone::clone)
|
||||
})
|
||||
}
|
||||
fn resource(
|
||||
&mut self,
|
||||
kind: ResourceKind,
|
||||
name: &str,
|
||||
from: &str,
|
||||
) -> Result<LoadedResource, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, resource(kind, &name, &from); |result| {
|
||||
result.as_ref().map(|resource| resource.version.clone()).map_err(Clone::clone)
|
||||
})
|
||||
}
|
||||
fn virtual_font(&mut self, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, virtual_font(&name, &from); |result| {
|
||||
result.as_ref().map(|resource| resource.as_ref().map(|item| item.version.clone()))
|
||||
.map_err(Clone::clone)
|
||||
})
|
||||
}
|
||||
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))
|
||||
}
|
||||
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))
|
||||
}
|
||||
fn pk_font(&mut self, name: &str, dpi: u32, from: &str) -> Result<LoadedResource, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, pk_font(&name, dpi, &from); |result| {
|
||||
result.as_ref().map(|resource| resource.version.clone()).map_err(Clone::clone)
|
||||
})
|
||||
}
|
||||
fn default_pk_resolution(&mut self) -> Result<i32, String> {
|
||||
call!(self, default_pk_resolution())
|
||||
}
|
||||
fn observe_message(&mut self, text: &str) -> Result<(), String> {
|
||||
let text = text.to_owned();
|
||||
call!(self, observe_message(&text))
|
||||
}
|
||||
fn observe_diagnostic(
|
||||
&mut self,
|
||||
destination: WriteDestination,
|
||||
text: &str,
|
||||
) -> Result<(), String> {
|
||||
let text = text.to_owned();
|
||||
call!(self, observe_diagnostic(destination, &text))
|
||||
}
|
||||
fn observe_inline_diagnostic(
|
||||
&mut self,
|
||||
destination: WriteDestination,
|
||||
text: &str,
|
||||
) -> Result<(), String> {
|
||||
let text = text.to_owned();
|
||||
call!(self, observe_inline_diagnostic(destination, &text))
|
||||
}
|
||||
fn observe_raw_diagnostic(
|
||||
&mut self,
|
||||
destination: WriteDestination,
|
||||
text: &str,
|
||||
) -> Result<(), String> {
|
||||
let text = text.to_owned();
|
||||
call!(self, observe_raw_diagnostic(destination, &text))
|
||||
}
|
||||
fn observe_pseudo_input(&mut self, opening: bool) -> Result<(), String> {
|
||||
call!(self, observe_pseudo_input(opening))
|
||||
}
|
||||
fn observe_diagnostic_pair(&mut self, log: &str, terminal: &str) -> Result<(), String> {
|
||||
let (log, terminal) = (log.to_owned(), terminal.to_owned());
|
||||
call!(self, observe_diagnostic_pair(&log, &terminal))
|
||||
}
|
||||
fn observe_error(&mut self, error: &Error) -> Result<(), String> {
|
||||
self.calls = None;
|
||||
self.files.observe_error(error)
|
||||
}
|
||||
fn open_in(&mut self, stream: u8, name: &str, from: &str) -> Result<Option<String>, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, open_in(stream, &name, &from))
|
||||
}
|
||||
fn read_line(&mut self, stream: u8) -> Result<Option<Vec<u8>>, String> {
|
||||
call!(self, read_line(stream))
|
||||
}
|
||||
fn close_in(&mut self, stream: u8) -> Result<(), String> {
|
||||
call!(self, close_in(stream))
|
||||
}
|
||||
fn open_out(&mut self, stream: u8, name: &str, from: &str) -> Result<String, String> {
|
||||
let (name, from) = (name.to_owned(), from.to_owned());
|
||||
call!(self, open_out(stream, &name, &from))
|
||||
}
|
||||
fn write_out(&mut self, stream: u8, text: &str) -> Result<(), String> {
|
||||
let text = text.to_owned();
|
||||
call!(self, write_out(stream, &text))
|
||||
}
|
||||
fn close_out(&mut self, stream: u8) -> Result<(), String> {
|
||||
call!(self, close_out(stream))
|
||||
}
|
||||
fn diagnostic(&mut self, destination: WriteDestination, text: &str) -> Result<(), String> {
|
||||
let text = text.to_owned();
|
||||
call!(self, diagnostic(destination, &text))
|
||||
}
|
||||
}
|
||||
|
||||
fn digest(bytes: &[u8]) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires the preserved original A3 format and a dedicated output directory"]
|
||||
fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
|
||||
let cwd = PathBuf::from(std::env::var_os("TEXRRA_A3_CHECKPOINT_WORK").unwrap());
|
||||
fs::create_dir(&cwd).unwrap();
|
||||
let format = PathBuf::from(std::env::var_os("TEXRRA_A3_CHECKPOINT_FORMAT").unwrap());
|
||||
let resource_file = std::env::var_os("TEXRRA_A3_CHECKPOINT_FORMAT_RESOURCES").unwrap();
|
||||
let resource_manifest: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(resource_file).unwrap()).unwrap();
|
||||
let roots = serde_json::from_value(resource_manifest["texmf_roots"].clone()).unwrap();
|
||||
let fixture = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("examples/native-format-stage/a3-pages/main.tex");
|
||||
let original = fs::read_to_string(fixture).unwrap();
|
||||
let marker = "This explicit page follows the naturally paginated material.";
|
||||
assert_eq!(original.matches(marker).count(), 1);
|
||||
let marker_start = original.find(marker).unwrap();
|
||||
let mut world = WorldConfig::from_environment(&cwd, roots).unwrap();
|
||||
world.input_policy = texrra_tex_core::resources::InputPolicy::Tex;
|
||||
let mut request = CompileRequest::new(
|
||||
world,
|
||||
"main.tex",
|
||||
"main.pdf",
|
||||
JobTime::new(2026, 11, 18, 1000)
|
||||
.unwrap()
|
||||
.with_pdf_clock(0, 0)
|
||||
.unwrap(),
|
||||
);
|
||||
request.entry = Entry::Format(format);
|
||||
request.etex = true;
|
||||
request.limits.steps = 600_000_000;
|
||||
fs::write(cwd.join("main.tex"), &original).unwrap();
|
||||
NativeCompiler::default().compile(request.clone()).unwrap();
|
||||
let aux = fs::read(cwd.join("main.aux")).unwrap();
|
||||
|
||||
let cancellation = Cancellation::default();
|
||||
let obtain = || {
|
||||
prepare(
|
||||
&request,
|
||||
false,
|
||||
None,
|
||||
&cancellation,
|
||||
&mut AttemptEvidence::new(1),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let PreparedJob {
|
||||
executor,
|
||||
source,
|
||||
mut files,
|
||||
..
|
||||
} = obtain();
|
||||
let mut record = RecordingHost {
|
||||
files: &mut files,
|
||||
calls: Some(Vec::new()),
|
||||
};
|
||||
let (original_execution, captured) = executor.run_capturing_entry(
|
||||
source,
|
||||
&mut record,
|
||||
marker_start.saturating_sub(1200),
|
||||
|host| host.calls.take().unwrap(),
|
||||
);
|
||||
let original_execution = original_execution.expect("the original A3 job reaches its end");
|
||||
let (checkpoint, calls) = captured.expect("a physical command boundary before the edited line");
|
||||
assert!(checkpoint.frontier() <= marker_start);
|
||||
assert!(checkpoint.completed_steps() > 100_000);
|
||||
files.finish().unwrap();
|
||||
drop(files);
|
||||
assert_eq!(aux, fs::read(cwd.join("main.aux")).unwrap());
|
||||
eprintln!(
|
||||
"checkpoint physical frontier {} of {}, skips {} of {} steps, replays {} host calls",
|
||||
checkpoint.frontier(),
|
||||
marker_start,
|
||||
checkpoint.completed_steps(),
|
||||
original_execution.steps,
|
||||
calls.len()
|
||||
);
|
||||
|
||||
let edits = [
|
||||
original.replace(
|
||||
marker,
|
||||
"This edited page follows the naturally paginated material.",
|
||||
),
|
||||
original.replace(
|
||||
marker,
|
||||
"This revised page also uses the same open auxiliary stream.",
|
||||
),
|
||||
];
|
||||
for (number, edit) in edits.into_iter().enumerate() {
|
||||
fs::write(cwd.join("main.tex"), edit).unwrap();
|
||||
let PreparedJob {
|
||||
source,
|
||||
mut files,
|
||||
output,
|
||||
..
|
||||
} = obtain();
|
||||
assert!(checkpoint.accepts_entry(&source));
|
||||
let mut changed_prefix = source.clone();
|
||||
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}"));
|
||||
}
|
||||
let resumed = checkpoint
|
||||
.resume_after_host_replay(source, &mut files, Cancellation::default())
|
||||
.expect("validated entry remains resumable")
|
||||
.unwrap();
|
||||
let execution =
|
||||
RevisionExecution::from_execution(1, resumed, Some(files.resource_trace().clone()));
|
||||
let mut pages = execution.execution.shipout_display_lists().unwrap();
|
||||
texrra_tex_core::native_font::resolve_native_fonts(&mut pages, &mut files).unwrap();
|
||||
let source_map = SourceMap::from_revision(&execution, &pages).unwrap();
|
||||
let pdf = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document(
|
||||
&pages,
|
||||
execution.execution.state.pdf_final_options(),
|
||||
)
|
||||
.unwrap();
|
||||
for warning in &pdf.diagnostics {
|
||||
files
|
||||
.observe_message(&format!("native PDF warning: {warning}"))
|
||||
.unwrap();
|
||||
}
|
||||
files.finish().unwrap();
|
||||
drop(files);
|
||||
PreparedOutput::write(&output, &pdf.bytes)
|
||||
.unwrap()
|
||||
.commit(&output)
|
||||
.unwrap();
|
||||
let resumed_aux = fs::read(cwd.join("main.aux")).unwrap();
|
||||
let resumed_log = fs::read(cwd.join("main.log")).unwrap();
|
||||
assert_eq!(aux, resumed_aux);
|
||||
let pdf_for_preview: Arc<[u8]> = Arc::from(pdf.bytes.as_slice());
|
||||
let resumed_preview = PreviewState::new(&pages, None, false)
|
||||
.render(1, &pages, Some(&pdf_for_preview), None)
|
||||
.unwrap();
|
||||
let full = NativeCompiler::default().compile(request.clone()).unwrap();
|
||||
assert!(
|
||||
execution.execution == full.execution.execution,
|
||||
"kernel execution differs"
|
||||
);
|
||||
assert_eq!(execution.source_versions, full.execution.source_versions);
|
||||
assert_eq!(
|
||||
execution.execution_resources,
|
||||
full.execution.execution_resources
|
||||
);
|
||||
assert!(pages == full.pages, "pages or resolved paint differ");
|
||||
assert_eq!(pdf.bytes.as_slice(), full.pdf.as_deref().unwrap());
|
||||
assert!(source_map == full.source_map, "source map differs");
|
||||
assert_eq!(resumed_aux, fs::read(cwd.join("main.aux")).unwrap());
|
||||
assert_eq!(resumed_log, fs::read(cwd.join("main.log")).unwrap());
|
||||
let full_preview = full.preview_since(None).unwrap();
|
||||
assert_eq!(resumed_preview.pages.len(), 8);
|
||||
assert!(
|
||||
resumed_preview
|
||||
.pages
|
||||
.iter()
|
||||
.map(|page| &page.svg)
|
||||
.eq(full_preview.pages.iter().map(|page| &page.svg))
|
||||
);
|
||||
eprintln!(
|
||||
"edit {}: {} suffix steps, 8 equal pages; output {}, aux {}, log {}",
|
||||
number + 1,
|
||||
execution.execution.steps - checkpoint.completed_steps(),
|
||||
digest(&pdf.bytes),
|
||||
digest(&resumed_aux),
|
||||
digest(&resumed_log)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user