Author SHA1 Message Date
gloamxun 31bf50806e Prototype cancellable GNU matching in native compilation sessions 2026-11-19 22:44:42 +08:00
gloamxun 24ea6ef7ee Reuse fixed file identity within a live alias scan 2026-11-19 22:02:53 +08:00
gloamxun 1c02d8af25 Trace live alias checks and GNU regex cancellation 2026-11-19 21:52:39 +08:00
gloamxun 7e67494863 Verify buffered fingerprints across the workspace and publisher corpus 2026-11-19 21:38:06 +08:00
gloamxun 10a08c4597 Batch native state fingerprint writes for live editing 2026-11-19 21:15:54 +08:00
gloamxun 959dd4f24a Measure real A4 hyphenation fingerprint reuse 2026-11-19 20:59:32 +08:00
gloamxun 37ae9b5e9e Verify real A3 continuation at the edited line 2026-11-19 20:35:19 +08:00
gloamxun 2368db1d71 Verify input resolution across compiler and publisher jobs 2026-11-19 20:29:32 +08:00
gloamxun 11063c65dd Record pdfTeX margin behavior and capture checkpoint evidence 2026-11-19 20:15:49 +08:00
gloamxun ee22f25ee0 Resolve TeX inputs with the default suffix alternatives 2026-11-19 20:01:08 +08:00
gloamxun 901a50c36c Record A4 preview transport timing 2026-11-19 19:32:32 +08:00
gloamxun 48c980c871 Share TeX hyphenation patterns and reuse verified state fingerprints 2026-11-19 19:00:55 +08:00
gloamxun 3ffa452fd1 Use file identities for Unix alias checks 2026-11-19 18:43:34 +08:00
gloamxun 3faac740bd Test official ACM journals and proceedings 2026-11-19 18:25:37 +08:00
gloamxun ab50ca7dad Reuse project directory indexes within a revision 2026-11-19 18:14:31 +08:00
gloamxun 41af3d8d22 Cancel jobs while their private file sync drains 2026-11-19 18:01:50 +08:00
gloamxun f6c493e462 Edit multiple project buffers in the native preview 2026-11-19 17:39:01 +08:00
gloamxun b5e87a8706 Stop obsolete draft rendering between pages 2026-11-19 17:28:55 +08:00
gloamxun eda01fb689 Show native preview during durable file publication 2026-11-19 17:19:11 +08:00
gloamxun 75d156f0cf Retain recent checkpoints for alternating body edits 2026-11-19 17:02:26 +08:00
gloamxun d587405d2e Record mixed editing latency and retention regression 2026-11-19 16:44:45 +08:00
gloamxun 393fba42d8 Reuse closed events and line breaking after a checkpoint 2026-11-19 16:39:08 +08:00
gloamxun fc6786d9f4 Record current real-format preview equivalence 2026-11-19 16:29:09 +08:00
gloamxun 8d3a2f8f27 Record fresh CVPR and microtype template baselines 2026-11-19 16:19:29 +08:00
gloamxun 28668ea10f Refresh interactive TeX state across successive edits 2026-11-19 16:19:29 +08:00
36 changed files with 3422 additions and 369 deletions

No files matched your search

