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 page;
mod paragraphs;
mod pdf_color;
mod pdf_catalog;
mod pdf_color;
mod pdf_graphics;
mod pdf_links;
mod pdf_image;
mod pdf_links;
mod quantities;
mod restores;
mod scanning;
mod scheduling;
mod statistics;
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Limits {
pub steps: usize,
pub tokens: usize,
@@ -65,6 +65,7 @@ impl From<Token> for InputToken {
}
}
}
#[derive(Clone)]
enum InputFrame {
Source {
source: usize,
@@ -110,6 +111,7 @@ enum TheValue {
Tokens(Vec<Token>),
Text(std::string::String),
}
#[derive(Clone)]
struct Conditional {
primitive: Primitive,
inverted: bool,
@@ -137,6 +139,7 @@ impl ConditionalLimit {
}
}
#[derive(Clone)]
pub struct Executor {
state: State,
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 {
// Native jobs enforce the no-shell-escape policy for immediate and shipped writes.
const SHELL_ESCAPE: i32 = 0;
@@ -541,7 +598,9 @@ impl Executor {
Ok(Some(input))
} else {
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),
}
};
@@ -2874,7 +2933,72 @@ impl Executor {
files: &mut impl SourceProvider,
) -> Result<Execution, ExecutionFailure> {
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();
if let Err(error) = result {
use sha2::{Digest, Sha256};
@@ -2932,17 +3056,25 @@ impl Executor {
steps: self.steps,
})
}
fn run_observed(
fn run_observed<F: SourceProvider>(
&mut self,
file: SourceFile,
files: &mut impl SourceProvider,
files: &mut F,
capture_boundary: impl FnMut(&Self, usize, &mut F),
) -> Result<(), Error> {
self.check_cancellation()?;
self.change_interaction_mode(self.interaction_mode, files)?;
let result = self
.run_input(file, files)
.and_then(|()| self.finish_pdf_catalog());
if let Err(mut error) = result {
let result = self.prepare_input(file, files).and_then(|initial_depth| {
self.run_active_input(initial_depth, files, capture_boundary)
});
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) {
error
.message
@@ -2966,11 +3098,11 @@ impl Executor {
self.check_cancellation()?;
Ok(())
}
fn run_input(
fn prepare_input(
&mut self,
file: SourceFile,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
) -> Result<usize, Error> {
if self.job_name.is_none() {
self.job_name = std::path::Path::new(&file.name)
.file_stem()
@@ -3021,7 +3153,16 @@ impl Executor {
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 {
capture_boundary(self, initial_depth, files);
self.process_native_pages(files)?;
let Some(input) = self.expanded(files)? else {
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)?;
}
Some(Dimen | Skip | Muskip) => {
@@ -23,10 +23,12 @@ struct Template {
prefix: Vec<Token>,
suffix: Vec<Token>,
}
#[derive(Clone)]
struct Cell {
last: usize,
node: NativeBox,
}
#[derive(Clone)]
pub(super) struct AlignmentFrame {
horizontal: bool,
span: Span,
@@ -9,6 +9,7 @@ pub(super) enum Destination {
Adjustment { pre: bool },
Insertion { class: u8 },
}
#[derive(Clone)]
pub(super) struct BoxFrame {
kind: BoxKind,
spec: PackSpec,
@@ -23,6 +24,7 @@ pub(super) struct BoxFrame {
// An inner $...$ belongs to this box, even inside an outer display.
display: Option<super::display::DisplayFrame>,
}
#[derive(Clone)]
struct DiscretionaryFrame {
parts: Vec<Vec<TextNode>>,
font: FontId,
@@ -13,6 +13,7 @@ pub(super) struct EquationNumber {
pub(super) box_: NativeBox,
}
#[derive(Clone)]
pub(super) struct DisplayFrame {
previous_lines: usize,
pub(super) number_side: Option<EquationSide>,
@@ -1,6 +1,7 @@
use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*;
#[derive(Clone)]
pub(super) struct OutputFrame {
depth: usize,
paragraph: Option<super::super::paragraph::Builder>,
@@ -16,6 +16,7 @@ struct Segment {
transformed: bool,
}
#[derive(Clone)]
pub(super) struct ActiveLink {
layout: LinkStart,
attributes: String,
@@ -28,6 +28,7 @@ pub struct PageMarks {
}
#[derive(Default)]
#[derive(Clone)]
pub(super) struct MigratingMaterial {
pub pre: Vec<NativeVerticalNode>,
pub post: Vec<NativeVerticalNode>,
@@ -216,6 +216,7 @@ pub(super) enum MathGroupTarget {
Field(FieldTarget),
Choice { node: usize, branch: usize },
}
#[derive(Clone)]
pub(super) struct MathBuilder {
pub nodes: Vec<MathNode>,
pub numerator: Option<PendingFraction>,
@@ -225,6 +226,7 @@ pub(super) struct MathBuilder {
pub left: Option<(Delimiter, PaintSource)>,
pub span: Span,
}
#[derive(Clone)]
pub(super) struct PendingFraction {
pub numerator: Vec<MathNode>,
pub specification: FractionSpec,
+1 -1
View File
@@ -52,7 +52,7 @@ pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{Executor, Limits};
pub use engine::{EntryCheckpoint, Executor, Limits};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
};
@@ -168,11 +168,13 @@ enum LineState {
Skip,
}
#[derive(Clone)]
enum LineBreaks {
Physical,
Generated(Option<char>),
}
#[derive(Clone)]
pub(super) struct Mouth {
source: usize,
data: Vec<u8>,
@@ -187,6 +189,28 @@ pub(super) struct 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 {
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 std::sync::{Arc, Mutex};
use super::{
Cancellation, Error, Execution, ExecutionFailure, Executor, SourceFile, SourceProvider,
Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, SourceFile,
SourceProvider,
};
#[derive(Clone, Default)]
@@ -165,6 +166,45 @@ impl RevisionJob {
let executed = executor
.with_cancellation(self.cancellation.clone())
.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
// invoke the host while holding the session publication lock.
let resources = files.execution_resource_trace().cloned();
+26 -3
View File
@@ -509,6 +509,7 @@ pub struct FileWorld {
deferred_probes: BTreeMap<PathBuf, DeferredProbe>,
namespace_observations: usize,
live_paths: BTreeSet<PathBuf>,
staged_generated: BTreeMap<PathBuf, PathBuf>,
/// Actual host resource promotions, never inferred from serialized cache.
protected_paths: BTreeSet<PathBuf>,
replay_gaps: Vec<String>,
@@ -642,6 +643,7 @@ impl FileWorld {
deferred_probes: BTreeMap::new(),
namespace_observations: 0,
live_paths: BTreeSet::new(),
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(),
replay_gaps: Vec::new(),
project: None,
@@ -680,6 +682,7 @@ impl FileWorld {
deferred_probes: BTreeMap::new(),
namespace_observations: 0,
live_paths,
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(),
replay_gaps: Vec::new(),
project: Some(project),
@@ -763,6 +766,7 @@ impl FileWorld {
.as_ref()
.map(|p| p.generated().map(Path::to_path_buf).collect())
.unwrap_or_default(),
staged_generated: BTreeMap::new(),
protected_paths: BTreeSet::new(),
replay_gaps: Vec::new(),
project: snapshot.project.clone(),
@@ -880,6 +884,21 @@ impl FileWorld {
pub fn generated_paths(&self) -> impl Iterator<Item = &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> {
self.live_paths
.union(&self.protected_paths)
@@ -905,7 +924,11 @@ impl FileWorld {
let location = project.locate(path, &self.project_paths())?;
let result = if location.kind == Some(project::NodeKind::File) {
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 {
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 {
version: ResourceVersion {
path: path.clone(),
@@ -1530,7 +1553,7 @@ impl FileWorld {
}
let time = match project_time {
Some(time) => Some(time),
None => fs::metadata(path)
None => fs::metadata(self.generated_storage(path))
.and_then(|metadata| metadata.modified())
.ok()
.map(FileModificationTime::from_system_time)
@@ -158,6 +158,19 @@ impl ProjectSnapshot {
pub fn modification_time(&self, path: &Path) -> Option<FileModificationTime> {
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> {
self.generated.iter().map(PathBuf::as_path)
}