779 lines
30 KiB
Rust
779 lines
30 KiB
Rust
//! Capture and verify the native host calls made by an entry prefix.
|
|
use super::*;
|
|
use std::{collections::BTreeSet, fmt::Debug, path::Path};
|
|
#[cfg(test)]
|
|
use std::fs;
|
|
#[cfg(test)]
|
|
use texrra_tex_core::source_map::SourceMap;
|
|
use texrra_tex_core::{
|
|
execution::{Error, HostResourceUsage, StatisticsPhase, StatisticsReport, WriteDestination},
|
|
resources::{LoadedResource, ResourceKind, ResourceVersion},
|
|
};
|
|
|
|
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>),
|
|
EndStatistics(Arc<StatisticsReport>),
|
|
ResourceUsage(Arc<ResourceUsageRead>),
|
|
}
|
|
|
|
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>,
|
|
}
|
|
|
|
pub(super) struct ResourceUsageRead {
|
|
observed: Option<HostResourceUsage>,
|
|
entry_bytes: Option<u64>,
|
|
}
|
|
|
|
pub(super) struct RebindableSourceObservations {
|
|
pub(super) size: Option<u64>,
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
pub(super) struct ClosedSourceUsageOffset {
|
|
previous: u64,
|
|
current: u64,
|
|
}
|
|
|
|
impl ClosedSourceUsageOffset {
|
|
pub(super) fn new(previous: u64, current: u64, reads: usize) -> Option<Self> {
|
|
let reads = u64::try_from(reads).ok()?;
|
|
Some(Self {
|
|
previous: previous.checked_mul(reads)?,
|
|
current: current.checked_mul(reads)?,
|
|
})
|
|
}
|
|
}
|
|
|
|
/// Return the entire byte-read count of a closed immutable child, including
|
|
/// typed size queries. Every other observation of the child rules out reuse.
|
|
pub(super) fn closed_source_reads(
|
|
version: &ResourceVersion,
|
|
trace: &ResourceTrace,
|
|
calls: &[Call],
|
|
) -> Option<usize> {
|
|
let path = &version.path;
|
|
if trace.stream_reads.iter().any(|read| &read.path == path)
|
|
|| trace.file_modifications.iter().any(|item| &item.path == path)
|
|
|| trace.generated_lookups.iter().any(|lookup| &lookup.target == path)
|
|
|| trace.format_input_bindings.iter().any(|(old, current)| old == path || current == path)
|
|
|| trace.read_errors.iter().any(|(read, _)| read == path)
|
|
|| !trace.namespace_capture_failures.is_empty()
|
|
{
|
|
return None;
|
|
}
|
|
let mut sources = 0usize;
|
|
let mut sizes = 0usize;
|
|
for call in calls {
|
|
match call {
|
|
Call::ReadSource(source) => {
|
|
if let Ok(read) = &source.expected
|
|
&& &read.path == path
|
|
{
|
|
if read != version {
|
|
return None;
|
|
}
|
|
sources += 1;
|
|
}
|
|
}
|
|
Call::FileSize(size) if size.read.as_ref().is_some_and(|read| &read.path == path) => {
|
|
// A size query can have been replayed from an equal-sized
|
|
// earlier source. Its exact path and numeric result are
|
|
// evidence, while the actual trace authenticates the bytes.
|
|
if call.observed_file_size() != Some((path.as_path(), version.bytes)) {
|
|
return None;
|
|
}
|
|
sizes += 1;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
let count = sources.checked_add(sizes)?;
|
|
let mut actual = trace.reads.iter().filter(|read| &read.path == path);
|
|
if sources != 1 || actual.clone().count() != count || !actual.all(|read| read == version) {
|
|
return None;
|
|
}
|
|
let mut lookups = trace.lookups.iter().filter(|lookup| lookup.resolved.as_ref() == Some(path));
|
|
(lookups.clone().count() == count && lookups.all(|item| item.kind == ResourceKind::Tex))
|
|
.then_some(count)
|
|
}
|
|
|
|
impl Call {
|
|
pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> {
|
|
let Self::FileSize(read) = self else { return None };
|
|
let version = read.read.as_ref()?;
|
|
(read.observed == Ok(Some(version.bytes))).then_some((&version.path, version.bytes))
|
|
}
|
|
|
|
pub(super) fn replay(&self, files: &mut Files, partial_source: Option<&ResourceVersion>) -> Result<(), String> {
|
|
match self {
|
|
Self::Checked(call) => call(files),
|
|
Self::EndStatistics(report) => files.observe_statistics(report),
|
|
Self::ResourceUsage(read) => {
|
|
let mut expected = read.observed.clone();
|
|
if let (Some(usage), Some(previous), Some(current)) =
|
|
(&mut expected, read.entry_bytes, files.replayed_entry_bytes())
|
|
{
|
|
// The first read was the verified entry. All other
|
|
// resource and stream observations are still exact.
|
|
usage.rebind_entry_bytes(previous, current)
|
|
.ok_or("invalid replayed entry resource usage")?;
|
|
}
|
|
let actual = files.resource_usage()?;
|
|
if actual != expected {
|
|
return Err(format!("resource usage changed: expected {expected:?}, observed {actual:?}"));
|
|
}
|
|
Ok(())
|
|
}
|
|
Self::FileSize(read) => {
|
|
let before = files.resource_trace().reads.len();
|
|
let observed = files.file_size(&read.name, &read.from);
|
|
if observed != read.observed {
|
|
return Err(format!("file size changed: expected {:?}, observed {observed:?}", read.observed));
|
|
}
|
|
if let Some(expected) = &read.read
|
|
&& !matches!(&files.resource_trace().reads[before..], [actual] if actual.path == expected.path)
|
|
{
|
|
return Err(format!("file size lookup changed: {}", expected.path.display()));
|
|
}
|
|
Ok(())
|
|
}
|
|
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> {
|
|
files: &'a mut Files,
|
|
calls: Option<Vec<Call>>,
|
|
}
|
|
|
|
impl<'a> RecordingHost<'a> {
|
|
pub(super) fn new(files: &'a mut Files) -> Self {
|
|
Self::after_replay(files, &[], None)
|
|
}
|
|
|
|
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)]
|
|
pub(super) fn capture(&mut self) -> Option<(Vec<Call>, ResourceTrace)> {
|
|
let (trace, _) = self.prefix()?;
|
|
let trace = trace.clone();
|
|
Some((self.calls.take()?, trace))
|
|
}
|
|
|
|
pub(super) fn prefix(&self) -> Option<(&ResourceTrace, &[Call])> {
|
|
let calls = self.calls.as_deref()?;
|
|
(calls.len() < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), calls))
|
|
}
|
|
|
|
pub(super) fn rebindable_source_observations(
|
|
&self,
|
|
version: &ResourceVersion,
|
|
) -> Option<RebindableSourceObservations> {
|
|
let calls = self.calls.as_ref()?;
|
|
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) => {
|
|
if read.observed != Ok(Some(version.bytes)) {
|
|
return None;
|
|
}
|
|
size_reads += 1;
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
let actual_reads = self.files.resource_trace().reads.iter()
|
|
.filter(|read| read.path == version.path).count();
|
|
(source_reads == 1 && actual_reads == source_reads + size_reads).then_some(
|
|
RebindableSourceObservations { size: (size_reads > 0).then_some(version.bytes) },
|
|
)
|
|
}
|
|
|
|
pub(super) fn files(&self) -> &Files {
|
|
self.files
|
|
}
|
|
|
|
pub(super) fn replay_suffix(
|
|
&mut self,
|
|
calls: &[Call],
|
|
end_statistics: Option<&StatisticsReport>,
|
|
closed_source: Option<ClosedSourceUsageOffset>,
|
|
cancellation: &Cancellation,
|
|
) -> Result<(), String> {
|
|
let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?;
|
|
if recorded.len() + calls.len() >= MAX_REPLAY_CALLS {
|
|
return Err("completed suffix exceeds the host recording budget".into());
|
|
}
|
|
for call in calls {
|
|
check(cancellation).map_err(|error| error.to_string())?;
|
|
let call = match call {
|
|
Call::EndStatistics(report) => {
|
|
// The kernel has already checked and translated this report.
|
|
let translated = end_statistics.ok_or("completed suffix is missing its final statistics")?;
|
|
if report.as_ref() == translated {
|
|
call.clone()
|
|
} else {
|
|
Call::EndStatistics(Arc::new(translated.clone()))
|
|
}
|
|
}
|
|
Call::ResourceUsage(read) if closed_source.is_some_and(|bytes| bytes.previous != bytes.current) => {
|
|
let bytes = closed_source.expect("checked closed source adjustment");
|
|
let mut observed = read.observed.clone();
|
|
if let Some(usage) = &mut observed {
|
|
usage.rebind_entry_bytes(bytes.previous, bytes.current)
|
|
.ok_or("invalid replayed child resource usage")?;
|
|
}
|
|
Call::ResourceUsage(Arc::new(ResourceUsageRead {
|
|
observed,
|
|
entry_bytes: read.entry_bytes,
|
|
}))
|
|
}
|
|
call => call.clone(),
|
|
};
|
|
call.replay(self.files, None)?;
|
|
recorded.push(call);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
|
|
self.files.generated_outputs()
|
|
}
|
|
|
|
pub(super) fn into_calls(self) -> Option<Vec<Call>> {
|
|
self.calls
|
|
}
|
|
|
|
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 {
|
|
return result;
|
|
}
|
|
let expected = evidence(&result);
|
|
calls.push(Call::Checked(Arc::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 match_pdf_regex(
|
|
&mut self,
|
|
request: &texrra_tex_core::execution::RegexRequest,
|
|
cancellation: Option<&Cancellation>,
|
|
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
|
|
// Matching consumes only kernel-supplied bytes and is pinned to
|
|
// this executable on registered frontends. Its result is kernel state.
|
|
self.files.match_pdf_regex(request, cancellation)
|
|
}
|
|
|
|
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 replayed_entry_bytes(&self) -> Option<u64> {
|
|
self.files.replayed_entry_bytes()
|
|
}
|
|
fn resource_usage(&mut self) -> Result<Option<HostResourceUsage>, String> {
|
|
let observed = self.files.resource_usage()?;
|
|
if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS {
|
|
calls.push(Call::ResourceUsage(Arc::new(ResourceUsageRead {
|
|
observed: observed.clone(),
|
|
entry_bytes: self.files.replayed_entry_bytes(),
|
|
})));
|
|
}
|
|
Ok(observed)
|
|
}
|
|
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
|
|
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,
|
|
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 resource_with_lookup_path(
|
|
&mut self,
|
|
kind: ResourceKind,
|
|
name: &str,
|
|
from: &str,
|
|
) -> Result<(LoadedResource, PathBuf), String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, resource_with_lookup_path(kind, &name, &from); |result| {
|
|
result.as_ref().map(|(resource, path)| (resource.version.clone(), path.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 named_font(
|
|
&mut self,
|
|
name: &str,
|
|
style: texrra_tex_core::resources::FontStyle,
|
|
from: &str,
|
|
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
|
|
self.named_font_with_size(name, style, None, from)
|
|
}
|
|
fn named_font_with_size(
|
|
&mut self,
|
|
name: &str,
|
|
style: texrra_tex_core::resources::FontStyle,
|
|
optical_points: Option<f64>,
|
|
from: &str,
|
|
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, named_font_with_size(&name, style, optical_points, &from); |result| {
|
|
result.as_ref().map(|result| result.as_ref().map(|font| {
|
|
(font.resource.version.clone(), font.index, font.full_name.clone())
|
|
})).map_err(Clone::clone)
|
|
})
|
|
}
|
|
fn pdf_truetype(
|
|
&mut self, name: &str, from: &str,
|
|
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, pdf_truetype(&name, &from); |result| {
|
|
result.as_ref().map(|result| result.as_ref().map(|font| {
|
|
(font.resource.version.clone(), font.index, font.full_name.clone())
|
|
})).map_err(Clone::clone)
|
|
})
|
|
}
|
|
fn pdf_cff(
|
|
&mut self, name: &str, from: &str, cid_keyed: bool,
|
|
) -> Result<Option<texrra_tex_core::resources::NamedFont>, String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, pdf_cff(&name, &from, cid_keyed); |result| {
|
|
result.as_ref().map(|result| result.as_ref().map(|font| {
|
|
(font.resource.version.clone(), font.index, font.full_name.clone())
|
|
})).map_err(Clone::clone)
|
|
})
|
|
}
|
|
fn optional_font_file(&mut self, kind: ResourceKind, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, optional_font_file(kind, &name, &from); |result| {
|
|
result.as_ref().map(|resource| resource.as_ref().map(|item| item.version.clone()))
|
|
.map_err(Clone::clone)
|
|
})
|
|
}
|
|
fn optional_font_map(&mut self, name: &str, from: &str) -> Result<Option<LoadedResource>, String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, optional_font_map(&name, &from); |result| {
|
|
result.as_ref().map(|resource| resource.as_ref().map(|item| item.version.clone()))
|
|
.map_err(Clone::clone)
|
|
})
|
|
}
|
|
fn optional_tex_input(
|
|
&mut self,
|
|
name: &str,
|
|
from: &str,
|
|
) -> Result<Option<LoadedResource>, String> {
|
|
let (name, from) = (name.to_owned(), from.to_owned());
|
|
call!(self, optional_tex_input(&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 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))
|
|
}
|
|
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_message_bytes(&mut self, bytes: &[u8]) -> Result<(), String> {
|
|
let bytes = bytes.to_owned();
|
|
call!(self, observe_message_bytes(&bytes))
|
|
}
|
|
fn observe_diagnostic(
|
|
&mut self,
|
|
destination: WriteDestination,
|
|
text: &str,
|
|
) -> Result<(), String> {
|
|
let text = text.to_owned();
|
|
call!(self, observe_diagnostic(destination, &text))
|
|
}
|
|
fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> {
|
|
// Shipout reports do not write the step count in their transcript.
|
|
if !matches!(&report.phase, StatisticsPhase::End { .. }) {
|
|
return self.observe_diagnostic(report.destination, &report.text);
|
|
}
|
|
self.files.observe_statistics(report)?;
|
|
if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS {
|
|
calls.push(Call::EndStatistics(Arc::new(report.clone())));
|
|
}
|
|
Ok(())
|
|
}
|
|
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 read_xe_line(
|
|
&mut self,
|
|
stream: u8,
|
|
framing: texrra_tex_core::execution::XeLineFraming,
|
|
) -> Result<Option<Vec<u8>>, String> {
|
|
call!(self, read_xe_line(stream, framing))
|
|
}
|
|
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 write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> {
|
|
let bytes = bytes.to_owned();
|
|
call!(self, write_out_bytes(stream, &bytes))
|
|
}
|
|
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 diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> {
|
|
let bytes = bytes.to_owned();
|
|
call!(self, diagnostic_bytes(destination, &bytes))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
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.unwrap().run_capturing_entry(
|
|
source,
|
|
&mut record,
|
|
marker_start,
|
|
|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.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())
|
|
.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 fonts = PreviewFonts::resolve(
|
|
&pages, &mut files, &texrra_tex_core::native_font::NativeFontCache::default(),
|
|
).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_diagnostic(
|
|
WriteDestination::TerminalAndLog,
|
|
&format!("native PDF warning: {warning}\n"),
|
|
)
|
|
.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, fonts)
|
|
.render(1, &pages, Some(&pdf_for_preview), None, || Ok(()))
|
|
.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)
|
|
);
|
|
}
|
|
}
|