Generated
+1
View File
@@ -1431,6 +1431,7 @@ version = "0.1.0"
dependencies = [
"flate2",
"hyphenate",
"libc",
"lopdf",
"rusttype",
"serde",
+3
View File
@@ -13,3 +13,6 @@ serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
sha2 = "=0.10.9"
hyphenate = { path = "../../vendor/hyphenate" }
[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies]
libc = "0.2"
+132 -17
View File
@@ -26,6 +26,8 @@ mod pdf_color;
mod pdf_graphics;
mod pdf_image;
mod pdf_links;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub(super) mod pdf_match;
mod quantities;
mod restores;
mod scanning;
@@ -139,6 +141,55 @@ impl ConditionalLimit {
}
}
// Closed chunks keep their original order and are shared by entry checkpoints.
// The live tail is the only part changed while a continuation executes.
#[derive(Clone, Default)]
struct ExecutionEvents {
prefix: Vec<std::sync::Arc<Vec<Event>>>,
prefix_len: usize,
tail: Vec<Event>,
}
impl ExecutionEvents {
fn push(&mut self, event: Event) {
self.tail.push(event);
}
fn len(&self) -> usize {
self.prefix_len + self.tail.len()
}
fn iter(&self) -> impl Iterator<Item = &Event> {
self.prefix
.iter()
.flat_map(|chunk| chunk.iter())
.chain(&self.tail)
}
fn seal_prefix(&mut self) {
if !self.tail.is_empty() {
self.prefix_len += self.tail.len();
self.prefix
.push(std::sync::Arc::new(std::mem::take(&mut self.tail)));
}
}
fn into_vec(self) -> Vec<Event> {
if self.prefix.is_empty() {
return self.tail;
}
let mut events = Vec::with_capacity(self.len());
for chunk in self.prefix {
match std::sync::Arc::try_unwrap(chunk) {
Ok(chunk) => events.extend(chunk),
Err(chunk) => events.extend_from_slice(&chunk),
}
}
events.extend(self.tail);
events
}
}
#[derive(Clone)]
pub struct Executor {
state: State,
@@ -155,7 +206,7 @@ pub struct Executor {
conditionals: Vec<Conditional>,
in_csname: bool,
command_trace_mode: Option<&'static str>,
events: Vec<Event>,
events: ExecutionEvents,
steps: usize,
ligature_carry: super::ligature::Carry,
current: Span,
@@ -166,6 +217,8 @@ pub struct Executor {
io: IoState,
pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>,
pdf_outlines: Vec<crate::pdf_device::catalog::PdfOutline<Vec<Token>>>,
pdf_outline_payload: usize,
@@ -242,11 +295,44 @@ impl EntryCheckpoint {
source: SourceFile,
files: &mut impl SourceProvider,
cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed(source, files, cancellation, None, None, |_, _, _| {})
}
pub(super) fn resume_capturing_entries_after_host_replay<F: SourceProvider, S>(
&self,
source: SourceFile,
files: &mut F,
cancellation: Cancellation,
line_break_cache: std::sync::Arc<super::LineBreakCache>,
previous: Option<&Execution>,
select: impl FnMut(usize, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed(
source,
files,
cancellation,
Some(line_break_cache),
previous,
Executor::entry_observer(self.incoming_state, select, capture),
)
}
fn resume_observed<F: SourceProvider>(
&self,
source: SourceFile,
files: &mut F,
cancellation: Cancellation,
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>,
capture_boundary: impl FnMut(&mut Executor, usize, &mut F),
) -> Option<Result<Execution, ExecutionFailure>> {
if !self.accepts_entry(&source) {
return None;
}
let mut executor = self.executor.clone().with_cancellation(cancellation);
executor.line_break_cache = line_break_cache;
let Some(InputFrame::Source { mouth, .. }) = executor.inputs.first_mut() else {
unreachable!("entry checkpoints start with the physical source frame");
};
@@ -254,9 +340,9 @@ impl EntryCheckpoint {
executor.sources[self.entry] = source;
let result = executor
.check_cancellation()
.and_then(|_| executor.run_active_input(self.initial_depth, files, |_, _, _| {}));
.and_then(|_| executor.run_active_input(self.initial_depth, files, capture_boundary));
let result = executor.finish_observed_input(result, files);
Some(executor.finish_execution(result, self.incoming_state))
Some(executor.finish_execution(result, self.incoming_state, previous))
}
}
@@ -284,7 +370,7 @@ impl Executor {
conditionals: Vec::new(),
in_csname: false,
command_trace_mode: None,
events: Vec::new(),
events: ExecutionEvents::default(),
steps: 0,
ligature_carry: super::ligature::Carry::default(),
current: Span::default(),
@@ -295,6 +381,8 @@ impl Executor {
io: IoState::default(),
pdf_colors: Default::default(),
pdf_link_stack: Vec::new(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None,
pdf_catalog_tokens: Vec::new(),
pdf_outlines: Vec::new(),
pdf_outline_payload: 0,
@@ -762,6 +850,13 @@ impl Executor {
};
self.print_tokens(result, token)?;
}
Pdfmatch | Pdflastmatch => {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
self.expand_pdf_match(primitive, token, files)?;
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
return self
.fail("pdfTeX regular expressions are unavailable on this host");
}
Pdfcolorstackinit => {
let stack = self.init_pdf_color_stack(files)?;
self.print_tokens(&stack.to_string(), token)?;
@@ -2714,7 +2809,7 @@ impl Executor {
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
events: self.events,
events: self.events.into_vec(),
steps: self.steps,
})
}
@@ -2958,7 +3053,7 @@ impl Executor {
) -> Result<Execution, ExecutionFailure> {
let incoming_state = self.state.fingerprint();
let result = self.run_observed(file, files, |_, _, _| {});
self.finish_execution(result, incoming_state)
self.finish_execution(result, incoming_state, None)
}
/// Capture the first eligible entry command boundary at or beyond the
/// requested physical byte. The callback captures the matching host state.
@@ -2998,11 +3093,24 @@ impl Executor {
mut self,
file: SourceFile,
files: &mut F,
mut select: impl FnMut(usize, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
select: impl FnMut(usize, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Result<Execution, ExecutionFailure> {
let incoming_state = self.state.fingerprint();
let result = self.run_observed(file, files, |engine, initial_depth, files| {
let result = self.run_observed(
file,
files,
Self::entry_observer(incoming_state, select, capture),
);
self.finish_execution(result, incoming_state, None)
}
fn entry_observer<F: SourceProvider, S>(
incoming_state: u64,
mut select: impl FnMut(usize, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> impl FnMut(&mut Self, usize, &mut F) {
move |engine, initial_depth, files| {
if engine.job_ended {
return;
}
@@ -3035,24 +3143,26 @@ impl Executor {
}) {
return;
}
let entry = *source;
engine.events.seal_prefix();
let mut executor = engine.clone();
executor.cancellation = None;
executor.line_break_cache = None;
let checkpoint = EntryCheckpoint {
executor,
entry: *source,
entry,
initial_depth,
incoming_state,
frontier,
};
capture(slot, checkpoint, files);
});
self.finish_execution(result, incoming_state)
}
}
fn finish_execution(
mut self,
result: Result<(), Error>,
incoming_state: u64,
previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> {
self.collect_meaning_reads();
if let Err(error) = result {
@@ -3071,7 +3181,7 @@ impl Executor {
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
events: self.events,
events: self.events.into_vec(),
input_position: self.input_position,
incoming_state,
outgoing_state: self.state.fingerprint(),
@@ -3090,15 +3200,20 @@ impl Executor {
evidence,
});
}
// An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments.
let outgoing_state = previous
.filter(|last| last.state == self.state)
.map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state);
Ok(Execution {
format_dumped: self.format_dumped,
job_name: self.job_name,
interaction_mode: self.interaction_mode,
after_assignment: self.after_assignment,
events: self.events,
events: self.events.into_vec(),
native_page: self.native_page,
split_discards: self.split_discards,
outgoing_state: self.state.fingerprint(),
outgoing_state,
state: self.state,
io: self.io,
input_position: self.input_position,
@@ -3115,7 +3230,7 @@ impl Executor {
&mut self,
file: SourceFile,
files: &mut F,
capture_boundary: impl FnMut(&Self, usize, &mut F),
capture_boundary: impl FnMut(&mut Self, usize, &mut F),
) -> Result<(), Error> {
self.check_cancellation()?;
self.change_interaction_mode(self.interaction_mode, files)?;
@@ -3214,7 +3329,7 @@ impl Executor {
&mut self,
initial_depth: usize,
files: &mut F,
mut capture_boundary: impl FnMut(&Self, usize, &mut F),
mut capture_boundary: impl FnMut(&mut Self, usize, &mut F),
) -> Result<(), Error> {
loop {
self.check_box_capacity(None)?;
@@ -44,7 +44,7 @@ impl Executor {
}
}
fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
pub(super) fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
let tokens = self.scan_pdf_tokens(files)?;
self.pdf_token_bytes(&tokens)
}
@@ -0,0 +1,218 @@
use super::*;
use std::ffi::{CString, c_int};
use std::mem::MaybeUninit;
use std::ops::Range;
use std::ptr;
pub(super) struct PdfMatch {
input: Vec<u8>,
captures: Vec<Option<Range<usize>>>,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct RegexRequest {
pub pattern: Vec<u8>,
pub input: Vec<u8>,
pub count: usize,
pub insensitive: bool,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub enum RegexOutcome {
Match(Vec<Option<Range<usize>>>),
NoMatch,
InvalidPattern(String),
}
pub fn match_pdf_regex(request: &RegexRequest) -> Result<RegexOutcome, String> {
match search(
request.pattern.clone(),
request.input.clone(),
request.count,
request.insensitive,
) {
Ok(Some(matched)) => Ok(RegexOutcome::Match(matched.captures)),
Ok(None) => Ok(RegexOutcome::NoMatch),
Err(SearchError::Pattern(message)) => Ok(RegexOutcome::InvalidPattern(message)),
Err(SearchError::Runtime(message)) => Err(message),
}
}
impl Executor {
pub(super) fn expand_pdf_match(
&mut self,
primitive: Primitive,
origin: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if primitive == Primitive::Pdflastmatch {
let index = usize::try_from(self.integer(files)?)
.map_err(|_| self.error("Bad match number", self.current))?;
let text = self
.pdf_last_match
.as_ref()
.and_then(|last| {
let range = last.captures.get(index)?.as_ref()?;
let mut text = format!("{}->", range.start);
text.extend(last.input[range.clone()].iter().copied().map(char::from));
Some(text)
})
.unwrap_or_else(|| String::from("-1->"));
return self.print_tokens(&text, origin);
}
let insensitive = self.keyword("icase", files)?;
let count = if self.keyword("subcount", files)? {
usize::try_from(self.integer(files)?).unwrap_or(10)
} else {
10
};
let pattern = self.scan_pdf_bytes(files)?;
let input = self.scan_pdf_bytes(files)?;
self.check_cancellation()?;
let request = RegexRequest {
pattern,
input,
count,
insensitive,
};
let result = files.match_pdf_regex(&request, self.cancellation.as_ref());
self.check_cancellation()?;
let text = match result.map_err(|message| self.error(message, origin.span))? {
RegexOutcome::Match(captures) => {
let input = as_c_string(request.input).into_bytes();
if captures
.iter()
.flatten()
.any(|range| range.start > range.end || range.end > input.len())
{
return self.fail("regex backend supplied invalid captures");
}
self.pdf_last_match = Some(Arc::new(PdfMatch { input, captures }));
"1"
}
RegexOutcome::NoMatch => {
self.pdf_last_match = None;
"0"
}
RegexOutcome::InvalidPattern(message) => {
files
.observe_diagnostic(
WriteDestination::TerminalAndLog,
&format!("pdfTeX warning: pdftex: \\pdfmatch: {message}\n"),
)
.map_err(|error| self.error(error, origin.span))?;
"-1"
}
};
self.print_tokens(text, origin)
}
}
enum SearchError {
Pattern(String),
Runtime(String),
}
struct CLocale {
active: libc::locale_t,
previous: libc::locale_t,
}
impl CLocale {
fn enter() -> Result<Self, SearchError> {
// The reference engine treats matching as C-locale byte processing.
// Changing only this thread leaves concurrent jobs and the host alone.
let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) };
if active.is_null() {
return Err(SearchError::Runtime("cannot create pdfTeX C locale".into()));
}
let previous = unsafe { libc::uselocale(active) };
if previous.is_null() {
unsafe { libc::freelocale(active) };
return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into()));
}
Ok(Self { active, previous })
}
}
impl Drop for CLocale {
fn drop(&mut self) {
// previous is the still-live locale returned by uselocale above.
unsafe {
libc::uselocale(self.previous);
libc::freelocale(self.active);
}
}
}
struct CompiledRegex(libc::regex_t);
impl Drop for CompiledRegex {
fn drop(&mut self) {
// This wrapper is created only after successful regcomp.
unsafe { libc::regfree(&mut self.0) };
}
}
fn regex_error(code: c_int) -> String {
// An error code can be described without referring to a compiled regex.
let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) };
let mut message = vec![0u8; length];
unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) };
message.pop();
String::from_utf8_lossy(&message).into_owned()
}
fn as_c_string(mut bytes: Vec<u8>) -> CString {
// pdfTeX's makecstring passes the prefix through the first NUL.
if let Some(end) = bytes.iter().position(|&byte| byte == 0) {
bytes.truncate(end);
}
CString::new(bytes).expect("regex bytes were truncated at the first NUL")
}
fn search(
pattern: Vec<u8>,
input: Vec<u8>,
requested: usize,
insensitive: bool,
) -> Result<Option<PdfMatch>, SearchError> {
let _locale = CLocale::enter()?;
let pattern = as_c_string(pattern);
let input = as_c_string(input);
let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 };
let mut regex = MaybeUninit::uninit();
// regcomp initializes the regex storage on success. The pattern is
// NUL-terminated and valid throughout the call.
let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) };
if status != 0 {
return Err(SearchError::Pattern(regex_error(status)));
}
let regex = CompiledRegex(unsafe { regex.assume_init() });
// Group starts cannot outnumber pattern bytes. Requests beyond that
// bound are observable only as missing captures.
let count = requested.min(pattern.as_bytes().len() + 1);
let mut ranges = vec![
libc::regmatch_t {
rm_so: -1,
rm_eo: -1
};
count
];
// Both C strings and the initialized regex live through the call.
// A zero count asks regexec to skip writing capture positions.
let status = unsafe { libc::regexec(&regex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) };
if status != 0 {
return Ok(None);
}
let input = input.into_bytes();
let captures = ranges
.into_iter()
.map(|range| {
let start = usize::try_from(range.rm_so).ok()?;
let end = usize::try_from(range.rm_eo).ok()?;
(start <= end && end <= input.len()).then_some(start..end)
})
.collect();
Ok(Some(PdfMatch { input, captures }))
}
@@ -112,7 +112,7 @@ impl Executor {
InputFrame::Boundary => {}
}
}
for e in &self.events {
for e in self.events.iter() {
if matches!(e, Event::Statistics(_)) {
continue;
}
@@ -4,10 +4,11 @@ use crate::resources::{ResourceReadRange, ResourceVersion};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BTreeSet},
path::Path,
path::{Path, PathBuf},
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 27;
const SCHEMA: u32 = 30;
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -22,6 +23,17 @@ pub struct FormatImage {
resources: Vec<ResourceVersion>,
stream_reads: Vec<ResourceReadRange>,
file_dates: Vec<FormatFileDate>,
#[serde(skip)]
input_checks: OnceLock<BTreeMap<PathBuf, InputChecks>>,
}
#[derive(Default)]
struct InputChecks {
sources: Vec<usize>,
versions: Vec<usize>,
ranges: Vec<usize>,
// The same immutable allocation already passed this image's full checks.
verified: Mutex<Option<Weak<[u8]>>>,
}
#[derive(serde::Serialize, serde::Deserialize)]
@@ -69,6 +81,7 @@ impl FormatImage {
resources,
stream_reads,
file_dates,
input_checks: OnceLock::new(),
})
}
@@ -198,84 +211,61 @@ impl FormatImage {
input_profile: InputProfile,
files: &mut F,
mut read: impl FnMut(&mut F, &Path) -> Result<T, String>,
date: impl FnMut(&mut F, &str, &str) -> Result<Option<String>, String>,
) -> Result<(), String> {
self.validate_inputs(
profile,
input_profile,
files,
|files, path, checks| self.check_input(path, checks, read(files, path)?.as_ref()),
date,
)
}
/// Resolve every format input in this job. Skip content checks only when
/// the resolver returns the same immutable buffer already verified by this image.
pub fn validate_shared_job_inputs<F>(
&self,
profile: Profile,
input_profile: InputProfile,
files: &mut F,
mut read: impl FnMut(&mut F, &Path) -> Result<Arc<[u8]>, String>,
date: impl FnMut(&mut F, &str, &str) -> Result<Option<String>, String>,
) -> Result<(), String> {
self.validate_inputs(
profile,
input_profile,
files,
|files, path, checks| {
let data = read(files, path)?;
let identity = Arc::downgrade(&data);
let mut verified = checks
.verified
.lock()
.map_err(|_| "native format input cache poisoned")?;
if !verified.as_ref().is_some_and(|old| old.ptr_eq(&identity)) {
self.check_input(path, checks, &data)?;
*verified = Some(identity);
}
Ok(())
},
date,
)
}
fn validate_inputs<F>(
&self,
profile: Profile,
input_profile: InputProfile,
files: &mut F,
mut validate: impl FnMut(&mut F, &Path, &InputChecks) -> Result<(), String>,
mut date: impl FnMut(&mut F, &str, &str) -> Result<Option<String>, String>,
) -> Result<(), String> {
if self.state.profile() != profile || self.state.input_profile() != input_profile {
return Err("native format profile mismatch".into());
}
#[derive(Default)]
struct Checks<'a> {
sources: Vec<(usize, &'a SourceFile)>,
versions: Vec<&'a ResourceVersion>,
ranges: Vec<&'a ResourceReadRange>,
}
let mut checks = BTreeMap::<&Path, Checks<'_>>::new();
for (id, source) in self.sources.iter().enumerate() {
if !self.generated_inputs.contains_key(&id) {
checks
.entry(Path::new(&source.name))
.or_default()
.sources
.push((id, source));
}
}
for version in &self.resources {
checks
.entry(&version.path)
.or_default()
.versions
.push(version);
}
for range in &self.stream_reads {
checks.entry(&range.path).or_default().ranges.push(range);
}
for (path, checks) in checks {
let data = read(files, path)?;
let bytes = data.as_ref();
for (id, source) in checks.sources {
let valid = if self.stream_sources.contains(&id) {
bytes.starts_with(&source.data)
} else {
bytes == source.data
};
if !valid {
return Err(format!("native format source changed: {}", source.name));
}
}
if !checks.versions.is_empty() {
let sha256 = digest(bytes);
if checks
.versions
.iter()
.any(|version| bytes.len() as u64 != version.bytes || sha256 != version.sha256)
{
return Err(format!(
"native format resource changed: {}",
path.display()
));
}
}
for range in checks.ranges {
let valid = if range.eof {
bytes.len() as u64 == range.offset
} else {
let start = usize::try_from(range.offset).ok();
let end = range
.offset
.checked_add(range.bytes)
.and_then(|n| usize::try_from(n).ok());
start
.zip(end)
.and_then(|(start, end)| bytes.get(start..end))
.is_some_and(|bytes| digest(bytes) == range.sha256)
};
if !valid {
return Err(format!(
"native format stream dependency changed: {}",
path.display()
));
}
}
for (path, checks) in self.input_checks.get_or_init(|| self.build_input_checks()) {
validate(files, path, checks)?;
}
for observed in &self.file_dates {
if date(files, &observed.name, &observed.from)? != observed.value {
@@ -287,8 +277,143 @@ impl FormatImage {
}
Ok(())
}
fn build_input_checks(&self) -> BTreeMap<PathBuf, InputChecks> {
let mut checks = BTreeMap::<&Path, InputChecks>::new();
for (id, source) in self.sources.iter().enumerate() {
if !self.generated_inputs.contains_key(&id) {
checks
.entry(Path::new(&source.name))
.or_default()
.sources
.push(id);
}
}
for (id, version) in self.resources.iter().enumerate() {
checks.entry(&version.path).or_default().versions.push(id);
}
for (id, range) in self.stream_reads.iter().enumerate() {
checks.entry(&range.path).or_default().ranges.push(id);
}
checks
.into_iter()
.map(|(path, checks)| (path.to_path_buf(), checks))
.collect()
}
fn check_input(&self, path: &Path, checks: &InputChecks, bytes: &[u8]) -> Result<(), String> {
for &id in &checks.sources {
let source = &self.sources[id];
let valid = if self.stream_sources.contains(&id) {
bytes.starts_with(&source.data)
} else {
bytes == source.data
};
if !valid {
return Err(format!("native format source changed: {}", source.name));
}
}
if !checks.versions.is_empty() {
let sha256 = digest(bytes);
if checks.versions.iter().any(|&id| {
let version = &self.resources[id];
bytes.len() as u64 != version.bytes || sha256 != version.sha256
}) {
return Err(format!(
"native format resource changed: {}",
path.display()
));
}
}
for &id in &checks.ranges {
let range = &self.stream_reads[id];
let valid = if range.eof {
bytes.len() as u64 == range.offset
} else {
let start = usize::try_from(range.offset).ok();
let end = range
.offset
.checked_add(range.bytes)
.and_then(|n| usize::try_from(n).ok());
start
.zip(end)
.and_then(|(start, end)| bytes.get(start..end))
.is_some_and(|bytes| digest(bytes) == range.sha256)
};
if !valid {
return Err(format!(
"native format stream dependency changed: {}",
path.display()
));
}
}
Ok(())
}
}
fn digest(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shared_format_checks_track_live_lookups_and_reject_replaced_stream_bytes() {
let path = PathBuf::from("stream.tex");
let image = FormatImage {
schema: SCHEMA,
engine: ENGINE.into(),
state: State::default(),
sources: Vec::new(),
stream_sources: BTreeSet::new(),
generated_inputs: BTreeMap::new(),
resources: Vec::new(),
stream_reads: vec![ResourceReadRange {
path: path.clone(),
offset: 1,
bytes: 2,
sha256: digest(b"bc"),
eof: false,
}],
file_dates: vec![FormatFileDate {
name: "date.tex".into(),
from: "stream.tex".into(),
value: Some("observed date".into()),
}],
input_checks: OnceLock::new(),
};
let encoded = image.encode().unwrap();
let mut bytes: Arc<[u8]> = Arc::from(&b"abcd"[..]);
let mut seen = (0, 0);
let mut check = |bytes: &Arc<[u8]>| {
image.validate_shared_job_inputs(
image.state.profile(),
image.state.input_profile(),
&mut seen,
|seen, requested| {
assert_eq!(requested, path);
seen.0 += 1;
Ok(bytes.clone())
},
|seen, name, from| {
assert_eq!((name, from), ("date.tex", "stream.tex"));
seen.1 += 1;
Ok(Some("observed date".into()))
},
)
};
check(&bytes).unwrap();
check(&bytes).unwrap();
Arc::make_mut(&mut bytes)[1] = b'x';
assert!(
check(&bytes)
.unwrap_err()
.contains("stream dependency changed")
);
check(&Arc::from(&b"abc!"[..])).unwrap();
assert_eq!(seen, (4, 3));
assert_eq!(image.encode().unwrap(), encoded);
}
}
@@ -1,6 +1,10 @@
//! Native language tables and pattern trie. No implicit English dictionary.
use super::*;
use std::collections::BTreeMap;
use std::{
collections::BTreeMap,
hash::{Hash, Hasher},
sync::{Arc, OnceLock},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct HyphenationLanguage {
pub language: u8,
@@ -39,20 +43,48 @@ struct TrieNode {
edges: BTreeMap<u32, usize>,
weights: Vec<u8>,
}
// Job state and checkpoints share the pattern trie. Pattern assignments
// can still mutate it while building a format.
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct TrieNodes {
values: Vec<TrieNode>,
#[serde(skip)]
counts: OnceLock<(usize, usize)>,
}
impl PartialEq for TrieNodes {
fn eq(&self, other: &Self) -> bool {
self.values == other.values
}
}
impl Eq for TrieNodes {}
impl Hash for TrieNodes {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.values.hash(hasher);
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) struct HyphenationData {
nodes: Vec<TrieNode>,
nodes: Arc<TrieNodes>,
roots: BTreeMap<u8, usize>,
pub exceptions: BTreeMap<u8, BTreeMap<String, Vec<usize>>>,
pub sealed: bool,
}
impl HyphenationData {
pub(super) fn resource_counts(&self) -> (usize, usize, usize) {
(
self.nodes.len(),
self.nodes.iter().map(|n| n.edges.len()).sum(),
self.nodes.iter().map(|n| n.weights.len()).sum(),
)
let (edges, weights) = *self.nodes.counts.get_or_init(|| {
self.nodes
.values
.iter()
.fold((0, 0), |(edges, weights), node| {
(edges + node.edges.len(), weights + node.weights.len())
})
});
(self.nodes.values.len(), edges, weights)
}
pub fn insert(
&mut self,
@@ -61,34 +93,37 @@ impl HyphenationData {
weights: &[u8],
limit: usize,
) -> Result<(), String> {
let trie = Arc::make_mut(&mut self.nodes);
trie.counts.take();
let nodes = &mut trie.values;
let mut at = if let Some(&root) = self.roots.get(&language) {
root
} else {
let root = self.node(limit)?;
let root = Self::node(nodes, limit)?;
self.roots.insert(language, root);
root
};
for c in letters {
at = if let Some(&next) = self.nodes[at].edges.get(c) {
at = if let Some(&next) = nodes[at].edges.get(c) {
next
} else {
let next = self.node(limit)?;
self.nodes[at].edges.insert(*c, next);
let next = Self::node(nodes, limit)?;
nodes[at].edges.insert(*c, next);
next
};
}
if self.nodes[at].weights.iter().any(|v| *v != 0) {
if nodes[at].weights.iter().any(|v| *v != 0) {
return Err("duplicate hyphenation pattern".into());
}
self.nodes[at].weights = weights.to_vec();
nodes[at].weights = weights.to_vec();
Ok(())
}
fn node(&mut self, limit: usize) -> Result<usize, String> {
if self.nodes.len() >= limit {
fn node(nodes: &mut Vec<TrieNode>, limit: usize) -> Result<usize, String> {
if nodes.len() >= limit {
return Err("native hyphenation pattern memory limit exceeded".into());
}
let next = self.nodes.len();
self.nodes.push(TrieNode::default());
let next = nodes.len();
nodes.push(TrieNode::default());
Ok(next)
}
pub fn points(&self, language: u8, word: &str) -> Vec<usize> {
@@ -98,6 +133,7 @@ impl HyphenationData {
let Some(&root) = self.roots.get(&language) else {
return Vec::new();
};
let nodes = &self.nodes.values;
let letters: Vec<_> = std::iter::once(0)
.chain(word.chars().map(|c| c as u32))
.chain([0])
@@ -106,11 +142,11 @@ impl HyphenationData {
for start in 0..letters.len() {
let mut at = root;
for c in &letters[start..] {
let Some(&next) = self.nodes[at].edges.get(c) else {
let Some(&next) = nodes[at].edges.get(c) else {
break;
};
at = next;
for (i, &v) in self.nodes[at].weights.iter().enumerate() {
for (i, &v) in nodes[at].weights.iter().enumerate() {
scores[start + i] = scores[start + i].max(v);
}
}
@@ -120,3 +156,37 @@ impl HyphenationData {
.collect()
}
}
#[test]
fn cloned_patterns_remain_isolated_on_assignment() {
let mut format = HyphenationData::default();
let letters = ['t' as u32, 'e' as u32];
format.insert(0, &letters, &[0, 1, 0], 12).unwrap();
assert_eq!(format.resource_counts(), (3, 2, 3));
let shared = format.clone();
assert!(Arc::ptr_eq(&format.nodes, &shared.nodes));
format.insert(0, &['a' as u32], &[0, 0], 12).unwrap();
assert_eq!(format.resource_counts(), (4, 3, 5));
assert_eq!(shared.resource_counts(), (3, 2, 3));
assert_eq!(shared.points(0, "tea"), [1]);
assert_eq!(format.points(0, "tea"), [1]);
let encoded = serde_json::to_value(&shared).unwrap();
assert_eq!(
encoded["nodes"],
serde_json::to_value(&shared.nodes.values).unwrap()
);
let restored: HyphenationData = serde_json::from_value(encoded).unwrap();
assert_eq!(restored, shared);
assert_eq!(restored.resource_counts(), (3, 2, 3));
let hash = |nodes: &TrieNodes| {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
nodes.hash(&mut hasher);
hasher.finish()
};
let mut legacy = std::collections::hash_map::DefaultHasher::new();
shared.nodes.values.hash(&mut legacy);
assert_eq!(hash(&shared.nodes), legacy.finish());
}
+14 -4
View File
@@ -7,6 +7,8 @@ mod context;
mod device;
mod diagnostics;
mod engine;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub use engine::pdf_match::{RegexOutcome, RegexRequest, match_pdf_regex};
mod font_catalog;
mod fonts;
mod format_image;
@@ -210,6 +212,15 @@ pub struct GeneratedInput {
/// File lookup belongs to the host. Execution never shells out to TeX or
/// searches a different engine when a file/primitive is absent.
pub trait SourceProvider {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &RegexRequest,
_cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
match_pdf_regex(request)
}
/// Change the TeX diagnostic selector. Mode zero suppresses the terminal.
fn set_interaction_mode(&mut self, _mode: u8) -> Result<(), String> {
Ok(())
@@ -749,14 +760,13 @@ impl Execution {
}
NativeVerticalNode::Glue(g)
| NativeVerticalNode::NamedGlue(g, _)
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => {
items.push(VerticalItem::StretchGlue(VerticalGlue::with_order(
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => items
.push(VerticalItem::StretchGlue(VerticalGlue::with_order(
bp(g.width as i64),
bp(g.stretch.amount as i64),
bp(g.shrink.amount as i64),
g.stretch.order,
)))
}
))),
NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => {
items.push(VerticalItem::Glue(bp(*n as i64)))
}
@@ -3,8 +3,8 @@ use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex};
use super::{
Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, SourceFile,
SourceProvider,
Cancellation, EntryCheckpoint, Error, Execution, ExecutionFailure, Executor, LineBreakCache,
SourceFile, SourceProvider,
};
#[derive(Clone, Default)]
@@ -197,6 +197,29 @@ impl RevisionJob {
Some(self.finish_execution(executed, files))
}
/// Resume a verified prefix and observe new boundaries in the executed suffix.
pub fn resume_capturing_entries_after_host_replay<F: SourceProvider, S>(
self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
files: &mut F,
line_break_cache: Arc<LineBreakCache>,
select: impl FnMut(usize, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Option<Result<Arc<RevisionExecution>, RevisionFailure>> {
let previous = self.session.latest();
let executed = checkpoint.resume_capturing_entries_after_host_replay(
source,
files,
self.cancellation.clone(),
line_break_cache,
previous.as_deref().map(|revision| &revision.execution),
select,
capture,
)?;
Some(self.finish_execution(executed, files))
}
fn finish_execution(
self,
executed: Result<Execution, ExecutionFailure>,
+69 -2
View File
@@ -1,5 +1,5 @@
use std::collections::BTreeMap;
use std::hash::{Hash, Hasher};
use std::hash::{DefaultHasher, Hash, Hasher};
use super::{
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
@@ -102,6 +102,8 @@ pub enum Primitive {
Ifpdfabsnum,
Ifpdfabsdim,
Pdfstrcmp,
Pdfmatch,
Pdflastmatch,
Pdfcolorstackinit,
Pdfcolorstack,
Pdfsave,
@@ -362,6 +364,8 @@ impl Primitive {
| Pdfcreationdate
| Pdftexrevision
| Pdfstrcmp
| Pdfmatch
| Pdflastmatch
| Pdfcolorstackinit
| Csname
| Unless
@@ -607,6 +611,65 @@ pub struct State {
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl Hasher for FingerprintHasher {
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
#[test]
fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut state = State::initex().with_etex();
let check = |state: &State| {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
assert_eq!(state.fingerprint(), direct.finish());
};
check(&state);
state.begin_group(GroupKind::Simple, None);
state.define(
CommandName::Control("断字".repeat(1024)),
Meaning::Primitive(Primitive::Relax),
false,
);
state.define(CommandName::Control("μ".into()), Meaning::Count(123), true);
check(&state);
}
impl Default for State {
fn default() -> Self {
use Primitive::*;
@@ -859,6 +922,10 @@ impl Default for State {
("pdfcreationdate", Pdfcreationdate),
("pdfshellescape", Pdfshellescape),
("pdfstrcmp", Pdfstrcmp),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdfmatch", Pdfmatch),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdflastmatch", Pdflastmatch),
("pdfcolorstackinit", Pdfcolorstackinit),
("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave),
@@ -1450,7 +1517,7 @@ impl State {
self.groups.len()
}
pub fn fingerprint(&self) -> u64 {
let mut hash = std::collections::hash_map::DefaultHasher::new();
let mut hash = FingerprintHasher::default();
self.hash(&mut hash);
hash.finish()
}
+95 -12
View File
@@ -341,6 +341,9 @@ pub struct InputSnapshot {
replay_gaps: Vec<String>,
#[serde(default)]
project: Option<Arc<ProjectSnapshot>>,
// Older captures only probed the supplied name when it had a suffix.
#[serde(default)]
tex_suffix_fallback: bool,
}
/// A failed enumeration is not a complete namespace. Retain the usable prefix
/// only as evidence and replay its actual error, never as a successful index.
@@ -498,7 +501,9 @@ impl InputSnapshot {
}
pub struct FileWorld {
config: WorldConfig,
tex_suffix_fallback: bool,
indexes: BTreeMap<PathBuf, Arc<DirectoryIndex>>,
current_project_indexes: BTreeSet<PathBuf>,
index_failures: BTreeMap<PathBuf, DirectoryFailure>,
trace: ResourceTrace,
pinned: bool,
@@ -632,7 +637,9 @@ impl FileWorld {
};
Ok(Self {
config,
tex_suffix_fallback: true,
indexes: BTreeMap::new(),
current_project_indexes: BTreeSet::new(),
index_failures: BTreeMap::new(),
trace,
pinned: false,
@@ -671,7 +678,9 @@ impl FileWorld {
let live_paths = project.generated().map(Path::to_path_buf).collect();
Ok(Self {
config,
tex_suffix_fallback: true,
indexes: BTreeMap::new(),
current_project_indexes: BTreeSet::new(),
index_failures: BTreeMap::new(),
trace,
pinned: true,
@@ -747,7 +756,9 @@ impl FileWorld {
};
Ok(Self {
config,
tex_suffix_fallback: snapshot.tex_suffix_fallback,
indexes: snapshot.indexes.clone(),
current_project_indexes: BTreeSet::new(),
index_failures: snapshot.index_failures.clone(),
trace,
pinned: true,
@@ -779,6 +790,7 @@ impl FileWorld {
}
Arc::new(InputSnapshot {
schema: 1,
tex_suffix_fallback: self.tex_suffix_fallback,
config: self.config.clone(),
files: self.input_files.clone(),
file_modifications: self.file_modifications.clone(),
@@ -803,7 +815,9 @@ impl FileWorld {
path.display()
));
}
self.live_paths.insert(path.to_owned());
if self.live_paths.insert(path.to_owned()) && self.project.is_some() {
self.current_project_indexes.clear();
}
}
pub fn mark_generated_initial(&mut self, path: &Path) -> Result<(), String> {
if self
@@ -826,7 +840,10 @@ impl FileWorld {
let was_live = self.live_paths.remove(&resource.version.path);
if self.pinned {
if was_live || self.project.is_some() {
self.protected_paths.insert(resource.version.path.clone());
let newly_protected = self.protected_paths.insert(resource.version.path.clone());
if self.project.is_some() && (was_live || newly_protected) {
self.current_project_indexes.clear();
}
}
if was_live {
self.replay_gaps.push(format!(
@@ -1221,15 +1238,35 @@ impl FileWorld {
}
paths
}
fn variants(kind: ResourceKind, name: &str) -> Vec<PathBuf> {
let p = Path::new(name);
fn variants(kind: ResourceKind, name: &str, tex_suffix_fallback: bool) -> Vec<PathBuf> {
let path = Path::new(name);
let mut values = Vec::new();
if p.extension().is_none() {
values.extend(kind.extensions().iter().map(|e| p.with_extension(e)));
if path.extension().is_none() {
values.extend(
kind.extensions()
.iter()
.map(|extension| path.with_extension(extension)),
);
} else if tex_suffix_fallback && !deferred::directory_only(path) {
// Kpathsea tries the standard suffix before an unrecognized one
// within a search path entry. The recognized TeX suffixes are
// tried as supplied.
const TEX_SUFFIXES: &[&str] =
&["tex", "sty", "cls", "fd", "aux", "bbl", "def", "clo", "ldf"];
let extension = path.extension().and_then(|extension| extension.to_str());
let recognized = extension.is_some_and(|extension| {
TEX_SUFFIXES.iter().any(|known| {
extension == *known || (cfg!(windows) && extension.eq_ignore_ascii_case(known))
})
});
if !recognized {
values.push(PathBuf::from(format!("{name}.tex")));
}
}
values.push(p.to_owned());
values.push(path.to_owned());
values
}
fn existing(path: &Path) -> Result<Option<PathBuf>, String> {
match path.metadata() {
Ok(m) if !m.is_dir() => path
@@ -1243,9 +1280,14 @@ impl FileWorld {
}
fn index(&mut self, root: &Path) -> Result<&DirectoryIndex, String> {
if let Some(project) = &self.project {
let index =
project.index(root, &self.project_paths(), self.config.max_index_entries)?;
self.indexes.insert(root.into(), Arc::new(index));
// The index tracks the logical namespace. Each candidate's live
// existence and staged bytes are still checked by probe().
if !self.current_project_indexes.contains(root) {
let index =
project.index(root, &self.project_paths(), self.config.max_index_entries)?;
self.indexes.insert(root.into(), Arc::new(index));
self.current_project_indexes.insert(root.into());
}
return Ok(&self.indexes[root]);
}
if self.pinned {
@@ -1356,8 +1398,17 @@ impl FileWorld {
name: &str,
from: &Path,
) -> Result<Option<PathBuf>, String> {
self.resolve_variants(kind, name, from, Self::variants(kind, name))
self.resolve_variants(kind, name, from, Self::variants(kind, name, false))
}
/// Apply the TeX input scanner's default suffix alternatives. Raw host
/// files and recorded format dependencies still keep their names.
pub fn resolve_tex_input(&mut self, name: &str, from: &Path) -> Result<Option<PathBuf>, String> {
let kind = ResourceKind::Tex;
let fallback = self.config.input_policy == InputPolicy::Tex && self.tex_suffix_fallback;
self.resolve_variants(kind, name, from, Self::variants(kind, name, fallback))
}
fn resolve_variants(
&mut self,
kind: ResourceKind,
@@ -1486,7 +1537,39 @@ impl FileWorld {
name: &str,
from: &Path,
) -> Result<SnapshotFile, String> {
let path = self.resolve(kind, name, from)?.ok_or_else(|| {
let path = self.resolve(kind, name, from)?;
self.read_shared_resolved(kind, name, from, path)
}
/// Read a normal TeX source, including an unrecognized suffix's .tex
/// alternative when supported by the active input policy.
pub fn read_tex_input(&mut self, name: &str, from: &Path) -> Result<LoadedResource, String> {
let path = self.resolve_tex_input(name, from)?;
self.read_shared_resolved(ResourceKind::Tex, name, from, path)
.map(SnapshotFile::into_loaded)
}
/// TeX file queries use the same lookup as TeX input. A missing lookup
/// is returned as None without opening an arbitrary fallback file.
pub fn read_tex_input_optional(
&mut self,
name: &str,
from: &Path,
) -> Result<Option<LoadedResource>, String> {
let name = if name.is_empty() { ".tex" } else { name };
self.resolve_tex_input(name, from)?
.map(|path| self.read_path(path))
.transpose()
}
fn read_shared_resolved(
&mut self,
kind: ResourceKind,
name: &str,
from: &Path,
path: Option<PathBuf>,
) -> Result<SnapshotFile, String> {
let path = path.ok_or_else(|| {
format!(
"native {kind:?} resource {name} not found from {}",
from.display()
@@ -174,7 +174,7 @@ impl ProjectSnapshot {
pub fn generated(&self) -> impl Iterator<Item = &Path> {
self.generated.iter().map(PathBuf::as_path)
}
pub fn immutable_paths(&self) -> impl Iterator<Item = &Path> {
pub fn immutable_paths(&self) -> impl Iterator<Item = &Path> + Clone {
self.files.keys().map(PathBuf::as_path)
}
pub fn protects_artifact(&self, path: &Path) -> bool {
@@ -0,0 +1,155 @@
#![cfg(all(target_os = "linux", target_env = "gnu"))]
use std::{fs, process::Command};
use texrra_tex_core::execution::*;
const SOURCE: &str = r#"
\catcode123=1 \catcode125=2 \catcode35=6 \catcode94=7
\def\probe#1{\message{!pdfmatch:#1:end!}}
\probe{before=[\pdflastmatch0]}
\def\dimpat{^([0-9]+([.,][0-9]+)?|[.,][0-9]+)(em|ex|cm|mm|in|pc|pt|dd|cc|bp|sp|nd|nc|px)? *$}
\def\value{12.5pt}
\probe{dim=[\pdfmatch{\dimpat}{\value}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]/[\pdflastmatch3]}
\probe{dim-fail=[\pdfmatch{\dimpat}{wd0}]/[\pdflastmatch0]}
\probe{longest=[\pdfmatch{(a|ab)}{cab}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{leftmost=[\pdfmatch{(a|bcde)}{abcde}]/[\pdflastmatch0]}
\probe{case=[\pdfmatch icase subcount 2{(a)(B)}{xAb}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]}
\probe{invalid=[\pdfmatch{[}{x}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{zero=[\pdfmatch subcount 0{(a)}{xax}]/[\pdflastmatch0]}
\probe{negative=[\pdfmatch subcount -2{(a)}{xax}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{optional=[\pdfmatch{(a)?(b*)}{x}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]}
\begingroup \edef\inside{\pdfmatch{(c)}{abc}}\endgroup
\probe{group=[\pdflastmatch0]/[\pdflastmatch1]}
\begingroup\escapechar=-1 \xdef\bs{\string\\}\endgroup
\probe{gnu-backref=[\pdfmatch{^(a)\bs1$}{aa}]/[\pdflastmatch1]}
\probe{gnu-class=[\pdfmatch{^\bs w+$}{a01}]/[\pdflastmatch0]}
\probe{byte-offset=[\pdfmatch{(q)}{^^c3^^a9q}]/[\pdflastmatch1]}
\def\capturedbyte#1->#2{\number`#2}
\edef\status{\pdfmatch{(.)}{^^ffq}}
\edef\capture{\pdflastmatch0}
\probe{nonutf8=[\status]/[\expandafter\capturedbyte\capture]}
\catcode0=12 \catcode10=12
\probe{nul-text=[\pdfmatch{c}{ab^^00cd}]/[\pdflastmatch0]}
\probe{nul-pattern=[\pdfmatch{a^^00b}{xa}]/[\pdflastmatch0]}
\probe{newline=[\pdfmatch{a.b}{a^^0ab}]}
\end
"#;
fn file(source: &str) -> SourceFile {
SourceFile {
name: "probe.tex".into(),
data: source.as_bytes().to_vec(),
}
}
#[test]
fn pdf_regex_matches_reference_bytes_and_retains_job_local_captures() {
let dir = std::env::temp_dir().join(format!("texrra-pdfmatch-{}", std::process::id()));
fs::create_dir(&dir).unwrap();
fs::write(dir.join("probe.tex"), SOURCE).unwrap();
let reference = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.env("LC_ALL", "C")
.env("max_print_line", "1000")
.current_dir(&dir)
.output()
.unwrap();
assert!(
reference.status.success(),
"{}",
String::from_utf8_lossy(&reference.stdout)
);
let log = fs::read(dir.join("probe.log")).unwrap();
let reference: String = log.into_iter().map(char::from).collect();
let expected: Vec<_> = reference
.split("!pdfmatch:")
.skip(1)
.map(|part| part.split_once(":end!").unwrap().0)
.collect();
assert_eq!(expected.len(), 18);
let native = Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(file(SOURCE), &mut NoFiles)
.unwrap();
let actual: Vec<_> = native
.events
.iter()
.filter_map(|event| match event {
Event::Message { text, .. } => text.strip_prefix("!pdfmatch:")?.strip_suffix(":end!"),
_ => None,
})
.collect();
assert_eq!(actual, expected);
let fresh = Executor::new(native.state, Limits::default())
.run(file(r"\message{\pdflastmatch0}\end"), &mut NoFiles)
.unwrap();
assert!(
fresh
.events
.iter()
.any(|event| { matches!(event, Event::Message { text, .. } if text == "-1->") })
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_negative_capture_index_is_a_scan_error() {
let error = Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(
file(r"\catcode123=1 \catcode125=2 \message{\pdflastmatch-1}\end"),
&mut NoFiles,
)
.unwrap_err();
assert!(error.message.contains("Bad match number"));
}
#[test]
fn capture_is_restored_after_editing_the_unread_suffix() {
let initial = r"\catcode123=1 \catcode125=2
\edef\status{\pdfmatch{(ab)}{zab}}
\message{original=[\pdflastmatch1]}
\end";
let edited = initial.replace("original", "edited");
let frontier = initial.find("\n\\message").unwrap();
let state = State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit);
let (original, captured) = Executor::new(state.clone(), Limits::default()).run_capturing_entry(
file(initial),
&mut NoFiles,
frontier,
|_| (),
);
original.unwrap();
let (checkpoint, ()) = captured.expect("capture after scanning the match");
let resumed = checkpoint
.resume_after_host_replay(file(&edited), &mut NoFiles, Cancellation::default())
.expect("edited suffix is beyond the checkpoint")
.unwrap();
let full = Executor::new(state, Limits::default())
.run(file(&edited), &mut NoFiles)
.unwrap();
assert_eq!(resumed.events, full.events);
assert!(
resumed
.events
.iter()
.any(|event| matches!(event, Event::Message { text, .. } if text == "edited=[1->ab]"))
);
}
+88
View File
@@ -520,3 +520,91 @@ fn frozen_real_reference_resources_are_read_as_their_actual_bytes_and_versions()
);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn tex_unknown_suffix_lookup_keeps_path_priority_and_format_names() {
let root = directory().canonicalize().unwrap();
let first = root.join("first");
let second = root.join("second");
put(first.join("chapter.fragment"), b"first");
put(second.join("chapter.fragment.tex"), b"later");
put(first.join("style.clo.tex"), b"not a style fallback");
let mut config = WorldConfig::new(&root);
config.paths.insert(
ResourceKind::Tex,
vec![
SearchPath::directory(&first, false),
SearchPath::directory(&second, false),
],
);
let entry = root.join("main.tex");
let mut world = FileWorld::new(config.clone()).unwrap();
assert_eq!(
world
.read_tex_input("chapter.fragment", &entry)
.unwrap()
.data,
b"first"
);
let selected = first.join("chapter.fragment.tex");
put(&selected, b"standard suffix");
let resource = world.read_tex_input("chapter.fragment", &entry).unwrap();
assert_eq!(resource.version.path, selected);
assert_eq!(resource.data, b"standard suffix");
assert_eq!(
world
.read_tex_input_optional("chapter.fragment", &entry)
.unwrap()
.unwrap()
.version
.path,
selected
);
assert_eq!(
world
.read_shared(ResourceKind::Tex, "chapter.fragment", &entry)
.unwrap()
.data
.as_ref(),
b"first"
);
assert_eq!(world.resolve_tex_input("style.clo", &entry).unwrap(), None);
let mut capture = FileWorld::new(config.clone()).unwrap();
capture.capture_inputs();
capture.read_tex_input("chapter.fragment", &entry).unwrap();
let captured = serde_json::to_vec(capture.input_snapshot().as_ref()).unwrap();
config.input_policy = InputPolicy::Project;
let mut old_capture = FileWorld::new(config).unwrap();
old_capture.capture_inputs();
old_capture
.read_tex_input("chapter.fragment", &entry)
.unwrap();
// The original serialization omitted the flag and recorded only the
// supplied spelling for inputs such as chapter.fragment.
let mut previous = serde_json::to_value(old_capture.input_snapshot().as_ref()).unwrap();
previous
.as_object_mut()
.unwrap()
.remove("tex_suffix_fallback");
previous["config"]["input_policy"] = serde_json::json!("Tex");
fs::remove_dir_all(&root).unwrap();
let mut recent = FileWorld::from_snapshot(serde_json::from_slice(&captured).unwrap()).unwrap();
assert_eq!(
recent
.read_tex_input("chapter.fragment", &entry)
.unwrap()
.data,
b"standard suffix"
);
let mut older = FileWorld::from_snapshot(serde_json::from_value(previous).unwrap()).unwrap();
assert_eq!(
older
.read_tex_input("chapter.fragment", &entry)
.unwrap()
.data,
b"first"
);
}
+15 -4
View File
@@ -13,10 +13,21 @@
页面端到端路径排在迭代优先级第一。原样出版模板继续作为兼容性门禁,原语
和排版改动由实际兼容性差异、会话正确性或性能瓶颈驱动。
A3 固定两版各30次逐次交替编辑。第7页实际更新,PDF、SVG及最终 aux 保持
一致,可见 p95 从 4635.0 ms 降到 3379.2 ms。下一步量出发布耗时中同步、
版本复核和替换的分项,验证编辑预览能在当前 revision 受控发布,并缩减
剩余的执行和布局范围。100 ms 的 p95 继续作为正式门禁。
Typst 将实际访问依赖用于判定阶段结果能否复用。TeX 会话在此基础上还要验证
执行前缀的宏、输入游标、分组与页面状态,以及均可重放的文件效果。每次跳过
的工作都用同版本的原生全量结果和真实页面交付验证。
[Typst 上游架构文档](https://github.com/typst/typst/blob/main/docs/dev/architecture.md)
复用上游组件时须测量真实的依赖可追踪性、增量执行范围、取消和字体及文件效果。
Tectonic 的 XeTeX 入口在进程级锁内运行,桥接层能提供输入输出钩子。它可以用来
评估集成与语义对照。若选作实时执行组件,须先以原样项目证明增量恢复和取消。
[Tectonic XeTeX 入口](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/engine_xetex/src/lib.rs#L163-L205)
[Tectonic 桥接层](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/bridge_core/src/lib.rs#L271-L288)
原样 A4 在连续子文件编辑中,取消旧作业的浏览器观测 p95 已低于100 ms。
新编辑到可见页面的 p95 仍高于250 ms。接下来分解编译准备、执行复用和页面
交付,继续按固定预算及逐版本全量一致性验收。
[阶段测量与回执](P2_M1_PROGRESS.md)
## 2026-11-11 总目标重新确认
+540 -2
View File
@@ -220,14 +220,552 @@ SHA-256 为 `2bb2dd465e5a7f1c94f834d305b2405a03efadb2382db5c64cdfc9b151fcfdfc`
发布。集成测试核对 11 种失败路径,包含原序列化字节、原有报告保护、错误
保留及暂存清理。真实 CVPR 大报告的峰值内存还需重新测量。
### 连续编辑的检查点与格式验证
自动续跑在实际执行的新后缀采集检查点。只有当前修订成功发布才更新共享集合。
从较早位置编辑后,下一次可在较晚位置继续。跨位置回归验证 PDF、页面差量、
来源范围、实际资源观察和 aux 与同版本全量一致。原样 A3 与真实 schema25
格式的两轮增量也再次通过独立全量校验。
实际 LaTeX 格式包含45583段流读取校验。格式镜像只复用已验证的同一不可变
字节分配,依然为每一轮解析及记录实际依赖、校验新内容、查询文件日期。
schema27 合并版本通过539项库、工作流和内核回归,零失败。日志
`target/p4-revision-reuse-main/directed.log` 的 SHA-256 为
`b0fb358eced953b0600e7e8cbbe2d65c075b63e64521c8588b1bd9206201dc69`。
同一合并版使用真实 schema27 格式再做原样8页 A3 的两轮续跑与独立全量。
每轮复用794348/870724步、重放61次宿主调用,只替换第7页。PDF、SVG、来源
映射、aux 及日志通过原有门禁。回执 `target/p4-revision-reuse-main/a3-shared.log` 的
SHA-256 为 `eb91a271962e06b1279875538bc2ed0c88256c013b23fb2efd0da271c2f524b5`。
同一 schema27 格式和 A3 在 Edge 交替测量。使用并行同步版作为基线,候选
增加滚动检查点和格式验证复用,每版各做30次正文编辑和30次后页编辑。
每轮实际绘制的变更页、保留的页面节点、PDF 及已绘制 SVG 与另一版一致,
最终 aux 字节一致。延迟按提交字节至浏览器实际应用与绘制统计。
| 编辑范围 | 基线 p50 / p95 | 候选 p50 / p95 |
| --- | ---: | ---: |
| 正文往返编辑 | 2168.2 / 3376.9 ms | 2669.2 / 4694.7 ms |
| 第7页编辑 | 1447.5 / 2950.9 ms | 991.9 / 2308.9 ms |
基线半数后页编辑从前沿24字节开始且复用0步,候选30次均从前沿411字节进入,
复用794263或794342步。正文恢复原文时,基线有15次仍可复用794342步,候选
30次复用0步。结果暴露了滚动集合对往返编辑的旧分支淘汰问题。峰值 RSS
为1027704和1252016 KiB,WSL I/O pressure 运行前后 avg10 为3.66%和19.11%。
候选正文延迟和内存回退,100 ms 与1 GiB 门禁仍待达到。该组未包含随后合入
的续跑断行和事件共享。保留对照并复验有限的旧前缀保留策略。
`target/p4-revision-reuse-main/edge-mixed/run-1/receipt.json` SHA-256
`b1eba07b8dec9a2fba50992c7325edf698d4b347fbdef92b2974ff5a1d0e1861`。
### 续跑断行和已执行事件
自动续跑接回现有断行搜索缓存。编辑一个段落时,后续未改段落可复用求解,
仍按本轮原始节点重新构造量测与来源映射。已完成的事件区间由检查点共享,
统计、错误证据和公开结果保留完整事件顺序。
548项定向回归零失败,原样 A3 的两轮续跑、独立全量、页面差量、SVG、来源
映射、aux 和日志通过。定向日志 `target/p4-suffix-reuse-next/directed.log`
SHA-256 为 `47cb200c753e1f05270fa83f2d0f87d67a58f01292876f326990b2577d83215d`。
A3 日志 SHA-256 为 `99e2e14be446aaa2b8cf823b1f764881a4bdc22fa9f947e0a6a5da2d38cc6fb0`。
下一组浏览器比较需单独测量这两项改动的延迟和内存。
### 往返编辑的检查点保留
早段改动跨过首次发页所依赖的输入时,额外保留此前最多两处有实际发页记录的
检查点。每处保留原有的版本校验和宿主调用序列。后续编辑选取当前输入允许
跳过最多执行步骤的位置。只有真实成功发布才更新这组状态。库和原生工作流
62项定向回归通过。日志 `target/p4-checkpoint-branch-retention/directed.log`
的 SHA-256 为 `f0d36792148fbb208d6880513be9d728451cd6244db02bc943f49170d7961199`。
使用含续跑断行和事件共享的主线作为基线,在同一真实格式和 Edge 上重跑两类
各30次。正文往返编辑从0次复用有效步骤变为29次复用794269或794348步,后页
所有30次仍复用约79.4万步。两端实际变更页、节点保留、PDF、SVG 和最终 aux
一致。
| 编辑范围 | 基线 p50 / p95 | 候选 p50 / p95 |
| --- | ---: | ---: |
| 正文往返编辑 | 3082.8 / 4191.1 ms | 2416.7 / 3859.9 ms |
| 第7页编辑 | 1540.3 / 2090.8 ms | 1341.1 / 2532.9 ms |
峰值 RSS 为1029020和1021868 KiB,均在该语料的1 GiB 门槛内。正文执行阶段
p95 为978.5和193.0 ms。后页端到端 p95 回退,同时该组封存与发布阶段 p95
为1731.6和2180.1 ms。运行前后 WSL I/O pressure avg10 为18.19%和38.52%。
100 ms 门槛仍待达到。回执 `target/p4-checkpoint-branch-retention/edge-mixed/run-1/receipt.json`
SHA-256 为 `81d06fae9f6c1ba2fabb7ef0e3dece25cdeab538c4b41a3ebedd3b9d4db34783`。
### 文件写入期间的页面预览
共享原生编译器在生成真实页面、字体、PDF 和私有写入之后交付可选预览。
编辑器先绘制这次修订的 SVG,成功持久发布后才开放本次 PDF 和来源图。
被替代或发布失败时恢复上一版的页面节点。文件同步和原子安装沿用同一修订
门禁。63项库和原生流程回归通过。日志
`target/p4-provisional-preview/directed-2.log` SHA-256 为
`0f67e839c2eaa46e47885e51a660ed652678fa0f521d87b42f4a1abc1ad29e5b`。
同一个优化程序、真实格式和原样 A3,在 Edge 交替测量。两种交付方式各测
30次正文和30次后页编辑。每次绘制差量、保留节点、PDF、SVG 和最终 aux
一致。候选60轮中,有43轮在浏览器绘制之后仍直接查询到文件发布未完成。
实测文件别名冲突发生在已生成草稿之后,编辑器恢复此前的8个页面节点,
此前实际 PDF、日志和 aux 的字节保持一致。
| 编辑范围 | 文件发布后绘制 p50 / p95 | 文件写入期间绘制 p50 / p95 |
| --- | ---: | ---: |
| 正文往返编辑 | 1936.6 / 3168.7 ms | 1323.5 / 1749.6 ms |
| 第7页编辑 | 1066.2 / 1913.5 ms | 356.2 / 467.9 ms |
服务端峰值 RSS 为1020580和1036312 KiB。文件封存和安装 p95 分别为1579.1
和1676.6 ms,后续修订仍等待前一作业的私有文件和项目锁处理完成。100 ms
端到端门槛仍待达到。WSL 运行前后 I/O pressure avg10 为5.74%和32.43%。
`target/p4-provisional-preview/edge-mixed/run-1/receipt.json` 的 SHA-256 为
`7239cac58838afafe72fdab2f292d48f3893984b1bb4685684e92600508fcb5d`。
同一实现追加原样单页 A1 10pt 的浏览器对照,两版各30次。编辑到可见
p50/p95 由1293.0/2036.9降到309.5/398.8 ms。提前绘制模式在29轮中可在画后
直接观察到文件仍待发布。页面、实际 SVG、PDF、来源版本和映射、最终 aux
一致。服务端峰值 RSS 为617856和618676 KiB。提前绘制模式的准备与执行
p95 分别为105.9和119.7 ms。运行前后 I/O pressure avg10 为11.45%和39.90%。
报告 `target/p4-provisional-preview/edge-a1/run-1/receipt.json` 的 SHA-256
为 `97451f3e4e44209318bcb0892334ad456612955d505c4d51b2fc8df4cce578e9`,100 ms 门槛仍待达到。
浏览器测量后补入草稿 SVG 的页面间取消检查。已经开始的单页完成后重新校验
修订,失效后停止产生更多页面更新。已发布修订的预览保持可读取。63项库和
原生流程回归通过,覆盖真实修订被替代后拒绝再次渲染。日志
`target/p4-cancel-obsolete-svg/directed-2.log` 的 SHA-256 为
`8ee6161e103c8bc3bf1d41f2b4345533c77b1aed88a029cd223b8697427e8ee3`。取消延迟的独立预算还需实际测试。
### 多文件编辑器和原样 A4
测试编辑器可在现有端口参数之后接收相对入口目录的项目文件列表。选择主文件
或子文件编辑时,尚未保存的缓冲区合并为同一个原子项目修订。原有主文件请求
继续可用,未列为可编辑的文件拒绝进入修订。原始输入文件保持同字节。
用实际原样 A4 的 `main.tex` 和 `chapter.tex` 验证两份缓冲区在同一浏览器
帧内修改后都进入同一修订,并逐次核对 `chapter.tex` 实际入读版本与字形
来源。相同优化程序和真实 LaTeX 格式,每种交付方式各做30次主文件正文修改
和30次子文件正文修改。页面、SVG、PDF、当前来源版本和映射、最终 aux
一致。57次提前绘制后仍直接观察到文件待发布。
| 编辑范围 | 文件发布后绘制 p50 / p95 | 文件写入期间绘制 p50 / p95 |
| --- | ---: | ---: |
| 主文件正文 | 888.9 / 1935.3 ms | 261.9 / 293.3 ms |
| 子文件正文 | 1028.8 / 2197.6 ms | 280.5 / 316.1 ms |
服务端峰值 RSS 为629292和629900 KiB。主文件100 ms 和依赖250 ms 的可见
预算仍待达到。独立全量使用同一优化程序、原样格式和最后两份未保存的实际
缓冲区,零复用步骤,得到与热会话逐字节一致的 PDF、SVG、来源版本和映射、
最终 aux。浏览器回执 `target/p4-multifile-editor/edge-a4/run-1/receipt.json`
SHA-256 为 `305fa4b8a1247f5c3683e2434d8b43b7a5b4dfd0256711a37ffd3a220a13ebb3`,独立全量回执 SHA-256 为 `47753c1293eb31fca88d1ac2357dfd50ada6156699b703b3dc1178d87082b4b4`。
### 取消旧作业时释放编译路径
草稿 PDF、日志、aux 和账本的同步只持有私有文件。旧作业取消后释放编译和项目
锁,最多允许两个私有同步作业并存。仍在操作系统中同步的文件由原私有句柄收尾,
文件版本复核和实际安装仍由当前修订控制。受控 A4 实验停在实际文件同步入口,
新版能在放行旧同步前发布后续编辑。两边新版 PDF、SVG、来源映射和 aux 相同,
旧文件在实际同步返回后清理。64 项库和原生流程回归通过。
Edge 在原样 A4 前稿已绘制、文件仍待发布时提交下一次子文件编辑。两版交替,
各取得30次确认取消旧作业的样本,基线补采6次,新版无需补采。取消数值含浏览器
轮询,是观测到的上界。实际 PDF、SVG、来源版本和映射逐次相同,最终 aux 相同。
| 指标 | 基线 p50 / p95 | 新版 p50 / p95 |
| --- | ---: | ---: |
| 浏览器观察到旧作业取消 | 967.9 / 1864.7 ms | 49.7 / 67.8 ms |
| 新请求到编译准备开始 | 907.7 / 1828.0 ms | 14.6 / 21.2 ms |
| 新编辑到页面绘制 | 1317.9 / 2180.7 ms | 318.9 / 410.3 ms |
服务端峰值 RSS 由 647156 KiB 到 647612 KiB,
WSL I/O 压力 some avg10 从2.73%到34.67%。此场景的取消上界 p95 低于100 ms,
后续子文件编辑的可见 p95 仍高于250 ms。独立全量用同一优化程序和最后两份
浏览器缓冲区,零复用步骤,PDF、SVG、来源版本和映射、最终 aux 均相同。
回执和回归日志位于 `target/p4-cancel-private-sync`。自然测试
`rapid-edits-final/run-1/receipt.json` 的 SHA-256 为
`41488e8eabbc45aaced4e5f62721df26ed877d58b21f126ef088a42b7d3431a7`,受控回执
`held-sync/paired-receipt-final.json` 的 SHA-256 为
`50de5a1ea2e3a92d159207c446d76eb70ee8592eee52b67e5d1b4c7d09bf8b4b`,独立全量回执
`full-equivalence/receipt.json` 的 SHA-256 为
`3fd9a702715c6df6200e2eee44ab7748730390a266e9d5db1a264c2dd73d301c`。定向回归
`directed-final.log` 的 SHA-256 为
`90b907c33458cc109effdf696721d9ddc572fbd43f3a1dc05694fb986b49330f`。
### 同一修订中的资源目录索引
对于冻结了文件树的项目,同一编译准备及执行过程中复用同一根目录的索引。
路径在可变文件与受保护文件之间的角色更新时,相关索引重新生成。每次查找
仍按当前生成文件和私有写入状态检验候选文件。70 项资源、快照和原生作业
回归通过。
原样 A4 同一机器、同一原版格式及字体,两版各有30次主文件和30次子文件
的真实 Edge 输入。两版都允许文件同步期间绘制。按每次修订比较执行步数、
复用步数、PDF、SVG 和来源版本与映射,全部相同,最终 aux 相同。独立全量
使用同版优化程序和实际末次未保存缓冲区,零复用步骤,得到相同输出。
| 编辑范围 | 基线准备 p50 / p95 (ms) | 新版准备 p50 / p95 (ms) | 基线绘制 p50 / p95 (ms) | 新版绘制 p50 / p95 (ms) |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 66.7 / 105.5 | 63.9 / 78.1 | 276.7 / 402.9 | 265.6 / 321.0 |
| 子文件正文 | 67.0 / 106.0 | 63.3 / 80.0 | 296.0 / 362.1 | 284.3 / 338.7 |
峰值 RSS 分别为 630020 和 630028 KiB。
WSL I/O 压力 some avg10 从8.19%到20.84%。两类可见延迟均需继续缩短。
`target/p4-project-index-main` 内浏览器回执 `edge-a4/run-1/receipt.json`
SHA-256 为 `b0d0ba06fa38a4b7a2b404be2e5e8a5dddd4256382cc41c3cfa11f299600b654`,独立全量回执
`full-equivalence/receipt.json` SHA-256 为
`ea236e14b3d7e1a3808169d818945dbe7d1f60e94a1717b7cf534328efb8174a`,回归日志
`directed.log` SHA-256 为
`2592b8dfb81a028fc88155e4b421b4e11313ea4beca07b7444ef4560d31280c1`。
### 已存在文件的实际身份检查
在原样 A4 采样24次子文件热编辑,1149个 CPU 样本中有272个位于 `readlink`。
Unix 的别名检查直接比较实际设备号和 inode,覆盖硬链接和通过符号链接访问
同一文件。其他读失败仍可走原路径解析。别名结果和观测到的文件身份继续
进入宿主记录。64 项库及原生流程回归通过,包含输出保护和实际链接冲突。
同一原样 A4、真实格式和字体,Edge 两版交替执行各30次主文件正文和30次
子文件正文编辑。每次执行和复用步数、PDF、SVG、来源版本和映射相同,最终
aux 相同。新版与同二进制零复用独立全量的最后两份实际缓冲区输出一致。
| 编辑范围 | 基线准备 p50 / p95 (ms) | 新版准备 p50 / p95 (ms) | 基线绘制 p50 / p95 (ms) | 新版绘制 p50 / p95 (ms) |
| --- | ---: | ---: | ---: | ---: |
| 主文件正文 | 64.5 / 74.3 | 17.8 / 20.9 | 265.3 / 321.3 | 205.5 / 238.7 |
| 子文件正文 | 64.1 / 82.4 | 18.1 / 26.8 | 285.8 / 358.3 | 225.8 / 283.7 |
峰值 RSS 为630356和625576 KiB,WSL I/O 压力 some avg10 从13.04%到
45.68%。两类可见延迟仍高于各自预算。浏览器回执
`target/p4-host-file-identity/edge-a4/run-1/receipt.json` 的 SHA-256 为
`c9ba2faafb2ac1c6387d5051ab7ae41489119c783258328431fcf9d91240f7a6`。独立全量回执 `full-equivalence/receipt.json`
SHA-256 为 `40fde3f64d7209d55a5442c49db6203a2cf99845936ef3342d0b58b758176e42`。定向回归 `directed.log` SHA-256 为
`776ccb6f9b7ec83e1044be715100bc38d2b6dc681ff5e51b1ec341189674cf5d`。CPU 采样明细
`target/p4-warm-cpu-profile/original-a4/symbolized.json` SHA-256 为
`b7b48e1be44de33c531279628d244dcd2a71814ad3dbfb9f9377e6ff64aa7e48`。
### 共享断字模式与已验证的末态指纹
格式和各编辑检查点共享只读字典树。INITEX 插入模式时复制并更新实际节点,
当前断字统计随树版本重新计算。格式编码和原有完整指纹保留。自动恢复结束
后,只有完整状态与会话前一份成功执行相等才复用其指纹,否则重新计算。
比较包含宏参数、分组、来源跨度和真实寄存器。560 项定向回归通过。
原样 A4 在 Edge 上两轮交替比较,每轮各版本30次主文件和30次子文件编辑。
真实格式、字体、执行和复用步数相同,每个对应修订的 PDF、SVG、来源版本
及映射相同,最终 aux 相同。用同版二进制最后两份浏览器缓冲区独立全量,
得到同样输出,零复用步骤。
| 轮次 | 编辑 | 基线执行 p50 / p95 (ms) | 新版执行 p50 / p95 (ms) | 基线绘制 p50 / p95 (ms) | 新版绘制 p50 / p95 (ms) |
| ---: | --- | ---: | ---: | ---: | ---: |
| 1 | 主文件 | 85.2 / 118.2 | 81.6 / 110.4 | 211.2 / 273.5 | 211.4 / 256.1 |
| 1 | 子文件 | 105.4 / 147.4 | 59.8 / 90.2 | 228.2 / 308.5 | 188.3 / 251.1 |
| 2 | 主文件 | 83.1 / 102.8 | 84.3 / 141.0 | 209.1 / 259.9 | 206.9 / 268.9 |
| 2 | 子文件 | 105.7 / 136.4 | 60.5 / 87.6 | 226.0 / 277.3 | 184.1 / 220.5 |
两轮服务端峰值 RSS 分别由625832降至591780 KiB、由625860降至591332 KiB。
第一轮子文件可见 p95 略超250 ms,第二轮低于门限。主文件100 ms门限仍未
达到,第二轮主文件可见 p95 比当轮基线增加9.0 ms。两轮 WSL I/O 压力 some
avg10 起止分别为15.85%与47.50%、7.56%与60.70%。
复测给各浏览器配置足够的资源记录容量。每条响应记录均落在对应编辑的
时间窗口。新版子文件从收完响应至浏览器确认绘制的 p50 为
29.3 ms,响应体传输 p50 为 0.8 ms。
从发送请求至响应头的时间扣除服务端排队和准备到就绪,剩余 p50 为
49.2 ms,包含连接两端的剩余开销。
浏览器回执位于 `target/p4-shared-patterns/edge-a4`,`run-1/receipt.json`
SHA-256 为 `56724948c13ad54bdfef4d095b7f78025e35dbf24ed5d2f20ab88cf98bb8ad69`,
`run-2/receipt.json` SHA-256 为
`0bf8d4b09eb9e52e23739bef7e2c999607bf890395e9461bf50e59df6927bbfd`。独立全量回执 `full-equivalence/receipt.json`
SHA-256 为 `287bb542d9da1429fe0aa0134490b0c65485c4433026eb988e4de8f6d41c7b35`。定向回归 `directed.log` SHA-256
为 `6ddbccc5481fb4ff752db594bf5da54a0cffda152741197d745161c536317bd1`。
### 原样 A4 编辑的传输与执行分解
同一个优化程序和原样 A4,两轮交替比较普通套接字和启用 `TCP_NODELAY` 的
套接字。每轮每组各30次主和子文件真实 Edge 输入,逐条验证输出与实际
设置调用。第二轮通过连接标识核对浏览器请求与 Linux 进程收发头部的记录。
扣掉排队与实际编译就绪时间后,Linux 进程内响应残差 p50 为
0.89–0.93 ms,Linux 进程外两段合计 p50 为
49.3–51.4 ms。两种套接字设置下的残差接近。
进程外合计消去固定的两端时钟偏移,覆盖浏览器及 WSL 的实际转发和调度。
回执 `target/p4-preview-network/decomposition-receipt.json` SHA-256 为
`ccc822bb92ade8196130faf0afb62efece58d24541ea4d0e0946d1c9152ac898`。
另对主文件采样24次热编辑。684个 CPU 样本中185个在 SipHash,30个在
宏替换列表的 hash。准备和实际执行 p50 分别为
16.3 和 79.7 ms。
CPU 采样独立于浏览器延迟验收,明细保存在
`target/p4-warm-cpu-profile-main/original-a4/symbolized.json`,
SHA-256 为 `fa098bc394fb0247977e1393572759cada44513f86efc801d0c40e13979e5e12`。
### 原样 A4 的断字指纹与整状态哈希
隔离候选只缓存共享断字节点的有序哈希字节。格式序列化保留原结构,
写入实际模式时使缓存失效。487 项断字、格式、内核测试通过。
真实 schema27 含 29385 个节点,捕获字节916552。独立哈希探针在60个
前缀和尾部组合下值完全相同,p50 为3.355 → 0.221 ms。
`target/p4-hyphenation-hash-stream/real-trie-v2-receipt.json` 的 SHA-256 为
`7af2f1c66acad5a8bfb3df03d8f863afcc6552956ca734f6ff9b7f85b3d3bead`。
原样 A4、真实字体和格式在 Edge 两轮交替对照,每轮每版各做30次主文件、
30次子文件编辑。第二轮对调首测顺序并固定 TeX 日期寄存器。
各次真实执行、复用步数、PDF、SVG、来源映射和最终 aux 一致。
用第一轮最后两份编辑缓冲区独立全量、零复用,与当次增量输出一致。
| 轮次及范围 | 可见 p50 / p95 基线 (ms) | 可见 p50 / p95 候选 (ms) |
| --- | ---: | ---: |
| 第1轮主文件 | 200.2 / 237.7 | 204.5 / 239.1 |
| 第1轮子文件 | 179.4 / 234.6 | 187.8 / 238.3 |
| 第2轮主文件 | 209.7 / 276.4 | 207.5 / 261.7 |
| 第2轮子文件 | 189.5 / 235.6 | 186.9 / 212.4 |
两轮峰值 RSS 基线591908、592112 KiB,候选593680、593432 KiB。
两轮延迟改善方向相反,候选保留在隔离工作区。原始回执
`edge-a4/run-1/receipt.json`、`edge-a4/run-2/receipt.json`、
`full-equivalence/receipt.json` 的 SHA-256 依次为
`fc931354984478d599cbb2688a038b32b8816f85808f7d874b33516db686a93e`、
`13540569618c59002c6ca331658bbb32e3cf66f1aa3f6cfa3374d39b39e53411`、
`c174b5128ffd31d07bc7bef351cfb602b9ef847378ca45e6b601c01a6149677c`。
实际 CLI 故障探针用相同格式和 A4 在同一故障位置记录完整进出指纹。
首次对照的日期寄存器分钟不同,冻结 `SOURCE_DATE_EPOCH` 并设置
`FORCE_SOURCE_DATE=1` 后,二者指纹和执行544561步完全一致。可见证据
`fingerprints-frozen/receipt.json`、首次比较差异 `fingerprints.log` 和
两次原始失败报告均保存在同一阶段目录。
另用真实 schema27 的完整解码状态测量合并短哈希写入。该独立探针链接
断字缓存候选的内核,对每组60次哈希核对完整值。原 p50 57.075 ms,
4 KiB 写入缓冲为31.747 ms,16 KiB 为30.834 ms。这个测试只测哈希。
`real-state-buffer-receipt.json` 的 SHA-256 为
`617826bcda930d75840bb06db219c4206431ef85ac7a5d1ffc159fb8cfe62634`。
下一候选独立从主线对完整指纹启用 4 KiB 缓冲,已进入真实编译验证。
[Rust 标准库所用 SipHash 写入](https://github.com/rust-lang/rust/blob/58cf8f9c3/library/core/src/hash/sip.rs#L227-L283)
### 完整状态指纹的短写入合并
主线对完整状态指纹使用4 KiB 缓冲,按原次序把同一状态哈希的短写入成批
交给 `DefaultHasher`。491 项定向测试通过,包含跨缓冲边界的大控制序列、
Unicode、分组、实际断字与格式加载。真实 schema27 完整状态在60个不同
作业分钟下逐一核对原哈希值,直接计算 p50 63.741 ms,缓冲37.272 ms。
这是独立内核探针。与构建重叠的第一份结果另存。
`target/p4-buffered-state-fingerprint/probe-integrated-receipt.json`
SHA-256 为 `6cf8c48c17910dd959859cf80883ddbfdda46d3ce3ad8d4be71f9213524bb0fc`。
真实 CLI 在固定同一 TeX 时钟和故障位置时,实际进出指纹及544561步
执行完全与旧版一致。`fingerprints-frozen/receipt.json` 的 SHA-256 为
`5bf935fe1ce88529e0c40033cb211659d57c5fb7e1e0bd85bc7d84460ddf1a28`。
同一真实格式、字体和原样 A4,Edge 两轮每版各30次主文件和30次子文件。
第一轮沿用往返编辑,第二轮每份文件用30个独立正文版本并倒换首测次序。
每轮的实际执行和复用步数、PDF、实际绘制的 SVG、来源映射和最终 aux
两版一致。每轮最后两份编辑缓冲区用同候选另开零复用编译,各自重现
独立 A4 输出。
| 编辑范围 | 基线可见 p50 / p95 (ms) | 缓冲可见 p50 / p95 (ms) |
| --- | ---: | ---: |
| 往返主文件 | 207.3 / 354.2 | 186.7 / 241.9 |
| 往返子文件 | 187.0 / 214.7 | 185.3 / 216.1 |
| 不同正文主文件 | 227.3 / 293.9 | 208.6 / 236.0 |
| 不同正文子文件 | 188.4 / 237.1 | 195.2 / 234.8 |
主文件实际执行 p50 分别从79.8到62.3 ms、99.0到79.4 ms,两轮配对
可见中位数改善18.4和23.8 ms。子文件尚无稳定改善。
峰值 RSS 两轮分别为591744 → 592140、603140 → 603316 KiB。
不同正文的候选版进一步分解了时延。主文件与子文件的准备 p50 分别为
17.5和17.7 ms,内核就绪为114.4和94.4 ms。浏览器请求到响应扣除就绪与
排队后,残差 p50 分别为51.2和51.4 ms。响应结束到观测到实际绘制含
SVG 解码,p50 为31.9和34.9 ms。各分布独立统计。
`distinct-edit-path.json` 的 SHA-256 为
`2bcf7b91d7ccbd5eb4eaf6eea8ed641652eee8c189bd0624ec1f2e91793ca8e5`。
当前 A4 p95 仍高于100 ms。
同一补丁完成全工作区复验,1625 项通过、零失败,两项带独立格式和目录
的原样 A3 也手动复验通过。共享测试两轮均复用794348/870724步、重放61次
宿主调用,只替换第7页。手动探针均复用770678/870728步、重放59次,
两轮独立全量的8页、PDF、SVG、来源映射、aux 与日志一致。
`workspace.log`、`a3-shared/test.log`、`a3-manual/test.log` 的 SHA-256 为
`286e0991ce3224b65b09ff3b020d9ad9a3847dbe4c03b7748604040ec705f089`、
`f7856181fbec9b8390ccb6ad254b763580f5addf51e98fa5a33b4200a8d7442e`、
`e45cb607aa2f2e3a247e3847b6336b9b523243e0db06e787fef36c5209878dc7`。
同一正式优化二进制的14项原样复验详见[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。
| 回执(均在 `target/p4-buffered-state-fingerprint`) | SHA-256 |
| --- | --- |
| `directed.log` | `e1bfdab3060a8b3a54818464c4a85163ee34acc6202b7e0a427a6706ce145244` |
| `edge-a4/run-1/receipt.json` | `3683486916211d28bf817784a56bec59a1106cba06159c95b77f55d3be2781e9` |
| `edge-a4/run-2/receipt.json` | `079d96c6ef170ebb01dc1057034060b2bec245331d983b8bdec534a796e9abc7` |
| `full-equivalence/receipt.json` | `c5e64db6cbe03ad7bce9b3739fd74757ca2f90efeb12549226aee4f37983cf1d` |
| `full-equivalence-distinct/receipt.json` | `b7fbd4cfafe8a9f972887cf3e905b7e5da96c838dd0c8f8c63159af64952643c` |
### 主线热编辑的文件身份开销和正则运行边界
对缓冲指纹已进入主线的优化版,使用真实 A4 和旧格式采集24次主文件
编辑。587个 CPU 样本中,`statx` 63,SipHash 写入54,SHA-256 44,
宏替换序列的哈希38。真实准备和执行 p50 为16.107和60.956 ms。
原始报告 `target/p4-buffered-warm-profile/original-a4/symbolized.json`
SHA-256 为 `ae44671f7d0cee93ab3a32008ec4ef82ec52ef61020be6ecd3eac1d8512b5b72`。
另一次相同范围用调用栈核对实际 `statx`,61992次中61296次来自
`HostPreparation::same_file`,该组调用在24次编辑共耗时242 ms。
堆栈主要是准备阶段保护已读资源和生成输出,以及运行中读取、关闭
并登记实际资源时检查别名。探针报告
`target/p4-live-statx/original-a4/statx-summary.json` SHA-256 为
`1096f50bca0c9c4ad01b8f592216f794e8d73db1a9776732faff533404b07dde`。
当前隔离候选在单次 Unix 别名扫描内共用固定目标的身份观察,阴性
扫描结束前重查目标,发生替换时重新按实时路径逐对核验。
旧隔离 schema30 的 GNU 正则在原样 arXiv、ACL、NeurIPS 到达原字符
悬挂诊断前各调用55次编译和匹配。每份的两项调用合计约3.19、4.74和
5.22 ms。最大模式80字节,输入分别2、5、2字节。数值只覆盖此模板前缀。
在另一份使用同一 GNU 实现的旧内核中,用探针在实际匹配入口暂缓调用,
取消后100.190 ms仍未返回,放行后报告真实取消。它验证调用内部的控制
边界,正常模式开销由前一组真实模板观测。两个回执都在
`target/p3-pdfmatch-runtime-audit`,分别为 `publisher/receipt.json` 与
`gated-cancel.json`。SHA-256 为
`b1da8b6e1075555f9fe3a7d88590563d36c71e513c79719442d1ac29fb083bd3`、
`a8fe144b2d2beed5efdb7ae0204de4faa6f0404efab474ea2d702925a17a9a88`。
[TeX Live 正则实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/utils.c#L762-L852)
[GNU C 库匹配接口](https://sourceware.org/glibc/manual/latest/html_node/Matching-POSIX-Regexps.html)
### 单次 Unix 别名扫描共用固定目标的身份
固定路径的设备与 inode 观察只在同一轮扫描内共用。没有发现冲突时,
返回前重查固定路径,观察发生变化则用实时逐对比较重跑。真实单元测试
在检查两条候选之间,把固定路径原子替换为指向应保护文件的硬链接,
检查仍发现冲突。定向通过65项,包含已存在的硬链接、保护路径、生成
文件、实际错误和取消。实际项目的新一轮扫描重新获取身份。
在同样的24次真实主文件编辑中,`statx` 调用 61992 → 32664,其中
别名检查 61296 → 31968,别名查询本身合计 242.1 → 134.0 ms。
候选调用栈在 `target/p4-alias-scan-identity/statx/original-a4/statx-summary.json`,
SHA-256 为 `d2fa1a80f378445e1dccc29378cfc1546d94e823a49f460bffda827ba5790b0d`。
两轮 Edge 各做每版30次主文件和30次子文件编辑。第一轮每文件的正文
版本都不同,第二轮是往返编辑,调整首测顺序。每轮同格式、字体与
输入版本,两版的实际执行和复用步数、PDF、SVG、来源映射、最终 aux
对齐。两轮最后的编辑缓冲区用同版本另开零复用全量,各自输出一致。
| 场景 | 准备 p50 基线 → 候选 (ms) | 可见 p95 基线 → 候选 (ms) |
| --- | ---: | ---: |
| 不同正文主文件 | 17.8 → 13.3 | 219.2 → 224.0 |
| 不同正文子文件 | 18.6 → 13.3 | 293.3 → 205.0 |
| 往返主文件 | 17.2 → 13.6 | 209.5 → 208.6 |
| 往返子文件 | 17.0 → 13.2 | 210.5 → 244.5 |
准备耗时改善复现,两轮可见 p95 的方向有变化,100 ms端到端目标仍待
达到。峰值 RSS 在两轮分别从603280降到601528、591968降到590028 KiB。
两个浏览器报告 `edge-a4/run-{1,2}/receipt.json` SHA-256 为
`dec5ad9d3d48960147a3d2957a1061e9625d7f032841acc927463d3cab0db1eb`、
`5a4b5d454d06bf1313af37f61231935e9bf6a17a0a2d64a39cd10a1256119a80`。
真实 A3 手动和共享编译器两项也已通过,共享续跑仍只更新第7页。
回执 `a3-shared/test.log` 与 `a3-manual/test.log` SHA-256 为
`34fd27652fb0afb59deaee5b68c0dcede8bd2d8e38460746031f134d698683f6`、
`f4c65f08d98a2c15544dde3f3bd82cc57f7f139fbd50782541a04e65cc407d03`。
完整工作区和原样模板复验在同一补丁上运行。
为验证可停止的匹配方式,用 GNU 正则子进程独立测量管道往返。6个对照
覆盖最长选择、反向引用、字节位置、大小写、无匹配和模式错误。60次
短模式往返 p50 0.246 ms,p95 0.372 ms。受控阻塞时,终止并回收 worker
耗时1.360 ms,旧作业未产生匹配答复,随后新的 helper 返回实际匹配。
`target/p3-pdfmatch-worker-probe/receipt.json` 的 SHA-256 为
`492bd9a411e6547b41bf294061e45c8c79567107e4f8d959e92a2843a5cf170a`。
目前只完成独立进程探针,编译会话接线仍待验收。
### TeX 输入的默认扩展名候选
默认 TeX 编译在每个搜索目录中为带未知后缀的输入先试附加 `.tex`,并保留
已识别后缀及目录优先级。实际 `\input`、`\openin` 与 `\pdffilesize`
共用候选,通用宿主资源和格式镜像沿用各自的原解析。捕获显式保存所用规则,
旧输入快照继续按其原候选轨迹严格重放。74项定向测试通过,覆盖原生作业、
格式、项目、源快照和旧的活动文件别名回归。
[Kpathsea 默认候选顺序](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/kpathsea/tex-file.c#L999-L1038)
同一原样 `lipsum` 和未知后缀冲突样例分别由 pdfTeX、旧原生和新版独立编译。
新版实际读入 TeX Live 的 `lipsum.ltd.tex`,两个用例生成 PDF 且词序分别与
pdfTeX 一致。旧原生在 `lipsum.ltd` 缺失处停止。回执
`target/p3-tex-suffix-search/reference-jobs-v3/receipt.json` SHA-256 为
`5a2887155491071aea7d66e12d4938b0a8b99be44790a41b47487f4a6f708eed`。回归 `directed-v3.log` 的 SHA-256 为
`543f11b7e406963bac3ca3f7f03eeadfc988856314b58ad1db8edb7d628f07d2`。首轮全工作区在通用活动文件别名重放发现未捕获的扩展候选,
修订版保持原接口及该用例。首轮全工作区日志和第二版真实包加载诊断均保留。
同一原样 A4 和旧实际格式,两版各交替做30次主文件与30次子文件编辑。逐轮
执行与复用步数、PDF、SVG、来源版本及映射一致,最后 aux 相同。用新版和
最后两份真实编辑缓冲区独立全量,零复用步骤,产生相同输出。
| 编辑范围 | 基线可见 p50 / p95 (ms) | 新版可见 p50 / p95 (ms) |
| --- | ---: | ---: |
| 主文件正文 | 212.7 / 271.5 | 219.8 / 286.8 |
| 子文件正文 | 199.9 / 256.6 | 191.2 / 221.4 |
峰值 RSS 分别为 591964 和 591972 KiB。
浏览器回执 `target/p3-tex-suffix-search/edge-a4/run-1/receipt.json`
SHA-256 为 `3f65e945629d6da49af4ee59ef0fe7285e3dde5e98b46397b069b8756943d8b8`。独立全量回执 `full-equivalence/receipt.json`
SHA-256 为 `ca8cc3879c21de6369230b14c51ac3435fd9bb8b6fc0b73f795b7f49ae100858`。
最终后缀实现以同一源码完成全工作区复验,1624 项通过、零失败,
两项真实 A3 续跑按测试标记需单独提供格式和工作目录。日志
`target/p3-tex-suffix-search/workspace-v3.log` 的 SHA-256 为
`f948262b43a7c35a21b7963355ab76740722573e6a4d2a8a60076ffa6a35e7c0`。
### 原样 A3 再次核对编辑到页面结果
手动启用真实 schema27 格式的 A3 共享编译器测试,原样8页工程连续两次编辑。
每次从字节411恢复,复用794348/870724步,重放61次宿主调用,只替换第7页。
两轮执行和资源观察、PDF、SVG、来源映射、aux 和日志均与各自同版本独立
全量编译一致。日志 `target/p3-tex-suffix-search/a3-shared-v3/test.log`
SHA-256 为 `b4ca36451506b9ba26787507e329d0287006ac6d232a3470cf1ad74b2fa686d0`。
此处验证实际复用和页面更新的正确性。延迟门禁沿用独立浏览器观测。
单独运行的手动探针从编辑行开头选择恢复点。原先从411减1200并截为0,
过早选择检查点,未通过至少复用100000步的检查。旧失败日志
`a3-manual-v3/test.log` SHA-256 为
`4e96eb58a1216c66d149556da3fa8412c6e3c7a5f66de93b722803efb485a45e`。
修正后实际在字节411捕获,复用770678/870728步并重放59次宿主调用。
两轮后缀各执行100046步,8页、执行与资源观察、PDF、SVG、来源映射、
aux 和日志均与独立全量一致。`a3-manual-frontier/test.log` 的 SHA-256 为
`2439c362b98e9c65a166d3eb70333d9179d3e75a478c40b570a36e01759f9e93`。
两份日志均在 `target/p3-tex-suffix-search`。
### 正则捕获的检查点与字符悬挂参考
在主线 `ee22f25` 基础上复用已验证的 POSIX 正则组件,独立组合
`\pdfmatch`、`\pdflastmatch` 与 TeX 默认后缀查找。捕获字节及其位置随
同一作业的执行检查点续跑,新作业清空捕获内容。原生候选按真实 pdfTeX
的18个匹配观察对照,并在读过匹配表达式后编辑未读后缀,核对恢复执行
与全量的完整事件序列。格式、后缀、项目资源及匹配共17项定向测试通过。
候选仍限 GNU/Linux,正则调用的内部取消与端到端延迟需单独验证。
`target/p3-pdf-match-with-input/{candidate.patch,directed.log}` 的 SHA-256
分别为 `cc3ca430c91b09e7aa8e49f39c3e4f0b687c80f7ed47af0974ec03c3923813ff`
和 `e73f75e9b0084ea4eaec4ba82dc1fb8a1f93295708eca0769d5a87058114a692`。
[TeX Live 的匹配及捕获实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/utils.c#L762-L852)
已用真实 pdfTeX 1.40.29 固定两个字符悬挂探针。相同的文字和行宽在
`\pdfprotrudechars` 为 0、1、2 时分别为 2、2、1 行。第一个词的
可见横坐标为 72.000、70.755、70.755 PDF 点。级别1与2均输出实际左右
边缘 kern,级别2同时将其计入断行候选。从组内给特定字体设置
`\lpcode`、`\rpcode` 后,两值按 ±1000 截断并保留至组外,
`\pdfprotrudechars` 恢复原值,另一字号的同字体仍有独立的代码。
在 10 和 20 pt 两个字号上读取实际边缘 kern,验证字距随字体 quad
变化,`\unhcopy` 后边缘 kern 消失。续跑版应对同一编辑版本核对
断行、实际字形坐标、节点和来源位置。对照源、日志、PDF、词框及
指纹见 `target/p3-microtype-margin-reference/receipt.json`,
SHA-256 为 `6cfc2cacdf17cc1486b5c72708d63c0dd7c7b8f2dd9375df1e04a31f46ad3d88`。
[pdfTeX 字体边缘度量](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L19387-L19431)
[pdfTeX 断行候选处理](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L23356-L23370)
以组合候选新建 schema30,并原样复跑 arXiv、ACL、NeurIPS、
Springer Nature、Elsevier CAS 双栏和 IEEE Transactions。arXiv 实际读入
发行版 `lipsum.ltd.tex`,与两份会议样稿同在字符悬挂处停止。参考端六份
均生成 PDF 并收敛。原生 Springer Nature 和 IEEE Transactions 两项
生成 PDF 并收敛。各自词框、灰度图、字体、aux 和首处诊断见
[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。
### schema27 与主线兼容性
合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。
按483项源码和测试指纹核对的工作区回归通过1617项,零失败。日志
`target/p3-schema27-main-reconcile/workspace.log` 的 SHA-256 为
`561766e409640fa3d407a365b4e3e88885bcc2a7e7f9bfc49f680ad92b7370f4`。
独立 schema27 候选已使用真实 LaTeX 格式通过七份原样 article 的21轮 PDF 及
版面对照,合并后的优化构建将单独复验。
主线合并版本的优化程序以原版 LaTeX 启动新建真实 schema27 格式,复验
七份原样 article 的21轮。参考页数、字体、词框、墨迹、原始字形和规则坐标、
aux 和引用全部通过。回执
`target/p3-schema27-main-reconcile/release-articles/native-article-audit.json`
SHA-256 为 `ce9abcee0891dd6b466ac1cc6b2d4fd3b8dbb575aa34f2a628279abc049fc1cf`。
### schema25 主干验收
+111 -1
View File
@@ -12,13 +12,16 @@
| 期刊双栏 | Elsevier `cas-dc-sample.tex` | [Elsevier CAS 发布包](https://ctan.org/pkg/els-cas-templates) |
| 期刊双栏 | IEEE Transactions `bare_jrnl.tex` | [IEEEtran 发布包](https://ctan.org/pkg/ieeetran) |
| 期刊双栏 | APS REVTeX `apssamp.tex`(reprint) | [APS REVTeX](https://journals.aps.org/revtex) |
| 期刊单栏 | ACM `acmsmall.tex` | [ACM acmart 官方发布](https://ctan.org/pkg/acmart) |
| 期刊双栏 | ACM Transactions on Graphics `acmtog.tex` | [ACM acmart 官方发布](https://ctan.org/pkg/acmart) |
| 会议 | ACM `sigconf.tex` | [ACM acmart 官方发布](https://ctan.org/pkg/acmart) |
| 会议 | Springer LNCS `samplepaper.tex` | [LNCS 作者与编辑指南](https://link.springer.com/series/558/information-for-authors-and-editors) |
| 会议 | IEEE `bare_conf.tex` | [IEEE 会议模板指南](https://conferences.ieeeauthorcenter.ieee.org/write-your-paper/authoring-tools-and-templates/) |
| 会议 | ACL `acl_latex.tex` | [ACL 官方源码](https://github.com/acl-org/acl-style-files) |
| 会议 | CVPR 2026 `main.tex` | [CVPR 官方发布包](https://github.com/cvpr-org/author-kit/releases) |
| 会议 | NeurIPS 2025 `neurips_2025.tex` | [NeurIPS 官方样式包](https://media.neurips.cc/Conferences/NeurIPS2025/Styles.zip) |
从 `scripts/publisher-template-matrix.json` 中的地址取得八个原始压缩包,按键名存为
从 `scripts/publisher-template-matrix.json` 中的地址取得所选样例的原始压缩包,按键名存为
`<键名>.zip`。`scripts/probe-publisher-templates.py` 会校验包的 SHA-256,独立复制
源文件树,用固定参考格式和指定原生格式执行。它保留每轮命令、错误、aux 版本、
字体、页面与词框。需要 BibTeX 时,两端都从实际作业生成的 aux 独立运行。
@@ -311,6 +314,113 @@ NeurIPS 2025 官方包已固定 SHA-256 并进入矩阵。首轮参考和原生
无未定义引用,原生推进到 `microtype.cfg:70` 缺少 `\pdfmatch`。
复跑报告 SHA-256 为 `0718bc2b7d5fbc561c0e53ac8277d140d82045d3649e28de5b21861afb6c1991`。
以官方 firstaid 和原版启动文件新建 schema27 格式后,CVPR 2026 原样复验
再次完成五轮 LaTeX 和一次 BibTeX。同名 `main` 作业两端各5页,引用和
aux 都收敛,嵌入字体相同。词序、灰度图和最终 aux 字节仍有差异。版面对照
`target/p3-macro-par-delimiter/release-cvpr/matrix/pdf-fidelity/report.json` 的
SHA-256 为 `7184b2901abd49deb0439a7ea8a5e39ad302ee9663aaa07b43ace697bd74ec5b`。
隔离 schema29 的通用 `\pdfmatch` 候选按真实 pdfTeX 对照通过23项定向测试。
用新建格式分别复验原样 arXiv、ACL 和 NeurIPS。三份参考均完成,原生均已
越过原 `\pdfmatch` 停止处。ACL 和 NeurIPS 的首处诊断是未定义
`\MT@protrudechars`。arXiv 首处诊断为未找到 `lipsum.ltd`,同环境的
`kpsewhich -format=tex lipsum.ltd` 实际返回原版 `lipsum.ltd.tex`。
总报告 `target/p3-pdf-match-native/release-microtype/matrix/report.json` 的
SHA-256 为 `6a29764fe8e66fe7899a2ce1c0ca3639e5cc018974d53e0b0a291c2afdcba7b9`。
这些结果仍需主干合并后复验。
主线另以原版 `lipsum` 的独立 article 用例复现并验证了 `lipsum.ltd` 的查找。
TeX 输入与 LaTeX3 使用的 `\pdffilesize` 实际读入发行版 `lipsum.ltd.tex`。
输出 PDF 的文字顺序与 pdfTeX 一致。[后缀查找阶段证据](P2_M1_PROGRESS.md)
在 `ee22f25` 上将后缀处理与正则组件组合,使用发行版原样启动文件
新建 schema30,复跑原样 arXiv、ACL 和 NeurIPS。重新核验两次所选归档、
输入、参考格式、字体映射和覆盖层,参考端三份的词框和每轮 aux 完全一致,
分别生成 3、4、12 页。组合候选实际读取发行版 `lipsum.ltd.tex`,arXiv、
ACL 和 NeurIPS 原生首处诊断均为 `\MT@protrudechars`,分别位于
`template.tex:93`、`acl_latex.tex:107` 和 `neurips_2025.tex:103`。
三份原生 PDF 仍待字符悬挂及后续行为完成。
回执 `target/p3-pdf-match-with-input/publisher/verification.json` 的 SHA-256 为
`d32b74a4a730e533909c350b3aa08fbad229793c526123f2bd1e776bf7e102b9`。
同一组合候选和实际格式另跑三项官方期刊,参考端均完成且 aux 收敛。
| 项目 | 原生结果 | 与参考对照 |
| --- | --- | --- |
| Springer Nature | 12 页,aux 收敛 | 每页词序和嵌入字体名称相同,词框最大差 12 bp,灰度图和最终 aux 仍有差异 |
| Elsevier CAS 双栏 | 在 `cas-dc-sample.tex:441` 停止 | 到达原生宏展开嵌套上限,参考为 6 页 |
| IEEE Transactions 双栏 starter | 1 页,aux 收敛 | 词序、词框、嵌入字体名称、144 DPI 灰度图及最终 aux 一致 |
报告 `target/p3-pdf-match-with-input/journals/report.json` 的 SHA-256 为
`b63d10941f07ac0aaa1d78ee28b2452766760c9613f7be8777a97ca96cff6dfa`。
独立版面对照 `journals/fidelity.json` 的 SHA-256 为
`baedb018d7a678a6da1072b35ad1cda3f4d39a26ef0b54256bc375b4e6a96e49`。
### 主线完整状态指纹缓冲后的原样复验
用主线 `10a08c4` 的同一优化程序覆盖14项期刊、双栏期刊、会议和 arXiv。
先用保留的 schema27 格式和既有出版环境完整运行。NeurIPS 缺
`trimspaces.sty`,ACM 三项缺元数据支持,两端均触发。再用相同启动源和
已验证的官方 firstaid 新建 schema27,分别按之前记录的官方依赖与字体
映射复跑这四项。两次选中输入逐项相同,四份参考的页数和每轮 aux
与各自的既有基线相同。合并核对后,参考端14份全部生成 PDF、aux
收敛,且无未定义引用告警。
| 样稿 | 主线结果 | 实际对照 |
| --- | --- | --- |
| Springer Nature | 12 页,aux 收敛 | 每页词序和嵌入字体名相同,最大词框差12 bp,灰度图及最终 aux 有差异 |
| IEEE Transactions 双栏 starter、IEEE Conference starter | 各1页,aux 收敛 | 词序、词框、嵌入字体名、144 DPI 灰度图、最终 aux 一致 |
| Springer LNCS | 3 页,aux 收敛 | 每页词序、嵌入字体名和最终 aux 一致,最大词框差0.009963 bp,灰度图存在差异 |
| CVPR 2026 | 5 页,aux 收敛 | 嵌入字体名相同,词序、灰度图、最终 aux 有差异 |
| arXiv、ACL、NeurIPS | 起始停止 | 缺 `\pdfmatch` |
| Elsevier CAS 单栏和双栏 | 起始停止 | 宏展开嵌套上限 |
| APS REVTeX 双栏 | 起始停止 | 缺 `\accent` |
| ACM 单栏、双栏及会议 | 起始停止 | PDF 颜色程序尚不支持相关操作 |
`target/p4-buffered-state-fingerprint/publisher-matrix/report.json` SHA-256
为 `bb849b239663a2d52610517f21c76ef40264973777ea5770fb5e56d7565950c5`。
实际版面对照 `publisher-matrix/fidelity.json` SHA-256 为
`fa048dbe120918d1835b5821cdc849ded35217cf56115ddfa2b263264fbfa576`。
四项复跑及分范围合并回执 `publisher-followup/receipt.json` 的 SHA-256 为
`65ee11dea157174e282033cf993a8bfd1e5e0989bab48fe73df1ab7005bd7e19`。
### ACM 的三类官方样例
新增 ACM acmart v2.21 的单栏期刊 `acmsmall`、双栏期刊 `acmtog` 和会议
`sigconf`。矩阵核验 CTAN 压缩包 SHA-256,运行随包未改动的 DocStrip
安装器,并记录生成的 UTF-8 源、类和资产的指纹。参考和原生各使用独立源
副本和各自生成的辅助文件。可分别传入 `--case acm-acmsmall`、
`--case acm-acmtog` 和 `--case acm-sigconf`。
[ACM acmart 官方发布](https://ctan.org/pkg/acmart)
初轮两端均缺少 `\DocumentMetadata` 的支持文件。补入 Fedora 44 的
LaTeX-lab、PDF management、tagpdf 及其他实际查到的原版依赖后,参考 pdfTeX
分别生成11、7、7页带标签的 PDF 2.0。三项经过五轮 LaTeX 和一次 BibTeX 后
aux 收敛且无未定义引用。双栏期刊有6页实际文字行并排,单栏期刊没有匹配
双栏的字框。参考审计 SHA-256 为
`a9ee4e8e11ec0785c9b77ab898d915396004aced3e786a45bfc64a80f86f947a`。
隔离 schema29 原生候选均在实际 `l3backend-pdftex.def` 的
`\pdfcolorstackinit page direct` 处拒绝 `/opacity1 gs`。最小样例验证
pdfTeX 会把该操作写入页面内容流,并链接对应的 `ExtGState` 资源。原生
的实际诊断和参考 PDF 保留在 `color-stack-probe`。
[pdfTeX 上游对颜色栈参数的扫描](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L10457-L10478)
两份独立的 pdfTeX 参考作业补齐跨页与对象生命周期的约束。第一页先发初始
图形状态再推入新状态,第二页先重放新状态再弹回。当前页的资源字典连接两个
实际对象。对象编号保留、立即写出、页面引用、丢弃盒及从未引用对象各有实际
PDF 证据。回执 `target/p3-pdf-graphic-state-reference/receipt.json`
SHA-256 为 `0f9082ccfabbd34895b95abe9a20011c68cd9669a5cc69c2068e97b7aa3ae631`。
[pdfTeX 对象写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L31785-L31839)
[pdfTeX 页面资源写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L17886-L17903)
最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json`
SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存
DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有
IEEE 会议单项参数复验,原生与参考均生成1页且三轮 aux 逐字相同。回执
`matrix-original-ieee/report.json` SHA-256 为
`0abb0304e0cab323cd9e52f515d69e02fe8ced5d9a84b3e20aa9c9dcfb7fb276`。
单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、
双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源
与容差都不得为通过而替换。类 Typst 的编辑延迟另用同批原样项目分规模测量,
+113 -36
View File
@@ -3,9 +3,16 @@ const pages = document.querySelector("#pages");
const status = document.querySelector("#status");
const error = document.querySelector("#error");
const pdf = document.querySelector("#pdf");
const selector = document.querySelector("#project-files");
const name = document.querySelector("#name");
const edits = new Map();
let files;
let activeFile;
let sequence = 0;
let visibleRevision = null;
let publishedRevision = null;
let draft = null;
let frame;
const previewDraft = new URLSearchParams(location.hash.slice(1)).get("preview") !== "published";
function showError(message) {
status.textContent = "编译失败";
@@ -21,60 +28,99 @@ function pageImage(page) {
return img;
}
function removeTrailingPages(count) {
while (pages.children.length > count) {
const old = pages.lastElementChild;
URL.revokeObjectURL(old.src);
old.remove();
function revokeDetached(images) {
for (const image of images) {
if (!image.isConnected) URL.revokeObjectURL(image.src);
}
}
async function compile(edit, submitted) {
function applyPages(update, replacements) {
const previous = [...pages.children];
if (update.base_revision === null) {
pages.replaceChildren(...replacements);
} else {
for (const image of replacements) {
const old = pages.children[Number(image.dataset.index)];
if (old) old.replaceWith(image);
else pages.append(image);
}
while (pages.children.length > update.page_count) pages.lastElementChild.remove();
}
document.body.dataset.visibleRevision = update.revision;
return previous;
}
function restorePublishedPages() {
if (!draft) return;
const discarded = [...pages.children];
pages.replaceChildren(...draft.previous);
revokeDetached(discarded);
if (publishedRevision === null) delete document.body.dataset.visibleRevision;
else document.body.dataset.visibleRevision = publishedRevision;
pdf.hidden = publishedRevision === null;
draft = null;
}
function acceptPublication(revision, previous) {
revokeDetached(previous);
publishedRevision = revision;
pdf.href = `/pdf?revision=${revision}`;
pdf.hidden = false;
draft = null;
}
async function publicationStatus(edit, revision) {
while (edit === sequence) {
const response = await fetch(`/publication?revision=${revision}`);
const result = await response.json();
if (!response.ok || result.state === "failed") throw new Error(result.error);
if (result.state === "published") return result;
await new Promise((resolve) => setTimeout(resolve, 40));
}
return null;
}
async function compile(edit, submitted, changes) {
const replacements = [];
try {
const response = await fetch("/preview", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ sequence: edit, visible_revision: visibleRevision, source: source.value }),
body: JSON.stringify({
sequence: edit,
visible_revision: publishedRevision,
files: changes,
preview_draft: previewDraft,
}),
});
const result = await response.json();
if (edit !== sequence) return;
if (!response.ok) throw new Error(result.error);
const update = result.update;
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== visibleRevision)) {
if (result.sequence !== edit || (update.base_revision !== null && update.base_revision !== publishedRevision)) {
throw new Error("预览版本与当前页面不一致");
}
for (const page of update.pages) replacements.push(pageImage(page));
await Promise.all(replacements.map((page) => page.decode()));
if (edit !== sequence) {
for (const img of replacements) URL.revokeObjectURL(img.src);
revokeDetached(replacements);
return;
}
if (update.base_revision === null) {
removeTrailingPages(0);
pages.replaceChildren(...replacements);
const previous = applyPages(update, replacements);
if (result.pending_publication) {
draft = { previous };
pdf.hidden = true;
status.textContent = "正在写入文件";
} else {
for (const img of replacements) {
const old = pages.children[Number(img.dataset.index)];
if (old) {
old.replaceWith(img);
URL.revokeObjectURL(old.src);
} else {
pages.append(img);
}
}
removeTrailingPages(update.page_count);
acceptPublication(update.revision, previous);
}
visibleRevision = update.revision;
pdf.href = `/pdf?revision=${visibleRevision}`;
pdf.hidden = false;
error.hidden = true;
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
if (edit !== sequence) return;
const sample = {
sequence: edit,
revision: visibleRevision,
revision: update.revision,
changed: update.pages.map((page) => page.index + 1),
count: update.page_count,
compileMs: result.compile_ms,
@@ -86,15 +132,29 @@ async function compile(edit, submitted) {
reusedSteps: result.reused_steps,
reusedFrontier: result.reused_frontier,
replayedCalls: result.replayed_calls,
pendingPublication: result.pending_publication === true,
};
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
document.body.dataset.visibleRevision = visibleRevision;
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
if (result.pending_publication) {
const committed = await publicationStatus(edit, update.revision);
if (edit !== sequence || !committed) return;
acceptPublication(update.revision, draft.previous);
window.dispatchEvent(new CustomEvent("texrra-preview-published", {
detail: {
sequence: edit,
revision: update.revision,
compileMs: committed.compile_ms,
publicationMs: committed.publication_ms,
},
}));
}
status.textContent = `${sample.count} 页 · ${Math.round(sample.visibleMs)} 毫秒`;
} catch (failure) {
for (const img of replacements) {
if (!img.isConnected) URL.revokeObjectURL(img.src);
revokeDetached(replacements);
if (edit === sequence) {
restorePublishedPages();
showError(failure.message);
}
if (edit === sequence) showError(failure.message);
}
}
@@ -102,8 +162,10 @@ function queueCompile() {
const edit = ++sequence;
const submitted = performance.now();
cancelAnimationFrame(frame);
restorePublishedPages();
status.textContent = "正在编译";
frame = requestAnimationFrame(() => compile(edit, submitted));
const changes = Object.fromEntries(edits);
frame = requestAnimationFrame(() => compile(edit, submitted, changes));
}
async function openProject() {
@@ -111,11 +173,26 @@ async function openProject() {
const response = await fetch("/project");
if (!response.ok) throw new Error("无法打开源文件");
const project = await response.json();
document.querySelector("#name").textContent = project.name;
source.value = project.source;
files = new Map(Object.entries(project.files));
activeFile = project.name;
name.textContent = activeFile;
source.value = files.get(activeFile);
source.disabled = false;
sequence = project.sequence;
source.addEventListener("input", queueCompile);
if (files.size > 1) {
for (const filename of files.keys()) selector.add(new Option(filename, filename));
selector.value = activeFile;
selector.hidden = false;
name.hidden = true;
selector.addEventListener("change", () => {
activeFile = selector.value;
source.value = edits.get(activeFile) ?? files.get(activeFile);
});
}
source.addEventListener("input", () => {
edits.set(activeFile, source.value);
queueCompile();
});
queueCompile();
} catch (failure) {
showError(failure.message);
+4 -1
View File
@@ -42,7 +42,10 @@
</header>
<main>
<section class="edit" aria-label="源文件">
<label class="file" for="source" id="name">源文件</label>
<div class="file">
<label for="source" id="name">源文件</label>
<select id="project-files" aria-label="选择源文件" hidden></select>
</div>
<textarea id="source" spellcheck="false" disabled></textarea>
</section>
<section class="preview" aria-label="页面预览">
+253 -42
View File
@@ -5,7 +5,7 @@ use std::{
collections::{BTreeMap, BTreeSet},
fs,
io::Read,
path::{Path, PathBuf},
path::{Component, Path, PathBuf},
sync::{
Arc, Condvar, Mutex,
atomic::{AtomicU64, Ordering},
@@ -13,8 +13,9 @@ use std::{
time::Instant,
};
use texrra_engine::native::{
CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, Entry, NativeCompiler,
ProjectDefinition, ProjectSnapshot, job_time,
CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, DraftPreview, Entry,
EntryCheckpointWork, NativeCompiler, PreviewUpdate, ProjectDefinition, ProjectSnapshot,
job_time,
};
use texrra_tex_core::resources::{InputPolicy, WorldConfig};
use tiny_http::{Header, Method, Request, Response, Server};
@@ -27,7 +28,11 @@ const SCRIPT: &str = include_str!("app.js");
struct Edit {
sequence: u64,
visible_revision: Option<u64>,
source: String,
source: Option<String>,
#[serde(default)]
files: BTreeMap<String, String>,
#[serde(default)]
preview_draft: bool,
}
struct Work {
@@ -37,14 +42,21 @@ struct Work {
sequence: u64,
visible_revision: Option<u64>,
received: Instant,
preview_draft: bool,
}
struct StageTimes {
struct EditorObserver {
started: Instant,
ended: Mutex<[f64; 5]>,
queue: Arc<Queue>,
request: Mutex<Option<Request>>,
sequence: u64,
visible_revision: Option<u64>,
received: Instant,
preview_draft: bool,
}
impl CompileObserver for StageTimes {
impl CompileObserver for EditorObserver {
fn stage(&self, _: u64, stage: CompileStage) -> Result<(), String> {
let index = match stage {
CompileStage::Prepared => 0,
@@ -53,12 +65,81 @@ impl CompileObserver for StageTimes {
CompileStage::Exported => 3,
CompileStage::ReadyToPublish => 4,
};
self.ended.lock().unwrap()[index] = self.started.elapsed().as_secs_f64() * 1000.0;
self.ended.lock().unwrap()[index] = self.elapsed_ms();
Ok(())
}
fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> {
if !self.preview_draft || !self.is_current() {
return Ok(());
}
// If SVG rendering fails, let the normal compile result and durable
// response handle the error. An editor transport failure cannot veto
// an otherwise valid document.
let Ok(update) = draft.preview_since(self.visible_revision) else {
return Ok(());
};
if !self.is_current() {
return Ok(());
}
let revision = update.revision;
let reply_body = self.preview_payload(
update,
draft.execution_steps(),
draft.entry_checkpoint_work(),
None,
);
let request = self
.request
.lock()
.unwrap()
.take()
.expect("draft response sent once");
let publication = Publication {
revision,
started_ms: self.elapsed_ms(),
result: None,
};
*self.queue.publication.lock().unwrap() = Some(publication);
std::thread::spawn(move || reply(request, 200, reply_body));
Ok(())
}
}
impl StageTimes {
impl EditorObserver {
fn elapsed_ms(&self) -> f64 {
self.started.elapsed().as_secs_f64() * 1000.0
}
fn is_current(&self) -> bool {
self.sequence == self.queue.current.load(Ordering::Acquire)
}
fn preview_payload(
&self,
update: PreviewUpdate,
steps: usize,
work: &EntryCheckpointWork,
compiled: Option<f64>,
) -> Value {
let ready = self.elapsed_ms();
let pending = compiled.is_none();
let compiled = compiled.unwrap_or_else(|| self.ended.lock().unwrap()[4]);
json!({
"sequence": self.sequence,
"update": update,
"pending_publication": pending,
"compile_ms": compiled,
"ready_ms": ready,
"admission_and_queue_ms": self.started.duration_since(self.received).as_secs_f64() * 1000.0,
"phases": self.phases(compiled, ready),
"steps": steps,
"reused_steps": work.reused_steps,
"reused_frontier": work.reused_frontier,
"replayed_calls": work.replayed_calls,
})
}
fn phases(&self, compiled: f64, rendered: f64) -> Value {
let [prepared, executed, fonts, exported, ready] = *self.ended.lock().unwrap();
json!({
@@ -73,16 +154,23 @@ impl StageTimes {
}
}
struct Publication {
revision: u64,
started_ms: f64,
result: Option<Value>,
}
#[derive(Default)]
struct Queue {
next: Mutex<Option<Work>>,
available: Condvar,
current: AtomicU64,
publication: Mutex<Option<Publication>>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args_os().skip(1).map(PathBuf::from);
let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT]";
let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]";
let source = args.next().ok_or(usage)?.canonicalize()?;
let format = args.next().ok_or(usage)?.canonicalize()?;
let manifest = args.next().ok_or(usage)?;
@@ -92,12 +180,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.map(|s| s.to_string_lossy().parse())
.transpose()?
.unwrap_or(0u16);
if args.next().is_some() {
return Err(usage.into());
}
let additional = args.collect::<Vec<_>>();
fs::create_dir(&run)?;
let run = run.canonicalize()?;
let (mut project, entry, options) = prepare(&source, &format, &manifest, &run)?;
let EditorProject {
mut project,
entry,
editable,
options,
} = prepare(&source, &format, &manifest, &run, &additional)?;
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
let queue = Arc::new(Queue {
@@ -121,12 +212,22 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
),
(&Method::Get, "/project") => {
let file = project.file(&entry).expect("the editor owns its entry");
let files = editable
.iter()
.map(|(name, path)| {
let file = project
.file(path)
.expect("editable project files are immutable");
Ok((name, std::str::from_utf8(&file.data)?))
})
.collect::<Result<BTreeMap<_, _>, std::str::Utf8Error>>()?;
reply(
request,
200,
json!({
"name": entry.file_name().unwrap().to_string_lossy(),
"source": std::str::from_utf8(&file.data)?,
"files": files,
"sequence": queue.current.load(Ordering::Acquire),
}),
);
@@ -149,10 +250,26 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);
continue;
}
let next = project.with_file_edits(
edit.sequence,
BTreeMap::from([(entry.clone(), Arc::from(edit.source.into_bytes()))]),
);
let updates = edit
.files
.into_iter()
.map(|(name, value)| {
let path = editable
.get(&name)
.ok_or_else(|| format!("File is not editable: {name}"))?;
Ok((path.clone(), Arc::from(value.into_bytes())))
})
.collect::<Result<BTreeMap<_, _>, String>>();
let next = updates.and_then(|mut updates| {
if let Some(source) = edit.source
&& updates
.insert(entry.clone(), Arc::from(source.into_bytes()))
.is_some()
{
return Err("The entry file was edited twice".into());
}
project.with_file_edits(edit.sequence, updates)
});
project = match next {
Ok(project) => project,
Err(error) => {
@@ -170,6 +287,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
sequence: edit.sequence,
visible_revision: edit.visible_revision,
received,
preview_draft: edit.preview_draft,
});
queue.available.notify_one();
if let Some(old) = replaced {
@@ -180,6 +298,30 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
);
}
}
(&Method::Get, path) if path.starts_with("/publication?revision=") => {
let revision = path["/publication?revision=".len()..].parse::<u64>().ok();
let result = queue
.publication
.lock()
.unwrap()
.as_ref()
.filter(|publication| Some(publication.revision) == revision)
.map(|publication| {
publication
.result
.clone()
.unwrap_or_else(|| json!({"state": "pending"}))
});
if let Some(result) = result {
reply(request, 200, result);
} else {
reply(
request,
409,
json!({"error": "This publication is no longer current"}),
);
}
}
(&Method::Get, path) if path.starts_with("/pdf?revision=") => {
let revision = path["/pdf?revision=".len()..].parse::<u64>().ok();
match compiler
@@ -228,20 +370,66 @@ fn read_edit(request: &mut Request) -> Result<Edit, String> {
serde_json::from_slice(&body).map_err(|e| e.to_string())
}
struct EditorProject {
project: Arc<ProjectSnapshot>,
entry: PathBuf,
editable: BTreeMap<String, PathBuf>,
options: CompileRequest,
}
fn prepare(
source: &Path,
format: &Path,
manifest: &Path,
run: &Path,
) -> Result<(Arc<ProjectSnapshot>, PathBuf, CompileRequest), Box<dyn std::error::Error>> {
additional: &[PathBuf],
) -> Result<EditorProject, Box<dyn std::error::Error>> {
let format_resources: Value = serde_json::from_slice(&fs::read(manifest)?)?;
let roots: Vec<PathBuf> = serde_json::from_value(format_resources["texmf_roots"].clone())?;
let mut world = WorldConfig::from_environment(run, roots.clone())?;
world.input_policy = InputPolicy::Tex;
let entry = run.join(source.file_name().ok_or("Source needs a filename")?);
let name = source
.file_name()
.and_then(|name| name.to_str())
.ok_or("Source needs a UTF-8 filename")?;
let entry = run.join(name);
let original = fs::read(source)?;
std::str::from_utf8(&original)?;
fs::write(&entry, &original)?;
let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]);
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::from([(entry.clone(), Arc::from(original))]);
let source_root = source.parent().expect("the entry has a parent");
for relative in additional {
if relative.as_os_str().is_empty()
|| relative
.components()
.any(|item| !matches!(item, Component::Normal(_)))
{
return Err(format!(
"Project file must be relative to the entry directory: {}",
relative.display()
)
.into());
}
let logical = run.join(relative);
let physical = source_root.join(relative).canonicalize()?;
if !physical.starts_with(source_root) || files.contains_key(&logical) {
return Err(format!(
"Project file is outside the entry directory or is listed twice: {}",
relative.display()
)
.into());
}
let data: Arc<[u8]> = Arc::from(fs::read(physical)?);
fs::create_dir_all(logical.parent().expect("project file has a parent"))?;
fs::write(&logical, &data)?;
if let Some(name) = relative.to_str()
&& std::str::from_utf8(&data).is_ok()
{
editable.insert(name.into(), logical.clone());
}
files.insert(logical, data);
}
let mut request = CompileRequest::new(
world.clone(),
&entry,
@@ -255,7 +443,6 @@ fn prepare(
// Provision the finite, immutable resource bundle used by this trial.
// The seed uses the same native compiler and actual package bytes.
let seed = NativeCompiler::default().compile(request.clone())?;
let mut files = BTreeMap::from([(entry.clone(), Arc::from(original))]);
for (path, captured) in seed.inputs.files() {
if !path.starts_with(run) {
files.insert(path.to_owned(), captured?.data.clone());
@@ -293,10 +480,15 @@ fn prepare(
generated_roots: BTreeSet::from([run.to_owned()]),
generated,
})?;
Ok((project, entry, request))
Ok(EditorProject {
project,
entry,
editable,
options: request,
})
}
fn worker(queue: &Queue) {
fn worker(queue: &Arc<Queue>) {
loop {
let Work {
request,
@@ -305,19 +497,46 @@ fn worker(queue: &Queue) {
sequence,
visible_revision,
received,
preview_draft,
} = queue
.available
.wait_while(queue.next.lock().unwrap(), |next| next.is_none())
.unwrap()
.take()
.expect("the worker was woken with an edit");
let start = Instant::now();
let timings = Arc::new(StageTimes {
started: start,
let observer = Arc::new(EditorObserver {
started: Instant::now(),
ended: Mutex::new([0.0; 5]),
queue: queue.clone(),
request: Mutex::new(Some(request)),
sequence,
visible_revision,
received,
preview_draft,
});
compile.observer = Some(timings.clone());
let document = match job.compile(compile) {
let revision = job.revision();
compile.observer = Some(observer.clone());
let result = job.compile(compile);
let compile_ms = observer.elapsed_ms();
let request = observer.request.lock().unwrap().take();
let Some(request) = request else {
let mut current = queue.publication.lock().unwrap();
let publication = current
.as_mut()
.filter(|p| p.revision == revision)
.expect("the worker owns the current publication");
let state = match result {
Ok(_) => json!({
"state": "published",
"compile_ms": compile_ms,
"publication_ms": compile_ms - publication.started_ms,
}),
Err(error) => json!({ "state": "failed", "error": error.to_string() }),
};
publication.result = Some(state);
continue;
};
let document = match result {
Ok(document) => document,
Err(CompileError::Cancelled) => {
reply(
@@ -336,10 +555,8 @@ fn worker(queue: &Queue) {
continue;
}
};
let compile_ms = start.elapsed().as_secs_f64() * 1000.0;
let preview = document.preview_since(visible_revision);
let ready_ms = start.elapsed().as_secs_f64() * 1000.0;
if sequence != queue.current.load(Ordering::Acquire) {
if !observer.is_current() {
reply(
request,
409,
@@ -351,18 +568,12 @@ fn worker(queue: &Queue) {
Ok(update) => reply(
request,
200,
json!({
"sequence": sequence,
"update": update,
"compile_ms": compile_ms,
"ready_ms": ready_ms,
"admission_and_queue_ms": start.duration_since(received).as_secs_f64() * 1000.0,
"phases": timings.phases(compile_ms, ready_ms),
"steps": document.execution.execution.steps,
"reused_steps": document.entry_checkpoint_work.reused_steps,
"reused_frontier": document.entry_checkpoint_work.reused_frontier,
"replayed_calls": document.entry_checkpoint_work.replayed_calls,
}),
observer.preview_payload(
update,
document.execution.execution.steps,
&document.entry_checkpoint_work,
Some(compile_ms),
),
),
Err(error) => reply(
request,
+6
View File
@@ -6,3 +6,9 @@
references, and Letter paper.
- Compile the fixture by importing it as a project (ZIP upload) or by copying
the directory into `projects/` next to a `.meta` entry.
- `pdftex-margin-protrusion/` contains two plain pdfTeX reference probes.
`probes.tex` compares protrusion levels 0, 1, and 2 at the same line width.
`font-scope.tex` exercises font-specific codes, grouping, font scaling,
margin queries, and unboxing. Run each in a separate output directory
with `pdftex -interaction=nonstopmode -halt-on-error -no-shell-escape -recorder`.
[Reference observations](../docs/P2_M1_PROGRESS.md)
@@ -0,0 +1,31 @@
\pdfoutput=1
\pdfadjustspacing=0
\pdfprotrudechars=0
\font\face=cmr10 at 10pt
\font\bigface=cmr10 at 20pt
\face
\begingroup
\lpcode\face`A=-1200
\rpcode\face`!=1200
\pdfprotrudechars=2
\message{!scope:inside:[\the\lpcode\face`A]/[\the\rpcode\face`!]/[\the\pdfprotrudechars]:end!}
\endgroup
\message{!scope:outside:[\the\lpcode\face`A]/[\the\rpcode\face`!]/[\the\pdfprotrudechars]:end!}
\message{!scope:other-font:[\the\lpcode\bigface`A]/[\the\rpcode\bigface`!]:end!}
\lpcode\face`A=-125
\rpcode\face`!=400
\lpcode\bigface`A=-125
\rpcode\bigface`!=400
\pdfprotrudechars=1
\parfillskip=0pt
\rightskip=0pt plus 1fil
\hsize=45pt
\def\probe#1{%
\setbox0=\vbox{#1\noindent A!\par\global\setbox2=\lastbox}%
\message{!scope:line:[\leftmarginkern2]/[\rightmarginkern2]:end!}%
\setbox3=\hbox{\unhcopy2}%
\message{!scope:unboxed:[\leftmarginkern3]/[\rightmarginkern3]:end!}%
\shipout\vbox{\copy2\box3}}
\probe\face
\probe\bigface
\end
@@ -0,0 +1,28 @@
\pdfoutput=1
\pdfadjustspacing=0
\font\face=cmr10
\face
\lpcode\face`A=125
\rpcode\face`!=400
\spaceskip=3.33333pt
\rightskip=0pt plus 1fil
\emergencystretch=0pt
\parindent=0pt
\tolerance=100
\showboxbreadth=100
\showboxdepth=100
\tracingoutput=1
\setbox0=\hbox{A! B!}
\hsize=\wd0
\advance\hsize by -1pt
\def\shipprobe#1{%
\pdfprotrudechars=#1
\setbox0=\vbox{\noindent A! B!\par
\global\setbox2=\lastbox
\message{!margin-check:#1:[\leftmarginkern2]/[\rightmarginkern2]:end!}%
\box2}%
\shipout\box0}
\shipprobe0
\shipprobe1
\shipprobe2
\end
+49 -3
View File
@@ -26,6 +26,9 @@ CASES = [
("acl", "conference", "acl", "acl-style-files-master/acl_latex.tex"),
("cvpr-2026", "conference", "cvpr-2026", "author-kit-CVPR2026-v1-latex-/main.tex"),
("neurips-2025", "conference", "neurips-2025", "Styles/neurips_2025.tex"),
("acm-acmsmall", "journal-single-column", "acmart", "acmart/samples/acmsmall.tex"),
("acm-acmtog", "journal-two-columns", "acmart", "acmart/samples/acmtog.tex"),
("acm-sigconf", "conference", "acmart", "acmart/samples/sigconf.tex"),
]
EPS_FIGURES = {
"springer-nature": ["fig.eps"],
@@ -66,6 +69,41 @@ def run(command, cwd, env, label, evidence):
return {"command": list(map(str, command)), "exit_code": status, "label": label}
def prepare_acmart(directory, evidence):
"""Extract the published class and samples with the package's DocStrip installers."""
upstream = directory / "acmart"
samples = upstream / "samples"
workspace = evidence / "docstrip"
sample_workspace = workspace / "samples"
sample_workspace.mkdir(parents=True)
env = {**os.environ, "TEXINPUTS": os.pathsep, "SOURCE_DATE_EPOCH": "1783900800"}
latex = ["pdflatex", "-interaction=nonstopmode", "-halt-on-error", "-no-shell-escape", "-recorder"]
commands = []
for original, work, installer, sources in (
(upstream, workspace, "acmart.ins", ["acmart.dtx"]),
(samples, sample_workspace, "samples.ins", ["samples.dtx", "acmengage.dtx"]),
):
for name in [installer, *sources]:
shutil.copyfile(original / name, work / name)
result = run([*latex, installer], work, env, installer, evidence)
if result["exit_code"]:
raise RuntimeError(f"ACM sample extraction failed: {evidence / installer}")
commands.append(result)
generated = {}
for source, destination in [
(workspace / "acmart.cls", samples / "acmart.cls"),
*[(sample_workspace / name, samples / name)
for name in ("acmsmall.tex", "acmtog.tex", "sigconf.tex")],
*[(upstream / name, samples / name)
for name in ("ACM-Reference-Format.bst", "acm-jdslogo.png")],
]:
if destination.exists():
raise ValueError(f"ACM installer output already exists: {destination}")
shutil.copyfile(source, destination)
generated[destination.relative_to(directory).as_posix()] = sha(destination)
return {"commands": commands, "sample_inputs": generated}
def diagnostics(evidence, label):
lines = []
for stream in ("stderr", "stdout"):
@@ -215,7 +253,12 @@ def main():
args = parser.parse_args()
if args.font_map and args.font_map.name != "pdftex.map":
parser.error("--font-map must name a pdftex.map file")
config = json.loads((ROOT / "scripts/publisher-template-matrix.json").read_text())
selected = [item for item in CASES if not args.case or item[0] in args.case]
archives = {item[2] for item in selected if item[2]}
registry = json.loads((ROOT / "scripts/publisher-template-matrix.json").read_text())
config = {name: registry[name] for name in registry if name in archives}
if config.keys() != archives:
raise ValueError(f"publisher archives missing from registry: {archives - config.keys()}")
sources = args.output / "inputs"
sources.mkdir(parents=True)
for archive, (digest, url) in config.items():
@@ -223,6 +266,10 @@ def main():
if sha(path) != digest:
raise ValueError(f"archive bytes differ from the pinned SHA-256: {path}")
unpack(path, sources / archive)
archive_preparation = {}
if "acmart" in config:
archive_preparation["acmart"] = prepare_acmart(
sources / "acmart", args.output / "preparation/acmart")
if args.texmf_overlay and not args.texmf_overlay.is_dir():
raise ValueError(f"missing overlay: {args.texmf_overlay}")
additions = inputs(args.texmf_overlay) if args.texmf_overlay else {}
@@ -247,7 +294,6 @@ def main():
print(name, row["reference"]["pdf_built"], row["native"]["pdf_built"], flush=True)
return row
selected = [item for item in CASES if not args.case or item[0] in args.case]
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(case, selected))
report = {"schema": 1, "scope": "compile and collect evidence; PDF creation alone is not fidelity",
@@ -255,7 +301,7 @@ def main():
"native_format_sha256": sha(args.native_format),
"reference_format_sha256": sha(args.reference_format), "texmf_overlay": additions,
"font_map_sha256": font_map_sha256,
"templates": results}
"archive_preparation": archive_preparation, "templates": results}
assert not args.texmf_overlay or inputs(args.texmf_overlay) == additions
assert not args.font_map or sha(args.font_map) == font_map_sha256
(args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
+4
View File
@@ -30,5 +30,9 @@
"neurips-2025": [
"72032130232955b785cd622b7c52d893e3166f30a90e1e6279d0a28e8373beef",
"https://media.neurips.cc/Conferences/NeurIPS2025/Styles.zip"
],
"acmart": [
"81977a834f5cfd5302c37181ede34d2663eeea60604d1d89230e3c5e74b9a4bb",
"https://mirrors.bfsu.edu.cn/CTAN/macros/latex/contrib/acmart.zip"
]
}
+25
View File
@@ -0,0 +1,25 @@
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
use std::io::{self, BufRead, Write};
use texrra_tex_core::execution::{RegexRequest, match_pdf_regex};
let mut input = io::stdin().lock();
let mut output = io::stdout().lock();
let mut request = Vec::new();
loop {
request.clear();
if input.read_until(b'\n', &mut request)? == 0 {
return Ok(());
}
let request: RegexRequest = serde_json::from_slice(&request)?;
serde_json::to_writer(&mut output, &match_pdf_regex(&request))?;
output.write_all(b"\n")?;
output.flush()?;
}
}
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
fn main() -> std::process::ExitCode {
eprintln!("pdfTeX regular expressions require the GNU backend");
std::process::ExitCode::FAILURE
}
+2
View File
@@ -9,5 +9,7 @@ mod native_generated;
mod native_host;
mod native_job;
mod native_preview;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod native_regex;
mod native_stream;
pub mod rust_typeset;
+62 -7
View File
@@ -12,7 +12,8 @@ pub use crate::native_host::{
};
pub use crate::native_job::job_time;
use crate::native_job::{
EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output, file_modification_date,
DraftSyncQueue, EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output,
file_modification_date,
};
use crate::native_preview::PreviewState;
pub use crate::native_preview::{PreviewPage, PreviewUpdate};
@@ -85,6 +86,39 @@ pub enum CompileStage {
/// schedule compilation after the callback returns, rather than recursing.
pub trait CompileObserver: Send + Sync {
fn stage(&self, revision: u64, stage: CompileStage) -> Result<(), String>;
/// Called for a completed native draft before its staged files are synced
/// and installed. The caller can display these pages provisionally. The
/// compile result determines whether this revision actually published.
fn draft_ready(&self, _draft: DraftPreview<'_>) -> Result<(), String> {
Ok(())
}
}
/// The same revision's native preview, available before artifact publication.
pub struct DraftPreview<'a> {
document: &'a CompiledDocument,
cancellation: &'a Cancellation,
}
impl DraftPreview<'_> {
pub fn preview_since(&self, visible_revision: Option<u64>) -> Result<PreviewUpdate, String> {
self.document.preview.render(
self.document.revision(),
&self.document.pages,
self.document.pdf.as_ref(),
visible_revision,
|| check(self.cancellation).map_err(|error| error.to_string()),
)
}
pub fn execution_steps(&self) -> usize {
self.document.execution.execution.steps
}
pub fn entry_checkpoint_work(&self) -> &EntryCheckpointWork {
&self.document.entry_checkpoint_work
}
}
fn notify(
request: &CompileRequest,
@@ -219,6 +253,7 @@ impl CompiledDocument {
&self.pages,
self.pdf.as_ref(),
visible_revision,
|| Ok(()),
)
}
pub fn has_show_diagnostic(&self) -> bool {
@@ -522,6 +557,7 @@ pub struct NativeCompiler {
session: NativeSession,
latest: Arc<Mutex<Option<Arc<CompiledDocument>>>>,
jobs: Arc<Mutex<()>>,
draft_sync: Arc<DraftSyncQueue>,
format_cache: Arc<FormatCache>,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
entry_checkpoints: Option<Arc<CheckpointCache>>,
@@ -753,7 +789,7 @@ fn prepare_checked(
),
};
let executor = if kernel == KernelPreparation::Resume {
image.validate_job_inputs(
image.validate_shared_job_inputs(
state.profile(),
request.input_profile,
&mut world,
@@ -781,7 +817,7 @@ fn prepare_checked(
None => {
let image = FormatImage::decode(&loaded.data)?;
let executor = if kernel == KernelPreparation::Resume {
image.validate_job_inputs(
image.validate_shared_job_inputs(
state.profile(),
request.input_profile,
&mut world,
@@ -969,8 +1005,14 @@ impl CompileJob {
let before = cache.work();
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
debug_assert!(executor.is_none());
let (executed, next) =
current.resume(self.job, source, files, &mut entry_checkpoint_work)?;
let (executed, next) = current.resume(
&request,
self.job,
source,
files,
cache.clone(),
&mut entry_checkpoint_work,
)?;
(executed, Some(next))
} else {
let executor = executor
@@ -1149,6 +1191,16 @@ impl CompileJob {
CompileStage::ReadyToPublish,
&cancellation,
)?;
if checkpoints.is_some()
&& let Some(observer) = &request.observer
{
let observed = observer.draft_ready(DraftPreview {
document: &result,
cancellation: &cancellation,
});
check(&cancellation)?;
observed?;
}
evidence.phase = AttemptPhase::Publishing;
let expose = || {
*self
@@ -1161,10 +1213,13 @@ impl CompileJob {
let publication = available_host
.take()
.expect("prepared draft host")
.seal_draft(prepared)
.seal_draft(prepared, &self.compiler.draft_sync, &cancellation)
.and_then(|draft| {
let Some(draft) = draft else {
return Ok(None);
};
draft.publish_current(&self.compiler.session, result.revision(), || {
cache.set(next_checkpoint);
cache.set(next_checkpoint, &request);
expose();
})
});
+385 -52
View File
@@ -12,6 +12,7 @@ use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EntryCheckpointWork {
pub captured_frontier: Option<usize>,
/// Checkpoints in the selected or freshly captured set.
pub retained_checkpoints: usize,
pub reused_frontier: Option<usize>,
pub reused_steps: usize,
@@ -21,18 +22,25 @@ pub struct EntryCheckpointWork {
pub(super) struct CheckpointCache {
minimum_frontier: Option<usize>,
published: Mutex<Option<Arc<CheckpointSet>>>,
published: Mutex<Option<Arc<PublishedCheckpoints>>>,
}
pub(super) struct PublishedCheckpoints {
current: Arc<CheckpointSet>,
previous_body: Option<Arc<CheckpointSet>>,
}
struct CachedCheckpoint {
entry: EntryCheckpoint,
guard: PrefixInputGuard,
replay_count: usize,
slots: CaptureSlots,
}
pub(super) struct CheckpointSet {
entries: Vec<Arc<CachedCheckpoint>>,
calls: Vec<Call>,
refresh_on_resume: bool,
}
pub(super) struct SelectedCheckpoint {
@@ -52,10 +60,12 @@ struct CaptureSchedule {
fixed_frontier: Option<usize>,
}
#[derive(Clone, Copy)]
struct CaptureSlots {
interval: usize,
early: bool,
page: bool,
next_page: usize,
}
impl CaptureSchedule {
@@ -79,6 +89,7 @@ impl CaptureSchedule {
interval: 0,
early: true,
page: false,
next_page: self.next_page,
});
}
if frontier >= self.bytes {
@@ -94,8 +105,109 @@ impl CaptureSchedule {
interval,
early,
page,
next_page: self.next_page,
})
}
fn retain(&mut self, checkpoint: &CachedCheckpoint) -> Option<CaptureSlots> {
let frontier = checkpoint.entry.frontier();
if frontier >= self.bytes {
return None;
}
let interval = (frontier - 1) / self.stride;
let early = checkpoint.slots.early && !std::mem::replace(&mut self.seen[interval], true);
self.next_page = self.next_page.max(checkpoint.slots.next_page);
Some(CaptureSlots {
interval,
early,
..checkpoint.slots
})
}
}
struct CapturedEntries<'a> {
request: &'a CompileRequest,
entry_path: Option<PathBuf>,
initial: Option<GeneratedInitialState>,
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
changed: bool,
}
impl<'a> CapturedEntries<'a> {
fn new(request: &'a CompileRequest, files: &Files) -> Self {
Self {
request,
entry_path: files
.resource_trace()
.reads
.first()
.map(|first| first.path.clone()),
initial: files.preparation().generated_initial.clone(),
early: Default::default(),
shipped: Default::default(),
changed: false,
}
}
fn retain(&mut self, slots: CaptureSlots, checkpoint: Arc<CachedCheckpoint>) {
if slots.early {
self.early[slots.interval] = Some(checkpoint.clone());
}
if slots.page {
self.shipped[slots.interval] = Some(checkpoint);
}
}
fn capture(&mut self, slots: CaptureSlots, entry: EntryCheckpoint, host: &RecordingHost) {
let (Some((trace, replay_count)), Some(path), Some(initial)) = (
host.prefix(),
self.entry_path.as_deref(),
self.initial.as_ref(),
) else {
return;
};
let Ok(guard) = PrefixInputGuard::capture(self.request, path, trace, initial.clone())
else {
return;
};
self.retain(
slots,
Arc::new(CachedCheckpoint {
entry,
guard,
replay_count,
slots,
}),
);
self.changed = true;
}
fn finish(
self,
recording: RecordingHost,
refresh_on_resume: bool,
) -> Option<Arc<CheckpointSet>> {
if !self.changed {
return None;
}
let mut entries: Vec<_> = self
.early
.into_iter()
.chain(self.shipped)
.flatten()
.collect();
entries.sort_by_key(|candidate| candidate.entry.completed_steps());
entries.dedup_by(|a, b| Arc::ptr_eq(a, b));
let replay_count = entries.iter().map(|entry| entry.replay_count).max()?;
let mut calls = recording.into_calls()?;
calls.truncate(replay_count);
Some(Arc::new(CheckpointSet {
entries,
calls,
refresh_on_resume,
}))
}
}
pub(super) fn can_stage(request: &CompileRequest) -> bool {
@@ -114,18 +226,50 @@ impl CheckpointCache {
}
}
pub(super) fn current(&self) -> Option<Arc<CheckpointSet>> {
pub(super) fn current(&self) -> Option<Arc<PublishedCheckpoints>> {
self.published
.lock()
.expect("native entry checkpoint cache poisoned")
.clone()
}
pub(super) fn set(&self, checkpoint: Option<Arc<CheckpointSet>>) {
*self
pub(super) fn set(&self, next: Option<Arc<CheckpointSet>>, request: &CompileRequest) {
let mut published = self
.published
.lock()
.expect("native entry checkpoint cache poisoned") = checkpoint;
.expect("native entry checkpoint cache poisoned");
let Some(next) = next else {
*published = None;
return;
};
if published
.as_ref()
.and_then(|set| set.previous_body.as_ref())
.is_some_and(|previous| Arc::ptr_eq(previous, &next))
{
return;
}
let previous_body = published.as_ref().and_then(|published| {
if next.refresh_on_resume
&& let Some(project) = request.project.as_deref()
&& published
.current
.entries
.iter()
.find(|entry| entry.slots.page)
.is_some_and(|entry| entry.accept_entry(project).is_err())
{
// Keep useful continuations from before a change to the first
// shipped prefix. Later edits keep that same reserve.
published.current.reserve_body()
} else {
published.previous_body.clone()
}
});
*published = Some(Arc::new(PublishedCheckpoints {
current: next,
previous_body,
}));
}
pub(super) fn capture(
@@ -139,55 +283,18 @@ impl CheckpointCache {
Result<Arc<RevisionExecution>, RevisionFailure>,
Option<Arc<CheckpointSet>>,
) {
let entry_path = files
.resource_trace()
.reads
.first()
.map(|first| first.path.clone());
let initial = files.preparation().generated_initial.clone();
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier);
let mut early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS] = Default::default();
let mut shipped = early.clone();
let mut captures = CapturedEntries::new(request, files);
let mut recording = RecordingHost::new(files);
let result = job.run_capturing_entries(
executor,
source,
&mut recording,
|frontier, pages| schedule.select(frontier, pages),
|slots, entry, host| {
let (Some((trace, replay_count)), Some(path), Some(initial)) =
(host.prefix(), entry_path.as_deref(), initial.as_ref())
else {
return;
};
let Ok(guard) = PrefixInputGuard::capture(request, path, trace, initial.clone())
else {
return;
};
let captured = Arc::new(CachedCheckpoint {
entry,
guard,
replay_count,
});
if slots.early {
early[slots.interval] = Some(captured.clone());
}
if slots.page {
shipped[slots.interval] = Some(captured);
}
},
|slots, entry, host| captures.capture(slots, entry, host),
);
let mut entries: Vec<_> = early.into_iter().chain(shipped).flatten().collect();
entries.sort_by_key(|candidate| candidate.entry.completed_steps());
entries.dedup_by(|a, b| Arc::ptr_eq(a, b));
let replay_count = entries.iter().map(|entry| entry.replay_count).max();
let next = if result.is_ok()
&& let Some(replay_count) = replay_count
{
recording.into_calls().map(|mut calls| {
calls.truncate(replay_count);
Arc::new(CheckpointSet { entries, calls })
})
let next = if result.is_ok() {
captures.finish(recording, self.minimum_frontier.is_none())
} else {
None
};
@@ -195,7 +302,49 @@ impl CheckpointCache {
}
}
impl PublishedCheckpoints {
pub(super) fn select(&self, request: &CompileRequest) -> Result<SelectedCheckpoint, String> {
let current = self.current.clone().select(request);
let Some(previous) = &self.previous_body else {
return current;
};
let completed = current
.as_ref()
.map_or(0, SelectedCheckpoint::completed_steps);
if previous
.entries
.last()
.is_some_and(|entry| entry.entry.completed_steps() > completed)
&& let Ok(previous) = previous.clone().select(request)
&& previous.completed_steps() > completed
{
return Ok(previous);
}
current
}
}
impl CheckpointSet {
fn reserve_body(&self) -> Option<Arc<Self>> {
// The reserve holds only recent shipped checkpoints and the host
// call prefix they independently require.
let mut entries: Vec<_> = self
.entries
.iter()
.rev()
.filter(|entry| entry.slots.page)
.take(2)
.cloned()
.collect();
entries.reverse();
let replay_count = entries.last()?.replay_count;
Some(Arc::new(Self {
entries,
calls: self.calls[..replay_count].to_vec(),
refresh_on_resume: self.refresh_on_resume,
}))
}
pub(super) fn report_capture(&self, work: &mut EntryCheckpointWork) {
work.retained_checkpoints = self.entries.len();
work.captured_frontier = self.entries.last().map(|entry| entry.entry.frontier());
@@ -241,6 +390,10 @@ impl CachedCheckpoint {
}
impl SelectedCheckpoint {
fn completed_steps(&self) -> usize {
self.set.entries[self.index].entry.completed_steps()
}
pub(super) fn prepare(
&self,
request: &CompileRequest,
@@ -275,9 +428,11 @@ impl SelectedCheckpoint {
pub(super) fn resume(
self,
request: &CompileRequest,
job: RevisionJob,
source: SourceFile,
files: &mut Files,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
work: &mut EntryCheckpointWork,
) -> Result<
(
@@ -287,14 +442,59 @@ impl SelectedCheckpoint {
CompileError,
> {
let checkpoint = &self.set.entries[self.index];
let result = job
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
.ok_or_else(|| CompileError::Host("prepared checkpoint prefix changed".into()))?;
let frontier = checkpoint.entry.frontier();
work.retained_checkpoints = self.set.entries.len();
work.reused_frontier = Some(checkpoint.entry.frontier());
work.reused_frontier = Some(frontier);
work.reused_steps = checkpoint.entry.completed_steps();
work.replayed_calls = checkpoint.replay_count;
Ok((result, self.set))
let changed_prefix = || CompileError::Host("prepared checkpoint prefix changed".into());
if !self.set.refresh_on_resume {
let result = job
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
.ok_or_else(changed_prefix)?;
return Ok((result, self.set));
}
let mut schedule = CaptureSchedule::new(source.data.len(), None);
let mut captures = CapturedEntries::new(request, files);
// Share only calls and continuations from the prefix just replayed.
for previous in &self.set.entries[..=self.index] {
if previous.replay_count <= checkpoint.replay_count
&& previous.entry.frontier() <= frontier
&& let Some(slots) = schedule.retain(previous)
{
captures.retain(slots, previous.clone());
}
}
let mut recording =
RecordingHost::after_replay(files, &self.set.calls[..checkpoint.replay_count]);
let result = job
.resume_capturing_entries_after_host_replay(
&checkpoint.entry,
source,
&mut recording,
line_break_cache,
|offset, pages| {
if offset > frontier {
schedule.select(offset, pages)
} else {
None
}
},
|slots, entry, host| captures.capture(slots, entry, host),
)
.ok_or_else(changed_prefix)?;
let next = if result.is_ok() {
captures.finish(recording, true)
} else {
None
};
if let Some(next) = next {
next.report_capture(work);
Ok((result, next))
} else {
Ok((result, self.set))
}
}
}
@@ -716,7 +916,14 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
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();
let staged = files
.seal_draft(
Some(prepared_pdf),
&DraftSyncQueue::default(),
&Cancellation::default(),
)
.unwrap()
.unwrap();
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
(result, source_map, pdf.bytes, staged)
@@ -970,6 +1177,132 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
);
}
#[test]
fn automatic_checkpoints_follow_successive_edits_at_different_frontiers() {
let cwd = std::env::temp_dir().join(format!("texrra-rolling-{}", std::process::id()));
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().unwrap();
let entry = cwd.join("rolling.tex");
let aux = cwd.join("rolling.aux");
let mut original =
"\\catcode123=1 \\catcode125=2\n\\immediate\\openout1=rolling.aux\n".to_owned();
let mut stable_aux = String::new();
for width in 10..20 {
original.push_str(&format!(
"\\immediate\\write1{{page {width}}}\n\\shipout\\hbox{{\\vrule width{width}pt height1pt}}\n"
));
stable_aux.push_str(&format!("page {width}\n"));
}
original.push_str("\\immediate\\closeout1 \\end\n");
fs::write(&aux, &stable_aux).unwrap();
let mut world = WorldConfig::new(&cwd);
world.input_policy = InputPolicy::Tex;
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: BTreeSet::from([cwd.clone()]),
files: BTreeMap::from([(entry.clone(), Arc::from(original.as_bytes()))]),
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::from([aux.clone()]),
})
.unwrap();
let mut request = CompileRequest::new(
world,
"rolling.tex",
"rolling.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;
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let original_result = compiler.compile(request.clone()).unwrap();
assert_eq!(original_result.pages.len(), 10);
let first_edit = original.replace("width10pt", "width22pt");
let edited_project = project
.with_file_edits(
2,
BTreeMap::from([(entry.clone(), Arc::from(first_edit.as_bytes()))]),
)
.unwrap();
let first_request = request.clone().with_project(edited_project.clone());
let first = compiler.compile(first_request.clone()).unwrap();
let first_full = NativeCompiler::default().compile(first_request).unwrap();
let first_work = &first.entry_checkpoint_work;
let first_frontier = first_work.reused_frontier.unwrap();
assert!(first_work.captured_frontier.unwrap() > first_frontier);
assert!(first_work.replayed_calls > 0);
assert!(first.execution.execution == first_full.execution.execution);
assert_eq!(first.pdf, first_full.pdf);
assert_eq!(first.source_map.pages, first_full.source_map.pages);
assert_eq!(fs::read_to_string(&aux).unwrap(), stable_aux);
let second_edit = first_edit.replace("width19pt", "width29pt");
let second_project = edited_project
.with_file_edits(
3,
BTreeMap::from([(entry.clone(), Arc::from(second_edit.as_bytes()))]),
)
.unwrap();
let second_request = request.clone().with_project(second_project.clone());
let second = compiler.compile(second_request.clone()).unwrap();
let second_full = NativeCompiler::default().compile(second_request).unwrap();
let second_work = &second.entry_checkpoint_work;
assert!(second_work.reused_frontier.unwrap() > original.find("width10pt").unwrap());
assert!(second_work.reused_steps > first_work.reused_steps);
assert!(second_work.replayed_calls > first_work.replayed_calls);
assert!((2..=2 * SOURCE_INTERVALS).contains(&second_work.retained_checkpoints));
assert_eq!(second.entry_checkpoint_work.rejection, None);
assert!(second.execution.execution == second_full.execution.execution);
assert_eq!(
second.execution.source_versions,
second_full.execution.source_versions
);
assert_eq!(
second.execution.execution_resources,
second_full.execution.execution_resources
);
assert_eq!(second.pdf, second_full.pdf);
assert_eq!(second.source_map.pages, second_full.source_map.pages);
assert_eq!(fs::read_to_string(&aux).unwrap(), stable_aux);
assert_eq!(
second
.preview_since(Some(first.revision()))
.unwrap()
.pages
.iter()
.map(|page| page.index)
.collect::<Vec<_>>(),
[9],
);
let reverted = original.replace("width19pt", "width29pt");
let third_project = second_project
.with_file_edits(
4,
BTreeMap::from([(entry, Arc::from(reverted.into_bytes()))]),
)
.unwrap();
let third_request = request.with_project(third_project);
let third = compiler.compile(third_request.clone()).unwrap();
let third_full = NativeCompiler::default().compile(third_request).unwrap();
assert!(
third.entry_checkpoint_work.reused_steps > first_work.reused_steps,
"{:?}",
third.entry_checkpoint_work
);
assert_eq!(third.pdf, third_full.pdf);
assert_eq!(third.source_map.pages, third_full.source_map.pages);
assert_eq!(fs::read_to_string(&aux).unwrap(), stable_aux);
}
#[test]
#[ignore = "requires the verified LaTeX format, A3 fixture and a dedicated output directory"]
fn original_a3_shared_compiler_publishes_checkpoint_and_page_delta() {
+23 -10
View File
@@ -10,7 +10,7 @@ use texrra_tex_core::{
resources::{LoadedResource, ResourceKind},
};
pub(super) type Call = Box<dyn Fn(&mut Files) -> Result<(), String> + Send + Sync>;
pub(super) type Call = Arc<dyn Fn(&mut Files) -> Result<(), String> + Send + Sync>;
const MAX_REPLAY_CALLS: usize = 65_536;
pub(super) struct RecordingHost<'a> {
@@ -20,9 +20,13 @@ pub(super) struct RecordingHost<'a> {
impl<'a> RecordingHost<'a> {
pub(super) fn new(files: &'a mut Files) -> Self {
Self::after_replay(files, &[])
}
pub(super) fn after_replay(files: &'a mut Files, prefix: &[Call]) -> Self {
Self {
files,
calls: Some(Vec::new()),
calls: Some(prefix.to_vec()),
}
}
@@ -54,7 +58,7 @@ impl<'a> RecordingHost<'a> {
return result;
}
let expected = evidence(&result);
calls.push(Box::new(move |files| {
calls.push(Arc::new(move |files| {
let observed = evidence(&call(files));
if observed == expected {
Ok(())
@@ -79,6 +83,15 @@ macro_rules! call {
}
impl SourceProvider for RecordingHost<'_> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
self.files.match_pdf_regex(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&ResourceTrace> {
self.files.execution_resource_trace()
}
@@ -255,12 +268,12 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
files: &mut files,
calls: Some(Vec::new()),
};
let (original_execution, captured) = executor.unwrap().run_capturing_entry(
source,
&mut record,
marker_start.saturating_sub(1200),
|host| host.calls.take().unwrap(),
);
let (original_execution, captured) =
executor
.unwrap()
.run_capturing_entry(source, &mut record, marker_start, |host| {
host.calls.take().unwrap()
});
let original_execution = original_execution.expect("the original A3 job reaches its end");
let (checkpoint, calls) = captured.expect("a physical command boundary before the edited line");
assert!(checkpoint.frontier() <= marker_start);
@@ -332,7 +345,7 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
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)
.render(1, &pages, Some(&pdf_for_preview), None, || Ok(()))
.unwrap();
let full = NativeCompiler::default().compile(request.clone()).unwrap();
assert!(
+79 -20
View File
@@ -91,6 +91,13 @@ pub struct HostPreparation {
#[serde(default)]
pub generated_initial: Option<crate::native_generated::GeneratedInitialState>,
}
#[cfg(unix)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum UnixPathIdentity {
Present(u64, u64),
Missing,
}
impl HostPreparation {
pub(crate) fn environment(&mut self, name: &str) -> Option<OsString> {
let value = std::env::var_os(name);
@@ -140,30 +147,65 @@ impl HostPreparation {
result
}
pub(crate) fn same_file(&mut self, a: &Path, b: &Path) -> bool {
let same = if a == b {
true
} else if self
.canonicalize(a)
.ok()
.zip(self.canonicalize(b).ok())
.is_some_and(|(a, b)| a == b)
let same = a == b || self.same_file_target(a, b);
self.record_alias(a, b, same)
}
pub(crate) fn aliases_any<'a>(
&mut self,
path: &Path,
candidates: impl Iterator<Item = &'a Path> + Clone,
) -> bool {
#[cfg(unix)]
{
true
} else {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if let (Ok(a), Ok(b)) = (self.metadata(a), self.metadata(b)) {
a.dev() == b.dev() && a.ino() == b.ino()
} else {
false
let mut candidates = candidates.peekable();
let Some(first) = candidates.peek().copied() else {
return false;
};
if path == first {
return self.same_file(first, path);
}
if let Some(identity) = self.path_identity(path) {
let same = candidates.clone().any(|candidate| {
let alias = if candidate == path {
true
} else if identity == UnixPathIdentity::Missing {
false
} else if let Some(candidate_identity) = self.path_identity(candidate) {
identity == candidate_identity
} else {
return self.same_file(candidate, path);
};
self.record_alias(candidate, path, alias)
});
// Keep observations local to this scan. If the fixed path
// changed during a negative scan, use fresh pairwise probes.
if same || self.path_identity(path) == Some(identity) {
return same;
}
}
#[cfg(not(unix))]
{
false
return candidates.any(|candidate| self.same_file(candidate, path));
}
#[cfg(not(unix))]
{
let mut candidates = candidates;
candidates.any(|candidate| self.same_file(candidate, path))
}
}
#[cfg(unix)]
fn path_identity(&mut self, path: &Path) -> Option<UnixPathIdentity> {
use std::os::unix::fs::MetadataExt;
match self.metadata(path) {
Ok(metadata) => Some(UnixPathIdentity::Present(metadata.dev(), metadata.ino())),
Err(error) if error.kind() == io::ErrorKind::NotFound => {
Some(UnixPathIdentity::Missing)
}
};
Err(_) => None,
}
}
fn record_alias(&mut self, a: &Path, b: &Path, same: bool) -> bool {
self.observations.push(HostObservation::Alias {
left: a.into(),
right: b.into(),
@@ -171,6 +213,23 @@ impl HostPreparation {
});
same
}
fn same_file_target(&mut self, a: &Path, b: &Path) -> bool {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
// Metadata follows symlinks. The device and inode also identify
// hard links, so existing Unix paths need no canonicalization.
match (self.metadata(a), self.metadata(b)) {
(Ok(a), Ok(b)) => return a.dev() == b.dev() && a.ino() == b.ino(),
(Err(e), _) | (_, Err(e)) if e.kind() == io::ErrorKind::NotFound => return false,
_ => {}
}
}
self.canonicalize(a)
.ok()
.zip(self.canonicalize(b).ok())
.is_some_and(|(a, b)| a == b)
}
pub(crate) fn output(&mut self, cwd: &Path, path: &Path) -> Result<PathBuf, String> {
let path = cwd.join(path);
if self.metadata(&path).is_ok() {
+310 -57
View File
@@ -14,10 +14,16 @@ use std::{
fs::{self, File, OpenOptions},
io::{self, BufRead, BufReader, Seek, Write},
path::{Path, PathBuf},
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
mpsc,
},
time::Duration,
};
use texrra_tex_core::artifacts::{ArtifactLedger, file_version};
use texrra_tex_core::execution::{
JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination,
Cancellation, JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination,
};
use texrra_tex_core::resources::{FileWorld, LoadedResource, ResourceKind, ResourceVersion};
@@ -145,6 +151,8 @@ struct DraftLedger {
pub struct Files {
world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: Option<crate::native_regex::Worker>,
cwd: PathBuf,
inputs: BTreeMap<u8, Input>,
outputs: BTreeMap<u8, Output>,
@@ -311,9 +319,13 @@ impl Files {
|| resource.path == pdf
|| existing_log.as_ref() == Some(&resource.path)
|| existing_output.as_ref() == Some(&resource.path)
|| preparation.same_file(&resource.path, &log_path)
|| preparation.same_file(&resource.path, &pdf)
})
|| preparation.aliases_any(
&log_path,
world.trace().reads.iter().map(|r| r.path.as_path()),
)
|| preparation
.aliases_any(&pdf, world.trace().reads.iter().map(|r| r.path.as_path()))
|| preparation.same_file(source, &log_path)
|| preparation.same_file(&pdf, &log_path)
{
@@ -348,9 +360,8 @@ impl Files {
protected.extend(project.immutable_paths().map(Path::to_path_buf));
protected.sort();
protected.dedup();
if project
.immutable_paths()
.any(|p| preparation.same_file(p, &pdf) || preparation.same_file(p, &log_path))
if preparation.aliases_any(&pdf, project.immutable_paths())
|| preparation.aliases_any(&log_path, project.immutable_paths())
{
return Err("native output would overwrite an atomic project input".into());
}
@@ -359,11 +370,8 @@ impl Files {
preparation.same_file(p, source)
|| preparation.same_file(p, &pdf)
|| preparation.same_file(p, &log_path)
|| world
.trace()
.reads
.iter()
.any(|r| preparation.same_file(p, &r.path))
|| preparation
.aliases_any(p, world.trace().reads.iter().map(|r| r.path.as_path()))
}) {
return Err(
"native artifact metadata must differ from protected inputs and outputs".into(),
@@ -402,10 +410,13 @@ impl Files {
let immutable_claims: Vec<_> = ledger
.paths()
.filter(|path| {
protected
.iter()
.chain(std::iter::once(&log_path))
.any(|p| preparation.same_file(p, path))
preparation.aliases_any(
path,
protected
.iter()
.chain(std::iter::once(&log_path))
.map(PathBuf::as_path),
)
})
.map(Path::to_owned)
.collect();
@@ -417,11 +428,13 @@ impl Files {
.map(|p| p.generated().map(Path::to_path_buf).collect())
.unwrap_or_default();
for path in declared {
if protected
.iter()
.chain(std::iter::once(&log_path))
.any(|p| preparation.same_file(p, &path))
{
if preparation.aliases_any(
&path,
protected
.iter()
.chain(std::iter::once(&log_path))
.map(PathBuf::as_path),
) {
return Err("atomic generated role aliases a protected input or output".into());
}
let observed = file_version(&path);
@@ -536,6 +549,8 @@ impl Files {
preparation.phase = HostPreparationPhase::Ready;
Ok(Self {
world: stored_world.take().unwrap(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: None,
cwd,
inputs: BTreeMap::new(),
outputs: BTreeMap::new(),
@@ -842,10 +857,13 @@ impl Files {
Ok(())
}
fn is_protected(&self, path: &Path) -> bool {
self.protected
.iter()
.chain(std::iter::once(&self.log_path))
.any(|p| self.same_file(p, path))
self.runtime_observations.borrow_mut().aliases_any(
path,
self.protected
.iter()
.chain(std::iter::once(&self.log_path))
.map(PathBuf::as_path),
)
}
fn observe_resource(&mut self, kind: ResourceKind, resource: &LoadedResource) {
let path = &resource.version.path;
@@ -1127,7 +1145,9 @@ impl Files {
pub(crate) fn seal_draft(
mut self,
pdf: Option<PreparedOutput>,
) -> Result<DraftPublication, String> {
queue: &DraftSyncQueue,
cancellation: &Cancellation,
) -> Result<Option<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());
@@ -1156,6 +1176,105 @@ impl Files {
.filter(|(path, _)| !draft.generated.contains_key(*path))
.map(|(path, version)| (path.clone(), version.clone()))
.collect::<BTreeMap<_, _>>();
let pending = PendingDraft {
draft,
log,
pdf,
untouched,
ledger_current: self.ledger_current.clone(),
};
// The worker owns private files only. The foreground retains this
// host and its project lock until it can publish or has been cancelled.
let synced = queue.sync(cancellation, move |stop| pending.sync(stop))?;
Ok(synced.map(|synced| DraftPublication {
synced,
_host: self,
}))
}
}
#[derive(Default)]
pub(crate) struct DraftSyncQueue {
active: Arc<AtomicUsize>,
}
struct DraftSyncSlot(Arc<AtomicUsize>);
impl Drop for DraftSyncSlot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
impl DraftSyncQueue {
fn sync(
&self,
cancellation: &Cancellation,
run: impl FnOnce(&Cancellation) -> Result<Option<SyncedDraft>, String> + Send + 'static,
) -> Result<Option<SyncedDraft>, String> {
const WAIT: Duration = Duration::from_millis(5);
// Allow one obsolete sync to drain while the current draft syncs.
// If both calls are still in the OS, wait without starting more.
let slot = loop {
if cancellation.is_cancelled() {
return Ok(None);
}
let active = self.active.load(Ordering::Acquire);
if active < 2
&& self
.active
.compare_exchange(active, active + 1, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
break DraftSyncSlot(self.active.clone());
}
std::thread::sleep(WAIT);
};
let stop = cancellation.clone();
let (send, receive) = mpsc::channel();
std::thread::Builder::new()
.name("texrra-draft-sync".into())
.spawn(move || {
let _slot = slot;
let _ = send.send(run(&stop));
})
.map_err(|error| format!("start native draft sync: {error}"))?;
loop {
if cancellation.is_cancelled() {
return Ok(None);
}
match receive.recv_timeout(WAIT) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("native draft sync worker stopped".into());
}
}
}
}
}
struct PendingDraft {
log: Option<File>,
draft: DraftEffects,
pdf: Option<PreparedOutput>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
ledger_current: Option<ResourceVersion>,
}
impl PendingDraft {
fn sync(self, cancellation: &Cancellation) -> Result<Option<SyncedDraft>, String> {
if cancellation.is_cancelled() {
return Ok(None);
}
let Self {
draft,
log,
pdf,
untouched,
ledger_current,
} = self;
let mut artifacts: Vec<_> = draft.generated.into_values().collect();
let sync_pdf = || -> Result<(), String> {
if let Some(file) = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref()) {
@@ -1175,28 +1294,50 @@ impl Files {
// Flush independent files concurrently, then finish collecting all
// results before the revision gate can install any artifact.
std::thread::scope(|scope| {
let pdf_worker = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref())
.and_then(|_| std::thread::Builder::new().spawn_scoped(scope, sync_pdf).ok());
let log_worker = log.as_ref()
.and_then(|_| std::thread::Builder::new().spawn_scoped(scope, sync_log).ok());
let pdf_worker = pdf
.as_ref()
.and_then(|pdf| pdf.pending_sync.as_ref())
.and_then(|_| {
std::thread::Builder::new()
.spawn_scoped(scope, sync_pdf)
.ok()
});
let log_worker = log.as_ref().and_then(|_| {
std::thread::Builder::new()
.spawn_scoped(scope, sync_log)
.ok()
});
let generated = artifacts.iter().try_for_each(|artifact| {
if cancellation.is_cancelled() {
return Ok(());
}
OpenOptions::new()
.write(true)
.open(&artifact.staged.path)
.and_then(|file| file.sync_all())
.map_err(|error| {
format!("sync native draft {}: {error}", artifact.target.path.display())
format!(
"sync native draft {}: {error}",
artifact.target.path.display()
)
})
});
let pdf_result = pdf_worker.map_or_else(sync_pdf, |worker| {
worker.join().map_err(|_| "native draft PDF sync thread panicked".to_owned())?
worker
.join()
.map_err(|_| "native draft PDF sync thread panicked".to_owned())?
});
let log_result = log_worker.map_or_else(sync_log, |worker| {
worker.join().map_err(|_| "native draft log sync thread panicked".to_owned())?
worker
.join()
.map_err(|_| "native draft log sync thread panicked".to_owned())?
});
pdf_result.and(log_result).and(generated)
})?;
drop(log);
if cancellation.is_cancelled() {
return Ok(None);
}
artifacts.push(draft.log);
let untouched_ledger = if let Some(DraftLedger { file, staged }) = draft.ledger {
let target = &draft.ledger_target.path;
@@ -1205,7 +1346,7 @@ impl Files {
if !actual.is_file()
|| DraftFileStamp::from_metadata(&actual).map_err(|e| e.to_string())?
!= DraftFileStamp::from_metadata(&descriptor).map_err(|e| e.to_string())?
|| Some(staged.version(target)?) != self.ledger_current
|| Some(staged.version(target)?) != ledger_current
{
return Err(format!(
"native staged ledger changed: {}",
@@ -1230,12 +1371,11 @@ impl Files {
staged,
});
}
Ok(DraftPublication {
Ok(Some(SyncedDraft {
artifacts,
untouched,
untouched_ledger,
_host: self,
})
}))
}
}
@@ -1263,6 +1403,27 @@ pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result<PathBuf, String
}
impl SourceProvider for Files {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
if self.regex_worker.is_none() {
let path = self
.runtime_observations
.borrow_mut()
.environment("TEXRRA_PDF_REGEX_WORKER");
if let Some(path) = path {
self.regex_worker = Some(crate::native_regex::Worker::start(Path::new(&path))?);
}
}
match &mut self.regex_worker {
Some(worker) => worker.request(request, cancellation),
None => texrra_tex_core::execution::match_pdf_regex(request),
}
}
fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> {
Some(self.world.trace())
}
@@ -1355,7 +1516,8 @@ impl SourceProvider for Files {
self.emit_diagnostic(WriteDestination::TerminalOnly, terminal, false)
}
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
let resource = self.resource(ResourceKind::Tex, name, from)?;
let resource = self.world.read_tex_input(name, Path::new(from))?;
self.observe_resource(ResourceKind::Tex, &resource);
let path = resource.version.path;
Ok(SourceFile {
name: path.display().to_string(),
@@ -1382,10 +1544,7 @@ impl SourceProvider for Files {
Ok(resource)
}
fn file_size(&mut self, name: &str, from: &str) -> Result<Option<u64>, String> {
let Some(resource) = self
.world
.read_optional(ResourceKind::Tex, name, Path::new(from))?
else {
let Some(resource) = self.world.read_tex_input_optional(name, Path::new(from))? else {
return Ok(None);
};
self.observe_resource(ResourceKind::Tex, &resource);
@@ -1397,10 +1556,7 @@ impl SourceProvider for Files {
fn open_in(&mut self, stream: u8, name: &str, from: &str) -> Result<Option<String>, String> {
self.release_input(stream, ReleaseCause::Replaced, false);
let result = (|| -> Result<Option<InputOpened>, String> {
let Some(path) = self
.world
.resolve(ResourceKind::Tex, name, Path::new(from))?
else {
let Some(path) = self.world.resolve_tex_input(name, Path::new(from))? else {
return Ok(None);
};
let (reader, storage): (Box<dyn BufRead + Send>, InputStorage) =
@@ -1739,10 +1895,14 @@ struct DraftArtifact {
staged: PreparedOutput,
}
pub(crate) struct DraftPublication {
struct SyncedDraft {
artifacts: Vec<DraftArtifact>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
untouched_ledger: Option<DraftDestination>,
}
pub(crate) struct DraftPublication {
synced: SyncedDraft,
// The native project lock covers validation, installation and rollback.
_host: Files,
}
@@ -1757,9 +1917,12 @@ impl DraftPublication {
expose_document: impl FnOnce() -> T,
) -> Result<Option<T>, String> {
let Self {
artifacts,
untouched,
untouched_ledger,
synced:
SyncedDraft {
artifacts,
untouched,
untouched_ledger,
},
_host,
} = self;
session.publish_current(revision, || {
@@ -1914,8 +2077,7 @@ impl PreparedOutput {
write: impl FnOnce(&mut File) -> Result<(), String>,
) -> Result<(Self, File), String> {
let (prepared, mut file) = Self::create(output)?;
write(&mut file)
.map_err(|error| format!("stage output {}: {error}", output.display()))?;
write(&mut file).map_err(|error| format!("stage output {}: {error}", output.display()))?;
Ok((prepared, file))
}
@@ -1979,7 +2141,15 @@ impl PreparedOutput {
let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id()));
if path != output {
match create(&path) {
Ok(value) => return Ok((Self { path, pending_sync: None }, value)),
Ok(value) => {
return Ok((
Self {
path,
pending_sync: None,
},
value,
));
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(format!("stage output {}: {error}", output.display()));
@@ -2110,9 +2280,14 @@ mod generated_file_tests {
assert!(!staged.exists());
assert!(!host.draft_paths().contains_key(&ledger_path));
host.finish().unwrap();
let sealed = host.seal_draft(None).unwrap();
let queue = DraftSyncQueue::default();
let cancellation = Cancellation::default();
let sealed = host
.seal_draft(None, &queue, &cancellation)
.unwrap()
.unwrap();
assert_eq!(
sealed.untouched_ledger.as_ref().unwrap().version,
sealed.synced.untouched_ledger.as_ref().unwrap().version,
original_version
);
let permissions = fs::metadata(&ledger_path).unwrap().permissions();
@@ -2151,7 +2326,7 @@ mod generated_file_tests {
let staged = host.draft_paths()[&ledger_path].clone();
let size = fs::metadata(&staged).unwrap().len() as usize;
fs::write(&staged, vec![b'x'; size]).unwrap();
let error = host.seal_draft(None).err().unwrap();
let error = host.seal_draft(None, &queue, &cancellation).err().unwrap();
assert!(error.contains("native staged ledger changed"), "{error}");
assert!(!staged.exists());
assert_eq!(fs::read(&ledger_path).unwrap(), original_ledger);
@@ -2169,8 +2344,14 @@ mod generated_file_tests {
let mut pdf = PreparedOutput::write_for_draft(&output, b"new PDF").unwrap();
let path = pdf.path.clone();
pdf.pending_sync = Some(File::open("/dev/null").unwrap());
let error = host.seal_draft(Some(pdf)).err().unwrap();
assert!(error.contains("sync native draft") && error.contains("job.pdf"), "{error}");
let error = host
.seal_draft(Some(pdf), &queue, &cancellation)
.err()
.unwrap();
assert!(
error.contains("sync native draft") && error.contains("job.pdf"),
"{error}"
);
assert!(!path.exists());
assert_eq!(fs::read(&output).unwrap(), b"already published PDF");
assert_eq!(fs::read(&log).unwrap(), original_log);
@@ -2180,6 +2361,53 @@ mod generated_file_tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn cancelled_draft_sync_releases_the_job_before_private_io_completes() {
let queue = Arc::new(DraftSyncQueue::default());
let cancelled = Cancellation::default();
let (entered, entry) = mpsc::channel();
let (release, held) = mpsc::channel();
let (returned, result) = mpsc::channel();
let (completed, drained) = mpsc::channel();
let old = std::thread::spawn({
let queue = queue.clone();
let cancelled = cancelled.clone();
move || {
let sealed = queue.sync(&cancelled, move |_| {
entered.send(()).unwrap();
held.recv_timeout(Duration::from_secs(5)).unwrap();
completed.send(()).unwrap();
Ok(None)
});
returned.send(sealed).unwrap();
}
});
entry.recv_timeout(Duration::from_secs(3)).unwrap();
cancelled.cancel();
assert!(
result
.recv_timeout(Duration::from_secs(1))
.unwrap()
.unwrap()
.is_none()
);
old.join().unwrap();
assert_eq!(queue.active.load(Ordering::Acquire), 1);
queue
.sync(&Cancellation::default(), {
let queue = queue.clone();
move |_| {
assert_eq!(queue.active.load(Ordering::Acquire), 2);
Ok(None)
}
})
.unwrap();
assert!(matches!(drained.try_recv(), Err(mpsc::TryRecvError::Empty)));
release.send(()).unwrap();
drained.recv_timeout(Duration::from_secs(3)).unwrap();
}
#[test]
fn stream_journal_distinguishes_pinned_bytes_live_handles_replacement_and_finish() {
let root = root();
@@ -2427,6 +2655,31 @@ mod generated_file_tests {
assert!(p.ledger.as_ref().unwrap().version.is_none());
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn scanning_aliases_rechecks_a_changed_target() {
let root = root();
let target = root.join("target");
let replacement = root.join("replacement");
let peer = root.join("main.tex");
let other = root.join("other");
fs::write(&target, b"original").unwrap();
fs::write(&other, b"other").unwrap();
fs::hard_link(&peer, &replacement).unwrap();
let switched = std::cell::Cell::new(false);
let candidates = [other.as_path(), peer.as_path()]
.into_iter()
.inspect(|candidate| {
if *candidate == peer && !switched.replace(true) {
fs::rename(&replacement, &target).unwrap();
}
});
let mut preparation = HostPreparation::default();
assert!(preparation.aliases_any(&target, candidates));
assert_eq!(fs::read(&target).unwrap(), fs::read(&peer).unwrap());
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn preparation_alias_rejection_records_actual_hardlink_identity() {
+4
View File
@@ -97,6 +97,7 @@ impl PreviewState {
pages: &[DisplayList],
pdf: Option<&Arc<[u8]>>,
visible: Option<u64>,
check: impl Fn() -> Result<(), String>,
) -> Result<PreviewUpdate, String> {
let pdf = PdfPreview {
bytes: pdf,
@@ -107,15 +108,18 @@ impl PreviewState {
visible
} else if visible.is_some() && visible == self.previous_revision {
for &index in &self.changed {
check()?;
rendered.push(self.render_page(index, &pages[index], &pdf)?);
}
visible
} else {
for (index, page) in pages.iter().enumerate() {
check()?;
rendered.push(self.render_page(index, page, &pdf)?);
}
None
};
check()?;
Ok(PreviewUpdate {
base_revision,
revision,
+99
View File
@@ -0,0 +1,99 @@
use std::{
io::{BufRead, BufReader, Write},
path::Path,
process::{Child, Command, Stdio},
sync::mpsc::{self, Receiver, Sender},
thread::{self, JoinHandle},
time::Duration,
};
use texrra_tex_core::execution::{Cancellation, RegexOutcome, RegexRequest};
pub(crate) struct Worker {
child: Child,
requests: Option<Sender<Vec<u8>>>,
answers: Receiver<Result<RegexOutcome, String>>,
pipe: Option<JoinHandle<()>>,
}
impl Worker {
pub(crate) fn start(path: &Path) -> Result<Self, String> {
let mut child = Command::new(path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("pdfTeX regex worker launch: {e}"))?;
let mut input = child.stdin.take().expect("worker stdin is piped");
let mut output = BufReader::new(child.stdout.take().expect("worker stdout is piped"));
let (requests, waiting) = mpsc::channel::<Vec<u8>>();
let (answer, answers) = mpsc::sync_channel(1);
let pipe = thread::spawn(move || {
let mut response = Vec::new();
for request in waiting {
let result = (|| {
input.write_all(&request).map_err(|e| e.to_string())?;
input.write_all(b"\n").map_err(|e| e.to_string())?;
response.clear();
if output
.read_until(b'\n', &mut response)
.map_err(|e| e.to_string())?
== 0
{
return Err("pdfTeX regex worker closed its response pipe".into());
}
serde_json::from_slice::<Result<RegexOutcome, String>>(&response)
.map_err(|e| format!("pdfTeX regex response: {e}"))?
})();
if answer.send(result).is_err() {
break;
}
}
});
Ok(Self {
child,
requests: Some(requests),
answers,
pipe: Some(pipe),
})
}
pub(crate) fn request(
&mut self,
request: &RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
let payload = serde_json::to_vec(request).map_err(|e| e.to_string())?;
self.requests
.as_ref()
.ok_or("pdfTeX regex worker has stopped")?
.send(payload)
.map_err(|_| "pdfTeX regex worker has stopped")?;
loop {
if cancellation.is_some_and(Cancellation::is_cancelled) {
self.stop();
return Err("native compilation cancelled".into());
}
match self.answers.recv_timeout(Duration::from_millis(2)) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("pdfTeX regex worker lost its response pipe".into());
}
}
}
}
fn stop(&mut self) {
self.requests.take();
if let Some(pipe) = self.pipe.take() {
let _ = self.child.kill();
let _ = self.child.wait();
let _ = pipe.join();
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop();
}
}
+187
View File
@@ -367,6 +367,193 @@ fn atomic_definition(p: &Path, revision: u64, body: &str) -> ProjectDefinition {
}
}
#[test]
fn resumed_suffix_reuses_search_for_unchanged_paragraphs() {
let p = directory("resumed-paragraphs");
let original = "The first paragraph contains a few distinct words.";
let changed =
"The first paragraph now occupies a different number of lines in the measured box.";
let body = format!(
r"
\hsize=82pt \parindent=0pt \tolerance=10000 \pretolerance=10000
\rightskip=0pt plus20pt \parfillskip=0pt plus1fil
\shipout\hbox{{Stable first page}}
\shipout\vbox{{
\noindent {original}\par
\noindent Second material remains in place while the first text changes its length.\par
\noindent Each reused break still lays out the paragraph from the current measured nodes.\par
}}
\end
"
);
let project = ProjectSnapshot::new(atomic_definition(&p, 1, &body)).unwrap();
let first_request = request(&p)
.with_project(project.clone())
.observe_generated_initial();
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let first = compiler.compile(first_request.clone()).unwrap();
assert_eq!(first.pages.len(), 2);
let edit = format!("{HEADER}{}", body.replace(original, changed));
let edited = project
.with_file_edits(
2,
BTreeMap::from([(p.join("main.tex"), Arc::from(edit.into_bytes()))]),
)
.unwrap();
let repeat = first_request.with_project(edited);
let resumed = compiler.compile(repeat.clone()).unwrap();
let full = NativeCompiler::default().compile(repeat).unwrap();
assert!(resumed.entry_checkpoint_work.reused_steps > 0);
assert!(resumed.line_break_work.reused_passes >= 2);
assert!(resumed.line_break_work.examined_edges < full.line_break_work.examined_edges);
assert_eq!(resumed.pdf, full.pdf);
assert_eq!(resumed.pages, full.pages);
assert_eq!(resumed.source_map.pages, full.source_map.pages);
assert_eq!(
resumed.execution.execution_resources,
full.execution.execution_resources
);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts() {
#[derive(Clone, Copy)]
enum Action {
Supersede,
#[cfg(unix)]
Conflict,
Publish,
}
struct WatchDraft {
compiler: NativeCompiler,
p: PathBuf,
previous: Arc<CompiledDocument>,
artifacts: [Vec<u8>; 3],
update: Mutex<Option<PreviewUpdate>>,
action: Action,
}
impl CompileObserver for WatchDraft {
fn stage(&self, _: u64, _: CompileStage) -> Result<(), String> {
Ok(())
}
fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> {
assert!(Arc::ptr_eq(
&self.previous,
&self.compiler.latest().unwrap()
));
for (name, expected) in ["job.pdf", "job.log", "state.dat"]
.into_iter()
.zip(&self.artifacts)
{
assert_eq!(&fs::read(self.p.join(name)).unwrap(), expected);
}
let preview = draft.preview_since(Some(self.previous.revision()))?;
assert_eq!(
preview.pages.iter().map(|p| p.index).collect::<Vec<_>>(),
[1]
);
*self.update.lock().unwrap() = Some(preview);
match self.action {
Action::Supersede => {
self.compiler.start();
assert!(draft.preview_since(None).unwrap_err().contains("cancelled"));
}
#[cfg(unix)]
Action::Conflict => {
fs::hard_link(self.p.join("job.pdf"), self.p.join("conflicting.pdf")).unwrap();
}
Action::Publish => {}
}
Ok(())
}
}
let p = directory("provisional-preview");
let body = r"
\immediate\openout1=state.dat
\immediate\write1{ORIGINAL}
\immediate\closeout1
\shipout\hbox{Stable first page}
\shipout\hbox{Previous second page}
\end
";
let mut definition = atomic_definition(&p, 1, body);
definition.generated.insert(p.join("state.dat"));
let project = ProjectSnapshot::new(definition).unwrap();
let request = request(&p)
.with_project(project.clone())
.observe_generated_initial();
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let previous = compiler.compile(request.clone()).unwrap();
let artifacts = ["job.pdf", "job.log", "state.dat"].map(|name| fs::read(p.join(name)).unwrap());
let edit = format!(
"{HEADER}{}",
body.replace("ORIGINAL", "EDITED")
.replace("Previous second page", "Current second page")
);
let changed = project
.with_file_edits(
2,
BTreeMap::from([(p.join("main.tex"), Arc::from(edit.into_bytes()))]),
)
.unwrap();
let mut request = request.with_project(changed);
let mut cancelled = None;
for action in [
Action::Supersede,
#[cfg(unix)]
Action::Conflict,
Action::Publish,
] {
let observer = Arc::new(WatchDraft {
compiler: compiler.clone(),
p: p.clone(),
previous: previous.clone(),
artifacts: artifacts.clone(),
update: Mutex::new(None),
action,
});
request.observer = Some(observer.clone());
let result = compiler.compile_detailed(request.clone());
let update = observer.update.lock().unwrap().take().unwrap();
if !matches!(action, Action::Publish) {
let failure = result.err().unwrap();
if matches!(action, Action::Supersede) {
assert!(matches!(failure.error, CompileError::Cancelled));
assert_eq!(failure.phase, AttemptPhase::ReadyToPublish);
} else {
assert!(failure.error.to_string().contains("aliases"), "{failure:?}");
assert_eq!(failure.phase, AttemptPhase::Publishing);
fs::remove_file(p.join("conflicting.pdf")).unwrap();
}
assert!(Arc::ptr_eq(&previous, &compiler.latest().unwrap()));
assert_eq!(
["job.pdf", "job.log", "state.dat"].map(|name| fs::read(p.join(name)).unwrap()),
artifacts,
);
cancelled = Some(update);
} else {
let document = result.unwrap();
assert_eq!(
update,
document.preview_since(Some(previous.revision())).unwrap()
);
assert_eq!(update.pages, cancelled.as_ref().unwrap().pages);
assert_eq!(
document.pdf.as_deref(),
Some(fs::read(p.join("job.pdf")).unwrap().as_slice())
);
assert_eq!(fs::read(p.join("state.dat")).unwrap(), b"EDITED\n");
assert!(Arc::ptr_eq(&document, &compiler.latest().unwrap()));
}
}
fs::remove_dir_all(p).unwrap();
}
#[test]
fn library_cli_bytes_final_resource_closure_and_immutable_revision_match() {
let p = directory("closure");