From c008c5296482e4503223e8d7fe98588e064512f2 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Tue, 1 Dec 2026 22:50:53 +0800 Subject: [PATCH] Reduce macro copying during native suffix convergence --- .../src/execution/engine/continuation.rs | 25 +++++--- .../execution/engine/continuation/relocate.rs | 54 ++++++++-------- .../texrra-tex-core/src/execution/session.rs | 22 ++++--- .../src/execution/source_relocation_events.rs | 58 +++++++++++++++-- .../src/execution/state/source_relocation.rs | 62 +++++-------------- .../tests/execution_attempts.rs | 9 ++- docs/P2_M1_PROGRESS.md | 39 ++++++++++++ src/native.rs | 19 ++++++ src/native_checkpoint_guard.rs | 50 +++++++++++---- 9 files changed, 228 insertions(+), 110 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index 6f2fa69..18dea25 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -1,4 +1,6 @@ -use super::super::source_relocation::SourceRelocation; +use super::super::{ + source_relocation::SourceRelocation, source_relocation_events::EventRelocation, +}; use super::*; mod material; mod relocate; @@ -171,7 +173,10 @@ impl EntryCheckpoint { None if self.frontier == prior.frontier => None, None => return None, }; - if !same_kernel_continuation(current, old, relocation.as_ref()) { + // Comparison and publication visit some of the same original + // allocations. Keep the checked relocations for this donor only. + let mut moved = relocation.as_ref().map(EventRelocation::new); + if !same_kernel_continuation(current, old, moved.as_mut()) { return None; } let offset = StepOffset::new(old.steps, current.steps); @@ -214,8 +219,11 @@ impl EntryCheckpoint { reads_event_history: false, accounts_event_history: completed.accounts_event_history, }; - if let Some((map, sizes)) = relocation.as_ref().zip(entry_sizes) { - relocate::append_suffix(&mut execution, tail, offset, map, sizes, old.sources.len())?; + if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) { + relocate::append_suffix(&mut execution, tail, offset, moved, sizes, old.sources.len())?; + if execution.state != completed.state { + execution.outgoing_state = execution.state.fingerprint(); + } } else if offset.is_identity() { execution.events.extend_from_slice(tail); } else { @@ -378,7 +386,7 @@ fn is_idle_continuation(e: &Executor) -> bool { fn same_kernel_continuation( current: &Executor, prior: &Executor, - relocation: Option<&SourceRelocation>, + relocation: Option<&mut EventRelocation<'_>>, ) -> bool { // Every field belongs to one of these checks. Adding kernel state requires // an explicit decision here before a later execution may be skipped. @@ -489,9 +497,10 @@ fn same_kernel_continuation( { return false; } + let map = relocation.as_ref().map(|context| context.map()); let relocated; - let prior = if let Some(map) = relocation { - relocated = match relocate::kernel_continuation(prior, map) { + let prior = if let Some(context) = relocation { + relocated = match relocate::kernel_continuation(prior, context) { Some(executor) => executor, None => return false, }; @@ -522,5 +531,5 @@ fn same_kernel_continuation( .inputs .iter() .zip(&prior.inputs) - .all(|(a, b)| a.same_at_shipout(b, relocation)) + .all(|(a, b)| a.same_at_shipout(b, map)) } diff --git a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs index cbc1a4e..b9c7717 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs @@ -1,26 +1,26 @@ use super::*; -use crate::execution::{ - source_relocation_events::EventRelocation, state::source_relocation::relocate_macro, -}; +use crate::execution::source_relocation_events::EventRelocation; -pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> Option { +pub(super) fn kernel_continuation( + prior: &Executor, + relocation: &mut EventRelocation<'_>, +) -> Option { let mut prior = prior.clone(); - let mut relocation = EventRelocation::new(map); + let map = relocation.map(); prior.current = map.relocate_span(prior.current)?; - prior.state = prior.state.relocate_source(&mut relocation)?; + prior.state.relocate_source(relocation)?; relocate_generated(&mut prior.generated_inputs, map)?; for conditional in &mut prior.conditionals { conditional.span = map.relocate_span(conditional.span)?; } - let mut macros = std::collections::HashMap::new(); for frame in &mut prior.inputs { match frame { InputFrame::Tokens { tokens, .. } => match tokens { - InputTokens::One(token) => token.token = relocation.relocate_token(&token.token)?, + InputTokens::One(token) => relocation.relocate_token(&mut token.token)?, InputTokens::Many(tokens) => { for token in tokens { - token.token = relocation.relocate_token(&token.token)?; + relocation.relocate_token(&mut token.token)?; } } }, @@ -30,7 +30,7 @@ pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> O call, .. } => { - *definition = relocate_macro(definition, &mut relocation, &mut macros)?; + *definition = relocation.relocate_macro(definition)?; for tokens in arguments { *tokens = relocation.relocate_tokens(tokens)?; } @@ -45,17 +45,17 @@ pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> O InputFrame::Source { .. } | InputFrame::Boundary => {} } } - relocate_tokens(&mut prior.pdf_catalog_tokens, &mut relocation)?; - relocate_tokens(&mut prior.pdf_info_tokens, &mut relocation)?; + relocate_tokens(&mut prior.pdf_catalog_tokens, relocation)?; + relocate_tokens(&mut prior.pdf_info_tokens, relocation)?; for outline in &mut prior.pdf_outlines { - relocate_tokens(&mut outline.attributes, &mut relocation)?; + relocate_tokens(&mut outline.attributes, relocation)?; } if let Some(token) = &mut prior.after_assignment { - *token = relocation.relocate_token(token)?; + relocation.relocate_token(token)?; } - relocate_vertical(&mut prior.vertical.nodes, &mut relocation)?; - relocate_vertical(&mut prior.split_discards, &mut relocation)?; - relocate_page(&mut prior.native_page, &mut relocation)?; + relocate_vertical(&mut prior.vertical.nodes, relocation)?; + relocate_vertical(&mut prior.split_discards, relocation)?; + relocate_page(&mut prior.native_page, relocation)?; for value in &mut prior.pending_shipouts { *value = relocation.relocate_box(value)?; } @@ -66,11 +66,11 @@ pub(super) fn append_suffix( execution: &mut Execution, tail: &[Event], offset: StepOffset, - map: &SourceRelocation, + relocation: &mut EventRelocation<'_>, (previous_bytes, current_bytes): (usize, usize), source_count: usize, ) -> Option<()> { - let mut relocation = EventRelocation::new(map); + let map = relocation.map(); for event in tail { if let Event::Statistics(report) = event { if let StatisticsPhase::Shipout { before, after } = &report.phase { @@ -90,19 +90,15 @@ pub(super) fn append_suffix( execution.events.push(relocation.relocate_event(event)?); } } - let state = execution.state.relocate_source(&mut relocation)?; - if state != execution.state { - execution.outgoing_state = state.fingerprint(); - } - execution.state = state; - relocate_page(&mut execution.native_page, &mut relocation)?; - relocate_vertical(&mut execution.split_discards, &mut relocation)?; + execution.state.relocate_source(relocation)?; + relocate_page(&mut execution.native_page, relocation)?; + relocate_vertical(&mut execution.split_discards, relocation)?; if let Some(token) = &mut execution.after_assignment { - *token = relocation.relocate_token(token)?; + relocation.relocate_token(token)?; } relocate_generated(&mut execution.generated_inputs, map)?; for image in &mut execution.format_pdf_images { - relocate_tokens(&mut image.attributes, &mut relocation)?; + relocate_tokens(&mut image.attributes, relocation)?; } Some(()) } @@ -132,7 +128,7 @@ fn relocate_page( fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> { for token in tokens { - *token = relocation.relocate_token(token)?; + relocation.relocate_token(token)?; } Some(()) } diff --git a/crates/texrra-tex-core/src/execution/session.rs b/crates/texrra-tex-core/src/execution/session.rs index b12bb1c..c9129f8 100644 --- a/crates/texrra-tex-core/src/execution/session.rs +++ b/crates/texrra-tex-core/src/execution/session.rs @@ -332,12 +332,12 @@ impl RevisionJob { ) -> Result, RevisionFailure> { // Host observations can themselves supersede the revision. Do not // invoke the host while holding the session publication lock. - let resources = files.execution_resource_trace().cloned(); + let mut resources = files.execution_resource_trace().cloned(); let result = executed.map(|execution| { Arc::new(RevisionExecution::with_previous_sources( self.revision, execution, - resources.clone(), + resources.take(), previous, )) }); @@ -359,13 +359,17 @@ impl RevisionJob { completed_execution: None, resources, }), - Ok(result) if cancelled => Err(RevisionFailure { - revision: self.revision, - error: RevisionError::Cancelled, - failed_execution: None, - completed_execution: Some(result), - resources, - }), + Ok(result) if cancelled => { + drop(state); + let resources = result.execution_resources.clone(); + Err(RevisionFailure { + revision: self.revision, + error: RevisionError::Cancelled, + failed_execution: None, + completed_execution: Some(result), + resources, + }) + } Ok(result) => { state.latest = Some(Arc::clone(&result)); Ok(result) diff --git a/crates/texrra-tex-core/src/execution/source_relocation_events.rs b/crates/texrra-tex-core/src/execution/source_relocation_events.rs index 03882ea..d7296b8 100644 --- a/crates/texrra-tex-core/src/execution/source_relocation_events.rs +++ b/crates/texrra-tex-core/src/execution/source_relocation_events.rs @@ -11,12 +11,16 @@ use crate::{ }, provenance::PaintSource, }; -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::{HashMap, hash_map::Entry}, + sync::Arc, +}; type Shared = HashMap<*const T, Arc>; pub(super) struct EventRelocation<'a> { map: &'a SourceRelocation, + macros: Shared, text_lists: Shared>, vertical_lists: Shared>, diagnostic_lists: Shared<[DiagnosticNode]>, @@ -28,6 +32,7 @@ impl<'a> EventRelocation<'a> { pub(super) fn new(map: &'a SourceRelocation) -> Self { Self { map, + macros: HashMap::new(), text_lists: HashMap::new(), vertical_lists: HashMap::new(), diagnostic_lists: HashMap::new(), @@ -36,6 +41,10 @@ impl<'a> EventRelocation<'a> { } } + pub(super) fn map(&self) -> &'a SourceRelocation { + self.map + } + pub(super) fn relocate_event(&mut self, event: &Event) -> Option { self.relocated(event) } @@ -51,8 +60,36 @@ impl<'a> EventRelocation<'a> { self.relocated(node) } - pub(super) fn relocate_token(&mut self, token: &Token) -> Option { - self.relocated(token) + pub(super) fn relocate_token(&mut self, token: &mut Token) -> Option<()> { + token.relocate(self) + } + + pub(super) fn relocate_macro(&mut self, body: &Arc) -> Option> { + match self.macros.entry(Arc::as_ptr(body)) { + Entry::Occupied(entry) => Some(entry.get().clone()), + Entry::Vacant(entry) => { + let mut mapped = None; + for (index, part) in body.replacement.iter().enumerate() { + if let Replacement::Token(token) = part { + let previous = TokenOrigin::from(token); + let mut next = previous; + relocate_origin(&mut next, self.map)?; + if next != previous { + let replacement = &mut mapped + .get_or_insert_with(|| body.as_ref().clone()) + .replacement[index]; + let Replacement::Token(token) = replacement else { + unreachable!("cloned macro replacement retains its token kind"); + }; + token.span = next.span; + token.invocation = next.invocation; + } + } + } + let mapped = mapped.map_or_else(|| body.clone(), Arc::new); + Some(entry.insert(mapped).clone()) + } + } } pub(super) fn relocate_tokens(&mut self, tokens: &Arc<[Token]>) -> Option> { @@ -150,7 +187,20 @@ macro_rules! relocate_fields { } relocate_fields!(Token { span, invocation; kind }); -relocate_fields!(TokenOrigin { span, invocation; }); +impl Relocate for TokenOrigin { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + relocate_origin(self, context.map) + } +} + +fn relocate_origin(origin: &mut TokenOrigin, map: &SourceRelocation) -> Option<()> { + let TokenOrigin { span, invocation } = origin; + *span = map.relocate_span(*span)?; + if let Some(invocation) = invocation { + *invocation = map.relocate_span(*invocation)?; + } + Some(()) +} relocate_fields!(PaintSource { tokens; derivations }); relocate_fields!(NativeRule { span, origin; derivation, width, height, depth }); relocate_fields!(NativeMark { span, tokens; class }); diff --git a/crates/texrra-tex-core/src/execution/state/source_relocation.rs b/crates/texrra-tex-core/src/execution/state/source_relocation.rs index 85c37b4..6c91a43 100644 --- a/crates/texrra-tex-core/src/execution/state/source_relocation.rs +++ b/crates/texrra-tex-core/src/execution/state/source_relocation.rs @@ -1,44 +1,42 @@ use super::*; use crate::execution::source_relocation_events::EventRelocation; use crate::pdf_device::forms::FormContents; -use std::collections::HashMap; impl State { /// Relocate the provenance stored in persistent kernel assignments. A /// command shard or macro shared by aliases keeps its ownership structure. pub(in crate::execution) fn relocate_source( - &self, + &mut self, relocation: &mut EventRelocation<'_>, - ) -> Option { - let mut state = self.clone(); - let mut macros = HashMap::new(); + ) -> Option<()> { + let commands = self.commands.clone(); // Copy only shards with a relocated macro. Ordinary format macros // and macros from the byte-identical prefix keep their allocations. - for (index, shard) in self.commands.shards.iter().enumerate() { + for (index, shard) in commands.shards.iter().enumerate() { for (name, meaning) in shard.iter() { if let Meaning::Macro(body) = meaning { - let relocated = relocate_macro(body, relocation, &mut macros)?; + let relocated = relocation.relocate_macro(body)?; if !Arc::ptr_eq(body, &relocated) { - let shard = &mut Arc::make_mut(&mut state.commands).shards[index]; + let shard = &mut Arc::make_mut(&mut self.commands).shards[index]; Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated)); } } } } - for tokens in state.toks.values_mut() { + for tokens in self.toks.values_mut() { relocate_tokens(tokens, relocation)?; } - for tokens in state + for tokens in self .token_parameters .values_mut() - .chain(state.xe_inter_char_tokens.values_mut()) + .chain(self.xe_inter_char_tokens.values_mut()) { *tokens = relocation.relocate_tokens(tokens)?; } - for value in state.boxes.values_mut() { + for value in self.boxes.values_mut() { *value = relocation.relocate_box(value)?; } - for marks in state.page_marks.values_mut() { + for marks in self.page_marks.values_mut() { for tokens in [&mut marks.top, &mut marks.first, &mut marks.bottom] .into_iter() .flatten() @@ -46,11 +44,11 @@ impl State { *tokens = relocation.relocate_tokens(tokens)?; } } - for marks in state.split_marks.values_mut() { + for marks in self.split_marks.values_mut() { marks.first = relocation.relocate_tokens(&marks.first)?; marks.bottom = relocation.relocate_tokens(&marks.bottom)?; } - for form in state.pdf_forms.values_mut() { + for form in self.pdf_forms.values_mut() { if let FormContents::Pending(body) = &mut form.contents { let mut mapped = body.as_ref().clone(); mapped.box_node = relocation.relocate_box(&mapped.box_node)?; @@ -61,12 +59,12 @@ impl State { } } } - for group in &mut state.groups { + for group in &mut self.groups { relocate_tokens(&mut group.after, relocation)?; for saved in group.saved.values_mut() { match saved { Saved::Command(Some(Meaning::Macro(body))) => { - *body = relocate_macro(body, relocation, &mut macros)?; + *body = relocation.relocate_macro(body)?; } Saved::Tokens(Some(tokens)) => relocate_tokens(tokens, relocation)?, Saved::Hook(Some(tokens)) | Saved::XeInterCharTokens(Some(tokens)) => { @@ -94,39 +92,13 @@ impl State { } } } - Some(state) + Some(()) } } fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> { for token in tokens { - *token = relocation.relocate_token(token)?; + relocation.relocate_token(token)?; } Some(()) } - -pub(in crate::execution) fn relocate_macro( - body: &Arc, - relocation: &mut EventRelocation<'_>, - cached: &mut HashMap<*const Macro, Arc>, -) -> Option> { - use std::collections::hash_map::Entry; - match cached.entry(Arc::as_ptr(body)) { - Entry::Occupied(entry) => Some(entry.get().clone()), - Entry::Vacant(entry) => { - let mut mapped = None; - for (index, part) in body.replacement.iter().enumerate() { - if let Replacement::Token(token) = part { - let next = relocation.relocate_token(token)?; - if next != *token { - mapped - .get_or_insert_with(|| body.as_ref().clone()) - .replacement[index] = Replacement::Token(next); - } - } - } - let mapped = mapped.map_or_else(|| body.clone(), Arc::new); - Some(entry.insert(mapped).clone()) - } - } -} diff --git a/crates/texrra-tex-core/tests/execution_attempts.rs b/crates/texrra-tex-core/tests/execution_attempts.rs index 2d355d2..df3f3ea 100644 --- a/crates/texrra-tex-core/tests/execution_attempts.rs +++ b/crates/texrra-tex-core/tests/execution_attempts.rs @@ -1,6 +1,6 @@ //! Failed observations are retained without publishing or claiming a checkpoint. use sha2::{Digest, Sha256}; -use std::cell::RefCell; +use std::{cell::RefCell, sync::Arc}; use texrra_tex_core::{execution::*, resources::ResourceTrace}; fn source(name: &str, text: &str) -> SourceFile { @@ -52,7 +52,7 @@ fn failed_child_macro_keeps_actual_versions_meanings_events_and_state_boundary() ); assert_eq!(host.messages, ["BEFORE"]); let e = &failure.evidence; - assert_eq!(e.sources, [main, child]); + assert_eq!(e.sources, [Arc::new(main), Arc::new(child)]); for (s, v) in e.sources.iter().zip(&e.source_versions) { assert_eq!(v.sha256, format!("{:x}", Sha256::digest(&s.data))); assert_eq!(v.bytes, s.data.len() as u64); @@ -102,7 +102,7 @@ fn cancellation_preserves_observed_progress_but_prestart_does_not_invent_input() }; let failure = run().run_detailed(main.clone(), &mut host).unwrap_err(); assert!(failure.error.message.contains("cancelled")); - assert_eq!(failure.evidence.sources, [main.clone()]); + assert_eq!(failure.evidence.sources, [Arc::new(main.clone())]); assert!(failure.evidence.reads.contains(&Dependency::Source(0))); assert_eq!(host.messages, ["FIRST"]); let before = run().run_detailed(main, &mut host).unwrap_err(); @@ -145,6 +145,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() { .start() .run(executor(), source("old.tex", r"\count0=1\end"), &mut host) .unwrap(); + assert_eq!(previous.execution_resources, Some(host.trace.clone())); host.armed = true; let failure = session .start() @@ -156,6 +157,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() { assert_eq!(completed.execution.state.count(0), 2); assert_eq!(completed.revision, failure.revision); assert_eq!(failure.resources, Some(host.trace.clone())); + assert_eq!(completed.execution_resources, failure.resources); assert_eq!(session.latest().unwrap().revision, previous.revision); assert!(host.pending.borrow().as_ref().unwrap().revision() > completed.revision); host.pending.borrow_mut().take(); @@ -165,6 +167,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() { .unwrap_err(); assert!(matches!(interrupted.error, RevisionError::Cancelled)); assert!(interrupted.completed_execution.is_none()); + assert_eq!(interrupted.resources, Some(host.trace.clone())); assert!( interrupted .failed_execution diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index c54987b..7b5146c 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,45 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-12-01 热编辑的会合与宿主开销 + +在 `57c05d9` 的 NeurIPS 同一行增删对照中,从 Prepared 到 +Executed 取得 1,098 个 CPU 样本。高频位置包括内存分配、 +复制、命令排序,以及用于确认宏来源的 token 克隆。 + +宏重定位现在先检查来源和调用位置,位置移动时才复制宏体。 +同一次会合与后缀拼接共享已验证的结果。直接更新已有草稿, +省去对完整状态的重复复制。成功执行也直接拥有已取得的资源 +轨迹,被其他修订取消的结果和失败证据继续保留各自的轨迹。 +编译观察器可分别取得捕获、宿主核验、内核核验、后缀重放 +和保留检查点的时间。 + +同一项目两个热编辑的 Prepared 至 Executed 由 2.28/2.12 秒 +记录为 1.57/1.07 秒。会合核验与拼接分别占 808/523 毫秒, +此区间的宿主核验和后缀重放合计 21/14 毫秒。扣除这些实测区间 +及捕获开销后,恢复、执行和核心收尾还有 723/525 毫秒。 +宏和 token 重定位相关样本由 62/1,098 降至 19/661。 +这些数据用于选定下一次优化位置。正式可见时延和内存仍按冻结 +工况采样。 + +两次仍执行 646,780 步、跳过 4,634,847 步后缀,重生成 1 页 +绘制并复用 11 页。完整执行、PDF、SVG、字形来源、显示列表、 +资源和文件效果等同独立全量,PDF 和局部 SVG 与上版逐字节一致。 +八项管线回归和三项失败及取消回归通过。 +下一批沿内核会合核验拆分状态比较、资源记账和后缀换算。 +证据位于 `target/p4-hot-execution-profile/`。 + +### Springer Nature 旋转目标复核 + +本地 pdfTeX 1.40.29 上,同一个旋转 XYZ 目标仅在输入前加入 +一个创建后丢弃的空盒,坐标就从 `[71.004 128.249]` 变成 +`[-4009.694 128.249]`,栅格相同。八种控制在 INITEX 和 plain +格式各重复两次,同组 PDF 字节一致。所检查的 WEB 实现表明, +普通 XYZ 未写入 FitR 尺寸字段,但矩阵输出会读取这些节点槽位。 +该结果依赖内核节点分配与释放历史,Springer 第 5 页 `table.3` +坐标差异仍开放。对照与源码版本指纹已保存在 +`target/p4-hot-execution-profile/springer-controls/`。 + ## 2026-12-01 复用已核验后缀的页面绘制 宿主重放通过后,当前编译尝试保留实际后缀原执行的身份、首个 diff --git a/src/native.rs b/src/native.rs index 7eda36c..a7d9dbc 100644 --- a/src/native.rs +++ b/src/native.rs @@ -27,6 +27,7 @@ use std::{ collections::BTreeMap, path::{Path, PathBuf}, sync::{Arc, Mutex}, + time::Duration, }; pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, ProjectVersion}; pub use texrra_tex_core::resources::{WorldFailure, WorldObservation}; @@ -94,12 +95,30 @@ pub enum CompileStage { Exported, ReadyToPublish, } +/// Elapsed work while resuming a native checkpoint after prefix replay. +/// The callback slices are disjoint and included in `resume`. +#[derive(Clone, Copy, Debug, Default)] +pub struct CheckpointTimings { + /// Restoring the executor, running new commands, observing checkpoints, + /// and finishing the revision's kernel result. + pub resume: Duration, + pub capture: Duration, + pub suffix_host_validation: Duration, + pub suffix_kernel_validation: Duration, + pub suffix_host_replay: Duration, + /// Collecting the retained checkpoint set after the resumed run. + pub retain: Duration, +} + /// Called outside the publication lock. An observer can request a new /// revision or fail without publishing this result. Start/cancel are allowed; /// schedule compilation after the callback returns, rather than recursing. pub trait CompileObserver: Send + Sync { fn stage(&self, revision: u64, stage: CompileStage) -> Result<(), String>; + /// Observe the work of a resumed native revision before layout begins. + fn checkpoint_timings(&self, _revision: u64, _timings: CheckpointTimings) {} + /// Called for a completed native draft before its staged files are synced /// and installed. The caller can display these pages provisionally. The /// compile result determines whether this revision actually published. diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index ca752c5..8346c19 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -7,6 +7,7 @@ use std::{ collections::{BTreeMap, BTreeSet, VecDeque}, ffi::OsString, path::Path, + time::Instant, }; use texrra_tex_core::{ execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, RelocatedShipoutSuffix}, @@ -956,6 +957,9 @@ impl SelectedCheckpoint { let suffixes = self.set.completion.iter().chain(&self.set.suffix_base); let mut suffix_base = None; let mut reused_layouts = None; + let mut timings = CheckpointTimings::default(); + let timed = request.observer.is_some(); + let resume_started = timed.then(Instant::now); let result = job .resume_deciding_suffix( &checkpoint.entry, @@ -979,7 +983,9 @@ impl SelectedCheckpoint { }, |slots, entry, host| { let entry = Arc::new(entry); - captures.capture(slots, entry.clone(), host); + measure(&mut timings.capture, timed, || { + captures.capture(slots, entry.clone(), host); + }); let Capture::Settled { page, .. } = slots else { return CheckpointDecision::Continue; }; @@ -988,21 +994,25 @@ impl SelectedCheckpoint { }; 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) - || !can_replay_completed_suffix(completed, request, host.files()) - { + let host_matches = measure(&mut timings.suffix_host_validation, timed, || { + old.call_count == new.call_count + && new.host.matches_for_suffix(&old.host) + && can_replay_completed_suffix(completed, request, host.files()) + }); + if !host_matches { return None; } - let (execution, layout) = entry - .splice_settled_suffix_with_layout(&old.entry, &completed.result.execution)?; + let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || { + entry.splice_settled_suffix_with_layout(&old.entry, &completed.result.execution) + })?; Some((completed, old, execution, layout)) }) else { return CheckpointDecision::Continue; }; let calls = &completed.calls[old.call_count..]; - let replayed = - captures.replay_settled_suffix(page, &entry, old, completed, host, &cancellation); + let replayed = measure(&mut timings.suffix_host_replay, timed, || { + captures.replay_settled_suffix(page, &entry, old, completed, host, &cancellation) + }); if let Err(error) = replayed { let discarded = entry.completed_steps().saturating_sub(work.reused_steps); *suffix_failure = Some((error.clone(), discarded)); @@ -1027,10 +1037,17 @@ impl SelectedCheckpoint { ) .map_err(CompileError::Host)? .ok_or_else(changed_prefix)?; - let next = result.as_ref().ok().and_then(|result| { - captures.finish(recording, true, result, suffix_base) + if let Some(started) = resume_started { + timings.resume = started.elapsed(); + } + let next = measure(&mut timings.retain, timed, || { + result.as_ref().ok().and_then(|result| captures.finish(recording, true, result, suffix_base)) }); - if result.is_err() { + if result.is_ok() { + if let Some(observer) = &request.observer { + observer.checkpoint_timings(job.revision(), timings); + } + } else { reused_layouts = None; } if let Some(next) = next { @@ -1042,6 +1059,15 @@ impl SelectedCheckpoint { } } +fn measure(elapsed: &mut Duration, enabled: bool, action: impl FnOnce() -> T) -> T { + let started = enabled.then(Instant::now); + let value = action(); + if let Some(started) = started { + *elapsed += started.elapsed(); + } + value +} + fn can_replay_completed_suffix( completed: &CompletedExecution, request: &CompileRequest,