From 287d4a7cf0f2fc4ad44fc88ee411ddfc32e30753 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Fri, 20 Nov 2026 08:26:44 +0800 Subject: [PATCH] Validate live checkpoint reuse across atomic project file changes --- .../texrra-tex-core/src/resources/project.rs | 52 +++- docs/NATIVE_PROJECT_INPUTS.md | 17 ++ docs/P2_M1_PROGRESS.md | 17 ++ examples/native_editor/main.rs | 74 +++-- src/native_checkpoint_guard.rs | 256 +++++++++++++++++- 5 files changed, 377 insertions(+), 39 deletions(-) diff --git a/crates/texrra-tex-core/src/resources/project.rs b/crates/texrra-tex-core/src/resources/project.rs index f7644bf..9d59dc2 100644 --- a/crates/texrra-tex-core/src/resources/project.rs +++ b/crates/texrra-tex-core/src/resources/project.rs @@ -109,10 +109,7 @@ impl ProjectSnapshot { revision: u64, edits: BTreeMap>, ) -> Result, String> { - self.validate()?; - let mut next = self.clone(); - next.version.revision = revision; - next.validated = OnceLock::new(); + let mut next = self.next_revision(revision)?; for (path, data) in edits { let previous = next.files.get_mut(&path).ok_or_else(|| { format!("atomic edit requires an immutable file: {}", path.display()) @@ -124,6 +121,44 @@ impl ProjectSnapshot { next.seal() } + /// Set or remove immutable files in a single revision. New files require + /// a declared parent directory. Replacing a file preserves its captured + /// modification time, and removing a file discards it. + pub fn with_file_changes( + &self, + revision: u64, + changes: BTreeMap>>, + ) -> Result, String> { + let mut next = self.next_revision(revision)?; + for (path, data) in changes { + if let Some(data) = data { + if !next + .file(&path) + .is_some_and(|previous| Arc::ptr_eq(&previous.data, &data)) + { + next.files.insert(path.clone(), Self::capture(path, data)); + } + } else { + if next.files.remove(&path).is_none() { + return Err(format!( + "atomic removal requires an immutable file: {}", + path.display() + )); + } + next.file_modifications.remove(&path); + } + } + next.seal() + } + + fn next_revision(&self, revision: u64) -> Result { + self.validate()?; + let mut next = self.clone(); + next.version.revision = revision; + next.validated = OnceLock::new(); + Ok(next) + } + fn capture(path: PathBuf, data: Arc<[u8]>) -> SnapshotFile { SnapshotFile { version: ResourceVersion { @@ -161,6 +196,12 @@ impl ProjectSnapshot { /// Whether both snapshots give lookups the same configuration, names, /// aliases and roles. The bytes and captured times are separate inputs. pub fn same_lookup_namespace(&self, next: &Self) -> Result { + Ok(self.same_lookup_configuration(next)? && self.files.keys().eq(next.files.keys())) + } + + /// Whether search settings, directories, aliases and generated roles agree. + /// File creation and removal can still change lookup results. + pub fn same_lookup_configuration(&self, next: &Self) -> Result { self.validate()?; next.validate()?; Ok(self.configuration == next.configuration @@ -168,8 +209,7 @@ impl ProjectSnapshot { && self.directories == next.directories && self.aliases == next.aliases && self.generated_roots == next.generated_roots - && self.generated == next.generated - && self.files.keys().eq(next.files.keys())) + && self.generated == next.generated) } pub fn generated(&self) -> impl Iterator { self.generated.iter().map(PathBuf::as_path) diff --git a/docs/NATIVE_PROJECT_INPUTS.md b/docs/NATIVE_PROJECT_INPUTS.md index 0eab8a5..8e36b08 100644 --- a/docs/NATIVE_PROJECT_INPUTS.md +++ b/docs/NATIVE_PROJECT_INPUTS.md @@ -66,6 +66,23 @@ profile、入口和执行限制仍是显式请求参数。没有单独的编辑 下一步仍需完整I/O效果/物理alias/句柄恢复契约、checkpoint、失效传播、执行/布局 复用和局部页面发布。当前仍为全量执行,不代表完整 LaTeX 或实时性能已经通过。 +## 原子文件增删与检查点 + +`ProjectSnapshot::with_file_changes` 接收一组同版本的绝对逻辑路径,`Some` +提交字节,`None` 删除已存在的不可变文件。新增文件使用已声明的父目录, +由快照校验资源覆盖范围、别名和生成角色。旧快照继续持有原字节。 +替换现有文件沿用已捕获的修改时间,删除同时清除对应时间记录。 + +检查点选择要求查找配置、目录、别名和生成角色仍相同,并核对实际读取的版本。 +文件集合变化时,准备新作业后重放前缀,然后逐项核对实际查找记录。这样即使 +`\pdffilesize` 返回值相同,候选顺序和最终来源变化也能使检查点失效。 +重放发生在原有暂存作业中,失效后按新快照全量执行。 + +`examples/native_editor` 的 `/preview` 接受 `files` 里的 JSON 字符串和 `null`。 +启动参数可以声明当前缺失的可编辑文件,其父目录需在项目下存在。入口文件受保护, +`/project` 返回当前版本存在的可编辑文件。原字符串写入和 `source` 请求继续使用 +同一共享编译接口。 + ## 2026-11-16:真实TeX流效果与清理(阶段未完成) [流效果契约](NATIVE_STREAM_EFFECTS.md)记录实际顺序、唯一句柄、snapshot/file身份、 diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index d795974..3d23a35 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -739,6 +739,23 @@ PDF、SVG、来源和最终 aux。实测24个基线 TCP 连接保持 TCP_NODELAY `target/p4-http-nodelay/run-1/receipt.json` 的 SHA-256 为 `879cb3ab850209eae3558558011391d9880d281073febe2fff16a934691e9cb3`。 +### 原子文件增删和实际查找 + +在隔离的上游导言区实验中,通过结构化 Kpathsea 调用核对了10个版本。 +正文和无关文件变更继续复用。前缀依赖新增、同名高优先级替换、改字节、 +删除回退或恢复缺失均触发重建。每版 SVG、aux 和项目内 SyncTeX 与 +全量一致。只读范围以外,实际在导言区创建并关闭输出的样例被探针标为 +不可复用。上游回执 `target/p4-upstream-lookup-contract/synthetic-session/receipt.json` +的 SHA-256 为 `9232c1558faed10fc7fe8206be990f25ae4fee590bc8f7c045ec41828a6f79f8`。 + +原生 Route-D 已接入原子文件增删。10次版本对照覆盖未知变已知、查找 +优先级、按路径删除后回落、已读字节变化,以及同尺寸文件改变来源。 +三次增删无关文件各复用162步并重放6项真实宿主调用。所有版本 PDF、 +SVG、来源映射、TeX 执行和 aux 与零复用一致。3项定向检查点测试通过。 +日志 `target/p4-checkpoint-file-changes/guard-tests-v2.log` 的 SHA-256 为 +`0619f4200c17f8d58f23b84bbad6a18c8fd622730bb45cbe0bbf31dc0b87a252`。 +[项目快照与编辑接口](NATIVE_PROJECT_INPUTS.md) + ### TeX 输入的默认扩展名候选 默认 TeX 编译在每个搜索目录中为带未知后缀的输入先试附加 `.tex`,并保留 diff --git a/examples/native_editor/main.rs b/examples/native_editor/main.rs index 629046b..d19a3eb 100644 --- a/examples/native_editor/main.rs +++ b/examples/native_editor/main.rs @@ -30,7 +30,7 @@ struct Edit { visible_revision: Option, source: Option, #[serde(default)] - files: BTreeMap, + files: BTreeMap>, #[serde(default)] preview_draft: bool, } @@ -214,12 +214,8 @@ fn main() -> Result<(), Box> { let file = project.file(&entry).expect("the editor owns its entry"); let files = editable .iter() - .map(|(name, path)| { - let file = project - .file(path) - .expect("editable project files are immutable"); - Ok((name, std::str::from_utf8(&file.data)?)) - }) + .filter_map(|(name, path)| project.file(path).map(|file| (name, file))) + .map(|(name, file)| Ok((name, std::str::from_utf8(&file.data)?))) .collect::, std::str::Utf8Error>>()?; reply( request, @@ -257,18 +253,21 @@ fn main() -> Result<(), Box> { let path = editable .get(&name) .ok_or_else(|| format!("File is not editable: {name}"))?; - Ok((path.clone(), Arc::from(value.into_bytes()))) + if *path == entry && value.is_none() { + return Err("The entry file cannot be removed".into()); + } + Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes())))) }) .collect::, String>>(); let next = updates.and_then(|mut updates| { if let Some(source) = edit.source && updates - .insert(entry.clone(), Arc::from(source.into_bytes())) + .insert(entry.clone(), Some(Arc::from(source.into_bytes()))) .is_some() { return Err("The entry file was edited twice".into()); } - project.with_file_edits(edit.sequence, updates) + project.with_file_changes(edit.sequence, updates) }); project = match next { Ok(project) => project, @@ -399,6 +398,8 @@ fn prepare( let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]); let mut files = BTreeMap::>::from([(entry.clone(), Arc::from(original))]); let source_root = source.parent().expect("the entry has a parent"); + let mut declared = BTreeSet::from([entry.clone()]); + let mut directories = BTreeSet::new(); for relative in additional { if relative.as_os_str().is_empty() || relative @@ -412,23 +413,50 @@ fn prepare( .into()); } let logical = run.join(relative); - let physical = source_root.join(relative).canonicalize()?; - if !physical.starts_with(source_root) || files.contains_key(&logical) { - return Err(format!( - "Project file is outside the entry directory or is listed twice: {}", - relative.display() - ) - .into()); + if !declared.insert(logical.clone()) { + return Err(format!("Project file is listed twice: {}", relative.display()).into()); } - let data: Arc<[u8]> = Arc::from(fs::read(physical)?); - fs::create_dir_all(logical.parent().expect("project file has a parent"))?; - fs::write(&logical, &data)?; + let physical = source_root.join(relative); + let data = match physical.canonicalize() { + Ok(path) if path.starts_with(source_root) => Some(Arc::<[u8]>::from(fs::read(path)?)), + Ok(_) => { + return Err(format!( + "Project file is outside the entry directory: {}", + relative.display() + ) + .into()); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + let parent = physical + .parent() + .expect("project file has a parent") + .canonicalize()?; + if !parent.starts_with(source_root) || physical.symlink_metadata().is_ok() { + return Err(error.into()); + } + None + } + Err(error) => return Err(error.into()), + }; + let directory = logical.parent().expect("project file has a parent"); + fs::create_dir_all(directory)?; + directories.extend( + directory + .ancestors() + .take_while(|path| path.starts_with(run)) + .map(Path::to_owned), + ); if let Some(name) = relative.to_str() - && std::str::from_utf8(&data).is_ok() + && data + .as_deref() + .is_none_or(|bytes| std::str::from_utf8(bytes).is_ok()) { editable.insert(name.into(), logical.clone()); } - files.insert(logical, data); + if let Some(data) = data { + fs::write(&logical, &data)?; + files.insert(logical, data); + } } let mut request = CompileRequest::new( world.clone(), @@ -475,7 +503,7 @@ fn prepare( revision: 1, roots: coverage, files, - directories: BTreeSet::new(), + directories, aliases: BTreeMap::new(), generated_roots: BTreeSet::from([run.to_owned()]), generated, diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 3d395f0..dd42957 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -4,7 +4,10 @@ use super::*; #[cfg(test)] use std::{collections::BTreeMap, fs}; use std::{collections::BTreeSet, ffi::OsString, path::Path}; -use texrra_tex_core::{execution::EntryCheckpoint, resources::ResourceKind}; +use texrra_tex_core::{ + execution::EntryCheckpoint, + resources::{ResourceKind, ResourceLookup}, +}; #[cfg(test)] use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy}; @@ -423,6 +426,18 @@ impl SelectedCheckpoint { check(cancellation)?; call(&mut prepared.files)?; } + let project = request + .project + .as_deref() + .expect("validated atomic project"); + if !checkpoint + .guard + .project + .immutable_paths() + .eq(project.immutable_paths()) + { + checkpoint.guard.verify_replayed_lookups(&prepared.files)?; + } Ok(prepared) } @@ -504,6 +519,7 @@ struct PrefixInputGuard { initial: GeneratedInitialState, entry: PathBuf, immutable: BTreeSet, + lookups: Vec, clock_environment: Option<[Option; 3]>, } @@ -572,6 +588,7 @@ impl PrefixInputGuard { initial, entry: entry.to_path_buf(), immutable, + lookups: trace.lookups.clone(), clock_environment: (!trace.file_modifications.is_empty()).then(date_environment), }) } @@ -597,8 +614,8 @@ impl PrefixInputGuard { .project .as_deref() .ok_or("checkpoint requires an atomic project")?; - if !self.project.same_lookup_namespace(current)? { - return Err("checkpoint lookup namespace changed".into()); + if !self.project.same_lookup_configuration(current)? { + return Err("checkpoint lookup configuration changed".into()); } for path in &self.immutable { let old = self.project.file(path).map(|file| &file.version); @@ -621,6 +638,19 @@ impl PrefixInputGuard { Ok(current) } + fn verify_replayed_lookups(&self, files: &Files) -> Result<(), CompileError> { + let trace = files.resource_trace(); + if trace.lookups != self.lookups + || !trace.read_errors.is_empty() + || !trace.namespace_capture_failures.is_empty() + { + return Err(CompileError::Host( + "checkpoint replayed lookup changed".into(), + )); + } + Ok(()) + } + fn verify( &self, request: &CompileRequest, @@ -805,16 +835,16 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec &request.clone().with_project(changed_prefix), "entry prefix changed", ); - let mut appeared = definition; - appeared.revision = 3; - appeared - .files - .insert(cwd.join("optional.tex"), Arc::from(b"present".as_slice())); + let mut changed_namespace = definition; + changed_namespace.revision = 3; + changed_namespace + .directories + .insert(cwd.join("new-directory")); rejected( &request .clone() - .with_project(ProjectSnapshot::new(appeared).unwrap()), - "lookup namespace changed", + .with_project(ProjectSnapshot::new(changed_namespace).unwrap()), + "lookup configuration changed", ); let mut changed_clock = request.clone(); changed_clock.time = JobTime::new(2026, 11, 18, 1001).unwrap(); @@ -1177,6 +1207,212 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec ); } +#[test] +fn immutable_file_creation_and_removal_replay_real_lookup_results() { + use texrra_tex_core::resources::SearchPath; + + let cwd = std::env::temp_dir().join(format!("texrra-file-revisions-{}", std::process::id())); + fs::create_dir(&cwd).unwrap(); + let cwd = cwd.canonicalize().unwrap(); + let vendor = cwd.join("vendor"); + let entry = cwd.join("entry.tex"); + let aux = cwd.join("entry.aux"); + let extra = cwd.join("unread.tex"); + let settings = cwd.join("settings.tex"); + let vendor_settings = vendor.join("settings.tex"); + let tag = cwd.join("tag.tex"); + let vendor_tag = vendor.join("tag.tex"); + let prefix = concat!( + "\\catcode123=1 \\catcode125=2\n", + "\\def\\value{10}\n", + "\\openin3=settings.tex \\ifeof3\\else\\input settings.tex \\fi\\closein3\n", + "\\edef\\filesize{\\pdffilesize{tag.tex}}\n", + "\\immediate\\openout1=entry.aux\n", + "\\immediate\\write1{unchanged journal}\\relax\n", + "\\message{CHECKPOINT}\\relax\n", + ); + let tail = "\\shipout\\hbox{\\vrule width\\value pt height1pt}\n\\immediate\\closeout1\\end\n"; + let world = { + let mut world = WorldConfig::new(&cwd); + world.paths.insert( + ResourceKind::Tex, + vec![ + SearchPath::directory(&cwd, false), + SearchPath::directory(&vendor, false), + ], + ); + world + }; + let mut project = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: BTreeSet::from([cwd.clone()]), + files: BTreeMap::from([ + ( + entry.clone(), + Arc::from(format!("{prefix}{tail}").into_bytes()), + ), + (vendor_tag.clone(), Arc::from(b"42".as_slice())), + ]), + directories: BTreeSet::from([vendor]), + aliases: BTreeMap::new(), + generated_roots: BTreeSet::from([cwd.clone()]), + generated: BTreeSet::from([aux.clone()]), + }) + .unwrap(); + assert!( + project + .with_file_changes( + 2, + BTreeMap::from([(aux.clone(), Some(Arc::from(b"source collision".as_slice())))]), + ) + .is_err() + ); + assert!( + project + .with_file_changes( + 2, + BTreeMap::from([(cwd.join("missing-parent/entry.tex"), Some(Arc::from([])))]), + ) + .is_err() + ); + + let mut request = CompileRequest::new( + world, + "entry.tex", + "entry.pdf", + JobTime::new(2026, 11, 20, 540) + .unwrap() + .with_pdf_clock(0, 0) + .unwrap(), + ) + .observe_generated_initial(); + request.entry = Entry::Initex; + request.etex = true; + NativeCompiler::default() + .compile(request.clone().with_project(project.clone())) + .unwrap(); + let journal = fs::read(&aux).unwrap(); + let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() - 2); + + let revisions = [ + ("cold", None, false, None, 10), + ( + "unrelated appeared", + Some((&extra, Some(b"unused".as_slice()))), + true, + None, + 10, + ), + ("unrelated removed", Some((&extra, None)), true, None, 10), + ( + "missing dependency appeared", + Some((&vendor_settings, Some(br"\def\value{20}".as_slice()))), + false, + Some("open_in changed"), + 20, + ), + ( + "higher priority dependency appeared", + Some((&settings, Some(br"\def\value{30}".as_slice()))), + false, + Some("open_in changed"), + 30, + ), + ( + "dependency edited", + Some((&settings, Some(br"\def\value{40}".as_slice()))), + false, + Some("observed input changed"), + 40, + ), + ( + "removed dependency exposes fallback", + Some((&settings, None)), + false, + Some("observed input changed"), + 20, + ), + ( + "removed fallback", + Some((&vendor_settings, None)), + false, + Some("observed input changed"), + 10, + ), + ( + "equal-size result came from a new path", + Some((&tag, Some(b"59".as_slice()))), + false, + Some("replayed lookup changed"), + 10, + ), + ( + "unrelated file appeared again", + Some((&extra, Some(b"new unused".as_slice()))), + true, + None, + 10, + ), + ]; + let mut pdfs = BTreeMap::new(); + for (index, (label, edit, reuse, rejection, width)) in revisions.into_iter().enumerate() { + if let Some((path, bytes)) = edit { + let previous = project.clone(); + project = project + .with_file_changes( + index as u64 + 1, + BTreeMap::from([(path.clone(), bytes.map(Arc::from))]), + ) + .unwrap(); + if label == "unrelated appeared" { + assert!(previous.file(path).is_none()); + assert!(project.file(path).is_some()); + } + } + let next = request.clone().with_project(project.clone()); + let result = compiler.compile(next.clone()).unwrap(); + let work = &result.entry_checkpoint_work; + assert_eq!(work.reused_steps > 0, reuse, "{label}: {work:?}"); + if let Some(expect) = rejection { + assert!( + work.rejection + .as_deref() + .is_some_and(|e| e.contains(expect)), + "{label}: {work:?}" + ); + } + assert_eq!(fs::read(&aux).unwrap(), journal, "{label}"); + let full = NativeCompiler::default().compile(next).unwrap(); + assert_eq!(full.entry_checkpoint_work.reused_steps, 0, "{label}"); + assert_eq!(result.pdf, full.pdf, "{label}"); + assert_eq!(result.source_map.pages, full.source_map.pages, "{label}"); + assert_eq!( + result.source_map.sources, full.source_map.sources, + "{label}" + ); + assert_eq!( + result.preview_since(None).unwrap().pages, + full.preview_since(None).unwrap().pages, + "{label}", + ); + assert_eq!( + result.execution.execution, full.execution.execution, + "{label}" + ); + assert_eq!( + result.resources.trace.lookups, full.resources.trace.lookups, + "{label}" + ); + assert_eq!(fs::read(&aux).unwrap(), journal, "{label}"); + if let Some(previous) = pdfs.insert(width, result.pdf.clone()) { + assert_eq!(previous, result.pdf, "{label}"); + } + eprintln!("{label}: {work:?}"); + } + assert_eq!(pdfs.values().collect::>().len(), 4); +} + #[test] fn automatic_checkpoints_follow_successive_edits_at_different_frontiers() { let cwd = std::env::temp_dir().join(format!("texrra-rolling-{}", std::process::id()));