Stage verified suffix previews before new state hashing

This commit is contained in:
gloamxun committed 2026-12-02 06:14:40 +08:00
1 parent 5927196149
commit f684872941
9 files changed
+350 -80

No files matched your search

@@ -1,6 +1,7 @@
//! Deduplicate execution reads before producing the ordered public evidence.
use super::Dependency;
use std::{
cmp::Ordering,
collections::{BTreeSet, HashMap},
sync::Arc,
};
@@ -21,6 +22,54 @@ impl DependencyEvidence {
pub(super) fn epochs(&self) -> Option<&[u32]> {
self.0.as_deref()
}
pub(super) fn splice(
prefix: impl IntoIterator<Item = (Dependency, u32)>,
completed: &BTreeSet<Dependency>,
donor_epochs: &[u32],
prefix_epoch: u32,
donor_prefix_epoch: u32,
) -> Option<(BTreeSet<Dependency>, Self)> {
if donor_epochs.len() != completed.len() {
return None;
}
let prefix = ordered_unique_observations(prefix);
let mut suffix = completed
.iter()
.zip(donor_epochs.iter().copied())
.filter(|(_, epoch)| *epoch > donor_prefix_epoch)
.peekable();
let translate = |epoch| prefix_epoch.checked_add(epoch - donor_prefix_epoch);
let mut reads = Vec::with_capacity(prefix.len());
let mut epochs = Vec::with_capacity(prefix.len());
for (key, mut epoch) in prefix {
while let Some(&(donor_key, donor_epoch)) = suffix.peek() {
match donor_key.cmp(&key) {
Ordering::Less => {
reads.push(donor_key.clone());
epochs.push(translate(donor_epoch)?);
suffix.next();
}
Ordering::Equal => {
// A repeated read belongs to the suffix. Keep the
// prefix's owned key and update its observation.
epoch = translate(donor_epoch)?;
suffix.next();
break;
}
Ordering::Greater => break,
}
}
reads.push(key);
epochs.push(epoch);
}
for (key, epoch) in suffix {
reads.push(key.clone());
epochs.push(translate(epoch)?);
}
Some((reads.into_iter().collect(), Self::new(epochs)))
}
}
// The same execution can be captured at different boundaries.
@@ -154,11 +203,7 @@ impl DependencyReads {
);
}
let mut ordered: Vec<_> = observations.collect();
ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae)));
// A diagnostic can record a meaning also present in the lookup cache.
ordered.dedup_by(|a, b| a.0 == b.0);
let (reads, epochs) = ordered.into_iter().unzip();
let (reads, epochs) = ordered_unique_observations(observations).into_iter().unzip();
(reads, DependencyEvidence::new(epochs))
}
@@ -168,6 +213,16 @@ impl DependencyReads {
}
}
fn ordered_unique_observations(
observations: impl IntoIterator<Item = (Dependency, u32)>,
) -> Vec<(Dependency, u32)> {
let mut ordered: Vec<_> = observations.into_iter().collect();
ordered.sort_unstable_by(|(a, ae), (b, be)| a.cmp(b).then_with(|| be.cmp(ae)));
// A diagnostic can record a meaning also present in the lookup cache.
ordered.dedup_by(|a, b| a.0 == b.0);
ordered
}
fn byte_catcode_observations(
epochs: impl Iterator<Item = u32>,
) -> impl Iterator<Item = (Dependency, u32)> {
@@ -244,6 +299,32 @@ mod tests {
);
}
#[test]
fn suffix_splice_preserves_last_observation_for_each_ordered_dependency() {
let prefix = [
(Dependency::Count(3), 4),
(Dependency::Count(1), 2),
(Dependency::Count(3), 6),
(Dependency::Count(5), 7),
(Dependency::Count(4), 8),
];
let completed: BTreeSet<_> = [0, 2, 3, 4, 6].into_iter().map(Dependency::Count).collect();
let donor_epochs = [2, 4, 1, 5, 7];
let (reads, evidence) =
DependencyEvidence::splice(prefix.clone(), &completed, &donor_epochs, 8, 2).unwrap();
assert_eq!(reads, (1..=6).map(Dependency::Count).collect::<BTreeSet<_>>());
assert_eq!(evidence.epochs().unwrap(), [2, 10, 6, 11, 7, 13]);
assert!(
DependencyEvidence::splice(prefix.clone(), &completed, &donor_epochs[..4], 8, 2)
.is_none()
);
assert!(
DependencyEvidence::splice(prefix, &completed, &donor_epochs, u32::MAX - 2, 2)
.is_none()
);
}
#[test]
fn cloned_record_preserves_byte_and_unicode_dependencies() {
let mut read = DependencyReads::default();
+32 -22
View File
@@ -337,12 +337,25 @@ pub struct CheckpointSource<'a> {
/// Called only at a selected boundary. Reuse requires that the caller has
/// validated and replayed the previous suffix into this revision's draft.
pub enum CheckpointDecision {
pub enum CheckpointDecision<R = Execution> {
Continue,
Reuse(Box<Execution>),
Reuse(Box<R>),
ReplayFailed(String),
}
impl CheckpointDecision {
pub(super) fn into_prepared(self) -> CheckpointDecision<Execution<super::DeferredStateFingerprint>> {
match self {
Self::Continue => CheckpointDecision::Continue,
Self::ReplayFailed(error) => CheckpointDecision::ReplayFailed(error),
Self::Reuse(execution) => {
let fingerprint = super::DeferredStateFingerprint::known(execution.outgoing_state);
CheckpointDecision::Reuse(Box::new(execution.with_outgoing_state(fingerprint)))
}
}
}
}
/// Time spent cloning live kernel state while resuming or capturing checkpoints.
#[derive(Clone, Copy, Debug, Default)]
pub struct CheckpointCloneTimings {
@@ -454,7 +467,7 @@ impl EntryCheckpoint {
self.resume_observed(source, None, files, cancellation, None, None, None,
|_, _, _, _| CheckpointDecision::Continue)
.expect("ordinary resume cannot reject a cached suffix")
.map(|result| result.map(|execution| execution.finish_fingerprint(None)))
.map(|result| result.map(|execution| execution.finish_fingerprint()))
}
pub(super) fn resume_capturing_sources_after_host_replay<F: SourceProvider, S>(
@@ -482,7 +495,7 @@ impl EntryCheckpoint {
}),
)
.expect("ordinary resume cannot reject a cached suffix")
.map(|result| result.map(|execution| execution.finish_fingerprint(previous)))
.map(|result| result.map(|execution| execution.finish_fingerprint()))
}
pub(super) fn resume_deciding_suffix<F: SourceProvider, S>(
@@ -495,7 +508,7 @@ impl EntryCheckpoint {
previous: Option<&Execution>,
timings: Option<&mut CheckpointCloneTimings>,
select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision<Execution<super::DeferredStateFingerprint>>,
) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> {
let measured = timings.is_some().then(Cell::default);
let result = self.resume_observed(
@@ -517,7 +530,7 @@ impl EntryCheckpoint {
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>,
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<Execution<super::DeferredStateFingerprint>>,
) -> Result<Option<Result<Execution<super::DeferredStateFingerprint>, ExecutionFailure>>, String> {
if !self.accepts_entry(&source)
|| match &nested {
@@ -560,10 +573,7 @@ impl EntryCheckpoint {
)
});
let result = match result {
Ok(CheckpointDecision::Reuse(execution)) => {
let fingerprint = super::DeferredStateFingerprint(Some(execution.outgoing_state));
return Ok(Some(Ok(execution.with_outgoing_state(fingerprint))));
}
Ok(CheckpointDecision::Reuse(execution)) => return Ok(Some(Ok(*execution))),
Ok(CheckpointDecision::ReplayFailed(error)) => return Err(error),
Ok(CheckpointDecision::Continue) => Ok(()),
Err(error) => Err(error),
@@ -4013,12 +4023,12 @@ impl Executor {
self.finish_execution(result, incoming_state, None)
}
fn entry_observer<F: SourceProvider, S>(
fn entry_observer<F: SourceProvider, S, R>(
incoming_state: u64,
timings: Option<&Cell<CheckpointCloneTimings>>,
mut select: impl FnMut(CheckpointSource<'_>, usize) -> Option<S>,
mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision,
) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision {
mut capture: impl FnMut(S, EntryCheckpoint, &mut F) -> CheckpointDecision<R>,
) -> impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision<R> {
move |engine, initial_depth, pages_processed, files| {
if engine.job_ended {
return CheckpointDecision::Continue;
@@ -4092,7 +4102,7 @@ impl Executor {
previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> {
self.prepare_execution(result, incoming_state, previous)
.map(|execution| execution.finish_fingerprint(previous))
.map(|execution| execution.finish_fingerprint())
}
fn prepare_execution(
@@ -4149,11 +4159,11 @@ impl Executor {
}
// An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments.
let outgoing_state = super::DeferredStateFingerprint(
previous
.filter(|last| last.state == self.state)
.map(|last| last.outgoing_state),
);
let outgoing_state = if let Some(last) = previous.filter(|last| last.state == self.state) {
super::DeferredStateFingerprint::known(last.outgoing_state)
} else {
super::DeferredStateFingerprint::pending(previous.map(|last| &last.state))
};
let format_pdf_images = self.captured_format_pdf_images();
Ok(Execution {
format_dumped: self.format_dumped,
@@ -4305,13 +4315,13 @@ impl Executor {
self.read_parameter(Parameter::Partokencontext).width() >= minimum
}
fn run_active_input<F: SourceProvider>(
fn run_active_input<F: SourceProvider, R>(
&mut self,
initial_depth: usize,
mut pages_processed: bool,
files: &mut F,
mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision,
) -> Result<CheckpointDecision, Error> {
mut capture_boundary: impl FnMut(&mut Self, usize, bool, &mut F) -> CheckpointDecision<R>,
) -> Result<CheckpointDecision<R>, Error> {
let xe = self.state.input_profile() == InputProfile::XeTeX;
loop {
if !std::mem::take(&mut pages_processed) {
@@ -1,5 +1,5 @@
use super::super::{
dependency_reads::DependencyEvidence,
DeferredStateFingerprint, dependency_reads::DependencyEvidence,
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
statistics::{BoxNodeOffset, RetainedHistoryOffset, SuffixSourceResize},
};
@@ -290,6 +290,21 @@ impl EntryCheckpoint {
retained: Option<&RetainedStateFingerprint>,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
self.prepare_settled_suffix(prior, completed, closed_source, retained, false, timings)
.map(|(execution, layout)| (execution.finish_fingerprint(), layout))
}
/// Assemble the proved kernel suffix. The host must replay its recorded
/// effects before passing this output to the revision job for a draft.
pub fn prepare_settled_suffix(
&self,
prior: &Self,
completed: &Execution,
closed_source: Option<(usize, usize)>,
retained: Option<&RetainedStateFingerprint>,
defer_fingerprint: bool,
timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution<DeferredStateFingerprint>, Option<RelocatedShipoutSuffix>)> {
let (source_id, prefix_resource_reads) = match closed_source {
Some((source_id, reads)) => {
if reads == 0 || self.closed_source_change(prior, completed)?.source_id != source_id {
@@ -299,7 +314,9 @@ impl EntryCheckpoint {
}
None => (self.entry, 1),
};
self.splice_settled_sources(prior, completed, source_id, prefix_resource_reads, retained, timings)
self.splice_settled_sources(
prior, completed, source_id, prefix_resource_reads, retained, defer_fingerprint, timings,
)
}
fn splice_settled_sources(
@@ -309,8 +326,9 @@ impl EntryCheckpoint {
source_id: usize,
prefix_resource_reads: usize,
retained: Option<&RetainedStateFingerprint>,
defer_fingerprint: bool,
mut timings: Option<&mut SuffixKernelTimings>,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
) -> Option<(Execution<DeferredStateFingerprint>, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
@@ -499,7 +517,7 @@ impl EntryCheckpoint {
dependency_evidence,
line_observations,
incoming_state: completed.incoming_state,
outgoing_state: completed.outgoing_state,
outgoing_state: DeferredStateFingerprint::known(completed.outgoing_state),
steps,
box_nodes_created,
reads_event_history: false,
@@ -514,9 +532,14 @@ impl EntryCheckpoint {
&& execution.state == retained.state
{
reused_final_fingerprint = true;
retained.fingerprint
DeferredStateFingerprint::known(retained.fingerprint)
} else {
execution.state.fingerprint_with_prior(Some(&completed.state))
let pending = DeferredStateFingerprint::pending(Some(&completed.state));
if defer_fingerprint {
pending
} else {
DeferredStateFingerprint::known(pending.calculate(&execution.state))
}
};
}
} else if statistics.is_identity() {
@@ -701,21 +724,13 @@ fn splice_dependencies(
if let (Some(current_epoch), Some(donor_epoch), Some(donor)) = (
current.reads.epoch(), prior.reads.epoch(), completed.dependency_evidence.epochs(),
) {
if donor.len() != completed.reads.len() {
return None;
}
let mut observed: BTreeMap<Dependency, u32> = BTreeMap::new();
for (key, epoch) in current.dependency_observations() {
observed.entry(key).and_modify(|last| *last = (*last).max(epoch)).or_insert(epoch);
}
for (key, &epoch) in completed.reads.iter().zip(donor) {
if epoch > donor_epoch {
let translated = current_epoch.checked_add(epoch - donor_epoch)?;
observed.insert(key.clone(), translated);
}
}
let (reads, epochs) = observed.into_iter().unzip();
return Some((reads, DependencyEvidence::new(epochs)));
return DependencyEvidence::splice(
current.dependency_observations(),
&completed.reads,
donor,
current_epoch,
donor_epoch,
);
}
// Restored records without epoch evidence can only preserve every
@@ -110,8 +110,8 @@ pub(super) fn same_kernel_provenance(
Some(measure(timings.map(|timings| &mut timings.exact_equality), || current.state == state))
}
pub(super) fn append_suffix(
execution: &mut Execution,
pub(super) fn append_suffix<F>(
execution: &mut Execution<F>,
tail: &[Event],
statistics: &SuffixStatistics,
relocation: &mut EventRelocation<'_>,
+35 -7
View File
@@ -703,8 +703,38 @@ pub struct Execution<F = u64> {
/// 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>);
pub struct DeferredStateFingerprint(FingerprintState);
enum FingerprintState {
Known(u64),
NeedsHash(Option<state::CommandFingerprintBase>),
}
impl fmt::Debug for DeferredStateFingerprint {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
FingerprintState::Known(value) => formatter.debug_tuple("Known").field(&value).finish(),
FingerprintState::NeedsHash(_) => formatter.write_str("NeedsHash"),
}
}
}
impl DeferredStateFingerprint {
fn known(value: u64) -> Self {
Self(FingerprintState::Known(value))
}
fn pending(prior: Option<&State>) -> Self {
Self(FingerprintState::NeedsHash(prior.map(State::command_fingerprint_base)))
}
fn calculate(&self, state: &State) -> u64 {
match &self.0 {
FingerprintState::Known(value) => *value,
FingerprintState::NeedsHash(prior) => state.fingerprint_with_base(prior.as_ref()),
}
}
}
impl<F> Execution<F> {
fn with_outgoing_state<T>(self, outgoing_state: T) -> Execution<T> {
@@ -739,13 +769,11 @@ impl<F> Execution<F> {
impl Execution<DeferredStateFingerprint> {
fn needs_fingerprint(&self) -> bool {
self.outgoing_state.0.is_none()
matches!(self.outgoing_state.0, FingerprintState::NeedsHash(_))
}
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))
});
fn finish_fingerprint(self) -> Execution {
let fingerprint = self.outgoing_state.calculate(&self.state);
self.with_outgoing_state(fingerprint)
}
}
@@ -97,7 +97,6 @@ pub struct PreparedRevisionExecution {
execution: Execution<DeferredStateFingerprint>,
source_versions: Vec<SourceVersion>,
resources: Option<ResourceTrace>,
previous: Option<Arc<RevisionExecution>>,
}
impl PreparedRevisionExecution {
@@ -115,9 +114,7 @@ impl PreparedRevisionExecution {
}
pub fn finish(self) -> Result<Arc<RevisionExecution>, RevisionFailure> {
let execution = self.execution.finish_fingerprint(
self.previous.as_deref().map(|revision| &revision.execution),
);
let execution = self.execution.finish_fingerprint();
let complete = Arc::new(RevisionExecution {
revision: self.job.revision,
execution,
@@ -400,6 +397,27 @@ impl RevisionJob {
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 mut capture = capture;
self.resume_deciding_suffix_staged(
checkpoint, source, nested, files, line_break_cache, timings, defer_fingerprint, select,
|slot, entry, files| capture(slot, entry, files).into_prepared(),
)
}
/// Resume with a typed, host-verified suffix assembly. New fingerprints
/// may be finalized after the editor consumes the prepared page data.
pub fn resume_deciding_suffix_staged<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<Execution<DeferredStateFingerprint>>,
) -> Result<Option<Result<ResumedExecution, RevisionFailure>>, String> {
let previous = self.session.latest();
let executed = checkpoint.resume_deciding_suffix(
@@ -423,13 +441,10 @@ impl RevisionJob {
execution,
source_versions,
resources,
previous,
})))
}
result => {
let executed = result.map(|execution| execution.finish_fingerprint(
previous.as_deref().map(|item| &item.execution),
));
let executed = result.map(Execution::finish_fingerprint);
self.finish_execution(executed, files, previous.as_deref())
.map(ResumedExecution::Complete)
}
+16 -2
View File
@@ -1197,6 +1197,8 @@ impl<'de> serde::Deserialize<'de> for CommandBindings {
}
}
pub(super) struct CommandFingerprintBase(Arc<CommandBindings>);
// Derive the ordinary hash and emit the specialized fingerprint in the
// same field order. Only the command meanings can reuse recorded hash input.
macro_rules! define_state {
@@ -1213,9 +1215,21 @@ macro_rules! define_state {
self.fingerprint_with_prior(None)
}
pub(super) fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 {
fn fingerprint_with_prior(&self, prior: Option<&Self>) -> u64 {
self.fingerprint_with_bindings(prior.map(|prior| prior.commands.as_ref()))
}
pub(super) fn command_fingerprint_base(&self) -> CommandFingerprintBase {
CommandFingerprintBase(self.commands.clone())
}
pub(super) fn fingerprint_with_base(&self, prior: Option<&CommandFingerprintBase>) -> u64 {
self.fingerprint_with_bindings(prior.map(|prior| prior.0.as_ref()))
}
fn fingerprint_with_bindings(&self, prior: Option<&CommandBindings>) -> u64 {
let mut hash = FingerprintHasher::default();
self.commands.hash_fingerprint(&mut hash, prior.map(|prior| prior.commands.as_ref()));
self.commands.hash_fingerprint(&mut hash, prior);
$(self.$field.hash(&mut hash);)*
hash.finish()
}