Author SHA1 Message Date
gloamxun 31bf50806e Prototype cancellable GNU matching in native compilation sessions 2026-11-19 22:44:42 +08:00
22 changed files with 641 additions and 720 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",
+18 -21
View File
@@ -1,22 +1,18 @@
# texrra engine
Texrra is building a TeX engine for live editing of existing LaTeX projects.
It tracks inputs and compilation state, reuses eligible work after edits,
and publishes updated pages with source locations. The delivery targets are
a library, a CLI, and editor integration. The current Route-D implementation
is the development baseline. Upstream TeX components are candidates for reuse
where their state, file effects, and cancellation can be verified.
The [product goal](docs/NATIVE_PRODUCT_GOAL.md) defines compatibility and live
preview acceptance. The [publisher matrix](docs/PUBLISHER_TEMPLATE_MATRIX.md)
covers original journals, two-column journals, conferences, and arXiv.
Rust-native, Typst-inspired incremental LaTeX engine with a live preview
server. Typesetting is implemented in Rust; the engine does not invoke XeLaTeX,
LuaLaTeX, or pdfLaTeX. The web frontend is a separate repository,
[`texrra-web`](https://git.iloveuulove.me/gloamxun/texrra-web), served by this
engine as static files.
## Native execution bootstrap
The current Route-D entry is available through the developer CLI and the native
editor example. Its implementation and remaining work are tracked in the
[stage progress](docs/P2_M1_PROGRESS.md). The separate frontend repository
is [texrra-web](https://git.iloveuulove.me/gloamxun/texrra-web).
Route-D's native token/state kernel has a strict developer entry. Its target is
portable, complete LaTeX execution and real-time compilation; the web interface
is a test client. The full [P2-M1 stage](docs/NATIVE_FORMAT_ARTICLE_STAGE.md)
is active and incomplete; [current progress](docs/P2_M1_PROGRESS.md) records the
accepted components and remaining work.
Native fonts come from an explicit resource World. For the checked-in examples,
configure the actual TFM/PFB directories and an installed font-map directory:
@@ -44,8 +40,8 @@ canvas does not certify native pagination. There is no automatic fallback
between these targets. See [native pages and remaining device work](docs/NATIVE_PAGES.md).
INITEX starts with actual nullfont and zero layout dimensions. Non-INITEX
bootstrap loads its initial cmr10 through World. The current native job reports
missing resources directly.
bootstrap also loads its initial cmr10 through World. Missing resources fail;
the kernel does not silently use bundled fonts or run an external TeX process.
Use `--texmf-root`, resource search environment variables and `--input-policy`
for distribution/project resources; `--resource-manifest` records actual reads,
versions and negative lookups, including failed jobs. The CLI defaults to TeX
@@ -58,12 +54,13 @@ or source preprocessing. It now carries actual sized FontId resources through
text, math, geometry, SVG and PDF. Live fontdimen and em/ex affect their real
consumers; output uses actual map/encoding/PFB resources. See
[native font execution and boundaries](docs/NATIVE_FONT_EXECUTION.md).
The native editor example exercises the shared compile session and page
updates. The production HTTP routes still use the older implementation.
Format boot, active compatibility gaps, and whole-project results are tracked
in the [stage progress](docs/P2_M1_PROGRESS.md).
HTTP/project routes still use the older implementation and have not migrated
to this kernel.
[Streaming TFM keep/pass/boundary execution](docs/NATIVE_FONT_PROGRAMS.md) is
The e-TeX profile remains partial. Unmodified latex.ltx currently stops at
657:3, tracinggroups, using the actual native job target; the complete
pdflatex.ini entry now enters latex.ltx and stops at the same boundary. Neither
is a successful format boot. [Streaming TFM keep/pass/boundary execution](docs/NATIVE_FONT_PROGRAMS.md) is
connected to actual lists. [Owned discretionary branches and actual ligature
hyphenation/reconstitution](docs/NATIVE_DISCRETIONARIES.md) now feed line breaking,
packing, diagnostics and output. [Two-pass mathematical noad ligature/kern and
+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"
@@ -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;
@@ -215,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,
@@ -377,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,
@@ -844,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)?;
@@ -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 }))
}
@@ -8,7 +8,7 @@ use std::{
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)]
+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)))
}
@@ -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
@@ -918,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),
@@ -109,7 +109,10 @@ impl ProjectSnapshot {
revision: u64,
edits: BTreeMap<PathBuf, Arc<[u8]>>,
) -> Result<Arc<Self>, String> {
let mut next = self.next_revision(revision)?;
self.validate()?;
let mut next = self.clone();
next.version.revision = revision;
next.validated = OnceLock::new();
for (path, data) in edits {
let previous = next.files.get_mut(&path).ok_or_else(|| {
format!("atomic edit requires an immutable file: {}", path.display())
@@ -121,44 +124,6 @@ impl ProjectSnapshot {
next.seal()
}
/// Set or remove immutable files in a single revision. New files require
/// a declared parent directory. Replacing a file preserves its captured
/// modification time, and removing a file discards it.
pub fn with_file_changes(
&self,
revision: u64,
changes: BTreeMap<PathBuf, Option<Arc<[u8]>>>,
) -> Result<Arc<Self>, String> {
let mut next = self.next_revision(revision)?;
for (path, data) in changes {
if let Some(data) = data {
if !next
.file(&path)
.is_some_and(|previous| Arc::ptr_eq(&previous.data, &data))
{
next.files.insert(path.clone(), Self::capture(path, data));
}
} else {
if next.files.remove(&path).is_none() {
return Err(format!(
"atomic removal requires an immutable file: {}",
path.display()
));
}
next.file_modifications.remove(&path);
}
}
next.seal()
}
fn next_revision(&self, revision: u64) -> Result<Self, String> {
self.validate()?;
let mut next = self.clone();
next.version.revision = revision;
next.validated = OnceLock::new();
Ok(next)
}
fn capture(path: PathBuf, data: Arc<[u8]>) -> SnapshotFile {
SnapshotFile {
version: ResourceVersion {
@@ -196,12 +161,6 @@ impl ProjectSnapshot {
/// Whether both snapshots give lookups the same configuration, names,
/// aliases and roles. The bytes and captured times are separate inputs.
pub fn same_lookup_namespace(&self, next: &Self) -> Result<bool, String> {
Ok(self.same_lookup_configuration(next)? && self.files.keys().eq(next.files.keys()))
}
/// Whether search settings, directories, aliases and generated roles agree.
/// File creation and removal can still change lookup results.
pub fn same_lookup_configuration(&self, next: &Self) -> Result<bool, String> {
self.validate()?;
next.validate()?;
Ok(self.configuration == next.configuration
@@ -209,7 +168,8 @@ impl ProjectSnapshot {
&& self.directories == next.directories
&& self.aliases == next.aliases
&& self.generated_roots == next.generated_roots
&& self.generated == next.generated)
&& self.generated == next.generated
&& self.files.keys().eq(next.files.keys()))
}
pub fn generated(&self) -> impl Iterator<Item = &Path> {
self.generated.iter().map(PathBuf::as_path)
@@ -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]"))
);
}
+2 -3
View File
@@ -25,9 +25,8 @@ Tectonic 的 XeTeX 入口在进程级锁内运行,桥接层能提供输入输
[Tectonic 桥接层](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/bridge_core/src/lib.rs#L271-L288)
原样 A4 在连续子文件编辑中,取消旧作业的浏览器观测 p95 已低于100 ms。
当前两轮原样 A4 主文件编辑的可见 p95 为224.0和208.6 ms,仍需达到100 ms
门禁。评估上游执行入口时,分别测量编辑到可见页面、可恢复的状态范围与
全量一致性,并记录完整重新执行的成本作为基线。
新编辑到可见页面的 p95 仍高于250 ms。接下来分解编译准备、执行复用和页面
交付,继续按固定预算及逐版本全量一致性验收。
[阶段测量与回执](P2_M1_PROGRESS.md)
## 2026-11-11 总目标重新确认
-17
View File
@@ -66,23 +66,6 @@ profile、入口和执行限制仍是显式请求参数。没有单独的编辑
下一步仍需完整I/O效果/物理alias/句柄恢复契约、checkpoint、失效传播、执行/布局
复用和局部页面发布。当前仍为全量执行,不代表完整 LaTeX 或实时性能已经通过。
## 原子文件增删与检查点
`ProjectSnapshot::with_file_changes` 接收一组同版本的绝对逻辑路径,`Some`
提交字节,`None` 删除已存在的不可变文件。新增文件使用已声明的父目录,
由快照校验资源覆盖范围、别名和生成角色。旧快照继续持有原字节。
替换现有文件沿用已捕获的修改时间,删除同时清除对应时间记录。
检查点选择要求查找配置、目录、别名和生成角色仍相同,并核对实际读取的版本。
文件集合变化时,准备新作业后重放前缀,然后逐项核对实际查找记录。这样即使
`\pdffilesize` 返回值相同,候选顺序和最终来源变化也能使检查点失效。
重放发生在原有暂存作业中,失效后按新快照全量执行。
`examples/native_editor` 的 `/preview` 接受 `files` 里的 JSON 字符串和 `null`。
启动参数可以声明当前缺失的可编辑文件,其父目录需在项目下存在。入口文件受保护,
`/project` 返回当前版本存在的可编辑文件。原字符串写入和 `source` 请求继续使用
同一共享编译接口。
## 2026-11-16:真实TeX流效果与清理(阶段未完成)
[流效果契约](NATIVE_STREAM_EFFECTS.md)记录实际顺序、唯一句柄、snapshot/file身份、
+2 -272
View File
@@ -655,12 +655,7 @@ SHA-256 为 `d2fa1a80f378445e1dccc29378cfc1546d94e823a49f460bffda827ba5790b0d`
回执 `a3-shared/test.log` 与 `a3-manual/test.log` SHA-256 为
`34fd27652fb0afb59deaee5b68c0dcede8bd2d8e38460746031f134d698683f6`、
`f4c65f08d98a2c15544dde3f3bd82cc57f7f139fbd50782541a04e65cc407d03`。
同一优化程序已完成14项原样模板复验。原版工具生成14份 PDF,原生生成
5份,成功项的页数、词框和逐轮 aux 与各自前次结果一致。逐项回执见
[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。同一补丁的全工作区结果为
1626项通过、零失败,两项标记为单独运行的 A3 已使用优化二进制通过。
`target/p4-alias-scan-identity/workspace.log` 的 SHA-256 为
`127a150974936c12a2545f26ca8c21b9f1c0327416d2b53d807e3ae25af0a0cd`。
完整工作区和原样模板复验在同一补丁上运行。
为验证可停止的匹配方式,用 GNU 正则子进程独立测量管道往返。6个对照
覆盖最长选择、反向引用、字节位置、大小写、无匹配和模式错误。60次
@@ -668,272 +663,7 @@ SHA-256 为 `d2fa1a80f378445e1dccc29378cfc1546d94e823a49f460bffda827ba5790b0d`
耗时1.360 ms,旧作业未产生匹配答复,随后新的 helper 返回实际匹配。
`target/p3-pdfmatch-worker-probe/receipt.json` 的 SHA-256 为
`492bd9a411e6547b41bf294061e45c8c79567107e4f8d959e92a2843a5cf170a`。
另将旧候选真实编译 arXiv、ACL 与 NeurIPS 时的165次请求原样重放至
独立进程,三个样稿各55次。匹配状态、每个捕获及其字节位置全部一致。
`target/p3-pdfmatch-worker-probe/publisher/receipt.json` 的 SHA-256 为
`df24011752225937af162b6faa8c6f9bd8a35e609653dd472f50d4004adafc3c`。
隔离候选已用真实原生 CLI 各运行 arXiv、ACL 与 NeurIPS,三个样稿
均实际委托 GNU 子进程处理55次,完整调用记录与旧进程内实现逐字节一致,
继续执行到 `\MT@protrudechars`。真实编辑会话的受控测试中,旧作业在
匹配期间被新编辑取消,收到409响应并回收阻塞子进程,单次观察为89.3 ms。
新版本复用824404 / 904155步并正常发布。PDF、SVG、来源映射和 aux 均与
独立零复用全量一致。3项 pdfTeX 语义与检查点对照通过。
回执见 `target/p3-pdfmatch-cancellable-worker`,`publisher/receipt.json`
和 `editor-cancel-v2/receipt.json` 的 SHA-256 分别为
`4953d4b0d89952f79168011232d0319837228661226d8b6fefebac29e544ea4b`、
`998b6c49c4a5adde83921ae6501a6780d53e27b2756a9282a0f1971870891a37`。
候选需配置 GNU 辅助进程路径。已推送隔离分支
`experiment/cancellable-pdftex-regex` 的 `31bf508`,主线格式版本是27。
### 上游 pdfTeX 的实时预览边界
固定 pdfTeX 1.40.29、原样 A4 和已核对的 LaTeX 格式,用同样的正文
编辑序列分别做30次主文件、30次子文件修改。pdfTeX 每次执行并生成含
SyncTeX 的 PDF,再经 Poppler 生成真实 SVG。逐次核对文本和 aux,最后
一次与独立全量的词框、SVG 和 aux 一致。此轮与旧工作区编译并行,
I/O 压力较高,时延仅保留为有负载的记录。记录没有浏览器时间和
可恢复执行状态,不能作为实时门禁结果。
`target/p4-upstream-preview-boundary/warm-reference/receipt.json` 的
SHA-256 为 `154d1266ab6ea6c8f9be22f783384f57411f0efeea8e9d6c1576c9eebfb8249e`。
采用 TeX Live 发布的 `mylatexformat` 对原样 A4 实际保存导言区并恢复。
源文件字节保持原样,恢复后正文、分文件输入和 SyncTeX 均进入真正的
pdfTeX 作业。相同方法在14份原样项目中有10份成功,共58页。成功项的
灰度页面、字词位置、嵌入字体、项目文件来源和 aux 均与全量一致;
四份的失败位置在[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。
[CTAN 的 mylatexformat](https://ctan.org/pkg/mylatexformat)
在专门的导言区依赖样例中,未找到的 `settings.tex` 缺席于 `.fls`。
新增它后,复用旧图像保留旧标签,标准全量得到新标签,重新保存格式后
再次一致。Kpathsea 实际搜索日志能看见同一请求从无结果到相对文件,
需把它与配置、文件版本和效果一起纳入复用检查。回执
`snapshot-missing-dependency/receipt.json` 的 SHA-256 为
`2a0ded450e801191b66a7bd222bd3262180ffa17932e758b8b985a478cc93594`,
原始查找记录在 `negative-lookup-trace`。
[Kpathsea 查找入口](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/kpathsea/tex-file.c#L939-L959)
### A4 配对时延与页面交付
上游标准编译与导言区恢复分别做30次主文件、30次子文件正文编辑。
每次核对真实 PDF 文本、SVG、aux 和项目文件 SyncTeX。复验在浏览器
实验退出后独立运行,记录从提交 pdfTeX 到真实 SVG 生成的台架耗时。
| 编辑文件 | 标准 p50 / p95 (ms) | 恢复 p50 / p95 (ms) |
| --- | ---: | ---: |
| 主文件 | 154.9 / 178.2 | 145.8 / 233.0 |
| 子文件 | 150.5 / 189.9 | 148.2 / 229.3 |
逐版本等价。独立轮 p50 略减,p95 上升。较高 I/O 压力下的首轮得到
不同的 p95 方向。两轮均测量 SVG 就绪时间,覆盖上游执行与输出阶段。
`target/p4-upstream-preview-boundary/paired-a4{,-alone}/receipt.json`
的 SHA-256 分别为
`52d0ca5a24a6cc53b011b7610bff6e23e233b35413c275d5d763d6a081c12f48`、
`1bf495a1bfe54de5a16d9c2993bc3e295808e968b3232745b80ba63319ce0a00`。
另用两套 Edge 会话、同一个优化二进制和原样 A4 做连接选项对照。
每套各30次主文件与30次子文件编辑,逐次核对实际执行/复用步数、
PDF、SVG、来源和最终 aux。实测24个基线 TCP 连接保持 TCP_NODELAY=0,
候选21个 TCP 连接均从0切到1。浏览器请求剩余时延 p50 在主文件
为80.0 → 78.8 ms,子文件为75.1 → 75.0 ms。可见 p95 两类方向不同,
因此现有数据不支持据此改动编辑端传输。回执
`target/p4-http-nodelay/run-1/receipt.json` 的 SHA-256 为
`879cb3ab850209eae3558558011391d9880d281073febe2fff16a934691e9cb3`。
### 原子文件增删和实际查找
在隔离的上游导言区实验中,通过结构化 Kpathsea 调用核对了10个版本。
正文和无关文件变更继续复用。前缀依赖新增、同名高优先级替换、改字节、
删除回退或恢复缺失均触发重建。每版 SVG、aux 和项目内 SyncTeX 与
全量一致。只读范围以外,实际在导言区创建并关闭输出的样例被探针标为
不可复用。上游回执 `target/p4-upstream-lookup-contract/synthetic-session/receipt.json`
的 SHA-256 为 `9232c1558faed10fc7fe8206be990f25ae4fee590bc8f7c045ec41828a6f79f8`。
原生 Route-D 已接入原子文件增删。10次版本对照覆盖未知变已知、查找
优先级、按路径删除后回落、已读字节变化,以及同尺寸文件改变来源。
三次增删无关文件各复用162步并重放6项真实宿主调用。所有版本 PDF、
SVG、来源映射、TeX 执行和 aux 与零复用一致。3项定向检查点测试通过。
日志 `target/p4-checkpoint-file-changes/guard-tests-v2.log` 的 SHA-256 为
`0619f4200c17f8d58f23b84bbad6a18c8fd622730bb45cbe0bbf31dc0b87a252`。
同一优化版编辑端对带真实 LaTeX 格式的 A4 派生项目运行6次文件提交。
无关文件增删各复用589138 / 645020步,页面更新列表为空。新增依赖及
删除后重建触发全量。已有依赖改写和删除分别从依赖读取前的检查点
复用212230步。四次依赖变动均更新第1页。每次 PDF、SVG、归一化
来源映射和真实 aux 与独立零复用版本一致。编辑端还核对了未声明路径、
移除入口和删除不存在文件的拒绝结果。回执
`target/p4-checkpoint-file-changes/editor-run-v2/receipt.json` 的 SHA-256 为
`aeb8f77618438d2272bdd501e618e1969ee682b49035626997cbc343e9b94d8e`。
同一源码的两项原样 A3 单独通过。共享会话两次编辑复用
794348 / 870724步,重放61项宿主调用,各更新第7页。手动重放跳过
770678 / 870728步,重放59项调用,两次编辑的8页、PDF 和 aux 各与
独立全量一致。记录 `target/p4-checkpoint-file-changes/a3/{shared,manual}.log`。
完整工作区1627项通过、零失败,两项标记的真实 A3 已单独通过。
完整日志 `target/p4-checkpoint-file-changes/workspace.log` 的 SHA-256 为
`2078770f89397c8a08a4beedad4ebd6ba9c73cd605ba4f1b8341149605bdea87`。
原样模板参考14份、原生5份。Springer Nature 首次超时后用同一输入重跑
成功,arXiv 和 APS 也通过同日词框对照。
[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)
原样 A4 两版分别用 Edge 测量30次主文件和30次子文件编辑。每轮
执行与复用步数、页更新、PDF、SVG、来源映射以及最终 aux 一致。
最后版编辑缓冲区在独立会话用同一优化版零复用编译,再次核对输出相同。
| 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 新版可见 p50 / p95 (ms) |
| --- | ---: | ---: |
| 主文件正文 | 210.6 / 391.7 | 209.9 / 335.4 |
| 子文件正文 | 186.0 / 260.0 | 188.2 / 274.6 |
两类可见 p95 方向不同,100 ms门禁仍待通过。峰值 RSS 为601864与
602268 KiB。浏览器回执 `edge/run-1/receipt.json` 的 SHA-256 为
`98a9a49bc43b18e5b4b45bdae083d8fd1b3e6ee6f27cf40f9e719877de66f7cb`,
独立全量回执 `full-equivalence/receipt.json` 为
`abd248f1f2ba863c4c5e939460c83cae90d94698abd7728c890feea3731288e1`。
均在 `target/p4-checkpoint-file-changes` 下。
[项目快照与编辑接口](NATIVE_PROJECT_INPUTS.md)
### 检查点命令绑定的复制成本
当前原样 A4 的24次主文件热编辑共采集554个进程 CPU 样本。完整状态
指纹及资源内容处理仍占较大比例,主要符号包括55个 SipHash 写入、
48个 SHA-256 压缩块、42个宏替换列表哈希、26个状态统计、24个
`statx`,以及14个命令绑定树复制。采样回执
`target/p4-command-table-live-profile/original-a4/symbolized.json` 的 SHA-256 为
`752873ed167f168240cbcddf6936692266e6818a5dff597375ed23981cee330c`。
隔离候选在检查点共享完整命令绑定树,定义变化时才复制。481项核心
测试通过。两版的 schema 27 小格式文件逐字节相同,能双向加载,且
产出相同的 PDF。固定时钟的原样 A4 派生故障探针从旧实际格式执行
591745步,两版的进出状态指纹完全一致。记录
`target/p4-cow-command-table/wire-equivalence/receipt.json` 的 SHA-256 为
`14ae21c48752680b0d5dca3b6d788d8b3cc36cf5abf26173d0c51349667f55cd`。
同规格的候选 CPU 采样共546个样本,其中16个命令绑定树复制,执行
p50 为60.5 ms,基线为61.1 ms。候选采样回执 SHA-256 为
`8a44ef16a6f72493209f464e1bd63372ded4539456ed65a5504c846cc3e07fd8`。
两轮 Edge 对照交换两版的测量顺序,每版每轮各测30次不同主文件和
30次不同子文件编辑,逐次核对执行与复用步数、页面、PDF、SVG、
来源映射和最终 aux。
| 轮次 | 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 整表共享可见 p50 / p95 (ms) |
| --- | --- | ---: | ---: |
| 1 | 主文件正文 | 200.4 / 261.7 | 204.4 / 234.3 |
| 1 | 子文件正文 | 184.8 / 237.4 | 186.6 / 221.5 |
| 2 | 主文件正文 | 248.1 / 516.6 | 248.9 / 433.3 |
| 2 | 子文件正文 | 220.7 / 506.2 | 217.4 / 470.0 |
两个最终编辑缓冲区都用各自独立启动的会话、同一候选二进制全量
编译,复用步数为零。PDF、SVG、来源映射和 aux 均与各自增量结果
一致。两份 `target/p4-cow-command-table/full-equivalence-{1,2}/receipt.json`
同为 SHA-256 `421c2505e10f98d3356b75e651be680ca6825cc0756e914c35fd4f07a8835b5f`。
两轮可见 p95 均下降,中位数变化小。系统 I/O 等待显著,两轮
进入时的 I/O pressure some avg10 分别为28.21%和62.33%。
100 ms 正式门禁仍待达到。CPU 采样未观察到整树复制减少。整表方案
保留在隔离工作树。两轮浏览器回执
`target/p4-cow-command-table/edge/run-{1,2}/receipt.json` 的 SHA-256 分别为
`6f49f1e2a1477d8db600831dbd3f87b15e4b4c1c7f716018bcdcda587a2e2e84` 与
`0eda67d80964bfefe4fe17946e7622c00ca450520d70837347473bc950e055c6`。
隔离分桶候选按命令名有序划分绑定,只复制被写入的树。481项核心
测试通过。实际小格式逐字节保持一致并双向加载,旧 LaTeX 格式
运行同一 A4 派生探针的591745步及两条状态指纹完全一致。候选补丁
SHA-256 为 `c3caaf5432ae3f0e7c019d88e46226b1aa7266dc40c12835cb0d95eaaf74fbbb`。
回执 `target/p4-sharded-command-bindings/wire-equivalence/receipt.json`
的 SHA-256 为 `b9610fc43a21f4d8cf42ad4441998e810b909c9989f4951d64e3618c384569a3`。
该次24条热编辑的 CPU 采样中,命令树复制样本占22/1325,基线为
14/554。两次采样的运行耗时与当时负载相差明显,该比例只用于定位。
在同规格的两轮 Edge 配对中,每版每轮各30次不同主文件和30次
不同子文件编辑,逐次核对执行和复用步数、页更新、PDF、SVG、
来源映射与最终 aux。两轮最后一版各用独立会话零复用全量再次
核对一致。
| 轮次 | 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 分桶候选可见 p50 / p95 (ms) |
| --- | --- | ---: | ---: |
| 1 | 主文件正文 | 233.3 / 479.2 | 250.8 / 486.9 |
| 1 | 子文件正文 | 231.4 / 366.4 | 224.5 / 440.7 |
| 2 | 主文件正文 | 208.8 / 392.9 | 204.1 / 240.0 |
| 2 | 子文件正文 | 182.1 / 222.6 | 184.5 / 300.1 |
主文件 p95 变化方向不一致,子文件两轮均回退。峰值 RSS 各比基线
少3920和3720 KiB。分桶方案保留在隔离工作树。两轮浏览器回执
`target/p4-sharded-command-bindings/edge/run-{1,2}/receipt.json` 的 SHA-256 为
`899d4c3eeab8ecb82dd26afbcc3e0c76409ce8a17b9addfdeaeb8738cb981b64` 与
`446bc8fb666a45a01b79fb262f25221aa02ba2733ef78fea55dffab808ff2cee`。
两轮独立全量回执 `full-equivalence-{1,2}/receipt.json` 的 SHA-256
均为 `375fd7d1725e323cdc6ebd06ed02fc6d69c75c3633d9de57d6952561424404a5`。
对原样 A4 的13次热编辑定向获取 SHA-256 调用栈。捕获的12条
调用均来自自动续跑后 `RevisionExecution::from_execution` 对扫描源
计算内容指纹。该探针在捕获点暂停进程,证据用于定位调用方。
`target/p4-checkpoint-callchains/sha-blocks-a4/attribution.json`
记录12份原始栈的摘要,SHA-256 为
`69d48602bdb88f084a3ac5cf65d8b9c9b312ee717d7a39444230dcbd8fba5440`。
### 恢复检查点后复用源内容指纹
候选在同一会话恢复检查点后,源 ID、名称和实际扫描字节完全一致才
复用上一版的指纹,其他源重新计算。502项定向回归通过。两项原样 A3
单独通过,共享会话的两次编辑各跳过794348步,重放61项宿主调用,
仅更新第7页。日志 `target/p4-reuse-source-versions/a3/{shared,manual}.log`。
同规格的24次主文件热编辑采样中,基线590个 CPU 样本中有52个
SHA-256 样本,候选597个中有30个。执行 p50 为65.2与66.1 ms。
当时有原样 A3 验证运行,CPU 样本用于比较热点。基线及候选的
`target/p4-reuse-source-versions-profile{,-baseline}/original-a4/symbolized.json`
各自 SHA-256 为
`1c61b8a0b1a4349401ef493f392c41bb9bf7132e79f345138b289f0be5190c49`(基线)和
`1cc74b607766bfbd4da3fd0d7f9c3b0f15732b207e92f2e64256cf67d14e1279`(候选)。
原样 A4 两轮 Edge 配对各有30次不同主文件及30次不同子文件编辑。
第二轮按暂停前的反向配对顺序从新会话完整重跑,原中断目录保留
97次观测。逐次执行步数、复用步数、页更新、PDF、SVG、来源映射
和最终 aux 一致。两轮最后一版在各自独立的同版本会话中全量编译,
PDF、SVG、来源和 aux 与各自的增量版本一致。
| 轮次 | 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 候选可见 p50 / p95 (ms) |
| --- | --- | ---: | ---: |
| 1 | 主文件正文 | 230.6 / 353.2 | 224.7 / 335.5 |
| 1 | 子文件正文 | 205.4 / 337.7 | 199.9 / 345.1 |
| 2 | 主文件正文 | 213.7 / 312.9 | 211.1 / 242.5 |
| 2 | 子文件正文 | 195.5 / 275.4 | 184.8 / 248.4 |
候选执行 p50 在两轮主文件编辑分别下降2.5和0.6 ms,子文件分别
下降4.1和3.0 ms。两轮 I/O 负载不同,首轮部分样本与 A3 验证重叠。
主文件100 ms门禁仍待达到。第二轮候选峰值 RSS 为603156 KiB。
浏览器回执 `target/p4-reuse-source-versions/edge/{run-1,run-2-resumed}/receipt.json`
的 SHA-256 为 `b9a25ba001e7bbb6cfb863b6246590a86b8931d9a92c5e2ac6298813b95815c6`
与 `0acf05c001ac00dc927847f85ca01d049783bb22464cbd0bcdc94bdc34dac72f`。
`full-equivalence-{1,2-resumed}/receipt.json` 的 SHA-256 均为
`ec72d40ee6d2ec74a45bcad39000c2c19a9f08024713b2f5fc35c8da49bac207`。
同一个候选和基线分别加载固定出版格式与官方 IEEE Transactions
双栏期刊样例。原始 `bare_jrnl.tex`、`IEEEtran.cls` 和格式的指纹
匹配出版矩阵。两次正文编辑分别覆盖同长替换和不同长度替换,每次
续跑复用2060882步,从字节20465继续,重放160项宿主调用。编辑后
实际正文词框位于两栏,候选和基线每版 PDF、SVG、来源、aux 和执行
步数一致。两次编辑也分别用独立会话零复用全量确认。回执
`target/p4-reuse-source-versions/ieee-journal/receipt.json` 的 SHA-256 为
`b9fe349ec25a4f767c93a05bb5dfc4678b350d4963358e2486936438973b0d97`。
官方 CVPR 2026 的五页项目加载出版矩阵中相同的原始文件、格式和
实际 BibTeX 产物。两次改动 `sec/1_intro.tex` 时,两个二进制的输出
一致,复用步数均为零。第一处编辑令 aux 多出一条实际行号记录。
最初按冷启动生成文件做独立全量,在 PDF 比较处发现差异。随后
逐次保留编辑前的 aux、brf、out、log 和 PDF。独立会话使用同一组
初始生成文件,三次编辑的执行步数、PDF、各页 SVG、来源和 aux
均与会话结果一致。辅助文件稳定后,第三次子文件编辑执行总步数
22864610,从主文件字节1791续跑,复用11375833步,重放407项
宿主调用,只提交第1页更新。回执
`target/p4-reuse-source-versions/cvpr-generated-initial/receipt.json`
的 SHA-256 为 `9381ab9ff11c46c569f5e175ae30af4e253b562e04eea3ed7c03f6dc8485fd3f`。
这是实际项目编译及页面差量证据,浏览器延迟见原样 A4 对照。
同一候选的定向 SHA-256 调用栈又定位到来源映射。12条捕获都在
`SourceMap::from_revision` 核对源内容指纹。
`target/p4-reuse-source-versions-callchains/sha-blocks-a4/attribution.json`
的 SHA-256 为 `c21e2a6c2ee248e246955c48f64326c113254958f91e65097c68a1180bff998e`。
下一隔离候选复用会话持有的同一内核结果里的已验证源指纹,保持
来源跨度与绘制索引的校验。不同会话或传入的独立执行结果照常
逐字节计算指纹。针对相同修订号的独立结果增加验证。
目前只完成独立进程探针,编译会话接线仍待验收。
### TeX 输入的默认扩展名候选
-52
View File
@@ -384,58 +384,6 @@ ACL 和 NeurIPS 原生首处诊断均为 `\MT@protrudechars`,分别位于
四项复跑及分范围合并回执 `publisher-followup/receipt.json` 的 SHA-256 为
`65ee11dea157174e282033cf993a8bfd1e5e0989bab48fe73df1ab7005bd7e19`。
### 主线文件身份扫描调整后的原样复验
主线 `24ea6ef` 的同一优化程序独立复跑14项。分别使用已验证的基础、
NeurIPS、ACM 编译环境。源文件、模板归档、格式和字体映射均按对应基线
校验。14份参考 PDF 生成,全部 aux 收敛且无未定义引用告警。原生生成
Springer Nature、IEEE Transactions 双栏 starter、IEEE Conference starter、
Springer LNCS、CVPR 2026 共5份 PDF。成功项的页数、词框和逐轮 aux 与各自
上一次结果一致,其他9项的首条诊断一致。三组报告及逐项复验汇总见
`target/p4-alias-scan-identity/publisher/receipt.json`,SHA-256 为
`a8aa32d5f9ca829dd121018300cd07f9f996b3aad17b11b3549bbbe49ee8ac3b`。
### 原子文件增删后的主线复验
同一优化版复跑14份原样期刊、双栏期刊、会议和 arXiv。参考端14份全部
生成,原生仍生成5份。成功项的页数、词框和逐轮 aux 与对照一致,其余
原生样稿的首条诊断一致。Springer Nature 首次原生试验达到90秒上限,
同二进制、格式和模板重试后正常生成12页。arXiv 和 APS 的参考词框
首次跨日对照只差日期数字,同日独立生成的全部词框逐字节一致。
`target/p4-checkpoint-file-changes/publisher-recovery/receipt.json` 的 SHA-256 为
`00265ef887ae499fa3ed5164f349198dfad6fb60ce9d07310c293cfa5ef9a6fb`。
初次报告、超时记录和同日重跑均保留。
### IEEE 双栏期刊与 CVPR 会议的实时会话对照
使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后
的 PDF、SVG、来源映射与 aux。IEEE Transactions 的两次同长和异长
正文改动均续跑,各复用2060882步,实际正文词框覆盖左右栏。CVPR
2026 的输入包括此前官方项目实际生成的 BibTeX 产物,共5页。前两次
子文件改动为全量,aux 稳定后第三次复用11375833步,仅更新第1页。
五次编辑分别用同一初始状态的独立零复用编译核对一致。
[会话回执与阶段记录](P2_M1_PROGRESS.md#恢复检查点后复用源内容指纹)
### 上游 pdfTeX 导言区恢复对照
在同一批14项原样项目上运行固定的 pdfTeX 1.40.29,配对比较标准格式
和 TeX Live 官方 `mylatexformat` 导言区恢复。两端均沿用相同原始模板、
资源和已收敛的辅助文件。标准入口生成14份。恢复入口完成10份、58页,
各页的144 DPI 灰度图、嵌入字体、逐字词框和 aux 均一致。规范化后的
项目文件 SyncTeX 记录逐条一致,7项仍有发行版文件来源记录差异。
Springer LNCS 的格式保存遇到包对 `\openout` 的范围限制。ACM 的
单栏期刊、双栏期刊和会议案例均在保存时遇到 `acks` 环境嵌套错误。
这四项保留标准全量结果和保存失败日志。此轮只验证已收敛文档的导言区
恢复范围。用户编辑后的依赖、重用、版面和时延通过各自的会话验收判断。
对应 `target/p4-upstream-preview-boundary/snapshot-publishers` 回执如下。
- `receipt.json` 为 `4fd41bab48ea42af55a4cef3964a080531a7d542a935c3ab08ad9beb7b5347b1`
- `source-map-comparison.json` 为 `8106461bd200fcc85769f05e37773fe855ef2c2a9caa56cfe6057961cbcb0da6`
- `rendered-comparison.json` 为 `d5590af00c2e4b30b9973fa6eea8bcd5b0f3854d8f156784352bb304885f6712`
### ACM 的三类官方样例
新增 ACM acmart v2.21 的单栏期刊 `acmsmall`、双栏期刊 `acmtog` 和会议
+23 -51
View File
@@ -30,7 +30,7 @@ struct Edit {
visible_revision: Option<u64>,
source: Option<String>,
#[serde(default)]
files: BTreeMap<String, Option<String>>,
files: BTreeMap<String, String>,
#[serde(default)]
preview_draft: bool,
}
@@ -214,8 +214,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let file = project.file(&entry).expect("the editor owns its entry");
let files = editable
.iter()
.filter_map(|(name, path)| project.file(path).map(|file| (name, file)))
.map(|(name, file)| Ok((name, std::str::from_utf8(&file.data)?)))
.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,
@@ -253,21 +257,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = editable
.get(&name)
.ok_or_else(|| format!("File is not editable: {name}"))?;
if *path == entry && value.is_none() {
return Err("The entry file cannot be removed".into());
}
Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes()))))
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(), Some(Arc::from(source.into_bytes())))
.insert(entry.clone(), Arc::from(source.into_bytes()))
.is_some()
{
return Err("The entry file was edited twice".into());
}
project.with_file_changes(edit.sequence, updates)
project.with_file_edits(edit.sequence, updates)
});
project = match next {
Ok(project) => project,
@@ -398,8 +399,6 @@ fn prepare(
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");
let mut declared = BTreeSet::from([entry.clone()]);
let mut directories = BTreeSet::new();
for relative in additional {
if relative.as_os_str().is_empty()
|| relative
@@ -413,50 +412,23 @@ fn prepare(
.into());
}
let logical = run.join(relative);
if !declared.insert(logical.clone()) {
return Err(format!("Project file is listed twice: {}", relative.display()).into());
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 physical = source_root.join(relative);
let data = match physical.canonicalize() {
Ok(path) if path.starts_with(source_root) => Some(Arc::<[u8]>::from(fs::read(path)?)),
Ok(_) => {
return Err(format!(
"Project file is outside the entry directory: {}",
relative.display()
)
.into());
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let parent = physical
.parent()
.expect("project file has a parent")
.canonicalize()?;
if !parent.starts_with(source_root) || physical.symlink_metadata().is_ok() {
return Err(error.into());
}
None
}
Err(error) => return Err(error.into()),
};
let directory = logical.parent().expect("project file has a parent");
fs::create_dir_all(directory)?;
directories.extend(
directory
.ancestors()
.take_while(|path| path.starts_with(run))
.map(Path::to_owned),
);
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()
&& data
.as_deref()
.is_none_or(|bytes| std::str::from_utf8(bytes).is_ok())
&& std::str::from_utf8(&data).is_ok()
{
editable.insert(name.into(), logical.clone());
}
if let Some(data) = data {
fs::write(&logical, &data)?;
files.insert(logical, data);
}
files.insert(logical, data);
}
let mut request = CompileRequest::new(
world.clone(),
@@ -503,7 +475,7 @@ fn prepare(
revision: 1,
roots: coverage,
files,
directories,
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([run.to_owned()]),
generated,
+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;
+10 -246
View File
@@ -4,10 +4,7 @@ use super::*;
#[cfg(test)]
use std::{collections::BTreeMap, fs};
use std::{collections::BTreeSet, ffi::OsString, path::Path};
use texrra_tex_core::{
execution::EntryCheckpoint,
resources::{ResourceKind, ResourceLookup},
};
use texrra_tex_core::{execution::EntryCheckpoint, resources::ResourceKind};
#[cfg(test)]
use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy};
@@ -426,18 +423,6 @@ impl SelectedCheckpoint {
check(cancellation)?;
call(&mut prepared.files)?;
}
let project = request
.project
.as_deref()
.expect("validated atomic project");
if !checkpoint
.guard
.project
.immutable_paths()
.eq(project.immutable_paths())
{
checkpoint.guard.verify_replayed_lookups(&prepared.files)?;
}
Ok(prepared)
}
@@ -519,7 +504,6 @@ struct PrefixInputGuard {
initial: GeneratedInitialState,
entry: PathBuf,
immutable: BTreeSet<PathBuf>,
lookups: Vec<ResourceLookup>,
clock_environment: Option<[Option<OsString>; 3]>,
}
@@ -588,7 +572,6 @@ impl PrefixInputGuard {
initial,
entry: entry.to_path_buf(),
immutable,
lookups: trace.lookups.clone(),
clock_environment: (!trace.file_modifications.is_empty()).then(date_environment),
})
}
@@ -614,8 +597,8 @@ impl PrefixInputGuard {
.project
.as_deref()
.ok_or("checkpoint requires an atomic project")?;
if !self.project.same_lookup_configuration(current)? {
return Err("checkpoint lookup configuration changed".into());
if !self.project.same_lookup_namespace(current)? {
return Err("checkpoint lookup namespace changed".into());
}
for path in &self.immutable {
let old = self.project.file(path).map(|file| &file.version);
@@ -638,19 +621,6 @@ impl PrefixInputGuard {
Ok(current)
}
fn verify_replayed_lookups(&self, files: &Files) -> Result<(), CompileError> {
let trace = files.resource_trace();
if trace.lookups != self.lookups
|| !trace.read_errors.is_empty()
|| !trace.namespace_capture_failures.is_empty()
{
return Err(CompileError::Host(
"checkpoint replayed lookup changed".into(),
));
}
Ok(())
}
fn verify(
&self,
request: &CompileRequest,
@@ -835,16 +805,16 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
&request.clone().with_project(changed_prefix),
"entry prefix changed",
);
let mut changed_namespace = definition;
changed_namespace.revision = 3;
changed_namespace
.directories
.insert(cwd.join("new-directory"));
let mut appeared = definition;
appeared.revision = 3;
appeared
.files
.insert(cwd.join("optional.tex"), Arc::from(b"present".as_slice()));
rejected(
&request
.clone()
.with_project(ProjectSnapshot::new(changed_namespace).unwrap()),
"lookup configuration changed",
.with_project(ProjectSnapshot::new(appeared).unwrap()),
"lookup namespace changed",
);
let mut changed_clock = request.clone();
changed_clock.time = JobTime::new(2026, 11, 18, 1001).unwrap();
@@ -1207,212 +1177,6 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
);
}
#[test]
fn immutable_file_creation_and_removal_replay_real_lookup_results() {
use texrra_tex_core::resources::SearchPath;
let cwd = std::env::temp_dir().join(format!("texrra-file-revisions-{}", std::process::id()));
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().unwrap();
let vendor = cwd.join("vendor");
let entry = cwd.join("entry.tex");
let aux = cwd.join("entry.aux");
let extra = cwd.join("unread.tex");
let settings = cwd.join("settings.tex");
let vendor_settings = vendor.join("settings.tex");
let tag = cwd.join("tag.tex");
let vendor_tag = vendor.join("tag.tex");
let prefix = concat!(
"\\catcode123=1 \\catcode125=2\n",
"\\def\\value{10}\n",
"\\openin3=settings.tex \\ifeof3\\else\\input settings.tex \\fi\\closein3\n",
"\\edef\\filesize{\\pdffilesize{tag.tex}}\n",
"\\immediate\\openout1=entry.aux\n",
"\\immediate\\write1{unchanged journal}\\relax\n",
"\\message{CHECKPOINT}\\relax\n",
);
let tail = "\\shipout\\hbox{\\vrule width\\value pt height1pt}\n\\immediate\\closeout1\\end\n";
let world = {
let mut world = WorldConfig::new(&cwd);
world.paths.insert(
ResourceKind::Tex,
vec![
SearchPath::directory(&cwd, false),
SearchPath::directory(&vendor, false),
],
);
world
};
let mut project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: BTreeSet::from([cwd.clone()]),
files: BTreeMap::from([
(
entry.clone(),
Arc::from(format!("{prefix}{tail}").into_bytes()),
),
(vendor_tag.clone(), Arc::from(b"42".as_slice())),
]),
directories: BTreeSet::from([vendor]),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::from([aux.clone()]),
})
.unwrap();
assert!(
project
.with_file_changes(
2,
BTreeMap::from([(aux.clone(), Some(Arc::from(b"source collision".as_slice())))]),
)
.is_err()
);
assert!(
project
.with_file_changes(
2,
BTreeMap::from([(cwd.join("missing-parent/entry.tex"), Some(Arc::from([])))]),
)
.is_err()
);
let mut request = CompileRequest::new(
world,
"entry.tex",
"entry.pdf",
JobTime::new(2026, 11, 20, 540)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
)
.observe_generated_initial();
request.entry = Entry::Initex;
request.etex = true;
NativeCompiler::default()
.compile(request.clone().with_project(project.clone()))
.unwrap();
let journal = fs::read(&aux).unwrap();
let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() - 2);
let revisions = [
("cold", None, false, None, 10),
(
"unrelated appeared",
Some((&extra, Some(b"unused".as_slice()))),
true,
None,
10,
),
("unrelated removed", Some((&extra, None)), true, None, 10),
(
"missing dependency appeared",
Some((&vendor_settings, Some(br"\def\value{20}".as_slice()))),
false,
Some("open_in changed"),
20,
),
(
"higher priority dependency appeared",
Some((&settings, Some(br"\def\value{30}".as_slice()))),
false,
Some("open_in changed"),
30,
),
(
"dependency edited",
Some((&settings, Some(br"\def\value{40}".as_slice()))),
false,
Some("observed input changed"),
40,
),
(
"removed dependency exposes fallback",
Some((&settings, None)),
false,
Some("observed input changed"),
20,
),
(
"removed fallback",
Some((&vendor_settings, None)),
false,
Some("observed input changed"),
10,
),
(
"equal-size result came from a new path",
Some((&tag, Some(b"59".as_slice()))),
false,
Some("replayed lookup changed"),
10,
),
(
"unrelated file appeared again",
Some((&extra, Some(b"new unused".as_slice()))),
true,
None,
10,
),
];
let mut pdfs = BTreeMap::new();
for (index, (label, edit, reuse, rejection, width)) in revisions.into_iter().enumerate() {
if let Some((path, bytes)) = edit {
let previous = project.clone();
project = project
.with_file_changes(
index as u64 + 1,
BTreeMap::from([(path.clone(), bytes.map(Arc::from))]),
)
.unwrap();
if label == "unrelated appeared" {
assert!(previous.file(path).is_none());
assert!(project.file(path).is_some());
}
}
let next = request.clone().with_project(project.clone());
let result = compiler.compile(next.clone()).unwrap();
let work = &result.entry_checkpoint_work;
assert_eq!(work.reused_steps > 0, reuse, "{label}: {work:?}");
if let Some(expect) = rejection {
assert!(
work.rejection
.as_deref()
.is_some_and(|e| e.contains(expect)),
"{label}: {work:?}"
);
}
assert_eq!(fs::read(&aux).unwrap(), journal, "{label}");
let full = NativeCompiler::default().compile(next).unwrap();
assert_eq!(full.entry_checkpoint_work.reused_steps, 0, "{label}");
assert_eq!(result.pdf, full.pdf, "{label}");
assert_eq!(result.source_map.pages, full.source_map.pages, "{label}");
assert_eq!(
result.source_map.sources, full.source_map.sources,
"{label}"
);
assert_eq!(
result.preview_since(None).unwrap().pages,
full.preview_since(None).unwrap().pages,
"{label}",
);
assert_eq!(
result.execution.execution, full.execution.execution,
"{label}"
);
assert_eq!(
result.resources.trace.lookups, full.resources.trace.lookups,
"{label}"
);
assert_eq!(fs::read(&aux).unwrap(), journal, "{label}");
if let Some(previous) = pdfs.insert(width, result.pdf.clone()) {
assert_eq!(previous, result.pdf, "{label}");
}
eprintln!("{label}: {work:?}");
}
assert_eq!(pdfs.values().collect::<BTreeSet<_>>().len(), 4);
}
#[test]
fn automatic_checkpoints_follow_successive_edits_at_different_frontiers() {
let cwd = std::env::temp_dir().join(format!("texrra-rolling-{}", std::process::id()));
+15 -6
View File
@@ -83,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()
}
@@ -259,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,
|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);
+25
View File
@@ -151,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>,
@@ -547,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(),
@@ -1399,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())
}
+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();
}
}