Reuse settled suffixes after verified closed child edits

This commit is contained in:
gloamxun committed 2026-12-02 01:53:20 +08:00
1 parent 55c497dccd
commit e4d6e049f8
11 files changed
+565 -72

No files matched your search

+122 -22
View File
@@ -1,5 +1,5 @@
//! Reuse a recorded entry prefix only after validating the current job host.
use super::checkpoint_probe::{Call, RecordingHost};
use super::checkpoint_probe::{Call, ClosedSourceUsageOffset, RecordingHost, closed_source_reads};
use super::*;
#[cfg(test)]
use std::fs;
@@ -10,7 +10,7 @@ use std::{
time::Instant,
};
use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport},
execution::{CheckpointDecision, CheckpointSource, ClosedSourceChange, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport},
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
};
#[cfg(test)]
@@ -59,9 +59,17 @@ struct CompletedExecution {
result: Arc<RevisionExecution>,
guard: PrefixInputGuard,
calls: Arc<[Call]>,
trace: ResourceTrace,
settled: BTreeMap<usize, SettledCheckpoint>,
}
struct ClosedSourceSuffix {
source_id: usize,
prefix_resource_reads: usize,
version: ResourceVersion,
usage: ClosedSourceUsageOffset,
}
struct SettledCheckpoint {
entry: Arc<EntryCheckpoint>,
host: crate::native_job::ReplayBoundary,
@@ -417,6 +425,7 @@ impl<'a> CapturedEntries<'a> {
prior: &SettledCheckpoint,
completed: &CompletedExecution,
end_statistics: Option<&StatisticsReport>,
closed_source: Option<&ClosedSourceSuffix>,
host: &mut RecordingHost,
cancellation: &Cancellation,
) -> Result<(), String> {
@@ -426,9 +435,10 @@ impl<'a> CapturedEntries<'a> {
let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len();
let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1);
let mut later = [const { None }; SOURCE_INTERVALS];
// Untranslated live continuations and their source intervals still
// refer to the old entry when its length changed.
if previous_bytes == bytes
// Carried checkpoints still carry the donor's scanner and source
// allocations. An exhausted child edit also changes that history.
if closed_source.is_none()
&& previous_bytes == bytes
&& let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution)
{
// Keep the deepest compatible settled continuation per source interval.
@@ -451,7 +461,7 @@ impl<'a> CapturedEntries<'a> {
let Some(calls) = completed.calls.get(replayed..anchor.call_count) else {
continue;
};
host.replay_suffix(calls, end_statistics, cancellation)?;
host.replay_suffix(calls, end_statistics, None, cancellation)?;
replayed = anchor.call_count;
if anchor.host == host.files().replay_boundary() {
let regular = CaptureSlots {
@@ -464,7 +474,16 @@ impl<'a> CapturedEntries<'a> {
self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host);
}
}
host.replay_suffix(&completed.calls[replayed..], end_statistics, cancellation)?;
host.replay_suffix(
&completed.calls[replayed..], end_statistics, closed_source.map(|child| child.usage),
cancellation,
)?;
if let Some(child) = closed_source {
let (trace, calls) = host.prefix().ok_or("child suffix host observations are unavailable")?;
if closed_source_reads(&child.version, trace, calls) != Some(child.prefix_resource_reads) {
return Err("completed suffix observed the changed child again".into());
}
}
completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string())
}
@@ -521,17 +540,18 @@ impl<'a> CapturedEntries<'a> {
recording.generated_outputs(),
self.initial?,
).ok()?;
Some(guard)
Some((guard, trace.clone()))
}).flatten();
let mut calls = recording.into_calls()?;
if completion.is_none() {
calls.truncate(replay_count);
}
let calls = Arc::<[Call]>::from(calls);
let completion = completion.map(|guard| Arc::new(CompletedExecution {
let completion = completion.map(|(guard, trace)| Arc::new(CompletedExecution {
result: result.clone(),
guard,
calls: calls.clone(),
trace,
settled: self.settled,
}));
Some(Arc::new(CheckpointSet {
@@ -996,23 +1016,38 @@ impl SelectedCheckpoint {
let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else {
return CheckpointDecision::Continue;
};
let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| {
let Some((completed, old, execution, layout, closed_source)) = suffixes.clone().find_map(|completed| {
let old = completed.settled.get(&page)?;
let host_matches = measure(&mut timings.suffix_host_validation, timed, || {
old.call_count == new.call_count
&& new.host.matches_for_suffix(&old.host)
let closed_source = measure(&mut timings.suffix_host_validation, timed, || {
if old.call_count != new.call_count {
return None;
}
if new.host.matches_for_suffix(&old.host)
&& can_replay_completed_suffix(completed, request, host.files())
});
if !host_matches {
return None;
}
{
return Some(None);
}
let change = entry.closed_source_change(&old.entry, &completed.result.execution)?;
prove_closed_source_suffix(change, old, new, completed, request, host)
.map(Some)
})?;
let kernel_timings = timed.then_some(&mut timings.suffix_kernel);
let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || {
entry.splice_settled_suffix_observed(
&old.entry, &completed.result.execution, kernel_timings,
)
if let Some(child) = &closed_source {
entry.splice_settled_closed_source_suffix_observed(
&old.entry,
&completed.result.execution,
child.source_id,
child.prefix_resource_reads,
kernel_timings,
)
} else {
entry.splice_settled_suffix_observed(
&old.entry, &completed.result.execution, kernel_timings,
)
}
})?;
Some((completed, old, execution, layout))
Some((completed, old, execution, layout, closed_source))
}) else {
return CheckpointDecision::Continue;
};
@@ -1024,7 +1059,8 @@ impl SelectedCheckpoint {
});
let replayed = measure(&mut timings.suffix_host_replay, timed, || {
captures.replay_settled_suffix(
page, &entry, old, completed, end_statistics, host, &cancellation,
page, &entry, old, completed, end_statistics,
closed_source.as_ref(), host, &cancellation,
)
});
if let Err(error) = replayed {
@@ -1090,6 +1126,61 @@ fn can_replay_completed_suffix(
completed.guard.verify(request, files.replay_world(), files.preparation()).is_ok()
}
fn prove_closed_source_suffix(
change: ClosedSourceChange<'_>,
old: &SettledCheckpoint,
current: &SettledCheckpoint,
completed: &CompletedExecution,
request: &CompileRequest,
host: &RecordingHost<'_>,
) -> Option<ClosedSourceSuffix> {
let path = Path::new(change.name);
let guard = &completed.guard;
let next_project = request.project.as_deref()?;
if path == guard.entry || !guard.immutable.contains(path) || guard.generated.contains(path)
|| !guard.project.immutable_paths().eq(next_project.immutable_paths())
{
return None;
}
// The child route cannot simultaneously relocate or replace the entry.
if guard.project.file(&guard.entry)?.version != next_project.file(&guard.entry)?.version {
return None;
}
let previous = &guard.project.file(path)?.version;
let current_version = &next_project.file(path)?.version;
if previous == current_version || previous.path != path || current_version.path != path
|| previous.bytes != u64::try_from(change.previous_bytes).ok()?
|| current_version.bytes != u64::try_from(change.current_bytes).ok()?
{
return None;
}
let (trace, calls) = host.prefix()?;
if calls.len() != current.call_count || trace.project_version.as_ref() != Some(next_project.version()) {
return None;
}
let prefix_resource_reads = closed_source_reads(
previous, old.host.trace_for_suffix(), completed.calls.get(..old.call_count)?,
)?;
// In the donor's whole job, the only observations of the child must
// be the reads already present at the splice. The live prefix has
// actually made the same count of allowed observations of its new version.
if closed_source_reads(previous, &completed.trace, &completed.calls)? != prefix_resource_reads
|| closed_source_reads(current_version, trace, calls)? != prefix_resource_reads
|| !current.host.matches_for_closed_source_suffix(&old.host, previous, current_version)
{
return None;
}
let files = host.files();
let project = guard.verify_project_with_closed_source(request, Some(path)).ok()?;
guard.verify_host(project, files.replay_world(), files.preparation()).ok()?;
Some(ClosedSourceSuffix {
source_id: change.source_id,
prefix_resource_reads,
version: current_version.clone(),
usage: ClosedSourceUsageOffset::new(previous.bytes, current_version.bytes, prefix_resource_reads)?,
})
}
fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
if previous == current {
return None;
@@ -1317,6 +1408,14 @@ impl PrefixInputGuard {
fn verify_project<'a>(
&self,
request: &'a CompileRequest,
) -> Result<&'a ProjectSnapshot, String> {
self.verify_project_with_closed_source(request, None)
}
fn verify_project_with_closed_source<'a>(
&self,
request: &'a CompileRequest,
closed_source: Option<&Path>,
) -> Result<&'a ProjectSnapshot, String> {
let old = &self.original;
if old.input != request.input
@@ -1354,6 +1453,7 @@ impl PrefixInputGuard {
let same_bytes = self.project.file(path).zip(current.file(path)).is_some_and(
|(old, new)| {
old.version == new.version
|| closed_source == Some(path.as_path())
|| self.nested_source.as_ref().is_some_and(|source| &source.path == path)
|| self.immutable_sizes.get(path) == Some(&new.version.bytes)
|| self.immutable_stream_prefixes.get(path).is_some_and(|&end| {
+82
View File
@@ -42,6 +42,75 @@ pub(super) struct RebindableSourceObservations {
pub(super) size: Option<u64>,
}
#[derive(Clone, Copy)]
pub(super) struct ClosedSourceUsageOffset {
previous: u64,
current: u64,
}
impl ClosedSourceUsageOffset {
pub(super) fn new(previous: u64, current: u64, reads: usize) -> Option<Self> {
let reads = u64::try_from(reads).ok()?;
Some(Self {
previous: previous.checked_mul(reads)?,
current: current.checked_mul(reads)?,
})
}
}
/// Return the entire byte-read count of a closed immutable child, including
/// typed size queries. Every other observation of the child rules out reuse.
pub(super) fn closed_source_reads(
version: &ResourceVersion,
trace: &ResourceTrace,
calls: &[Call],
) -> Option<usize> {
let path = &version.path;
if trace.stream_reads.iter().any(|read| &read.path == path)
|| trace.file_modifications.iter().any(|item| &item.path == path)
|| trace.generated_lookups.iter().any(|lookup| &lookup.target == path)
|| trace.format_input_bindings.iter().any(|(old, current)| old == path || current == path)
|| trace.read_errors.iter().any(|(read, _)| read == path)
|| !trace.namespace_capture_failures.is_empty()
{
return None;
}
let mut sources = 0usize;
let mut sizes = 0usize;
for call in calls {
match call {
Call::ReadSource(source) => {
if let Ok(read) = &source.expected
&& &read.path == path
{
if read != version {
return None;
}
sources += 1;
}
}
Call::FileSize(size) if size.read.as_ref().is_some_and(|read| &read.path == path) => {
// A size query can have been replayed from an equal-sized
// earlier source. Its exact path and numeric result are
// evidence, while the actual trace authenticates the bytes.
if call.observed_file_size() != Some((path.as_path(), version.bytes)) {
return None;
}
sizes += 1;
}
_ => {}
}
}
let count = sources.checked_add(sizes)?;
let mut actual = trace.reads.iter().filter(|read| &read.path == path);
if sources != 1 || actual.clone().count() != count || !actual.all(|read| read == version) {
return None;
}
let mut lookups = trace.lookups.iter().filter(|lookup| lookup.resolved.as_ref() == Some(path));
(lookups.clone().count() == count && lookups.all(|item| item.kind == ResourceKind::Tex))
.then_some(count)
}
impl Call {
pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> {
let Self::FileSize(read) = self else { return None };
@@ -178,6 +247,7 @@ impl<'a> RecordingHost<'a> {
&mut self,
calls: &[Call],
end_statistics: Option<&StatisticsReport>,
closed_source: Option<ClosedSourceUsageOffset>,
cancellation: &Cancellation,
) -> Result<(), String> {
let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?;
@@ -196,6 +266,18 @@ impl<'a> RecordingHost<'a> {
Call::EndStatistics(Arc::new(translated.clone()))
}
}
Call::ResourceUsage(read) if closed_source.is_some_and(|bytes| bytes.previous != bytes.current) => {
let bytes = closed_source.expect("checked closed source adjustment");
let mut observed = read.observed.clone();
if let Some(usage) = &mut observed {
usage.rebind_entry_bytes(bytes.previous, bytes.current)
.ok_or("invalid replayed child resource usage")?;
}
Call::ResourceUsage(Arc::new(ResourceUsageRead {
observed,
entry_bytes: read.entry_bytes,
}))
}
call => call.clone(),
};
call.replay(self.files, None)?;
+36
View File
@@ -169,6 +169,42 @@ impl ReplayBoundary {
pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool {
self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state
}
pub(super) fn trace_for_suffix(&self) -> &texrra_tex_core::resources::ResourceTrace {
&self.state.trace
}
/// The caller proves that all reads of this canonical path are the
/// closed source or its typed size queries, and that none are in the tail.
pub(super) fn matches_for_closed_source_suffix(
&self,
prior: &Self,
previous: &ResourceVersion,
current: &ResourceVersion,
) -> bool {
if self.entry_bytes.is_none() || self.entry_bytes != prior.entry_bytes {
return false;
}
let ReplayState {
inputs, outputs, next_handle, columns, terminal_enabled, generated_reads,
generated_before, generated_written, trace, stream_events,
} = &self.state;
let old = &prior.state;
if inputs != &old.inputs || outputs != &old.outputs || next_handle != &old.next_handle
|| columns != &old.columns || terminal_enabled != &old.terminal_enabled
|| generated_reads != &old.generated_reads || generated_before != &old.generated_before
|| generated_written != &old.generated_written || stream_events != &old.stream_events
{
return false;
}
let mut old_trace = old.trace.clone();
for read in &mut old_trace.reads {
if read == previous {
*read = current.clone();
}
}
*trace == old_trace
}
}
#[derive(PartialEq, Eq)]