Advance native LaTeX execution and preview
This commit is contained in:
1 parent
91f9d76b16
commit
2741546ca8
414 files changed
+99872
-933
No files matched your search
@@ -0,0 +1,456 @@
|
||||
//! Real LaTeX acceptance for editor-owned logical input batches. Package bytes
|
||||
//! are supplied explicitly; no installed namespace is claimed to be snapshotted.
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
use texrra_engine::native::{
|
||||
AttemptPhase, CompileRequest, CompiledDocument, Entry, GeneratedInitialState,
|
||||
HostPreparationPhase, NativeCompiler, ProjectDefinition, ProjectSnapshot, StreamJournal,
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
artifacts::file_version,
|
||||
execution::JobTime,
|
||||
resources::{ResourceVersion, WorldConfig},
|
||||
};
|
||||
fn request(cwd: &Path, image: &Path, roots: &[PathBuf]) -> Result<CompileRequest, String> {
|
||||
let mut r = CompileRequest::new(
|
||||
WorldConfig::from_environment(cwd, roots.to_vec())?,
|
||||
"main.tex",
|
||||
"main.pdf",
|
||||
JobTime::new(2026, 11, 16, 123)
|
||||
.unwrap()
|
||||
.with_pdf_clock(0, 480)
|
||||
.unwrap(),
|
||||
);
|
||||
r.entry = Entry::Format(image.into());
|
||||
r.etex = true;
|
||||
r.limits.steps = 600_000_000;
|
||||
r.resource_manifest = Some("resources.json".into());
|
||||
r.layout_manifest = Some("layout.json".into());
|
||||
r = r.observe_generated_initial();
|
||||
Ok(r)
|
||||
}
|
||||
fn initial(cwd: &Path) -> Result<GeneratedInitialState, String> {
|
||||
let path = cwd.join("main.aux");
|
||||
GeneratedInitialState::new(
|
||||
cwd.into(),
|
||||
BTreeMap::from([(path.clone(), file_version(&path)?)]),
|
||||
)
|
||||
}
|
||||
// Physical IDs may differ when independently creating an initially absent file.
|
||||
// Preserve their equality relations within each job, plus all other evidence.
|
||||
// Original journals remain untouched in the saved report.
|
||||
fn stream_behavior(journal: &StreamJournal) -> Result<serde_json::Value, String> {
|
||||
let mut value = serde_json::to_value(journal).map_err(|e| e.to_string())?;
|
||||
let mut identities = BTreeMap::new();
|
||||
for event in value["events"].as_array_mut().unwrap() {
|
||||
for pointer in [
|
||||
"/effect/OpenInput/result/Ok/storage/File/Ok/unix_identity",
|
||||
"/effect/OutputOpened/descriptor/Ok/unix_identity",
|
||||
] {
|
||||
if let Some(identity) = event.pointer_mut(pointer).filter(|v| !v.is_null()) {
|
||||
let key = serde_json::to_string(identity).map_err(|e| e.to_string())?;
|
||||
let next = identities.len() + 1;
|
||||
let id = identities.entry(key).or_insert(next);
|
||||
*identity = serde_json::json!({"within_job_identity":id});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
fn compile(c: &NativeCompiler, r: CompileRequest) -> Result<Arc<CompiledDocument>, String> {
|
||||
c.compile_detailed(r).map_err(|e| e.to_string())
|
||||
}
|
||||
fn save(path: &Path, value: &impl serde::Serialize) -> Result<(), String> {
|
||||
fs::write(
|
||||
path,
|
||||
serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?,
|
||||
)
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
fn put(path: &Path, data: &[u8]) -> Result<(), String> {
|
||||
fs::write(path, data).map_err(|e| e.to_string())
|
||||
}
|
||||
fn restore(path: &Path, bytes: Option<&[u8]>) -> Result<(), String> {
|
||||
if let Some(data) = bytes {
|
||||
put(path, data)
|
||||
} else {
|
||||
match fs::remove_file(path) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn run() -> Result<(), String> {
|
||||
let mut args = std::env::args_os().skip(1);
|
||||
let image = PathBuf::from(
|
||||
args.next()
|
||||
.ok_or("native_atomic_session IMAGE NEW_OUTPUT_DIR TEXMF_ROOT...")?,
|
||||
)
|
||||
.canonicalize()
|
||||
.map_err(|e| e.to_string())?;
|
||||
let out = PathBuf::from(args.next().ok_or("missing output directory")?);
|
||||
let roots: Vec<PathBuf> = args.map(PathBuf::from).collect();
|
||||
if roots.is_empty() {
|
||||
return Err("explicit TEXMF roots required".into());
|
||||
}
|
||||
fs::create_dir(&out).map_err(|e| e.to_string())?;
|
||||
let out = out.canonicalize().map_err(|e| e.to_string())?;
|
||||
let fixture =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/native-format-stage/a4-project");
|
||||
let original_main = fs::read_to_string(fixture.join("main.tex")).map_err(|e| e.to_string())?;
|
||||
let original_child =
|
||||
fs::read_to_string(fixture.join("chapter.tex")).map_err(|e| e.to_string())?;
|
||||
let original_versions = [
|
||||
file_version(&fixture.join("main.tex"))?,
|
||||
file_version(&fixture.join("chapter.tex"))?,
|
||||
];
|
||||
let seed = out.join("physical-seed");
|
||||
let shared = out.join("shared");
|
||||
fs::create_dir(&seed).map_err(|e| e.to_string())?;
|
||||
fs::create_dir(&shared).map_err(|e| e.to_string())?;
|
||||
put(&seed.join("main.tex"), original_main.as_bytes())?;
|
||||
put(&seed.join("chapter.tex"), original_child.as_bytes())?;
|
||||
let seed_compiler = NativeCompiler::default();
|
||||
let mut seed_result = None;
|
||||
let mut assets: BTreeMap<PathBuf, Arc<[u8]>> = BTreeMap::new();
|
||||
for pass in 1..=3 {
|
||||
let document = compile(&seed_compiler, request(&seed, &image, &roots)?)?;
|
||||
let mut captured = Vec::new();
|
||||
for (path, value) in document.inputs.files() {
|
||||
if path.starts_with(&seed) {
|
||||
continue;
|
||||
}
|
||||
let value = value.map_err(str::to_owned)?;
|
||||
captured.push(value.version.clone());
|
||||
if let Some(previous) = assets.insert(path.into(), value.data.clone()) {
|
||||
if previous != value.data {
|
||||
return Err(format!(
|
||||
"seed resource changed between passes: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
save(&seed.join(format!("pass-{pass}-captured.json")), &captured)?;
|
||||
save(
|
||||
&seed.join(format!("pass-{pass}-resources.json")),
|
||||
&document.resources,
|
||||
)?;
|
||||
// Existence-only positive probes are namespace entries too. In
|
||||
// particular, first-pass unresolved references can request fonts which
|
||||
// the converged third pass no longer reads. Do not infer the complete
|
||||
// logical bundle from the last pass's byte reads alone.
|
||||
for path in document
|
||||
.resources
|
||||
.trace
|
||||
.lookups
|
||||
.iter()
|
||||
.filter_map(|v| v.resolved.as_ref())
|
||||
{
|
||||
if !path.starts_with(&seed) && !assets.contains_key(path) {
|
||||
assets.insert(
|
||||
path.clone(),
|
||||
Arc::from(fs::read(path).map_err(|e| e.to_string())?),
|
||||
);
|
||||
}
|
||||
}
|
||||
seed_result = Some(document);
|
||||
}
|
||||
let seed_result = seed_result.unwrap();
|
||||
// This explicitly defines a new finite logical package bundle. Other
|
||||
// installed files are not inferred present; callers can supply any bundle.
|
||||
let mut coverage: BTreeSet<PathBuf> = roots.iter().cloned().collect();
|
||||
coverage.insert(shared.clone());
|
||||
for path in assets.keys() {
|
||||
if !coverage.iter().any(|r| path.starts_with(r)) {
|
||||
coverage.insert(path.parent().ok_or("asset requires parent")?.into());
|
||||
}
|
||||
}
|
||||
let asset_versions: Vec<_> = assets
|
||||
.iter()
|
||||
.map(|(path, data)| ResourceVersion {
|
||||
path: path.clone(),
|
||||
bytes: data.len() as u64,
|
||||
sha256: format!("{:x}", Sha256::digest(data)),
|
||||
})
|
||||
.collect();
|
||||
save(&out.join("package-assets.json"), &asset_versions)?;
|
||||
let poison = br"\texrraPhysicalPoisonMustNotExecute";
|
||||
for name in ["main.tex", "chapter.tex", "optional.tex"] {
|
||||
put(&shared.join(name), poison)?;
|
||||
}
|
||||
let cases=vec![
|
||||
("unmodified",original_main.clone(),original_child.clone(),"chapter.tex",None),
|
||||
("body",original_main.clone(),format!("{original_child}\\par A body buffer edit.\n"),"chapter.tex",None),
|
||||
("macro",original_main.replace("{Native project}","{Atomic macro edit}"),original_child.clone(),"chapter.tex",None),
|
||||
("new-input",original_main.replace(r"\input{chapter}",r"\input{buffer-note}"),format!("{original_child}\\par A new input buffer.\n"),"buffer-note.tex",None),
|
||||
("absent",original_main.replace(r"\end{document}","\\par\\InputIfFileExists{optional.tex}{}{Missing optional branch.}\n\\end{document}"),original_child.clone(),"chapter.tex",None),
|
||||
("present",original_main.replace(r"\end{document}","\\par\\InputIfFileExists{optional.tex}{}{Missing optional branch.}\n\\end{document}"),original_child.clone(),"chapter.tex",Some("Present optional buffer.\\par\n")),
|
||||
];
|
||||
let compiler = NativeCompiler::default();
|
||||
let mut rows = Vec::new();
|
||||
let mut last: Option<Arc<CompiledDocument>> = None;
|
||||
let mut previous_project: Option<Arc<ProjectSnapshot>> = None;
|
||||
let first_initial = initial(&shared)?;
|
||||
for (index, (name, main, child, child_name, optional)) in cases.into_iter().enumerate() {
|
||||
let case = out.join(name);
|
||||
fs::create_dir(&case).map_err(|e| e.to_string())?;
|
||||
put(&case.join("main.tex"), main.as_bytes())?;
|
||||
put(&case.join(child_name), child.as_bytes())?;
|
||||
if let Some(text) = optional {
|
||||
put(&case.join("optional.tex"), text.as_bytes())?;
|
||||
}
|
||||
let mut configuration = request(&shared, &image, &roots)?.world;
|
||||
configuration.cwd = shared.clone();
|
||||
let mut files = assets.clone();
|
||||
files.insert(shared.join("main.tex"), Arc::from(main.as_bytes()));
|
||||
files.insert(shared.join(child_name), Arc::from(child.as_bytes()));
|
||||
if let Some(text) = optional {
|
||||
files.insert(shared.join("optional.tex"), Arc::from(text.as_bytes()));
|
||||
}
|
||||
let definition = ProjectDefinition {
|
||||
configuration,
|
||||
revision: index as u64 + 1,
|
||||
roots: coverage.clone(),
|
||||
files,
|
||||
directories: BTreeSet::new(),
|
||||
aliases: BTreeMap::new(),
|
||||
generated_roots: BTreeSet::from([shared.clone()]),
|
||||
generated: BTreeSet::from([shared.join("main.aux")]),
|
||||
};
|
||||
let rebuilt = ProjectSnapshot::new(definition.clone())?;
|
||||
let mut edited_files = None;
|
||||
let mut unchanged_buffer_bytes = 0;
|
||||
let project = if let Some(previous) = &previous_project
|
||||
&& previous
|
||||
.files()
|
||||
.map(|(path, _)| path)
|
||||
.eq(definition.files.keys().map(PathBuf::as_path))
|
||||
{
|
||||
let edits: BTreeMap<_, _> = definition
|
||||
.files
|
||||
.iter()
|
||||
.filter(|(path, data)| {
|
||||
let old = &previous.file(path).unwrap().data;
|
||||
!Arc::ptr_eq(old, data) && old.as_ref() != data.as_ref()
|
||||
})
|
||||
.map(|(path, data)| (path.clone(), data.clone()))
|
||||
.collect();
|
||||
edited_files = Some(edits.len());
|
||||
let next = previous.with_file_edits(definition.revision, edits)?;
|
||||
assert_eq!(next.version(), rebuilt.version());
|
||||
assert_eq!(next.content_descriptor()?, rebuilt.content_descriptor()?);
|
||||
for (path, before) in previous.files() {
|
||||
let after = next.file(path).unwrap();
|
||||
if before.version == after.version {
|
||||
assert!(Arc::ptr_eq(&before.data, &after.data));
|
||||
unchanged_buffer_bytes += before.version.bytes;
|
||||
}
|
||||
}
|
||||
next
|
||||
} else {
|
||||
rebuilt.clone()
|
||||
};
|
||||
previous_project = Some(project.clone());
|
||||
put(
|
||||
&case.join("content-descriptor.json"),
|
||||
&project.content_descriptor()?,
|
||||
)?;
|
||||
if index == 1 {
|
||||
let previous = last.as_ref().unwrap();
|
||||
let pdf = fs::read(shared.join("main.pdf")).map_err(|e| e.to_string())?;
|
||||
let log = fs::read(shared.join("main.log")).map_err(|e| e.to_string())?;
|
||||
let aux = fs::read(shared.join("main.aux")).map_err(|e| e.to_string())?;
|
||||
let failure = compiler
|
||||
.compile_detailed(
|
||||
request(&shared, &image, &roots)?
|
||||
.with_project(project.clone())
|
||||
.with_generated_initial(first_initial.clone()),
|
||||
)
|
||||
.err()
|
||||
.ok_or("expected stale generated initial precondition failure")?;
|
||||
assert_eq!(failure.phase, AttemptPhase::Preparing);
|
||||
assert_eq!(
|
||||
failure.host_preparation.phase,
|
||||
HostPreparationPhase::GeneratedInitial
|
||||
);
|
||||
assert!(failure.failed_execution.is_none() && failure.completed_execution.is_none());
|
||||
assert_eq!(
|
||||
failure.host_preparation.generated_initial.as_ref(),
|
||||
Some(&initial(&shared)?)
|
||||
);
|
||||
assert!(Arc::ptr_eq(previous, &compiler.latest().unwrap()));
|
||||
assert_eq!(fs::read(shared.join("main.pdf")).unwrap(), pdf);
|
||||
assert_eq!(fs::read(shared.join("main.log")).unwrap(), log);
|
||||
assert_eq!(fs::read(shared.join("main.aux")).unwrap(), aux);
|
||||
save(
|
||||
&out.join("generated-stale-failure.json"),
|
||||
&serde_json::json!({"revision":failure.revision,"phase":failure.phase,"error":failure.error,"request":failure.request,"host_preparation":failure.host_preparation,"project":project.version(),"execution_absent":true,"old_publication_pdf_log_aux_preserved":true}),
|
||||
)?;
|
||||
}
|
||||
if index == 3 {
|
||||
let mut bad = definition;
|
||||
bad.revision = 100;
|
||||
let text = main.replace(
|
||||
r"\end{document}",
|
||||
"\\texrraUndefinedAtomicProof\n\\end{document}",
|
||||
);
|
||||
bad.files
|
||||
.insert(shared.join("main.tex"), Arc::from(text.as_bytes()));
|
||||
let bad = ProjectSnapshot::new(bad)?;
|
||||
let previous = last.as_ref().unwrap();
|
||||
let previous_pdf = fs::read(shared.join("main.pdf")).map_err(|e| e.to_string())?;
|
||||
let failure = compiler
|
||||
.compile_detailed(
|
||||
request(&shared, &image, &roots)?
|
||||
.with_project(bad.clone())
|
||||
.with_generated_initial(initial(&shared)?),
|
||||
)
|
||||
.err()
|
||||
.ok_or("expected actual atomic execution failure")?;
|
||||
assert!(failure.to_string().contains("texrraUndefinedAtomicProof"));
|
||||
assert_eq!(
|
||||
failure
|
||||
.inputs
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.project()
|
||||
.unwrap()
|
||||
.version(),
|
||||
bad.version()
|
||||
);
|
||||
assert!(Arc::ptr_eq(previous, &compiler.latest().unwrap()));
|
||||
assert_eq!(fs::read(shared.join("main.pdf")).unwrap(), previous_pdf);
|
||||
save(
|
||||
&out.join("atomic-failure.json"),
|
||||
&serde_json::json!({"phase":failure.phase,"error":failure.error,"project":failure.inputs.as_ref().unwrap().project().unwrap().version(),"source_versions":failure.failed_execution.as_ref().unwrap().evidence.source_versions,"host_preparation":failure.host_preparation,"host_runtime":failure.host_runtime,"stream_io":failure.resources.as_ref().unwrap().stream_io,"old_publication_preserved":true}),
|
||||
)?;
|
||||
// Genuine failed aux side effects remain; restore a known starting
|
||||
// state for the next shared/clean comparison, not inside the engine.
|
||||
put(
|
||||
&shared.join("main.aux"),
|
||||
&fs::read(out.join("macro/pass-3.aux")).map_err(|e| e.to_string())?,
|
||||
)?;
|
||||
}
|
||||
for pass in 1..=3 {
|
||||
let aux = shared.join("main.aux");
|
||||
let before = fs::read(&aux).ok();
|
||||
let expected_initial = initial(&shared)?;
|
||||
let actual = compile(
|
||||
&compiler,
|
||||
request(&shared, &image, &roots)?
|
||||
.with_project(project.clone())
|
||||
.with_generated_initial(expected_initial.clone()),
|
||||
)?;
|
||||
let actual_layout = fs::read(shared.join("layout.json")).map_err(|e| e.to_string())?;
|
||||
let after = fs::read(&aux).map_err(|e| e.to_string())?;
|
||||
restore(&aux, before.as_deref())?;
|
||||
let fresh = compile(
|
||||
&NativeCompiler::default(),
|
||||
request(&shared, &image, &roots)?
|
||||
.with_project(rebuilt.clone())
|
||||
.with_generated_initial(expected_initial.clone()),
|
||||
)?;
|
||||
assert_eq!(
|
||||
actual.resources.generated_initial.as_ref(),
|
||||
Some(&expected_initial)
|
||||
);
|
||||
assert_eq!(
|
||||
actual.resources.generated_initial,
|
||||
fresh.resources.generated_initial
|
||||
);
|
||||
assert_eq!(
|
||||
stream_behavior(&actual.resources.stream_io)?,
|
||||
stream_behavior(&fresh.resources.stream_io)?
|
||||
);
|
||||
assert_eq!(actual.pages, fresh.pages);
|
||||
assert_eq!(actual.pdf, fresh.pdf);
|
||||
assert_eq!(actual.source_map.pages, fresh.source_map.pages);
|
||||
assert_eq!(
|
||||
actual.execution.source_versions,
|
||||
fresh.execution.source_versions
|
||||
);
|
||||
assert_eq!(fs::read(&aux).unwrap(), after);
|
||||
assert_eq!(
|
||||
actual.resources.trace.project_version.as_ref(),
|
||||
Some(project.version())
|
||||
);
|
||||
assert!(actual.inputs.replay_gaps().is_empty());
|
||||
for filename in ["main.tex", "chapter.tex", "optional.tex"] {
|
||||
assert_eq!(fs::read(shared.join(filename)).unwrap(), poison);
|
||||
}
|
||||
assert!(!shared.join("buffer-note.tex").exists());
|
||||
let pdf = case.join(format!("pass-{pass}.pdf"));
|
||||
let map = case.join(format!("pass-{pass}-source-map.json"));
|
||||
let layout = case.join(format!("pass-{pass}-layout.json"));
|
||||
let saved_aux = case.join(format!("pass-{pass}.aux"));
|
||||
put(&pdf, actual.pdf.as_ref().ok_or("expected a real page")?)?;
|
||||
save(&map, &actual.source_map)?;
|
||||
put(&layout, &actual_layout)?;
|
||||
put(&saved_aux, &after)?;
|
||||
if name == "unmodified" && pass == 3 {
|
||||
assert_eq!(actual.pdf, seed_result.pdf);
|
||||
assert_eq!(actual.source_map.pages, seed_result.source_map.pages);
|
||||
assert_eq!(after, fs::read(seed.join("main.aux")).unwrap());
|
||||
}
|
||||
let work = actual.line_break_work;
|
||||
let independent = fresh.line_break_work;
|
||||
assert_eq!(
|
||||
work.examined_edges + work.reused_edges,
|
||||
independent.examined_edges + independent.reused_edges
|
||||
);
|
||||
assert_eq!(
|
||||
work.solved_passes + work.reused_passes,
|
||||
independent.solved_passes + independent.reused_passes
|
||||
);
|
||||
rows.push(serde_json::json!({
|
||||
"case":name,"pass":pass,"revision":actual.revision(),"project":project.version(),
|
||||
"editor_delta_files":edited_files,
|
||||
"editor_delta_unchanged_bytes":unchanged_buffer_bytes,
|
||||
"pdf":file_version(&pdf)?,"source_map":file_version(&map)?,"layout":file_version(&layout)?,
|
||||
"aux":file_version(&saved_aux)?,"aux_before":before,"resources":actual.resources,
|
||||
"independent_stream_io":fresh.resources.stream_io,"host_preparation":actual.host_preparation,
|
||||
"host_runtime":actual.host_runtime,"source_versions":actual.execution.source_versions,
|
||||
"full_clean_equal":true,"physical_poison_untouched":true,
|
||||
"line_break_work": {
|
||||
"solved_passes":work.solved_passes,"reused_passes":work.reused_passes,
|
||||
"examined_edges":work.examined_edges,"reused_edges":work.reused_edges
|
||||
},
|
||||
"independent_line_break_work": {
|
||||
"solved_passes":independent.solved_passes,"reused_passes":independent.reused_passes,
|
||||
"examined_edges":independent.examined_edges,"reused_edges":independent.reused_edges
|
||||
}
|
||||
}));
|
||||
save(
|
||||
&out.join("progress.json"),
|
||||
&serde_json::json!({"passed":false,"rows":rows}),
|
||||
)?;
|
||||
last = Some(actual);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
original_versions,
|
||||
[
|
||||
file_version(&fixture.join("main.tex"))?,
|
||||
file_version(&fixture.join("chapter.tex"))?
|
||||
]
|
||||
);
|
||||
save(
|
||||
&out.join("report.json"),
|
||||
&serde_json::json!({"passed":true,"scope":"atomic external logical project versions, exact complete known generated initial preconditions and real live I/O; no effect replay, execution/layout reuse or realtime claim","format":file_version(&image)?,"original_sources":original_versions,"logical_bundle":file_version(&out.join("package-assets.json"))?,"atomic_cases":6,"atomic_revisions":18,"independent_full_jobs":18,"physical_seed_jobs":3,"failure_jobs":2,"executed_failure_jobs":1,"preparation_failure_jobs":1,"compile_attempts":41,"executed_jobs":40,"physical_poison_untouched":true,"generated_initial_state_explicitly_restored":true,"generated_initial_expectations_checked":true,"rows":rows}),
|
||||
)?;
|
||||
println!("atomic real LaTeX project batches, failure and full-clean equality passed");
|
||||
Ok(())
|
||||
}
|
||||
fn main() {
|
||||
if let Err(e) = run() {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user