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

+23 -9
View File
@@ -454,6 +454,7 @@ impl EntryCheckpoint {
self.resume_observed(source, None, files, cancellation, None, None, None, self.resume_observed(source, None, files, cancellation, None, None, None,
|_, _, _, _| CheckpointDecision::Continue) |_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix") .expect("ordinary resume cannot reject a cached suffix")
.map(|result| result.map(|execution| execution.finish_fingerprint(None)))
} }
pub(super) fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>( pub(super) fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>(
@@ -481,6 +482,7 @@ impl EntryCheckpoint {
}), }),
) )
.expect("ordinary resume cannot reject a cached suffix") .expect("ordinary resume cannot reject a cached suffix")
.map(|result| result.map(|execution| execution.finish_fingerprint(previous)))
} }
pub(super) fn resume_deciding_suffix<F: SourceProvider, S>( pub(super) fn resume_deciding_suffix<F: SourceProvider, S>(
@@ -494,7 +496,7 @@ impl EntryCheckpoint {
timings: Option<&mut CheckpointCloneTimings>, timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>, select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision, capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> { ) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> {
let measured = timings.is_some().then(Cell::default); let measured = timings.is_some().then(Cell::default);
let result = self.resume_observed( let result = self.resume_observed(
source, nested, files, cancellation, Some(line_break_cache), previous, measured.as_ref(), source, nested, files, cancellation, Some(line_break_cache), previous, measured.as_ref(),
@@ -516,7 +518,7 @@ impl EntryCheckpoint {
previous: Option<&Execution>, previous: Option<&Execution>,
timings: Option<&Cell<CheckpointCloneTimings>>, timings: Option<&Cell<CheckpointCloneTimings>>,
capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision, capture_boundary: impl FnMut(&mut Executor, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<Option<Result<Execution, ExecutionFailure>>, String> { ) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> {
if !self.accepts_entry(&source) if !self.accepts_entry(&source)
|| match &nested { || match &nested {
Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data), Some(nested) => !self.accepts_nested_source(&nested.name, &nested.data),
@@ -559,14 +561,15 @@ impl EntryCheckpoint {
}); });
let result = match result { let result = match result {
Ok(CheckpointDecision::Reuse(execution)) => { Ok(CheckpointDecision::Reuse(execution)) => {
return Ok(Some(Ok(*execution))); let fingerprint = super::DeferredStateFingerprint(Some(execution.outgoing_state));
return Ok(Some(Ok(execution.with_outgoing_state(fingerprint))));
} }
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error), Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error),
Ok(CheckpointDecision::Continue) => Ok(()), Ok(CheckpointDecision::Continue) => Ok(()),
Err(error) => Err(error), Err(error) => Err(error),
}; };
let result = executor.finish_observed_input(result, files); let result = executor.finish_observed_input(result, files);
Ok(Some(executor.finish_execution(result, self.incoming_state, previous))) Ok(Some(executor.prepare_execution(result, self.incoming_state, previous)))
} }
} }
@@ -4083,11 +4086,21 @@ impl Executor {
} }
} }
fn finish_execution( fn finish_execution(
mut self, self,
result: Result<(), Error>, result: Result<(), Error>,
incoming_state: u64, incoming_state: u64,
previous: Option<&Execution>, previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> { ) -> Result<Execution, ExecutionFailure> {
self.prepare_execution(result, incoming_state, previous)
.map(|execution| execution.finish_fingerprint(previous))
}
fn prepare_execution(
mut self,
result: Result<(), Error>,
incoming_state: u64,
previous: Option<&Execution>,
) -> Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure> {
let (reads, dependency_evidence) = self.take_dependency_reads(); let (reads, dependency_evidence) = self.take_dependency_reads();
let result = result.and_then(|()| { let result = result.and_then(|()| {
if self.shipped_pages > 0 && !self.format_dumped if self.shipped_pages > 0 && !self.format_dumped
@@ -4136,10 +4149,11 @@ impl Executor {
} }
// An identical completed state has the same fingerprint. Compare // An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments. // the entire state, including token source spans and assignments.
let outgoing_state = match previous { let outgoing_state = super::DeferredStateFingerprint(
Some(last) if last.state == self.state => last.outgoing_state, previous
last => self.state.fingerprint_with_prior(last.map(|last| &last.state)), .filter(|last| last.state == self.state)
}; .map(|last| last.outgoing_state),
);
let format_pdf_images = self.captured_format_pdf_images(); let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution { Ok(Execution {
format_dumped: self.format_dumped, format_dumped: self.format_dumped,
+54 -4
View File
@@ -102,7 +102,8 @@ pub(crate) use registers::print_scaled;
pub use registers::{Flex, Glue, Register, RegisterKind, RegisterValue}; pub use registers::{Flex, Glue, Register, RegisterKind, RegisterValue};
pub use rule::NativeRule; pub use rule::NativeRule;
pub use session::{ pub use session::{
NativeSession, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceVersion, NativeSession, PreparedRevisionExecution, ResumedExecution, RevisionError, RevisionExecution,
RevisionFailure, RevisionJob, SourceVersion,
}; };
pub use state::{CommandName, LinePenaltyKind, Macro, Meaning, Primitive, Profile, Replacement, State}; pub use state::{CommandName, LinePenaltyKind, Macro, Meaning, Primitive, Profile, Replacement, State};
@@ -653,7 +654,7 @@ fn default_interaction_mode() -> u8 {
} }
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Execution { pub struct Execution<F = u64> {
#[serde(default)] #[serde(default)]
pub format_dumped: bool, pub format_dumped: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde(default, skip_serializing_if = "Vec::is_empty")]
@@ -689,7 +690,7 @@ pub struct Execution {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
line_observations: Option<BTreeMap<usize, usize>>, line_observations: Option<BTreeMap<usize, usize>>,
pub incoming_state: u64, pub incoming_state: u64,
pub outgoing_state: u64, pub outgoing_state: F,
pub steps: usize, pub steps: usize,
/// Completed charge count for proving remaining box capacity at a splice. /// Completed charge count for proving remaining box capacity at a splice.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
@@ -700,6 +701,55 @@ pub struct Execution {
accounts_event_history: bool, accounts_event_history: bool,
} }
/// The exact final state is available for layout. Its fingerprint may still
/// require the canonical hash before a completed execution can be published.
#[derive(Debug)]
pub struct DeferredStateFingerprint(Option<u64>);
impl<F> Execution<F> {
fn with_outgoing_state<T>(self, outgoing_state: T) -> Execution<T> {
Execution {
format_dumped: self.format_dumped,
format_pdf_images: self.format_pdf_images,
job_name: self.job_name,
interaction_mode: self.interaction_mode,
native_page: self.native_page,
split_discards: self.split_discards,
after_assignment: self.after_assignment,
events: self.events,
state: self.state,
io: self.io,
input_position: self.input_position,
paragraph_mode: self.paragraph_mode,
sources: self.sources,
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
dependency_evidence: self.dependency_evidence,
line_observations: self.line_observations,
incoming_state: self.incoming_state,
outgoing_state,
steps: self.steps,
box_nodes_created: self.box_nodes_created,
reads_event_history: self.reads_event_history,
accounts_event_history: self.accounts_event_history,
}
}
}
impl Execution<DeferredStateFingerprint> {
fn needs_fingerprint(&self) -> bool {
self.outgoing_state.0.is_none()
}
fn finish_fingerprint(self, previous: Option<&Execution>) -> Execution {
let fingerprint = self.outgoing_state.0.unwrap_or_else(|| {
self.state.fingerprint_with_prior(previous.map(|prior| &prior.state))
});
self.with_outgoing_state(fingerprint)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ScannerStatus { pub enum ScannerStatus {
#[default] #[default]
@@ -806,7 +856,7 @@ impl fmt::Display for Error {
} }
impl std::error::Error for Error {} impl std::error::Error for Error {}
impl Execution { impl<F> Execution<F> {
/// Paint actual shipped boxes using their captured device state. No /// Paint actual shipped boxes using their captured device state. No
/// pagination or application of the job's final device settings. /// pagination or application of the job's final device settings.
pub fn shipout_display_lists(&self) -> Result<Vec<crate::render::DisplayList>, Error> { pub fn shipout_display_lists(&self) -> Result<Vec<crate::render::DisplayList>, Error> {
+125 -12
View File
@@ -1,9 +1,11 @@
//! Revision-gated publication for native executions. //! Revision-gated publication for native executions.
use crate::resources::ResourceTrace;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use super::{ use super::{
Cancellation, CheckpointCloneTimings, EntryCheckpoint, Error, Execution, ExecutionFailure, Cancellation, CheckpointCloneTimings, DeferredStateFingerprint, EntryCheckpoint, Error,
Execution, ExecutionFailure,
Executor, LineBreakCache, Executor, LineBreakCache,
SourceFile, SourceProvider, SourceFile, SourceProvider,
}; };
@@ -33,7 +35,7 @@ pub struct RevisionExecution {
/// Versions of the actual scanned bytes, indexed by span source ID. /// Versions of the actual scanned bytes, indexed by span source ID.
pub source_versions: Vec<SourceVersion>, pub source_versions: Vec<SourceVersion>,
/// The host trace through execution. PDF embedding may read more resources later. /// The host trace through execution. PDF embedding may read more resources later.
pub execution_resources: Option<crate::resources::ResourceTrace>, pub execution_resources: Option<ResourceTrace>,
} }
impl RevisionExecution { impl RevisionExecution {
/// Attach actual source identities to a completed kernel result. This does /// Attach actual source identities to a completed kernel result. This does
@@ -41,7 +43,7 @@ impl RevisionExecution {
pub fn from_execution( pub fn from_execution(
revision: u64, revision: u64,
execution: Execution, execution: Execution,
resources: Option<crate::resources::ResourceTrace>, resources: Option<ResourceTrace>,
) -> Self { ) -> Self {
Self::with_previous_sources(revision, execution, resources, None) Self::with_previous_sources(revision, execution, resources, None)
} }
@@ -49,10 +51,20 @@ impl RevisionExecution {
fn with_previous_sources( fn with_previous_sources(
revision: u64, revision: u64,
execution: Execution, execution: Execution,
resources: Option<crate::resources::ResourceTrace>, resources: Option<ResourceTrace>,
previous: Option<&Self>, previous: Option<&Self>,
) -> Self { ) -> Self {
let source_versions = execution let source_versions = Self::source_versions(&execution, previous);
Self {
revision,
execution,
source_versions,
execution_resources: resources,
}
}
fn source_versions<F>(execution: &Execution<F>, previous: Option<&Self>) -> Vec<SourceVersion> {
execution
.sources .sources
.iter() .iter()
.enumerate() .enumerate()
@@ -75,12 +87,58 @@ impl RevisionExecution {
|(_, version)| version.clone(), |(_, version)| version.clone(),
) )
}) })
.collect(); .collect()
Self { }
revision, }
/// Successful resumed kernel output whose final state digest is still pending.
pub struct PreparedRevisionExecution {
job: RevisionJob,
execution: Execution<DeferredStateFingerprint>,
source_versions: Vec<SourceVersion>,
resources: Option<ResourceTrace>,
previous: Option<Arc<RevisionExecution>>,
}
impl PreparedRevisionExecution {
pub fn execution(&self) -> &Execution<DeferredStateFingerprint> {
&self.execution
}
pub fn source_map(
&self,
pages: &[crate::render::DisplayList],
) -> Result<crate::source_map::SourceMap, String> {
crate::source_map::SourceMap::from_execution_checked(
self.job.revision, &self.execution, &self.source_versions, pages, false,
)
}
pub fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> {
let execution = self.execution.finish_fingerprint(
self.previous.as_deref().map(|revision| &revision.execution),
);
let complete = Arc::new(RevisionExecution {
revision: self.job.revision,
execution, execution,
source_versions, source_versions: self.source_versions,
execution_resources: resources, execution_resources: self.resources,
});
self.job.publish_execution(Ok(complete), None)
}
}
/// A resumed result may be used for a draft before its receipt is finalized.
pub enum ResumedExecution {
Complete(Arc<RevisionExecution>),
Prepared(Box<PreparedRevisionExecution>),
}
impl ResumedExecution {
fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> {
match self {
Self::Complete(result) => Ok(result),
Self::Prepared(prepared) => prepared.finish(),
} }
} }
} }
@@ -104,7 +162,7 @@ pub struct RevisionFailure {
/// Execution can finish just before its revision is superseded. It still /// Execution can finish just before its revision is superseded. It still
/// must not be published as the current successful execution. /// must not be published as the current successful execution.
pub completed_execution: Option<Arc<RevisionExecution>>, pub completed_execution: Option<Arc<RevisionExecution>>,
pub resources: Option<crate::resources::ResourceTrace>, pub resources: Option<ResourceTrace>,
} }
impl NativeSession { impl NativeSession {
@@ -324,12 +382,59 @@ impl RevisionJob {
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>, select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision, capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> { ) -> Result<Option<Result<Arc<RevisionExecution>, RevisionFailure>>, String> {
Ok(self.resume_deciding_suffix_prepared(
checkpoint, source, nested, files, line_break_cache, timings, false, select, capture,
)?.map(|result| result.and_then(ResumedExecution::finish)))
}
/// Resume in the editor, with the option to compute a new final digest
/// after consuming the verified output for a draft preview.
pub fn resume_deciding_suffix_prepared<F: SourceProvider, S>(
&self,
checkpoint: &EntryCheckpoint,
source: SourceFile,
nested: Option<SourceFile>,
files: &mut F,
line_break_cache: Arc<LineBreakCache>,
timings: Option<&mut CheckpointCloneTimings>,
defer_fingerprint: bool,
select: impl FnMut(super::CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> super::CheckpointDecision,
) -> Result<Option<Result<ResumedExecution, RevisionFailure>>, String> {
let previous = self.session.latest(); let previous = self.session.latest();
let executed = checkpoint.resume_deciding_suffix( let executed = checkpoint.resume_deciding_suffix(
source, nested, files, self.cancellation.clone(), line_break_cache, source, nested, files, self.cancellation.clone(), line_break_cache,
previous.as_deref().map(|item| &item.execution), timings, select, capture, previous.as_deref().map(|item| &item.execution), timings, select, capture,
)?; )?;
Ok(executed.map(|result| self.finish_execution(result, files, previous.as_deref()))) Ok(executed.map(|result| {
match result {
Ok(execution)
if defer_fingerprint && execution.needs_fingerprint()
&& !self.cancellation.is_cancelled() =>
{
let resources = files.execution_resource_trace().cloned();
let source_versions = RevisionExecution::source_versions(&execution, previous.as_deref());
Ok(ResumedExecution::Prepared(Box::new(PreparedRevisionExecution {
job: RevisionJob {
session: self.session.clone(),
revision: self.revision,
cancellation: self.cancellation.clone(),
},
execution,
source_versions,
resources,
previous,
})))
}
result => {
let executed = result.map(|execution| execution.finish_fingerprint(
previous.as_deref().map(|item| &item.execution),
));
self.finish_execution(executed, files, previous.as_deref())
.map(ResumedExecution::Complete)
}
}
}))
} }
/// Publish a completed result after the caller verifies the same inputs /// Publish a completed result after the caller verifies the same inputs
@@ -359,6 +464,14 @@ impl RevisionJob {
previous, previous,
)) ))
}); });
self.publish_execution(result, resources)
}
fn publish_execution(
&self,
result: Result<Arc<RevisionExecution>, ExecutionFailure>,
resources: Option<ResourceTrace>,
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
let mut state = self let mut state = self
.session .session
.state .state
+16 -5
View File
@@ -5,7 +5,7 @@
//! used to infer an origin. Source IDs are local to this revision, including //! used to infer an origin. Source IDs are local to this revision, including
//! independent opens of the same input stream. //! independent opens of the same input stream.
use crate::{ use crate::{
execution::{GeneratedInput, RevisionExecution, SourceVersion, Span, TokenOrigin}, execution::{Execution, GeneratedInput, RevisionExecution, SourceVersion, Span, TokenOrigin},
pdf_device::{Affine, PdfGraphics}, pdf_device::{Affine, PdfGraphics},
provenance::PaintSource, provenance::PaintSource,
render::{DisplayItem, DisplayList, DisplayUnits}, render::{DisplayItem, DisplayList, DisplayUnits},
@@ -227,14 +227,25 @@ impl SourceMap {
pages: &[DisplayList], pages: &[DisplayList],
verify_source_hashes: bool, verify_source_hashes: bool,
) -> Result<Self, String> { ) -> Result<Self, String> {
let execution = &revision.execution; Self::from_execution_checked(
if revision.source_versions.len() != execution.sources.len() { revision.revision, &revision.execution, &revision.source_versions, pages, verify_source_hashes,
)
}
pub(crate) fn from_execution_checked<F>(
revision: u64,
execution: &Execution<F>,
source_versions: &[SourceVersion],
pages: &[DisplayList],
verify_source_hashes: bool,
) -> Result<Self, String> {
if source_versions.len() != execution.sources.len() {
return Err("source map version table does not match execution".into()); return Err("source map version table does not match execution".into());
} }
let sources: Vec<_> = execution let sources: Vec<_> = execution
.sources .sources
.iter() .iter()
.zip(&revision.source_versions) .zip(source_versions)
.enumerate() .enumerate()
.map(|(id, (file, version))| { .map(|(id, (file, version))| {
if version.bytes != file.data.len() as u64 if version.bytes != file.data.len() as u64
@@ -542,7 +553,7 @@ impl SourceMap {
mapped_pages.push(map); mapped_pages.push(map);
} }
Ok(Self { Ok(Self {
revision: revision.revision, revision,
sources, sources,
pages: mapped_pages, pages: mapped_pages,
}) })
+1
View File
@@ -308,6 +308,7 @@ async function compile(edit, submitted, changes) {
reusedFrontier: result.reused_frontier, reusedFrontier: result.reused_frontier,
replayedCalls: result.replayed_calls, replayedCalls: result.replayed_calls,
pendingPublication: result.pending_publication === true, pendingPublication: result.pending_publication === true,
deferredStateFingerprint: result.deferred_state_fingerprint === true,
}; };
window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample })); window.dispatchEvent(new CustomEvent("texrra-preview-painted", { detail: sample }));
if (result.pending_publication) { if (result.pending_publication) {
+8 -1
View File
@@ -135,6 +135,10 @@ impl CompileObserver for EditorObserver {
self.preview_draft self.preview_draft
} }
fn preview_before_fingerprint(&self) -> bool {
self.preview_draft
}
fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> { fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> {
if !self.preview_draft || !self.is_current() { if !self.preview_draft || !self.is_current() {
return Ok(()); return Ok(());
@@ -149,12 +153,15 @@ impl CompileObserver for EditorObserver {
return Ok(()); return Ok(());
} }
let revision = update.revision; let revision = update.revision;
let reply_body = self.preview_payload( let mut reply_body = self.preview_payload(
update, update,
draft.execution_steps(), draft.execution_steps(),
draft.entry_checkpoint_work(), draft.entry_checkpoint_work(),
None, None,
); );
if draft.state_fingerprint_pending() {
reply_body["deferred_state_fingerprint"] = Value::Bool(true);
}
let respond_to = self let respond_to = self
.respond_to .respond_to
.lock() .lock()
+93 -18
View File
@@ -35,7 +35,8 @@ use texrra_tex_core::{
execution::{ execution::{
Cancellation, CheckpointCloneTimings, ExecutionFailure, Executor, FormatImage, InputProfile, Cancellation, CheckpointCloneTimings, ExecutionFailure, Executor, FormatImage, InputProfile,
JobTime, Limits, JobTime, Limits,
NativeSession, Profile, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile, NativeSession, PreparedRevisionExecution, Profile, ResumedExecution, RevisionError,
RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
SourceProvider, State, SuffixKernelTimings, WriteDestination, SourceProvider, State, SuffixKernelTimings, WriteDestination,
}, },
pdf_unicode::XdvGlyphNames, pdf_unicode::XdvGlyphNames,
@@ -146,6 +147,12 @@ pub trait CompileObserver: Send + Sync {
false 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 /// Called once per compile attempt for a draft before publication. Observers
/// can receive SVG-only drafts before PDF export. The compile result /// can receive SVG-only drafts before PDF export. The compile result
/// determines whether this revision actually published. /// determines whether this revision actually published.
@@ -161,6 +168,7 @@ pub struct DraftPreview<'a> {
preview: &'a PreviewState, preview: &'a PreviewState,
pdf: Option<&'a Arc<[u8]>>, pdf: Option<&'a Arc<[u8]>>,
steps: usize, steps: usize,
state_fingerprint_pending: bool,
work: &'a EntryCheckpointWork, work: &'a EntryCheckpointWork,
cancellation: &'a Cancellation, cancellation: &'a Cancellation,
} }
@@ -180,6 +188,12 @@ impl DraftPreview<'_> {
self.steps 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 { pub fn entry_checkpoint_work(&self) -> &EntryCheckpointWork {
self.work self.work
} }
@@ -1092,6 +1106,26 @@ impl CompileJob {
Err(error) => Err(evidence.failure(error, summary).persist_requested()), 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( fn compile_observed(
&self, &self,
request: &CompileRequest, request: &CompileRequest,
@@ -1168,6 +1202,7 @@ impl CompileJob {
})? })?
}; };
let mut available_host = Some(files); let mut available_host = Some(files);
let mut prepared_execution = None;
evidence.inputs = None; evidence.inputs = None;
evidence.trace = None; evidence.trace = None;
let result = (|| -> Result<Arc<CompiledDocument>, CompileError> { let result = (|| -> Result<Arc<CompiledDocument>, CompileError> {
@@ -1182,7 +1217,8 @@ impl CompileJob {
evidence.phase = AttemptPhase::Executing; evidence.phase = AttemptPhase::Executing;
let cache = &self.compiler.line_break_cache; let cache = &self.compiler.line_break_cache;
let before = cache.work(); 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()); debug_assert!(executor.is_none());
let (executed, next, reused_layouts) = current.resume( let (executed, next, reused_layouts) = current.resume(
&request, &request,
@@ -1194,7 +1230,7 @@ impl CompileJob {
allow_suffix, allow_suffix,
suffix_failure, suffix_failure,
)?; )?;
(executed, Some(next), reused_layouts) (executed, None, Some(next), reused_layouts)
} else { } else {
let executor = executor let executor = executor
.expect("fresh native job has an executor") .expect("fresh native job has an executor")
@@ -1205,16 +1241,20 @@ impl CompileJob {
if let Some(snapshot) = &captured { if let Some(snapshot) = &captured {
snapshot.report_capture(&mut entry_checkpoint_work); snapshot.report_capture(&mut entry_checkpoint_work);
} }
(executed, captured, None) (executed.map(ResumedExecution::Complete), captured, None, None)
} else { } 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 { let mut completed = match executed {
Ok(execution) => { Ok(ResumedExecution::Complete(execution)) => {
evidence.completed_execution = Some(execution.clone()); evidence.completed_execution = Some(execution.clone());
report(files, &request)?; Some(execution)
execution }
Ok(ResumedExecution::Prepared(execution)) => {
prepared_execution = Some(execution);
None
} }
Err(failure) => { Err(failure) => {
evidence.failed_execution = failure.failed_execution; evidence.failed_execution = failure.failed_execution;
@@ -1228,15 +1268,22 @@ impl CompileJob {
}); });
} }
}; };
report(files, &request)?;
let line_break_work = cache.work().since(before); 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( return Err(CompileError::Host(
"native format dump requires --dump-format".into(), "native format dump requires --dump-format".into(),
)); ));
} }
notify(&request, revision, CompileStage::Executed, &cancellation)?; notify(&request, revision, CompileStage::Executed, &cancellation)?;
evidence.phase = AttemptPhase::Layout; evidence.phase = AttemptPhase::Layout;
let e = &execution.execution;
let font_cache = &self.compiler.font_cache; let font_cache = &self.compiler.font_cache;
let type1_before = font_cache.type1_work(); let type1_before = font_cache.type1_work();
let prior_layout = checkpoints.and_then(|_| self.compiler.latest()); 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 } if let Event::Shipout(page) = event { Some(page.as_ref()) } else { None }
}).zip(&prior.shipout_layouts) }).zip(&prior.shipout_layouts)
}).enumerate(); }).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))| { let reused = old.next().and_then(|(index, (prior, layout))| {
relocated_suffix relocated_suffix
.and_then(|suffix| suffix.relocate_layout(index, layout)) .and_then(|suffix| suffix.relocate_layout(index, layout))
@@ -1274,9 +1321,16 @@ impl CompileJob {
shipout_layouts.push(Arc::new(layout.clone())); shipout_layouts.push(Arc::new(layout.clone()));
} }
Ok(layout) 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()) (pages, 0, 0, texrra_tex_core::pdf::PageOrigin::default())
} else { } else {
let e = &completed.as_ref().expect("completed document layout execution").execution;
let document = e.document().map_err(|e| e.to_string())?; let document = e.document().map_err(|e| e.to_string())?;
let engine = texrra_tex_core::Engine::layout_paged(&document) let engine = texrra_tex_core::Engine::layout_paged(&document)
.ok_or_else(|| CompileError::Host("unsupported native vertical list".into()))?; .ok_or_else(|| CompileError::Host("unsupported native vertical list".into()))?;
@@ -1300,10 +1354,11 @@ impl CompileJob {
)); ));
} }
let draft_mode = 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 { if let Some(path) = &request.layout_manifest {
let source_map = self.compiler.session.source_map(&execution, &pages)?; let execution = completed.as_ref().expect("completed manifest execution");
files.write_layout_manifest(path, e, &pages, &source_map)?; let source_map = self.compiler.session.source_map(execution, &pages)?;
files.write_layout_manifest(path, &execution.execution, &pages, &source_map)?;
} }
evidence.phase = AttemptPhase::Fonts; evidence.phase = AttemptPhase::Fonts;
let mut preview_fonts = if draft_mode { 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( notify(
&request, &request,
revision, revision,
@@ -1389,7 +1448,8 @@ impl CompileJob {
pages: &pages, pages: &pages,
preview: &preview, preview: &preview,
pdf: None, pdf: None,
steps: e.steps, steps,
state_fingerprint_pending: prepared_execution.is_some(),
work: &entry_checkpoint_work, work: &entry_checkpoint_work,
cancellation: &cancellation, cancellation: &cancellation,
}); });
@@ -1399,6 +1459,14 @@ impl CompileJob {
} else { } else {
None 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 mut dvi = None;
let (pdf, export_diagnostics) = if pages.is_empty() { let (pdf, export_diagnostics) = if pages.is_empty() {
(None, Vec::new()) (None, Vec::new())
@@ -1513,6 +1581,7 @@ impl CompileJob {
preview: &result.preview, preview: &result.preview,
pdf: result.pdf.as_ref(), pdf: result.pdf.as_ref(),
steps: result.execution.execution.steps, steps: result.execution.execution.steps,
state_fingerprint_pending: false,
work: &result.entry_checkpoint_work, work: &result.entry_checkpoint_work,
cancellation: &cancellation, cancellation: &cancellation,
}); });
@@ -1565,6 +1634,12 @@ impl CompileJob {
} }
Ok(result) 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() if result.is_err()
&& let Some(mut files) = available_host && let Some(mut files) = available_host
{ {
+78 -35
View File
@@ -10,7 +10,7 @@ use std::{
time::Instant, time::Instant,
}; };
use texrra_tex_core::{ 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}, resources::{ResourceKind, ResourceLookup, ResourceReadRange},
}; };
#[cfg(test)] #[cfg(test)]
@@ -89,6 +89,44 @@ pub(super) struct CheckpointSet {
edit_frontier: Option<usize>, 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 { pub(super) struct SelectedCheckpoint {
set: Arc<CheckpointSet>, set: Arc<CheckpointSet>,
candidate: ExecutionCandidate, candidate: ExecutionCandidate,
@@ -495,10 +533,9 @@ impl<'a> CapturedEntries<'a> {
self, self,
recording: RecordingHost, recording: RecordingHost,
refresh_on_resume: bool, refresh_on_resume: bool,
result: &Arc<RevisionExecution>,
suffix_base: Option<Arc<CompletedExecution>>, suffix_base: Option<Arc<CompletedExecution>>,
inherited: impl Iterator<Item = &'b Arc<CachedCheckpoint>>, inherited: impl Iterator<Item = &'b Arc<CachedCheckpoint>>,
) -> Option<Arc<CheckpointSet>> { ) -> Option<CapturedCheckpointSet> {
if !self.changed { if !self.changed {
return None; return None;
} }
@@ -582,22 +619,21 @@ impl<'a> CapturedEntries<'a> {
if completion.is_none() { if completion.is_none() {
calls.truncate(replay_count); calls.truncate(replay_count);
} }
let calls = Arc::<[Call]>::from(calls); Some(CapturedCheckpointSet {
let completion = completion.map(|(guard, trace)| Arc::new(CompletedExecution { set: CheckpointSet {
result: result.clone(), entries,
guard, calls: Arc::from(calls),
calls: calls.clone(), completion: None,
trace, suffix_base,
settled: self.settled, refresh_on_resume,
})); edit_frontier,
Some(Arc::new(CheckpointSet { },
entries, completion: completion.map(|(guard, trace)| CapturedCompletion {
calls, guard,
completion, trace,
suffix_base, settled: self.settled,
refresh_on_resume, }),
edit_frontier, })
}))
} }
} }
@@ -724,7 +760,8 @@ impl CheckpointCache {
|slots, entry, host| captures.capture(slots, Arc::new(entry), host), |slots, entry, host| captures.capture(slots, Arc::new(entry), host),
); );
let next = result.as_ref().ok().and_then(|result| { 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) (result, next)
} }
@@ -995,8 +1032,8 @@ impl SelectedCheckpoint {
suffix_failure: &mut Option<(String, usize)>, suffix_failure: &mut Option<(String, usize)>,
) -> Result< ) -> Result<
( (
Result<Arc<RevisionExecution>, RevisionFailure>, Result<ResumedExecution, RevisionFailure>,
Arc<CheckpointSet>, ResumedCheckpoints,
Option<ReusedShipoutLayouts>, Option<ReusedShipoutLayouts>,
), ),
CompileError, CompileError,
@@ -1010,8 +1047,9 @@ impl SelectedCheckpoint {
work.reused_completion = true; work.reused_completion = true;
work.replayed_calls = completed.calls.len(); work.replayed_calls = completed.calls.len();
return Ok(( return Ok((
job.reuse_completed_after_host_replay(&completed.result, files), job.reuse_completed_after_host_replay(&completed.result, files)
self.set, .map(ResumedExecution::Complete),
ResumedCheckpoints { fallback: self.set, captured: None },
None, None,
)); ));
} }
@@ -1028,7 +1066,11 @@ impl SelectedCheckpoint {
let result = job let result = job
.resume_entry_after_host_replay(&checkpoint.entry, source, files) .resume_entry_after_host_replay(&checkpoint.entry, source, files)
.ok_or_else(changed_prefix)?; .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 let previous = checkpoint
@@ -1099,13 +1141,16 @@ impl SelectedCheckpoint {
let mut clones = CheckpointCloneTimings::default(); let mut clones = CheckpointCloneTimings::default();
let resume_started = timed.then(Instant::now); let resume_started = timed.then(Instant::now);
let result = job let result = job
.resume_deciding_suffix_observed( .resume_deciding_suffix_prepared(
&checkpoint.entry, &checkpoint.entry,
source, source,
nested_source, nested_source,
&mut recording, &mut recording,
line_break_cache, line_break_cache,
detailed_observer.is_some().then_some(&mut clones), detailed_observer.is_some().then_some(&mut clones),
observer.is_some_and(|observer| {
observer.preview_before_export() && observer.preview_before_fingerprint()
}),
|source, pages| { |source, pages| {
if source.is_entry { if source.is_entry {
// The loaded entry line can be shared by several shipouts. // The loaded entry line can be shared by several shipouts.
@@ -1211,10 +1256,9 @@ impl SelectedCheckpoint {
timings.resume = started.elapsed(); timings.resume = started.elapsed();
timings.clones = clones; timings.clones = clones;
} }
let next = measure(&mut timings.retain, timed, || { let captured = measure(&mut timings.retain, timed, || {
result.as_ref().ok().and_then(|result| { result.is_ok().then(|| captures.finish(recording, true, suffix_base, inherited))
captures.finish(recording, true, result, suffix_base, inherited) .flatten()
})
}); });
if result.is_ok() { if result.is_ok() {
if let Some(observer) = &request.observer { if let Some(observer) = &request.observer {
@@ -1223,12 +1267,11 @@ impl SelectedCheckpoint {
} else { } else {
reused_layouts = None; reused_layouts = None;
} }
if let Some(next) = next { if let Some(captured) = &captured {
next.report_capture(work); captured.set.report_capture(work);
Ok((result, next, reused_layouts))
} else {
Ok((result, self.current_set_for_nested_resume.unwrap_or(self.set), reused_layouts))
} }
let fallback = self.current_set_for_nested_resume.unwrap_or(self.set);
Ok((result, ResumedCheckpoints { fallback, captured }, reused_layouts))
} }
} }
+121
View File
@@ -2824,6 +2824,127 @@ fn checkpoint_keeps_late_special_tokens_until_the_updated_page_is_shipped() {
fs::remove_dir_all(p).unwrap(); fs::remove_dir_all(p).unwrap();
} }
#[test]
fn preview_before_state_fingerprint_keeps_exact_execution_evidence() {
#[derive(Clone, Copy)]
enum Action {
Supersede,
Reject,
Publish,
}
struct ObserveDraft {
compiler: NativeCompiler,
initial: Arc<CompiledDocument>,
action: Action,
update: Mutex<Option<PreviewUpdate>>,
}
impl CompileObserver for ObserveDraft {
fn stage(&self, _: u64, _: CompileStage) -> Result<(), String> {
Ok(())
}
fn preview_before_export(&self) -> bool {
true
}
fn preview_before_fingerprint(&self) -> bool {
true
}
fn draft_ready(&self, draft: DraftPreview<'_>) -> Result<(), String> {
assert!(draft.state_fingerprint_pending());
assert!(draft.entry_checkpoint_work().reused_steps > 0);
assert!(Arc::ptr_eq(&self.initial, &self.compiler.latest().unwrap()));
let update = draft.preview_since(Some(self.initial.revision()))?;
assert_eq!(update.pages.iter().map(|p| p.index).collect::<Vec<_>>(), [1]);
assert!(self.update.lock().unwrap().replace(update).is_none());
match self.action {
Action::Supersede => {
self.compiler.start();
Ok(())
}
Action::Reject => Err("reject resumed SVG draft".into()),
Action::Publish => Ok(()),
}
}
}
let root = directory("preview-before-state-fingerprint");
let entry = root.join("main.tex");
let padding = "\\relax\n".repeat(64);
let body = format!(
r"
\shipout\hbox{{Stable first page}}
{padding}
\global\count73=17
\immediate\openout1=state.dat
\immediate\write1{{\the\count73}}
\immediate\closeout1
\shipout\hbox{{Final value \the\count73}}
\end
"
);
let mut definition = atomic_definition(&root, 1, &body);
definition.generated.insert(root.join("state.dat"));
let project = ProjectSnapshot::new(definition).unwrap();
let job = request(&root).observe_generated_initial();
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let initial = compiler.compile(job.clone().with_project(project.clone())).unwrap();
let names = ["job.pdf", "job.log", "state.dat"];
let initial_files = names.map(|name| fs::read(root.join(name)).unwrap());
for (value, action) in [(23, Action::Supersede), (29, Action::Reject), (31, Action::Publish)] {
let edited = format!("{HEADER}{}", body.replace("count73=17", &format!("count73={value}")));
let project = project.with_file_edits(
u64::try_from(value).unwrap(),
[(entry.clone(), Arc::from(edited.into_bytes()))].into(),
).unwrap();
let compile = job.clone().with_project(project);
let observer = Arc::new(ObserveDraft {
compiler: compiler.clone(),
initial: initial.clone(),
action,
update: Mutex::new(None),
});
let mut observed = compile.clone();
observed.observer = Some(observer.clone());
let result = compiler.compile_detailed(observed);
let draft = observer.update.lock().unwrap().take().unwrap();
match action {
Action::Supersede | Action::Reject => {
let failure = result.err().unwrap();
assert_eq!(failure.phase, AttemptPhase::Export);
match action {
Action::Supersede => assert!(matches!(failure.error, CompileError::Cancelled)),
Action::Reject => assert!(failure.error.to_string().contains("reject resumed SVG draft")),
Action::Publish => unreachable!(),
}
let completed = failure.completed_execution.unwrap();
assert_eq!(completed.execution.outgoing_state, completed.execution.state.fingerprint());
assert_eq!(completed.execution.state.count(73), value);
assert!(Arc::ptr_eq(&initial, &compiler.latest().unwrap()));
assert_eq!(names.map(|name| fs::read(root.join(name)).unwrap()), initial_files);
}
Action::Publish => {
let published = result.unwrap();
let full = NativeCompiler::default().compile(compile).unwrap();
assert!(published.execution.execution == full.execution.execution);
assert_eq!(published.execution.source_versions, full.execution.source_versions);
assert_eq!(published.execution.execution_resources, full.execution.execution_resources);
assert_eq!(published.pdf, full.pdf);
assert_eq!(published.source_map.sources, full.source_map.sources);
assert_eq!(published.source_map.pages, full.source_map.pages);
let preview = published.preview_since(Some(initial.revision())).unwrap();
assert_eq!(draft.pages, preview.pages);
assert_eq!(fs::read(root.join("state.dat")).unwrap(), b"31\n");
}
}
}
fs::remove_dir_all(root).unwrap();
}
#[test] #[test]
fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts() { fn provisional_preview_matches_published_pages_and_cancellation_keeps_artifacts() {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]