//! Shared strict Route-D compilation, resource closure and revision publication. //! No process cwd changes, legacy frontend, or external TeX compilation. #[path = "native_checkpoint_guard.rs"] mod checkpoint_guard; #[path = "native_checkpoint_probe.rs"] mod checkpoint_probe; pub use crate::native_generated::{GeneratedInitialState, GeneratedInputPolicy}; pub use crate::native_host::{ HostMetadata, HostObservation, HostPreparation, HostPreparationPhase, LedgerRead, VersionExpectation, }; pub use crate::native_job::job_time; use crate::native_job::{ EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output, file_modification_date, }; use crate::native_preview::PreviewState; pub use crate::native_preview::{PreviewPage, PreviewUpdate}; pub use crate::native_stream::{ DescriptorIdentity, InputOpened, InputStorage, ReleaseCause, StreamEffect, StreamEvent, StreamJournal, WriteAttempt, WriteOutcome, }; use checkpoint_guard::CheckpointCache; pub use checkpoint_guard::EntryCheckpointWork; use std::{ path::PathBuf, sync::{Arc, Mutex}, }; pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, ProjectVersion}; pub use texrra_tex_core::resources::{WorldFailure, WorldObservation}; use texrra_tex_core::{ execution::{ Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits, NativeSession, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile, SourceProvider, State, }, render::DisplayList, resources::{FileWorld, InputSnapshot, ResourceTrace, ResourceVersion, WorldConfig}, }; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Entry { Bootstrap, Initex, Format(PathBuf), } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum Target { Shipouts, Paragraphs, } #[derive(Clone)] pub struct CompileRequest { pub world: WorldConfig, pub inputs: Option>, pub project: Option>, pub generated_inputs: GeneratedInputPolicy, pub input: PathBuf, pub output: PathBuf, pub entry: Entry, pub target: Target, pub etex: bool, pub input_profile: InputProfile, pub time: JobTime, pub limits: Limits, pub resource_manifest: Option, pub layout_manifest: Option, /// Failure reports only create new files; existing files are never replaced. pub failure_manifest: Option, /// Whether the host sends TeX terminal diagnostics to stderr. pub terminal: bool, pub observer: Option>, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CompileStage { Prepared, Executed, FontsResolved, Exported, ReadyToPublish, } /// Called outside the publication lock. An observer can request a new /// revision or fail without publishing this result. Start/cancel are allowed; /// schedule compilation after the callback returns, rather than recursing. pub trait CompileObserver: Send + Sync { fn stage(&self, revision: u64, stage: CompileStage) -> Result<(), String>; } fn notify( request: &CompileRequest, revision: u64, stage: CompileStage, cancellation: &Cancellation, ) -> Result<(), CompileError> { check(cancellation)?; if let Some(observer) = &request.observer { let result = observer.stage(revision, stage); check(cancellation)?; result?; } Ok(()) } impl CompileRequest { pub fn new( world: WorldConfig, input: impl Into, output: impl Into, time: JobTime, ) -> Self { Self { world, inputs: None, project: None, generated_inputs: GeneratedInputPolicy::Live, input: input.into(), output: output.into(), entry: Entry::Bootstrap, target: Target::Shipouts, etex: false, input_profile: InputProfile::TeX8Bit, time, limits: Limits::default(), resource_manifest: None, layout_manifest: None, failure_manifest: None, terminal: false, observer: None, } } pub fn with_inputs(mut self, inputs: Arc) -> Self { self.project = None; self.world = inputs.configuration(); self.inputs = Some(inputs); self } pub fn with_project(mut self, project: Arc) -> Self { self.world = project.configuration(); self.inputs = None; self.project = Some(project); self } pub fn with_generated_initial(mut self, state: GeneratedInitialState) -> Self { self.generated_inputs = GeneratedInputPolicy::Expect(state); self } pub fn observe_generated_initial(mut self) -> Self { self.generated_inputs = GeneratedInputPolicy::Observe; self } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct GeneratedWrite { /// Actual opened path even if both version inspections find it absent. #[serde(default)] pub path: PathBuf, pub producer: PathBuf, pub before: Option, pub after: Option, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct GeneratedArtifacts { pub schema: u32, pub ledger_path: PathBuf, pub ledger_input: Option, /// Last version accepted or written by this host. A failed live check can /// observe a different version; that actual result is in host_runtime. pub ledger_current: Option, pub writes: Vec, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ResourceSnapshot { #[serde(flatten)] pub trace: ResourceTrace, pub generated_artifacts: GeneratedArtifacts, #[serde(default)] pub generated_initial: Option, #[serde(default)] pub stream_io: StreamJournal, } pub struct CompiledDocument { pub execution: Arc, pub entry_checkpoint_work: EntryCheckpointWork, pub format_preparation: Option, /// Actual paragraph search performed or reused in this revision. pub line_break_work: texrra_tex_core::execution::LineBreakWork, /// Original measurements with actual resolved font programs. pub pages: Vec, /// Revision-local measured paint and source versions. `unmapped` explicitly /// records uncollected legacy or diagnostic paint without guessing origins. pub source_map: texrra_tex_core::source_map::SourceMap, /// Includes resources read while embedding fonts, after execution. pub resources: ResourceSnapshot, pub inputs: Arc, pub host_preparation: HostPreparation, pub host_runtime: Vec, pub export_diagnostics: Vec, /// Immutable bytes stay associated with this revision after another publish. pub pdf: Option>, pub output: Option, preview: PreviewState, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FormatPreparation { Decoded, Reused, } impl CompiledDocument { pub fn revision(&self) -> u64 { self.execution.revision } /// Render updates for a preview of an earlier published revision in this /// compiler session. An unknown revision gets a complete preview. pub fn preview_since(&self, visible_revision: Option) -> Result { self.preview.render( self.revision(), &self.pages, self.pdf.as_ref(), visible_revision, ) } pub fn has_show_diagnostic(&self) -> bool { self.execution.execution.events.iter().any(|e| { matches!( e, texrra_tex_core::execution::Event::ShowBox(_) | texrra_tex_core::execution::Event::Show(_) ) }) } } pub struct BuiltFormat { pub output: ResourceVersion, pub resources: ResourceSnapshot, pub inputs: Arc, pub host_preparation: HostPreparation, pub host_runtime: Vec, pub execution: Arc, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub enum CompileError { Cancelled, Execution(Box), Host(String), } #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum AttemptPhase { Queued, Preparing, Prepared, Executing, Layout, Fonts, Export, Finishing, ReadyToPublish, Publishing, } #[derive(Debug, serde::Serialize)] pub struct CompileFailure { pub request: AttemptRequest, pub revision: u64, pub phase: AttemptPhase, pub error: CompileError, pub failed_execution: Option, pub completed_execution: Option>, pub trace: Option, pub inputs: Option>, pub resources: Option, pub host_preparation: HostPreparation, pub host_runtime: Vec, pub world_failure: Option, /// Policy/stat/locking and partial finalization can be unavailable. These /// records never authorize caching/reusing a failed computation. pub evidence_gaps: Vec, pub export_diagnostics: Vec, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct AttemptRequest { pub world: WorldConfig, pub input: PathBuf, pub output: PathBuf, pub entry: Entry, pub target: Target, pub etex: bool, pub input_profile: InputProfile, pub time: JobTime, pub limits: Limits, pub resource_manifest: Option, pub layout_manifest: Option, pub failure_manifest: Option, pub terminal: bool, pub observer_attached: bool, pub replay_requested: bool, pub project_version: Option, #[serde(default)] pub generated_inputs: GeneratedInputPolicy, } impl From<&CompileRequest> for AttemptRequest { fn from(r: &CompileRequest) -> Self { Self { world: r.world.clone(), input: r.input.clone(), output: r.output.clone(), entry: r.entry.clone(), target: r.target, etex: r.etex, input_profile: r.input_profile, time: r.time, limits: r.limits, resource_manifest: r.resource_manifest.clone(), layout_manifest: r.layout_manifest.clone(), failure_manifest: r.failure_manifest.clone(), terminal: r.terminal, observer_attached: r.observer.is_some(), replay_requested: r.inputs.is_some(), generated_inputs: r.generated_inputs.clone(), project_version: r.project.as_ref().map(|p| p.version().clone()).or_else(|| { r.inputs .as_ref() .and_then(|s| s.project().map(|p| p.version().clone())) }), } } } impl std::fmt::Display for CompileFailure { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.error.fmt(f) } } impl std::error::Error for CompileFailure {} impl CompileFailure { /// Persist the actual typed failure, including captured bytes, in a new /// file. This is evidence, not an executable checkpoint or lock lease. pub fn write_manifest(&self, path: &std::path::Path) -> Result<(), String> { let cwd = self .trace .as_ref() .map(|t| t.cwd.as_path()) .unwrap_or(&self.request.world.cwd); let destination = absolute_output(cwd, path)?; if self .inputs .as_ref() .and_then(|s| s.project()) .is_some_and(|p| p.protects_artifact(&destination)) { return Err("failure report would overwrite an atomic project input or alias".into()); } let mut reserved = vec![ self.request.input.clone(), self.request.output.clone(), self.request.output.with_extension("log"), ]; reserved.extend(self.request.layout_manifest.iter().cloned()); reserved.extend(self.request.resource_manifest.iter().cloned()); for path in reserved { if absolute_output(cwd, &path).is_ok_and(|p| p == destination) { return Err( "native failure manifest must differ from job inputs, outputs and reports" .into(), ); } } if let Some(resources) = &self.resources { if destination == resources.generated_artifacts.ledger_path || destination == resources .generated_artifacts .ledger_path .with_extension("lock") || resources.generated_artifacts.writes.iter().any(|w| { w.path == destination || w.after .as_ref() .or(w.before.as_ref()) .is_some_and(|v| v.path == destination) }) { return Err( "native failure manifest collides with generated artifacts or metadata".into(), ); } } if self.host_preparation.ledger.as_ref().is_some_and(|l|destination==l.path||destination==l.path.with_extension("lock")) || self.host_preparation.observations.iter().any(|o|matches!(o,HostObservation::Operation {name,path,..} if (name=="open lock"||name=="acquire lock")&&(destination==*path||destination==path.with_extension("json")))) { return Err("native failure manifest collides with host metadata".into()); } if self.trace.as_ref().is_some_and(|t| { t.reads.iter().any(|r| r.path == destination) || t.stream_reads.iter().any(|r| r.path == destination) }) || self .inputs .as_ref() .is_some_and(|s| s.files().any(|(p, _)| p == destination)) { return Err("native failure manifest collides with a consumed input".into()); } #[derive(serde::Serialize)] struct Report<'a> { schema: u32, failure: &'a CompileFailure, } let bytes = serde_json::to_vec_pretty(&Report { schema: 1, failure: self, }) .map_err(|e| e.to_string())?; PreparedOutput::write(&destination, &bytes)?.commit_new(&destination) } fn persist_requested(mut self) -> Self { if let Some(path) = &self.request.failure_manifest { if let Err(error) = self.write_manifest(path) { self.evidence_gaps .push(format!("native failure manifest: {error}")); } } self } } struct AttemptEvidence { revision: u64, phase: AttemptPhase, failed_execution: Option, completed_execution: Option>, trace: Option, inputs: Option>, resources: Option, host_preparation: HostPreparation, host_runtime: Vec, world_failure: Option, gaps: Vec, diagnostics: Vec, } impl AttemptEvidence { fn new(revision: u64) -> Self { Self { revision, phase: AttemptPhase::Queued, failed_execution: None, completed_execution: None, trace: None, inputs: None, resources: None, host_preparation: HostPreparation::default(), host_runtime: Vec::new(), world_failure: None, gaps: Vec::new(), diagnostics: Vec::new(), } } fn world(&mut self, world: &FileWorld) { self.trace = Some(world.trace().clone()); self.inputs = Some(world.input_snapshot()); } fn files(&mut self, files: &Files) { self.host_preparation = files.preparation().clone(); self.trace = Some(files.resource_trace().clone()); self.inputs = Some(files.input_snapshot()); match files.snapshot() { Ok(snapshot) => self.resources = Some(snapshot), Err(e) => self.gaps.push(e), } self.host_runtime = files.runtime_observations(); } fn failure(self, error: CompileError, request: AttemptRequest) -> CompileFailure { CompileFailure { request, revision: self.revision, phase: self.phase, error, failed_execution: self.failed_execution, completed_execution: self.completed_execution, trace: self.trace, inputs: self.inputs, resources: self.resources, host_preparation: self.host_preparation, host_runtime: self.host_runtime, world_failure: self.world_failure, evidence_gaps: self.gaps, export_diagnostics: self.diagnostics, } } } impl std::fmt::Display for CompileError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Cancelled => f.write_str("native compilation cancelled"), Self::Execution(e) => e.fmt(f), Self::Host(s) => f.write_str(s), } } } impl std::error::Error for CompileError {} impl From for CompileError { fn from(s: String) -> Self { Self::Host(s) } } fn check(cancellation: &Cancellation) -> Result<(), CompileError> { if cancellation.is_cancelled() { Err(CompileError::Cancelled) } else { Ok(()) } } /// One editor/compiler session. Starting a job supersedes its previous job; /// only a completely exported current revision can replace `latest()` or PDF. #[derive(Clone, Default)] pub struct NativeCompiler { session: NativeSession, latest: Arc>>>, jobs: Arc>, format_cache: Arc, line_break_cache: Arc, entry_checkpoints: Option>, } #[derive(Default)] struct FormatCache(Mutex>); struct CachedFormat { version: ResourceVersion, image: Arc, } impl FormatCache { fn get(&self, version: &ResourceVersion) -> Option> { let cache = self.0.lock().expect("decoded native format cache poisoned"); cache .as_ref() .filter(|old| old.version == *version) .map(|old| old.image.clone()) } fn insert(&self, version: ResourceVersion, image: Arc) { *self.0.lock().expect("decoded native format cache poisoned") = Some(CachedFormat { version, image }); } } pub struct CompileJob { compiler: NativeCompiler, job: RevisionJob, } impl NativeCompiler { /// Enable entry-prefix reuse for atomic project shipout jobs. The byte /// position is a lower bound for a physical command boundary to retain. /// Invalidated prefixes use the same full compiler in the same revision. pub fn with_entry_checkpoints(mut self, minimum_frontier: usize) -> Self { self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(Some(minimum_frontier)))); self } /// Enable automatic prefix selection for a long-lived atomic project session. pub fn with_automatic_entry_checkpoints(mut self) -> Self { self.entry_checkpoints = Some(Arc::new(CheckpointCache::new(None))); self } pub fn start(&self) -> CompileJob { CompileJob { compiler: self.clone(), job: self.session.start(), } } pub fn cancel(&self, revision: u64) { self.session.cancel(revision) } pub fn latest(&self) -> Option> { self.latest .lock() .expect("native completed result poisoned") .clone() } pub fn compile(&self, request: CompileRequest) -> Result, CompileError> { self.start().compile(request) } pub fn compile_detailed( &self, request: CompileRequest, ) -> Result, CompileFailure> { self.start().compile_detailed(request) } } struct PreparedJob { executor: Option, format_preparation: Option, source: SourceFile, files: Files, output: PathBuf, } #[derive(Clone, Copy, PartialEq, Eq)] enum KernelPreparation { Fresh, Resume, } fn prepare( request: &CompileRequest, dump: bool, format_cache: Option<&FormatCache>, cancellation: &Cancellation, evidence: &mut AttemptEvidence, ) -> Result { prepare_checked( request, dump, format_cache, cancellation, evidence, None, EffectMode::Live, KernelPreparation::Fresh, ) } fn prepare_checked( request: &CompileRequest, dump: bool, format_cache: Option<&FormatCache>, cancellation: &Cancellation, evidence: &mut AttemptEvidence, check_inputs: Option>>, effects: EffectMode, kernel: KernelPreparation, ) -> Result { use texrra_tex_core::resources::ResourceKind; check(cancellation)?; if effects == EffectMode::Draft && (dump || request.layout_manifest.is_some() || request.resource_manifest.is_some()) { return Err(CompileError::Host( "draft effects require a document job without external reports".into(), )); } if request.layout_manifest.is_some() && (dump || request.target != Target::Shipouts) { return Err(CompileError::Host( "--layout-manifest requires a native document job".into(), )); } if dump && (!matches!(request.entry, Entry::Initex) || request.target != Target::Shipouts) { return Err(CompileError::Host( "format dump requires INITEX and actual shipouts".into(), )); } if dump && request.observer.is_some() { return Err(CompileError::Host( "format construction uses a cancellation token rather than revision observers".into(), )); } if request.inputs.is_some() && request.project.is_some() { return Err(CompileError::Host( "select an atomic project or captured inputs, not both".into(), )); } let mut world = if let Some(project) = &request.project { if project.configuration() != request.world { return Err(CompileError::Host( "atomic project configuration differs from request".into(), )); } FileWorld::from_project(project.clone())? } else if let Some(inputs) = &request.inputs { evidence.inputs = Some(inputs.clone()); if request.world != inputs.configuration() { return Err(CompileError::Host( "native input snapshot configuration differs from request".into(), )); } FileWorld::from_snapshot(inputs.clone())? } else { let mut world = FileWorld::new_detailed(request.world.clone()).map_err(|failure| { let error = failure.error.clone(); evidence.world_failure = Some(failure); CompileError::Host(error) })?; world.capture_inputs(); world }; let prepared = (|| -> Result<_, CompileError> { evidence.host_preparation.phase = HostPreparationPhase::OutputPaths; let output = evidence .host_preparation .output(&world.trace().cwd, &request.output)?; world.check_artifact_output(&output)?; let loaded = world.read( ResourceKind::Tex, &request.input.display().to_string(), &request.input, )?; let path = loaded.version.path; if output == path || output.canonicalize().ok().as_ref() == Some(&path) { return Err(CompileError::Host( "native PDF output must differ from the input source".into(), )); } let source = SourceFile { name: path.display().to_string(), data: loaded.data, }; check(cancellation)?; let state = if matches!(request.entry, Entry::Initex) { State::initex() } else { State::default() } .with_job_time(request.time) .with_input_profile(request.input_profile); let state = if request.target == Target::Shipouts && !dump { state.with_pdf_output() } else { state }; let state = if request.etex { state.with_etex() } else { state }; let (executor, format_preparation) = if let Entry::Format(name) = &request.entry { let loaded = world.read_shared(ResourceKind::Tex, &name.display().to_string(), &path)?; check(cancellation)?; let read = |world: &mut FileWorld, resource: &std::path::Path| { check(cancellation).map_err(|e| e.to_string())?; world .read_shared(ResourceKind::Tex, &resource.display().to_string(), &path) .map(|r| r.data) }; let date = |world: &mut FileWorld, name: &str, from: &str| { check(cancellation).map_err(|e| e.to_string())?; file_modification_date(world, name, from) }; match format_cache { Some(cache) => { let (image, preparation) = match cache.get(&loaded.version) { Some(image) => (image, FormatPreparation::Reused), None => ( Arc::new(FormatImage::decode(&loaded.data)?), FormatPreparation::Decoded, ), }; let executor = if kernel == KernelPreparation::Resume { image.validate_job_inputs( state.profile(), request.input_profile, &mut world, read, date, )?; None } else { Some(image.fork_job_with_file_dates( state.profile(), request.input_profile, request.time, request.limits, &mut world, read, date, )?) }; check(cancellation)?; if preparation == FormatPreparation::Decoded { cache.insert(loaded.version, image); } (executor, Some(preparation)) } None => { let image = FormatImage::decode(&loaded.data)?; let executor = if kernel == KernelPreparation::Resume { image.validate_job_inputs( state.profile(), request.input_profile, &mut world, read, date, )?; None } else { Some(image.new_job_with_file_dates( state.profile(), request.input_profile, request.time, request.limits, &mut world, read, date, )?) }; (executor, Some(FormatPreparation::Decoded)) } } } else { let executor = (kernel == KernelPreparation::Fresh).then(|| Executor::new(state, request.limits)); (executor, None) }; check(cancellation)?; Ok((path, source, executor, output, format_preparation)) })(); evidence.world(&world); let (path, source, executor, output, format_preparation) = prepared?; let files = Files::new_with_terminal( &path, &output, world, request.terminal, &request.generated_inputs, &mut evidence.host_preparation, check_inputs, effects, ) .map_err(|failure| { evidence.trace = Some(failure.trace); evidence.inputs = Some(failure.inputs); CompileError::Host(failure.error) })?; let executor = executor.map(|executor| { if request.target == Target::Shipouts { executor.with_native_pages() } else { executor } }); Ok(PreparedJob { executor, format_preparation, source, files, output, }) } fn report(files: &Files, request: &CompileRequest) -> Result<(), CompileError> { if let Some(path) = &request.resource_manifest { files.write_resource_manifest(path)?; } Ok(()) } impl CompileJob { pub fn revision(&self) -> u64 { self.job.revision() } pub fn compile(self, request: CompileRequest) -> Result, CompileError> { self.compile_detailed(request) .map_err(|failure| failure.error) } pub fn compile_detailed( self, mut request: CompileRequest, ) -> Result, CompileFailure> { if self.compiler.entry_checkpoints.is_some() && checkpoint_guard::can_stage(&request) && matches!(&request.generated_inputs, GeneratedInputPolicy::Live) { request.generated_inputs = GeneratedInputPolicy::Observe; } let mut evidence = AttemptEvidence::new(self.revision()); let summary = AttemptRequest::from(&request); match self.compile_observed(request, &mut evidence) { Ok(document) => Ok(document), Err(error) => Err(evidence.failure(error, summary).persist_requested()), } } fn compile_observed( self, request: CompileRequest, evidence: &mut AttemptEvidence, ) -> Result, CompileError> { let cancellation = self.job.cancellation(); check(&cancellation)?; // Starting a revision stays nonblocking; actual same-session I/O waits // for the cancelled predecessor to release its project handles. let _job_guard = self .compiler .jobs .lock() .map_err(|_| CompileError::Host("native job queue poisoned".into()))?; let revision = self.job.revision(); evidence.phase = AttemptPhase::Preparing; let checkpoints = self .compiler .entry_checkpoints .as_deref() .filter(|_| checkpoint_guard::can_stage(&request)); let format_cache = &self.compiler.format_cache; let mut entry_checkpoint_work = EntryCheckpointWork::default(); let mut active_checkpoint = checkpoints .and_then(CheckpointCache::current) .and_then(|available| match available.select(&request) { Ok(selected) => Some(selected), Err(error) => { entry_checkpoint_work.rejection = Some(error); None } }); let prepared = match active_checkpoint.as_ref() { Some(candidate) => { match candidate.prepare(&request, format_cache, &cancellation, evidence) { Ok(prepared) => Some(prepared), Err(error) => { check(&cancellation)?; *evidence = AttemptEvidence::new(revision); entry_checkpoint_work.rejection = Some(error.to_string()); active_checkpoint = None; None } } } None => None, }; let PreparedJob { executor, format_preparation, source, files, output, } = if let Some(prepared) = prepared { prepared } else { prepare_checked( &request, false, Some(format_cache), &cancellation, evidence, None, if checkpoints.is_some() { EffectMode::Draft } else { EffectMode::Live }, KernelPreparation::Fresh, ) .map_err(|error| { if cancellation.is_cancelled() { CompileError::Cancelled } else { error } })? }; let mut available_host = Some(files); evidence.inputs = None; evidence.trace = None; let result = (|| -> Result, CompileError> { let files = available_host.as_mut().expect("prepared native host"); if let Some(path) = &request.layout_manifest { files.check_layout_manifest_path(path, request.resource_manifest.as_deref())?; } evidence.phase = AttemptPhase::Prepared; notify(&request, revision, CompileStage::Prepared, &cancellation)?; evidence.phase = AttemptPhase::Executing; let cache = &self.compiler.line_break_cache; 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)?; (executed, Some(next)) } else { let executor = executor .expect("fresh native job has an executor") .with_line_break_cache(cache.clone()); if let Some(cache) = checkpoints { let (executed, captured) = cache.capture(&request, self.job, executor, source, files); if let Some(snapshot) = &captured { snapshot.report_capture(&mut entry_checkpoint_work); } (executed, captured) } else { (self.job.run_detailed(executor, source, files), None) } }; let execution = match executed { Ok(execution) => { evidence.completed_execution = Some(execution.clone()); report(files, &request)?; execution } Err(failure) => { evidence.failed_execution = failure.failed_execution; evidence.completed_execution = failure.completed_execution; if let Err(error) = report(files, &request) { evidence.gaps.push(error.to_string()); } return Err(match failure.error { RevisionError::Cancelled => CompileError::Cancelled, RevisionError::Execution(e) => CompileError::Execution(e), }); } }; let line_break_work = cache.work().since(before); if execution.execution.format_dumped { return Err(CompileError::Host( "native format dump requires --dump-format".into(), )); } notify(&request, revision, CompileStage::Executed, &cancellation)?; evidence.phase = AttemptPhase::Layout; let e = &execution.execution; let (mut pages, paper_width, paper_height, origin) = if request.target == Target::Shipouts { ( e.shipout_display_lists().map_err(|e| e.to_string())?, 0, 0, texrra_tex_core::pdf::PageOrigin::default(), ) } else { let document = e.document().map_err(|e| e.to_string())?; let engine = texrra_tex_core::Engine::layout_paged(&document) .ok_or_else(|| CompileError::Host("unsupported native vertical list".into()))?; ( engine.pages().iter().map(|p| p.display_list()).collect(), document.paper_width, document.paper_height, texrra_tex_core::pdf::PageOrigin { h_offset: document.h_offset, v_offset: document.v_offset, }, ) }; if let Some(path) = &request.layout_manifest { let source_map = texrra_tex_core::source_map::SourceMap::from_revision(&execution, &pages)?; files.write_layout_manifest(path, e, &pages, &source_map)?; } evidence.phase = AttemptPhase::Fonts; let fonts = texrra_tex_core::native_font::resolve_native_fonts(&mut pages, files); let reported = report(files, &request); if let Err(error) = fonts { if let Err(report) = reported { evidence.gaps.push(report.to_string()); } return Err(CompileError::Host(error)); } reported?; let source_map = texrra_tex_core::source_map::SourceMap::from_revision(&execution, &pages)?; notify( &request, revision, CompileStage::FontsResolved, &cancellation, )?; evidence.phase = AttemptPhase::Export; let (pdf, export_diagnostics) = if pages.is_empty() { (None, Vec::new()) } else if request.target == Target::Shipouts { let document = texrra_tex_core::pdf::shipout_lists_to_native_pdf_document( &pages, e.state.pdf_final_options(), )?; (Some(document.bytes), document.diagnostics) } else { ( Some(texrra_tex_core::pdf::display_lists_to_native_pdf( &pages, paper_width, paper_height, origin, )?), Vec::new(), ) }; evidence.diagnostics = export_diagnostics.clone(); notify(&request, revision, CompileStage::Exported, &cancellation)?; for warning in &export_diagnostics { files.observe_message(&format!("native PDF warning: {warning}"))?; } evidence.phase = AttemptPhase::Finishing; let finished = files.finish(); let reported = report(files, &request); if let Err(error) = finished { if let Err(report) = reported { evidence.gaps.push(report.to_string()); } return Err(CompileError::Host(error)); } reported?; let resources = files.snapshot()?; let inputs = files.input_snapshot(); let prepared = pdf .as_ref() .map(|bytes| PreparedOutput::write(&output, bytes)) .transpose()?; let receipt = prepared.as_ref().map(|p| p.version(&output)).transpose()?; let previous = self.compiler.latest(); // PDF-composited SVG is derived from the complete device output. // Reuse it only when the bytes underlying this rendering agree. let pdf_unchanged = pages.iter().any(DisplayList::has_embedded_pdf) && previous .as_deref() .is_some_and(|document| document.pdf.as_deref() == pdf.as_deref()); let preview = PreviewState::new( &pages, previous.as_deref().map(|document| { ( document.revision(), document.pages.as_slice(), &document.preview, ) }), pdf_unchanged, ); let result = Arc::new(CompiledDocument { format_preparation, entry_checkpoint_work, line_break_work, execution, pages, source_map, resources, inputs, host_preparation: files.preparation().clone(), host_runtime: files.runtime_observations(), export_diagnostics, pdf: pdf.map(Arc::from), output: receipt, preview, }); evidence.phase = AttemptPhase::ReadyToPublish; notify( &request, revision, CompileStage::ReadyToPublish, &cancellation, )?; evidence.phase = AttemptPhase::Publishing; let expose = || { *self .compiler .latest .lock() .expect("native completed result poisoned") = Some(result.clone()); }; let published = if let Some(cache) = checkpoints { let publication = available_host .take() .expect("prepared draft host") .seal_draft(prepared) .and_then(|draft| { draft.publish_current(&self.compiler.session, result.revision(), || { cache.set(next_checkpoint); expose(); }) }); if !matches!(publication, Ok(Some(()))) { evidence.host_preparation = result.host_preparation.clone(); evidence.inputs = Some(result.inputs.clone()); evidence.trace = Some(result.resources.trace.clone()); evidence.resources = Some(result.resources.clone()); evidence.host_runtime = result.host_runtime.clone(); } publication? } else { self.compiler .session .publish_current(result.revision(), || { if let Some(prepared) = prepared { prepared.commit(&output)?; } expose(); Ok::<_, String>(()) })? }; if published.is_none() { return Err(CompileError::Cancelled); } Ok(result) })(); if result.is_err() && let Some(mut files) = available_host { evidence.gaps.extend(files.finish_failed()); if let Err(error) = report(&files, &request) { evidence.gaps.push(error.to_string()); } evidence.files(&files); } result } } /// Offline format construction uses the same host and kernel. Its destination /// must be new; cancellation never publishes a partially prepared format. pub fn dump_format( request: CompileRequest, cancellation: Cancellation, ) -> Result { dump_format_detailed(request, cancellation).map_err(|failure| failure.error) } /// A format build has no editor-session revision; revision zero identifies the /// offline attempt. Its source versions and host effects are still actual. pub fn dump_format_detailed( request: CompileRequest, cancellation: Cancellation, ) -> Result { let mut evidence = AttemptEvidence::new(0); let summary = AttemptRequest::from(&request); evidence.phase = AttemptPhase::Preparing; dump_format_observed(request, cancellation, &mut evidence) .map_err(|error| evidence.failure(error, summary).persist_requested()) } fn dump_format_observed( request: CompileRequest, cancellation: Cancellation, evidence: &mut AttemptEvidence, ) -> Result { let PreparedJob { executor, format_preparation: _, source, mut files, output, } = prepare(&request, true, None, &cancellation, evidence)?; evidence.inputs = None; evidence.trace = None; let result = (|| -> Result { evidence.phase = AttemptPhase::Executing; let executed = executor .expect("format dump has a fresh executor") .with_cancellation(cancellation.clone()) .run_detailed(source, &mut files); let execution = match executed { Ok(execution) => { let execution = Arc::new(RevisionExecution::from_execution( 0, execution, Some(files.resource_trace().clone()), )); evidence.completed_execution = Some(execution.clone()); report(&files, &request)?; check(&cancellation)?; execution } Err(failure) => { let error = if cancellation.is_cancelled() { CompileError::Cancelled } else { CompileError::Execution(failure.error.clone()) }; evidence.failed_execution = Some(failure); if let Err(report) = report(&files, &request) { evidence.gaps.push(report.to_string()); } return Err(error); } }; evidence.phase = AttemptPhase::Export; let trace = files.resource_trace(); // Keep the completed kernel result available if format validation/encoding // fails. This extra offline copy is not part of interactive compilation. let bytes = FormatImage::from_dump( execution.execution.clone(), trace.reads.clone(), trace.stream_reads.clone(), )? .encode()?; evidence.phase = AttemptPhase::Finishing; let finished = files.finish(); let reported = report(&files, &request); if let Err(error) = finished { if let Err(report) = reported { evidence.gaps.push(report.to_string()); } return Err(CompileError::Host(error)); } reported?; let resources = files.snapshot()?; let inputs = files.input_snapshot(); let prepared = PreparedOutput::write(&output, &bytes)?; let version = prepared.version(&output)?; evidence.phase = AttemptPhase::ReadyToPublish; check(&cancellation)?; evidence.phase = AttemptPhase::Publishing; prepared.commit_new(&output)?; Ok(BuiltFormat { output: version, resources, inputs, host_preparation: files.preparation().clone(), host_runtime: files.runtime_observations(), execution, }) })(); if result.is_err() { evidence.gaps.extend(files.finish_failed()); if let Err(report) = report(&files, &request) { evidence.gaps.push(report.to_string()); } evidence.files(&files); } result }