From f387b1db61ab2e5ea963e9ddcb04f7b31f671ec8 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sun, 29 Nov 2026 07:19:47 +0800 Subject: [PATCH] Replay verified completed native jobs on exact document undo --- .../texrra-tex-core/src/execution/session.rs | 10 ++ docs/P2_M1_PROGRESS.md | 30 ++++ src/native_checkpoint_guard.rs | 152 ++++++++++++++---- tests/native_pipeline.rs | 88 ++++++++++ 4 files changed, 250 insertions(+), 30 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/session.rs b/crates/texrra-tex-core/src/execution/session.rs index 29f6012..0be2bd9 100644 --- a/crates/texrra-tex-core/src/execution/session.rs +++ b/crates/texrra-tex-core/src/execution/session.rs @@ -293,6 +293,16 @@ impl RevisionJob { Some(self.finish_execution(executed, files, previous.as_deref())) } + /// Publish a completed result after the caller verifies the same inputs + /// and replays every host call into the current revision's draft. + pub fn reuse_completed_after_host_replay( + self, + completed: &RevisionExecution, + files: &impl SourceProvider, + ) -> Result, RevisionFailure> { + self.finish_execution(Ok(completed.execution.clone()), files, Some(completed)) + } + fn finish_execution( self, executed: Result, diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index d6fa0d9..b4f9913 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,36 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-29 原文恢复复用与出页边界实测 + +自动检查点可保留两份最近的成功执行结果。恢复相同入口字节时, +校验作业设置、实际不可变依赖、已读流和已观察的生成初态, +并在当前作业的隔离草稿中重放到 TeX 收尾的全部已记录宿主调用。 +只有完整捕获且当前调用结果符合原记录才交付已完成的内核结果。 +资源轨迹、导出、页差量和发布仍由当前修订生成。重放失败后 +释放草稿并按已有路径重试,取消检查继续覆盖重放和发布。 + +同版原样 NeurIPS 2025 会话执行标点编辑、失败及恢复原文。恢复 +重放 601 次宿主调用,实际内核执行由此前 5,181,446 步降至 0。 +仍有 19,570,891 个逻辑步骤。恢复阶段只转换第 3 页,零断行 +求解,端到端库调用单轮为 542 ms。编辑和恢复各自与独立全量 +的 PDF、SVG、页列表、来源、读取依赖、辅助文件和最终状态 +一致。故障保留上次发布。四项定向测试通过,覆盖修改已读 +子文件及生成输入后拒绝完成态复用、出页后读入、子文件检查点 +和真实生成初态。正式浏览器可见时延与内存继续按原门禁验收。 + +另用隔离诊断版对照出页状态。第 3 页出页后,已比较的核心字段 +仍有 State 差异。第 4 页出页后,扫描游标、未读输入、TeX State、 +活跃页、计数、依赖和逻辑流状态首次在所查边界一致。位置是入口 +第 430 行、15,501,850 步,随后还剩 4,069,041 步。此时输出 +例程仍活跃,部分驱动状态尚未比较,原始宿主流日志也有差异。 +该位置是后续核验入口,当前普通编辑保留后缀执行。下一步捕获 +输出例程返回后的边界,核对驱动状态、实际文件内容和剩余调用, +再接通不同源码版本之间的后缀复用。 + +证据在 target/p4-shipout-convergence/,SHA256SUMS 指纹为 +27ee848738e4fa827ba616e0371dfa30c36e8da8bec17313eef15f9949e31d49。 + ## 2026-11-29 合并命令含义查询与依赖记录 原生命令查询在执行器中一次索引即返回已解析的含义,并记下读取的 diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 9fb0d42..6e7322c 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -25,6 +25,8 @@ pub struct EntryCheckpointWork { /// Child input at the resume frontier, when the entry scanner was suspended. pub reused_source: Option, pub reused_steps: usize, + /// The complete kernel result matched a previously successful input. + pub reused_completion: bool, pub replayed_calls: usize, pub rejection: Option, } @@ -37,6 +39,7 @@ pub(super) struct CheckpointCache { pub(super) struct PublishedCheckpoints { current: Arc, previous_body: Option>, + previous_completion: Option>, } struct CachedCheckpoint { @@ -47,16 +50,28 @@ struct CachedCheckpoint { } +struct CompletedExecution { + result: Arc, + guard: PrefixInputGuard, + calls: Arc<[Call]>, +} + pub(super) struct CheckpointSet { entries: Vec>, - calls: Vec, + calls: Arc<[Call]>, + completion: Option>, refresh_on_resume: bool, edit_frontier: Option, } pub(super) struct SelectedCheckpoint { set: Arc, - index: usize, + candidate: ExecutionCandidate, +} + +enum ExecutionCandidate { + Boundary(usize), + Completed(Arc), } const SOURCE_INTERVALS: usize = 4; @@ -298,6 +313,7 @@ impl<'a> CapturedEntries<'a> { self, recording: RecordingHost, refresh_on_resume: bool, + result: &Arc, ) -> Option> { if !self.changed { return None; @@ -333,11 +349,33 @@ impl<'a> CapturedEntries<'a> { entries.extend(self.nested.into_iter().flatten().flatten()); entries.sort_by_key(|candidate| candidate.entry.completed_steps()); let replay_count = entries.iter().map(|entry| entry.replay_count).max()?; + // Only automatic sessions retain completed jobs, and only when the + // recorder reached actual closeout without filling its call budget. + let completion = refresh_on_resume.then(|| { + let (trace, _) = recording.prefix()?; + let guard = PrefixInputGuard::capture( + self.request, + self.entry_path.as_deref()?, + trace, + recording.generated_outputs(), + self.initial?, + ).ok()?; + Some(guard) + }).flatten(); let mut calls = recording.into_calls()?; - calls.truncate(replay_count); + if completion.is_none() { + calls.truncate(replay_count); + } + let calls = Arc::<[Call]>::from(calls); + let completion = completion.map(|guard| Arc::new(CompletedExecution { + result: result.clone(), + guard, + calls: calls.clone(), + })); Some(Arc::new(CheckpointSet { entries, calls, + completion, refresh_on_resume, edit_frontier, })) @@ -376,6 +414,9 @@ impl CheckpointCache { *published = None; return; }; + if published.as_ref().is_some_and(|set| Arc::ptr_eq(&set.current, &next)) { + return; + } if published .as_ref() .and_then(|set| set.previous_body.as_ref()) @@ -400,9 +441,13 @@ impl CheckpointCache { published.previous_body.clone() } }); + let previous_completion = published.as_ref().and_then(|published| { + published.current.completion.clone().or_else(|| published.previous_completion.clone()) + }); *published = Some(Arc::new(PublishedCheckpoints { current: next, previous_body, + previous_completion, })); } @@ -437,11 +482,9 @@ impl CheckpointCache { }, |slots, entry, host| captures.capture(slots, entry, host), ); - let next = if result.is_ok() { - captures.finish(recording, self.minimum_frontier.is_none()) - } else { - None - }; + let next = result.as_ref().ok().and_then(|result| { + captures.finish(recording, self.minimum_frontier.is_none(), result) + }); (result, next) } } @@ -462,6 +505,12 @@ impl PublishedCheckpoints { .current .candidates() .chain(self.previous_body.iter().flat_map(|body| body.candidates())) + .chain(self.current.completion.iter().chain(&self.previous_completion).map(|result| { + SelectedCheckpoint { + set: self.current.clone(), + candidate: ExecutionCandidate::Completed(result.clone()), + } + })) .collect(); candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.completed_steps())); let mut candidates = VecDeque::from(candidates); @@ -471,10 +520,9 @@ impl PublishedCheckpoints { check(cancellation)?; let first = std::iter::from_fn(|| candidates.pop_front()) .find(|candidate| { - let checkpoint = &candidate.set.entries[candidate.index]; - match checkpoint + match candidate .accept_entry(project) - .and_then(|()| checkpoint.guard.verify_project(request)) + .and_then(|()| candidate.guard().verify_project(request)) { Ok(_) => true, Err(error) => { @@ -505,10 +553,9 @@ impl PublishedCheckpoints { let mut rejection = None; let remaining = std::iter::from_fn(|| candidates.pop_front()); for candidate in std::iter::once(first).chain(remaining) { - let checkpoint = &candidate.set.entries[candidate.index]; - match checkpoint + match candidate .accept_entry(project) - .and_then(|()| checkpoint.guard.verify(request, world, preparation)) + .and_then(|()| candidate.guard().verify(request, world, preparation)) { Ok(()) => { selected = Some(candidate); @@ -525,23 +572,23 @@ impl PublishedCheckpoints { KernelPreparation::Resume, )?; let selected = selected.expect("resume preparation chose a verified checkpoint"); - let checkpoint = &selected.set.entries[selected.index]; - let partial_source = checkpoint.guard.nested_source.as_deref() + let guard = selected.guard(); + let partial_source = guard.nested_source.as_deref() .and_then(|path| project.file(path)).map(|file| &file.version); - for (index, call) in selected.set.calls[..checkpoint.replay_count].iter().enumerate() { + for (index, call) in selected.calls().iter().enumerate() { check(cancellation)?; if let Err(error) = call.replay(&mut prepared.files, partial_source) { replay_rejection.get_or_insert(CompileError::Host(error)); // Other checkpoints sharing this call cannot use the // invalidated prefix either. Drop the draft on retry. candidates.retain(|candidate| { - !Arc::ptr_eq(&candidate.set, &selected.set) - || candidate.set.entries[candidate.index].replay_count <= index + let calls = candidate.calls(); + calls.len() <= index || !std::ptr::eq(calls.as_ptr(), selected.calls().as_ptr()) }); continue 'retry; } } - if let Err(error) = checkpoint.guard.verify_replayed_inputs(&prepared.files, project) { + if let Err(error) = guard.verify_replayed_inputs(&prepared.files, project) { replay_rejection.get_or_insert(error); continue; } @@ -567,7 +614,8 @@ impl CheckpointSet { let replay_count = entries.last()?.replay_count; Some(Arc::new(Self { entries, - calls: self.calls[..replay_count].to_vec(), + calls: Arc::from(&self.calls[..replay_count]), + completion: None, refresh_on_resume: self.refresh_on_resume, edit_frontier: self.edit_frontier, })) @@ -585,7 +633,7 @@ impl CheckpointSet { .rev() .map(|index| SelectedCheckpoint { set: Arc::clone(self), - index, + candidate: ExecutionCandidate::Boundary(index), }) } } @@ -613,7 +661,42 @@ impl CachedCheckpoint { impl SelectedCheckpoint { fn completed_steps(&self) -> usize { - self.set.entries[self.index].entry.completed_steps() + match &self.candidate { + ExecutionCandidate::Boundary(index) => self.set.entries[*index].entry.completed_steps(), + ExecutionCandidate::Completed(job) => job.result.execution.steps, + } + } + + fn guard(&self) -> &PrefixInputGuard { + match &self.candidate { + ExecutionCandidate::Boundary(index) => &self.set.entries[*index].guard, + ExecutionCandidate::Completed(job) => &job.guard, + } + } + + fn accept_entry(&self, project: &ProjectSnapshot) -> Result<(), String> { + match &self.candidate { + ExecutionCandidate::Boundary(index) => self.set.entries[*index].accept_entry(project), + ExecutionCandidate::Completed(job) => { + let path = &job.guard.entry; + if job.guard.project.file(path).zip(project.file(path)) + .is_some_and(|(old, new)| old.version == new.version && old.data == new.data) + { + Ok(()) + } else { + Err("completed checkpoint entry changed".into()) + } + } + } + } + + fn calls(&self) -> &[Call] { + match &self.candidate { + ExecutionCandidate::Boundary(index) => { + &self.set.calls[..self.set.entries[*index].replay_count] + } + ExecutionCandidate::Completed(job) => &job.calls, + } } pub(super) fn resume( @@ -631,7 +714,18 @@ impl SelectedCheckpoint { ), CompileError, > { - let checkpoint = &self.set.entries[self.index]; + let index = match &self.candidate { + ExecutionCandidate::Boundary(index) => *index, + ExecutionCandidate::Completed(completed) => { + work.retained_checkpoints = self.set.entries.len(); + work.reused_frontier = Some(source.data.len()); + 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)); + } + }; + let checkpoint = &self.set.entries[index]; let frontier = checkpoint.entry.frontier(); work.retained_checkpoints = self.set.entries.len(); work.reused_frontier = Some(frontier); @@ -663,7 +757,7 @@ impl SelectedCheckpoint { }); let mut captures = CapturedEntries::new(request, files); // Earlier retained positions refer only to calls already replayed. - for previous in &self.set.entries[..=self.index] { + for previous in &self.set.entries[..=index] { if previous.replay_count > checkpoint.replay_count { continue; } @@ -709,11 +803,9 @@ impl SelectedCheckpoint { |slots, entry, host| captures.capture(slots, entry, host), ) .ok_or_else(changed_prefix)?; - let next = if result.is_ok() { - captures.finish(recording, true) - } else { - None - }; + let next = result.as_ref().ok().and_then(|result| { + captures.finish(recording, true, result) + }); if let Some(next) = next { next.report_capture(work); Ok((result, next)) diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 5c53696..a21fba8 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1572,6 +1572,94 @@ fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn completed_checkpoint_replays_undo_and_rechecks_immutable_and_generated_inputs() { + let cwd = directory("completed-undo"); + let entry = cwd.join("main.tex"); + let chapter = cwd.join("chapter.tex"); + let seed = cwd.join("seed.aux"); + let aux = cwd.join("job.aux"); + fs::write(&seed, b"Seed A\n").unwrap(); + fs::write(&aux, b"slot\n").unwrap(); + + let body = |word: &str| format!(r" +\shipout\hbox{{Cover}} +\input chapter.tex +\openin2=seed.aux \read2 to\seed \closein2 +\immediate\openout1=job.aux +\immediate\write1{{slot}} +\immediate\closeout1 +\shipout\hbox{{{word} \chapter\seed}} +\end +"); + let mut definition = atomic_definition(&cwd, 1, &body("Original")); + definition.files.insert(chapter.clone(), Arc::from(br"\def\chapter{Chapter A }".as_slice())); + definition.generated.extend([aux.clone(), seed.clone()]); + let original = definition.files[&entry].clone(); + let mut project = ProjectSnapshot::new(definition).unwrap(); + let mut job = request(&cwd).observe_generated_initial(); + job.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let initial = session.compile(job.clone().with_project(project.clone())).unwrap(); + assert_eq!(initial.pages.len(), 2); + assert!(!initial.entry_checkpoint_work.reused_completion); + + let edited = Arc::from(format!("{HEADER}{}", body("Modified")).into_bytes()); + project = project.with_file_edits(2, [(entry.clone(), edited)].into()).unwrap(); + let changed = session.compile(job.clone().with_project(project.clone())).unwrap(); + assert!(!changed.entry_checkpoint_work.reused_completion); + assert_ne!(changed.pdf, initial.pdf); + + let failing = project.with_file_edits(3, [ + (entry.clone(), Arc::from(format!("{HEADER}{}", body(r"\UndefinedUndo")).into_bytes())), + ].into()).unwrap(); + assert!(session.compile(job.clone().with_project(failing)).is_err()); + assert_eq!(session.latest().unwrap().revision(), changed.revision()); + assert_eq!(fs::read(cwd.join("job.pdf")).unwrap(), changed.pdf.as_deref().unwrap()); + + for (revision, files, seed_bytes, expect_complete) in [ + (4, [(entry.clone(), original)].into(), b"Seed A\n".as_slice(), true), + (5, [(chapter.clone(), Arc::from(br"\def\chapter{Chapter B }".as_slice()))].into(), + b"Seed A\n".as_slice(), false), + (6, BTreeMap::new(), b"Seed B\n".as_slice(), false), + ] { + project = project.with_file_edits(revision, files).unwrap(); + fs::write(&seed, seed_bytes).unwrap(); + let current = job.clone().with_project(project.clone()); + let live = session.compile(current.clone()).unwrap(); + let work = &live.entry_checkpoint_work; + assert_eq!(work.reused_completion, expect_complete, "{work:?}"); + if expect_complete { + assert_eq!(work.reused_steps, live.execution.execution.steps); + assert_eq!(live.pdf, initial.pdf); + assert_eq!(live.line_break_work.solved_passes, 0); + assert!(work.replayed_calls > 0); + } else { + assert_ne!(live.pdf, initial.pdf); + assert!(work.reused_steps < live.execution.execution.steps); + } + let published_log = fs::read(cwd.join("job.log")).unwrap(); + let published_aux = fs::read(&aux).unwrap(); + assert_eq!(published_aux, b"slot\n"); + assert!(live.resources.stream_io.events().iter().any(|event| matches!( + &event.effect, StreamEffect::Write { accepted: 5, error: None, .. } + ))); + let full = NativeCompiler::default().compile(current).unwrap(); + assert_eq!(live.execution.execution, full.execution.execution); + assert_eq!(live.resources.trace.lookups, full.resources.trace.lookups); + assert_eq!(live.resources.trace.reads, full.resources.trace.reads); + assert_eq!(live.resources.trace.stream_reads, full.resources.trace.stream_reads); + assert_eq!(live.pdf, full.pdf); + assert_eq!(live.pages, full.pages); + assert_eq!(live.source_map.sources, full.source_map.sources); + assert_eq!(live.source_map.pages, full.source_map.pages); + assert_eq!(live.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + assert_eq!(published_log, fs::read(cwd.join("job.log")).unwrap()); + assert_eq!(published_aux, fs::read(&aux).unwrap()); + } + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn checkpoint_reuses_shipouts_when_late_inputs_share_the_final_entry_line() { let p = directory("shared-final-line");