Reuse native checkpoints for unchanged file-size observations

This commit is contained in:
gloamxun committed 2026-11-29 09:24:06 +08:00
1 parent 061e484001
commit 4162c88826
5 files changed
+177 -17

No files matched your search

+7 -1
View File
@@ -18,7 +18,13 @@
在功能接齐后的统一候选上跑 W0–W7、完整出版矩阵,以及浏览器延迟和内存门禁。
阶段记录先写实际可运行的项目、编辑节省的工作和下一项具体阻塞。
## 2026-11-20 先实现功能,再统一验收
功能批次以既有多栏出版项目尚未覆盖的真实流程为入口,优先解决跨栏浮动、
脚注与分页、辅助文件和多轮作业的共用阻塞。独立的增量优化积累在同一开发
批次,优先推进能覆盖原样项目的复用边界。ACM、Elsevier、Wiley 双栏和
XeLaTeX 的 NeurIPS 已有各自的专项结果,具体完备程度与证据见
[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。
## 2026-11-20 先实现功能,再统一验收(历史顺序)
后续迭代优先补齐 LaTeX 和实时编译功能。实时会话的状态、依赖和布局复用
随内核功能一起接入。按实际差异和共有依赖推进以下工作:
+19
View File
@@ -18,6 +18,25 @@
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 |
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
## 2026-11-29 独立校验文件大小依赖
检查点根据实际调用、读取及成功解析路径判断某个不可变文件是否仅被
查询了大小。读取正文、流数据、文件日期、格式绑定或涉及生成路径时,
保留原校验。重放重新解析同一路径,比较实际字节数,并保留当前版本
的依赖记录和捕获内容。
在只查询资源大小的两页作业中,4 字节的等长改动从重执行 27,175
步变为 0 步,没有页面更新。改成 11 字节仍实际执行 27,176 步,
只更新第一页。两次均与独立全量一致。原样 A4 子文件等长、异长、
恢复三次编辑分别执行 56,886、79,031、79,001 步,每次仅更新第一页。
完整执行、PDF、SVG、来源映射、资源及辅助文件与独立全量一致。
五项定向回归通过。旧版也会复用流编辑中未变化的第二页,已用上一
提交重现。现有用例同步核验读取点前恢复及未变化页面的布局复用。
证据在 target/p4-size-only-dependencies/,包含首次运行的失败和
独立作业复验。SHA256SUMS 指纹为
e4c55af83b689de7d482dd46d21ed29e0546049dfa508436760323820a89d014。
## 2026-11-29 子文件大小变化的检查点预检
子文件内部检查点记录已执行的真实文件大小查询。项目的查询配置
+61 -6
View File
@@ -305,11 +305,11 @@ impl<'a> CapturedEntries<'a> {
fn capture(&mut self, slots: Capture, entry: Arc<EntryCheckpoint>, host: &RecordingHost) {
let slots = if let Capture::Settled { page, regular } = slots {
if let Some((_, call_count)) = host.prefix() {
if let Some((_, calls)) = host.prefix() {
self.settled.insert(page, SettledCheckpoint {
entry: entry.clone(),
host: host.files().replay_boundary(),
call_count,
call_count: calls.len(),
});
self.changed = true;
}
@@ -318,7 +318,7 @@ impl<'a> CapturedEntries<'a> {
} else {
slots
};
let (Some((trace, replay_count)), Some(path), Some(initial)) = (
let (Some((trace, calls)), Some(path), Some(initial)) = (
host.prefix(),
self.entry_path.as_deref(),
self.initial.as_ref(),
@@ -329,6 +329,7 @@ impl<'a> CapturedEntries<'a> {
self.request,
path,
trace,
calls,
host.generated_outputs(),
initial.clone(),
) else {
@@ -344,7 +345,7 @@ impl<'a> CapturedEntries<'a> {
Arc::new(CachedCheckpoint {
entry,
guard,
replay_count,
replay_count: calls.len(),
slots,
}),
);
@@ -394,11 +395,12 @@ impl<'a> CapturedEntries<'a> {
// 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 (trace, calls) = recording.prefix()?;
let guard = PrefixInputGuard::capture(
self.request,
self.entry_path.as_deref()?,
trace,
calls,
recording.generated_outputs(),
self.initial?,
).ok()?;
@@ -942,6 +944,7 @@ struct PrefixInputGuard {
entry: PathBuf,
nested_source: Option<NestedSourceGuard>,
immutable: BTreeSet<PathBuf>,
immutable_sizes: BTreeMap<PathBuf, u64>,
immutable_stream_prefixes: BTreeMap<PathBuf, usize>,
generated: BTreeSet<PathBuf>,
lookups: Vec<ResourceLookup>,
@@ -950,6 +953,54 @@ struct PrefixInputGuard {
clock_environment: Option<[Option<OsString>; 3]>,
}
fn size_only_inputs(
project: &ProjectSnapshot,
trace: &ResourceTrace,
calls: &[Call],
) -> BTreeMap<PathBuf, u64> {
#[derive(Default)]
struct Observations {
sizes: usize,
reads: usize,
lookups: usize,
}
let mut counts = BTreeMap::<&Path, Observations>::new();
for (path, size) in calls.iter().filter_map(Call::observed_file_size) {
if project.file(path).is_some_and(|file| file.version.bytes == size) {
counts.entry(path).or_default().sizes += 1;
}
}
if counts.is_empty() {
return BTreeMap::new();
}
// A size call records one complete host read and one successful lookup.
// Any other consumer keeps its own stronger dependency on this path.
for version in &trace.reads {
if let Some(count) = counts.get_mut(version.path.as_path()) {
count.reads += 1;
}
}
for path in trace.lookups.iter().filter_map(|item| item.resolved.as_deref()) {
if let Some(count) = counts.get_mut(path) {
count.lookups += 1;
}
}
for path in trace.stream_reads.iter().map(|read| &read.path)
.chain(trace.file_modifications.iter().map(|read| &read.path))
.chain(trace.generated_lookups.iter().map(|read| &read.target))
.chain(trace.format_input_bindings.values())
{
counts.remove(path.as_path());
}
counts.into_iter()
.filter(|(_, count)| count.sizes == count.reads && count.sizes == count.lookups)
.map(|(path, _)| (path.to_owned(), project.file(path).unwrap().version.bytes))
.collect()
}
fn date_environment() -> [Option<OsString>; 3] {
["TZ", "SOURCE_DATE_EPOCH", "FORCE_SOURCE_DATE"].map(std::env::var_os)
}
@@ -959,6 +1010,7 @@ impl PrefixInputGuard {
request: &CompileRequest,
entry: &Path,
trace: &ResourceTrace,
calls: &[Call],
written: &BTreeSet<PathBuf>,
initial: GeneratedInitialState,
) -> Result<Self, String> {
@@ -1044,6 +1096,7 @@ impl PrefixInputGuard {
let prefix = immutable_stream_prefixes.entry(range.path.clone()).or_default();
*prefix = (*prefix).max(end);
}
let immutable_sizes = size_only_inputs(project, trace, calls);
Ok(Self {
original: AttemptRequest::from(request),
project: project.clone(),
@@ -1051,6 +1104,7 @@ impl PrefixInputGuard {
entry: entry.to_path_buf(),
nested_source: None,
immutable,
immutable_sizes,
immutable_stream_prefixes,
generated,
lookups: trace.lookups.clone(),
@@ -1121,6 +1175,7 @@ impl PrefixInputGuard {
|(old, new)| {
old.version == new.version
|| self.nested_source.as_ref().is_some_and(|source| &source.path == path)
|| self.immutable_sizes.get(path) == Some(&new.version.bytes)
|| self.immutable_stream_prefixes.get(path).is_some_and(|&end| {
new.data.get(..end) == Some(&old.data[..end])
})
@@ -1307,7 +1362,7 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
.iter()
.any(|lookup| lookup.name == "optional.tex" && lookup.resolved.is_none())
);
let guard = PrefixInputGuard::capture(&request, &entry, &trace, &written, initial).unwrap();
let guard = PrefixInputGuard::capture(&request, &entry, &trace, &calls, &written, initial).unwrap();
assert!(guard.generated.contains(&aux));
assert!(!guard.generated.contains(&seed));
assert!(guard.immutable.contains(&library));
+20 -9
View File
@@ -1,8 +1,8 @@
//! Capture and verify the native host calls made by an entry prefix.
use super::*;
use std::{collections::BTreeSet, fmt::Debug};
use std::{collections::BTreeSet, fmt::Debug, path::Path};
#[cfg(test)]
use std::{fs, path::Path};
use std::fs;
#[cfg(test)]
use texrra_tex_core::source_map::SourceMap;
use texrra_tex_core::{
@@ -36,16 +36,27 @@ pub(super) struct RebindableSourceObservations {
}
impl Call {
pub(super) fn observed_file_size(&self) -> Option<(&Path, u64)> {
let Self::FileSize(read) = self else { return None };
let version = read.read.as_ref()?;
(read.observed == Ok(Some(version.bytes))).then_some((&version.path, version.bytes))
}
pub(super) fn replay(&self, files: &mut Files, partial_source: Option<&ResourceVersion>) -> Result<(), String> {
match self {
Self::Checked(call) => call(files),
Self::FileSize(read) => {
let before = files.resource_trace().reads.len();
let observed = files.file_size(&read.name, &read.from);
if observed == read.observed {
Ok(())
} else {
Err(format!("file size changed: expected {:?}, observed {observed:?}", read.observed))
if observed != read.observed {
return Err(format!("file size changed: expected {:?}, observed {observed:?}", read.observed));
}
if let Some(expected) = &read.read
&& !matches!(&files.resource_trace().reads[before..], [actual] if actual.path == expected.path)
{
return Err(format!("file size lookup changed: {}", expected.path.display()));
}
Ok(())
}
Self::ReadSource(read) => {
let SourceRead { name, from, expected } = read.as_ref();
@@ -104,9 +115,9 @@ impl<'a> RecordingHost<'a> {
Some((self.calls.take()?, trace))
}
pub(super) fn prefix(&self) -> Option<(&ResourceTrace, usize)> {
let count = self.calls.as_ref()?.len();
(count < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), count))
pub(super) fn prefix(&self) -> Option<(&ResourceTrace, &[Call])> {
let calls = self.calls.as_deref()?;
(calls.len() < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), calls))
}
pub(super) fn rebindable_source_observations(
+70 -1
View File
@@ -680,6 +680,68 @@ fn child_checkpoints_reuse_only_the_validated_physical_prefix() {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn checkpoint_reuses_unchanged_sizes_and_replays_current_resource_versions() {
for (label, consumer) in [
("size-only", ""),
("size-and-source", r"\input metadata.tex"),
("size-and-stream", r"\openin1=metadata.tex \read1 to\fromfile \closein1 \fromfile"),
] {
let cwd = directory(label);
let metadata = cwd.join("metadata.tex");
let body = format!(r"
\count0=\pdffilesize{{metadata.tex}}\relax
{consumer}
\shipout\hbox{{\vrule width\dimexpr\count0 pt+\count2 pt\relax height1pt}}
\shipout\hbox{{\vrule width20pt height1pt}}
\end
");
let mut definition = atomic_definition(&cwd, 1, &body);
definition.files.insert(metadata.clone(), Arc::from(br"\count2=1".as_slice()));
let mut project = ProjectSnapshot::new(definition).unwrap();
let mut request = request(&cwd).observe_generated_initial();
request.world = project.configuration();
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
let mut prior = compiler.compile(request.clone().with_project(project.clone())).unwrap();
for (revision, bytes) in [
(2, br"\count2=2".as_slice()),
(3, br"\count2=12".as_slice()),
] {
project = project.with_file_edits(revision, [
(metadata.clone(), Arc::from(bytes)),
].into()).unwrap();
let job = request.clone().with_project(project.clone());
let after = compiler.compile(job.clone()).unwrap();
let full = NativeCompiler::default().compile(job).unwrap();
let reuse = consumer.is_empty() && revision == 2;
let work = &after.entry_checkpoint_work;
assert_eq!(work.reused_completion, reuse, "{label}: {work:?}");
if reuse {
assert_eq!(work.reused_steps, after.execution.execution.steps);
}
let version = &project.file(&metadata).unwrap().version;
assert!(after.resources.trace.reads.contains(version), "{label}");
assert!(after.inputs.files().any(|(path, input)| {
path == metadata && input.is_ok_and(|file| file.data.as_ref() == bytes)
}), "{label}");
assert_eq!(after.execution.execution.state.count(0) as usize, bytes.len());
assert!(after.execution.execution == full.execution.execution, "{label}");
assert_eq!(after.execution.execution_resources, full.execution.execution_resources);
assert_eq!(after.resources.trace, full.resources.trace);
assert_eq!(after.pdf, full.pdf);
assert_eq!(after.source_map.sources, full.source_map.sources);
assert_eq!(after.source_map.pages, full.source_map.pages);
assert_eq!(after.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages);
let changed: Vec<_> = after.preview_since(Some(prior.revision())).unwrap().pages
.into_iter().map(|page| page.index).collect();
assert_eq!(changed, if reuse { &[][..] } else { &[0][..] }, "{label}");
prior = after;
}
fs::remove_dir_all(cwd).unwrap();
}
}
#[test]
fn unicode_math_code_edit_updates_the_page_that_reads_the_table() {
let p = directory("unicode-math-code");
@@ -1542,7 +1604,7 @@ fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() {
for (revision, bytes, reused_pages, expected_change) in [
(2, b"Stable heading\nEdited body with more text\n".as_slice(), 1, [1]),
(3, b"Stable heading\nEdited body with more text\nAppendix\n".as_slice(), 1, [1]),
(4, b"Edited heading\nEdited body with more text\nAppendix\n".as_slice(), 0, [0]),
(4, b"Edited heading\nEdited body with more text\nAppendix\n".as_slice(), 1, [0]),
] {
project = project
.with_file_edits(revision, [(input.clone(), Arc::from(bytes))].into())
@@ -1550,6 +1612,13 @@ fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() {
let request = request.clone().with_project(project.clone());
let resumed = session.compile(request.clone()).unwrap();
let work = &resumed.entry_checkpoint_work;
if revision == 4 {
let first_read = HEADER.len() + body.find(r"\readline1 to\headline").unwrap();
assert!(
work.reused_frontier.is_none_or(|frontier| frontier <= first_read),
"{work:?}"
);
}
assert_eq!(resumed.shipout_layout_work.reused_pages, reused_pages, "{work:?}");
assert_eq!(resumed.shipout_layout_work.lowered_pages, 2 - reused_pages);
let changed: Vec<_> = resumed