diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 0349709..73e190a 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1062,6 +1062,37 @@ CVPR 的复用步数独立于 A4 100 ms 可见延迟门禁。 独立全量回执 `rebuilt-full-equivalence/receipt.json` 的 SHA-256 为 `a7f78749b86cb9d5b8aa2c9c7fb80aa1eda1a6d2e54718ad119579a00b1a1891`。 +### 编辑行检查点的快照预算 + +编辑行需要单独快照时,将随后一个普通字节区间的快照移到编辑行前。 +保留此前较早的回退位置、真实出页捕获和原快照数量上限。定向用例 +覆盖编辑行捕获、随后出页及独立全量等价,已通过。 + +以已测编辑行候选的同一优化二进制为基线,一轮原样 A4 配对每版各 +30次主文件和30次子文件编辑。60对的总执行步数、实际页差量、PDF、 +SVG 和来源映射一致。最终 aux 与使用最后编辑缓冲区的独立零复用 +全量一致。主文件全部保持原复用步数,子文件仅一版多复用13017步。 + +| 编辑范围 | 上一候选可见 p50 / p95 (ms) | 快照预算候选可见 p50 / p95 (ms) | 执行配对中位数变化 (ms) | +| --- | ---: | ---: | ---: | +| 主文件 | 304.7 / 569.9 | 305.2 / 399.4 | -9.09 | +| 子文件 | 310.5 / 445.6 | 284.2 / 400.2 | -14.65 | + +峰值 RSS 为615724 → 601592 KiB。采样期间 WSL I/O pressure some +avg10 从7.08%升至42.39%。此轮对照表明快照预算的执行时间和内存 +收益,主文件可见 p50 基本不变,100 ms 可见 p95 门槛仍待达到。 +同一基线二进制在上一轮多执行9步前缀,恢复位置、恢复后步数和页面 +保持一致。两个轮次的延迟独立报告。 + +按已测源码指纹合入主线。证据在 +`target/p4-edit-line-snapshot-budget`。快照预算补丁、浏览器回执、 +配对统计和独立全量的 SHA-256 分别为 + +- 完整补丁 `2cc91c7b8d62b1b9c7479d0b42041135aee480f7494f3035d84f8d55671d590a` +- 浏览器回执 `31000162b1c84ef79db4044d36118355f3c7785d4739fe3806bc7f200aab8bef` +- 配对统计 `cad6d20b795dfe30bd504a7351c4bc49a1d9deb0694e7fca8312137e8a416fcf` +- 独立零复用全量 `0c35c2c91876fd43f216b4d1834ced44127723cf89fcd9e14a9cda9a78cb49a2` + ### 文本重音与 APS 双栏样稿 原样 APS 在第一轮和真实 BibTeX 之后,第二轮从 `apssamp.bbl` @@ -1072,9 +1103,11 @@ CVPR 的复用步数独立于 A4 100 ms 可见延迟门禁。 15个实际 DVI 字形。最大坐标差为0 sp。回执 `target/p3-text-accent/focused-paint-receipt.json`。 -新写入的格式使用 schema28,已保存的 schema27 由同一解码器 -保留兼容。正在用原样 pdflatex.ini 生成新镜像,独立验证旧镜像 -及 APS 的多轮文献和 PDF。阶段源码仍在隔离工作树。 +新写入的格式使用 schema28。已用优化候选和原样 A0 载入既有 +schema27,生成单页 PDF,逐词坐标和 aux 与已验证的旧结果一致。 +验证首轮误用未存档的源副本,修正后从原资源记录核对源文件指纹。 +正在用原样 pdflatex.ini 生成新镜像,继续 APS 的实际多轮文献和 PDF。 +阶段源码仍在隔离工作树。 ### TeX 输入的默认扩展名候选 diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 4117f44..9745b39 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -44,6 +44,7 @@ pub(super) struct CheckpointSet { entries: Vec>, calls: Vec, refresh_on_resume: bool, + edit_frontier: Option, } pub(super) struct SelectedCheckpoint { @@ -61,6 +62,7 @@ struct CaptureSchedule { seen: [bool; SOURCE_INTERVALS], next_page: usize, fixed_frontier: Option, + pending_edit_frontier: Option, } #[derive(Clone, Copy)] @@ -68,20 +70,38 @@ struct CaptureSlots { interval: usize, early: bool, page: bool, + edit: bool, next_page: usize, } impl CaptureSchedule { - fn new(bytes: usize, fixed_frontier: Option) -> Self { + fn new(bytes: usize, fixed_frontier: Option, edit_frontier: Option) -> Self { Self { bytes, stride: bytes.div_ceil(SOURCE_INTERVALS).max(1), seen: [false; SOURCE_INTERVALS], next_page: 1, fixed_frontier, + pending_edit_frontier: edit_frontier, } } + fn take_edit_frontier(&mut self, frontier: usize, ordinary_capture: bool) -> bool { + let edit = self + .pending_edit_frontier + .take_if(|pending| *pending == frontier) + .is_some(); + if edit && !ordinary_capture { + // Move a later byte-interval capture to the active editing line. + // Keep the earlier prefix and all shipout capture opportunities. + let next_interval = (frontier - 1) / self.stride + 1; + if let Some(seen) = self.seen.get_mut(next_interval) { + *seen = true; + } + } + edit + } + fn select(&mut self, frontier: usize, pages: usize) -> Option { if let Some(minimum) = self.fixed_frontier { if self.seen[0] || frontier < minimum { @@ -92,6 +112,7 @@ impl CaptureSchedule { interval: 0, early: true, page: false, + edit: false, next_page: self.next_page, }); } @@ -104,10 +125,12 @@ impl CaptureSchedule { if page { self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two()); } - (early || page).then_some(CaptureSlots { + let edit = self.take_edit_frontier(frontier, early || page); + (early || page || edit).then_some(CaptureSlots { interval, early, page, + edit, next_page: self.next_page, }) } @@ -123,6 +146,7 @@ impl CaptureSchedule { Some(CaptureSlots { interval, early, + edit: self.take_edit_frontier(frontier, early || checkpoint.slots.page), ..checkpoint.slots }) } @@ -134,6 +158,7 @@ struct CapturedEntries<'a> { initial: Option, early: [Option>; SOURCE_INTERVALS], shipped: [Option>; SOURCE_INTERVALS], + edit: Option>, changed: bool, } @@ -149,6 +174,7 @@ impl<'a> CapturedEntries<'a> { initial: files.preparation().generated_initial.clone(), early: Default::default(), shipped: Default::default(), + edit: None, changed: false, } } @@ -157,6 +183,9 @@ impl<'a> CapturedEntries<'a> { if slots.early { self.early[slots.interval] = Some(checkpoint.clone()); } + if slots.edit { + self.edit = Some(checkpoint.clone()); + } if slots.page { self.shipped[slots.interval] = Some(checkpoint); } @@ -199,14 +228,34 @@ impl<'a> CapturedEntries<'a> { if !self.changed { return None; } + let edit_frontier = self + .edit + .as_ref() + .map(|checkpoint| checkpoint.entry.frontier()); let mut entries: Vec<_> = self .early .into_iter() .chain(self.shipped) .flatten() + .chain(self.edit) .collect(); entries.sort_by_key(|candidate| candidate.entry.completed_steps()); entries.dedup_by(|a, b| Arc::ptr_eq(a, b)); + if entries.len() > 2 * SOURCE_INTERVALS { + let edit = edit_frontier.expect("an edit checkpoint can fill the remaining slot"); + // Preserve the earliest continuation and the page checkpoints. + // Displace the ordinary continuation closest to the edited line. + let (index, _) = entries + .iter() + .enumerate() + .skip(1) + .filter(|(_, checkpoint)| { + !checkpoint.slots.page && checkpoint.entry.frontier() != edit + }) + .min_by_key(|(_, checkpoint)| checkpoint.entry.frontier().abs_diff(edit)) + .expect("the full schedule has ordinary continuations"); + entries.remove(index); + } let replay_count = entries.iter().map(|entry| entry.replay_count).max()?; let mut calls = recording.into_calls()?; calls.truncate(replay_count); @@ -214,6 +263,7 @@ impl<'a> CapturedEntries<'a> { entries, calls, refresh_on_resume, + edit_frontier, })) } } @@ -291,7 +341,7 @@ impl CheckpointCache { Result, RevisionFailure>, Option>, ) { - let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier); + let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None); let mut captures = CapturedEntries::new(request, files); let mut recording = RecordingHost::new(files); let result = job.run_capturing_entries( @@ -418,6 +468,7 @@ impl CheckpointSet { entries, calls: self.calls[..replay_count].to_vec(), refresh_on_resume: self.refresh_on_resume, + edit_frontier: self.edit_frontier, })) } @@ -485,7 +536,13 @@ impl SelectedCheckpoint { return Ok((result, self.set)); } - let mut schedule = CaptureSchedule::new(source.data.len(), None); + let previous = checkpoint + .guard + .project + .file(&checkpoint.guard.entry) + .expect("a checkpoint records its source"); + let edit = changed_line_start(&previous.data, &source.data).or(self.set.edit_frontier); + let mut schedule = CaptureSchedule::new(source.data.len(), None, edit); let mut captures = CapturedEntries::new(request, files); // Share only calls and continuations from the prefix just replayed. for previous in &self.set.entries[..=self.index] { @@ -528,6 +585,28 @@ impl SelectedCheckpoint { } } +fn changed_line_start(previous: &[u8], current: &[u8]) -> Option { + if previous == current { + return None; + } + let common = previous + .iter() + .zip(current) + .take_while(|(old, new)| old == new) + .count(); + let mut prefix = ¤t[..common]; + // A CR followed by LF is one physical line ending. + if prefix.ends_with(b"\r") && current.get(common) == Some(&b'\n') { + prefix = &prefix[..prefix.len() - 1]; + } + Some( + prefix + .iter() + .rposition(|byte| matches!(*byte, b'\r' | b'\n')) + .map_or(0, |offset| offset + 1), + ) +} + struct PrefixInputGuard { original: AttemptRequest, project: Arc, @@ -1461,6 +1540,122 @@ fn immutable_file_creation_and_removal_replay_real_lookup_results() { assert_eq!(pdfs.values().collect::>().len(), 4); } +#[test] +fn automatic_checkpoints_refresh_the_previous_edit_line_after_a_child_edit() { + let mut schedule = CaptureSchedule::new(400, None, Some(290)); + assert!(schedule.select(215, 0).unwrap().early); + let edit = schedule.select(290, 0).unwrap(); + assert!(edit.edit && !edit.early); + assert!(schedule.select(345, 0).is_none()); + assert!(schedule.select(345, 1).unwrap().page); + + let cwd = std::env::temp_dir().join(format!("texrra-edit-line-{}", std::process::id())); + fs::create_dir(&cwd).unwrap(); + let cwd = cwd.canonicalize().unwrap(); + let entry = cwd.join("main.tex"); + let child = cwd.join("child.tex"); + let source_prefix = format!( + "\\catcode123=1 \\catcode125=2\n{}\\input child.tex\n{}", + "\\advance\\count0 by 1\\relax\n".repeat(40), + "\\advance\\count2 by 1\\relax\n".repeat(18), + ); + let edited_line_start = source_prefix.len(); + let original = format!( + "{source_prefix}\\shipout\\hbox{{\\vrule width1pt height\\heightfromchild pt}}\n{}\\end\n", + "\\advance\\count1 by 1\\relax\n".repeat(5), + ); + let mut world = WorldConfig::new(&cwd); + world.input_policy = InputPolicy::Tex; + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: BTreeSet::from([cwd.clone()]), + files: BTreeMap::from([ + (entry.clone(), Arc::from(original.as_bytes())), + ( + child.clone(), + Arc::from(b"\\def\\heightfromchild{1}\n".as_slice()), + ), + ]), + directories: BTreeSet::new(), + aliases: BTreeMap::new(), + generated_roots: BTreeSet::from([cwd.clone()]), + generated: BTreeSet::new(), + }) + .unwrap(); + let mut request = CompileRequest::new( + world, + "main.tex", + "main.pdf", + JobTime::new(2026, 11, 20, 540) + .unwrap() + .with_pdf_clock(0, 0) + .unwrap(), + ) + .with_project(project.clone()) + .observe_generated_initial(); + request.entry = Entry::Initex; + NativeCompiler::default().compile(request.clone()).unwrap(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + session.compile(request.clone()).unwrap(); + + let entry_edit = project + .with_file_edits( + 2, + BTreeMap::from([( + entry.clone(), + Arc::from(original.replace("width1pt", "width2pt").into_bytes()), + )]), + ) + .unwrap(); + session + .compile(request.clone().with_project(entry_edit.clone())) + .unwrap(); + let child_edit = entry_edit + .with_file_edits( + 3, + BTreeMap::from([(child, Arc::from(b"\\def\\heightfromchild{3}\n".as_slice()))]), + ) + .unwrap(); + let child_result = session + .compile(request.clone().with_project(child_edit.clone())) + .unwrap(); + let child_work = &child_result.entry_checkpoint_work; + assert!( + child_work.reused_frontier.unwrap() < edited_line_start, + "{child_work:?}" + ); + + let revision = child_edit + .with_file_edits( + 4, + BTreeMap::from([( + entry, + Arc::from(original.replace("width1pt", "width4pt").into_bytes()), + )]), + ) + .unwrap(); + let request = request.with_project(revision); + let updated = session.compile(request.clone()).unwrap(); + let full = NativeCompiler::default().compile(request).unwrap(); + let work = &updated.entry_checkpoint_work; + assert_eq!(work.reused_frontier, Some(edited_line_start), "{work:?}"); + assert!(work.reused_steps > child_work.reused_steps, "{work:?}"); + assert!( + work.retained_checkpoints <= 2 * SOURCE_INTERVALS, + "{work:?}" + ); + assert!(updated.pages[0].items.iter().any(|item| matches!( + item, + texrra_tex_core::render::DisplayItem::Rule { width, height, .. } + if (*width, *height) == (4 * 65_536, 3 * 65_536) + ))); + assert_eq!(updated.pdf, full.pdf); + assert_eq!(updated.source_map.sources, full.source_map.sources); + assert_eq!(updated.source_map.pages, full.source_map.pages); + assert!(updated.execution.execution == full.execution.execution); +} + #[test] fn generated_input_change_uses_a_checkpoint_before_the_read() { let cwd = std::env::temp_dir().join(format!("texrra-generated-prefix-{}", std::process::id()));