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

+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();