Let resumed SVG drafts precede a new final-state fingerprint

This commit is contained in:
gloamxun committed 2026-12-02 05:58:32 +08:00
1 parent 1a2379a6c2
commit 58b0f16998
9 files changed
+519 -84

No files matched your search

+93 -18
View File
@@ -35,7 +35,8 @@ use texrra_tex_core::{
execution::{
Cancellation, CheckpointCloneTimings, ExecutionFailure, Executor, FormatImage, InputProfile,
JobTime, Limits,
NativeSession, Profile, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
NativeSession, PreparedRevisionExecution, Profile, ResumedExecution, RevisionError,
RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
SourceProvider, State, SuffixKernelTimings, WriteDestination,
},
pdf_unicode::XdvGlyphNames,
@@ -146,6 +147,12 @@ pub trait CompileObserver: Send + Sync {
false
}
/// Allow a resumed direct SVG draft before hashing a new final state.
/// The completed execution and publication still require the exact digest.
fn preview_before_fingerprint(&self) -> bool {
false
}
/// Called once per compile attempt for a draft before publication. Observers
/// can receive SVG-only drafts before PDF export. The compile result
/// determines whether this revision actually published.
@@ -161,6 +168,7 @@ pub struct DraftPreview<'a> {
preview: &'a PreviewState,
pdf: Option<&'a Arc<[u8]>>,
steps: usize,
state_fingerprint_pending: bool,
work: &'a EntryCheckpointWork,
cancellation: &'a Cancellation,
}
@@ -180,6 +188,12 @@ impl DraftPreview<'_> {
self.steps
}
/// True when this draft was produced from a final state whose canonical
/// fingerprint will be calculated before the revision can be published.
pub fn state_fingerprint_pending(&self) -> bool {
self.state_fingerprint_pending
}
pub fn entry_checkpoint_work(&self) -> &EntryCheckpointWork {
self.work
}
@@ -1092,6 +1106,26 @@ impl CompileJob {
Err(error) => Err(evidence.failure(error, summary).persist_requested()),
}
}
fn finish_prepared_execution(
prepared: PreparedRevisionExecution,
evidence: &mut AttemptEvidence,
) -> Result<Arc<RevisionExecution>, CompileError> {
match prepared.finish() {
Ok(execution) => {
evidence.completed_execution = Some(execution.clone());
Ok(execution)
}
Err(failure) => {
evidence.failed_execution = failure.failed_execution;
evidence.completed_execution = failure.completed_execution;
Err(match failure.error {
RevisionError::Cancelled => CompileError::Cancelled,
RevisionError::Execution(error) => CompileError::Execution(error),
})
}
}
}
fn compile_observed(
&self,
request: &CompileRequest,
@@ -1168,6 +1202,7 @@ impl CompileJob {
})?
};
let mut available_host = Some(files);
let mut prepared_execution = None;
evidence.inputs = None;
evidence.trace = None;
let result = (|| -> Result<Arc<CompiledDocument>, CompileError> {
@@ -1182,7 +1217,8 @@ impl CompileJob {
evidence.phase = AttemptPhase::Executing;
let cache = &self.compiler.line_break_cache;
let before = cache.work();
let (executed, next_checkpoint, reused_layouts) = if let Some(current) = active_checkpoint {
let (executed, next_checkpoint, resumed_checkpoints, reused_layouts) =
if let Some(current) = active_checkpoint {
debug_assert!(executor.is_none());
let (executed, next, reused_layouts) = current.resume(
&request,
@@ -1194,7 +1230,7 @@ impl CompileJob {
allow_suffix,
suffix_failure,
)?;
(executed, Some(next), reused_layouts)
(executed, None, Some(next), reused_layouts)
} else {
let executor = executor
.expect("fresh native job has an executor")
@@ -1205,16 +1241,20 @@ impl CompileJob {
if let Some(snapshot) = &captured {
snapshot.report_capture(&mut entry_checkpoint_work);
}
(executed, captured, None)
(executed.map(ResumedExecution::Complete), captured, None, None)
} else {
(self.job.run_detailed(executor, source, files), None, None)
(self.job.run_detailed(executor, source, files).map(ResumedExecution::Complete),
None, None, None)
}
};
let execution = match executed {
Ok(execution) => {
let mut completed = match executed {
Ok(ResumedExecution::Complete(execution)) => {
evidence.completed_execution = Some(execution.clone());
report(files, &request)?;
execution
Some(execution)
}
Ok(ResumedExecution::Prepared(execution)) => {
prepared_execution = Some(execution);
None
}
Err(failure) => {
evidence.failed_execution = failure.failed_execution;
@@ -1228,15 +1268,22 @@ impl CompileJob {
});
}
};
report(files, &request)?;
let line_break_work = cache.work().since(before);
if execution.execution.format_dumped {
let (format_dumped, steps, state) = if let Some(prepared) = &prepared_execution {
let execution = prepared.execution();
(execution.format_dumped, execution.steps, &execution.state)
} else {
let execution = &completed.as_ref().expect("completed execution").execution;
(execution.format_dumped, execution.steps, &execution.state)
};
if 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 font_cache = &self.compiler.font_cache;
let type1_before = font_cache.type1_work();
let prior_layout = checkpoints.and_then(|_| self.compiler.latest());
@@ -1256,7 +1303,7 @@ impl CompileJob {
if let Event::Shipout(page) = event { Some(page.as_ref()) } else { None }
}).zip(&prior.shipout_layouts)
}).enumerate();
let pages = e.shipout_display_lists_with(|page| {
let mut lower = |page: &texrra_tex_core::execution::NativeShipout| {
let reused = old.next().and_then(|(index, (prior, layout))| {
relocated_suffix
.and_then(|suffix| suffix.relocate_layout(index, layout))
@@ -1274,9 +1321,16 @@ impl CompileJob {
shipout_layouts.push(Arc::new(layout.clone()));
}
Ok(layout)
}).map_err(|e| e.to_string())?;
};
let pages = if let Some(prepared) = &prepared_execution {
prepared.execution().shipout_display_lists_with(&mut lower)
} else {
completed.as_ref().expect("completed shipout execution").execution
.shipout_display_lists_with(&mut lower)
}.map_err(|e| e.to_string())?;
(pages, 0, 0, texrra_tex_core::pdf::PageOrigin::default())
} else {
let e = &completed.as_ref().expect("completed document layout execution").execution;
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()))?;
@@ -1300,10 +1354,11 @@ impl CompileJob {
));
}
let draft_mode =
request.target == Target::Shipouts && !dvi_mode && e.state.pdf_draft_mode();
request.target == Target::Shipouts && !dvi_mode && state.pdf_draft_mode();
if let Some(path) = &request.layout_manifest {
let source_map = self.compiler.session.source_map(&execution, &pages)?;
files.write_layout_manifest(path, e, &pages, &source_map)?;
let execution = completed.as_ref().expect("completed manifest execution");
let source_map = self.compiler.session.source_map(execution, &pages)?;
files.write_layout_manifest(path, &execution.execution, &pages, &source_map)?;
}
evidence.phase = AttemptPhase::Fonts;
let mut preview_fonts = if draft_mode {
@@ -1343,7 +1398,11 @@ impl CompileJob {
}
}
};
let source_map = self.compiler.session.source_map(&execution, &pages)?;
let source_map = if let Some(prepared) = &prepared_execution {
prepared.source_map(&pages)
} else {
self.compiler.session.source_map(completed.as_ref().expect("completed source map execution"), &pages)
}?;
notify(
&request,
revision,
@@ -1389,7 +1448,8 @@ impl CompileJob {
pages: &pages,
preview: &preview,
pdf: None,
steps: e.steps,
steps,
state_fingerprint_pending: prepared_execution.is_some(),
work: &entry_checkpoint_work,
cancellation: &cancellation,
});
@@ -1399,6 +1459,14 @@ impl CompileJob {
} else {
None
};
if let Some(prepared) = prepared_execution.take() {
completed = Some(Self::finish_prepared_execution(*prepared, evidence)?);
}
let execution = completed.expect("completed execution before export");
let next_checkpoint = resumed_checkpoints
.map(|checkpoints| checkpoints.bind(&execution))
.or(next_checkpoint);
let e = &execution.execution;
let mut dvi = None;
let (pdf, export_diagnostics) = if pages.is_empty() {
(None, Vec::new())
@@ -1513,6 +1581,7 @@ impl CompileJob {
preview: &result.preview,
pdf: result.pdf.as_ref(),
steps: result.execution.execution.steps,
state_fingerprint_pending: false,
work: &result.entry_checkpoint_work,
cancellation: &cancellation,
});
@@ -1565,6 +1634,12 @@ impl CompileJob {
}
Ok(result)
})();
if let Some(prepared) = prepared_execution.take() {
// Preserve the actual completed kernel result on any error before
// export, including cancellation requested from the draft callback.
debug_assert!(result.is_err());
let _ = Self::finish_prepared_execution(*prepared, evidence);
}
if result.is_err()
&& let Some(mut files) = available_host
{
+78 -35
View File
@@ -10,7 +10,7 @@ use std::{
time::Instant,
};
use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, RetainedStateFingerprint, StatisticsPhase, StatisticsReport},
execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, ResumedExecution, RetainedStateFingerprint, StatisticsPhase, StatisticsReport},
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
};
#[cfg(test)]
@@ -89,6 +89,44 @@ pub(super) struct CheckpointSet {
edit_frontier: Option<usize>,
}
struct CapturedCheckpointSet {
set: CheckpointSet,
completion: Option<CapturedCompletion>,
}
struct CapturedCompletion {
guard: PrefixInputGuard,
trace: ResourceTrace,
settled: BTreeMap<usize, SettledCheckpoint>,
}
impl CapturedCheckpointSet {
fn bind(mut self, result: &Arc<RevisionExecution>) -> Arc<CheckpointSet> {
self.set.completion = self.completion.map(|completion| Arc::new(CompletedExecution {
result: result.clone(),
guard: completion.guard,
calls: self.set.calls.clone(),
trace: completion.trace,
settled: completion.settled,
}));
Arc::new(self.set)
}
}
pub(super) struct ResumedCheckpoints {
fallback: Arc<CheckpointSet>,
captured: Option<CapturedCheckpointSet>,
}
impl ResumedCheckpoints {
pub(super) fn bind(self, result: &Arc<RevisionExecution>) -> Arc<CheckpointSet> {
match self.captured {
Some(captured) => captured.bind(result),
None => self.fallback,
}
}
}
pub(super) struct SelectedCheckpoint {
set: Arc<CheckpointSet>,
candidate: ExecutionCandidate,
@@ -495,10 +533,9 @@ impl<'a> CapturedEntries<'a> {
self,
recording: RecordingHost,
refresh_on_resume: bool,
result: &Arc<RevisionExecution>,
suffix_base: Option<Arc<CompletedExecution>>,
inherited: impl Iterator<Item = &'b Arc<CachedCheckpoint>>,
) -> Option<Arc<CheckpointSet>> {
) -> Option<CapturedCheckpointSet> {
if !self.changed {
return None;
}
@@ -582,22 +619,21 @@ impl<'a> CapturedEntries<'a> {
if completion.is_none() {
calls.truncate(replay_count);
}
let calls = Arc::<[Call]>::from(calls);
let completion = completion.map(|(guard, trace)| Arc::new(CompletedExecution {
result: result.clone(),
guard,
calls: calls.clone(),
trace,
settled: self.settled,
}));
Some(Arc::new(CheckpointSet {
entries,
calls,
completion,
suffix_base,
refresh_on_resume,
edit_frontier,
}))
Some(CapturedCheckpointSet {
set: CheckpointSet {
entries,
calls: Arc::from(calls),
completion: None,
suffix_base,
refresh_on_resume,
edit_frontier,
},
completion: completion.map(|(guard, trace)| CapturedCompletion {
guard,
trace,
settled: self.settled,
}),
})
}
}
@@ -724,7 +760,8 @@ impl CheckpointCache {
|slots, entry, host| captures.capture(slots, Arc::new(entry), host),
);
let next = result.as_ref().ok().and_then(|result| {
captures.finish(recording, self.minimum_frontier.is_none(), result, None, std::iter::empty())
captures.finish(recording, self.minimum_frontier.is_none(), None, std::iter::empty())
.map(|captured| captured.bind(result))
});
(result, next)
}
@@ -995,8 +1032,8 @@ impl SelectedCheckpoint {
suffix_failure: &mut Option<(String, usize)>,
) -> Result<
(
Result<Arc<RevisionExecution>, RevisionFailure>,
Arc<CheckpointSet>,
Result<ResumedExecution, RevisionFailure>,
ResumedCheckpoints,
Option<ReusedShipoutLayouts>,
),
CompileError,
@@ -1010,8 +1047,9 @@ impl SelectedCheckpoint {
work.reused_completion = true;
work.replayed_calls = completed.calls.len();
return Ok((
job.reuse_completed_after_host_replay(&completed.result, files),
self.set,
job.reuse_completed_after_host_replay(&completed.result, files)
.map(ResumedExecution::Complete),
ResumedCheckpoints { fallback: self.set, captured: None },
None,
));
}
@@ -1028,7 +1066,11 @@ impl SelectedCheckpoint {
let result = job
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
.ok_or_else(changed_prefix)?;
return Ok((result, self.set, None));
return Ok((
result.map(ResumedExecution::Complete),
ResumedCheckpoints { fallback: self.set, captured: None },
None,
));
}
let previous = checkpoint
@@ -1099,13 +1141,16 @@ impl SelectedCheckpoint {
let mut clones = CheckpointCloneTimings::default();
let resume_started = timed.then(Instant::now);
let result = job
.resume_deciding_suffix_observed(
.resume_deciding_suffix_prepared(
&checkpoint.entry,
source,
nested_source,
&mut recording,
line_break_cache,
detailed_observer.is_some().then_some(&mut clones),
observer.is_some_and(|observer| {
observer.preview_before_export() && observer.preview_before_fingerprint()
}),
|source, pages| {
if source.is_entry {
// The loaded entry line can be shared by several shipouts.
@@ -1211,10 +1256,9 @@ impl SelectedCheckpoint {
timings.resume = started.elapsed();
timings.clones = clones;
}
let next = measure(&mut timings.retain, timed, || {
result.as_ref().ok().and_then(|result| {
captures.finish(recording, true, result, suffix_base, inherited)
})
let captured = measure(&mut timings.retain, timed, || {
result.is_ok().then(|| captures.finish(recording, true, suffix_base, inherited))
.flatten()
});
if result.is_ok() {
if let Some(observer) = &request.observer {
@@ -1223,12 +1267,11 @@ impl SelectedCheckpoint {
} else {
reused_layouts = None;
}
if let Some(next) = next {
next.report_capture(work);
Ok((result, next, reused_layouts))
} else {
Ok((result, self.current_set_for_nested_resume.unwrap_or(self.set), reused_layouts))
if let Some(captured) = &captured {
captured.set.report_capture(work);
}
let fallback = self.current_set_for_nested_resume.unwrap_or(self.set);
Ok((result, ResumedCheckpoints { fallback, captured }, reused_layouts))
}
}