Resume native editor jobs through verified checkpoints

This commit is contained in:
gloamxun committed 2026-11-19 09:35:33 +08:00
1 parent 31364ae33e
commit 0abf700817
19 files changed
+2311 -93

No files matched your search

+157 -14
View File
@@ -21,18 +21,18 @@ mod math;
mod nesting; mod nesting;
mod page; mod page;
mod paragraphs; mod paragraphs;
mod pdf_color;
mod pdf_catalog; mod pdf_catalog;
mod pdf_color;
mod pdf_graphics; mod pdf_graphics;
mod pdf_links;
mod pdf_image; mod pdf_image;
mod pdf_links;
mod quantities; mod quantities;
mod restores; mod restores;
mod scanning; mod scanning;
mod scheduling; mod scheduling;
mod statistics; mod statistics;
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Limits { pub struct Limits {
pub steps: usize, pub steps: usize,
pub tokens: usize, pub tokens: usize,
@@ -65,6 +65,7 @@ impl From<Token> for InputToken {
} }
} }
} }
#[derive(Clone)]
enum InputFrame { enum InputFrame {
Source { Source {
source: usize, source: usize,
@@ -110,6 +111,7 @@ enum TheValue {
Tokens(Vec<Token>), Tokens(Vec<Token>),
Text(std::string::String), Text(std::string::String),
} }
#[derive(Clone)]
struct Conditional { struct Conditional {
primitive: Primitive, primitive: Primitive,
inverted: bool, inverted: bool,
@@ -137,6 +139,7 @@ impl ConditionalLimit {
} }
} }
#[derive(Clone)]
pub struct Executor { pub struct Executor {
state: State, state: State,
limits: Limits, limits: Limits,
@@ -197,6 +200,60 @@ impl Default for Executor {
} }
} }
/// A live, in-memory kernel continuation at an entry-file command boundary.
/// The host must validate dependencies and replay all prefix effects before
/// resumption. The checkpoint itself validates the entry bytes already loaded.
pub struct EntryCheckpoint {
executor: Executor,
entry: usize,
initial_depth: usize,
incoming_state: u64,
frontier: usize,
}
impl EntryCheckpoint {
pub fn frontier(&self) -> usize {
self.frontier
}
pub fn completed_steps(&self) -> usize {
self.executor.steps
}
pub fn accepts_entry(&self, source: &SourceFile) -> bool {
self.accepts_entry_bytes(&source.name, &source.data)
}
pub fn accepts_entry_bytes(&self, name: &str, data: &[u8]) -> bool {
let Some(InputFrame::Source { mouth, .. }) = self.executor.inputs.first() else {
unreachable!("entry checkpoints start with the physical source frame");
};
self.executor.sources[self.entry].name == name && mouth.matches_loaded_prefix(data)
}
pub fn resume_after_host_replay(
&self,
source: SourceFile,
files: &mut impl SourceProvider,
cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> {
if !self.accepts_entry(&source) {
return None;
}
let mut executor = self.executor.clone().with_cancellation(cancellation);
let Some(InputFrame::Source { mouth, .. }) = executor.inputs.first_mut() else {
unreachable!("entry checkpoints start with the physical source frame");
};
mouth.rebind_loaded_prefix(source.data.clone());
executor.sources[self.entry] = source;
let result = executor
.check_cancellation()
.and_then(|_| executor.run_active_input(self.initial_depth, files, |_, _, _| {}));
let result = executor.finish_observed_input(result, files);
Some(executor.finish_execution(result, self.incoming_state))
}
}
impl Executor { impl Executor {
// Native jobs enforce the no-shell-escape policy for immediate and shipped writes. // Native jobs enforce the no-shell-escape policy for immediate and shipped writes.
const SHELL_ESCAPE: i32 = 0; const SHELL_ESCAPE: i32 = 0;
@@ -541,7 +598,9 @@ impl Executor {
Ok(Some(input)) Ok(Some(input))
} else { } else {
match self.meaning(&input.token) { match self.meaning(&input.token) {
Meaning::Primitive(Primitive::Expandafter) => self.expand_after(&input.token, files), Meaning::Primitive(Primitive::Expandafter) => {
self.expand_after(&input.token, files)
}
meaning => self.expand_one_inner(input, meaning, files, definition_context), meaning => self.expand_one_inner(input, meaning, files, definition_context),
} }
}; };
@@ -2874,7 +2933,72 @@ impl Executor {
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
) -> Result<Execution, ExecutionFailure> { ) -> Result<Execution, ExecutionFailure> {
let incoming_state = self.state.fingerprint(); let incoming_state = self.state.fingerprint();
let result = self.run_observed(file, files); let result = self.run_observed(file, files, |_, _, _| {});
self.finish_execution(result, incoming_state)
}
/// Capture the first eligible entry command boundary at or beyond the
/// requested physical byte. The callback captures the matching host state.
pub fn run_capturing_entry<F: SourceProvider, H>(
mut self,
file: SourceFile,
files: &mut F,
minimum_frontier: usize,
capture_host: impl FnOnce(&mut F) -> H,
) -> (
Result<Execution, ExecutionFailure>,
Option<(EntryCheckpoint, H)>,
) {
let incoming_state = self.state.fingerprint();
let mut capture_host = Some(capture_host);
let mut captured = None;
let result = self.run_observed(file, files, |engine, initial_depth, files| {
if capture_host.is_none() || engine.job_ended {
return;
}
let Some(InputFrame::Source {
source,
mouth,
eof_seen: false,
pseudo_trace: None,
..
}) = engine.inputs.first()
else {
return;
};
let Some(frontier) = mouth.physical_frontier() else {
return;
};
// Keep the active macro and argument cursors, but a second
// physical source would have an independent unread frontier.
if frontier < minimum_frontier
|| engine.inputs[1..]
.iter()
.any(|frame| matches!(frame, InputFrame::Source { .. }))
|| engine.sources.iter().enumerate().any(|(index, other)| {
index != *source && other.name == engine.sources[*source].name
})
{
return;
}
let mut executor = engine.clone();
executor.cancellation = None;
executor.line_break_cache = None;
let checkpoint = EntryCheckpoint {
executor,
entry: *source,
initial_depth,
incoming_state,
frontier,
};
captured = Some((checkpoint, capture_host.take().unwrap()(files)));
});
(self.finish_execution(result, incoming_state), captured)
}
fn finish_execution(
mut self,
result: Result<(), Error>,
incoming_state: u64,
) -> Result<Execution, ExecutionFailure> {
self.collect_meaning_reads(); self.collect_meaning_reads();
if let Err(error) = result { if let Err(error) = result {
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
@@ -2932,17 +3056,25 @@ impl Executor {
steps: self.steps, steps: self.steps,
}) })
} }
fn run_observed( fn run_observed<F: SourceProvider>(
&mut self, &mut self,
file: SourceFile, file: SourceFile,
files: &mut impl SourceProvider, files: &mut F,
capture_boundary: impl FnMut(&Self, usize, &mut F),
) -> Result<(), Error> { ) -> Result<(), Error> {
self.check_cancellation()?; self.check_cancellation()?;
self.change_interaction_mode(self.interaction_mode, files)?; self.change_interaction_mode(self.interaction_mode, files)?;
let result = self let result = self.prepare_input(file, files).and_then(|initial_depth| {
.run_input(file, files) self.run_active_input(initial_depth, files, capture_boundary)
.and_then(|()| self.finish_pdf_catalog()); });
if let Err(mut error) = result { self.finish_observed_input(result, files)
}
fn finish_observed_input(
&mut self,
result: Result<(), Error>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if let Err(mut error) = result.and_then(|()| self.finish_pdf_catalog()) {
if let Err(sink) = files.observe_error(&error) { if let Err(sink) = files.observe_error(&error) {
error error
.message .message
@@ -2966,11 +3098,11 @@ impl Executor {
self.check_cancellation()?; self.check_cancellation()?;
Ok(()) Ok(())
} }
fn run_input( fn prepare_input(
&mut self, &mut self,
file: SourceFile, file: SourceFile,
files: &mut impl SourceProvider, files: &mut impl SourceProvider,
) -> Result<(), Error> { ) -> Result<usize, Error> {
if self.job_name.is_none() { if self.job_name.is_none() {
self.job_name = std::path::Path::new(&file.name) self.job_name = std::path::Path::new(&file.name)
.file_stem() .file_stem()
@@ -3021,7 +3153,16 @@ impl Executor {
self.push_mode_hook(TokenParameter::Everyjob)?; self.push_mode_hook(TokenParameter::Everyjob)?;
} }
} }
Ok(initial_depth)
}
fn run_active_input<F: SourceProvider>(
&mut self,
initial_depth: usize,
files: &mut F,
mut capture_boundary: impl FnMut(&Self, usize, &mut F),
) -> Result<(), Error> {
loop { loop {
capture_boundary(self, initial_depth, files);
self.process_native_pages(files)?; self.process_native_pages(files)?;
let Some(input) = self.expanded(files)? else { let Some(input) = self.expanded(files)? else {
break; break;
@@ -3713,7 +3854,9 @@ impl Executor {
}, },
)?; )?;
} }
Some(p @ (Chardef | Mathchardef | Countdef | Toksdef | Dimendef | Skipdef | Muskipdef)) => { Some(
p @ (Chardef | Mathchardef | Countdef | Toksdef | Dimendef | Skipdef | Muskipdef),
) => {
self.define_shorthand(p, global, files)?; self.define_shorthand(p, global, files)?;
} }
Some(Dimen | Skip | Muskip) => { Some(Dimen | Skip | Muskip) => {
@@ -23,10 +23,12 @@ struct Template {
prefix: Vec<Token>, prefix: Vec<Token>,
suffix: Vec<Token>, suffix: Vec<Token>,
} }
#[derive(Clone)]
struct Cell { struct Cell {
last: usize, last: usize,
node: NativeBox, node: NativeBox,
} }
#[derive(Clone)]
pub(super) struct AlignmentFrame { pub(super) struct AlignmentFrame {
horizontal: bool, horizontal: bool,
span: Span, span: Span,
@@ -9,6 +9,7 @@ pub(super) enum Destination {
Adjustment { pre: bool }, Adjustment { pre: bool },
Insertion { class: u8 }, Insertion { class: u8 },
} }
#[derive(Clone)]
pub(super) struct BoxFrame { pub(super) struct BoxFrame {
kind: BoxKind, kind: BoxKind,
spec: PackSpec, spec: PackSpec,
@@ -23,6 +24,7 @@ pub(super) struct BoxFrame {
// An inner $...$ belongs to this box, even inside an outer display. // An inner $...$ belongs to this box, even inside an outer display.
display: Option<super::display::DisplayFrame>, display: Option<super::display::DisplayFrame>,
} }
#[derive(Clone)]
struct DiscretionaryFrame { struct DiscretionaryFrame {
parts: Vec<Vec<TextNode>>, parts: Vec<Vec<TextNode>>,
font: FontId, font: FontId,
@@ -13,6 +13,7 @@ pub(super) struct EquationNumber {
pub(super) box_: NativeBox, pub(super) box_: NativeBox,
} }
#[derive(Clone)]
pub(super) struct DisplayFrame { pub(super) struct DisplayFrame {
previous_lines: usize, previous_lines: usize,
pub(super) number_side: Option<EquationSide>, pub(super) number_side: Option<EquationSide>,
@@ -1,6 +1,7 @@
use super::super::boxes::{self, PackSpec, VerticalBuilder}; use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*; use super::*;
#[derive(Clone)]
pub(super) struct OutputFrame { pub(super) struct OutputFrame {
depth: usize, depth: usize,
paragraph: Option<super::super::paragraph::Builder>, paragraph: Option<super::super::paragraph::Builder>,
@@ -16,6 +16,7 @@ struct Segment {
transformed: bool, transformed: bool,
} }
#[derive(Clone)]
pub(super) struct ActiveLink { pub(super) struct ActiveLink {
layout: LinkStart, layout: LinkStart,
attributes: String, attributes: String,
@@ -28,6 +28,7 @@ pub struct PageMarks {
} }
#[derive(Default)] #[derive(Default)]
#[derive(Clone)]
pub(super) struct MigratingMaterial { pub(super) struct MigratingMaterial {
pub pre: Vec<NativeVerticalNode>, pub pre: Vec<NativeVerticalNode>,
pub post: Vec<NativeVerticalNode>, pub post: Vec<NativeVerticalNode>,
@@ -216,6 +216,7 @@ pub(super) enum MathGroupTarget {
Field(FieldTarget), Field(FieldTarget),
Choice { node: usize, branch: usize }, Choice { node: usize, branch: usize },
} }
#[derive(Clone)]
pub(super) struct MathBuilder { pub(super) struct MathBuilder {
pub nodes: Vec<MathNode>, pub nodes: Vec<MathNode>,
pub numerator: Option<PendingFraction>, pub numerator: Option<PendingFraction>,
@@ -225,6 +226,7 @@ pub(super) struct MathBuilder {
pub left: Option<(Delimiter, PaintSource)>, pub left: Option<(Delimiter, PaintSource)>,
pub span: Span, pub span: Span,
} }
#[derive(Clone)]
pub(super) struct PendingFraction { pub(super) struct PendingFraction {
pub numerator: Vec<MathNode>, pub numerator: Vec<MathNode>,
pub specification: FractionSpec, pub specification: FractionSpec,
+1 -1
View File
@@ -52,7 +52,7 @@ pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext}; pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice}; pub use device::{NativeShipout, ShipoutDevice};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport}; pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{Executor, Limits}; pub use engine::{EntryCheckpoint, Executor, Limits};
pub use font_catalog::{ pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource, FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
}; };
@@ -168,11 +168,13 @@ enum LineState {
Skip, Skip,
} }
#[derive(Clone)]
enum LineBreaks { enum LineBreaks {
Physical, Physical,
Generated(Option<char>), Generated(Option<char>),
} }
#[derive(Clone)]
pub(super) struct Mouth { pub(super) struct Mouth {
source: usize, source: usize,
data: Vec<u8>, data: Vec<u8>,
@@ -187,6 +189,28 @@ pub(super) struct Mouth {
} }
impl Mouth { impl Mouth {
pub(super) fn physical_frontier(&self) -> Option<usize> {
(matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0)
.then_some(self.offset)
}
pub(super) fn matches_loaded_prefix(&self, data: &[u8]) -> bool {
let Some(offset) = self.physical_frontier() else {
return false;
};
let loaded = &self.data[..offset];
// A CR looks ahead for LF. For an unterminated line, EOF is part
// of what has already been observed.
let same_boundary = match loaded.last() {
Some(b'\r') => data.get(offset) != Some(&b'\n'),
Some(b'\n') => true,
_ => data.len() == offset,
};
same_boundary && data.starts_with(loaded)
}
pub(super) fn rebind_loaded_prefix(&mut self, data: Vec<u8>) {
debug_assert!(self.matches_loaded_prefix(&data));
self.data = data;
}
pub(super) fn payload_bytes(&self) -> usize { pub(super) fn payload_bytes(&self) -> usize {
self.data.len() self.data.len()
} }
@@ -1,9 +1,10 @@
//! Revision-gated publication for full native executions. //! Revision-gated publication for native executions.
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use super::{ use super::{
Cancellation, Error, Execution, ExecutionFailure, Executor, SourceFile, SourceProvider, Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, SourceFile,
SourceProvider,
}; };
#[derive(Clone, Default)] #[derive(Clone, Default)]
@@ -165,6 +166,45 @@ impl RevisionJob {
let executed = executor let executed = executor
.with_cancellation(self.cancellation.clone()) .with_cancellation(self.cancellation.clone())
.run_detailed(source, files); .run_detailed(source, files);
self.finish_execution(executed, files)
}
/// Capture a possible entry continuation while executing the full revision.
pub fn run_capturing_entry<F: SourceProvider, H>(
self,
executor: Executor,
source: SourceFile,
files: &mut F,
minimum_frontier: usize,
capture_host: impl FnOnce(&mut F) -> H,
) -> (
Result<Arc<RevisionExecution>, RevisionFailure>,
Option<(EntryCheckpoint, H)>,
) {
let (executed, captured) = executor
.with_cancellation(self.cancellation.clone())
.run_capturing_entry(source, files, minimum_frontier, capture_host);
(self.finish_execution(executed, files), captured)
}
/// Resume after the host has validated prefix dependencies and replayed
/// their effects into the new revision's isolated file host.
pub fn resume_entry_after_host_replay(
self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
files: &mut impl SourceProvider,
) -> Option<Result<Arc<RevisionExecution>, RevisionFailure>> {
let executed =
checkpoint.resume_after_host_replay(source, files, self.cancellation.clone())?;
Some(self.finish_execution(executed, files))
}
fn finish_execution(
self,
executed: Result<Execution, ExecutionFailure>,
files: &impl SourceProvider,
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
// Host observations can themselves supersede the revision. Do not // Host observations can themselves supersede the revision. Do not
// invoke the host while holding the session publication lock. // invoke the host while holding the session publication lock.
let resources = files.execution_resource_trace().cloned(); let resources = files.execution_resource_trace().cloned();
+26 -3
View File
@@ -509,6 +509,7 @@ pub struct FileWorld {
deferred_probes: BTreeMap<PathBuf, DeferredProbe>, deferred_probes: BTreeMap<PathBuf, DeferredProbe>,
namespace_observations: usize, namespace_observations: usize,
live_paths: BTreeSet<PathBuf>, live_paths: BTreeSet<PathBuf>,
staged_generated: BTreeMap<PathBuf, PathBuf>,
/// Actual host resource promotions, never inferred from serialized cache. /// Actual host resource promotions, never inferred from serialized cache.
protected_paths: BTreeSet<PathBuf>, protected_paths: BTreeSet<PathBuf>,
replay_gaps: Vec<String>, replay_gaps: Vec<String>,
@@ -642,6 +643,7 @@ impl FileWorld {
deferred_probes: BTreeMap::new(), deferred_probes: BTreeMap::new(),
namespace_observations: 0, namespace_observations: 0,
live_paths: BTreeSet::new(), live_paths: BTreeSet::new(),
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(), protected_paths: BTreeSet::new(),
replay_gaps: Vec::new(), replay_gaps: Vec::new(),
project: None, project: None,
@@ -680,6 +682,7 @@ impl FileWorld {
deferred_probes: BTreeMap::new(), deferred_probes: BTreeMap::new(),
namespace_observations: 0, namespace_observations: 0,
live_paths, live_paths,
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(), protected_paths: BTreeSet::new(),
replay_gaps: Vec::new(), replay_gaps: Vec::new(),
project: Some(project), project: Some(project),
@@ -763,6 +766,7 @@ impl FileWorld {
.as_ref() .as_ref()
.map(|p| p.generated().map(Path::to_path_buf).collect()) .map(|p| p.generated().map(Path::to_path_buf).collect())
.unwrap_or_default(), .unwrap_or_default(),
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(), protected_paths: BTreeSet::new(),
replay_gaps: Vec::new(), replay_gaps: Vec::new(),
project: snapshot.project.clone(), project: snapshot.project.clone(),
@@ -880,6 +884,21 @@ impl FileWorld {
pub fn generated_paths(&self) -> impl Iterator<Item = &Path> { pub fn generated_paths(&self) -> impl Iterator<Item = &Path> {
self.live_paths.iter().map(PathBuf::as_path) self.live_paths.iter().map(PathBuf::as_path)
} }
/// Bind private storage to a host-authorized mutable project path. Resource
/// resolution, observations and source names still use the project path.
pub fn stage_generated(&mut self, path: &Path, storage: PathBuf) -> Result<(), String> {
if !self.live(path)
|| !self.project.as_ref().is_some_and(|p| p.permits_generated(path))
|| self.protected_paths.contains(path)
{
return Err("staged native storage requires a mutable project file".into());
}
self.staged_generated.insert(path.to_owned(), storage);
Ok(())
}
pub fn generated_storage<'a>(&'a self, path: &'a Path) -> &'a Path {
self.staged_generated.get(path).map_or(path, PathBuf::as_path)
}
fn project_paths(&self) -> BTreeSet<PathBuf> { fn project_paths(&self) -> BTreeSet<PathBuf> {
self.live_paths self.live_paths
.union(&self.protected_paths) .union(&self.protected_paths)
@@ -905,7 +924,11 @@ impl FileWorld {
let location = project.locate(path, &self.project_paths())?; let location = project.locate(path, &self.project_paths())?;
let result = if location.kind == Some(project::NodeKind::File) { let result = if location.kind == Some(project::NodeKind::File) {
if self.live_paths.contains(&location.path) { if self.live_paths.contains(&location.path) {
Self::existing(&location.path) if let Some(storage) = self.staged_generated.get(&location.path) {
Self::existing(storage).map(|found| found.map(|_| location.path))
} else {
Self::existing(&location.path)
}
} else { } else {
Ok(Some(location.path)) Ok(Some(location.path))
} }
@@ -1111,7 +1134,7 @@ impl FileWorld {
)); ));
} }
} }
let value = fs::read(&path) let value = fs::read(self.generated_storage(&path))
.map(|data| SnapshotFile { .map(|data| SnapshotFile {
version: ResourceVersion { version: ResourceVersion {
path: path.clone(), path: path.clone(),
@@ -1530,7 +1553,7 @@ impl FileWorld {
} }
let time = match project_time { let time = match project_time {
Some(time) => Some(time), Some(time) => Some(time),
None => fs::metadata(path) None => fs::metadata(self.generated_storage(path))
.and_then(|metadata| metadata.modified()) .and_then(|metadata| metadata.modified())
.ok() .ok()
.map(FileModificationTime::from_system_time) .map(FileModificationTime::from_system_time)
@@ -158,6 +158,19 @@ impl ProjectSnapshot {
pub fn modification_time(&self, path: &Path) -> Option<FileModificationTime> { pub fn modification_time(&self, path: &Path) -> Option<FileModificationTime> {
self.file_modifications.get(path).copied() self.file_modifications.get(path).copied()
} }
/// Whether both snapshots give lookups the same configuration, names,
/// aliases and roles. The bytes and captured times are separate inputs.
pub fn same_lookup_namespace(&self, next: &Self) -> Result<bool, String> {
self.validate()?;
next.validate()?;
Ok(self.configuration == next.configuration
&& self.roots == next.roots
&& self.directories == next.directories
&& self.aliases == next.aliases
&& self.generated_roots == next.generated_roots
&& self.generated == next.generated
&& self.files.keys().eq(next.files.keys()))
}
pub fn generated(&self) -> impl Iterator<Item = &Path> { pub fn generated(&self) -> impl Iterator<Item = &Path> {
self.generated.iter().map(PathBuf::as_path) self.generated.iter().map(PathBuf::as_path)
} }
+5 -1
View File
@@ -99,6 +99,9 @@ schema23 目录候选实际写出字典、打开动作和目的地引用,519
schema24 信息字典候选对照 pdfTeX 的原始 Token 累积、默认键抑制、最终日期 schema24 信息字典候选对照 pdfTeX 的原始 Token 累积、默认键抑制、最终日期
控制及 DVI 忽略规则,477项内核测试和9项 PDF 字典测试通过。 控制及 DVI 忽略规则,477项内核测试和9项 PDF 字典测试通过。
真实 LaTeX 格式、七项 article 和原样出版矩阵从新的优化构建复验。 真实 LaTeX 格式、七项 article 和原样出版矩阵从新的优化构建复验。
真实格式、七项 article 共21轮和出版矩阵复验已完成。原样 Springer Nature 推进到
`\leaders`;Elsevier CAS SC/DC 以及用官方 firstaid 重建格式的原样 CVPR 推进到
字体标识扫描。schema24 全工作区回归已启动。
检查点宿主的独立候选用真实私有文件隔离 aux、日志和账本,TeX 以原逻辑名 检查点宿主的独立候选用真实私有文件隔离 aux、日志和账本,TeX 以原逻辑名
读取暂存内容。组合候选在同一版本门禁内发布检查点续跑的 aux、日志、账本和 读取暂存内容。组合候选在同一版本门禁内发布检查点续跑的 aux、日志、账本和
@@ -109,7 +112,8 @@ PDF,并暴露完成的结果。实测重放7项宿主调用,当前续跑的
会选中已读入第7页待编辑行的字节472。允许保留活动宏与参数游标后,从字节411 会选中已读入第7页待编辑行的字节472。允许保留活动宏与参数游标后,从字节411
续跑两次。每次跳过770678/870724步,重放59项实际宿主调用,只更新第7页。 续跑两次。每次跳过770678/870724步,重放59项实际宿主调用,只更新第7页。
PDF、八页布局、SVG、来源映射、aux 与日志均与同版本独立全量编译一致。 PDF、八页布局、SVG、来源映射、aux 与日志均与同版本独立全量编译一致。
全工作区回归正在运行。自动选取候选按入口字节区间和实际出页保留少量状态, 固定边界候选完成1599项工作区回归,已按475项源码指纹合入主线。
自动选取候选按入口字节区间和实际出页保留少量状态,
先校验最近可用的前缀,再在宿主锁内重验与重放。原样 A3 两次均从5个候选中 先校验最近可用的前缀,再在宿主锁内重验与重放。原样 A3 两次均从5个候选中
选中字节411,每次跳过794348/870724步,重放61项调用,只替换第7页。 选中字节411,每次跳过794348/870724步,重放61项调用,只替换第7页。
同版本 PDF、八页布局、SVG、来源映射、aux 和日志的独立全量对照通过。 同版本 PDF、八页布局、SVG、来源映射、aux 和日志的独立全量对照通过。
+9 -2
View File
@@ -173,8 +173,15 @@ CVPR 在正文的首个引用处进入实际 LaTeX firstaid 的宏调用,首
原样 CVPR 的失败复核发现两端格式构建输入有差异。参考格式的文件记录包含 原样 CVPR 的失败复核发现两端格式构建输入有差异。参考格式的文件记录包含
同发行版官方 `latex2e-first-aid-for-external-files.ltx`,原生格式构建日志 同发行版官方 `latex2e-first-aid-for-external-files.ltx`,原生格式构建日志
记录了该文件缺失。缺失的宏正由该官方文件定义。使用同字节文件和同版本入口 记录了该文件缺失。缺失的宏正由该官方文件定义。使用同字节文件和同版本入口
重建原生出版格式,CVPR 原样复验已启动。七项 article 继续使用原先冻结的 重建原生出版格式。真实原样 CVPR 越过该宏,在第一个相关 URL 的
基准格式输入和验收容差。 `\textfont` 赋值停于字体标识扫描。
schema24 候选按原参考条件通过七项 article 的21轮复验。原样 Springer Nature
越过 `\pdfinfo` 推进到 `\leaders`,原样 Elsevier CAS SC/DC 越过
`\pdfinfo` 后,与 CVPR 同样在字体标识扫描处停止。原样出版矩阵参考10/10、
原生生成3/10。含官方 firstaid 的 CVPR 分项报告单列于
`target/p3-pdf-info/coherent-cvpr`,完整矩阵位于
`target/p3-pdf-info/publisher-matrix/report.json`。
单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、 单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、
双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源 双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源
+169 -41
View File
@@ -1,18 +1,27 @@
//! Shared strict Route-D compilation, resource closure and revision publication. //! Shared strict Route-D compilation, resource closure and revision publication.
//! No process cwd changes, legacy frontend, or external TeX compilation. //! No process cwd changes, legacy frontend, or external TeX compilation.
#[path = "native_checkpoint_guard.rs"]
mod checkpoint_guard;
#[path = "native_checkpoint_probe.rs"]
mod checkpoint_probe;
pub use crate::native_generated::{GeneratedInitialState, GeneratedInputPolicy}; pub use crate::native_generated::{GeneratedInitialState, GeneratedInputPolicy};
pub use crate::native_host::{ pub use crate::native_host::{
HostMetadata, HostObservation, HostPreparation, HostPreparationPhase, LedgerRead, HostMetadata, HostObservation, HostPreparation, HostPreparationPhase, LedgerRead,
VersionExpectation, VersionExpectation,
}; };
pub use crate::native_job::job_time; pub use crate::native_job::job_time;
use crate::native_job::{Files, PreparedOutput, absolute_output, file_modification_date}; use crate::native_job::{
EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output, file_modification_date,
};
use crate::native_preview::PreviewState; use crate::native_preview::PreviewState;
pub use crate::native_preview::{PreviewPage, PreviewUpdate}; pub use crate::native_preview::{PreviewPage, PreviewUpdate};
pub use crate::native_stream::{ pub use crate::native_stream::{
DescriptorIdentity, InputOpened, InputStorage, ReleaseCause, StreamEffect, StreamEvent, DescriptorIdentity, InputOpened, InputStorage, ReleaseCause, StreamEffect, StreamEvent,
StreamJournal, WriteAttempt, WriteOutcome, StreamJournal, WriteAttempt, WriteOutcome,
}; };
use checkpoint_guard::CheckpointCache;
pub use checkpoint_guard::EntryCheckpointWork;
use std::{ use std::{
path::PathBuf, path::PathBuf,
sync::{Arc, Mutex}, sync::{Arc, Mutex},
@@ -22,14 +31,14 @@ pub use texrra_tex_core::resources::{WorldFailure, WorldObservation};
use texrra_tex_core::{ use texrra_tex_core::{
execution::{ execution::{
Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits, Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits,
NativeSession, RevisionError, RevisionExecution, RevisionJob, SourceFile, SourceProvider, NativeSession, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
State, SourceProvider, State,
}, },
render::DisplayList, render::DisplayList,
resources::{FileWorld, InputSnapshot, ResourceTrace, ResourceVersion, WorldConfig}, resources::{FileWorld, InputSnapshot, ResourceTrace, ResourceVersion, WorldConfig},
}; };
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Entry { pub enum Entry {
Bootstrap, Bootstrap,
Initex, Initex,
@@ -172,6 +181,7 @@ pub struct ResourceSnapshot {
pub struct CompiledDocument { pub struct CompiledDocument {
pub execution: Arc<RevisionExecution>, pub execution: Arc<RevisionExecution>,
pub entry_checkpoint_work: EntryCheckpointWork,
pub format_preparation: Option<FormatPreparation>, pub format_preparation: Option<FormatPreparation>,
/// Actual paragraph search performed or reused in this revision. /// Actual paragraph search performed or reused in this revision.
pub line_break_work: texrra_tex_core::execution::LineBreakWork, pub line_break_work: texrra_tex_core::execution::LineBreakWork,
@@ -506,6 +516,7 @@ pub struct NativeCompiler {
jobs: Arc<Mutex<()>>, jobs: Arc<Mutex<()>>,
format_cache: Arc<FormatCache>, format_cache: Arc<FormatCache>,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>, line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
entry_checkpoints: Option<Arc<CheckpointCache>>,
} }
#[derive(Default)] #[derive(Default)]
@@ -535,6 +546,14 @@ pub struct CompileJob {
job: RevisionJob, job: RevisionJob,
} }
impl NativeCompiler { impl NativeCompiler {
/// Enable entry-prefix reuse for atomic project shipout jobs. The byte
/// position is a lower bound for a physical command boundary to retain.
/// Invalidated prefixes use the same full compiler in the same revision.
pub fn with_entry_checkpoints(mut self, minimum_frontier: usize) -> Self {
self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(minimum_frontier)));
self
}
pub fn start(&self) -> CompileJob { pub fn start(&self) -> CompileJob {
CompileJob { CompileJob {
compiler: self.clone(), compiler: self.clone(),
@@ -574,9 +593,36 @@ fn prepare(
format_cache: Option<&FormatCache>, format_cache: Option<&FormatCache>,
cancellation: &Cancellation, cancellation: &Cancellation,
evidence: &mut AttemptEvidence, evidence: &mut AttemptEvidence,
) -> Result<PreparedJob, CompileError> {
prepare_checked(
request,
dump,
format_cache,
cancellation,
evidence,
None,
EffectMode::Live,
)
}
fn prepare_checked(
request: &CompileRequest,
dump: bool,
format_cache: Option<&FormatCache>,
cancellation: &Cancellation,
evidence: &mut AttemptEvidence,
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
effects: EffectMode,
) -> Result<PreparedJob, CompileError> { ) -> Result<PreparedJob, CompileError> {
use texrra_tex_core::resources::ResourceKind; use texrra_tex_core::resources::ResourceKind;
check(cancellation)?; check(cancellation)?;
if effects == EffectMode::Draft
&& (dump || request.layout_manifest.is_some() || request.resource_manifest.is_some())
{
return Err(CompileError::Host(
"draft effects require a document job without external reports".into(),
));
}
if request.layout_manifest.is_some() && (dump || request.target != Target::Shipouts) { if request.layout_manifest.is_some() && (dump || request.target != Target::Shipouts) {
return Err(CompileError::Host( return Err(CompileError::Host(
"--layout-manifest requires a native document job".into(), "--layout-manifest requires a native document job".into(),
@@ -726,6 +772,8 @@ fn prepare(
request.terminal, request.terminal,
&request.generated_inputs, &request.generated_inputs,
&mut evidence.host_preparation, &mut evidence.host_preparation,
check_inputs,
effects,
) )
.map_err(|failure| { .map_err(|failure| {
evidence.trace = Some(failure.trace); evidence.trace = Some(failure.trace);
@@ -762,8 +810,14 @@ impl CompileJob {
} }
pub fn compile_detailed( pub fn compile_detailed(
self, self,
request: CompileRequest, mut request: CompileRequest,
) -> Result<Arc<CompiledDocument>, CompileFailure> { ) -> Result<Arc<CompiledDocument>, CompileFailure> {
if self.compiler.entry_checkpoints.is_some()
&& checkpoint_guard::can_stage(&request)
&& matches!(&request.generated_inputs, GeneratedInputPolicy::Live)
{
request.generated_inputs = GeneratedInputPolicy::Observe;
}
let mut evidence = AttemptEvidence::new(self.revision()); let mut evidence = AttemptEvidence::new(self.revision());
let summary = AttemptRequest::from(&request); let summary = AttemptRequest::from(&request);
match self.compile_observed(request, &mut evidence) { match self.compile_observed(request, &mut evidence) {
@@ -787,29 +841,64 @@ impl CompileJob {
.map_err(|_| CompileError::Host("native job queue poisoned".into()))?; .map_err(|_| CompileError::Host("native job queue poisoned".into()))?;
let revision = self.job.revision(); let revision = self.job.revision();
evidence.phase = AttemptPhase::Preparing; evidence.phase = AttemptPhase::Preparing;
let checkpoints = self
.compiler
.entry_checkpoints
.as_deref()
.filter(|_| checkpoint_guard::can_stage(&request));
let format_cache = &self.compiler.format_cache;
let mut entry_checkpoint_work = EntryCheckpointWork::default();
let mut active_checkpoint = checkpoints.and_then(CheckpointCache::current);
let prepared = match active_checkpoint.as_ref() {
Some(candidate) => {
match candidate.prepare(&request, format_cache, &cancellation, evidence) {
Ok(prepared) => Some(prepared),
Err(error) => {
check(&cancellation)?;
*evidence = AttemptEvidence::new(revision);
entry_checkpoint_work.rejection = Some(error.to_string());
active_checkpoint = None;
None
}
}
}
None => None,
};
let PreparedJob { let PreparedJob {
executor, executor,
format_preparation, format_preparation,
source, source,
mut files, files,
output, output,
} = prepare( } = if let Some(prepared) = prepared {
&request, prepared
false, } else {
Some(&self.compiler.format_cache), prepare_checked(
&cancellation, &request,
evidence, false,
) Some(format_cache),
.map_err(|error| { &cancellation,
if cancellation.is_cancelled() { evidence,
CompileError::Cancelled None,
} else { if checkpoints.is_some() {
error EffectMode::Draft
} } else {
})?; EffectMode::Live
},
)
.map_err(|error| {
if cancellation.is_cancelled() {
CompileError::Cancelled
} else {
error
}
})?
};
let mut available_host = Some(files);
evidence.inputs = None; evidence.inputs = None;
evidence.trace = None; evidence.trace = None;
let result = (|| -> Result<Arc<CompiledDocument>, CompileError> { let result = (|| -> Result<Arc<CompiledDocument>, CompileError> {
let files = available_host.as_mut().expect("prepared native host");
if let Some(path) = &request.layout_manifest { if let Some(path) = &request.layout_manifest {
files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?; files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?;
} }
@@ -819,16 +908,29 @@ impl CompileJob {
let cache = &self.compiler.line_break_cache; let cache = &self.compiler.line_break_cache;
let before = cache.work(); let before = cache.work();
let executor = executor.with_line_break_cache(cache.clone()); let executor = executor.with_line_break_cache(cache.clone());
let execution = match self.job.run_detailed(executor, source, &mut files) { let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
let executed =
current.resume(self.job, source, files, &mut entry_checkpoint_work)?;
(executed, Some(current))
} else if let Some(cache) = checkpoints {
let (executed, captured) =
cache.capture(&request, self.job, executor, source, files);
entry_checkpoint_work.captured_frontier =
captured.as_ref().map(|entry| entry.frontier());
(executed, captured)
} else {
(self.job.run_detailed(executor, source, files), None)
};
let execution = match executed {
Ok(execution) => { Ok(execution) => {
evidence.completed_execution = Some(execution.clone()); evidence.completed_execution = Some(execution.clone());
report(&files, &request)?; report(files, &request)?;
execution execution
} }
Err(failure) => { Err(failure) => {
evidence.failed_execution = failure.failed_execution; evidence.failed_execution = failure.failed_execution;
evidence.completed_execution = failure.completed_execution; evidence.completed_execution = failure.completed_execution;
if let Err(error) = report(&files, &request) { if let Err(error) = report(files, &request) {
evidence.gaps.push(error.to_string()); evidence.gaps.push(error.to_string());
} }
return Err(match failure.error { return Err(match failure.error {
@@ -875,8 +977,8 @@ impl CompileJob {
files.write_layout_manifest(path, e, &pages, &source_map)?; files.write_layout_manifest(path, e, &pages, &source_map)?;
} }
evidence.phase = AttemptPhase::Fonts; evidence.phase = AttemptPhase::Fonts;
let fonts = texrra_tex_core::native_font::resolve_native_fonts(&mut pages, &mut files); let fonts = texrra_tex_core::native_font::resolve_native_fonts(&mut pages, files);
let reported = report(&files, &request); let reported = report(files, &request);
if let Err(error) = fonts { if let Err(error) = fonts {
if let Err(report) = reported { if let Err(report) = reported {
evidence.gaps.push(report.to_string()); evidence.gaps.push(report.to_string());
@@ -919,7 +1021,7 @@ impl CompileJob {
} }
evidence.phase = AttemptPhase::Finishing; evidence.phase = AttemptPhase::Finishing;
let finished = files.finish(); let finished = files.finish();
let reported = report(&files, &request); let reported = report(files, &request);
if let Err(error) = finished { if let Err(error) = finished {
if let Err(report) = reported { if let Err(report) = reported {
evidence.gaps.push(report.to_string()); evidence.gaps.push(report.to_string());
@@ -954,6 +1056,7 @@ impl CompileJob {
); );
let result = Arc::new(CompiledDocument { let result = Arc::new(CompiledDocument {
format_preparation, format_preparation,
entry_checkpoint_work,
line_break_work, line_break_work,
execution, execution,
pages, pages,
@@ -975,26 +1078,51 @@ impl CompileJob {
&cancellation, &cancellation,
)?; )?;
evidence.phase = AttemptPhase::Publishing; evidence.phase = AttemptPhase::Publishing;
let published = self let expose = || {
.compiler *self
.session .compiler
.publish_current(result.revision(), || { .latest
if let Some(prepared) = prepared { .lock()
prepared.commit(&output)?; .expect("native completed result poisoned") = Some(result.clone());
} };
*self let published = if let Some(cache) = checkpoints {
.compiler let publication = available_host
.latest .take()
.lock() .expect("prepared draft host")
.expect("native completed result poisoned") = Some(result.clone()); .seal_draft(prepared)
Ok::<_, String>(()) .and_then(|draft| {
})?; draft.publish_current(&self.compiler.session, result.revision(), || {
cache.set(next_checkpoint);
expose();
})
});
if !matches!(publication, Ok(Some(()))) {
evidence.host_preparation = result.host_preparation.clone();
evidence.inputs = Some(result.inputs.clone());
evidence.trace = Some(result.resources.trace.clone());
evidence.resources = Some(result.resources.clone());
evidence.host_runtime = result.host_runtime.clone();
}
publication?
} else {
self.compiler
.session
.publish_current(result.revision(), || {
if let Some(prepared) = prepared {
prepared.commit(&output)?;
}
expose();
Ok::<_, String>(())
})?
};
if published.is_none() { if published.is_none() {
return Err(CompileError::Cancelled); return Err(CompileError::Cancelled);
} }
Ok(result) Ok(result)
})(); })();
if result.is_err() { if result.is_err()
&& let Some(mut files) = available_host
{
evidence.gaps.extend(files.finish_failed()); evidence.gaps.extend(files.finish_failed());
if let Err(error) = report(&files, &request) { if let Err(error) = report(&files, &request) {
evidence.gaps.push(error.to_string()); evidence.gaps.push(error.to_string());
+925
View File
@@ -0,0 +1,925 @@
//! Reuse a recorded entry prefix only after validating the current job host.
use super::checkpoint_probe::{Call, RecordingHost};
use super::*;
#[cfg(test)]
use std::{collections::BTreeMap, fs};
use std::{collections::BTreeSet, ffi::OsString, path::Path};
use texrra_tex_core::{execution::EntryCheckpoint, resources::ResourceKind};
#[cfg(test)]
use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy};
/// Work actually performed by the optional entry-checkpoint path.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EntryCheckpointWork {
pub captured_frontier: Option<usize>,
pub reused_steps: usize,
pub replayed_calls: usize,
pub rejection: Option<String>,
}
pub(super) struct CheckpointCache {
minimum_frontier: usize,
published: Mutex<Option<Arc<CachedCheckpoint>>>,
}
pub(super) struct CachedCheckpoint {
entry: EntryCheckpoint,
guard: PrefixInputGuard,
calls: Vec<Call>,
}
pub(super) fn can_stage(request: &CompileRequest) -> bool {
request.project.is_some()
&& request.target == Target::Shipouts
&& !request.terminal
&& request.resource_manifest.is_none()
&& request.layout_manifest.is_none()
}
impl CheckpointCache {
pub(super) fn new(minimum_frontier: usize) -> Self {
Self {
minimum_frontier,
published: Mutex::new(None),
}
}
pub(super) fn current(&self) -> Option<Arc<CachedCheckpoint>> {
self.published
.lock()
.expect("native entry checkpoint cache poisoned")
.clone()
}
pub(super) fn set(&self, checkpoint: Option<Arc<CachedCheckpoint>>) {
*self
.published
.lock()
.expect("native entry checkpoint cache poisoned") = checkpoint;
}
pub(super) fn capture(
&self,
request: &CompileRequest,
job: RevisionJob,
executor: Executor,
source: SourceFile,
files: &mut Files,
) -> (
Result<Arc<RevisionExecution>, RevisionFailure>,
Option<Arc<CachedCheckpoint>>,
) {
let entry_path = files
.resource_trace()
.reads
.first()
.map(|first| first.path.clone());
let initial = files.preparation().generated_initial.clone();
let mut recording = RecordingHost::new(files);
let (result, captured) = job.run_capturing_entry(
executor,
source,
&mut recording,
self.minimum_frontier,
RecordingHost::capture,
);
let next = captured.and_then(|(entry, recorded)| {
let (calls, trace) = recorded?;
let guard =
PrefixInputGuard::capture(request, entry_path.as_deref()?, &trace, initial?)
.ok()?;
Some(Arc::new(CachedCheckpoint {
entry,
guard,
calls,
}))
});
(result, next)
}
}
impl CachedCheckpoint {
pub(super) fn frontier(&self) -> usize {
self.entry.frontier()
}
pub(super) fn prepare(
&self,
request: &CompileRequest,
cache: &FormatCache,
cancellation: &Cancellation,
evidence: &mut AttemptEvidence,
) -> Result<PreparedJob, CompileError> {
let mut prepared = prepare_checked(
request,
false,
Some(cache),
cancellation,
evidence,
Some(Box::new(|world, preparation| {
self.guard.verify(request, world, preparation)?;
let entry = world
.project()
.and_then(|p| p.file(&self.guard.entry))
.ok_or("checkpoint entry is unavailable")?;
if !self
.entry
.accepts_entry_bytes(&self.guard.entry.to_string_lossy(), &entry.data)
{
return Err("checkpoint entry prefix changed".into());
}
Ok(())
})),
EffectMode::Draft,
)?;
for call in &self.calls {
check(cancellation)?;
call(&mut prepared.files)?;
}
Ok(prepared)
}
pub(super) fn resume(
&self,
job: RevisionJob,
source: SourceFile,
files: &mut Files,
work: &mut EntryCheckpointWork,
) -> Result<Result<Arc<RevisionExecution>, RevisionFailure>, CompileError> {
let result = job
.resume_entry_after_host_replay(&self.entry, source, files)
.ok_or_else(|| CompileError::Host("prepared checkpoint prefix changed".into()))?;
work.reused_steps = self.entry.completed_steps();
work.replayed_calls = self.calls.len();
Ok(result)
}
}
struct PrefixInputGuard {
original: AttemptRequest,
project: Arc<ProjectSnapshot>,
initial: GeneratedInitialState,
entry: PathBuf,
immutable: BTreeSet<PathBuf>,
clock_environment: Option<[Option<OsString>; 3]>,
}
fn date_environment() -> [Option<OsString>; 3] {
["TZ", "SOURCE_DATE_EPOCH", "FORCE_SOURCE_DATE"].map(std::env::var_os)
}
impl PrefixInputGuard {
fn capture(
request: &CompileRequest,
entry: &Path,
trace: &ResourceTrace,
initial: GeneratedInitialState,
) -> Result<Self, String> {
let project = request
.project
.as_ref()
.ok_or("checkpoint requires an atomic project")?;
let source = project
.file(entry)
.ok_or("checkpoint entry was not immutable")?;
if trace.project_version.as_ref() != Some(project.version())
|| trace.reads.first() != Some(&source.version)
|| !trace.lookups.first().is_some_and(|lookup| {
lookup.kind == ResourceKind::Tex && lookup.resolved.as_deref() == Some(entry)
})
{
return Err("checkpoint trace does not begin at its actual project entry".into());
}
if !trace.read_errors.is_empty() || !trace.namespace_capture_failures.is_empty() {
return Err("checkpoint contains incomplete resource observations".into());
}
let tracked = trace
.lookups
.iter()
.skip(1)
.filter_map(|item| item.resolved.as_deref())
.chain(trace.reads.iter().skip(1).map(|item| item.path.as_path()))
.chain(trace.stream_reads.iter().map(|item| item.path.as_path()))
.chain(
trace
.generated_lookups
.iter()
.map(|item| item.target.as_path()),
);
let mut immutable = BTreeSet::new();
for path in tracked {
if project.file(path).is_some() {
immutable.insert(path.to_path_buf());
} else if !initial.files().contains_key(path) {
return Err(format!(
"checkpoint input has no stable initial role: {}",
path.display()
));
}
}
for observed in &trace.file_modifications {
if project.file(&observed.path).is_none() {
return Err("checkpoint file date requires a captured immutable resource".into());
}
immutable.insert(observed.path.clone());
}
Ok(Self {
original: AttemptRequest::from(request),
project: project.clone(),
initial,
entry: entry.to_path_buf(),
immutable,
clock_environment: (!trace.file_modifications.is_empty()).then(date_environment),
})
}
fn verify(
&self,
request: &CompileRequest,
world: &FileWorld,
preparation: &HostPreparation,
) -> Result<(), String> {
let old = &self.original;
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.time != request.time
|| old.limits != request.limits
|| old.terminal != request.terminal
{
return Err("checkpoint job parameters changed".into());
}
let current = world
.project()
.ok_or("checkpoint requires an atomic project")?;
if !self.project.same_lookup_namespace(current)? {
return Err("checkpoint lookup namespace changed".into());
}
if world.trace().reads.first() != current.file(&self.entry).map(|file| &file.version) {
return Err("checkpoint entry resolved to a different path".into());
}
for path in &self.immutable {
let old = self.project.file(path).map(|file| &file.version);
let new = current.file(path).map(|file| &file.version);
if old != new || self.project.modification_time(path) != current.modification_time(path)
{
return Err(format!(
"checkpoint observed input changed: {}",
path.display()
));
}
}
if self
.clock_environment
.as_ref()
.is_some_and(|old| *old != date_environment())
{
return Err("checkpoint file-date environment changed".into());
}
let current = preparation
.generated_initial
.as_ref()
.ok_or("checkpoint requires generated versions observed under the job lock")?;
self.initial.check(current)
}
}
#[cfg(test)]
const PREFIX: &str = concat!(
"\\catcode123=1 \\catcode125=2\n",
"\\input library.tex\n",
"\\openin3=optional.tex \\ifeof3 \\message{MISSING}\\else \\message{PRESENT}\\fi \\closein3\n",
"\\immediate\\openout1=entry.aux\n",
"\\pdfcatalog{/Lang (en)}\n",
"\\immediate\\write1{\\value}\\relax\n",
"\\message{CHECKPOINT}\\relax\n",
);
#[cfg(test)]
const TAIL: &str = concat!(
"\\immediate\\write1{old tail}\n",
"\\openin2=entry.aux \\read2 to\\firstline \\read2 to\\secondline \\closein2\\relax\n",
"\\openin4=seed.aux \\read4 to\\seedline \\closein4\\relax\n",
"\\message{SEED: \\seedline}\\relax\n",
"\\pdfcatalog{/PageLayout /SinglePage}\n",
"\\message{READ: \\firstline/\\secondline}\\relax\n",
"\\shipout\\hbox{\\vrule width2pt height1pt}\n",
"\\immediate\\closeout1 \\end\n",
);
#[test]
fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejection() {
let cwd = std::env::temp_dir().join(format!("texrra-guard-{}", std::process::id()));
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().unwrap();
let entry = cwd.join("entry.tex");
let library = cwd.join("library.tex");
let unrelated = cwd.join("unread.tex");
let aux = cwd.join("entry.aux");
let seed = cwd.join("seed.aux");
fs::write(&seed, b"prior job\n").unwrap();
let output_paths =
|| ["entry.aux", "entry.log", "entry.pdf"].map(|name| fs::read(cwd.join(name)).unwrap());
let mut world = WorldConfig::new(&cwd);
world.input_policy = InputPolicy::Tex;
let definition = ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: BTreeSet::from([cwd.clone()]),
files: BTreeMap::from([
(
entry.clone(),
Arc::from(format!("{PREFIX}{TAIL}").into_bytes()),
),
(library.clone(), Arc::from(br"\def\value{A}".as_slice())),
(unrelated.clone(), Arc::from(b"unread original".as_slice())),
]),
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::from([aux.clone(), seed.clone()]),
};
let project = ProjectSnapshot::new(definition.clone()).unwrap();
let mut request = CompileRequest::new(
world,
"entry.tex",
"entry.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;
NativeCompiler::default().compile(request.clone()).unwrap();
let cancellation = Cancellation::default();
let PreparedJob {
executor,
source,
mut files,
..
} = prepare(
&request,
false,
None,
&cancellation,
&mut AttemptEvidence::new(1),
)
.unwrap();
let initial = files.preparation().generated_initial.clone().unwrap();
let mut recording = checkpoint_probe::RecordingHost::new(&mut files);
let (executed, checkpoint) =
executor.run_capturing_entry(source, &mut recording, PREFIX.len() - 25, |host| {
(host.capture(), host.resource_usage().unwrap().unwrap())
});
assert!(executed.is_ok());
let (checkpoint, (recorded, usage)) = checkpoint.unwrap();
let (calls, trace) = recorded.unwrap();
assert_eq!(usage.open_outputs, Some(1));
assert!(
trace
.lookups
.iter()
.any(|lookup| lookup.name == "optional.tex" && lookup.resolved.is_none())
);
let guard = PrefixInputGuard::capture(&request, &entry, &trace, initial).unwrap();
assert!(guard.immutable.contains(&library));
assert!(!guard.immutable.contains(&unrelated));
assert!(!guard.immutable.contains(&entry));
files.finish().unwrap();
drop(files);
let guarded = |candidate: &CompileRequest, evidence: &mut AttemptEvidence, effects| {
prepare_checked(
candidate,
false,
None,
&cancellation,
evidence,
Some(Box::new(|world, prep| {
guard.verify(candidate, world, prep)?;
let source = world.project().unwrap().file(&entry).unwrap();
if !checkpoint.accepts_entry_bytes(&entry.to_string_lossy(), &source.data) {
return Err("checkpoint entry prefix changed".into());
}
Ok(())
})),
effects,
)
};
let rejected = |candidate: &CompileRequest, reason: &str| {
let saved = output_paths();
let mut evidence = AttemptEvidence::new(2);
let error = guarded(candidate, &mut evidence, EffectMode::Draft)
.err()
.unwrap();
assert!(error.to_string().contains(reason), "{error}");
assert_eq!(
evidence.host_preparation.phase,
HostPreparationPhase::GeneratedInitial
);
assert_eq!(output_paths(), saved);
eprintln!("rejected before transcript and generated writes: {error}");
};
let changed_library = project
.with_file_edits(
2,
BTreeMap::from([(library.clone(), Arc::from(br"\def\value{B}".as_slice()))]),
)
.unwrap();
rejected(
&request.clone().with_project(changed_library.clone()),
"observed input changed",
);
let changed_prefix = project
.with_file_edits(
5,
BTreeMap::from([(
entry.clone(),
Arc::from(
format!("{}{TAIL}", PREFIX.replace("CHECKPOINT", "CHECKFORGE")).into_bytes(),
),
)]),
)
.unwrap();
rejected(
&request.clone().with_project(changed_prefix),
"entry prefix changed",
);
let mut appeared = definition;
appeared.revision = 3;
appeared
.files
.insert(cwd.join("optional.tex"), Arc::from(b"present".as_slice()));
rejected(
&request
.clone()
.with_project(ProjectSnapshot::new(appeared).unwrap()),
"lookup namespace changed",
);
let mut changed_clock = request.clone();
changed_clock.time = JobTime::new(2026, 11, 18, 1001).unwrap();
rejected(&changed_clock, "job parameters changed");
let old_aux = fs::read(&aux).unwrap();
fs::write(&aux, b"externally edited auxiliary file").unwrap();
rejected(&request, "generated initial role or version mismatch");
fs::write(&aux, &old_aux).unwrap();
let edited = project
.with_file_edits(
4,
BTreeMap::from([
(
entry.clone(),
Arc::from(
format!(
"{PREFIX}{}",
TAIL.replace("old tail", "new tail")
.replace("width2pt", "width3pt")
)
.into_bytes(),
),
),
(unrelated, Arc::from(b"unread modified".as_slice())),
]),
)
.unwrap();
let edited_request = request.clone().with_project(edited);
let saved = output_paths();
let PreparedJob {
source, mut files, ..
} = guarded(
&edited_request,
&mut AttemptEvidence::new(3),
EffectMode::Draft,
)
.unwrap();
for call in &calls {
call(&mut files).unwrap();
}
assert_eq!(
files.resource_usage().unwrap().unwrap().open_outputs,
Some(1)
);
assert_eq!(output_paths(), saved);
let draft_execution = checkpoint
.resume_after_host_replay(source, &mut files, cancellation.clone())
.unwrap()
.unwrap();
let draft_trace = files.resource_trace().clone();
files.finish().unwrap();
let draft_paths = files.draft_paths();
assert_eq!(draft_paths.len(), 3);
assert_eq!(output_paths(), saved);
let draft_aux = fs::read(&draft_paths[&aux]).unwrap();
let draft_log = fs::read(&draft_paths[&cwd.join("entry.log")]).unwrap();
let (ledger, draft_ledger) = draft_paths
.iter()
.find(|(dest, _)| {
dest.extension()
.is_some_and(|extension| extension == "json")
})
.unwrap();
let saved_ledger = fs::read(ledger).unwrap();
let draft_ledger = fs::read(draft_ledger).unwrap();
assert_ne!(draft_ledger, saved_ledger);
drop(files);
assert!(draft_paths.values().all(|path| !path.exists()));
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
let stage_revision = |session: &NativeSession| {
let revision = session.start();
let PreparedJob {
source, mut files, ..
} = guarded(
&edited_request,
&mut AttemptEvidence::new(revision.revision()),
EffectMode::Draft,
)
.unwrap();
for call in &calls {
call(&mut files).unwrap();
}
let result = revision
.resume_entry_after_host_replay(&checkpoint, source, &mut files)
.unwrap()
.unwrap();
assert_eq!(result.execution, draft_execution);
let pages = result.execution.shipout_display_lists().unwrap();
let source_map =
texrra_tex_core::source_map::SourceMap::from_revision(&result, &pages).unwrap();
let pdf = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document(
&pages,
result.execution.state.pdf_final_options(),
)
.unwrap();
assert!(pdf.diagnostics.is_empty(), "{:?}", pdf.diagnostics);
files.finish().unwrap();
let prepared_pdf = PreparedOutput::write(&cwd.join("entry.pdf"), &pdf.bytes).unwrap();
let staged = files.seal_draft(Some(prepared_pdf)).unwrap();
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
(result, source_map, pdf.bytes, staged)
};
let session = NativeSession::default();
let (stale, _, _, staged) = stage_revision(&session);
assert!(session.start().revision() > stale.revision);
let unexpected_publication = || -> u64 { panic!("rejected draft exposed a document") };
assert_eq!(
staged
.publish_current(&session, stale.revision, unexpected_publication)
.unwrap(),
None
);
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
let (cancelled, _, _, staged) = stage_revision(&session);
session.cancel(cancelled.revision);
assert_eq!(
staged
.publish_current(&session, cancelled.revision, unexpected_publication)
.unwrap(),
None
);
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
let (conflicted, _, _, staged) = stage_revision(&session);
fs::write(ledger, b"external ledger edit").unwrap();
let error = staged
.publish_current(&session, conflicted.revision, unexpected_publication)
.unwrap_err();
assert!(
error.contains("native draft destination changed"),
"{error}"
);
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), b"external ledger edit");
fs::write(ledger, &saved_ledger).unwrap();
let (conflicted, _, _, staged) = stage_revision(&session);
fs::write(&seed, b"external input edit\n").unwrap();
let error = staged
.publish_current(&session, conflicted.revision, unexpected_publication)
.unwrap_err();
assert!(error.contains("native draft input changed"), "{error}");
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
assert_eq!(fs::read(&seed).unwrap(), b"external input edit\n");
fs::write(&seed, b"prior job\n").unwrap();
let (current, resumed_source_map, resumed_pdf, staged) = stage_revision(&session);
let lock_error = guarded(
&edited_request,
&mut AttemptEvidence::new(current.revision),
EffectMode::Draft,
)
.err()
.unwrap();
assert!(
lock_error.to_string().contains("already in use"),
"{lock_error}"
);
let exposed = staged
.publish_current(&session, current.revision, || {
assert_eq!(fs::read(cwd.join("entry.pdf")).unwrap(), resumed_pdf);
current.revision
})
.unwrap();
assert_eq!(exposed, Some(current.revision));
let resumed_output = output_paths();
assert_eq!(resumed_output[0], draft_aux);
assert_eq!(resumed_output[1], draft_log);
assert_eq!(resumed_output[2], resumed_pdf);
assert_ne!(resumed_output[2], saved[2]);
assert_eq!(fs::read(ledger).unwrap(), draft_ledger);
for (name, bytes) in ["entry.aux", "entry.log", "entry.pdf"]
.into_iter()
.zip(&saved)
{
fs::write(cwd.join(name), bytes).unwrap();
}
fs::write(ledger, &saved_ledger).unwrap();
let PreparedJob {
source, mut files, ..
} = guarded(
&edited_request,
&mut AttemptEvidence::new(4),
EffectMode::Draft,
)
.unwrap();
for call in &calls {
call(&mut files).unwrap();
}
let cancelled = Cancellation::default();
cancelled.cancel();
let error = checkpoint
.resume_after_host_replay(source, &mut files, cancelled)
.unwrap()
.unwrap_err();
assert!(error.error.message.contains("cancelled"), "{error:?}");
assert!(files.finish_failed().is_empty());
let discarded = files.draft_paths();
drop(files);
assert!(discarded.values().all(|path| !path.exists()));
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
let PreparedJob {
source, mut files, ..
} = guarded(
&edited_request,
&mut AttemptEvidence::new(5),
EffectMode::Live,
)
.unwrap();
assert!(checkpoint.accepts_entry(&source));
for call in &calls {
call(&mut files).unwrap();
}
let resumed_usage: HostResourceUsage = files.resource_usage().unwrap().unwrap();
assert_eq!(resumed_usage.open_outputs, Some(1));
let resumed = checkpoint
.resume_after_host_replay(source, &mut files, cancellation.clone())
.unwrap()
.unwrap();
let trace = files.resource_trace().clone();
files.finish().unwrap();
drop(files);
let resumed_aux = fs::read(&aux).unwrap();
let resumed_log = fs::read(cwd.join("entry.log")).unwrap();
assert_eq!(resumed_aux, b"A\nnew tail\n");
fs::write(&aux, &old_aux).unwrap();
let full = NativeCompiler::default()
.compile(edited_request.clone())
.unwrap();
assert_eq!(resumed, full.execution.execution);
assert_eq!(Some(trace), full.execution.execution_resources);
assert_eq!(resumed.shipout_display_lists().unwrap(), full.pages);
assert_eq!(resumed_aux, fs::read(&aux).unwrap());
assert_eq!(resumed_log, fs::read(cwd.join("entry.log")).unwrap());
assert_eq!(draft_execution, full.execution.execution);
assert_eq!(Some(draft_trace), full.execution.execution_resources);
assert_eq!(draft_aux, resumed_aux);
assert_eq!(draft_log, resumed_log);
assert_eq!(draft_ledger, fs::read(ledger).unwrap());
assert_eq!(resumed_pdf.as_slice(), full.pdf.as_deref().unwrap());
assert_eq!(resumed_source_map.sources, full.source_map.sources);
assert_eq!(resumed_source_map.pages, full.source_map.pages);
assert_eq!(resumed_output, output_paths());
let fallback = NativeCompiler::default()
.compile(request.clone().with_project(changed_library.clone()))
.unwrap();
assert_eq!(fallback.pages.len(), 1);
assert_eq!(fs::read(&aux).unwrap(), b"B\nold tail\n");
fs::write(&aux, &old_aux).unwrap();
let compiler = NativeCompiler::default().with_entry_checkpoints(PREFIX.len() - 25);
let first = compiler.compile(request.clone()).unwrap();
assert!(first.entry_checkpoint_work.captured_frontier.is_some());
struct Supersede(NativeCompiler);
impl CompileObserver for Supersede {
fn stage(&self, _: u64, stage: CompileStage) -> Result<(), String> {
if stage == CompileStage::ReadyToPublish {
self.0.start();
}
Ok(())
}
}
let before = output_paths();
let mut cancelled_request = edited_request.clone();
cancelled_request.observer = Some(Arc::new(Supersede(compiler.clone())));
let failure = compiler.compile_detailed(cancelled_request).err().unwrap();
assert!(matches!(failure.error, CompileError::Cancelled));
assert!(Arc::ptr_eq(&compiler.latest().unwrap(), &first));
assert_eq!(output_paths(), before);
let resumed = compiler.compile(edited_request.clone()).unwrap();
assert!(resumed.entry_checkpoint_work.reused_steps > 0);
assert_eq!(resumed.entry_checkpoint_work.replayed_calls, calls.len());
assert_eq!(resumed.pdf, full.pdf);
let pdf = lopdf::Document::load_mem(resumed.pdf.as_deref().unwrap()).unwrap();
let catalog = pdf.catalog().unwrap();
assert_eq!(catalog.get(b"Lang").unwrap().as_str().unwrap(), b"en");
assert_eq!(
catalog.get(b"PageLayout").unwrap().as_name().unwrap(),
b"SinglePage"
);
assert_eq!(resumed.pages, full.pages);
assert_eq!(resumed.source_map.pages, full.source_map.pages);
assert!(Arc::ptr_eq(&compiler.latest().unwrap(), &resumed));
let rebuilt = compiler
.compile(request.with_project(changed_library))
.unwrap();
assert_eq!(rebuilt.entry_checkpoint_work.reused_steps, 0);
assert!(
rebuilt
.entry_checkpoint_work
.rejection
.as_deref()
.unwrap()
.contains("observed input changed")
);
assert_eq!(rebuilt.execution.execution, fallback.execution.execution);
assert_eq!(fs::read(&aux).unwrap(), b"B\nold tail\n");
eprintln!(
"accepted edited suffix and unread resource, replayed {} actual host calls, full fallback consumes changed library",
calls.len()
);
}
#[test]
#[ignore = "requires the verified LaTeX format, A3 fixture and a dedicated output directory"]
fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() {
let cwd = PathBuf::from(std::env::var_os("TEXRRA_A3_CHECKPOINT_WORK").unwrap());
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().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 manifest: serde_json::Value =
serde_json::from_slice(&fs::read(resource_file).unwrap()).unwrap();
let roots: Vec<PathBuf> = serde_json::from_value(manifest["texmf_roots"].clone()).unwrap();
let source = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("examples/native-format-stage/a3-pages/main.tex");
let original = fs::read_to_string(source).unwrap();
let marker = "This explicit page follows the naturally paginated material.";
assert_eq!(original.matches(marker).count(), 1);
let frontier = original.find(marker).unwrap();
let entry = cwd.join("main.tex");
fs::write(&entry, &original).unwrap();
let mut world = WorldConfig::from_environment(&cwd, roots.clone()).unwrap();
world.input_policy = InputPolicy::Tex;
let mut request = CompileRequest::new(
world.clone(),
"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;
let seed = NativeCompiler::default().compile(request.clone()).unwrap();
let mut files = BTreeMap::from([(entry.clone(), Arc::from(original.as_bytes()))]);
for (path, captured) in seed.inputs.files() {
if !path.starts_with(&cwd) {
files.insert(path.to_owned(), captured.unwrap().data.clone());
}
}
for lookup in &seed.resources.trace.lookups {
if let Some(path) = &lookup.resolved
&& !path.starts_with(&cwd)
&& !files.contains_key(path)
{
files.insert(path.clone(), Arc::from(fs::read(path).unwrap()));
}
}
let mut coverage = BTreeSet::from_iter(roots);
coverage.insert(cwd.clone());
for path in files.keys() {
if !coverage.iter().any(|root| path.starts_with(root)) {
coverage.insert(path.parent().unwrap().to_owned());
}
}
let aux = cwd.join("main.aux");
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: world,
revision: 1,
roots: coverage,
files,
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::from([aux.clone()]),
})
.unwrap();
let request = request
.with_project(project.clone())
.observe_generated_initial();
let compiler = NativeCompiler::default().with_entry_checkpoints(frontier);
let mut previous = compiler.compile(request.clone()).unwrap();
assert_eq!(
previous.entry_checkpoint_work.captured_frontier,
Some(frontier)
);
assert_eq!(previous.pages.len(), 8);
assert!(previous.pages == seed.pages);
let mut visible = previous.preview_since(None).unwrap().pages;
let baseline_aux = fs::read(&aux).unwrap();
for (index, replacement) in [
"This edited page follows the naturally paginated material.",
"This revised page also uses the same open auxiliary stream.",
]
.into_iter()
.enumerate()
{
let edited = project
.with_file_edits(
index as u64 + 2,
BTreeMap::from([(
entry.clone(),
Arc::from(original.replace(marker, replacement).into_bytes()),
)]),
)
.unwrap();
let edit_request = request.clone().with_project(edited);
let resumed = compiler.compile(edit_request.clone()).unwrap();
let work = &resumed.entry_checkpoint_work;
assert!(
work.reused_steps > 700_000 && work.replayed_calls > 0,
"{work:?}"
);
assert!(work.rejection.is_none(), "{work:?}");
assert_eq!(
resumed.pdf.as_deref().unwrap(),
fs::read(cwd.join("main.pdf")).unwrap()
);
assert_eq!(baseline_aux, fs::read(&aux).unwrap());
let log = fs::read(cwd.join("main.log")).unwrap();
let update = resumed.preview_since(Some(previous.revision())).unwrap();
assert_eq!(update.base_revision, Some(previous.revision()));
assert_eq!(update.page_count, 8);
assert_eq!(
update.pages.iter().map(|p| p.index).collect::<Vec<_>>(),
vec![6]
);
for page in update.pages {
let index = page.index;
visible[index] = page;
}
let full = NativeCompiler::default().compile(edit_request).unwrap();
assert!(resumed.execution.execution == full.execution.execution);
assert_eq!(
resumed.execution.source_versions,
full.execution.source_versions
);
assert_eq!(
resumed.execution.execution_resources,
full.execution.execution_resources
);
assert!(resumed.pages == full.pages);
assert_eq!(resumed.source_map.sources, full.source_map.sources);
assert_eq!(resumed.source_map.pages, full.source_map.pages);
assert_eq!(resumed.pdf, full.pdf);
assert_eq!(visible, full.preview_since(None).unwrap().pages);
assert_eq!(log, fs::read(cwd.join("main.log")).unwrap());
eprintln!(
"A3 edit {} skips {} of {} steps, replays {} host calls and replaces only page 7",
index + 1,
work.reused_steps,
resumed.execution.execution.steps,
work.replayed_calls
);
previous = resumed;
}
}
+359
View File
@@ -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)
);
}
}
+571 -29
View File
@@ -14,7 +14,9 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use texrra_tex_core::artifacts::{ArtifactLedger, file_version}; use texrra_tex_core::artifacts::{ArtifactLedger, file_version};
use texrra_tex_core::execution::{JobTime, SourceFile, SourceProvider, WriteDestination}; use texrra_tex_core::execution::{
JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination,
};
use texrra_tex_core::resources::{FileWorld, LoadedResource, ResourceKind, ResourceVersion}; use texrra_tex_core::resources::{FileWorld, LoadedResource, ResourceKind, ResourceVersion};
pub fn job_time() -> Result<JobTime, String> { pub fn job_time() -> Result<JobTime, String> {
@@ -81,6 +83,24 @@ pub struct HostPreparationFailure {
pub trace: texrra_tex_core::resources::ResourceTrace, pub trace: texrra_tex_core::resources::ResourceTrace,
pub inputs: std::sync::Arc<texrra_tex_core::resources::InputSnapshot>, pub inputs: std::sync::Arc<texrra_tex_core::resources::InputSnapshot>,
} }
pub(crate) type PreparedInputsCheck<'a> =
dyn FnOnce(&FileWorld, &HostPreparation) -> Result<(), String> + 'a;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum EffectMode {
Live,
Draft,
}
struct DraftEffects {
log: DraftArtifact,
generated: BTreeMap<PathBuf, DraftArtifact>,
ledger_target: DraftDestination,
ledger: Option<PreparedOutput>,
pdf: DraftDestination,
finished: bool,
}
pub struct Files { pub struct Files {
world: FileWorld, world: FileWorld,
cwd: PathBuf, cwd: PathBuf,
@@ -90,6 +110,7 @@ pub struct Files {
stream_io: StreamJournal, stream_io: StreamJournal,
log_path: PathBuf, log_path: PathBuf,
log: Option<File>, log: Option<File>,
draft: Option<DraftEffects>,
protected: Vec<PathBuf>, protected: Vec<PathBuf>,
producer: PathBuf, producer: PathBuf,
ledger: ArtifactLedger, ledger: ArtifactLedger,
@@ -142,6 +163,8 @@ impl Files {
terminal: bool, terminal: bool,
generated_inputs: &GeneratedInputPolicy, generated_inputs: &GeneratedInputPolicy,
preparation: &mut HostPreparation, preparation: &mut HostPreparation,
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
effects: EffectMode,
) -> Result<Self, HostPreparationFailure> { ) -> Result<Self, HostPreparationFailure> {
preparation.phase = HostPreparationPhase::Environment; preparation.phase = HostPreparationPhase::Environment;
let state = preparation let state = preparation
@@ -181,6 +204,8 @@ impl Files {
terminal, terminal,
generated_inputs, generated_inputs,
preparation, preparation,
check_inputs,
effects,
) )
} }
#[cfg(test)] #[cfg(test)]
@@ -198,6 +223,8 @@ impl Files {
true, true,
&GeneratedInputPolicy::Live, &GeneratedInputPolicy::Live,
&mut HostPreparation::default(), &mut HostPreparation::default(),
None,
EffectMode::Live,
) )
.map_err(|f| f.error) .map_err(|f| f.error)
} }
@@ -209,6 +236,8 @@ impl Files {
terminal: bool, terminal: bool,
generated_inputs: &GeneratedInputPolicy, generated_inputs: &GeneratedInputPolicy,
preparation: &mut HostPreparation, preparation: &mut HostPreparation,
check_inputs: Option<Box<PreparedInputsCheck<'_>>>,
effects: EffectMode,
) -> Result<Self, HostPreparationFailure> { ) -> Result<Self, HostPreparationFailure> {
// Keep the world until all fallible preparation has succeeded. Failure // Keep the world until all fallible preparation has succeeded. Failure
// must return its final actual observations rather than an earlier copy. // must return its final actual observations rather than an earlier copy.
@@ -411,14 +440,51 @@ impl Files {
expected.check(&actual)?; expected.check(&actual)?;
} }
} }
if let Some(check_inputs) = check_inputs {
check_inputs(world, preparation)?;
}
if effects == EffectMode::Draft
&& (world.project().is_none()
|| terminal
|| preparation.generated_initial.is_none())
{
return Err(
"draft effects require an atomic project, observed generated versions and no terminal sink".into(),
);
}
preparation.phase = HostPreparationPhase::Log; preparation.phase = HostPreparationPhase::Log;
// An input job really opens a transcript/terminal input entry. Keep // An input job really opens a transcript/terminal input entry. Keep
// the resulting partial-line state; a later log-only diagnostic must // the resulting partial-line state; a later log-only diagnostic must
// resume both streams from this actual output, even without message. // resume both streams from this actual output, even without message.
let entry = format!("({}", source.display()); let entry = format!("({}", source.display());
let opened = File::create(&log_path); let opened = if effects == EffectMode::Draft {
(|| {
let pdf = DraftDestination::capture(&pdf)?;
let ledger_target = DraftDestination::capture(&ledger_path)?;
if ledger_target.version != ledger_input {
return Err("native generated-file ledger changed before drafting".into());
}
let target = DraftDestination::capture(&log_path)?;
let (staged, file) = PreparedOutput::draft(&log_path)?;
Ok((
file,
Some(DraftEffects {
log: DraftArtifact { target, staged },
generated: BTreeMap::new(),
ledger_target,
ledger: None,
pdf,
finished: false,
}),
))
})()
} else {
File::create(&log_path)
.map(|file| (file, None))
.map_err(|e| format!("native log {}: {e}", log_path.display()))
};
preparation.operation("open log", &log_path, &opened); preparation.operation("open log", &log_path, &opened);
let mut log = opened.map_err(|e| format!("native log {}: {e}", log_path.display()))?; let (mut log, draft) = opened?;
let written = log.write_all(entry.as_bytes()); let written = log.write_all(entry.as_bytes());
preparation.operation("write log entry", &log_path, &written); preparation.operation("write log entry", &log_path, &written);
written.map_err(|e| e.to_string())?; written.map_err(|e| e.to_string())?;
@@ -435,6 +501,7 @@ impl Files {
stream_io: StreamJournal::default(), stream_io: StreamJournal::default(),
log_path, log_path,
log: Some(log), log: Some(log),
draft,
protected, protected,
producer: source.to_owned(), producer: source.to_owned(),
ledger, ledger,
@@ -475,7 +542,21 @@ impl Files {
path: &Path, path: &Path,
expected: Option<Option<ResourceVersion>>, expected: Option<Option<ResourceVersion>>,
) -> Result<Option<ResourceVersion>, String> { ) -> Result<Option<ResourceVersion>, String> {
let observed = file_version(path); let observed = (|| {
let storage = if path == self.ledger_path {
self.draft.as_ref().and_then(|draft| draft.ledger.as_ref())
} else {
None
};
if let Some(storage) = storage {
return storage.version(path).map(Some);
}
let mut observed = file_version(self.world.generated_storage(path))?;
if let Some(version) = &mut observed {
version.path = path.to_owned();
}
Ok(observed)
})();
self.runtime_observations.borrow_mut().observations.push( self.runtime_observations.borrow_mut().observations.push(
crate::native_host::HostObservation::VersionCheck { crate::native_host::HostObservation::VersionCheck {
path: path.into(), path: path.into(),
@@ -555,6 +636,20 @@ impl Files {
pub fn input_snapshot(&self) -> std::sync::Arc<texrra_tex_core::resources::InputSnapshot> { pub fn input_snapshot(&self) -> std::sync::Arc<texrra_tex_core::resources::InputSnapshot> {
self.world.input_snapshot() self.world.input_snapshot()
} }
#[cfg(test)]
pub(crate) fn draft_paths(&self) -> BTreeMap<PathBuf, PathBuf> {
let draft = self.draft.as_ref().expect("draft-mode host");
let mut paths: BTreeMap<_, _> = draft
.generated
.iter()
.map(|(path, draft)| (path.clone(), draft.staged.path.clone()))
.collect();
paths.insert(self.log_path.clone(), draft.log.staged.path.clone());
if let Some(ledger) = &draft.ledger {
paths.insert(self.ledger_path.clone(), ledger.path.clone());
}
paths
}
pub fn check_layout_manifest_path( pub fn check_layout_manifest_path(
&self, &self,
layout: &Path, layout: &Path,
@@ -730,6 +825,13 @@ impl Files {
} }
fn persist_ledger(&mut self) -> Result<(), String> { fn persist_ledger(&mut self) -> Result<(), String> {
let path = self.ledger_path.clone(); let path = self.ledger_path.clone();
if let Some(draft) = self.draft.as_mut() {
draft.ledger_target.verify()?;
let staged = PreparedOutput::write(&path, &self.ledger.encode()?)?;
self.ledger_current = Some(staged.version(&path)?);
draft.ledger = Some(staged);
return Ok(());
}
if self.observe_version(&path, Some(self.ledger_current.clone()))? != self.ledger_current { if self.observe_version(&path, Some(self.ledger_current.clone()))? != self.ledger_current {
return Err("native generated-file ledger changed during the job".into()); return Err("native generated-file ledger changed during the job".into());
} }
@@ -750,6 +852,44 @@ impl Files {
} }
self.persist_ledger() self.persist_ledger()
} }
fn open_generated_output(
&mut self,
path: &Path,
before: &Option<ResourceVersion>,
) -> Result<File, String> {
let Some(draft) = self.draft.as_mut() else {
return OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(path)
.map_err(|e| format!("openout {}: {e}", path.display()));
};
if let Some(staged) = draft.generated.get(path) {
return OpenOptions::new()
.truncate(true)
.write(true)
.open(&staged.staged.path)
.map_err(|e| format!("openout {}: {e}", path.display()));
}
if self.inputs.values().any(|input| input.path == path) {
return Err("cannot stage a generated file with a live input handle".into());
}
let target = DraftDestination::capture(path)?;
if &target.version != before {
return Err(format!(
"generated output changed before drafting: {}",
path.display()
));
}
let (staged, file) = PreparedOutput::draft(path)?;
self.world.mark_live(path);
self.world.stage_generated(path, staged.path.clone())?;
draft
.generated
.insert(path.to_owned(), DraftArtifact { target, staged });
Ok(file)
}
fn handle_id(&mut self) -> u64 { fn handle_id(&mut self) -> u64 {
self.next_handle += 1; self.next_handle += 1;
self.next_handle self.next_handle
@@ -811,8 +951,12 @@ impl Files {
if destination != WriteDestination::TerminalOnly { if destination != WriteDestination::TerminalOnly {
if self.log.is_none() { if self.log.is_none() {
self.log = Some( self.log = Some(
File::create(&self.log_path) File::create(
.map_err(|e| format!("native log {}: {e}", self.log_path.display()))?, self.draft
.as_ref()
.map_or(&self.log_path, |draft| &draft.log.staged.path),
)
.map_err(|e| format!("native log {}: {e}", self.log_path.display()))?,
); );
} }
let log = self.log.as_mut().unwrap(); let log = self.log.as_mut().unwrap();
@@ -836,6 +980,9 @@ impl Files {
/// Close actual handles and retain partial writes after failure. No normal /// Close actual handles and retain partial writes after failure. No normal
/// success footer or rollback is invented; cleanup errors remain separate. /// success footer or rollback is invented; cleanup errors remain separate.
pub fn finish_failed(&mut self) -> Vec<String> { pub fn finish_failed(&mut self) -> Vec<String> {
if let Some(draft) = &mut self.draft {
draft.finished = false;
}
let mut errors = Vec::new(); let mut errors = Vec::new();
self.cleanup_boundary(ReleaseCause::FailureCleanup); self.cleanup_boundary(ReleaseCause::FailureCleanup);
for stream in self.outputs.keys().copied().collect::<Vec<_>>() { for stream in self.outputs.keys().copied().collect::<Vec<_>>() {
@@ -900,8 +1047,78 @@ impl Files {
} }
self.persist_ledger()?; self.persist_ledger()?;
} }
if let Some(draft) = &mut self.draft {
draft.finished = true;
}
Ok(()) Ok(())
} }
pub(crate) fn seal_draft(
mut self,
pdf: Option<PreparedOutput>,
) -> Result<DraftPublication, String> {
let draft = self.draft.take().ok_or("native draft host required")?;
if !draft.finished {
return Err("native draft must finish successfully before publication".into());
}
if let Some(log) = self.log.take() {
log.sync_all()
.map_err(|e| format!("sync native draft log: {e}"))?;
}
let initial = self
.preparation
.generated_initial
.as_ref()
.ok_or("native draft lacks generated initial versions")?;
for (path, artifact) in &draft.generated {
if initial
.files()
.get(path)
.is_some_and(|v| *v != artifact.target.version)
{
return Err(format!(
"native draft output changed after preparation: {}",
path.display()
));
}
}
let mut untouched = initial
.files()
.iter()
.filter(|(path, _)| !draft.generated.contains_key(*path))
.map(|(path, version)| (path.clone(), version.clone()))
.collect::<BTreeMap<_, _>>();
let mut artifacts: Vec<_> = draft.generated.into_values().collect();
for artifact in &artifacts {
OpenOptions::new()
.write(true)
.open(&artifact.staged.path)
.and_then(|file| file.sync_all())
.map_err(|e| {
format!("sync native draft {}: {e}", artifact.target.path.display())
})?;
}
artifacts.push(draft.log);
if let Some(staged) = draft.ledger {
artifacts.push(DraftArtifact {
target: draft.ledger_target,
staged,
});
} else {
untouched.insert(draft.ledger_target.path, draft.ledger_target.version);
}
if let Some(staged) = pdf {
artifacts.push(DraftArtifact {
target: draft.pdf,
staged,
});
}
Ok(DraftPublication {
artifacts,
untouched,
_host: self,
})
}
} }
impl Drop for Files { impl Drop for Files {
@@ -1075,7 +1292,7 @@ impl SourceProvider for Files {
InputStorage::Snapshot(snapshot.version), InputStorage::Snapshot(snapshot.version),
) )
} else { } else {
let file = File::open(&path).map_err(|e| { let file = File::open(self.world.generated_storage(&path)).map_err(|e| {
let error = format!("openin {}: {e}", path.display()); let error = format!("openin {}: {e}", path.display());
self.world.observe_read_error(&path, error.clone()); self.world.observe_read_error(&path, error.clone());
error error
@@ -1186,13 +1403,9 @@ impl SourceProvider for Files {
path.display() path.display()
)); ));
} }
let opened = OpenOptions::new() let opened = self.open_generated_output(&path, &before);
.create(true)
.truncate(true)
.write(true)
.open(&path);
self.operation("open output", &path, &opened); self.operation("open output", &path, &opened);
let file = opened.map_err(|e| format!("openout {}: {e}", path.display()))?; let file = opened?;
let handle = self.handle_id(); let handle = self.handle_id();
opened_handle = Some(handle); opened_handle = Some(handle);
self.stream_io.push(StreamEffect::OutputOpened { self.stream_io.push(StreamEffect::OutputOpened {
@@ -1301,6 +1514,241 @@ impl SourceProvider for Files {
} }
} }
#[derive(PartialEq, Eq)]
struct DraftFileStamp {
bytes: u64,
modified: std::time::SystemTime,
readonly: bool,
#[cfg(unix)]
identity: (u64, u64, u32),
}
impl DraftFileStamp {
fn from_metadata(metadata: &fs::Metadata) -> io::Result<Self> {
Ok(Self {
bytes: metadata.len(),
modified: metadata.modified()?,
readonly: metadata.permissions().readonly(),
#[cfg(unix)]
identity: {
use std::os::unix::fs::MetadataExt;
(metadata.dev(), metadata.ino(), metadata.mode())
},
})
}
}
#[derive(PartialEq, Eq)]
struct DraftDestination {
path: PathBuf,
parent: PathBuf,
#[cfg(unix)]
parent_identity: (u64, u64),
stamp: Option<DraftFileStamp>,
version: Option<ResourceVersion>,
}
impl DraftDestination {
fn capture(path: &Path) -> Result<Self, String> {
let metadata = (|| -> io::Result<_> {
let parent = path
.parent()
.ok_or(io::ErrorKind::InvalidInput)?
.canonicalize()?;
let target = match fs::symlink_metadata(path) {
Ok(metadata) => Some(metadata),
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
if let Some(metadata) = &target {
if !metadata.is_file() {
return Err(io::Error::other("target is not a regular file"));
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if metadata.nlink() != 1 {
return Err(io::Error::other("target has file aliases"));
}
}
}
let stamp = target
.as_ref()
.map(DraftFileStamp::from_metadata)
.transpose()?;
Ok((parent, stamp))
})();
let (parent, stamp) =
metadata.map_err(|e| format!("native draft target {}: {e}", path.display()))?;
let version = file_version(path)?;
if stamp.as_ref().map(|stamp| stamp.bytes) != version.as_ref().map(|version| version.bytes)
{
return Err(format!(
"native draft target changed during inspection: {}",
path.display()
));
}
#[cfg(unix)]
let parent_identity = {
use std::os::unix::fs::MetadataExt;
let metadata = fs::metadata(&parent)
.map_err(|e| format!("native draft directory {}: {e}", parent.display()))?;
(metadata.dev(), metadata.ino())
};
Ok(Self {
path: path.to_owned(),
parent,
stamp,
version,
#[cfg(unix)]
parent_identity,
})
}
fn verify(&self) -> Result<(), String> {
if *self == Self::capture(&self.path)? {
return Ok(());
}
Err(format!(
"native draft destination changed: {}",
self.path.display()
))
}
}
struct DraftArtifact {
target: DraftDestination,
staged: PreparedOutput,
}
pub(crate) struct DraftPublication {
artifacts: Vec<DraftArtifact>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
// The native project lock covers validation, installation and rollback.
_host: Files,
}
impl DraftPublication {
/// Install host effects and expose the completed document under one
/// session revision gate. The callback must not call the session.
pub(crate) fn publish_current<T>(
self,
session: &NativeSession,
revision: u64,
expose_document: impl FnOnce() -> T,
) -> Result<Option<T>, String> {
let Self {
artifacts,
untouched,
_host,
} = self;
session.publish_current(revision, || {
for (path, expected) in untouched {
if DraftDestination::capture(&path)?.version != expected {
return Err(format!("native draft input changed: {}", path.display()));
}
}
install_draft(
artifacts
.into_iter()
.map(DraftInstall::prepare)
.collect::<Result<Vec<_>, _>>()?,
)?;
Ok(expose_document())
})
}
}
struct DraftInstall {
artifact: DraftArtifact,
installed: DraftFileStamp,
backup: Option<PreparedOutput>,
}
impl DraftInstall {
fn prepare(artifact: DraftArtifact) -> Result<Self, String> {
artifact.target.verify()?;
let metadata = fs::symlink_metadata(&artifact.staged.path)
.map_err(|e| format!("inspect staged {}: {e}", artifact.target.path.display()))?;
if !metadata.is_file() {
return Err(format!(
"native staged output must be a regular file: {}",
artifact.target.path.display()
));
}
let installed = DraftFileStamp::from_metadata(&metadata).map_err(|e| e.to_string())?;
let backup = artifact
.target
.stamp
.as_ref()
.map(|_| PreparedOutput::backup(&artifact.target.path))
.transpose()?;
Ok(Self {
artifact,
installed,
backup,
})
}
}
fn install_draft(installs: Vec<DraftInstall>) -> Result<(), String> {
let mut applied: Vec<(PathBuf, DraftFileStamp, Option<PreparedOutput>)> = Vec::new();
for DraftInstall {
mut artifact,
installed,
backup,
} in installs
{
let path = artifact.target.path;
let result = match &backup {
Some(_) => artifact.staged.replace(&path),
None => artifact.staged.link(&path),
};
if let Err(mut error) = result {
while let Some((path, installed, backup)) = applied.pop() {
if let Err(rollback) = restore_draft(&path, installed, backup) {
error.push_str(&format!("; native draft rollback: {rollback}"));
}
}
return Err(error);
}
applied.push((path, installed, backup));
}
Ok(())
}
fn restore_draft(
path: &Path,
installed: DraftFileStamp,
mut backup: Option<PreparedOutput>,
) -> Result<(), String> {
let restore = (|| -> io::Result<()> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || DraftFileStamp::from_metadata(&metadata)? != installed {
return Err(io::Error::other("installed file changed"));
}
match &backup {
Some(backup) => fs::rename(&backup.path, path),
None => fs::remove_file(path),
}
})();
if let Err(error) = restore {
if let Some(backup) = &mut backup {
let recovery = std::mem::take(&mut backup.path);
return Err(format!(
"{}: {error}; previous file retained at {}",
path.display(),
recovery.display()
));
}
return Err(format!("{}: {error}", path.display()));
}
if let Some(backup) = &mut backup {
backup.path.clear();
}
Ok(())
}
/// Write complete bytes before publishing the output path. /// Write complete bytes before publishing the output path.
pub struct PreparedOutput { pub struct PreparedOutput {
path: PathBuf, path: PathBuf,
@@ -1313,39 +1761,99 @@ impl PreparedOutput {
Ok(version) Ok(version)
} }
pub fn write(output: &Path, bytes: &[u8]) -> Result<Self, String> { pub fn write(output: &Path, bytes: &[u8]) -> Result<Self, String> {
let (prepared, mut file) = Self::create(output)?;
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
written.map_err(|error| format!("stage output {}: {error}", output.display()))?;
Ok(prepared)
}
fn draft(output: &Path) -> Result<(Self, File), String> {
let existing = match fs::symlink_metadata(output) {
Ok(metadata) => {
if !metadata.is_file() {
return Err(format!(
"native draft needs a regular file: {}",
output.display()
));
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if metadata.nlink() != 1 {
return Err(format!(
"native draft target has aliases: {}",
output.display()
));
}
}
OpenOptions::new()
.write(true)
.open(output)
.map_err(|e| format!("native draft target {}: {e}", output.display()))?;
Some(metadata.permissions())
}
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(format!("native draft target {}: {e}", output.display())),
};
let (prepared, file) = Self::create(output)?;
if let Some(permissions) = existing {
file.set_permissions(permissions)
.map_err(|e| e.to_string())?;
}
Ok((prepared, file))
}
fn create(output: &Path) -> Result<(Self, File), String> {
Self::allocate(output, |path| {
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
})
}
fn backup(output: &Path) -> Result<Self, String> {
Self::allocate(output, |path| fs::hard_link(output, path)).map(|(backup, ())| backup)
}
fn allocate<T>(
output: &Path,
create: impl Fn(&Path) -> io::Result<T>,
) -> Result<(Self, T), String> {
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0); static NEXT: AtomicU64 = AtomicU64::new(0);
for _ in 0..16 { for _ in 0..16 {
let id = NEXT.fetch_add(1, Ordering::Relaxed); let id = NEXT.fetch_add(1, Ordering::Relaxed);
let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id())); let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id()));
if path == output { if path != output {
continue; match create(&path) {
Ok(value) => return Ok((Self { path }, value)),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(format!("stage output {}: {error}", output.display()));
}
}
} }
let mut file = match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(format!("stage output {}: {error}", output.display())),
};
let prepared = Self { path };
let written = file.write_all(bytes).and_then(|()| file.sync_all());
drop(file);
written.map_err(|error| format!("stage output {}: {error}", output.display()))?;
return Ok(prepared);
} }
Err(format!("could not stage output {}", output.display())) Err(format!("could not stage output {}", output.display()))
} }
/// Publish a new format without replacing an existing path. /// Publish a new format without replacing an existing path.
pub fn commit_new(self, output: &Path) -> Result<(), String> { pub fn commit_new(self, output: &Path) -> Result<(), String> {
self.link(output)
}
fn link(&self, output: &Path) -> Result<(), String> {
fs::hard_link(&self.path, output) fs::hard_link(&self.path, output)
.map_err(|error| format!("output {}: {error}", output.display())) .map_err(|error| format!("output {}: {error}", output.display()))
} }
pub fn commit(mut self, output: &Path) -> Result<(), String> { pub fn commit(mut self, output: &Path) -> Result<(), String> {
self.replace(output)
}
fn replace(&mut self, output: &Path) -> Result<(), String> {
fs::rename(&self.path, output) fs::rename(&self.path, output)
.map_err(|error| format!("output {}: {error}", output.display()))?; .map_err(|error| format!("output {}: {error}", output.display()))?;
self.path.clear(); self.path.clear();
@@ -1557,6 +2065,8 @@ mod generated_file_tests {
false, false,
&GeneratedInputPolicy::Live, &GeneratedInputPolicy::Live,
preparation, preparation,
None,
EffectMode::Live,
) )
} }
#[test] #[test]
@@ -1887,6 +2397,38 @@ mod prepared_output_tests {
fs::remove_dir_all(root).unwrap(); fs::remove_dir_all(root).unwrap();
} }
#[test]
fn failed_draft_install_restores_replaced_file_and_removes_new_file() {
let root =
std::env::temp_dir().join(format!("texrra-draft-rollback-{}", std::process::id()));
fs::create_dir(&root).unwrap();
let replaced = root.join("entry.aux");
let new = root.join("entry.log");
let unavailable = root.join("entry.pdf");
fs::write(&replaced, b"old auxiliary file").unwrap();
let expected = DraftDestination::capture(&replaced).unwrap();
let installs = [&replaced, &new, &unavailable]
.into_iter()
.map(|path| {
DraftInstall::prepare(DraftArtifact {
target: DraftDestination::capture(path).unwrap(),
staged: PreparedOutput::write(path, b"staged native bytes").unwrap(),
})
.unwrap()
})
.collect::<Vec<_>>();
fs::remove_file(&installs[2].artifact.staged.path).unwrap();
let error = install_draft(installs).unwrap_err();
assert!(error.contains("entry.pdf"), "{error}");
expected.verify().unwrap();
assert_eq!(fs::read(&replaced).unwrap(), b"old auxiliary file");
assert!(!new.exists());
assert!(!unavailable.exists());
assert_eq!(fs::read_dir(&root).unwrap().count(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn staged_output_from_superseded_revision_cannot_replace_destination() { fn staged_output_from_superseded_revision_cannot_replace_destination() {
let root = let root =