Cancel jobs while their private file sync drains

This commit is contained in:
gloamxun committed 2026-11-19 18:01:50 +08:00
1 parent f6c493e462
commit 41af3d8d22
5 files changed
+283 -32

No files matched your search

+10 -4
View File
@@ -18,10 +18,16 @@ Typst 将实际访问依赖用于判定阶段结果能否复用。TeX 会话在
的工作都用同版本的原生全量结果和真实页面交付验证。
[Typst 上游架构文档](https://github.com/typst/typst/blob/main/docs/dev/architecture.md)
A3 固定两版各30次逐次交替编辑。第7页实际更新,PDF、SVG及最终 aux 保持
一致,可见 p95 从 4635.0 ms 降到 3379.2 ms。下一步量出发布耗时中同步、
版本复核和替换的分项,验证编辑预览能在当前 revision 受控发布,并缩减
剩余的执行和布局范围。100 ms 的 p95 继续作为正式门禁。
复用上游组件时须测量真实的依赖可追踪性、增量执行范围、取消和字体及文件效果。
Tectonic 的 XeTeX 入口在进程级锁内运行,桥接层能提供输入输出钩子。它可以用来
评估集成与语义对照。若选作实时执行组件,须先以原样项目证明增量恢复和取消。
[Tectonic XeTeX 入口](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/engine_xetex/src/lib.rs#L163-L205)
[Tectonic 桥接层](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/bridge_core/src/lib.rs#L271-L288)
原样 A4 在连续子文件编辑中,取消旧作业的浏览器观测 p95 已低于100 ms。
新编辑到可见页面的 p95 仍高于250 ms。接下来分解编译准备、执行复用和页面
交付,继续按固定预算及逐版本全量一致性验收。
[阶段测量与回执](P2_M1_PROGRESS.md)
## 2026-11-11 总目标重新确认
+33
View File
@@ -353,6 +353,39 @@ p95 分别为105.9和119.7 ms。运行前后 I/O pressure avg10 为11.45%和39.9
最终 aux。浏览器回执 `target/p4-multifile-editor/edge-a4/run-1/receipt.json`
SHA-256 为 `305fa4b8a1247f5c3683e2434d8b43b7a5b4dfd0256711a37ffd3a220a13ebb3`,独立全量回执 SHA-256 为 `47753c1293eb31fca88d1ac2357dfd50ada6156699b703b3dc1178d87082b4b4`。
### 取消旧作业时释放编译路径
草稿 PDF、日志、aux 和账本的同步只持有私有文件。旧作业取消后释放编译和项目
锁,最多允许两个私有同步作业并存。仍在操作系统中同步的文件由原私有句柄收尾,
文件版本复核和实际安装仍由当前修订控制。受控 A4 实验停在实际文件同步入口,
新版能在放行旧同步前发布后续编辑。两边新版 PDF、SVG、来源映射和 aux 相同,
旧文件在实际同步返回后清理。64 项库和原生流程回归通过。
Edge 在原样 A4 前稿已绘制、文件仍待发布时提交下一次子文件编辑。两版交替,
各取得30次确认取消旧作业的样本,基线补采6次,新版无需补采。取消数值含浏览器
轮询,是观测到的上界。实际 PDF、SVG、来源版本和映射逐次相同,最终 aux 相同。
| 指标 | 基线 p50 / p95 | 新版 p50 / p95 |
| --- | ---: | ---: |
| 浏览器观察到旧作业取消 | 967.9 / 1864.7 ms | 49.7 / 67.8 ms |
| 新请求到编译准备开始 | 907.7 / 1828.0 ms | 14.6 / 21.2 ms |
| 新编辑到页面绘制 | 1317.9 / 2180.7 ms | 318.9 / 410.3 ms |
服务端峰值 RSS 由 647156 KiB 到 647612 KiB,
WSL I/O 压力 some avg10 从2.73%到34.67%。此场景的取消上界 p95 低于100 ms,
后续子文件编辑的可见 p95 仍高于250 ms。独立全量用同一优化程序和最后两份
浏览器缓冲区,零复用步骤,PDF、SVG、来源版本和映射、最终 aux 均相同。
回执和回归日志位于 `target/p4-cancel-private-sync`。自然测试
`rapid-edits-final/run-1/receipt.json` 的 SHA-256 为
`41488e8eabbc45aaced4e5f62721df26ed877d58b21f126ef088a42b7d3431a7`,受控回执
`held-sync/paired-receipt-final.json` 的 SHA-256 为
`50de5a1ea2e3a92d159207c446d76eb70ee8592eee52b67e5d1b4c7d09bf8b4b`,独立全量回执
`full-equivalence/receipt.json` 的 SHA-256 为
`3fd9a702715c6df6200e2eee44ab7748730390a266e9d5db1a264c2dd73d301c`。定向回归
`directed-final.log` 的 SHA-256 为
`90b907c33458cc109effdf696721d9ddc572fbd43f3a1dc05694fb986b49330f`。
### schema27 与主线兼容性
合并了真实重复盒及 PDF 书签布局,并保留主线的宏参数分隔符和流式失败报告。
+7 -2
View File
@@ -12,7 +12,8 @@ pub use crate::native_host::{
};
pub use crate::native_job::job_time;
use crate::native_job::{
EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output, file_modification_date,
DraftSyncQueue, EffectMode, Files, PreparedInputsCheck, PreparedOutput, absolute_output,
file_modification_date,
};
use crate::native_preview::PreviewState;
pub use crate::native_preview::{PreviewPage, PreviewUpdate};
@@ -556,6 +557,7 @@ pub struct NativeCompiler {
session: NativeSession,
latest: Arc<Mutex<Option<Arc<CompiledDocument>>>>,
jobs: Arc<Mutex<()>>,
draft_sync: Arc<DraftSyncQueue>,
format_cache: Arc<FormatCache>,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
entry_checkpoints: Option<Arc<CheckpointCache>>,
@@ -1211,8 +1213,11 @@ impl CompileJob {
let publication = available_host
.take()
.expect("prepared draft host")
.seal_draft(prepared)
.seal_draft(prepared, &self.compiler.draft_sync, &cancellation)
.and_then(|draft| {
let Some(draft) = draft else {
return Ok(None);
};
draft.publish_current(&self.compiler.session, result.revision(), || {
cache.set(next_checkpoint, &request);
expose();
+8 -1
View File
@@ -916,7 +916,14 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
assert!(pdf.diagnostics.is_empty(), "{:?}", pdf.diagnostics);
files.finish().unwrap();
let prepared_pdf = PreparedOutput::write(&cwd.join("entry.pdf"), &pdf.bytes).unwrap();
let staged = files.seal_draft(Some(prepared_pdf)).unwrap();
let staged = files
.seal_draft(
Some(prepared_pdf),
&DraftSyncQueue::default(),
&Cancellation::default(),
)
.unwrap()
.unwrap();
assert_eq!(output_paths(), saved);
assert_eq!(fs::read(ledger).unwrap(), saved_ledger);
(result, source_map, pdf.bytes, staged)
+225 -25
View File
@@ -14,10 +14,16 @@ use std::{
fs::{self, File, OpenOptions},
io::{self, BufRead, BufReader, Seek, Write},
path::{Path, PathBuf},
sync::{
Arc,
atomic::{AtomicUsize, Ordering},
mpsc,
},
time::Duration,
};
use texrra_tex_core::artifacts::{ArtifactLedger, file_version};
use texrra_tex_core::execution::{
JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination,
Cancellation, JobTime, NativeSession, SourceFile, SourceProvider, WriteDestination,
};
use texrra_tex_core::resources::{FileWorld, LoadedResource, ResourceKind, ResourceVersion};
@@ -1127,7 +1133,9 @@ impl Files {
pub(crate) fn seal_draft(
mut self,
pdf: Option<PreparedOutput>,
) -> Result<DraftPublication, String> {
queue: &DraftSyncQueue,
cancellation: &Cancellation,
) -> Result<Option<DraftPublication>, String> {
let draft = self.draft.take().ok_or("native draft host required")?;
if !draft.finished {
return Err("native draft must finish successfully before publication".into());
@@ -1156,6 +1164,105 @@ impl Files {
.filter(|(path, _)| !draft.generated.contains_key(*path))
.map(|(path, version)| (path.clone(), version.clone()))
.collect::<BTreeMap<_, _>>();
let pending = PendingDraft {
draft,
log,
pdf,
untouched,
ledger_current: self.ledger_current.clone(),
};
// The worker owns private files only. The foreground retains this
// host and its project lock until it can publish or has been cancelled.
let synced = queue.sync(cancellation, move |stop| pending.sync(stop))?;
Ok(synced.map(|synced| DraftPublication {
synced,
_host: self,
}))
}
}
#[derive(Default)]
pub(crate) struct DraftSyncQueue {
active: Arc<AtomicUsize>,
}
struct DraftSyncSlot(Arc<AtomicUsize>);
impl Drop for DraftSyncSlot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
impl DraftSyncQueue {
fn sync(
&self,
cancellation: &Cancellation,
run: impl FnOnce(&Cancellation) -> Result<Option<SyncedDraft>, String> + Send + 'static,
) -> Result<Option<SyncedDraft>, String> {
const WAIT: Duration = Duration::from_millis(5);
// Allow one obsolete sync to drain while the current draft syncs.
// If both calls are still in the OS, wait without starting more.
let slot = loop {
if cancellation.is_cancelled() {
return Ok(None);
}
let active = self.active.load(Ordering::Acquire);
if active < 2
&& self
.active
.compare_exchange(active, active + 1, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
break DraftSyncSlot(self.active.clone());
}
std::thread::sleep(WAIT);
};
let stop = cancellation.clone();
let (send, receive) = mpsc::channel();
std::thread::Builder::new()
.name("texrra-draft-sync".into())
.spawn(move || {
let _slot = slot;
let _ = send.send(run(&stop));
})
.map_err(|error| format!("start native draft sync: {error}"))?;
loop {
if cancellation.is_cancelled() {
return Ok(None);
}
match receive.recv_timeout(WAIT) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("native draft sync worker stopped".into());
}
}
}
}
}
struct PendingDraft {
log: Option<File>,
draft: DraftEffects,
pdf: Option<PreparedOutput>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
ledger_current: Option<ResourceVersion>,
}
impl PendingDraft {
fn sync(self, cancellation: &Cancellation) -> Result<Option<SyncedDraft>, String> {
if cancellation.is_cancelled() {
return Ok(None);
}
let Self {
draft,
log,
pdf,
untouched,
ledger_current,
} = self;
let mut artifacts: Vec<_> = draft.generated.into_values().collect();
let sync_pdf = || -> Result<(), String> {
if let Some(file) = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref()) {
@@ -1175,28 +1282,50 @@ impl Files {
// Flush independent files concurrently, then finish collecting all
// results before the revision gate can install any artifact.
std::thread::scope(|scope| {
let pdf_worker = pdf.as_ref().and_then(|pdf| pdf.pending_sync.as_ref())
.and_then(|_| std::thread::Builder::new().spawn_scoped(scope, sync_pdf).ok());
let log_worker = log.as_ref()
.and_then(|_| std::thread::Builder::new().spawn_scoped(scope, sync_log).ok());
let pdf_worker = pdf
.as_ref()
.and_then(|pdf| pdf.pending_sync.as_ref())
.and_then(|_| {
std::thread::Builder::new()
.spawn_scoped(scope, sync_pdf)
.ok()
});
let log_worker = log.as_ref().and_then(|_| {
std::thread::Builder::new()
.spawn_scoped(scope, sync_log)
.ok()
});
let generated = artifacts.iter().try_for_each(|artifact| {
if cancellation.is_cancelled() {
return Ok(());
}
OpenOptions::new()
.write(true)
.open(&artifact.staged.path)
.and_then(|file| file.sync_all())
.map_err(|error| {
format!("sync native draft {}: {error}", artifact.target.path.display())
format!(
"sync native draft {}: {error}",
artifact.target.path.display()
)
})
});
let pdf_result = pdf_worker.map_or_else(sync_pdf, |worker| {
worker.join().map_err(|_| "native draft PDF sync thread panicked".to_owned())?
worker
.join()
.map_err(|_| "native draft PDF sync thread panicked".to_owned())?
});
let log_result = log_worker.map_or_else(sync_log, |worker| {
worker.join().map_err(|_| "native draft log sync thread panicked".to_owned())?
worker
.join()
.map_err(|_| "native draft log sync thread panicked".to_owned())?
});
pdf_result.and(log_result).and(generated)
})?;
drop(log);
if cancellation.is_cancelled() {
return Ok(None);
}
artifacts.push(draft.log);
let untouched_ledger = if let Some(DraftLedger { file, staged }) = draft.ledger {
let target = &draft.ledger_target.path;
@@ -1205,7 +1334,7 @@ impl Files {
if !actual.is_file()
|| DraftFileStamp::from_metadata(&actual).map_err(|e| e.to_string())?
!= DraftFileStamp::from_metadata(&descriptor).map_err(|e| e.to_string())?
|| Some(staged.version(target)?) != self.ledger_current
|| Some(staged.version(target)?) != ledger_current
{
return Err(format!(
"native staged ledger changed: {}",
@@ -1230,12 +1359,11 @@ impl Files {
staged,
});
}
Ok(DraftPublication {
Ok(Some(SyncedDraft {
artifacts,
untouched,
untouched_ledger,
_host: self,
})
}))
}
}
@@ -1739,10 +1867,14 @@ struct DraftArtifact {
staged: PreparedOutput,
}
pub(crate) struct DraftPublication {
struct SyncedDraft {
artifacts: Vec<DraftArtifact>,
untouched: BTreeMap<PathBuf, Option<ResourceVersion>>,
untouched_ledger: Option<DraftDestination>,
}
pub(crate) struct DraftPublication {
synced: SyncedDraft,
// The native project lock covers validation, installation and rollback.
_host: Files,
}
@@ -1757,9 +1889,12 @@ impl DraftPublication {
expose_document: impl FnOnce() -> T,
) -> Result<Option<T>, String> {
let Self {
artifacts,
untouched,
untouched_ledger,
synced:
SyncedDraft {
artifacts,
untouched,
untouched_ledger,
},
_host,
} = self;
session.publish_current(revision, || {
@@ -1914,8 +2049,7 @@ impl PreparedOutput {
write: impl FnOnce(&mut File) -> Result<(), String>,
) -> Result<(Self, File), String> {
let (prepared, mut file) = Self::create(output)?;
write(&mut file)
.map_err(|error| format!("stage output {}: {error}", output.display()))?;
write(&mut file).map_err(|error| format!("stage output {}: {error}", output.display()))?;
Ok((prepared, file))
}
@@ -1979,7 +2113,15 @@ impl PreparedOutput {
let path = output.with_file_name(format!(".texrra-{}-{id}.tmp", std::process::id()));
if path != output {
match create(&path) {
Ok(value) => return Ok((Self { path, pending_sync: None }, value)),
Ok(value) => {
return Ok((
Self {
path,
pending_sync: None,
},
value,
));
}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
Err(error) => {
return Err(format!("stage output {}: {error}", output.display()));
@@ -2110,9 +2252,14 @@ mod generated_file_tests {
assert!(!staged.exists());
assert!(!host.draft_paths().contains_key(&ledger_path));
host.finish().unwrap();
let sealed = host.seal_draft(None).unwrap();
let queue = DraftSyncQueue::default();
let cancellation = Cancellation::default();
let sealed = host
.seal_draft(None, &queue, &cancellation)
.unwrap()
.unwrap();
assert_eq!(
sealed.untouched_ledger.as_ref().unwrap().version,
sealed.synced.untouched_ledger.as_ref().unwrap().version,
original_version
);
let permissions = fs::metadata(&ledger_path).unwrap().permissions();
@@ -2151,7 +2298,7 @@ mod generated_file_tests {
let staged = host.draft_paths()[&ledger_path].clone();
let size = fs::metadata(&staged).unwrap().len() as usize;
fs::write(&staged, vec![b'x'; size]).unwrap();
let error = host.seal_draft(None).err().unwrap();
let error = host.seal_draft(None, &queue, &cancellation).err().unwrap();
assert!(error.contains("native staged ledger changed"), "{error}");
assert!(!staged.exists());
assert_eq!(fs::read(&ledger_path).unwrap(), original_ledger);
@@ -2169,8 +2316,14 @@ mod generated_file_tests {
let mut pdf = PreparedOutput::write_for_draft(&output, b"new PDF").unwrap();
let path = pdf.path.clone();
pdf.pending_sync = Some(File::open("/dev/null").unwrap());
let error = host.seal_draft(Some(pdf)).err().unwrap();
assert!(error.contains("sync native draft") && error.contains("job.pdf"), "{error}");
let error = host
.seal_draft(Some(pdf), &queue, &cancellation)
.err()
.unwrap();
assert!(
error.contains("sync native draft") && error.contains("job.pdf"),
"{error}"
);
assert!(!path.exists());
assert_eq!(fs::read(&output).unwrap(), b"already published PDF");
assert_eq!(fs::read(&log).unwrap(), original_log);
@@ -2180,6 +2333,53 @@ mod generated_file_tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn cancelled_draft_sync_releases_the_job_before_private_io_completes() {
let queue = Arc::new(DraftSyncQueue::default());
let cancelled = Cancellation::default();
let (entered, entry) = mpsc::channel();
let (release, held) = mpsc::channel();
let (returned, result) = mpsc::channel();
let (completed, drained) = mpsc::channel();
let old = std::thread::spawn({
let queue = queue.clone();
let cancelled = cancelled.clone();
move || {
let sealed = queue.sync(&cancelled, move |_| {
entered.send(()).unwrap();
held.recv_timeout(Duration::from_secs(5)).unwrap();
completed.send(()).unwrap();
Ok(None)
});
returned.send(sealed).unwrap();
}
});
entry.recv_timeout(Duration::from_secs(3)).unwrap();
cancelled.cancel();
assert!(
result
.recv_timeout(Duration::from_secs(1))
.unwrap()
.unwrap()
.is_none()
);
old.join().unwrap();
assert_eq!(queue.active.load(Ordering::Acquire), 1);
queue
.sync(&Cancellation::default(), {
let queue = queue.clone();
move |_| {
assert_eq!(queue.active.load(Ordering::Acquire), 2);
Ok(None)
}
})
.unwrap();
assert!(matches!(drained.try_recv(), Err(mpsc::TryRecvError::Empty)));
release.send(()).unwrap();
drained.recv_timeout(Duration::from_secs(3)).unwrap();
}
#[test]
fn stream_journal_distinguishes_pinned_bytes_live_handles_replacement_and_finish() {
let root = root();