Reuse cached layouts for relocated native shipouts

This commit is contained in:
gloamxun committed 2026-12-01 22:30:37 +08:00
1 parent 41a459b4ca
commit 57c05d9635
8 files changed
+394 -26

No files matched your search

@@ -43,6 +43,7 @@ mod scheduling;
mod specials;
mod statistics;
mod continuation;
pub use continuation::RelocatedShipoutSuffix;
mod xdv_annotation;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -87,10 +87,43 @@ impl InputFrame {
}
}
/// Source coordinates for the shipouts copied from a moved execution suffix.
pub struct RelocatedShipoutSuffix {
first_page: usize,
map: SourceRelocation,
}
impl RelocatedShipoutSuffix {
/// Relocate a raw local layout from the exact donor execution at the
/// given zero-based shipout index. The host must match that execution
/// before supplying a cached list.
pub fn relocate_layout(
&self,
index: usize,
layout: &crate::render::DisplayList,
) -> Option<crate::render::DisplayList> {
if index < self.first_page {
return None;
}
layout.relocate_sources(|span| self.map.relocate_span(span))
}
}
impl EntryCheckpoint {
/// Construct an execution with the current prefix and a previously
/// completed suffix. The host must still validate and replay that suffix.
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
self.splice_settled_suffix_with_layout(prior, completed)
.map(|(execution, _)| execution)
}
/// Also return the coordinate mapping for copied shipouts whose cached
/// local layouts belong to the supplied completed execution.
pub fn splice_settled_suffix_with_layout(
&self,
prior: &Self,
completed: &Execution,
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
if self.entry != self.active_source
|| prior.entry != prior.active_source
|| self.entry != prior.entry
@@ -190,7 +223,13 @@ impl EntryCheckpoint {
execution.events.push(offset_event_steps(event, offset)?);
}
}
Some(execution)
let layout = relocation.map(|map| RelocatedShipoutSuffix {
// The executor records one top-level shipout event whenever
// this count advances. Form canvases do not enter this sequence.
first_page: old.shipped_pages,
map,
});
Some((execution, layout))
}
/// Carry later checkpoints from the suffix accepted by
/// splice_settled_suffix into this revision. The host must still replay
+3 -1
View File
@@ -71,7 +71,9 @@ pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits};
pub use engine::{
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix,
};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
};
+205
View File
@@ -6,6 +6,7 @@
//! wired up.
use crate::cmr10::Cmr10Metrics;
use crate::execution::{Span, TokenOrigin};
use crate::math::{self, MathAtom, MathColumnAlign};
use crate::paragraph::ParagraphFont;
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
@@ -355,6 +356,78 @@ impl SvgTransparency {
}
impl DisplayList {
/// Reuse a raw shipout layout with a verified map of its source spans.
/// The current execution still projects forms and resolves PDF resources.
#[doc(hidden)]
pub fn relocate_sources(
&self,
mut relocate_span: impl FnMut(Span) -> Option<Span>,
) -> Option<Self> {
if !self.forms.is_empty() {
return None;
}
let mut relocate_origin = |mut origin: TokenOrigin| {
origin.span = relocate_span(origin.span)?;
if let Some(invocation) = origin.invocation {
origin.invocation = Some(relocate_span(invocation)?);
}
Some(origin)
};
let mut layout = self.clone();
for (old, moved) in self.sources.values().zip(layout.sources.values_mut()) {
for (index, origin) in old.tokens.iter().enumerate() {
let shifted = relocate_origin(*origin)?;
// Keep the lowered origin order and its equality classes. A
// newly merged or split origin would change PaintSource::merge.
if old.tokens[..index]
.iter()
.zip(&moved.tokens[..index])
.any(|(left, right)| (left == origin) != (*right == shifted))
{
return None;
}
moved.tokens[index] = shifted;
}
}
use crate::pdf_device::PdfGraphics;
for item in &mut layout.items {
match item {
DisplayItem::PdfGraphics { operation, .. } => match operation {
PdfGraphics::XdvFormUse { source, .. } => *source = relocate_origin(*source)?,
PdfGraphics::Save
| PdfGraphics::Matrix(_)
| PdfGraphics::Restore { .. }
| PdfGraphics::Literal { .. }
| PdfGraphics::SaveMatrix(_)
| PdfGraphics::TextBoundary
| PdfGraphics::XdvFormBegin(_)
| PdfGraphics::XdvFormEnd(_) => {}
},
DisplayItem::NativeGlyph { .. }
| DisplayItem::OpenTypeGlyph { .. }
| DisplayItem::OpenTypeActualText(_)
| DisplayItem::OpenTypeColor(_)
| DisplayItem::MathGlyph { .. }
| DisplayItem::Text { .. }
| DisplayItem::Rule { .. }
| DisplayItem::Line { .. }
| DisplayItem::Image { .. }
| DisplayItem::PdfImage { .. }
| DisplayItem::PdfImageObject(_)
| DisplayItem::PdfForm { .. }
| DisplayItem::Rect { .. }
| DisplayItem::Frame { .. }
| DisplayItem::Link { .. }
| DisplayItem::Background(_)
| DisplayItem::Fill(_)
| DisplayItem::PdfColor { .. }
| DisplayItem::PdfTextSpace { .. }
| DisplayItem::Special(_) => {}
}
}
Some(layout)
}
/// Whether page or captured form colors depend on a PDF default color space.
pub fn has_pdf_default_colors(&self) -> bool {
self.pdf_resources.has_default_color_spaces
@@ -2507,6 +2580,138 @@ impl Page {
mod tests {
use super::*;
#[test]
fn relocates_raw_shipout_origins_without_changing_paint_or_virtual_packets() {
use crate::math_engine_tex::{MathItem, PositionedItem};
use crate::pdf_device::PdfGraphics;
use crate::provenance::{Derivation, PaintSource};
use std::sync::Arc;
let span = |source, start| Span {
source,
start,
end: start + 1,
};
let glyph_origin = TokenOrigin {
span: span(2, 7),
invocation: Some(span(3, 12)),
};
let other_origin = TokenOrigin {
span: span(3, 4),
invocation: None,
};
let form_origin = TokenOrigin {
span: span(3, 15),
invocation: Some(span(2, 5)),
};
let packet = Arc::new(vec![PositionedItem {
x: 2,
y: 3,
item: MathItem::Rule {
width: 4,
height: 5,
},
source: PaintSource::default(),
}]);
let mut layout = DisplayList {
items: vec![
DisplayItem::Rule {
x: 1,
y: 2,
width: 3,
height: 4,
},
DisplayItem::PdfGraphics {
x: 5,
y: 6,
operation: PdfGraphics::XdvFormUse {
number: 7,
options: Default::default(),
source: form_origin,
available: true,
},
},
],
xdv_horizontal_offsets: vec![(1, 8)],
prepared_virtual_glyphs: Some([(0, packet.clone())].into()),
..Default::default()
};
layout.sources.insert(
0,
PaintSource {
tokens: vec![glyph_origin, other_origin],
derivations: vec![Derivation::FontMapping],
},
);
let relocated = layout
.relocate_sources(|value| {
Some(if value.source == 3 && value.start >= 10 {
span(value.source, value.start + 2)
} else {
value
})
})
.unwrap();
let mut expected = layout.clone();
expected.sources.get_mut(&0).unwrap().tokens[0].invocation = Some(span(3, 14));
let DisplayItem::PdfGraphics {
operation: PdfGraphics::XdvFormUse { source, .. },
..
} = &mut expected.items[1]
else {
unreachable!();
};
source.span = span(3, 17);
assert_eq!(relocated, expected);
assert!(Arc::ptr_eq(
&relocated.prepared_virtual_glyphs.unwrap()[&0],
&packet
));
}
#[test]
fn rejects_a_new_collision_or_unproved_invocation_in_relocated_origins() {
use crate::provenance::PaintSource;
let span = |offset| Span {
source: 0,
start: offset,
end: offset,
};
let layout = DisplayList {
items: vec![DisplayItem::Rule {
x: 0,
y: 0,
width: 1,
height: 1,
}],
sources: [(
0,
PaintSource {
tokens: vec![
TokenOrigin {
span: span(5),
invocation: Some(span(8)),
},
TokenOrigin {
span: span(6),
invocation: Some(span(8)),
},
],
derivations: Vec::new(),
},
)]
.into(),
..Default::default()
};
assert!(layout.relocate_sources(|_| Some(span(3))).is_none());
assert!(
layout
.relocate_sources(|value| { (value != span(8)).then_some(value) })
.is_none()
);
}
#[test]
fn tall_delimiters_are_lowered_to_stay_centered() {
let atom = crate::math::parse_math(r"\left(\frac{a}{b}\right)");
+24
View File
@@ -18,6 +18,30 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-12-01 复用已核验后缀的页面绘制
宿主重放通过后,当前编译尝试保留实际后缀原执行的身份、首个
复用页及已验证的来源换算。缓存绘制属于同一执行对象且页序匹配
时,直接使用其原始绘制列表并换算字形和 XDV 表单调用的来源。
其余页面继续走现有的精确比较和绘制流程。较早的执行可以提供
后缀,当前已经发布的页面缓存仍需匹配原执行。
当前修订继续解析字体、投影 PDF 表单和资源、生成来源映射并完成
导出。
12 页原样 NeurIPS 的第 3 页分别插入和删除 1 字节。两次都从
第 272 行恢复,执行 646,780 步并跳过 4,634,847 步未改后缀。
重新生成的绘制列表由上版 10 页降为 1 页,复用 11 页,两次都只
发布第 3 页。第 4 页字形来源按当前输入移动 1 字节。完整执行、
PDF、SVG、显示列表、来源映射、资源与流轨迹,以及 aux、out、log
均与独立全量一致。两份 PDF 及局部 SVG 与上版对应产物逐字节一致。
六项内核单测和十项管线回归通过。原执行身份不一致时,仍可复用
已核验的执行后缀,当前缓存绘制按原有逐页比较。证据及指纹位于
`target/p4-relocated-layout/`。本次两次热编辑在 Prepared 至 Executed
阶段分别用时 2.14 秒和 1.78 秒。后续测清宿主重放和内核执行各自的
成本,正式可见时延与内存仍按冻结语料验收。
## 2026-12-01 单行增删后复用未变化的后缀
同一物理行内增删后,扫描器须在后续字节一致的物理行会合。
+19 -10
View File
@@ -1127,9 +1127,9 @@ impl CompileJob {
evidence.phase = AttemptPhase::Executing;
let cache = &self.compiler.line_break_cache;
let before = cache.work();
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
let (executed, next_checkpoint, reused_layouts) = if let Some(current) = active_checkpoint {
debug_assert!(executor.is_none());
let (executed, next) = current.resume(
let (executed, next, reused_layouts) = current.resume(
&request,
&self.job,
source,
@@ -1139,7 +1139,7 @@ impl CompileJob {
allow_suffix,
suffix_failure,
)?;
(executed, Some(next))
(executed, Some(next), reused_layouts)
} else {
let executor = executor
.expect("fresh native job has an executor")
@@ -1150,9 +1150,9 @@ impl CompileJob {
if let Some(snapshot) = &captured {
snapshot.report_capture(&mut entry_checkpoint_work);
}
(executed, captured)
(executed, captured, None)
} else {
(self.job.run_detailed(executor, source, files), None)
(self.job.run_detailed(executor, source, files), None, None)
}
};
let execution = match executed {
@@ -1191,18 +1191,27 @@ impl CompileJob {
== Target::Shipouts
{
use texrra_tex_core::execution::Event;
let relocated_suffix = prior_layout.as_ref().and_then(|prior| {
reused_layouts.as_ref()
.filter(|reused| Arc::ptr_eq(&prior.execution, &reused.donor))
.map(|reused| &reused.suffix)
});
let mut old = prior_layout.as_deref().into_iter().flat_map(|prior| {
prior.execution.execution.events.iter().filter_map(|event| {
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| {
if let Some((_, layout)) =
old.next().filter(|(prior, _)| page.shares_local_layout_with(prior))
{
let reused = old.next().and_then(|(index, (prior, layout))| {
relocated_suffix
.and_then(|suffix| suffix.relocate_layout(index, layout))
.map(Arc::new)
.or_else(|| page.shares_local_layout_with(prior).then(|| layout.clone()))
});
if let Some(layout) = reused {
shipout_layout_work.reused_pages += 1;
shipout_layouts.push(layout.clone());
return Ok((**layout).clone());
return Ok((*layout).clone());
}
let layout = page.display_list()?;
shipout_layout_work.lowered_pages += 1;
+27 -9
View File
@@ -9,7 +9,7 @@ use std::{
path::Path,
};
use texrra_tex_core::{
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint},
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, RelocatedShipoutSuffix},
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
};
#[cfg(test)]
@@ -83,6 +83,11 @@ pub(super) struct SelectedCheckpoint {
candidate: ExecutionCandidate,
}
pub(super) struct ReusedShipoutLayouts {
pub(super) donor: Arc<RevisionExecution>,
pub(super) suffix: RelocatedShipoutSuffix,
}
enum ExecutionCandidate {
Boundary(usize),
Completed(Arc<CompletedExecution>),
@@ -874,6 +879,7 @@ impl SelectedCheckpoint {
(
Result<Arc<RevisionExecution>, RevisionFailure>,
Arc<CheckpointSet>,
Option<ReusedShipoutLayouts>,
),
CompileError,
> {
@@ -885,7 +891,11 @@ impl SelectedCheckpoint {
work.reused_steps = completed.result.execution.steps;
work.reused_completion = true;
work.replayed_calls = completed.calls.len();
return Ok((job.reuse_completed_after_host_replay(&completed.result, files), self.set));
return Ok((
job.reuse_completed_after_host_replay(&completed.result, files),
self.set,
None,
));
}
};
let checkpoint = &self.set.entries[index];
@@ -900,7 +910,7 @@ impl SelectedCheckpoint {
let result = job
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
.ok_or_else(changed_prefix)?;
return Ok((result, self.set));
return Ok((result, self.set, None));
}
let previous = checkpoint
@@ -945,6 +955,7 @@ impl SelectedCheckpoint {
let cancellation = job.cancellation();
let suffixes = self.set.completion.iter().chain(&self.set.suffix_base);
let mut suffix_base = None;
let mut reused_layouts = None;
let result = job
.resume_deciding_suffix(
&checkpoint.entry,
@@ -975,7 +986,7 @@ impl SelectedCheckpoint {
let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else {
return CheckpointDecision::Continue;
};
let Some((completed, old, execution)) = suffixes.clone().find_map(|completed| {
let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| {
let old = completed.settled.get(&page)?;
if old.call_count != new.call_count
|| !new.host.matches_for_suffix(&old.host)
@@ -983,9 +994,9 @@ impl SelectedCheckpoint {
{
return None;
}
let execution =
entry.splice_settled_suffix(&old.entry, &completed.result.execution)?;
Some((completed, old, execution))
let (execution, layout) = entry
.splice_settled_suffix_with_layout(&old.entry, &completed.result.execution)?;
Some((completed, old, execution, layout))
}) else {
return CheckpointDecision::Continue;
};
@@ -1007,6 +1018,10 @@ impl SelectedCheckpoint {
work.reused_suffix_steps = execution.steps - entry.completed_steps();
work.reused_steps += work.reused_suffix_steps;
work.replayed_calls += calls.len();
reused_layouts = layout.map(|suffix| ReusedShipoutLayouts {
donor: Arc::clone(&completed.result),
suffix,
});
CheckpointDecision::Reuse(Box::new(execution))
},
)
@@ -1015,11 +1030,14 @@ impl SelectedCheckpoint {
let next = result.as_ref().ok().and_then(|result| {
captures.finish(recording, true, result, suffix_base)
});
if result.is_err() {
reused_layouts = None;
}
if let Some(next) = next {
next.report_capture(work);
Ok((result, next))
Ok((result, next, reused_layouts))
} else {
Ok((result, self.set))
Ok((result, self.set, reused_layouts))
}
}
}
+75 -5
View File
@@ -1872,10 +1872,10 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() {
).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let mut previous = session.compile(request.clone().with_project(project.clone())).unwrap();
for (revision, letter, note) in [(2, 'B', "expanded comment"), (3, 'C', "x")] {
// Only the current document can donate the suffix in either direction.
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let previous = session.compile(request.clone().with_project(project.clone())).unwrap();
let source = format!("{HEADER}{}", body(letter, note, tail_query));
let tail_offset = source.find("Suffix glyphs").unwrap();
let bytes = i32::try_from(source.len()).unwrap();
@@ -1886,9 +1886,16 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() {
let updated = session.compile(job.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
assert_eq!(work.reused_suffix_steps > 0, tail_query.is_empty(), "{work:?}");
if !tail_query.is_empty() {
let layout = &updated.shipout_layout_work;
if tail_query.is_empty() {
// The cover and both pages in the accepted tail reuse local layout.
assert!(layout.reused_pages >= 3, "{work:?} {layout:?}");
} else {
// Only the cover can use its original source coordinates.
assert_eq!(layout.reused_pages, 1, "{work:?} {layout:?}");
assert_eq!(updated.execution.execution.state.count(42), bytes);
}
assert_eq!(layout.lowered_pages + layout.reused_pages, 5);
let preview = updated.preview_since(Some(previous.revision())).unwrap();
assert_eq!(preview.pages.iter().map(|page| page.index).collect::<Vec<_>>(), [1]);
assert!(updated.source_map.pages[3].entries.iter().any(|glyph| {
@@ -1905,12 +1912,75 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() {
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
previous = updated;
}
}
fs::remove_dir_all(cwd).unwrap();
}
#[test]
fn relocated_suffix_cannot_reuse_layouts_from_a_different_donor() {
let cwd = directory("relocated-suffix-older-donor");
let entry = cwd.join("main.tex");
let middle = "\\shipout\\hbox{Middle}\\relax\n".repeat(5);
let body = |early, early_comment, late, late_comment| format!(r"
\tracingstats=2
\shipout\hbox{{Cover ABCXYZ}}
\setbox3=\hbox{{{early}}}\relax%{early_comment}
\shipout\box3
\relax
{middle}\setbox3=\hbox{{{late}}}\relax%{late_comment}
\shipout\box3
\relax
\shipout\hbox{{Checkpoint}}\relax
\shipout\hbox{{Suffix glyphs}}\relax
\shipout\hbox{{Final}}\relax
\end
");
let original = body('A', "early", 'X', "late");
let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &original)).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
session.compile(request.clone().with_project(project.clone())).unwrap();
let early_edit = body('B', "expanded early comment", 'X', "late");
project = project.with_file_edits(
2, [(entry.clone(), Arc::from(format!("{HEADER}{early_edit}").into_bytes()))].into(),
).unwrap();
let latest = session.compile(request.clone().with_project(project.clone())).unwrap();
let first_work = &latest.entry_checkpoint_work;
assert!(first_work.reused_suffix_steps > 0, "{first_work:?}");
// Relative to the latest layout this changes two lines. Only the older
// execution, which differs on the late line alone, can donate the suffix.
let late_edit = body('A', "early", 'Y', "x");
project = project.with_file_edits(
3, [(entry, Arc::from(format!("{HEADER}{late_edit}").into_bytes()))].into(),
).unwrap();
let job = request.with_project(project);
let updated = session.compile(job.clone()).unwrap();
let work = &updated.entry_checkpoint_work;
let layout = &updated.shipout_layout_work;
assert!(work.reused_suffix_steps > 0, "{work:?}");
assert_eq!(layout.reused_pages, 1, "{work:?} {layout:?}");
assert_eq!(layout.lowered_pages, updated.pages.len() - 1);
let changed: Vec<_> = updated.preview_since(Some(latest.revision())).unwrap()
.pages.into_iter().map(|page| page.index).collect();
assert_eq!(changed, [1, 7]);
let log = fs::read(cwd.join("job.log")).unwrap();
let full = NativeCompiler::default().compile(job).unwrap();
assert_eq!(updated.execution.execution, full.execution.execution);
assert_eq!(updated.resources.trace, full.resources.trace);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.pages, full.pages);
assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
fs::remove_dir_all(cwd).unwrap();
}
#[test]
fn settled_suffix_translates_step_counts_and_enforces_the_limit() {
let cwd = directory("settled-step-counts");