Skip to main content

latexml/
format_dumps.rs

1//! A format dump for the TeX tree this process reads.
2//!
3//! A dump is the format: the state `latex.ltx` (and the L3 kernel it loads) or `plain.tex` leaves,
4//! built from one TeX tree's files. Packages come raw from the tree the process reads, so a dump
5//! built from another tree is the wrong format for them — `expl3.sty` refuses a format whose L3
6//! kernel date differs from its own ("Mismatched LaTeX support files", expl3.sty:64-78). The 2609
7//! release ran a dump built from `/usr/local/texlive/2025` with `/usr/share/texlive`'s packages, and
8//! 12,144 papers ended as Error (witnesses 2607.28725, 2609.40175).
9//!
10//! Every dump records the files it was built from, and the loaders pass over one this tree does not
11//! have (`latexml_engine::dump_paths::dump_matches_tree`). When no dump found matches, the format
12//! is built here once, as `--init` and fmtutil build it, into a per-user cache keyed by the engine
13//! build and the tree's files, and that dump is used. When it cannot be built, the format loads
14//! from the engine's own definitions, `LoadFormat`'s branch for a missing dump (Perl
15//! Package.pm:2755-2766).
16
17use std::{
18  path::{Path, PathBuf},
19  sync::{
20    Mutex, Once, OnceLock, PoisonError,
21    atomic::{AtomicBool, Ordering},
22  },
23  time::{Duration, Instant},
24};
25
26use latexml_core::util::private_files::{
27  private_dir, private_to_user, publish_read_only, trusted_dir, user_id,
28};
29use latexml_engine::dump_paths;
30
31/// Marks, per format (`.failed.<kind>`), a cache directory where it could not be built, holding the
32/// reason: later processes take the base branch at once instead of building again. The mark lapses
33/// after [`FAILED_LAPSE`]; removing it retries at once.
34const FAILED: &str = ".failed";
35
36/// Counts, per format (`.attempts.<kind>`), the builds into a cache directory that have not
37/// succeeded in a row, with the last one's reason: written before a build, as one that dies with
38/// its process (killed, or a panic in a binary built to abort) records nothing after; removed by a
39/// success, or replaced by the [`FAILED`] mark. A build an interrupt cancels puts it back as it was
40/// ([`cancel_builds_on_interrupt`]).
41const ATTEMPTS: &str = ".attempts";
42
43/// Builds of a format that may fail in a row before it is marked [`FAILED`]: a format that does not
44/// build is not tried by every process, and one passing failure (a full disk, no thread) is not
45/// taken for it.
46const MAX_ATTEMPTS: u32 = 2;
47
48/// How long a [`FAILED`] mark holds: a failure that passes (the disk is cleared, the tree repaired)
49/// is not kept for good.
50const FAILED_LAPSE: Duration = Duration::from_secs(24 * 60 * 60);
51
52/// How long a process waits for another one building into the same directory — far longer than a
53/// build takes, even on a loaded host.
54const LOCK_WAIT: Duration = Duration::from_secs(300);
55
56/// Stamps a cache directory with when it was last used, for [`prune`].
57const LAST_USED: &str = ".last_used";
58
59/// Held, shared, by each process using a cache directory for as long as it runs (it reads its dumps
60/// again for each conversion); a pruner removes only a directory it can lock exclusively.
61const IN_USE: &str = ".inuse";
62
63/// The lock a build into a cache directory holds (exclusive), and a stamp of its use (shared).
64const LOCK: &str = ".lock";
65
66/// The formats a cache directory holds dumps of.
67const KINDS: [&str; 2] = ["plain", "latex"];
68
69/// How stale a use stamp (a cache directory's [`LAST_USED`], an executable's digest) may grow
70/// before a use refreshes it: a file is written once a day, not by every process.
71const STAMP_REFRESH: Duration = Duration::from_secs(24 * 60 * 60);
72
73/// Holds the executables' digests, by file identity ([`executable_digest`]).
74const BINARIES: &str = ".binaries";
75
76/// How long a cache directory of another build or tree may go unused before it is pruned.
77const PRUNE_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
78
79/// The cache directories of other builds or trees kept however long unused: the last used, as a
80/// user switching between a few binaries or trees keeps them.
81const KEEP_NEWEST: usize = 3;
82
83/// How often the cache is pruned: [`LAST_PRUNE`] stamps the last sweep, [`PRUNE_LOCK`] keeps it to
84/// one process at a time. Both in the private [`BINARIES`]: the base is often group-writable, where
85/// another user could put a link to a file of this user's in their place, which opening would truncate.
86const PRUNE_EVERY: Duration = Duration::from_secs(24 * 60 * 60);
87const LAST_PRUNE: &str = ".last_prune";
88const PRUNE_LOCK: &str = ".prune.lock";
89
90/// The prefix of a pruned directory on its way out (`.trash-<removal time>-<pid>-<name>`); one a
91/// killed pruner left is removed [`TRASH_LAPSE`] after its removal time (a rename keeps the
92/// directory's modification time).
93const TRASH: &str = ".trash-";
94const TRASH_LAPSE: Duration = Duration::from_secs(60 * 60);
95
96/// The cache directory this process uses, stamped again at each later conversion, and its [`IN_USE`]
97/// lock, held to the process's end: a long-running `--server`'s is not pruned while it runs.
98static CACHE_IN_USE: OnceLock<CacheInUse> = OnceLock::new();
99
100struct CacheInUse {
101  dir:    PathBuf,
102  _inuse: Option<std::fs::File>,
103}
104
105/// The exit status of a process an interrupt ends while it builds a format: a shell's for Ctrl+C
106/// (128 + SIGINT).
107const INTERRUPTED: i32 = 130;
108
109/// Whether an interrupt cancels a build ([`cancel_builds_on_interrupt`]).
110static CANCEL_ON_INTERRUPT: AtomicBool = AtomicBool::new(false);
111
112/// The build this process is running, as an interrupt would undo it ([`cancel_in_flight_build`]).
113static IN_FLIGHT: Mutex<Option<InFlight>> = Mutex::new(None);
114
115/// What a running build has left in its cache directory.
116struct InFlight {
117  /// The build's [`ATTEMPTS`] note, and what it held before the build (`None`: no note).
118  attempts: PathBuf,
119  before:   Option<String>,
120  /// The dump being written.
121  partial:  PathBuf,
122}
123
124/// Makes an interrupt that ends this process while it builds a format dump a cancellation, not a
125/// failed build (issue 988): the build's attempt note goes back to what it held before the build,
126/// its partial dump is removed, and the process exits with status 130. The next process builds the
127/// format again, where an interrupted build used to count towards marking it failed (`.failed.<kind>`), so two
128/// interrupts left every conversion for a day on the engine's own definitions. The interrupts are
129/// Ctrl+C and, on Unix, SIGTERM and SIGHUP (on Windows, Ctrl+Break and closing the console). For a
130/// front end its user interrupts (the `latexml_oxide` CLI's conversions); an embedder that handles
131/// signals itself leaves it off. The handler is installed when the process starts its first build,
132/// so a process that builds nothing keeps its default interrupt. One that builds keeps the handler
133/// to its end: a later SIGTERM or SIGHUP ends it with status 130, not by the signal, since neither
134/// ctrlc nor a safe `signal`/`sigaction` can put the default action back. A process that ignores or
135/// handles any of these signals already (`nohup`, a shell's background job) keeps them as they are,
136/// and an interrupted build there counts as before.
137pub fn cancel_builds_on_interrupt() { CANCEL_ON_INTERRUPT.store(true, Ordering::Release); }
138
139/// Installs, once per process, the interrupt handler [`cancel_builds_on_interrupt`] asks for.
140fn install_interrupt_handler() {
141  static INSTALLED: Once = Once::new();
142  INSTALLED.call_once(|| {
143    // `try_`: a signal the process already ignores or handles stays so (ctrlc's `MultipleHandlers`).
144    let installed = ctrlc::try_set_handler(|| {
145      // The record stays locked until the process ends, so the build cannot record an outcome after
146      // its undo (`set_in_flight` waits).
147      let mut slot = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
148      if let Some(build) = slot.take() {
149        undo(build);
150        note(log::Level::Info, format_args!(
151          "\n[format_dumps] interrupted: the format build was cancelled; the next conversion builds it again"
152        ));
153      }
154      // `_exit`: the build's thread still runs, and `exit` would run libxml2's destructor under it (#973). The
155      // note above is written (stderr is unbuffered) and the undo is on disk.
156      latexml_core::watchdog::exit_now(INTERRUPTED);
157    });
158    if let Err(e @ ctrlc::Error::System(_)) = installed {
159      note(log::Level::Warn, format_args!(
160        "[format_dumps] cannot take the interrupt ({e}): a build interrupted now counts as one that failed"
161      ));
162    }
163  });
164}
165
166/// A line of `level` on stderr, as a logged record of it would print: `--quiet` hides an Info or Warning note,
167/// never an Error (OXIDIZED_DESIGN_DIVERGENCES #1158).
168fn note(level: log::Level, args: std::fmt::Arguments) {
169  if level <= log::Level::Error || latexml_core::util::logger::stderr_admits(level) {
170    eprintln!("{args}");
171  }
172}
173
174/// Undoes the format build this process is running, if any (the interrupt handler's undo, without
175/// its exit). Whether a build was running.
176#[cfg(test)]
177fn cancel_in_flight_build() -> bool {
178  let build = IN_FLIGHT
179    .lock()
180    .unwrap_or_else(PoisonError::into_inner)
181    .take();
182  build.map(undo).is_some()
183}
184
185/// Undoes a format build: its attempt note goes back to what it held before the build and its
186/// partial dump is removed.
187fn undo(build: InFlight) {
188  match build.before {
189    Some(before) => {
190      let _ = std::fs::write(&build.attempts, before);
191    },
192    None => {
193      let _ = std::fs::remove_file(&build.attempts);
194    },
195  }
196  // (On Windows a file the build still has open stays; the next build removes it, `remove_partial_dumps`.)
197  let _ = std::fs::remove_file(&build.partial);
198}
199
200/// Records the build this process starts or ends ([`IN_FLIGHT`]).
201fn set_in_flight(build: Option<InFlight>) {
202  *IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner) = build;
203}
204
205/// Ensures each format has a dump built from this process's TeX tree, building any that has none
206/// into the cache. Once per process, before the first session loads a format; nothing to do without
207/// a TeX tree, under `LATEXML_NODUMP`, or while a format is being built (`--init`, or the thread
208/// building one here). A format that cannot be built is reported once, as a Warning on stderr (not
209/// under `--quiet`) and in each conversion's log (`converter::note_format_build_failure`), and
210/// loads from the engine's definitions. A build changes the process's working directory while
211/// it runs (see `build`), so it belongs before the process converts anything.
212pub fn ensure_format_dumps() {
213  if dump_paths::building_format() {
214    return;
215  }
216  static ENSURED: OnceLock<()> = OnceLock::new();
217  ENSURED.get_or_init(|| {
218    // Once per TeX tree, not the document's work: off the conversion's `--timeout`, which a busy host's build outlasted
219    // and, killed twice, marked the format failed. Bounded (under a non-zero `--timeout`) by the lock wait and a build.
220    let ensured = latexml_core::watchdog::off_the_clock(
221      "the format build",
222      LOCK_WAIT + Duration::from_secs(300),
223      ensure,
224    );
225    if let Err(reason) = ensured {
226      // A Warning, as each conversion logs it (`converter::note_format_build_failure`).
227      note(log::Level::Warn, format_args!(
228        "[format_dumps] {reason}: the format loads from the engine's own definitions instead of a dump"
229      ));
230      dump_paths::set_format_build_failure(reason);
231    }
232  });
233  if let Some(in_use) = CACHE_IN_USE.get() {
234    refresh_last_used(&in_use.dir);
235  }
236}
237
238fn ensure() -> Result<(), String> {
239  if std::env::var_os("LATEXML_NODUMP").is_some() || dump_paths::ini_mode() {
240    return Ok(());
241  }
242  let kinds: Vec<&'static str> = ["plain", "latex"]
243    .into_iter()
244    .filter(|kind| dump_paths::runtime_source_stamps(kind).is_some())
245    .collect();
246  if kinds.is_empty() {
247    return Ok(());
248  }
249  // A dump the configuration names, installs or keeps beside the sources is used before the cache's;
250  // the embedded one only after it, as reading it back costs every process a 4 MB dump.
251  let wanted: Vec<&'static str> = kinds
252    .into_iter()
253    .filter(|kind| !dump_paths::format_dump_on_disk(kind))
254    .collect();
255  if wanted.is_empty() {
256    return Ok(());
257  }
258  // Only the dump's file name carries the year.
259  let year = dump_paths::detect_ambient_texlive_year().unwrap_or(2000);
260  let dir = match cache_dir() {
261    Ok(dir) => dir,
262    Err(_)
263      if wanted
264        .iter()
265        .all(|kind| dump_paths::format_dump_available(kind)) =>
266    {
267      return Ok(());
268    },
269    Err(reason) => return Err(reason),
270  };
271  // Before its dumps are found: a pruner re-reads the stamp under the lock the refresh takes, and
272  // removes no directory whose `.inuse` a process holds.
273  refresh_last_used(&dir);
274  let mut in_use = if trusted_dir(&dir) {
275    hold_in_use(&dir)
276  } else {
277    None
278  };
279  let ensured = ensure_in(&dir, year, wanted);
280  if trusted_dir(&dir) {
281    refresh_last_used(&dir);
282    // A directory this process has just made.
283    if in_use.is_none() {
284      in_use = hold_in_use(&dir);
285    }
286    let _ = CACHE_IN_USE.set(CacheInUse {
287      _inuse: in_use,
288      dir:    dir.clone(),
289    });
290  }
291  if let Some(base) = dir.parent() {
292    prune(base, &dir);
293  }
294  ensured
295}
296
297/// Finds the `wanted` dumps in the cache directory `dir`, building those it does not hold.
298fn ensure_in(dir: &Path, year: u32, wanted: Vec<&'static str>) -> Result<(), String> {
299  // Each kind uses the cache's dump on its own merits.
300  let use_cached = |kind: &str| match cached_dump(dir, kind, year) {
301    Some((path, found_year)) => {
302      dump_paths::set_rebuilt_dump(kind, path, found_year);
303      true
304    },
305    None => false,
306  };
307  let missing: Vec<&'static str> = wanted
308    .into_iter()
309    .filter(|kind| !use_cached(kind) && !dump_paths::format_dump_available(kind))
310    .collect();
311  if missing.is_empty() {
312    return Ok(());
313  }
314  private_dir(dir)?;
315  let mut reasons = Vec::new();
316  let missing: Vec<&'static str> = missing
317    .into_iter()
318    .filter(|kind| match failed_before(dir, kind) {
319      Some(reason) => {
320        reasons.push(reason);
321        false
322      },
323      None => true,
324    })
325    .collect();
326  if !missing.is_empty() {
327    // What the builds so far have left, to tell whether one failed while this process waited. (A
328    // build that fails between this read and its release of the lock goes unseen: the window is
329    // the few instructions between its last write and its unlock.)
330    let seen: Vec<Option<String>> = missing
331      .iter()
332      .map(|kind| attempts_text(dir, kind))
333      .collect();
334    // One process builds; the others wait for it and find the dump, or its failure.
335    let _lock = match lock_dir(dir) {
336      Ok(lock) => lock,
337      Err(reason) => {
338        reasons.push(reason);
339        return Err(reasons.join("; "));
340      },
341    };
342    // No other process builds here while this one holds the lock: a partial dump is a killed
343    // build's.
344    remove_partial_dumps(dir);
345    for (kind, seen) in missing.into_iter().zip(seen) {
346      // Built by the process this one waited for.
347      if use_cached(kind) {
348        continue;
349      }
350      if let Some(reason) = failed_before(dir, kind) {
351        reasons.push(reason);
352        continue;
353      }
354      // A build that failed while this process waited is not tried again at once: a passing
355      // failure would likely recur, and a later process retries it.
356      let now = attempts_text(dir, kind);
357      if now.is_some() && now != seen {
358        reasons.push(previous_attempts(dir, kind).1);
359        continue;
360      }
361      if let Err(reason) = attempt(kind, year, dir, &use_cached) {
362        reasons.push(reason);
363      }
364    }
365  }
366  if reasons.is_empty() {
367    Ok(())
368  } else {
369    Err(reasons.join("; "))
370  }
371}
372
373/// Builds the `kind` dump into `dir`, counting it until it succeeds and marking the format
374/// [`FAILED`] after [`MAX_ATTEMPTS`] builds in a row that did not.
375fn attempt(
376  kind: &'static str,
377  year: u32,
378  dir: &Path,
379  use_cached: &dyn Fn(&str) -> bool,
380) -> Result<(), String> {
381  let (failed, last_reason) = previous_attempts(dir, kind);
382  if failed >= MAX_ATTEMPTS {
383    return Err(mark_failed(dir, kind, &last_reason));
384  }
385  // Installed before the build leaves anything to undo, so an interrupt always finds what it left.
386  if CANCEL_ON_INTERRUPT.load(Ordering::Acquire) {
387    install_interrupt_handler();
388  }
389  {
390    // What an interrupt undoes is recorded and its note written under one lock: an interrupt
391    // meanwhile waits, then undoes both (it could otherwise undo before the note was written).
392    let mut slot = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
393    *slot = Some(InFlight {
394      attempts: kind_file(dir, ATTEMPTS, kind),
395      before:   attempts_text(dir, kind),
396      partial:  partial_dump(dir, kind, year),
397    });
398    if let Err(reason) = note_attempt(
399      dir,
400      kind,
401      failed + 1,
402      &format!("the {kind} format build died with its process"),
403    ) {
404      *slot = None;
405      return Err(reason);
406    }
407  }
408  note(
409    log::Level::Info,
410    format_args!(
411      "[format_dumps] no {kind} dump matches this TeX tree; building one into {} (once for this tree; later \
412     conversions reuse it)",
413      dir.display()
414    ),
415  );
416  let built = build(kind, year, dir);
417  // The build has ended (a published dump cleared the record as it was published, `publish`): what
418  // follows records its outcome, which an interrupt no longer undoes.
419  set_in_flight(None);
420  let built = built.and_then(|()| {
421    if use_cached(kind) {
422      Ok(())
423    } else {
424      Err(format!(
425        "the {kind} dump built into {} does not match this TeX tree",
426        dir.display()
427      ))
428    }
429  });
430  match built {
431    Ok(()) => {
432      let _ = std::fs::remove_file(kind_file(dir, ATTEMPTS, kind));
433      Ok(())
434    },
435    Err(reason) => {
436      let _ = note_attempt(dir, kind, failed + 1, &reason);
437      if failed + 1 >= MAX_ATTEMPTS {
438        Err(mark_failed(dir, kind, &reason))
439      } else {
440        Err(reason)
441      }
442    },
443  }
444}
445
446/// `dir`'s `marker` file (`.attempts`, `.failed`) for the `kind` format.
447fn kind_file(dir: &Path, marker: &str, kind: &str) -> PathBuf {
448  dir.join(format!("{marker}.{kind}"))
449}
450
451/// What the builds of the `kind` format into `dir` that have not succeeded have recorded.
452fn attempts_text(dir: &Path, kind: &str) -> Option<String> {
453  std::fs::read_to_string(kind_file(dir, ATTEMPTS, kind)).ok()
454}
455
456/// The builds of the `kind` format into `dir` that have not succeeded in a row so far, and the last
457/// one's reason.
458fn previous_attempts(dir: &Path, kind: &str) -> (u32, String) {
459  let Some(text) = attempts_text(dir, kind) else {
460    return (0, String::new());
461  };
462  let (count, reason) = text.split_once('\t').unwrap_or((&text, ""));
463  let reason = if reason.is_empty() {
464    format!("the {kind} format build did not succeed")
465  } else {
466    reason.to_string()
467  };
468  (count.trim().parse().unwrap_or(1), reason)
469}
470
471/// Records that the `count`th build of the `kind` format into `dir` in a row has not succeeded
472/// (yet), and why.
473fn note_attempt(dir: &Path, kind: &str, count: u32, reason: &str) -> Result<(), String> {
474  let path = kind_file(dir, ATTEMPTS, kind);
475  std::fs::write(&path, format!("{count}\t{reason}"))
476    .map_err(|e| format!("cannot write {}: {e}", path.display()))
477}
478
479/// Marks the `kind` format as one that could not be built into `dir`, and says so. The mark holds
480/// the reason in place of the count, so removing it gives the format fresh attempts.
481fn mark_failed(dir: &Path, kind: &str, reason: &str) -> String {
482  let path = kind_file(dir, FAILED, kind);
483  if std::fs::write(&path, reason).is_ok() {
484    let _ = std::fs::remove_file(kind_file(dir, ATTEMPTS, kind));
485  }
486  failure_message(&path, reason)
487}
488
489/// The failure a [`FAILED`] mark at `path` records, with how to retry.
490fn failure_message(path: &Path, reason: &str) -> String {
491  format!(
492    "no dump matches this TeX tree and none could be built ({reason}; remove {} to retry)",
493    path.display()
494  )
495}
496
497/// Where dumps built here go: `$LATEXML_FORMAT_CACHE`, else the user's cache directory
498/// (`$XDG_CACHE_HOME`, `~/.cache`, when absolute), else the temp dir under the user's id — one
499/// directory per engine build and TeX tree, so a process reuses what an earlier one built. The build
500/// is the executable's content ([`executable_digest`]) beside the version: the embedded git revision
501/// is the one `build.rs` last saw, and a dump is the engine's as much as the tree's. Absolute, as the
502/// build runs in it.
503fn cache_dir() -> Result<PathBuf, String> {
504  let base = cache_base(|name| std::env::var_os(name))?;
505  let tree: String = ["plain", "latex"]
506    .into_iter()
507    .filter_map(dump_paths::runtime_source_stamps)
508    .flatten()
509    .map(|stamp| format!("{:08x}", stamp.checksum))
510    .collect::<Vec<_>>()
511    .join("-");
512  let build = build_key(&running_executable()?, |exe| executable_digest(&base, exe))?;
513  Ok(base.join(format!("{}-{build}-{tree}", crate::identity::VERSION)))
514}
515
516/// The build part of a cache key: the first 16 hex digits of the executable's `digest`; for an
517/// executable this user cannot read (installed 0711), `m<size>.<modification time>` in hex, the key
518/// before issue 1023, which a digest prefix never equals.
519fn build_key(
520  exe: &Path,
521  digest: impl FnOnce(&Path) -> Result<String, String>,
522) -> Result<String, String> {
523  match digest(exe) {
524    Ok(digest) => Ok(digest[..16].to_string()),
525    Err(unreadable) => {
526      let meta = std::fs::metadata(exe).map_err(|_| unreadable)?;
527      let modified = meta
528        .modified()
529        .ok()
530        .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
531        .map_or(0, |since| since.as_nanos());
532      Ok(format!("m{:x}.{modified:x}", meta.len()))
533    },
534  }
535}
536
537/// Whether `name` is a cache key: `<version>-<build>-<tree>`, the build a digest prefix (16 hex
538/// digits) or `m<size>.<mtime>` ([`build_key`]), or before issue 1023 `<size>-<mtime>` or nothing,
539/// and the tree one or more 8-digit checksums. A directory of another name is not the cache's.
540fn is_cache_key(name: &str) -> bool {
541  let hex = |s: &str| !s.is_empty() && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
542  let version = |segments: &[&str]| {
543    segments.first().is_some_and(|first| {
544      first.starts_with(|c: char| c.is_ascii_digit())
545        && segments
546          .iter()
547          .all(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '.'))
548    })
549  };
550  let build_and_version = |head: &[&str]| match head {
551    [rest @ .., build] if build.len() == 16 && hex(build) => version(rest),
552    [rest @ .., build]
553      if build
554        .strip_prefix('m')
555        .and_then(|b| b.split_once('.'))
556        .is_some_and(|(size, mtime)| hex(size) && hex(mtime)) =>
557    {
558      version(rest)
559    },
560    [rest @ .., size, mtime] if hex(size) && hex(mtime) && version(rest) => true,
561    [rest @ .., ""] => version(rest),
562    _ => false,
563  };
564  let segments: Vec<&str> = name.split('-').collect();
565  (1..segments.len()).any(|k| {
566    let (head, tree) = segments.split_at(segments.len() - k);
567    tree.iter().all(|s| s.len() == 8 && hex(s)) && build_and_version(head)
568  })
569}
570
571/// Whether `name` is a file the cache writes into a cache directory: its locks and stamps, a format's
572/// dump (`<kind>.<year>.dump.txt`), a build's partial dump (`.<dump>.<pid>.partial`), and a format's
573/// attempt note and failure mark (`.attempts.<kind>`, `.failed.<kind>`; `.failed` before 0.8.0).
574fn is_cache_file(name: &str) -> bool {
575  let dump = |name: &str| {
576    name
577      .strip_suffix(".dump.txt")
578      .and_then(|stem| stem.split_once('.'))
579      .is_some_and(|(kind, year)| {
580        KINDS.contains(&kind) && !year.is_empty() && year.bytes().all(|b| b.is_ascii_digit())
581      })
582  };
583  let partial = || {
584    name
585      .strip_prefix('.')
586      .and_then(|name| name.strip_suffix(".partial"))
587      .and_then(|name| name.rsplit_once('.'))
588      .is_some_and(|(dump_name, pid)| {
589        dump(dump_name) && !pid.is_empty() && pid.bytes().all(|b| b.is_ascii_digit())
590      })
591  };
592  let marker = |marker: &str| {
593    name
594      .strip_prefix(marker)
595      .and_then(|kind| kind.strip_prefix('.'))
596      .is_some_and(|kind| KINDS.contains(&kind))
597  };
598  [LOCK, LAST_USED, IN_USE, FAILED].contains(&name)
599    || dump(name)
600    || partial()
601    || marker(ATTEMPTS)
602    || marker(FAILED)
603}
604
605/// Whether the directory `dir` holds only files the cache writes ([`is_cache_file`]), and its lock or
606/// use stamp: what a pruner may remove whole. A file or directory of anyone else's keeps it.
607fn holds_only_cache_files(dir: &Path) -> bool {
608  let Ok(entries) = std::fs::read_dir(dir) else {
609    return false;
610  };
611  let mut stamped = false;
612  for entry in entries {
613    let Ok(entry) = entry else {
614      return false;
615    };
616    let name = entry.file_name();
617    let Some(name) = name.to_str() else {
618      return false;
619    };
620    if !entry.file_type().is_ok_and(|kind| kind.is_file()) || !is_cache_file(name) {
621      return false;
622    }
623    stamped |= name == LOCK || name == LAST_USED;
624  }
625  stamped
626}
627
628/// The directory holding the cache's directories, from the environment `var` reads.
629fn cache_base(var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Result<PathBuf, String> {
630  let absolute_var = |name: &str| var(name).map(PathBuf::from).filter(|dir| dir.is_absolute());
631  let base = var("LATEXML_FORMAT_CACHE")
632    .map(PathBuf::from)
633    .or_else(|| absolute_var("XDG_CACHE_HOME").map(|dir| dir.join("latexml-oxide/formats")))
634    .or_else(|| absolute_var("HOME").map(|dir| dir.join(".cache/latexml-oxide/formats")))
635    .unwrap_or_else(|| std::env::temp_dir().join(format!("latexml-oxide-formats-{}", user_id())));
636  std::path::absolute(&base)
637    .map_err(|e| format!("cannot place the format cache {}: {e}", base.display()))
638}
639
640/// The file this process runs from. On Linux `/proc/self/exe`, which still opens the running image
641/// after the file was replaced or removed (a fleet binary swapped under its workers).
642fn running_executable() -> Result<PathBuf, String> {
643  if cfg!(target_os = "linux") && Path::new("/proc/self/exe").exists() {
644    return Ok(PathBuf::from("/proc/self/exe"));
645  }
646  std::env::current_exe().map_err(|e| format!("cannot find this executable: {e}"))
647}
648
649/// The SHA-256 of the executable at `exe`, in hex: a copy keeps it, and two builds differ in it
650/// whatever their size and modification time (issue 1023; mtime-normalising packagers give every
651/// file one time). Remembered in `<base>/.binaries`, by the file's identity
652/// ([`file_identity`]), so each file is read once.
653fn executable_digest(base: &Path, exe: &Path) -> Result<String, String> {
654  use std::io::Read;
655
656  use sha2::{Digest, Sha256};
657  let unreadable = |e: std::io::Error| format!("cannot read {}: {e}", exe.display());
658  let mut file = std::fs::File::open(exe).map_err(unreadable)?;
659  // The identity of the file read here, not of a path that may meanwhile name another.
660  let meta = file.metadata().map_err(unreadable)?;
661  let memo_dir = base.join(BINARIES);
662  let memo = memo_dir.join(file_identity(exe, &meta));
663  if trusted_dir(&memo_dir) && private_to_user(&memo) {
664    let remembered = std::fs::read_to_string(&memo).unwrap_or_default();
665    if remembered.len() == 64 && remembered.bytes().all(|b| b.is_ascii_hexdigit()) {
666      touch_if_stale(&memo);
667      return Ok(remembered);
668    }
669  }
670  let mut hasher = Sha256::new();
671  let mut buf = vec![0u8; 1 << 20];
672  loop {
673    match file.read(&mut buf).map_err(unreadable)? {
674      0 => break,
675      n => hasher.update(&buf[..n]),
676    }
677  }
678  let digest = hex(&hasher.finalize());
679  // Remembered where it can be; a cache it cannot write hashes the executable each time.
680  if private_dir(&memo_dir).is_ok() {
681    let partial = memo.with_extension(format!("{}.partial", std::process::id()));
682    // Not under the umask: a file another user could write is not read back (`private_to_user`).
683    let written = std::fs::write(&partial, &digest)
684      .and_then(|()| publish_read_only(&partial))
685      .and_then(|()| std::fs::rename(&partial, &memo));
686    if written.is_err() {
687      let _ = std::fs::remove_file(&partial);
688    }
689  }
690  Ok(digest)
691}
692
693/// Names a file by what changes when it is replaced or rewritten: on Unix its device, inode, size,
694/// modification and change times; elsewhere the fields std exposes there (path, size, modification
695/// and creation times). Hashed, to make a file name.
696fn file_identity(exe: &Path, meta: &std::fs::Metadata) -> String {
697  use sha2::{Digest, Sha256};
698  #[cfg(unix)]
699  let identity = {
700    use std::os::unix::fs::MetadataExt;
701    let _ = exe;
702    format!(
703      "{}:{}:{}:{}.{}:{}.{}",
704      meta.dev(),
705      meta.ino(),
706      meta.size(),
707      meta.mtime(),
708      meta.mtime_nsec(),
709      meta.ctime(),
710      meta.ctime_nsec()
711    )
712  };
713  #[cfg(not(unix))]
714  let identity = {
715    let nanos = |time: std::io::Result<std::time::SystemTime>| {
716      time
717        .ok()
718        .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
719        .map_or(0, |since| since.as_nanos())
720    };
721    format!(
722      "{}:{}:{}:{}",
723      exe.display(),
724      meta.len(),
725      nanos(meta.modified()),
726      nanos(meta.created())
727    )
728  };
729  hex(&Sha256::digest(identity.as_bytes()))[..32].to_string()
730}
731
732/// Lowercase hex of `bytes`.
733fn hex(bytes: &[u8]) -> String {
734  use std::fmt::Write as _;
735  bytes.iter().fold(String::new(), |mut out, byte| {
736    let _ = write!(out, "{byte:02x}");
737    out
738  })
739}
740
741/// Sets the modification time of `path` to now when it is older than [`STAMP_REFRESH`]: one write
742/// a day marks a file in use. Whether `path` is now fresh.
743fn touch_if_stale(path: &Path) -> bool {
744  if age(path).is_some_and(|age| age < STAMP_REFRESH) {
745    return true;
746  }
747  open_to_lock(path, true)
748    .and_then(|file| file.set_modified(std::time::SystemTime::now()))
749    .is_ok()
750}
751
752/// How long ago `path` was modified.
753fn age(path: &Path) -> Option<Duration> {
754  std::fs::metadata(path)
755    .and_then(|meta| meta.modified())
756    .ok()
757    .and_then(|time| time.elapsed().ok())
758}
759
760/// When the cache directory `dir` was last used: its [`LAST_USED`] stamp; without one (a directory
761/// being built, or one a version before the stamp uses) the later of the directory's modification
762/// time and its dumps' last read.
763fn last_used(dir: &Path) -> Option<std::time::SystemTime> {
764  let modified = |path: &Path| {
765    std::fs::metadata(path)
766      .and_then(|meta| meta.modified())
767      .ok()
768  };
769  if let Some(stamp) = modified(&dir.join(LAST_USED)) {
770    return Some(stamp);
771  }
772  let read = std::fs::read_dir(dir)
773    .into_iter()
774    .flatten()
775    .flatten()
776    .filter(|entry| entry.file_name().to_string_lossy().ends_with(".dump.txt"))
777    .filter_map(|entry| entry.metadata().and_then(|meta| meta.accessed()).ok());
778  modified(dir).into_iter().chain(read).max()
779}
780
781/// Marks the cache directory `dir` used now, if it is this user's and its stamp is older than
782/// [`STAMP_REFRESH`]. Under a shared lock on `dir`'s `.lock`, which a pruner holds exclusively while
783/// it reads the stamp and removes the directory: so a directory is either removed before this
784/// process reads its dumps, which it then does not find, or stamped, and not removed. A `.lock` it
785/// cannot open (a link, a FIFO) it stamps without: a pruner cannot open it either, and leaves `dir`.
786fn refresh_last_used(dir: &Path) {
787  let stamp = dir.join(LAST_USED);
788  if age(&stamp).is_some_and(|age| age < STAMP_REFRESH) || !trusted_dir(dir) {
789    return;
790  }
791  let lock = open_to_lock(&dir.join(LOCK), true);
792  // Held exclusively by a pruner for an instant, or by a build into `dir`, which this waits for as
793  // `lock_dir` does.
794  if let Ok(lock) = &lock {
795    lock_shared_waiting(lock);
796  }
797  if dir.is_dir() {
798    touch_if_stale(&stamp);
799  }
800}
801
802/// Takes a shared lock on `file`, waiting up to [`LOCK_WAIT`] while another process holds it
803/// exclusively; past that, goes on without it.
804fn lock_shared_waiting(file: &std::fs::File) {
805  let deadline = Instant::now() + LOCK_WAIT;
806  while let Err(std::fs::TryLockError::WouldBlock) = file.try_lock_shared() {
807    if Instant::now() >= deadline {
808      break;
809    }
810    std::thread::sleep(Duration::from_millis(100));
811  }
812}
813
814/// Opens the cache directory `dir`'s [`IN_USE`] file and holds it shared ([`CACHE_IN_USE`] keeps
815/// it to the process's end): a process that keeps reading the directory's dumps is never pruned,
816/// whatever its stamp (a version before the stamp, or a clock gone wrong). One it cannot open (a
817/// link, a FIFO) it goes on without: a pruner cannot open it either, and leaves `dir`.
818fn hold_in_use(dir: &Path) -> Option<std::fs::File> {
819  let path = dir.join(IN_USE);
820  // A pruner may move the directory to the trash between the open and the lock: the lock is then
821  // on the trashed file, and the directory, if made again, is opened afresh.
822  for _ in 0..3 {
823    let file = open_to_lock(&path, true).ok()?;
824    lock_shared_waiting(&file);
825    if same_file(&file, &path) {
826      return Some(file);
827    }
828  }
829  None
830}
831
832/// Whether the open `file` is still the file at `path`.
833#[cfg(unix)]
834fn same_file(file: &std::fs::File, path: &Path) -> bool {
835  use std::os::unix::fs::MetadataExt;
836  match (file.metadata(), std::fs::symlink_metadata(path)) {
837    (Ok(open), Ok(named)) => open.dev() == named.dev() && open.ino() == named.ino(),
838    _ => false,
839  }
840}
841/// Off Unix a directory holding an open file is not renamed.
842#[cfg(not(unix))]
843fn same_file(_file: &std::fs::File, path: &Path) -> bool { path.is_file() }
844
845/// Opens the file at `path` to lock or stamp it, made if `create` and never truncated, following no
846/// symbolic link and waiting on no FIFO: anything but a regular file is an error.
847fn open_to_lock(path: &Path, create: bool) -> std::io::Result<std::fs::File> {
848  let mut options = std::fs::OpenOptions::new();
849  options.write(true).create(create).truncate(false);
850  #[cfg(unix)]
851  {
852    use std::os::unix::fs::OpenOptionsExt;
853    options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
854  }
855  let file = options.open(path)?;
856  if file.metadata()?.is_file() {
857    Ok(file)
858  } else {
859    Err(std::io::Error::other(format!(
860      "{} is not a regular file",
861      path.display()
862    )))
863  }
864}
865
866/// Removes, at most once per [`PRUNE_EVERY`], the cache directories of other builds or trees in
867/// `base` that have gone unused for [`PRUNE_AFTER`] ([`sweep`]). One process sweeps at a time
868/// ([`PRUNE_LOCK`]); a cache directory this user does not own, or one another user could write to,
869/// is left alone. `base` need only be this user's: it is made under the umask, often group-writable,
870/// so the sweep's own files are in the private [`BINARIES`].
871fn prune(base: &Path, current: &Path) {
872  let binaries = base.join(BINARIES);
873  let last_prune = binaries.join(LAST_PRUNE);
874  if !owned_by_user(base) || age(&last_prune).is_some_and(|age| age < PRUNE_EVERY) {
875    return;
876  }
877  if private_dir(&binaries).is_err() {
878    return;
879  }
880  let Ok(lock) = open_to_lock(&binaries.join(PRUNE_LOCK), true) else {
881    return;
882  };
883  if lock.try_lock().is_err()
884    || age(&last_prune).is_some_and(|age| age < PRUNE_EVERY)
885    || !touch_if_stale(&last_prune)
886  {
887    return;
888  }
889  sweep(base, current, std::time::SystemTime::now());
890}
891
892/// Whether `path` is a directory of this user's, not a symbolic link.
893#[cfg(unix)]
894fn owned_by_user(path: &Path) -> bool {
895  use std::os::unix::fs::MetadataExt;
896  std::fs::symlink_metadata(path).is_ok_and(|meta| meta.is_dir() && meta.uid() == user_id())
897}
898/// No ownership to check off Unix.
899#[cfg(not(unix))]
900fn owned_by_user(path: &Path) -> bool { path.is_dir() }
901
902/// Removes from `base`, as of `now`: the cache directories other than `current` unused for
903/// [`PRUNE_AFTER`], except the [`KEEP_NEWEST`] last used; the executables' digests
904/// ([`executable_digest`]) unread for as long; and the trash a pruner killed mid-removal left. A
905/// cache directory is one named as a key ([`is_cache_key`]) holding only what the cache writes
906/// ([`holds_only_cache_files`]): `$LATEXML_FORMAT_CACHE` may name a directory holding more.
907fn sweep(base: &Path, current: &Path, now: std::time::SystemTime) {
908  let older_than = |time: Option<std::time::SystemTime>, lapse: Duration| {
909    time.is_some_and(|time| now.duration_since(time).is_ok_and(|age| age > lapse))
910  };
911  let Ok(entries) = std::fs::read_dir(base) else {
912    return;
913  };
914  let mut caches = Vec::new();
915  for entry in entries.flatten() {
916    let path = entry.path();
917    let Some(name) = entry.file_name().to_str().map(str::to_string) else {
918      continue;
919    };
920    if !private_to_user(&path) || path == current {
921      continue;
922    }
923    if name == BINARIES {
924      for memo in std::fs::read_dir(&path).into_iter().flatten().flatten() {
925        let memo_name = memo.file_name();
926        let memo_name = memo_name.to_string_lossy();
927        // A digest (`<identity>`, `<identity>.<pid>.partial`), not the sweep's own files.
928        let digest = memo_name.split('.').next().is_some_and(|identity| {
929          identity.len() == 32 && identity.bytes().all(|b| b.is_ascii_hexdigit())
930        });
931        if digest && older_than(memo.metadata().and_then(|m| m.modified()).ok(), PRUNE_AFTER) {
932          let _ = std::fs::remove_file(memo.path());
933        }
934      }
935    } else if let Some(trashed) = name.strip_prefix(TRASH) {
936      // `<removal time>-<pid>-<key>`, holding what is left of a cache directory.
937      let removed = trashed
938        .split_once('-')
939        .and_then(|(secs, rest)| Some((secs.parse::<u64>().ok()?, rest.split_once('-')?)))
940        .filter(|(_, (pid, key))| pid.parse::<u32>().is_ok() && is_cache_key(key))
941        .map(|(secs, _)| std::time::UNIX_EPOCH + Duration::from_secs(secs));
942      if removed.is_some()
943        && older_than(removed, TRASH_LAPSE)
944        && holds_only_cache_files_or_nothing(&path)
945      {
946        let _ = std::fs::remove_dir_all(&path);
947      }
948    } else if is_cache_key(&name) && holds_only_cache_files(&path) {
949      caches.push((last_used(&path), path, name));
950    }
951  }
952  caches.sort_by_key(|cache| std::cmp::Reverse(cache.0));
953  for (used, dir, name) in caches.into_iter().skip(KEEP_NEWEST) {
954    if older_than(used, PRUNE_AFTER) {
955      remove_cache(base, &dir, &name, now, |dir| {
956        older_than(last_used(dir), PRUNE_AFTER)
957      });
958    }
959  }
960}
961
962/// Whether the trashed directory `dir` holds nothing but files the cache writes: a pruner removes
963/// some of them before it is killed.
964fn holds_only_cache_files_or_nothing(dir: &Path) -> bool {
965  std::fs::read_dir(dir).is_ok_and(|mut entries| {
966    entries.all(|entry| {
967      entry.is_ok_and(|entry| {
968        entry.file_type().is_ok_and(|kind| kind.is_file())
969          && entry.file_name().to_str().is_some_and(is_cache_file)
970      })
971    })
972  })
973}
974
975/// Removes the cache directory `dir` (named `name`, in `base`) if no process holds its [`LOCK`] or
976/// [`IN_USE`] and it is still `unused` under them; renamed into the trash first, so no process
977/// finds it half removed.
978fn remove_cache(
979  base: &Path,
980  dir: &Path,
981  name: &str,
982  now: std::time::SystemTime,
983  unused: impl Fn(&Path) -> bool,
984) {
985  // Not created: opening a file the directory lacks would make it look new. A directory without an
986  // `.inuse` has no process holding it (a version before it never makes one).
987  let Ok(lock) = open_to_lock(&dir.join(LOCK), false) else {
988    return;
989  };
990  if lock.try_lock().is_err() {
991    return;
992  }
993  // Any other failure (no permission, a link) counts as held.
994  let in_use = match open_to_lock(&dir.join(IN_USE), false) {
995    Ok(in_use) => Some(in_use),
996    Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
997    Err(_) => return,
998  };
999  if in_use
1000    .as_ref()
1001    .is_some_and(|in_use| in_use.try_lock().is_err())
1002    || !unused(dir)
1003  {
1004    return;
1005  }
1006  let removed = now
1007    .duration_since(std::time::UNIX_EPOCH)
1008    .map_or(0, |since| since.as_secs());
1009  let trash = base.join(format!("{TRASH}{removed}-{}-{name}", std::process::id()));
1010  // (On Windows a directory a process has a file open in is not renamed; it stays.) Its contents are
1011  // checked again in the trash: a file put in `dir` since the sweep looked stays, and the trash with it.
1012  if std::fs::rename(dir, &trash).is_ok() {
1013    drop((lock, in_use));
1014    if holds_only_cache_files_or_nothing(&trash) {
1015      let _ = std::fs::remove_dir_all(&trash);
1016    }
1017  }
1018}
1019
1020/// The cache's `kind` dump for this tree and its year, if this user built it: a dump is loaded as
1021/// the format, so one in a directory or file another user could have written is not used.
1022fn cached_dump(dir: &Path, kind: &str, year: u32) -> Option<(PathBuf, u32)> {
1023  if !trusted_dir(dir) {
1024    return None;
1025  }
1026  dump_paths::resolve_versioned_in_dir(dir, kind, Some(year))
1027    .filter(|(path, _)| private_to_user(path))
1028}
1029
1030/// The failure an earlier build of the `kind` format into `dir` recorded, if its mark has not lapsed
1031/// ([`FAILED_LAPSE`]); a lapsed mark is removed (no count is kept beside a mark, see `mark_failed`).
1032fn failed_before(dir: &Path, kind: &str) -> Option<String> {
1033  let path = kind_file(dir, FAILED, kind);
1034  let reason = std::fs::read_to_string(&path).ok()?;
1035  let lapsed = std::fs::metadata(&path)
1036    .and_then(|meta| meta.modified())
1037    .ok()
1038    .and_then(|marked| marked.elapsed().ok())
1039    .is_some_and(|age| age > FAILED_LAPSE);
1040  if lapsed {
1041    let _ = std::fs::remove_file(&path);
1042    return None;
1043  }
1044  Some(failure_message(&path, &reason))
1045}
1046
1047/// Takes `dir`'s build lock, waiting up to [`LOCK_WAIT`] for a process building there.
1048fn lock_dir(dir: &Path) -> Result<std::fs::File, String> {
1049  let file = open_to_lock(&dir.join(LOCK), true)
1050    .map_err(|e| format!("cannot lock {}: {e}", dir.display()))?;
1051  let deadline = Instant::now() + LOCK_WAIT;
1052  loop {
1053    match file.try_lock() {
1054      Ok(()) => return Ok(file),
1055      Err(std::fs::TryLockError::WouldBlock) if Instant::now() < deadline => {
1056        std::thread::sleep(Duration::from_millis(100));
1057      },
1058      Err(std::fs::TryLockError::WouldBlock) => {
1059        return Err(format!(
1060          "another process has been building into {} for {} s",
1061          dir.display(),
1062          LOCK_WAIT.as_secs()
1063        ));
1064      },
1065      Err(std::fs::TryLockError::Error(e)) => {
1066        return Err(format!("cannot lock {}: {e}", dir.display()));
1067      },
1068    }
1069  }
1070}
1071
1072/// The file this process's build writes the `kind` dump into, beside its final name in `dir`.
1073fn partial_dump(dir: &Path, kind: &str, year: u32) -> PathBuf {
1074  dir.join(format!(
1075    ".{}.{}.partial",
1076    dump_paths::dump_filename(kind, year),
1077    std::process::id()
1078  ))
1079}
1080
1081/// Removes the partial dumps killed builds left in `dir`.
1082fn remove_partial_dumps(dir: &Path) {
1083  let Ok(entries) = std::fs::read_dir(dir) else {
1084    return;
1085  };
1086  for entry in entries.flatten() {
1087    if entry.file_name().to_string_lossy().ends_with(".partial") {
1088      let _ = std::fs::remove_file(entry.path());
1089    }
1090  }
1091}
1092
1093/// Builds the `kind` dump into `dir` as `--init` does, on a thread of its own: the engine's state is
1094/// per thread, so the build starts from a fresh one, leaves the caller's untouched, and is released
1095/// when it ends. Like fmtutil, it runs in a directory holding no TeX files — `dir` — as kpathsea
1096/// searches `.` first and a document's own copy of a format file (`./expl3-code.tex`) must not go
1097/// into the format; the working directory is the process's, so it is `dir` for every thread until
1098/// the build ends, whatever the outcome. As `tools/make_formats.sh` does, a build that logs an
1099/// error or a fatal one is not kept. Written beside its final name and renamed, so a concurrent
1100/// reader never sees half a dump.
1101fn build(kind: &'static str, year: u32, dir: &Path) -> Result<(), String> {
1102  let dest = dir.join(dump_paths::dump_filename(kind, year));
1103  let partial = partial_dump(dir, kind, year);
1104  let partial_name = partial.to_string_lossy().into_owned();
1105  let init_file = if kind == "latex" {
1106    "latex.ltx"
1107  } else {
1108    "plain.tex"
1109  };
1110  let previous = std::env::current_dir().map_err(|e| format!("no working directory: {e}"))?;
1111  let workdir = dir.to_path_buf();
1112  let joined = std::thread::Builder::new()
1113    .name(format!("{kind}-format"))
1114    .stack_size(256 * 1024 * 1024)
1115    .spawn(move || -> Result<(), String> {
1116      dump_paths::set_building_format(true);
1117      std::env::set_current_dir(&workdir)
1118        .map_err(|e| format!("cannot enter {}: {e}", workdir.display()))?;
1119      let opts = latexml_core::common::Config {
1120        bindings_dispatch: Some(std::rc::Rc::new(latexml_package::dispatch)),
1121        extra_bindings_dispatch: Some(std::rc::Rc::new(latexml_contrib::dispatch)),
1122        ..latexml_core::common::Config::default()
1123      };
1124      let mut converter = crate::converter::Converter::from_config(opts.clone());
1125      let result = converter
1126        .prepare_session(&opts)
1127        .map_err(|e| format!("cannot prepare the {kind} format build: {e}"))
1128        .and_then(|()| crate::ini_tex::dump_format(&mut converter, init_file, Some(&partial_name)))
1129        .and_then(|_| {
1130          let counts = latexml_core::common::error::snapshot_report_counts();
1131          if counts.fatal || counts.error > 0 {
1132            Err(format!(
1133              "building the {kind} format logged {} error(s){}",
1134              counts.error,
1135              if counts.fatal { " and a fatal one" } else { "" }
1136            ))
1137          } else {
1138            Ok(())
1139          }
1140        });
1141      drop(converter);
1142      latexml_core::reset_thread_engine();
1143      result
1144    })
1145    .map_err(|e| format!("cannot start the {kind} format build: {e}"))?
1146    .join();
1147  let returned = std::env::set_current_dir(&previous);
1148  let built = joined
1149    .map_err(|_| format!("the {kind} format build panicked"))
1150    .and_then(|built| built)
1151    .and_then(|()| returned.map_err(|e| format!("cannot return to {}: {e}", previous.display())))
1152    .and_then(|()| publish(kind, &partial, &dest));
1153  if built.is_err() {
1154    let _ = std::fs::remove_file(&partial);
1155  }
1156  built
1157}
1158
1159/// Publishes the finished `kind` dump at `partial` as `dest`. The build's [`IN_FLIGHT`] record is
1160/// cleared under the same lock as the rename: an interrupt in between would put the attempt note
1161/// from before the build back beside the finished dump; one now waits, and finds nothing to undo.
1162fn publish(kind: &str, partial: &Path, dest: &Path) -> Result<(), String> {
1163  publish_read_only(partial)
1164    .map_err(|e| format!("cannot set the {kind} dump's permissions: {e}"))?;
1165  let mut slot = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
1166  std::fs::rename(partial, dest)
1167    .map_err(|e| format!("cannot move the {kind} dump to {}: {e}", dest.display()))?;
1168  *slot = None;
1169  Ok(())
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174  use super::*;
1175
1176  /// The tests share the process's [`IN_FLIGHT`] record: one at a time under `cargo test`.
1177  static SERIAL: Mutex<()> = Mutex::new(());
1178
1179  /// An interrupted build is undone (issue 988): its attempt note goes back to what it held before
1180  /// the build (none, or the count of earlier builds that did not succeed) and its partial dump is
1181  /// removed, so the next process builds the format again instead of counting the interrupted build
1182  /// towards marking it failed.
1183  #[test]
1184  fn an_interrupted_build_is_undone() {
1185    let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
1186    let dir = tempfile::tempdir().expect("create tempdir");
1187    let dir = dir.path();
1188    for before in [None, Some("1\tbuilding the latex format logged 3 error(s)")] {
1189      if let Some(text) = before {
1190        std::fs::write(kind_file(dir, ATTEMPTS, "latex"), text).expect("write the earlier note");
1191      }
1192      let count = previous_attempts(dir, "latex").0 + 1;
1193      let before_build = attempts_text(dir, "latex");
1194      note_attempt(
1195        dir,
1196        "latex",
1197        count,
1198        "the latex format build died with its process",
1199      )
1200      .expect("note the attempt");
1201      let partial = partial_dump(dir, "latex", 2025);
1202      std::fs::write(&partial, "half a dump").expect("write the partial dump");
1203      set_in_flight(Some(InFlight {
1204        attempts: kind_file(dir, ATTEMPTS, "latex"),
1205        before:   before_build,
1206        partial:  partial.clone(),
1207      }));
1208      assert!(cancel_in_flight_build());
1209      assert_eq!(attempts_text(dir, "latex").as_deref(), before);
1210      assert!(!partial.exists(), "the partial dump stayed");
1211      assert!(!cancel_in_flight_build(), "a build is undone once");
1212    }
1213  }
1214
1215  /// A published dump is no longer the build's to undo: an interrupt after the rename used to put
1216  /// the attempt note from before the build back beside the finished dump (CLIHARD 1b).
1217  #[test]
1218  fn a_published_build_is_not_undone() {
1219    let _serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner);
1220    let dir = tempfile::tempdir().expect("create tempdir");
1221    let dir = dir.path();
1222    let before = "1\tbuilding the latex format logged 3 error(s)";
1223    std::fs::write(kind_file(dir, ATTEMPTS, "latex"), before).expect("write the earlier note");
1224    note_attempt(
1225      dir,
1226      "latex",
1227      2,
1228      "the latex format build died with its process",
1229    )
1230    .expect("note the attempt");
1231    let partial = partial_dump(dir, "latex", 2025);
1232    std::fs::write(&partial, "a dump").expect("write the dump");
1233    set_in_flight(Some(InFlight {
1234      attempts: kind_file(dir, ATTEMPTS, "latex"),
1235      before:   Some(before.to_string()),
1236      partial:  partial.clone(),
1237    }));
1238    let dest = dir.join(dump_paths::dump_filename("latex", 2025));
1239    publish("latex", &partial, &dest).expect("publish");
1240    assert!(!cancel_in_flight_build(), "the published build was undone");
1241    assert_eq!(
1242      attempts_text(dir, "latex").as_deref(),
1243      Some("2\tthe latex format build died with its process")
1244    );
1245    assert!(dest.is_file());
1246  }
1247
1248  /// An executable of `len` bytes from `seed`, at `dir/name`.
1249  fn executable(dir: &Path, name: &str, seed: u8, len: usize) -> PathBuf {
1250    let path = dir.join(name);
1251    let bytes: Vec<u8> = (0..len)
1252      .map(|i| (i as u8).wrapping_mul(31) ^ seed)
1253      .collect();
1254    std::fs::write(&path, bytes).expect("write the executable");
1255    path
1256  }
1257
1258  /// Sets the modification time of the file or directory at `path` (`std::fs::set_times` opens a directory with backup
1259  /// semantics on Windows, and asks for write-attributes access, which a read-only handle lacks there).
1260  fn set_mtime(path: &Path, time: std::time::SystemTime) {
1261    std::fs::set_times(path, std::fs::FileTimes::new().set_modified(time))
1262      .unwrap_or_else(|e| panic!("set the time of {}: {e}", path.display()));
1263  }
1264
1265  /// A copy of the binary, with a modification time of its own, has the original's key (issue 1023:
1266  /// the same binary run from two paths built its formats twice; red on c5ca6e2ae1f, whose key held
1267  /// the executable's size and modification time). Each file is hashed once, then found by its
1268  /// identity in `.binaries`.
1269  #[test]
1270  fn a_copied_binary_keeps_its_cache_key() {
1271    let base = tempfile::tempdir().expect("create tempdir");
1272    let bin = tempfile::tempdir().expect("create tempdir");
1273    let original = executable(bin.path(), "latexml_oxide", 1, 3 << 20);
1274    let copy = bin.path().join("copy");
1275    std::fs::copy(&original, &copy).expect("copy the executable");
1276    set_mtime(
1277      &copy,
1278      std::time::SystemTime::now() - Duration::from_secs(3600),
1279    );
1280    let digest = executable_digest(base.path(), &original).expect("hash the original");
1281    assert_eq!(
1282      executable_digest(base.path(), &copy).expect("hash the copy"),
1283      digest
1284    );
1285    let memos = std::fs::read_dir(base.path().join(BINARIES))
1286      .expect("read the digests")
1287      .count();
1288    assert_eq!(memos, 2, "one digest per file");
1289    // Read back, not hashed again (a digest written under a 002 umask was not trusted).
1290    let identity = file_identity(&original, &std::fs::metadata(&original).expect("stat"));
1291    let memo = base.path().join(BINARIES).join(identity);
1292    assert!(
1293      private_to_user(&memo),
1294      "the digest is written for this user alone"
1295    );
1296    let remembered = "ab".repeat(32);
1297    std::fs::remove_file(&memo).expect("remove the digest");
1298    std::fs::write(&memo, &remembered).expect("write the digest");
1299    publish_read_only(&memo).expect("publish the digest");
1300    assert_eq!(
1301      executable_digest(base.path(), &original).expect("hash the original again"),
1302      remembered
1303    );
1304    // One another user could write is not.
1305    #[cfg(unix)]
1306    {
1307      use std::os::unix::fs::PermissionsExt;
1308      std::fs::set_permissions(&memo, std::fs::Permissions::from_mode(0o666)).expect("chmod");
1309      assert_eq!(
1310        executable_digest(base.path(), &original).expect("hash the original again"),
1311        digest
1312      );
1313    }
1314  }
1315
1316  /// Two builds of one size and modification time have keys of their own, as a packager that gives
1317  /// every file one time makes them (Nix's 1970 mtime; red on c5ca6e2ae1f: one key, so one build
1318  /// loaded the other's dump).
1319  #[test]
1320  fn builds_of_one_size_and_time_have_their_own_cache_keys() {
1321    let base = tempfile::tempdir().expect("create tempdir");
1322    let bin = tempfile::tempdir().expect("create tempdir");
1323    let nix_time = std::time::UNIX_EPOCH + Duration::from_secs(1);
1324    let one = executable(bin.path(), "one", 1, 1 << 20);
1325    let two = executable(bin.path(), "two", 2, 1 << 20);
1326    set_mtime(&one, nix_time);
1327    set_mtime(&two, nix_time);
1328    assert_ne!(
1329      executable_digest(base.path(), &one).expect("hash one"),
1330      executable_digest(base.path(), &two).expect("hash two")
1331    );
1332  }
1333
1334  /// `$LATEXML_FORMAT_CACHE` places the cache, before `$XDG_CACHE_HOME` and `$HOME`; a relative
1335  /// `$XDG_CACHE_HOME` is passed over (issue 1023's workaround keeps working).
1336  #[test]
1337  fn latexml_format_cache_places_the_cache() {
1338    // An absolute path on this platform: `/x` on Unix, `C:\x` on Windows (where `/x` has no drive,
1339    // so `$XDG_CACHE_HOME=/x` would be passed over as relative).
1340    let abs = |unix: &str| {
1341      if cfg!(windows) {
1342        PathBuf::from(format!("C:{}", unix.replace('/', "\\")))
1343      } else {
1344        PathBuf::from(unix)
1345      }
1346    };
1347    let env = |vars: Vec<(&'static str, PathBuf)>| {
1348      move |name: &str| {
1349        vars
1350          .iter()
1351          .find(|(var, _)| *var == name)
1352          .map(|(_, value)| value.clone().into_os_string())
1353      }
1354    };
1355    let all = vec![
1356      ("LATEXML_FORMAT_CACHE", abs("/pinned/cache")),
1357      ("XDG_CACHE_HOME", abs("/xdg")),
1358      ("HOME", abs("/home/u")),
1359    ];
1360    assert_eq!(
1361      cache_base(env(all.clone())).expect("place the cache"),
1362      abs("/pinned/cache")
1363    );
1364    assert_eq!(
1365      cache_base(env(all[1..].to_vec())).expect("place the cache"),
1366      abs("/xdg").join("latexml-oxide").join("formats")
1367    );
1368    assert_eq!(
1369      cache_base(env(vec![
1370        ("XDG_CACHE_HOME", PathBuf::from("xdg")),
1371        ("HOME", abs("/home/u"))
1372      ]))
1373      .expect("place the cache"),
1374      abs("/home/u")
1375        .join(".cache")
1376        .join("latexml-oxide")
1377        .join("formats")
1378    );
1379  }
1380
1381  /// A cache key (`<version>-<build>-<tree>`) with the build `n`.
1382  fn key(version: &str, n: u64) -> String { format!("{version}-{n:016x}-00000001-0000abcd") }
1383
1384  /// `days` ago.
1385  fn days_ago(days: u64) -> std::time::SystemTime {
1386    std::time::SystemTime::now() - Duration::from_secs(days * 24 * 60 * 60)
1387  }
1388
1389  /// A cache directory `name` in `base`, last used `days` ago (`None`: never stamped, so as old as
1390  /// the directory).
1391  fn cache(base: &Path, name: &str, days: Option<u64>) -> PathBuf {
1392    let dir = base.join(name);
1393    private_dir(&dir).expect("create the cache directory");
1394    std::fs::write(dir.join(LOCK), "").expect("write the lock");
1395    if let Some(days) = days {
1396      let stamp = dir.join(LAST_USED);
1397      std::fs::write(&stamp, "").expect("write the stamp");
1398      set_mtime(&stamp, days_ago(days));
1399    }
1400    dir
1401  }
1402
1403  /// Names of cache directories, old and new, and names that are not (issue 1023 review B1).
1404  #[test]
1405  fn only_cache_keys_name_cache_directories() {
1406    let version = crate::identity::VERSION;
1407    for name in [
1408      key(version, 0xda9a63d0ed92e3af),
1409      key("0.8.1-rc6", 7),
1410      // An unreadable executable's (`build_key`), and the key before issue 1023 (size, mtime).
1411      "0.8.1-m482b030.1870c1d8a2b1c000-7d8eda0f-3d2c3c06".to_string(),
1412      "0.8.0-482b030-1870c1d8a2b1c000-7d8eda0f-3d2c3c06-a418eeb3".to_string(),
1413      "0.8.0--7d8eda0f".to_string(),
1414    ] {
1415      assert!(is_cache_key(&name), "{name}");
1416    }
1417    for name in [
1418      "2023-notes",
1419      "0.9.1-x-0",
1420      "notes",
1421      "0.8.1-da9a63d0ed92e3af",
1422      "0.8.1-da9a63d0ed92e3af-7d8eda0",
1423      "v0.8.1-da9a63d0ed92e3af-7d8eda0f",
1424      "0.8.1-DA9A63D0ED92E3AF-7D8EDA0F",
1425    ] {
1426      assert!(!is_cache_key(name), "{name}");
1427    }
1428    for name in [
1429      ".lock",
1430      ".last_used",
1431      ".inuse",
1432      ".attempts.latex",
1433      ".failed.plain",
1434      ".failed",
1435      "latex.2025.dump.txt",
1436      ".plain.2025.dump.txt.4242.partial",
1437    ] {
1438      assert!(is_cache_file(name), "{name}");
1439    }
1440    for name in [
1441      "thesis.txt",
1442      "latex.dump.txt",
1443      "beamer.2025.dump.txt",
1444      ".attempts.beamer",
1445      ".latex.2025.dump.txt.partial",
1446    ] {
1447      assert!(!is_cache_file(name), "{name}");
1448    }
1449  }
1450
1451  /// An executable this user cannot read (installed 0711) keys its cache by its size and
1452  /// modification time, as before issue 1023, under a name no digest takes (review S4: it had no
1453  /// cache at all, its build marked failed at every run).
1454  #[test]
1455  fn an_unreadable_executable_keeps_a_cache_key() {
1456    let bin = tempfile::tempdir().expect("create tempdir");
1457    let exe = executable(bin.path(), "latexml_oxide", 1, 1 << 10);
1458    let unreadable = |_: &Path| Err("cannot read it: Permission denied".to_string());
1459    let key = build_key(&exe, unreadable).expect("a key from the file's metadata");
1460    assert!(key.starts_with('m'), "{key}");
1461    assert_eq!(
1462      build_key(&exe, unreadable).expect("again"),
1463      key,
1464      "the key is stable"
1465    );
1466    assert!(is_cache_key(&format!("0.8.1-{key}-00000001")), "{key}");
1467    let digest = executable_digest(bin.path(), &exe).expect("hash it");
1468    assert_eq!(
1469      build_key(&exe, |_| Ok(digest.clone())).expect("a digest key"),
1470      digest[..16]
1471    );
1472    assert!(build_key(&bin.path().join("gone"), unreadable).is_err());
1473  }
1474
1475  /// The sweep removes the cache directories of other builds or trees unused for 30 days, but the
1476  /// three last used; never the current one, however old its stamp, nor a new one with no stamp yet,
1477  /// nor a directory the cache did not make; and the trash a killed pruner left an hour after its
1478  /// removal.
1479  #[test]
1480  #[cfg_attr(
1481    not(unix),
1482    ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1483  )]
1484  fn caches_unused_for_a_month_are_pruned() {
1485    let base = tempfile::tempdir().expect("create tempdir");
1486    let base = base.path();
1487    let current = cache(base, &key("0.8.1", 1), Some(90));
1488    let new = cache(base, &key("0.8.1", 2), None);
1489    let kept = cache(base, &key("0.8.0", 40), Some(40));
1490    let pruned: Vec<PathBuf> = [50, 60, 70]
1491      .iter()
1492      .map(|days| cache(base, &key("0.7.6", *days), Some(*days)))
1493      .collect();
1494    let recent = cache(base, &key("0.8.0", 1), Some(1));
1495    let theirs = base.join("notes");
1496    private_dir(&theirs).expect("create a directory of the user's");
1497    std::fs::write(theirs.join(LOCK), "").expect("write a file of the user's");
1498    set_mtime(&theirs, std::time::UNIX_EPOCH + Duration::from_secs(1));
1499    let removed = days_ago(0) - Duration::from_secs(2 * 60 * 60);
1500    let since = |time: std::time::SystemTime| {
1501      time
1502        .duration_since(std::time::UNIX_EPOCH)
1503        .expect("after 1970")
1504        .as_secs()
1505    };
1506    let trash = base.join(format!("{TRASH}{}-1-{}", since(removed), key("0.7.4", 1)));
1507    private_dir(&trash).expect("create the trash");
1508    // Trashed less than an hour ago, though the directory itself is old (a rename keeps its time).
1509    let fresh_trash = base.join(format!(
1510      "{TRASH}{}-1-{}",
1511      since(days_ago(0)),
1512      key("0.7.4", 2)
1513    ));
1514    private_dir(&fresh_trash).expect("create the trash");
1515    set_mtime(&fresh_trash, days_ago(60));
1516    // In `.binaries`, a digest unread for 30 days goes; the sweep's own lock and stamp stay, however
1517    // old (removing a held `.prune.lock` would let a second sweep run).
1518    let binaries = base.join(BINARIES);
1519    private_dir(&binaries).expect("create the digests");
1520    let [old_digest, digest, prune_lock, last_prune] =
1521      [&"a".repeat(32), &"b".repeat(32), PRUNE_LOCK, LAST_PRUNE].map(|name| binaries.join(name));
1522    for (file, days) in [
1523      (&old_digest, 40),
1524      (&digest, 1),
1525      (&prune_lock, 90),
1526      (&last_prune, 90),
1527    ] {
1528      std::fs::write(file, "").expect("write the file");
1529      set_mtime(file, days_ago(days));
1530    }
1531    sweep(base, &current, std::time::SystemTime::now());
1532    assert!(!old_digest.exists(), "a digest unread for 40 days was kept");
1533    for file in [&digest, &prune_lock, &last_prune] {
1534      assert!(file.is_file(), "{} was removed", file.display());
1535    }
1536    // The three last used of the others are `new`, `recent` and `kept`.
1537    for dir in [&current, &new, &recent, &kept, &theirs, &fresh_trash] {
1538      assert!(dir.is_dir(), "{} was pruned", dir.display());
1539    }
1540    for dir in pruned.iter().chain([&trash]) {
1541      assert!(!dir.exists(), "{} was kept", dir.display());
1542    }
1543  }
1544
1545  /// Only a directory named as a cache key and holding nothing but what the cache writes is pruned
1546  /// (review B1: a user's `2023-notes/` holding a `.lock` beside `thesis.txt`, in the directory
1547  /// `$LATEXML_FORMAT_CACHE` named, was removed with what it held); a user's `.trash-` directory is
1548  /// not the cache's trash.
1549  #[test]
1550  #[cfg_attr(
1551    not(unix),
1552    ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1553  )]
1554  fn only_the_caches_own_directories_are_pruned() {
1555    let base = tempfile::tempdir().expect("create tempdir");
1556    let base = base.path();
1557    let current = cache(base, &key("0.8.1", 1), None);
1558    for i in 0..KEEP_NEWEST as u64 {
1559      cache(base, &key("0.9.0", 10 + i), Some(i));
1560    }
1561    let notes = cache(base, "2023-notes", Some(300));
1562    std::fs::write(notes.join("thesis.txt"), "a thesis").expect("write the user's file");
1563    let only_cache_files = cache(base, "0.9.1-x-0", Some(300));
1564    let beside = cache(base, &key("0.7.0", 1), Some(300));
1565    std::fs::write(beside.join("thesis.txt"), "a thesis").expect("write the user's file");
1566    let nested = cache(base, &key("0.7.0", 2), Some(300));
1567    private_dir(&nested.join("drafts")).expect("create the user's directory");
1568    let their_trash = base.join(format!("{TRASH}notes"));
1569    private_dir(&their_trash).expect("create the user's directory");
1570    std::fs::write(their_trash.join("thesis.txt"), "a thesis").expect("write the user's file");
1571    set_mtime(&their_trash, std::time::UNIX_EPOCH + Duration::from_secs(1));
1572    let named_as_trash = base.join(format!("{TRASH}1-1-{}", key("0.7.0", 4)));
1573    private_dir(&named_as_trash).expect("create the user's directory");
1574    std::fs::write(named_as_trash.join("thesis.txt"), "a thesis").expect("write the user's file");
1575    let pruned = cache(base, &key("0.7.0", 3), Some(300));
1576    sweep(base, &current, std::time::SystemTime::now());
1577    for dir in [
1578      &notes,
1579      &only_cache_files,
1580      &beside,
1581      &nested,
1582      &their_trash,
1583      &named_as_trash,
1584    ] {
1585      assert!(dir.is_dir(), "{} was pruned", dir.display());
1586    }
1587    assert!(notes.join("thesis.txt").is_file());
1588    assert!(beside.join("thesis.txt").is_file());
1589    assert!(!pruned.exists(), "the cache's own directory was kept");
1590  }
1591
1592  /// A cache directory a process holds the lock of — building into it, or stamping it — or holds
1593  /// in use is not pruned, however old its stamp.
1594  #[test]
1595  #[cfg_attr(
1596    not(unix),
1597    ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1598  )]
1599  fn a_locked_cache_is_not_pruned() {
1600    let base = tempfile::tempdir().expect("create tempdir");
1601    let base = base.path();
1602    let current = cache(base, &key("0.8.1", 1), None);
1603    let others: Vec<PathBuf> = (0..KEEP_NEWEST as u64)
1604      .map(|i| cache(base, &key("0.8.1", 10 + i), None))
1605      .collect();
1606    let locked = cache(base, &key("0.7.6", 1), Some(60));
1607    let held = std::fs::File::open(locked.join(LOCK)).expect("open the lock");
1608    held.lock_shared().expect("take the lock");
1609    sweep(base, &current, std::time::SystemTime::now());
1610    assert!(locked.is_dir(), "the locked cache was pruned");
1611    drop(held);
1612    sweep(base, &current, std::time::SystemTime::now());
1613    assert!(!locked.exists(), "the cache, unlocked, was kept");
1614    assert!(others.iter().all(|dir| dir.is_dir()));
1615  }
1616
1617  /// A cache directory a running process holds `.inuse` of is not pruned, however old its stamp
1618  /// (review S3: a `--server` reads its dumps again for each conversion).
1619  #[test]
1620  #[cfg_attr(
1621    not(unix),
1622    ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1623  )]
1624  fn a_cache_in_use_is_not_pruned() {
1625    let base = tempfile::tempdir().expect("create tempdir");
1626    let base = base.path();
1627    let current = cache(base, &key("0.8.1", 1), None);
1628    for i in 0..KEEP_NEWEST as u64 {
1629      cache(base, &key("0.8.1", 10 + i), None);
1630    }
1631    let in_use = cache(base, &key("0.7.6", 1), Some(60));
1632    let held = hold_in_use(&in_use).expect("hold it in use");
1633    sweep(base, &current, std::time::SystemTime::now());
1634    assert!(in_use.is_dir(), "the cache in use was pruned");
1635    drop(held);
1636    // A lock taken on a file since moved to the trash is not the directory's (Gemini, FMTCACHEKEY:
1637    // a pruner may rename the directory between a reader's open and its lock).
1638    let moved = cache(base, &key("0.7.6", 2), None);
1639    let file = std::fs::File::create(moved.join(IN_USE)).expect("open .inuse");
1640    assert!(same_file(&file, &moved.join(IN_USE)));
1641    std::fs::rename(&moved, base.join("moved")).expect("move it");
1642    std::fs::create_dir(&moved).expect("make it again");
1643    std::fs::write(moved.join(IN_USE), "").expect("write .inuse");
1644    assert!(
1645      !same_file(&file, &moved.join(IN_USE)),
1646      "a moved file is the directory's"
1647    );
1648    std::fs::remove_dir_all(&moved).expect("remove it");
1649    sweep(base, &current, std::time::SystemTime::now());
1650    assert!(!in_use.exists(), "the cache, no longer in use, was kept");
1651  }
1652
1653  /// A cache directory whose `.inuse` the pruner cannot open counts as held, never as idle.
1654  #[cfg(unix)]
1655  #[test]
1656  fn a_cache_whose_use_cannot_be_read_is_not_pruned() {
1657    use std::os::unix::fs::PermissionsExt;
1658    let base = tempfile::tempdir().expect("create tempdir");
1659    let base = base.path();
1660    let current = cache(base, &key("0.8.1", 1), None);
1661    for i in 0..KEEP_NEWEST as u64 {
1662      cache(base, &key("0.8.1", 10 + i), None);
1663    }
1664    let unreadable = cache(base, &key("0.7.6", 1), Some(60));
1665    let in_use = unreadable.join(IN_USE);
1666    std::fs::write(&in_use, "").expect("write .inuse");
1667    std::fs::set_permissions(&in_use, std::fs::Permissions::from_mode(0o000)).expect("chmod");
1668    sweep(base, &current, std::time::SystemTime::now());
1669    assert!(
1670      unreadable.is_dir(),
1671      "a cache whose .inuse could not be opened was pruned"
1672    );
1673    std::fs::set_permissions(&in_use, std::fs::Permissions::from_mode(0o644)).expect("chmod");
1674  }
1675
1676  /// A cache directory with no stamp (a version before it) counts as used when its dump was last
1677  /// read, though the directory is old (review S3).
1678  #[test]
1679  #[cfg_attr(
1680    not(unix),
1681    ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1682  )]
1683  fn an_unstamped_cache_read_lately_is_not_pruned() {
1684    let base = tempfile::tempdir().expect("create tempdir");
1685    let base = base.path();
1686    let current = cache(base, &key("0.8.1", 1), None);
1687    for i in 0..KEEP_NEWEST as u64 {
1688      cache(base, &key("0.8.1", 10 + i), Some(i));
1689    }
1690    let unstamped = |n: u64, read: std::time::SystemTime| {
1691      let dir = cache(base, &key("0.8.0", n), None);
1692      let dump = dir.join("latex.2025.dump.txt");
1693      std::fs::write(&dump, "a dump").expect("write the dump");
1694      std::fs::File::options()
1695        .write(true)
1696        .open(&dump)
1697        .and_then(|file| {
1698          file.set_times(
1699            std::fs::FileTimes::new()
1700              .set_accessed(read)
1701              .set_modified(days_ago(90)),
1702          )
1703        })
1704        .expect("set the dump's times");
1705      set_mtime(&dir, days_ago(90));
1706      dir
1707    };
1708    let read_lately = unstamped(1, days_ago(2));
1709    let unread = unstamped(2, days_ago(60));
1710    sweep(base, &current, std::time::SystemTime::now());
1711    assert!(read_lately.is_dir(), "the cache read lately was pruned");
1712    assert!(!unread.exists(), "the cache unread for 60 days was kept");
1713  }
1714
1715  /// A process prunes the cache once a day, in a cache it owns though the umask made it
1716  /// group-writable (0775; a check for a private base kept it from ever pruning there).
1717  #[cfg(unix)]
1718  #[test]
1719  fn the_cache_is_pruned_once_a_day() {
1720    use std::os::unix::fs::PermissionsExt;
1721    let base = tempfile::tempdir().expect("create tempdir");
1722    let base = base.path();
1723    std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o775)).expect("chmod");
1724    let current = cache(base, &key("0.8.1", 1), None);
1725    let others: Vec<PathBuf> = (0..=KEEP_NEWEST as u64)
1726      .map(|i| cache(base, &key("0.8.0", 40 + i), Some(40 + i)))
1727      .collect();
1728    prune(base, &current);
1729    assert!(base.join(BINARIES).join(LAST_PRUNE).is_file(), "no sweep");
1730    assert!(!others[KEEP_NEWEST].exists(), "the oldest cache was kept");
1731    assert!(others[..KEEP_NEWEST].iter().all(|dir| dir.is_dir()));
1732    let later = cache(base, &key("0.7.6", 90), Some(90));
1733    prune(base, &current);
1734    assert!(later.is_dir(), "swept twice in a day");
1735  }
1736
1737  /// The sweep's stamp and lock are kept in the private `.binaries`, so links another user plants
1738  /// in their old place in a group-writable base are not followed (review B2: opening `.prune.lock`
1739  /// truncated the file it linked to).
1740  #[cfg(unix)]
1741  #[test]
1742  fn links_in_the_base_are_not_followed() {
1743    use std::os::unix::fs::PermissionsExt;
1744    let base = tempfile::tempdir().expect("create tempdir");
1745    let base = base.path();
1746    std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o775)).expect("chmod");
1747    let victim_dir = tempfile::tempdir().expect("create tempdir");
1748    let victim = victim_dir.path().join("victim.txt");
1749    std::fs::write(&victim, "precious").expect("write the victim");
1750    let old = std::time::UNIX_EPOCH + Duration::from_secs(1);
1751    set_mtime(&victim, old);
1752    for name in [PRUNE_LOCK, LAST_PRUNE] {
1753      std::os::unix::fs::symlink(&victim, base.join(name)).expect("plant the link");
1754    }
1755    let current = cache(base, &key("0.8.1", 1), None);
1756    prune(base, &current);
1757    assert!(base.join(BINARIES).join(LAST_PRUNE).is_file(), "no sweep");
1758    assert_eq!(
1759      std::fs::read_to_string(&victim).expect("read the victim"),
1760      "precious"
1761    );
1762    assert_eq!(
1763      std::fs::metadata(&victim)
1764        .and_then(|meta| meta.modified())
1765        .expect("stat the victim"),
1766      old,
1767      "the victim was touched"
1768    );
1769  }
1770
1771  /// A FIFO or a link planted as the cache directory's `.lock`, `.inuse` or `.last_used` neither
1772  /// stops a conversion nor is followed: each is opened as the pruner opens it, a regular file or
1773  /// nothing (issue 1023 re-review: a FIFO `.inuse` hung a conversion past `--timeout`; a linked
1774  /// `.lock` was truncated by a build).
1775  #[cfg(unix)]
1776  #[test]
1777  fn fifos_and_links_in_the_cache_directory_are_not_opened() {
1778    let victims = tempfile::tempdir().expect("create tempdir");
1779    let victim = victims.path().join("victim.txt");
1780    std::fs::write(&victim, "precious").expect("write the victim");
1781    let old = std::time::UNIX_EPOCH + Duration::from_secs(1);
1782    set_mtime(&victim, old);
1783    let dangling = victims.path().join("made.txt");
1784    let fifo = |path: &Path| {
1785      let made = std::process::Command::new("mkfifo").arg(path).status();
1786      assert!(
1787        made.is_ok_and(|status| status.success()),
1788        "mkfifo {}",
1789        path.display()
1790      );
1791    };
1792    let link = |target: &Path, path: &Path| {
1793      std::os::unix::fs::symlink(target, path).expect("plant the link");
1794    };
1795    type Plant<'a> = &'a dyn Fn(&Path);
1796    let plants: [(&str, Plant); 3] = [
1797      ("FIFOs", &|dir| {
1798        fifo(&dir.join(LOCK));
1799        fifo(&dir.join(IN_USE));
1800      }),
1801      ("links", &|dir| {
1802        link(&victim, &dir.join(LOCK));
1803        link(&victim, &dir.join(IN_USE));
1804        link(&victim, &dir.join(LAST_USED));
1805      }),
1806      ("dangling links", &|dir| {
1807        link(&dangling, &dir.join(LOCK));
1808        link(&dangling, &dir.join(IN_USE));
1809      }),
1810    ];
1811    for (what, plant) in plants {
1812      let base = tempfile::tempdir().expect("create tempdir");
1813      let dir = cache(base.path(), &key("0.8.1", 1), None);
1814      std::fs::remove_file(dir.join(LOCK)).expect("remove the lock");
1815      plant(&dir);
1816      let (done, finished) = std::sync::mpsc::channel();
1817      let in_thread = dir.clone();
1818      std::thread::spawn(move || {
1819        refresh_last_used(&in_thread);
1820        let held = hold_in_use(&in_thread).is_some();
1821        let locked = lock_dir(&in_thread).is_ok();
1822        let _ = done.send((held, locked));
1823      });
1824      let (held, locked) = finished
1825        .recv_timeout(Duration::from_secs(20))
1826        .unwrap_or_else(|_| panic!("{what}: a lock or stamp file was waited on"));
1827      assert!(!held && !locked, "{what}: a file not regular was locked");
1828      assert_eq!(
1829        std::fs::read_to_string(&victim).expect("read the victim"),
1830        "precious",
1831        "{what}"
1832      );
1833      assert_eq!(
1834        std::fs::metadata(&victim)
1835          .and_then(|meta| meta.modified())
1836          .expect("stat the victim"),
1837        old,
1838        "{what}: the victim was touched"
1839      );
1840      assert!(!dangling.exists(), "{what}: a dangling link was followed");
1841    }
1842  }
1843
1844  /// A file put in a cache directory after the sweep found it holding only the cache's files stays,
1845  /// and the trash with it: the trash is checked again before it is removed (re-review nit).
1846  #[test]
1847  #[cfg_attr(
1848    not(unix),
1849    ignore = "Windows never prunes the format cache: it will not rename a directory a file is open in (row R FMTCACHE-WINPRUNE)"
1850  )]
1851  fn a_file_put_in_a_cache_being_pruned_stays() {
1852    let base = tempfile::tempdir().expect("create tempdir");
1853    let base = base.path();
1854    let current = cache(base, &key("0.8.1", 1), None);
1855    let name = key("0.7.6", 1);
1856    let old = cache(base, &name, Some(60));
1857    assert!(holds_only_cache_files(&old));
1858    let now = std::time::SystemTime::now();
1859    // Under the pruner's locks, just before the rename.
1860    remove_cache(base, &old, &name, now, |dir| {
1861      std::fs::write(dir.join("thesis.txt"), "a thesis").is_ok()
1862    });
1863    let trash: Vec<PathBuf> = std::fs::read_dir(base)
1864      .expect("read the base")
1865      .flatten()
1866      .filter(|entry| entry.file_name().to_string_lossy().starts_with(TRASH))
1867      .map(|entry| entry.path())
1868      .collect();
1869    assert_eq!(
1870      trash.len(),
1871      1,
1872      "the trash holding the user's file was removed"
1873    );
1874    sweep(base, &current, now + TRASH_LAPSE * 2);
1875    assert_eq!(
1876      std::fs::read_to_string(trash[0].join("thesis.txt")).expect("read the user's file"),
1877      "a thesis"
1878    );
1879  }
1880}