From 43231a48c00dc66f3065bb09cdd1a371ef0de907 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Thu, 19 Nov 2026 11:16:40 +0800 Subject: [PATCH] Reuse validated checkpoint executors during native preview --- .../src/execution/format_image.rs | 7 +- docs/P2_M1_PROGRESS.md | 8 +- docs/PUBLISHER_TEMPLATE_MATRIX.md | 10 +- examples/native_editor/app.js | 2 + examples/native_editor/main.rs | 54 +++++++- src/native.rs | 117 ++++++++++++------ src/native_checkpoint_guard.rs | 10 +- src/native_checkpoint_probe.rs | 2 +- 8 files changed, 160 insertions(+), 50 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index afb6ce0..4d93f14 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -141,7 +141,7 @@ impl FormatImage { read: impl FnMut(&mut F, &Path) -> Result, date: impl FnMut(&mut F, &str, &str) -> Result, String>, ) -> Result { - self.validate_job(profile, input_profile, files, read, date)?; + self.validate_job_inputs(profile, input_profile, files, read, date)?; Ok(Executor::new_format_job( self.state.with_job_time(time), self.sources, @@ -181,7 +181,7 @@ impl FormatImage { read: impl FnMut(&mut F, &Path) -> Result, date: impl FnMut(&mut F, &str, &str) -> Result, String>, ) -> Result { - self.validate_job(profile, input_profile, files, read, date)?; + self.validate_job_inputs(profile, input_profile, files, read, date)?; Ok(Executor::new_format_job( self.state.clone().with_job_time(time), self.sources.clone(), @@ -191,7 +191,8 @@ impl FormatImage { )) } - fn validate_job>( + /// Check the format profile and every required input without forking a job. + pub fn validate_job_inputs>( &self, profile: Profile, input_profile: InputProfile, diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 0f25961..0f19365 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -135,7 +135,13 @@ p50 2010.9 ms、p95 3125.1 ms。原始样本见 `target/p4-native-editor-preview/release-edge-warm-30/report.json`,SHA-256 `f57bb0456bd36180867a908cfbdabe17ac81c464dfba2ba5d831c7fe488b624b`。 采样时有并行构建,当前结果用于定位,100 ms预算仍待正式验收。 -独立续跑准备候选通过实际依赖守卫和 Edge 端到端复验,仍在运行全工作区回归。 +续跑准备复用已捕获执行器,依然校验实际格式依赖与锁内生成初态。该候选 +通过1599项工作区测试、实际依赖守卫和 Edge 端到端复验,按478项源码 +指纹合入主线。原样 A3 两轮都从字节411续跑、跳过794348步、重放61项 +宿主调用并只替换第7页;PDF、布局、SVG、来源映射、aux 和日志与独立全量一致。 +试验页已接入七阶段计时。旧手动探针在既有基线和候选上都因选择过早而失败, +两份失败与正式自动续跑凭据留在 `target/p4-resume-preparation`。 +同一候选的带计时优化构建正在运行,100 ms预算仍待正式验收。 多文件崩溃恢复和正式界面接入继续推进。 同一编译结果的差量预览通过37项原生预览与 PK 字体关联回归。原样8页 A3 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index 2d0ac60..e1969c7 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -194,7 +194,15 @@ schema24 候选按原参考条件通过七项 article 的21轮复验。原样 Sp JPEG 的原版探针保留原资源、改扩展名、自然密度、指定尺寸、灰度、CMYK、 渐进扫描和两种 EXIF 字节序的实际 PDF。嵌入的 DCT 流可逐字节还原输入。 隔离候选已接通实际导入和预览入口,9份实际文件的头解析断言已通过。 -真实 CLI 回归已启动,随后运行 PDF 差分和原样 Elsevier 两项的复验。 +真实 CLI、PDF 图形及预览3项通过,另有16份 PDF 匹配盒尺寸与 DCT 原始流, +并核对实际资源读取。5个指定渲染区域逐像素相同,2份拒绝保留已完成的输出。 +对照见 `target/p3-jpeg-native/debug-pdftex-compare/report.json`。原样 Elsevier +两项正在用新格式复验。 + +CVPR 容量错误已用一个501节点的竖直列表独立复现。原版拆盒重打包2050次并 +输出,旧原生触发同一容量检查。隔离候选在达到原阈值时核对实际活动与保留 +材料,保留超限单盒和复制材料的检测。盒、页、拆分和统计共30项通过,详见 +`target/p3-box-capacity-native/directed-2.log`。原样 CVPR 的优化复验待完成。 单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、 双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源 diff --git a/examples/native_editor/app.js b/examples/native_editor/app.js index a448799..5868d92 100644 --- a/examples/native_editor/app.js +++ b/examples/native_editor/app.js @@ -79,6 +79,8 @@ async function compile(edit, submitted) { count: update.page_count, compileMs: result.compile_ms, engineMs: result.ready_ms, + admissionAndQueueMs: result.admission_and_queue_ms, + phases: result.phases, visibleMs: performance.now() - submitted, steps: result.steps, reusedSteps: result.reused_steps, diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 50c5d8c..562babe 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -13,8 +13,8 @@ use std::{ time::Instant, }; use texrra_engine::native::{ - CompileError, CompileJob, CompileRequest, Entry, NativeCompiler, ProjectDefinition, - ProjectSnapshot, job_time, + CompileError, CompileJob, CompileObserver, CompileRequest, CompileStage, Entry, NativeCompiler, + ProjectDefinition, ProjectSnapshot, job_time, }; use texrra_tex_core::resources::{InputPolicy, WorldConfig}; use tiny_http::{Header, Method, Request, Response, Server}; @@ -36,6 +36,41 @@ struct Work { compile: CompileRequest, sequence: u64, visible_revision: Option, + received: Instant, +} + +struct StageTimes { + started: Instant, + ended: Mutex<[f64; 5]>, +} + +impl CompileObserver for StageTimes { + fn stage(&self, _: u64, stage: CompileStage) -> Result<(), String> { + let index = match stage { + CompileStage::Prepared => 0, + CompileStage::Executed => 1, + CompileStage::FontsResolved => 2, + CompileStage::Exported => 3, + CompileStage::ReadyToPublish => 4, + }; + self.ended.lock().unwrap()[index] = self.started.elapsed().as_secs_f64() * 1000.0; + Ok(()) + } +} + +impl StageTimes { + fn phases(&self, compiled: f64, rendered: f64) -> Value { + let [prepared, executed, fonts, exported, ready] = *self.ended.lock().unwrap(); + json!({ + "prepare_ms": prepared, + "execute_ms": executed - prepared, + "layout_and_fonts_ms": fonts - executed, + "pdf_ms": exported - fonts, + "draft_ms": ready - exported, + "seal_and_publish_ms": compiled - ready, + "svg_ms": rendered - compiled, + }) + } } #[derive(Default)] @@ -97,6 +132,7 @@ fn main() -> Result<(), Box> { ); } (&Method::Post, "/preview") => { + let received = Instant::now(); let mut request = request; let edit = match read_edit(&mut request) { Ok(edit) => edit, @@ -133,6 +169,7 @@ fn main() -> Result<(), Box> { compile, sequence: edit.sequence, visible_revision: edit.visible_revision, + received, }); queue.available.notify_one(); if let Some(old) = replaced { @@ -264,9 +301,10 @@ fn worker(queue: &Queue) { let Work { request, job, - compile, + mut compile, sequence, visible_revision, + received, } = queue .available .wait_while(queue.next.lock().unwrap(), |next| next.is_none()) @@ -274,6 +312,11 @@ fn worker(queue: &Queue) { .take() .expect("the worker was woken with an edit"); let start = Instant::now(); + let timings = Arc::new(StageTimes { + started: start, + ended: Mutex::new([0.0; 5]), + }); + compile.observer = Some(timings.clone()); let document = match job.compile(compile) { Ok(document) => document, Err(CompileError::Cancelled) => { @@ -295,6 +338,7 @@ fn worker(queue: &Queue) { }; let compile_ms = start.elapsed().as_secs_f64() * 1000.0; let preview = document.preview_since(visible_revision); + let ready_ms = start.elapsed().as_secs_f64() * 1000.0; if sequence != queue.current.load(Ordering::Acquire) { reply( request, @@ -311,7 +355,9 @@ fn worker(queue: &Queue) { "sequence": sequence, "update": update, "compile_ms": compile_ms, - "ready_ms": start.elapsed().as_secs_f64() * 1000.0, + "ready_ms": ready_ms, + "admission_and_queue_ms": start.duration_since(received).as_secs_f64() * 1000.0, + "phases": timings.phases(compile_ms, ready_ms), "steps": document.execution.execution.steps, "reused_steps": document.entry_checkpoint_work.reused_steps, "reused_frontier": document.entry_checkpoint_work.reused_frontier, diff --git a/src/native.rs b/src/native.rs index d7ac85e..63f5e6e 100644 --- a/src/native.rs +++ b/src/native.rs @@ -587,12 +587,19 @@ impl NativeCompiler { } struct PreparedJob { - executor: Executor, + executor: Option, format_preparation: Option, source: SourceFile, files: Files, output: PathBuf, } + +#[derive(Clone, Copy, PartialEq, Eq)] +enum KernelPreparation { + Fresh, + Resume, +} + fn prepare( request: &CompileRequest, dump: bool, @@ -608,6 +615,7 @@ fn prepare( evidence, None, EffectMode::Live, + KernelPreparation::Fresh, ) } @@ -619,6 +627,7 @@ fn prepare_checked( evidence: &mut AttemptEvidence, check_inputs: Option>>, effects: EffectMode, + kernel: KernelPreparation, ) -> Result { use texrra_tex_core::resources::ResourceKind; check(cancellation)?; @@ -735,36 +744,61 @@ fn prepare_checked( FormatPreparation::Decoded, ), }; - let executor = image.fork_job_with_file_dates( - state.profile(), - request.input_profile, - request.time, - request.limits, - &mut world, - read, - date, - )?; + let executor = if kernel == KernelPreparation::Resume { + image.validate_job_inputs( + state.profile(), + request.input_profile, + &mut world, + read, + date, + )?; + None + } else { + Some(image.fork_job_with_file_dates( + state.profile(), + request.input_profile, + request.time, + request.limits, + &mut world, + read, + date, + )?) + }; check(cancellation)?; if preparation == FormatPreparation::Decoded { cache.insert(loaded.version, image); } (executor, Some(preparation)) } - None => ( - FormatImage::decode(&loaded.data)?.new_job_with_file_dates( - state.profile(), - request.input_profile, - request.time, - request.limits, - &mut world, - read, - date, - )?, - Some(FormatPreparation::Decoded), - ), + None => { + let image = FormatImage::decode(&loaded.data)?; + let executor = if kernel == KernelPreparation::Resume { + image.validate_job_inputs( + state.profile(), + request.input_profile, + &mut world, + read, + date, + )?; + None + } else { + Some(image.new_job_with_file_dates( + state.profile(), + request.input_profile, + request.time, + request.limits, + &mut world, + read, + date, + )?) + }; + (executor, Some(FormatPreparation::Decoded)) + } } } else { - (Executor::new(state, request.limits), None) + let executor = + (kernel == KernelPreparation::Fresh).then(|| Executor::new(state, request.limits)); + (executor, None) }; check(cancellation)?; Ok((path, source, executor, output, format_preparation)) @@ -786,11 +820,13 @@ fn prepare_checked( evidence.inputs = Some(failure.inputs); CompileError::Host(failure.error) })?; - let executor = if request.target == Target::Shipouts { - executor.with_native_pages() - } else { - executor - }; + let executor = executor.map(|executor| { + if request.target == Target::Shipouts { + executor.with_native_pages() + } else { + executor + } + }); Ok(PreparedJob { executor, format_preparation, @@ -900,6 +936,7 @@ impl CompileJob { } else { EffectMode::Live }, + KernelPreparation::Fresh, ) .map_err(|error| { if cancellation.is_cancelled() { @@ -922,20 +959,25 @@ impl CompileJob { evidence.phase = AttemptPhase::Executing; let cache = &self.compiler.line_break_cache; let before = cache.work(); - let executor = executor.with_line_break_cache(cache.clone()); let (executed, next_checkpoint) = if let Some(current) = active_checkpoint { + debug_assert!(executor.is_none()); let (executed, next) = current.resume(self.job, source, files, &mut entry_checkpoint_work)?; (executed, Some(next)) - } else if let Some(cache) = checkpoints { - let (executed, captured) = - cache.capture(&request, self.job, executor, source, files); - if let Some(snapshot) = &captured { - snapshot.report_capture(&mut entry_checkpoint_work); - } - (executed, captured) } else { - (self.job.run_detailed(executor, source, files), None) + let executor = executor + .expect("fresh native job has an executor") + .with_line_break_cache(cache.clone()); + if let Some(cache) = checkpoints { + let (executed, captured) = + cache.capture(&request, self.job, executor, source, files); + if let Some(snapshot) = &captured { + snapshot.report_capture(&mut entry_checkpoint_work); + } + (executed, captured) + } else { + (self.job.run_detailed(executor, source, files), None) + } }; let execution = match executed { Ok(execution) => { @@ -1186,6 +1228,7 @@ fn dump_format_observed( let result = (|| -> Result { evidence.phase = AttemptPhase::Executing; let executed = executor + .expect("format dump has a fresh executor") .with_cancellation(cancellation.clone()) .run_detailed(source, &mut files); let execution = match executed { diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 0f46089..4bd82c6 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -264,6 +264,7 @@ impl SelectedCheckpoint { ) })), EffectMode::Draft, + KernelPreparation::Resume, )?; for call in &self.set.calls[..checkpoint.replay_count] { check(cancellation)?; @@ -524,9 +525,11 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec let initial = files.preparation().generated_initial.clone().unwrap(); let mut recording = checkpoint_probe::RecordingHost::new(&mut files); let (executed, checkpoint) = - executor.run_capturing_entry(source, &mut recording, PREFIX.len() - 25, |host| { - (host.capture(), host.resource_usage().unwrap().unwrap()) - }); + executor + .unwrap() + .run_capturing_entry(source, &mut recording, PREFIX.len() - 25, |host| { + (host.capture(), host.resource_usage().unwrap().unwrap()) + }); assert!(executed.is_ok()); let (checkpoint, (recorded, usage)) = checkpoint.unwrap(); let (calls, trace) = recorded.unwrap(); @@ -560,6 +563,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec Ok(()) })), effects, + KernelPreparation::Resume, ) }; let rejected = |candidate: &CompileRequest, reason: &str| { diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 60dcf08..efd4f8f 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -255,7 +255,7 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() { files: &mut files, calls: Some(Vec::new()), }; - let (original_execution, captured) = executor.run_capturing_entry( + let (original_execution, captured) = executor.unwrap().run_capturing_entry( source, &mut record, marker_start.saturating_sub(1200),