diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index 9eb2ba5..d4b848d 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -153,6 +153,84 @@ impl EntryCheckpoint { accounts_event_history: completed.accounts_event_history, }) } + /// Carry later checkpoints from the suffix accepted by + /// splice_settled_suffix into this revision. The host must still replay + /// each prefix and verify the resulting I/O boundary before keeping it. + pub fn prepare_suffix_rebase<'a>( + &'a self, + prior: &'a Self, + ) -> impl Fn(&Self) -> Option + 'a { + // Keep the old allocation for an unchanged event. Later snapshots + // can still refer to it even when the live run rebuilt that event. + let mut prefix = prior.executor.events.clone(); + let mut current = self.executor.events.iter(); + for chunk in &mut prefix.prefix { + let changes: Vec<_> = chunk.iter().zip(current.by_ref()).enumerate() + .filter(|(_, (old, new))| !std::ptr::eq(*old, *new) && old != new) + .map(|(index, (_, new))| (index, new.clone())) + .collect(); + if !changes.is_empty() { + let events = Arc::make_mut(chunk); + for (index, event) in changes { + events[index] = event; + } + } + } + move |later| self.rebase_verified_suffix(prior, later, &prefix) + } + + fn rebase_verified_suffix( + &self, + prior: &Self, + later: &Self, + prefix: &ExecutionEvents, + ) -> Option { + let old = &prior.executor; + let next = &later.executor; + let current = &self.executor; + if later.entry != self.entry + || later.active_source != self.entry + || later.frontier < self.frontier + || later.completed_steps() <= self.completed_steps() + || later.incoming_state != self.incoming_state + || next.reads_event_history + || !Arc::ptr_eq(&next.sources[later.entry], &old.sources[prior.entry]) + || old.events.prefix.len() > next.events.prefix.len() + || !old.events.prefix.iter().zip(&next.events.prefix).all(|(a, b)| Arc::ptr_eq(a, b)) + { + return None; + } + + let mut executor = next.clone(); + let mut events = prefix.clone(); + // Checkpoint capture seals the event log. Share the old suffix + // chunks so all carried checkpoints keep the same allocation graph. + events.prefix.extend_from_slice(&next.events.prefix[old.events.prefix.len()..]); + events.prefix_len += next.events.prefix_len - old.events.prefix_len; + executor.events = events; + executor.sources[self.entry] = current.sources[self.entry].clone(); + let InputFrame::Source { source, mouth, .. } = executor.inputs.first_mut()? else { + return None; + }; + if *source != self.entry || !mouth.rebind_after_convergence(self.source_mouth(self.entry)) { + return None; + } + // A later edit can turn on tracing or force a capacity recount. + // Keep a live checkpoint only if the merged history preserves + // the sharing relationships needed by either accounting path. + if !executor.equivalent_accounting_history(next) { + return None; + } + Some(Self { + executor, + entry: later.entry, + active_source: later.active_source, + initial_depth: later.initial_depth, + incoming_state: later.incoming_state, + frontier: later.frontier, + pages_processed: later.pages_processed, + }) + } } fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index 67ffbea..c2e6258 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -350,6 +350,15 @@ impl Mouth { debug_assert!(self.matches_loaded_prefix(&data)); self.data = Arc::new(data); } + pub(super) fn rebind_after_convergence(&mut self, current: &Self) -> bool { + if self.offset < current.offset + || self.data.get(current.offset..) != current.data.get(current.offset..) + { + return false; + } + self.data = current.data.clone(); + true + } pub(super) fn payload_bytes(&self) -> usize { self.data.len() } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 9edf80d..c07fb38 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,33 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-12-01 将已验证的后续检查点带入新修订 + +后缀复用完成时,会话可保留更靠后的执行检查点供下次编辑恢复。 +后续检查点沿用已经核验的旧执行状态和事件块,换入新修订的源码 +与有变化的事件。内容相同的事件保留其原分配,以便仍引用它们的 +后续状态保持一致。材料统计和共享关系、输入扫描器及隔离草稿的 +文件操作均核验通过后才保留。每个源码区间沿用已有的检查点预算。 + +12 页定向 TeX 文档先改第 2 页再改第 9 页,第二次从更后的位置 +恢复,保留前一次编辑。两次结果的执行、PDF、预览和来源与独立 +全量一致。优化构建和三项会话回归通过。 + +原样 NeurIPS 先修改第 7 行注释。无页面变化,复用 5,882,245 个 +后缀执行步。随后修改第 9 页正文,从第 620 行恢复,实际执行 +1,030,250 步,只更新第 9 页。两个修订的完整执行、PDF、SVG、 +绘制列表、来源、依赖、文件流与 aux/out/log 均与各自独立全量一致。 + +原样 NeurIPS 第 3 页正文标点接第 9 页字母的既有序列仍从第 345 +行恢复,实际执行 3,699,397 步。诊断确认后续候选未通过材料历史 +核验。该序列的两个修订和上轮 PDF、SVG 逐字节一致,各自通过 +本轮全量对照。下一步应处理发生变化的出页事件中仍被后续状态 +引用的材料,继续保留现有核验规则。正式时延和内存待统一验收。 + +证据在 target/p4-rebased-prefix/,包括首轮材料核验拒绝记录。 +SHA256SUMS 指纹为 +f41de187a38acb2bac83af19d2fefb25b837048b0af81d2817f687c5f294a878。 + ## 2026-12-01 八页之后的后缀检查点 每份完成执行仍最多保留八个收敛检查点。前四页逐页保留, diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index e5b5d11..5366d60 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -404,6 +404,56 @@ impl<'a> CapturedEntries<'a> { self.changed = true; } + fn replay_settled_suffix( + &mut self, + page: usize, + current: &EntryCheckpoint, + prior: &SettledCheckpoint, + completed: &CompletedExecution, + host: &mut RecordingHost, + cancellation: &Cancellation, + ) -> Result<(), String> { + let project = self.request.project.as_deref().expect("settled replay uses a project"); + let bytes = project.file(&completed.guard.entry).expect("settled entry").data.len(); + let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1); + let mut later = [const { None }; SOURCE_INTERVALS]; + let rebase = current.prepare_suffix_rebase(&prior.entry); + // Keep the deepest compatible settled continuation per source interval. + for (&page, anchor) in completed.settled.range((std::ops::Bound::Excluded(page), std::ops::Bound::Unbounded)).rev() { + let interval = (anchor.entry.frontier() - 1) / stride; + if later[interval].is_some() { + continue; + } + check(cancellation).map_err(|error| error.to_string())?; + if let Some(entry) = rebase(&anchor.entry) { + later[interval] = Some((page, anchor, entry)); + } + } + + let mut replayed = prior.call_count; + for (interval, (page, anchor, entry)) in later.into_iter().enumerate() + .filter_map(|(interval, anchor)| anchor.map(|anchor| (interval, anchor))) + { + let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { + continue; + }; + host.replay_suffix(calls, cancellation)?; + replayed = anchor.call_count; + if anchor.host == host.files().replay_boundary() { + let regular = CaptureSlots { + interval, + early: false, + page: true, + edit: false, + next_page: page.saturating_add(1), + }; + self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); + } + } + host.replay_suffix(&completed.calls[replayed..], cancellation)?; + completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) + } + fn finish( self, recording: RecordingHost, @@ -928,10 +978,8 @@ impl SelectedCheckpoint { return CheckpointDecision::Continue; }; let calls = &completed.calls[old.call_count..]; - let replayed = host.replay_suffix(calls, &cancellation) - .and_then(|()| completed.guard.verify_replayed_inputs( - host.files(), request.project.as_deref().expect("settled replay uses a project"), - ).map_err(|error| error.to_string())); + let replayed = + 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)); diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index b156ebe..ee0b327 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1703,42 +1703,60 @@ fn consecutive_edits_reuse_later_settled_suffixes() { } #[test] -fn settled_suffix_reuses_after_the_first_eight_pages() { +fn settled_suffix_carries_a_verified_prefix_into_later_edits() { let cwd = directory("long-settled-suffix"); let entry = cwd.join("main.tex"); - let cover = "\\shipout\\hbox{Cover AB}\\relax\n".repeat(8); + let middle = "\\shipout\\hbox{Middle}\\relax\n".repeat(6); let tail = "\\shipout\\hbox{Unchanged}\\relax\n".repeat(3); - let body = |letter| { - format!("\n\\tracingstats=1\n{cover}\\setbox3=\\hbox{{{letter}}}\n\\shipout\\box3\n\\relax\n{tail}\\end\n") + let body = |second, ninth| { + format!(r" +\tracingstats=1 +\shipout\hbox{{Cover ABXY}} +\setbox3=\hbox{{{second}}} +\shipout\box3 +\relax +{middle}\setbox3=\hbox{{{ninth}}} +\shipout\box3 +\relax +{tail}\end +") }; - let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body('A'))).unwrap(); + let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body('A', 'X'))).unwrap(); let mut request = request(&cwd).observe_generated_initial(); request.world = project.configuration(); let session = NativeCompiler::default().with_automatic_entry_checkpoints(); - let previous = session + let mut previous = session .compile(request.clone().with_project(project.clone())) .unwrap(); - let source = format!("{HEADER}{}", body('B')); - let project = project - .with_file_edits(2, [(entry, Arc::from(source.into_bytes()))].into()) - .unwrap(); - let input = request.with_project(project); - let updated = session.compile(input.clone()).unwrap(); - let work = &updated.entry_checkpoint_work; - assert!(work.reused_suffix_steps > 0, "{work:?}"); + for (revision, second, ninth, expected_page) in [(2, 'B', 'X', 1), (3, 'B', 'Y', 8)] { + let source = format!("{HEADER}{}", body(second, ninth)); + let start_of_middle = source.find(&middle).unwrap(); + project = project + .with_file_edits(revision, [(entry.clone(), Arc::from(source.into_bytes()))].into()) + .unwrap(); + let input = request.clone().with_project(project.clone()); + let updated = session.compile(input.clone()).unwrap(); + let work = &updated.entry_checkpoint_work; + assert!(work.reused_suffix_steps > 0, "{work:?}"); + if revision == 3 { + assert!(work.reused_frontier.unwrap() > start_of_middle, "{work:?}"); + } - let preview = updated.preview_since(Some(previous.revision())).unwrap(); - assert_eq!(preview.page_count, 12); - let changed: Vec<_> = preview.pages.iter().map(|page| page.index).collect(); - assert_eq!(changed, [8]); + let preview = updated.preview_since(Some(previous.revision())).unwrap(); + assert_eq!(preview.page_count, 12); + let changed: Vec<_> = preview.pages.iter().map(|page| page.index).collect(); + assert_eq!(changed, [expected_page]); - let full = NativeCompiler::default().compile(input).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.source_map.pages, full.source_map.pages); - assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + let full = NativeCompiler::default().compile(input).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.source_map.pages, full.source_map.pages); + assert_eq!(updated.source_map.sources, full.source_map.sources); + assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + previous = updated; + } fs::remove_dir_all(cwd).unwrap(); }