Skip to main content

latexml_post/
graphics_cache.rs

1//! Content-addressed graphics cache.
2//!
3//! Every `convert_image` / `convert_image_svg` call rasterises a
4//! self-contained source file (PDF / EPS / PNG / SVG) with a small set
5//! of render-shaping inputs (page, density, target format). Across a
6//! canvas of arXiv submissions the same byte content recurs constantly
7//! — common journal logos, reused author-affiliation marks, and
8//! regenerated runs of the same paper. PERFORMANCE.md §5 records the
9//! `graphics` phase as **36.5%** of corpus wall, so a cache that hits
10//! even a third of the time shaves ~11% off corpus wall.
11//!
12//! ## Heritage: Perl `LaTeXML.cache`
13//!
14//! The Perl post-processor stores a tied BerkeleyDB hash named
15//! `LaTeXML.cache` per output directory. Keys are built from the
16//! processor class, the source path, and the transform string; values
17//! are `"dest|width|height"` strings. The features we mirror are
18//! listed below.
19//!
20//! - **Disable flag** (Perl: `nocache`) → env `LATEXML_GRAPHICS_CACHE_OFF`.
21//! - **Names** (Perl: `key → dest`) → the document cache, `LaTeXML-oxide.cache` in the destination directory
22//!   ([`crate::document::DocCache`], [`crate::resource_cache`]); this cache holds the converted bytes only.
23//! - **Re-use across runs** (Perl: one .cache per dest dir) → global XDG cache, shared across all
24//!   conversions on the host. This is a strict superset of the Perl behaviour: cross-paper sharing,
25//!   plus reproducible content-keying instead of path-keying.
26//! - **Source-staleness check** (Perl compared source mtime to cached output mtime) → unnecessary
27//!   here: the cache key is SHA-256 of the source *bytes*, so any source edit produces a different
28//!   key.
29//! - **Cached dimensions** (Perl: width/height in the cached value) → sidecar `<hash>.<ext>.dims`
30//!   file containing `width\nheight\n`. Lookup returns `(success, dims)`; callers skip the
31//!   `read_image_dimensions` syscall on hits.
32//!
33//! Beyond Perl: content-hash keying gives stricter staleness; XDG
34//! placement gives cross-paper reuse; multi-process safety (below)
35//! lets canvas sweeps share the cache without corruption.
36//!
37//! ## Cache key
38//!
39//! SHA-256 of:
40//!   `source bytes ‖ page ‖ density ‖ target-extension [‖ SVG_KEY_VERSION]`
41//!
42//! The page/density bytes are appended as 4-byte little-endian; the
43//! extension is appended as ASCII lower-case bytes, and an `svg` key ends
44//! with `SVG_KEY_VERSION`, which retires cached SVGs. Bytes-only keying
45//! makes the cache reproducible across machines and gives near-zero
46//! collision risk for our use.
47//!
48//! ## On-disk layout
49//!
50//!   `$XDG_CACHE_HOME/latexml-oxide/graphics/<aa>/<full-hash>.<ext>`
51//!   `$XDG_CACHE_HOME/latexml-oxide/graphics/<aa>/<full-hash>.<ext>.dims`
52//!   `$XDG_CACHE_HOME/latexml-oxide/graphics/.prune.lock`
53//!   `$XDG_CACHE_HOME/latexml-oxide/graphics/.usage`
54//!
55//! Sharded by the first two hex characters of the hash to keep any one
56//! directory's entry count bounded (worst case ~1/256th of the total
57//! cache size).
58//!
59//! `$XDG_CACHE_HOME` falls back to `$HOME/.cache` per the XDG spec.
60//!
61//! ## Multi-process safety
62//!
63//! The cache is designed to be shared by parallel `cortex_worker`
64//! processes within a canvas sweep. Concurrency guarantees:
65//!
66//! 1. **Concurrent writes to the same key**: each writer copies into a private
67//!    `.<stem>.tmp.<pid>.<seq>.<ext>` file ([`crate::writer::Staged`]) then issues a single
68//!    `rename(2)` into the final path. `rename` is atomic on the same filesystem; if two writers
69//!    race, the last `rename` wins, and because both sources are byte-equivalent the outcome is
70//!    correct.
71//! 2. **Concurrent reads + writes**: a reader copies the cached file into the destination the same
72//!    way (a staged copy renamed onto it). An entry the writers replace by rename is never written
73//!    through, so the reader's open file keeps the bytes it opened. If the cache file is unlinked
74//!    between hash computation and the copy, the reader gets a miss and falls through — no data
75//!    corruption.
76//! 3. **Concurrent prunes**: prune holds `flock(LOCK_EX | LOCK_NB)` on `.prune.lock`. If another
77//!    process already holds the lock, this one skips its prune attempt. Only one prune runs at a
78//!    time per machine. The prune itself walks the dir, sorts by mtime, deletes oldest until under
79//!    the low-water mark — and tolerates `ENOENT` (another writer could have re-used the entry
80//!    concurrently). It also removes every `.tmp.` sidecar changed (ctime on Unix) over an hour ago:
81//!    a killed process's unfinished install.
82//! 4. **The usage tally**: `.usage` holds the bytes the last walk counted plus every insertion
83//!    since, and when that walk ran; an insertion adds its size under an exclusive lock on the file
84//!    (held for one read and one write). Drift — an entry two racing writers both count, one
85//!    removed by hand, one an older binary added — lasts until the next walk recounts.
86//! 5. **Destination ↔ cache**: every destination holds its own copy, so an output edited in place
87//!    (a post-processing step, a user) changes neither the cache entry nor another document's copy,
88//!    and a prune that deletes the entry leaves every destination whole.
89//!
90//! These guarantees hold on any POSIX filesystem, and on Windows, where `File::lock` is
91//! `LockFileEx`. (The prune lock there was a `create_new` sentinel no one removed, so no prune ran
92//! after a cache's first insertion.)
93//!
94//! ## Lifecycle
95//!
96//! * **Hit**: copy the cache file into the destination (`fs::copy`, which shares the extents where the
97//!   filesystem can: Linux `copy_file_range` on btrfs or XFS). Read the `.dims` sidecar if present.
98//! * **Miss-then-success**: copy the produced destination back into the cache. Write the `.dims`
99//!   sidecar alongside.
100//! * **LRU prune**: each insertion adds its size to the usage tally and checks it against the cap
101//!   (`LATEXML_GRAPHICS_CACHE_MAX_MB`, default 2048 = 2 GB). Over the cap, or an hour after the
102//!   last walk (which also recounts the tally and reclaims stale `.tmp.` files), it holds the prune
103//!   lock, walks the cache, sorts entries by mtime ascending and deletes the oldest until the total
104//!   is under 90 % of the cap, so the next tenth of the cap is inserted without a walk (each walk
105//!   stats every entry: 20-29 ms on a 2 GB cache, GCACHECHURN). File access on read also refreshes
106//!   the mtime so frequently-hit entries survive.
107//!
108//! ## Disable / tune
109//!
110//! * `LATEXML_GRAPHICS_CACHE_OFF=1` — bypass entirely (read+write both skipped). The wrapper
111//!   devolves to the bare conversion call.
112//! * `LATEXML_GRAPHICS_CACHE_DIR=/path` — override the cache directory.
113//! * `LATEXML_GRAPHICS_CACHE_MAX_MB=N` — cache size cap.
114
115use std::{
116  fs,
117  io::Read,
118  path::{Path, PathBuf},
119  sync::{
120    OnceLock,
121    atomic::{AtomicU32, Ordering},
122  },
123};
124
125use sha2::{Digest, Sha256};
126
127const DEFAULT_MAX_MB: u64 = 2048;
128/// How old a `.tmp.` sidecar must be before a prune takes it for a killed install's.
129const STALE_TMP_AGE: std::time::Duration = std::time::Duration::from_secs(3600);
130
131/// Mixed into every SVG key (DG 2026-11-16): before mutool's page ≥ 2 fix, a page ≥ 2 SVG was pdftocairo's
132/// render; every SVG key is retired so each page comes from the same converter (the fleet re-renders
133/// each vector SVG once). Change it whenever cached SVGs must not be served again.
134const SVG_KEY_VERSION: &str = "mutool-page-fix-2026-11-16";
135
136/// Memoised disabled flag (read env once at first call).
137fn disabled() -> bool {
138  static CELL: OnceLock<bool> = OnceLock::new();
139  *CELL.get_or_init(|| {
140    matches!(
141      std::env::var("LATEXML_GRAPHICS_CACHE_OFF")
142        .ok()
143        .as_deref()
144        .map(|s| s.trim()),
145      Some("1") | Some("true") | Some("yes")
146    )
147  })
148}
149
150/// Cache root, recomputed on each call.
151///
152/// Originally OnceLock-cached, but that bakes in whatever value the
153/// env-var has at first call and locks out any later setter. In tests
154/// (where one test binary contains both `graphics::*` and
155/// `graphics_cache::*` tests), an earlier `graphics::*` test that
156/// invokes `Graphics::process` triggers `cache_root()` with no
157/// `LATEXML_GRAPHICS_CACHE_DIR` set — pinning the cache to
158/// `~/.cache/latexml-oxide/graphics`. Subsequent `graphics_cache::*`
159/// tests then set the env var via `shared_cache_dir()` but the
160/// OnceLock ignores it, causing cache files to land outside the test
161/// dir and the assertions to fail. Re-reading the env var on each
162/// call costs ~one syscall in production (LATEXML_GRAPHICS_CACHE_DIR
163/// never changes there) — negligible compared to the disk I/O the
164/// cache layer drives.
165fn cache_root() -> Option<PathBuf> {
166  if let Ok(p) = std::env::var("LATEXML_GRAPHICS_CACHE_DIR") {
167    if !p.is_empty() {
168      return Some(PathBuf::from(p));
169    }
170  }
171  let base = std::env::var_os("XDG_CACHE_HOME")
172    .map(PathBuf::from)
173    .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".cache")))?;
174  Some(base.join("latexml-oxide").join("graphics"))
175}
176
177/// Cache size cap in bytes, read once from env.
178fn max_bytes() -> u64 {
179  static CELL: OnceLock<u64> = OnceLock::new();
180  *CELL.get_or_init(|| {
181    std::env::var("LATEXML_GRAPHICS_CACHE_MAX_MB")
182      .ok()
183      .and_then(|s| s.parse::<u64>().ok())
184      .unwrap_or(DEFAULT_MAX_MB)
185      .saturating_mul(1024 * 1024)
186  })
187}
188
189static HITS: AtomicU32 = AtomicU32::new(0);
190static MISSES: AtomicU32 = AtomicU32::new(0);
191
192/// Return `(hits, misses)` since process start. Useful for telemetry
193/// and the post-run summary log line.
194pub fn stats() -> (u32, u32) { (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed)) }
195
196/// Reset stats (test-only).
197#[cfg(test)]
198pub fn reset_stats() {
199  HITS.store(0, Ordering::Relaxed);
200  MISSES.store(0, Ordering::Relaxed);
201}
202
203/// Whether a given conversion consults the shared graphics cache.
204///
205/// The cache root is *process-global, host-persistent* state: it comes
206/// from `LATEXML_GRAPHICS_CACHE_DIR`, else
207/// `$XDG_CACHE_HOME/latexml-oxide/graphics`, which survives across runs
208/// and across unrelated conversions. A caller that needs its conversions
209/// to actually *run* — rather than be served from whatever a previous
210/// run on this host happened to leave behind — must be able to opt out,
211/// and must be able to do so **without mutating the environment**
212/// (`set_var` is process-wide and racy against every other thread).
213/// Hence an explicit, caller-threaded policy rather than another env var.
214///
215/// The env kill-switch `LATEXML_GRAPHICS_CACHE_OFF=1` still applies
216/// independently, inside [`lookup`] / [`store`].
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
218pub enum CachePolicy {
219  /// Consult and populate the shared cache. The production default.
220  #[default]
221  Shared,
222  /// Bypass the cache entirely: every conversion runs, nothing is read
223  /// and nothing is stored. Used where the *conversion itself* is the
224  /// observable under test, so a prior run's cached output must not be
225  /// able to substitute for it.
226  Bypass,
227}
228
229/// Render-shaping inputs that go into the cache key alongside source
230/// bytes. Two calls with the same `RenderKey` MUST produce
231/// byte-equivalent output (modulo metadata variation tools like
232/// ImageMagick are known to introduce — see `compare_outputs_strict`
233/// audit in the spawn paths).
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct RenderKey {
236  /// 1-based page selector (graphicx convention). `None` ⇒ default.
237  pub page:    Option<u32>,
238  /// DPI for raster conversions; 0 for pure vector (SVG) paths.
239  pub density: u32,
240  /// Target format, derived from destination extension (lowercase, no dot).
241  /// e.g. `"png"`, `"svg"`, `"jpg"`. Empty if missing.
242  pub ext:     &'static str,
243}
244
245/// Cached dimensions for an image. Mirrors Perl `LaTeXML.cache`
246/// `"dest|width|height"` value triple (we already have the dest path
247/// at the call site — only the dimensions need round-tripping).
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub struct CachedDims {
250  pub width:  u32,
251  pub height: u32,
252}
253
254/// A source file's SHA-256 state after its bytes: its content identity (the graphics pass's dedupe key) and, extended
255/// by a [`RenderKey`], its cache key, from one read of the file.
256#[derive(Clone)]
257pub struct SourceDigest(Sha256);
258
259impl SourceDigest {
260  /// Hash the file at `source_path`; `None` if it can't be opened or read.
261  pub fn of_file(source_path: &Path) -> Option<Self> {
262    let mut file = fs::File::open(source_path).ok()?;
263    let mut hasher = Sha256::new();
264    // 64 KB scratch buffer; large enough to dwarf syscall overhead, small
265    // enough to keep stack/heap pressure low under high concurrency.
266    let mut buf = [0u8; 64 * 1024];
267    loop {
268      match file.read(&mut buf) {
269        Ok(0) => break,
270        Ok(n) => hasher.update(&buf[..n]),
271        Err(_) => return None,
272      }
273    }
274    Some(SourceDigest(hasher))
275  }
276
277  /// The SHA-256 of the file's bytes.
278  pub fn content(&self) -> [u8; 32] { self.0.clone().finalize().into() }
279
280  /// The cache-key hash of `(source bytes, key)`, as lowercase hex.
281  fn key_hash(&self, key: RenderKey) -> String {
282    let mut hasher = self.0.clone();
283    hasher.update(key.page.unwrap_or(0).to_le_bytes());
284    hasher.update(key.density.to_le_bytes());
285    hasher.update(key.ext.as_bytes());
286    if key.ext == "svg" {
287      hasher.update(SVG_KEY_VERSION.as_bytes());
288    }
289    // sha2 0.11 returns a `hybrid_array::Array`, which (unlike 0.10's
290    // `GenericArray`) does not implement `LowerHex`, so `format!("{:x}", _)`
291    // no longer compiles. Render the digest to lowercase hex by hand — same
292    // output as the old `{:x}`, and version-agnostic.
293    use std::fmt::Write as _;
294    let digest = hasher.finalize();
295    let mut hash = String::with_capacity(digest.len() * 2);
296    for byte in digest.iter() {
297      let _ = write!(hash, "{byte:02x}");
298    }
299    hash
300  }
301}
302
303/// Compute the cache-key hash for `(source_bytes, render_key)`.
304fn hash_key(source_path: &Path, key: RenderKey) -> Option<String> {
305  Some(SourceDigest::of_file(source_path)?.key_hash(key))
306}
307
308/// The cache key of `(source, key)`: from `digest`, the source already read, or else from the file.
309fn source_key(source: &str, digest: Option<&SourceDigest>, key: RenderKey) -> Option<String> {
310  match digest {
311    Some(digest) => Some(digest.key_hash(key)),
312    None => hash_key(Path::new(source), key),
313  }
314}
315
316/// Build the cache file path for a given hash + extension.
317fn cache_path(root: &Path, hash: &str, ext: &str) -> PathBuf {
318  let shard = &hash[..2.min(hash.len())];
319  let mut p = root.join(shard);
320  if ext.is_empty() {
321    p.push(hash);
322  } else {
323    p.push(format!("{hash}.{ext}"));
324  }
325  p
326}
327
328/// Path to the `.dims` sidecar for a cache entry.
329fn dims_sidecar(cache_file: &Path) -> PathBuf {
330  let mut s = cache_file.as_os_str().to_owned();
331  s.push(".dims");
332  PathBuf::from(s)
333}
334
335/// Copy `src` to `dst` through a staged file and one rename ([`crate::writer::copy_atomic`]): a
336/// reader of `dst` never sees it half-written, and the copy is `dst`'s own, so an output edited in
337/// place changes neither the cache entry nor another document's copy (a hard link did, GFXHARDLINK).
338/// `fs::copy` shares the extents where the filesystem can (Linux `copy_file_range` on btrfs, XFS).
339fn deliver(src: &Path, dst: &Path) -> bool {
340  if let Some(parent) = dst.parent()
341    && fs::create_dir_all(parent).is_err()
342  {
343    return false;
344  }
345  crate::writer::copy_atomic(src, dst).is_ok()
346}
347
348/// Read a `.dims` sidecar if present.
349fn read_dims_sidecar(sidecar: &Path) -> Option<CachedDims> {
350  let raw = fs::read_to_string(sidecar).ok()?;
351  let mut lines = raw.split('\n').map(|s| s.trim());
352  let width = lines.next()?.parse::<u32>().ok()?;
353  let height = lines.next()?.parse::<u32>().ok()?;
354  Some(CachedDims { width, height })
355}
356
357/// Write a `.dims` sidecar atomically ([`crate::writer::write_atomic`]). Idempotent
358/// and best-effort — failures leave no state behind.
359fn write_dims_sidecar(sidecar: &Path, dims: CachedDims) {
360  if let Some(parent) = sidecar.parent()
361    && fs::create_dir_all(parent).is_err()
362  {
363    return;
364  }
365  let body = format!("{}\n{}\n", dims.width, dims.height);
366  let _ = crate::writer::write_atomic(sidecar, body.as_bytes());
367}
368
369/// Result of a cache lookup.
370#[derive(Debug, Clone, Copy)]
371pub struct CacheHit {
372  pub dims: Option<CachedDims>,
373}
374
375/// Look the cache up. On hit: copy into `dest`, refresh the
376/// cache entry's mtime, return `Some(CacheHit{dims})`. On miss or any
377/// I/O hiccup, return `None` so the caller falls through to a real
378/// conversion.
379pub fn lookup(source: &str, dest: &str, key: RenderKey) -> Option<CacheHit> {
380  lookup_digest(source, None, dest, key)
381}
382
383/// [`lookup`], with the source's [`SourceDigest`] when the caller has it.
384fn lookup_digest(
385  source: &str,
386  digest: Option<&SourceDigest>,
387  dest: &str,
388  key: RenderKey,
389) -> Option<CacheHit> {
390  if disabled() {
391    return None;
392  }
393  let root = cache_root()?;
394  let hash = source_key(source, digest, key)?;
395  let cached = cache_path(&root, &hash, key.ext);
396  if !cached.exists() {
397    MISSES.fetch_add(1, Ordering::Relaxed);
398    return None;
399  }
400  if !deliver(&cached, Path::new(dest)) {
401    MISSES.fetch_add(1, Ordering::Relaxed);
402    return None;
403  }
404  // Refresh mtime so the LRU prune doesn't evict an active entry.
405  // Errors here are non-fatal; the hit already succeeded.
406  let _ = touch_now(&cached);
407  let dims = read_dims_sidecar(&dims_sidecar(&cached));
408  HITS.fetch_add(1, Ordering::Relaxed);
409  Some(CacheHit { dims })
410}
411
412/// The cache's entry for `(source, key)` when `policy` consults the cache and it holds one: what a conversion of the
413/// source installs (`digest`: the source's, when read already).
414pub fn cached_output(
415  policy: CachePolicy,
416  source: &str,
417  digest: Option<&SourceDigest>,
418  key: RenderKey,
419) -> Option<PathBuf> {
420  if policy == CachePolicy::Bypass || disabled() {
421    return None;
422  }
423  let cached = cache_path(&cache_root()?, &source_key(source, digest, key)?, key.ext);
424  cached.exists().then_some(cached)
425}
426
427/// Insert `dest` (and optionally its dimensions) into the cache under
428/// `(source, key)`. Idempotent and best-effort: any I/O failure leaves
429/// the cache unchanged.
430pub fn store(source: &str, dest: &str, key: RenderKey, dims: Option<CachedDims>) {
431  store_digest(source, None, dest, key, dims)
432}
433
434/// [`store`], with the source's [`SourceDigest`] when the caller has it.
435fn store_digest(
436  source: &str,
437  digest: Option<&SourceDigest>,
438  dest: &str,
439  key: RenderKey,
440  dims: Option<CachedDims>,
441) {
442  if disabled() {
443    return;
444  }
445  let Some(root) = cache_root() else { return };
446  let Some(hash) = source_key(source, digest, key) else {
447    return;
448  };
449  let cached = cache_path(&root, &hash, key.ext);
450  // A sidecar without its entry is never reclaimed: the prune removes one only with its entry.
451  let added = install(Path::new(dest), &cached);
452  if added.is_some()
453    && let Some(d) = dims
454  {
455    write_dims_sidecar(&dims_sidecar(&cached), d);
456  }
457  // Best-effort LRU prune after insert (process-locked).
458  prune_if_over_cap(&root, added.unwrap_or(0));
459}
460
461/// Install `dest` as the cache entry `cached`, unless an entry is already there: the bytes it added (`0` when an
462/// entry was in place), `None` when no entry is in place after.
463/// Concurrent writers each stage a private copy and race the rename ([`deliver`]): the last wins,
464/// and both are the same bytes. A killed install's staged `.tmp.` file is reclaimed by the prune's
465/// `STALE_TMP_AGE` sweep (33k such files in the fleet's cache by 2026-11-16).
466fn install(dest: &Path, cached: &Path) -> Option<u64> {
467  if cached.is_file() {
468    let _ = touch_now(cached);
469    return Some(0);
470  }
471  if deliver(dest, cached) {
472    return Some(fs::metadata(cached).map_or(0, |meta| meta.len()));
473  }
474  cached.is_file().then_some(0)
475}
476
477fn touch_now(p: &Path) -> std::io::Result<()> {
478  let now = std::time::SystemTime::now();
479  let f = fs::File::options().write(true).open(p)?;
480  f.set_modified(now)?;
481  drop(f);
482  Ok(())
483}
484
485/// Acquire an advisory exclusive lock on the prune sentinel file (`File::try_lock`: `flock` on
486/// Unix, `LockFileEx` on Windows), held for the lifetime of the returned handle and released when
487/// its process dies. `None` => another process already holds the lock; skip the prune.
488fn acquire_prune_lock(root: &Path) -> Option<fs::File> {
489  let lock_path = root.join(".prune.lock");
490  let _ = fs::create_dir_all(root);
491  let file = fs::File::options()
492    .create(true)
493    .write(true)
494    .truncate(false)
495    .open(&lock_path)
496    .ok()?;
497  file.try_lock().is_ok().then_some(file)
498}
499
500/// The share of the cap a prune leaves filled: the next tenth of the cap is inserted without a walk.
501const LOW_WATER_PERCENT: u64 = 90;
502
503/// The usage tally, `.usage` in the cache root: the bytes of the entries the last walk kept plus
504/// every insertion's since, and when (Unix seconds) that walk ran.
505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506struct Usage {
507  bytes:  u64,
508  walked: u64,
509}
510
511/// The usage tally's file, opened under an exclusive lock (blocking; held for one read and one
512/// write, released when the handle drops).
513fn lock_usage(root: &Path) -> Option<fs::File> {
514  let file = fs::File::options()
515    .read(true)
516    .write(true)
517    .create(true)
518    .truncate(false)
519    .open(root.join(".usage"))
520    .ok()?;
521  file.lock().ok()?;
522  Some(file)
523}
524
525/// The tally `file` holds; `None` when it is empty (new) or unreadable (a write a kill cut short).
526fn read_usage(file: &mut fs::File) -> Option<Usage> {
527  use std::io::{Seek, SeekFrom};
528  let mut raw = String::new();
529  file.seek(SeekFrom::Start(0)).ok()?;
530  file.read_to_string(&mut raw).ok()?;
531  let mut lines = raw.lines();
532  Some(Usage {
533    bytes:  lines.next()?.parse().ok()?,
534    walked: lines.next()?.parse().ok()?,
535  })
536}
537
538fn write_usage(file: &mut fs::File, usage: Usage) {
539  use std::io::{Seek, SeekFrom, Write};
540  let body = format!("{}\n{}\n", usage.bytes, usage.walked);
541  let _ = file
542    .seek(SeekFrom::Start(0))
543    .and_then(|_| file.set_len(0))
544    .and_then(|_| file.write_all(body.as_bytes()));
545}
546
547fn unix_secs(t: std::time::SystemTime) -> u64 {
548  t.duration_since(std::time::UNIX_EPOCH)
549    .map_or(0, |d| d.as_secs())
550}
551
552/// Count an insertion of `added` bytes, and prune when that is due ([`prune_if_due`]). Errors are
553/// non-fatal. Without a cap (`0`) it returns at once, so stale tmp files stay too.
554fn prune_if_over_cap(root: &Path, added: u64) {
555  prune_if_due(root, added, max_bytes(), std::time::SystemTime::now())
556}
557
558/// [`prune_if_over_cap`] under `cap` at time `now`: the cache is walked and pruned when the tally
559/// passes the cap, when its last walk is over [`STALE_TMP_AGE`] old, or when there is no tally.
560fn prune_if_due(root: &Path, added: u64, cap: u64, now: std::time::SystemTime) {
561  if cap == 0 {
562    return;
563  }
564  // A clock under an hour past the epoch has no stale tmp; the size cap still applies.
565  let stale_before = now
566    .checked_sub(STALE_TMP_AGE)
567    .unwrap_or(std::time::UNIX_EPOCH);
568  let due = lock_usage(root).is_none_or(|mut file| match read_usage(&mut file) {
569    Some(usage) => {
570      let bytes = usage.bytes.saturating_add(added);
571      write_usage(&mut file, Usage { bytes, ..usage });
572      bytes > cap || usage.walked < unix_secs(stale_before)
573    },
574    None => true,
575  });
576  if due {
577    prune(root, cap, now, stale_before);
578  }
579}
580
581/// When a file's inode last changed: a tmp an older binary hard-linked from an old output keeps the
582/// output's mtime, but `link()` sets its ctime.
583#[cfg(unix)]
584fn changed(meta: &fs::Metadata) -> Option<std::time::SystemTime> {
585  use std::os::unix::fs::MetadataExt;
586  let since_epoch = std::time::Duration::new(
587    u64::try_from(meta.ctime()).ok()?,
588    u32::try_from(meta.ctime_nsec()).ok()?,
589  );
590  std::time::UNIX_EPOCH.checked_add(since_epoch)
591}
592
593#[cfg(not(unix))]
594fn changed(meta: &fs::Metadata) -> Option<std::time::SystemTime> { meta.modified().ok() }
595
596/// Walk the cache and total up its entries; over `cap`, delete the oldest (by mtime) until the total
597/// is under [`LOW_WATER_PERCENT`] of it; remove the `.tmp.` files changed before `stale_before`; and
598/// restart the usage tally from the total kept, walked at `now`. Only one process walks at a time
599/// (advisory lock); an insertion during the walk stays counted.
600fn prune(root: &Path, cap: u64, now: std::time::SystemTime, stale_before: std::time::SystemTime) {
601  let Some(_lock) = acquire_prune_lock(root) else {
602    // Another process is pruning; let it work.
603    return;
604  };
605  let tallied = || {
606    lock_usage(root)
607      .and_then(|mut file| read_usage(&mut file))
608      .map_or(0, |usage| usage.bytes)
609  };
610  let before = tallied();
611  let mut entries: Vec<(PathBuf, u64, std::time::SystemTime)> = Vec::new();
612  let mut total: u64 = 0;
613  let Ok(shard_iter) = fs::read_dir(root) else {
614    return;
615  };
616  for shard in shard_iter.flatten() {
617    let path = shard.path();
618    let Ok(meta) = shard.metadata() else { continue };
619    // Skip non-dirs (e.g. .prune.lock, .usage).
620    if !meta.is_dir() {
621      continue;
622    }
623    let Ok(entry_iter) = fs::read_dir(&path) else {
624      continue;
625    };
626    for entry in entry_iter.flatten() {
627      let path = entry.path();
628      let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
629        continue;
630      };
631      // A tmp sidecar is an install in flight, or one a killed process never finished: removed once
632      // older than any install takes. Dim metadata follows its parent's lifecycle.
633      if name.contains(".tmp.") {
634        let stale = entry
635          .metadata()
636          .ok()
637          .and_then(|meta| changed(&meta))
638          .is_some_and(|changed| changed < stale_before);
639        if stale {
640          let _ = fs::remove_file(&path);
641        }
642        continue;
643      }
644      if name.ends_with(".dims") {
645        continue;
646      }
647      let Ok(meta) = entry.metadata() else { continue };
648      let size = meta.len();
649      let mtime = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
650      total = total.saturating_add(size);
651      entries.push((path, size, mtime));
652    }
653  }
654  if total > cap {
655    let low_water = cap / 100 * LOW_WATER_PERCENT;
656    entries.sort_by_key(|(_, _, t)| *t);
657    for (path, size, _) in entries {
658      if total <= low_water {
659        break;
660      }
661      // Tolerate ENOENT: another writer may have raced this entry away.
662      if fs::remove_file(&path).is_ok() {
663        // Also drop the .dims sidecar if present (best-effort).
664        let mut dims = path.into_os_string();
665        dims.push(".dims");
666        let _ = fs::remove_file(PathBuf::from(dims));
667        total = total.saturating_sub(size);
668      }
669    }
670  }
671  if let Some(mut file) = lock_usage(root) {
672    let since = read_usage(&mut file).map_or(0, |usage| usage.bytes.saturating_sub(before));
673    write_usage(&mut file, Usage {
674      bytes:  total.saturating_add(since),
675      walked: unix_secs(now),
676    });
677  }
678  // _lock drops here, releasing the prune lock.
679}
680
681/// Three-state result from a cached conversion. Disambiguates the two
682/// failure modes that would otherwise collapse to `None`:
683///
684/// * `Ok { dims: Some(_) }` — conversion succeeded (or hit), dims known
685/// * `Ok { dims: None }`     — conversion succeeded but dims unknown
686/// * `Failed`                — conversion did not produce a usable output
687#[derive(Debug, Clone, Copy)]
688pub enum ConvertResult {
689  Ok { dims: Option<CachedDims> },
690  Failed,
691}
692
693impl ConvertResult {
694  pub fn is_ok(&self) -> bool { matches!(self, ConvertResult::Ok { .. }) }
695  pub fn dims(&self) -> Option<CachedDims> {
696    match self {
697      ConvertResult::Ok { dims } => *dims,
698      ConvertResult::Failed => None,
699    }
700  }
701}
702
703/// Cache-aware wrapper around any `(source, dest) -> bool` conversion
704/// that also wants to round-trip dimensions through the cache.
705///
706/// `measure` runs on the freshly-produced `dest` and feeds the cache
707/// for next time. On a cache hit `measure` is NOT called — the cached
708/// `.dims` value is returned instead.
709///
710/// Callers without a dimension hook can pass `measure = || None` to
711/// get the bytes-only cache behaviour.
712///
713/// `policy` decides whether the shared cache is consulted at all; see
714/// [`CachePolicy`].
715pub fn with_cache_dims<F, M>(
716  policy: CachePolicy,
717  source: &str,
718  digest: Option<&SourceDigest>,
719  dest: &str,
720  key: RenderKey,
721  convert: F,
722  measure: M,
723) -> ConvertResult
724where
725  F: FnOnce() -> bool,
726  M: FnOnce() -> Option<CachedDims>,
727{
728  if policy == CachePolicy::Bypass {
729    if !convert() {
730      return ConvertResult::Failed;
731    }
732    return ConvertResult::Ok { dims: measure() };
733  }
734  if let Some(hit) = lookup_digest(source, digest, dest, key) {
735    if let Some(d) = hit.dims {
736      return ConvertResult::Ok { dims: Some(d) };
737    }
738    // Dimensions sidecar missing or unreadable — measure now and
739    // attach so future hits get it for free.
740    let m = measure();
741    if let Some(d) = m {
742      if let (Some(root), Some(hash)) = (cache_root(), source_key(source, digest, key)) {
743        let cached = cache_path(&root, &hash, key.ext);
744        if cached.exists() {
745          write_dims_sidecar(&dims_sidecar(&cached), d);
746        }
747      }
748    }
749    return ConvertResult::Ok { dims: m };
750  }
751  if !convert() {
752    return ConvertResult::Failed;
753  }
754  let dims = measure();
755  store_digest(source, digest, dest, key, dims);
756  ConvertResult::Ok { dims }
757}
758
759/// Bytes-only cache wrapper. Use when the caller doesn't need
760/// dimensions cached (e.g. SVG path where viewBox dims are cheap to
761/// re-read from disk). Returns `true` on success.
762///
763/// `policy` decides whether the shared cache is consulted at all; see
764/// [`CachePolicy`].
765pub fn with_cache<F>(
766  policy: CachePolicy,
767  source: &str,
768  dest: &str,
769  key: RenderKey,
770  convert: F,
771) -> bool
772where
773  F: FnOnce() -> bool,
774{
775  if policy == CachePolicy::Bypass {
776    return convert();
777  }
778  if lookup(source, dest, key).is_some() {
779    return true;
780  }
781  let ok = convert();
782  if ok {
783    store(source, dest, key, None);
784  }
785  ok
786}
787
788#[cfg(test)]
789mod tests {
790  use std::sync::atomic::{AtomicU32, Ordering};
791
792  use super::*;
793
794  /// A test's scratch directory, removed when the test ends (they filled `/tmp`'s inodes).
795  struct TempDir(PathBuf);
796  impl std::ops::Deref for TempDir {
797    type Target = Path;
798
799    fn deref(&self) -> &Path { &self.0 }
800  }
801  impl Drop for TempDir {
802    fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); }
803  }
804
805  fn temp_dir(label: &str) -> TempDir {
806    let nanos = std::time::SystemTime::now()
807      .duration_since(std::time::UNIX_EPOCH)
808      .map(|d| d.as_nanos())
809      .unwrap_or(0);
810    let p = std::env::temp_dir().join(format!("gcache-{label}-{nanos}"));
811    fs::create_dir_all(&p).unwrap();
812    TempDir(p)
813  }
814
815  fn write_bytes(path: &Path, bytes: &[u8]) {
816    if let Some(parent) = path.parent() {
817      fs::create_dir_all(parent).unwrap();
818    }
819    fs::write(path, bytes).unwrap();
820  }
821
822  // These tests exercise the cache itself, so they need a real cache
823  // root — pointed at a scratch directory rather than the developer's
824  // `~/.cache`. One directory is shared across them (with unique source
825  // bytes per test) because the root is read from the environment, which
826  // is process-global.
827  //
828  // The env write is deliberately NOT undone: it stays set for the rest
829  // of the binary's life, and `LATEXML_GRAPHICS_CACHE_DIR` is leaked into
830  // any test that runs afterwards. That is tolerable only because no
831  // other test's correctness depends on the cache root any more — the one
832  // that used to, `graphics::tests::process_coalesces_only_matching_
833  // conversion_options`, now bypasses the cache explicitly via
834  // `CachePolicy::Bypass` instead of racing this setter (issue 401).
835  // Taking the shared `env_lock` keeps the write from interleaving with
836  // that test's `PATH` window.
837  static SHARED_DIR: OnceLock<PathBuf> = OnceLock::new();
838  fn shared_cache_dir() -> &'static Path {
839    SHARED_DIR.get_or_init(|| {
840      // Lives as long as the process (a `static`), so not a removed-on-drop `TempDir`.
841      let nanos = std::time::SystemTime::now()
842        .duration_since(std::time::UNIX_EPOCH)
843        .map(|d| d.as_nanos())
844        .unwrap_or(0);
845      let dir = std::env::temp_dir().join(format!("gcache-shared-{nanos}"));
846      fs::create_dir_all(&dir).unwrap();
847      let _lock = crate::test_env::env_lock()
848        .lock()
849        .unwrap_or_else(|e| e.into_inner());
850      // SAFETY: `set_var` is `unsafe` in edition 2024 because concurrent
851      // env access from another thread is a data race. We hold the
852      // binary-wide `env_lock`, so no other env-mutating test runs
853      // concurrently, and only the first caller runs this initializer.
854      unsafe {
855        std::env::set_var("LATEXML_GRAPHICS_CACHE_DIR", &dir);
856      }
857      dir
858    })
859  }
860
861  static SUFFIX: AtomicU32 = AtomicU32::new(0);
862  fn unique_source_bytes(label: &str) -> Vec<u8> {
863    let n = SUFFIX.fetch_add(1, Ordering::Relaxed);
864    format!("{label}::{n}\n").into_bytes()
865  }
866
867  #[test]
868  fn hash_changes_with_render_key() {
869    let dir = temp_dir("hash");
870    let src = dir.join("a.bin");
871    write_bytes(&src, b"hello");
872    let h_png = hash_key(&src, RenderKey {
873      page:    Some(1),
874      density: 90,
875      ext:     "png",
876    })
877    .unwrap();
878    let h_svg = hash_key(&src, RenderKey {
879      page:    Some(1),
880      density: 0,
881      ext:     "svg",
882    })
883    .unwrap();
884    let h_page2 = hash_key(&src, RenderKey {
885      page:    Some(2),
886      density: 90,
887      ext:     "png",
888    })
889    .unwrap();
890    assert_ne!(h_png, h_svg);
891    assert_ne!(h_png, h_page2);
892  }
893
894  /// SVG keys carry [`SVG_KEY_VERSION`], so an SVG cached before mutool's page ≥ 2 fix misses; every
895  /// other key is the unsalted hash of before, so the cached PNGs still hit.
896  #[test]
897  fn svg_keys_are_salted_and_png_keys_are_not() {
898    let dir = temp_dir("salt");
899    let src = dir.join("a.pdf");
900    write_bytes(&src, b"%PDF-1.5 two pages");
901    let unsalted = |key: RenderKey| {
902      let mut hasher = Sha256::new();
903      hasher.update(b"%PDF-1.5 two pages");
904      hasher.update(key.page.unwrap_or(0).to_le_bytes());
905      hasher.update(key.density.to_le_bytes());
906      hasher.update(key.ext.as_bytes());
907      let digest = hasher.finalize();
908      digest
909        .iter()
910        .map(|b| format!("{b:02x}"))
911        .collect::<String>()
912    };
913    for (ext, density, salted) in [("svg", 0, true), ("png", 90, false), ("jpg", 90, false)] {
914      for page in [None, Some(1), Some(2)] {
915        let key = RenderKey { page, density, ext };
916        let hash = hash_key(&src, key).unwrap();
917        assert_eq!(hash != unsalted(key), salted, "{ext} page {page:?}");
918      }
919    }
920  }
921
922  #[test]
923  fn first_call_misses_second_call_hits() {
924    let _ = shared_cache_dir();
925    reset_stats();
926    let dir = temp_dir("hit");
927    let bytes = unique_source_bytes("hit");
928    let src = dir.join("src.bin");
929    write_bytes(&src, &bytes);
930    let dest1 = dir.join("out1.png");
931    let dest2 = dir.join("out2.png");
932    let key = RenderKey {
933      page:    None,
934      density: 90,
935      ext:     "png",
936    };
937    let mut spawn_calls = 0u32;
938    let ok1 = with_cache(
939      CachePolicy::Shared,
940      src.to_str().unwrap(),
941      dest1.to_str().unwrap(),
942      key,
943      || {
944        spawn_calls += 1;
945        fs::write(&dest1, b"converted-output").unwrap();
946        true
947      },
948    );
949    assert!(ok1);
950    assert_eq!(spawn_calls, 1, "first call must spawn");
951
952    let ok2 = with_cache(
953      CachePolicy::Shared,
954      src.to_str().unwrap(),
955      dest2.to_str().unwrap(),
956      key,
957      || {
958        spawn_calls += 1;
959        true
960      },
961    );
962    assert!(ok2);
963    assert_eq!(spawn_calls, 1, "second call must NOT spawn");
964    assert_eq!(
965      fs::read(&dest2).unwrap(),
966      b"converted-output",
967      "cache hit must deliver the original bytes"
968    );
969  }
970
971  #[test]
972  fn dimensions_round_trip_through_cache() {
973    let _ = shared_cache_dir();
974    let dir = temp_dir("dims");
975    let bytes = unique_source_bytes("dims");
976    let src = dir.join("src.bin");
977    write_bytes(&src, &bytes);
978    let dest1 = dir.join("out1.png");
979    let dest2 = dir.join("out2.png");
980    let key = RenderKey {
981      page:    None,
982      density: 90,
983      ext:     "png",
984    };
985    let mut measure_calls = 0u32;
986    // First call: miss → spawn + measure → store dims.
987    let dims1 = with_cache_dims(
988      CachePolicy::Shared,
989      src.to_str().unwrap(),
990      None,
991      dest1.to_str().unwrap(),
992      key,
993      || {
994        fs::write(&dest1, b"png-bytes").unwrap();
995        true
996      },
997      || {
998        measure_calls += 1;
999        Some(CachedDims { width: 640, height: 480 })
1000      },
1001    );
1002    assert!(matches!(dims1, ConvertResult::Ok {
1003      dims: Some(CachedDims { width: 640, height: 480 }),
1004    }));
1005    assert_eq!(measure_calls, 1, "miss measures dims");
1006
1007    // Second call: hit → sidecar replay, NO spawn, NO measure.
1008    let dims2 = with_cache_dims(
1009      CachePolicy::Shared,
1010      src.to_str().unwrap(),
1011      Some(&SourceDigest::of_file(&src).unwrap()),
1012      dest2.to_str().unwrap(),
1013      key,
1014      || {
1015        panic!("hit must skip the conversion closure");
1016      },
1017      || {
1018        measure_calls += 1;
1019        Some(CachedDims { width: 999, height: 999 })
1020      },
1021    );
1022    assert!(matches!(dims2, ConvertResult::Ok {
1023      dims: Some(CachedDims { width: 640, height: 480 }),
1024    }));
1025    assert_eq!(measure_calls, 1, "hit replays sidecar dims, no re-measure");
1026  }
1027
1028  /// Each destination gets its own copy of a cache entry (GFXHARDLINK): an output edited in place
1029  /// (an append) leaves the cache entry and every other destination's file as they were.
1030  #[test]
1031  fn an_output_edited_in_place_leaves_the_cache_and_its_siblings() {
1032    use std::io::Write as _;
1033    let root = shared_cache_dir();
1034    let dir = temp_dir("edit-in-place");
1035    let src = dir.join("src.bin");
1036    write_bytes(&src, &unique_source_bytes("edit-in-place"));
1037    let key = RenderKey {
1038      page:    None,
1039      density: 0,
1040      ext:     "svg",
1041    };
1042    let cached = cache_path(root, &hash_key(&src, key).unwrap(), key.ext);
1043    let [out1, out2, out3] = ["out1", "out2", "out3"].map(|d| dir.join(d).join("fig.svg"));
1044    fs::create_dir_all(out1.parent().unwrap()).unwrap();
1045    // out1 converts and stores; out2 is served from the cache.
1046    let convert = || {
1047      fs::write(&out1, b"<svg/>").unwrap();
1048      true
1049    };
1050    assert!(with_cache(
1051      CachePolicy::Shared,
1052      src.to_str().unwrap(),
1053      out1.to_str().unwrap(),
1054      key,
1055      convert
1056    ));
1057    assert!(lookup(src.to_str().unwrap(), out2.to_str().unwrap(), key).is_some());
1058    for edited in [&out1, &out2] {
1059      let mut file = fs::OpenOptions::new().append(true).open(edited).unwrap();
1060      file.write_all(b"<!-- edited -->").unwrap();
1061    }
1062    assert_eq!(fs::read(&cached).unwrap(), b"<svg/>", "the cache entry");
1063    assert!(lookup(src.to_str().unwrap(), out3.to_str().unwrap(), key).is_some());
1064    let read = |p: &Path| String::from_utf8(fs::read(p).unwrap()).unwrap();
1065    assert_eq!([read(&out1), read(&out2), read(&out3)], [
1066      "<svg/><!-- edited -->",
1067      "<svg/><!-- edited -->",
1068      "<svg/>"
1069    ]);
1070  }
1071
1072  #[test]
1073  fn different_render_keys_dont_share_cache() {
1074    let _ = shared_cache_dir();
1075    let dir = temp_dir("keys");
1076    let bytes = unique_source_bytes("keys");
1077    let src = dir.join("src.bin");
1078    write_bytes(&src, &bytes);
1079    let dest_png = dir.join("out.png");
1080    let dest_svg = dir.join("out.svg");
1081    let key_png = RenderKey {
1082      page:    None,
1083      density: 90,
1084      ext:     "png",
1085    };
1086    let key_svg = RenderKey {
1087      page:    None,
1088      density: 0,
1089      ext:     "svg",
1090    };
1091    let mut calls = 0u32;
1092    let ok_png = with_cache(
1093      CachePolicy::Shared,
1094      src.to_str().unwrap(),
1095      dest_png.to_str().unwrap(),
1096      key_png,
1097      || {
1098        calls += 1;
1099        fs::write(&dest_png, b"png-bytes").unwrap();
1100        true
1101      },
1102    );
1103    let ok_svg = with_cache(
1104      CachePolicy::Shared,
1105      src.to_str().unwrap(),
1106      dest_svg.to_str().unwrap(),
1107      key_svg,
1108      || {
1109        calls += 1;
1110        fs::write(&dest_svg, b"svg-bytes").unwrap();
1111        true
1112      },
1113    );
1114    assert!(ok_png && ok_svg);
1115    assert_eq!(calls, 2, "distinct render keys must spawn separately");
1116  }
1117
1118  #[test]
1119  fn miss_failure_does_not_pollute_cache() {
1120    let _ = shared_cache_dir();
1121    let dir = temp_dir("miss");
1122    let bytes = unique_source_bytes("miss");
1123    let src = dir.join("src.bin");
1124    write_bytes(&src, &bytes);
1125    let dest = dir.join("out.png");
1126    let key = RenderKey {
1127      page:    None,
1128      density: 90,
1129      ext:     "png",
1130    };
1131    let mut calls = 0u32;
1132    let ok = with_cache(
1133      CachePolicy::Shared,
1134      src.to_str().unwrap(),
1135      dest.to_str().unwrap(),
1136      key,
1137      || {
1138        calls += 1;
1139        // simulate spawn failure: did NOT write dest, returned false
1140        false
1141      },
1142    );
1143    assert!(!ok);
1144    assert_eq!(calls, 1);
1145    let ok2 = with_cache(
1146      CachePolicy::Shared,
1147      src.to_str().unwrap(),
1148      dest.to_str().unwrap(),
1149      key,
1150      || {
1151        calls += 1;
1152        false
1153      },
1154    );
1155    assert!(!ok2);
1156    assert_eq!(calls, 2, "cache must not memoise failures");
1157  }
1158
1159  #[test]
1160  fn missing_disk_file_triggers_quiet_regeneration() {
1161    // Scenario: an earlier `store()` registered a cache entry, but
1162    // its on-disk file has since been removed (manual `rm`, another
1163    // tool clearing /tmp, or an aggressive prune from a parallel
1164    // worker on a different machine sharing the same network FS).
1165    // The next lookup must NOT raise any error, must NOT panic,
1166    // must report a miss, and the next `with_cache` call must
1167    // regenerate from the conversion closure and rewrite the entry.
1168    let _ = shared_cache_dir();
1169    let dir = temp_dir("missing-disk");
1170    let bytes = unique_source_bytes("missing-disk");
1171    let src = dir.join("src.bin");
1172    write_bytes(&src, &bytes);
1173    let dest1 = dir.join("out1.png");
1174    let dest2 = dir.join("out2.png");
1175    let key = RenderKey {
1176      page:    None,
1177      density: 90,
1178      ext:     "png",
1179    };
1180    let mut calls = 0u32;
1181    // Step 1: register a fresh entry via with_cache. Cache file is on disk.
1182    let ok = with_cache(
1183      CachePolicy::Shared,
1184      src.to_str().unwrap(),
1185      dest1.to_str().unwrap(),
1186      key,
1187      || {
1188        calls += 1;
1189        fs::write(&dest1, b"v1-bytes").unwrap();
1190        true
1191      },
1192    );
1193    assert!(ok);
1194    assert_eq!(calls, 1);
1195
1196    // Step 2: locate the cache file and DELETE it from disk, simulating
1197    // an externally-deleted entry. The `.dims` sidecar (if present) we
1198    // leave behind to test that orphan-sidecar tolerance also works.
1199    let root = shared_cache_dir();
1200    let hash = hash_key(&src, key).unwrap();
1201    let cached = cache_path(root, &hash, key.ext);
1202    assert!(cached.exists(), "step-1 should have written the cache file");
1203    fs::remove_file(&cached).unwrap();
1204    assert!(!cached.exists(), "cache file should now be gone");
1205
1206    // Step 3: a fresh lookup must return None — no panic, no error log.
1207    // (The function returns Option, so we just check the variant.)
1208    let hit = lookup(src.to_str().unwrap(), dest2.to_str().unwrap(), key);
1209    assert!(
1210      hit.is_none(),
1211      "lookup must report a miss when disk file is gone"
1212    );
1213
1214    // Step 4: with_cache must regenerate quietly. The closure should fire,
1215    // producing fresh output bytes. After this, the cache should hold the
1216    // new entry again.
1217    let ok2 = with_cache(
1218      CachePolicy::Shared,
1219      src.to_str().unwrap(),
1220      dest2.to_str().unwrap(),
1221      key,
1222      || {
1223        calls += 1;
1224        fs::write(&dest2, b"v2-bytes-regenerated").unwrap();
1225        true
1226      },
1227    );
1228    assert!(ok2);
1229    assert_eq!(
1230      calls, 2,
1231      "regeneration must run the conversion closure exactly once"
1232    );
1233    assert_eq!(
1234      fs::read(&dest2).unwrap(),
1235      b"v2-bytes-regenerated",
1236      "dest must contain the regenerated bytes"
1237    );
1238    assert!(
1239      cached.exists(),
1240      "cache file should be restored on disk after regeneration"
1241    );
1242
1243    // Step 5: a third lookup should now hit again (full self-heal).
1244    let dest3 = dir.join("out3.png");
1245    let hit3 = lookup(src.to_str().unwrap(), dest3.to_str().unwrap(), key);
1246    assert!(hit3.is_some(), "self-heal: subsequent lookup must hit");
1247    assert_eq!(fs::read(&dest3).unwrap(), b"v2-bytes-regenerated");
1248  }
1249
1250  #[test]
1251  fn orphan_dims_sidecar_is_silently_overwritten() {
1252    // Scenario: cache file missing, but a stale .dims sidecar
1253    // (perhaps from an aborted concurrent write) is still on disk.
1254    // The lookup must miss (no error), the regeneration must succeed,
1255    // and the new .dims sidecar must contain the FRESH dimensions —
1256    // not the stale ones.
1257    let _ = shared_cache_dir();
1258    let dir = temp_dir("orphan-dims");
1259    let bytes = unique_source_bytes("orphan-dims");
1260    let src = dir.join("src.bin");
1261    write_bytes(&src, &bytes);
1262    let key = RenderKey {
1263      page:    None,
1264      density: 90,
1265      ext:     "png",
1266    };
1267    let root = shared_cache_dir();
1268    let hash = hash_key(&src, key).unwrap();
1269    let cached = cache_path(root, &hash, key.ext);
1270    // Manually plant a stale .dims sidecar without the main file.
1271    let sidecar = dims_sidecar(&cached);
1272    if let Some(parent) = sidecar.parent() {
1273      fs::create_dir_all(parent).unwrap();
1274    }
1275    fs::write(&sidecar, "1234\n5678\n").unwrap();
1276    assert!(sidecar.exists());
1277    assert!(!cached.exists());
1278
1279    let dest = dir.join("out.png");
1280    let result = with_cache_dims(
1281      CachePolicy::Shared,
1282      src.to_str().unwrap(),
1283      None,
1284      dest.to_str().unwrap(),
1285      key,
1286      || {
1287        fs::write(&dest, b"fresh").unwrap();
1288        true
1289      },
1290      || Some(CachedDims { width: 100, height: 200 }),
1291    );
1292    assert!(matches!(result, ConvertResult::Ok {
1293      dims: Some(CachedDims { width: 100, height: 200 }),
1294    }));
1295    // The .dims sidecar should now contain the FRESH dims, not the stale.
1296    let after = read_dims_sidecar(&sidecar).unwrap();
1297    assert_eq!(after, CachedDims { width: 100, height: 200 });
1298  }
1299
1300  #[test]
1301  fn concurrent_writers_converge_to_one_cache_entry() {
1302    // Multi-process safety simulation: spawn 8 threads, all writing
1303    // the SAME key, all writing distinct dests. After all join, the
1304    // cache must contain exactly one final file (no leftover .tmp.*
1305    // sidecars), and a follow-up hit must succeed.
1306    let _ = shared_cache_dir();
1307    let dir = temp_dir("concurrent");
1308    let bytes = unique_source_bytes("concurrent");
1309    let src = dir.join("src.bin");
1310    write_bytes(&src, &bytes);
1311    let key = RenderKey {
1312      page:    None,
1313      density: 90,
1314      ext:     "png",
1315    };
1316
1317    let src_s = src.to_string_lossy().into_owned();
1318    let dir_s = dir.to_string_lossy().into_owned();
1319
1320    std::thread::scope(|s| {
1321      for i in 0..8 {
1322        let src_s = src_s.clone();
1323        let dir_s = dir_s.clone();
1324        s.spawn(move || {
1325          let dest = format!("{dir_s}/dest_{i}.png");
1326          with_cache(CachePolicy::Shared, &src_s, &dest, key, || {
1327            // Tiny artificial work to encourage interleaving.
1328            std::thread::sleep(std::time::Duration::from_millis(5));
1329            fs::write(&dest, b"final-bytes").unwrap();
1330            true
1331          });
1332        });
1333      }
1334    });
1335
1336    // Verify exactly one cache file for this hash, no leftover tmp.
1337    let root = shared_cache_dir();
1338    let hash = hash_key(&src, key).unwrap();
1339    let cached = cache_path(root, &hash, key.ext);
1340    assert!(
1341      cached.exists(),
1342      "cache entry must exist after concurrent writes"
1343    );
1344    let shard_dir = cached.parent().unwrap();
1345    let tmp_count = fs::read_dir(shard_dir)
1346      .unwrap()
1347      .filter_map(Result::ok)
1348      .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
1349      .count();
1350    assert_eq!(
1351      tmp_count, 0,
1352      "no leftover tmp sidecars after concurrent writes"
1353    );
1354
1355    // A fresh hit must still succeed and deliver the correct bytes.
1356    let dest_check = dir.join("dest_check.png");
1357    let hit = lookup(&src_s, dest_check.to_str().unwrap(), key);
1358    assert!(hit.is_some(), "follow-up lookup must hit");
1359    assert_eq!(fs::read(&dest_check).unwrap(), b"final-bytes");
1360  }
1361
1362  /// A shard directory's file names holding `.tmp.`.
1363  fn tmp_names(shard: &Path) -> Vec<String> {
1364    fs::read_dir(shard)
1365      .unwrap()
1366      .flatten()
1367      .map(|e| e.file_name().to_string_lossy().into_owned())
1368      .filter(|name| name.contains(".tmp."))
1369      .collect()
1370  }
1371
1372  /// A store whose install fails leaves neither its tmp file nor a `.dims` sidecar, which the prune
1373  /// reclaims only with its entry: a missing output (the copy fails before the tmp exists), an output
1374  /// that fails mid-copy (a partial tmp), a directory in the entry's place (the rename fails).
1375  #[test]
1376  fn a_failed_install_leaves_neither_tmp_nor_dims() {
1377    let root = shared_cache_dir();
1378    let dir = temp_dir("install");
1379    let key = RenderKey {
1380      page:    None,
1381      density: 90,
1382      ext:     "png",
1383    };
1384    let missing = dir.join("missing.png");
1385    let in_the_way = dir.join("in-the-way.png");
1386    write_bytes(&in_the_way, b"png");
1387    let mut cases = vec![("missing", missing), ("in-the-way", in_the_way)];
1388    // Reading `/proc/self/mem` at offset 0 (unmapped) fails with EIO after the copy has created its target.
1389    if cfg!(target_os = "linux") {
1390      cases.push(("unreadable", PathBuf::from("/proc/self/mem")));
1391    }
1392    for (label, dest) in cases {
1393      let src = dir.join(format!("{label}.src"));
1394      write_bytes(&src, &unique_source_bytes(label));
1395      let cached = cache_path(root, &hash_key(&src, key).unwrap(), key.ext);
1396      if label == "in-the-way" {
1397        fs::create_dir_all(cached.join("occupied")).unwrap();
1398      }
1399      store(
1400        src.to_str().unwrap(),
1401        dest.to_str().unwrap(),
1402        key,
1403        Some(CachedDims { width: 1, height: 2 }),
1404      );
1405      let entry = cached.file_name().unwrap().to_string_lossy().into_owned();
1406      let shard = cached.parent().unwrap();
1407      let leftovers: Vec<String> = fs::read_dir(shard)
1408        .unwrap()
1409        .flatten()
1410        .map(|e| e.file_name().to_string_lossy().into_owned())
1411        .filter(|name| name.starts_with(&entry) && *name != entry)
1412        .collect();
1413      assert_eq!(leftovers, Vec::<String>::new(), "{label}");
1414      assert_eq!(cached.is_dir(), label == "in-the-way", "{label}");
1415      if label == "in-the-way" {
1416        fs::remove_dir_all(&cached).unwrap();
1417      }
1418    }
1419  }
1420
1421  /// Over the cap a prune leaves 90 % of it (GCACHECHURN); an insertion that keeps the usage tally
1422  /// under the cap walks nothing, which an entry planted past the tally shows by surviving; an hour
1423  /// after the last walk the next insertion walks again, reclaiming the stale tmp files.
1424  #[test]
1425  fn a_prune_leaves_the_low_water_mark_and_a_later_insertion_walks_nothing() {
1426    let root = temp_dir("low-water");
1427    let cap = 1000;
1428    let start = std::time::SystemTime::now();
1429    let entry = |i: u64| {
1430      root
1431        .join(format!("{:02x}", i % 4))
1432        .join(format!("{i:064x}.png"))
1433    };
1434    // Twelve entries of 100 bytes, oldest first.
1435    for i in 0..12 {
1436      write_bytes(&entry(i), &[b'x'; 100]);
1437      let mtime = start - std::time::Duration::from_secs(1200 - i * 60);
1438      fs::File::options()
1439        .write(true)
1440        .open(entry(i))
1441        .unwrap()
1442        .set_modified(mtime)
1443        .unwrap();
1444    }
1445    let present = || {
1446      (0..20)
1447        .filter(|&i| entry(i).is_file())
1448        .collect::<Vec<u64>>()
1449    };
1450    let tally = || read_usage(&mut lock_usage(&root).unwrap());
1451    // No tally yet: the first insertion walks, and 1200 bytes over a cap of 1000 leave 900.
1452    prune_if_due(&root, 100, cap, start);
1453    assert_eq!(present(), (3..12).collect::<Vec<u64>>());
1454    assert_eq!(
1455      tally(),
1456      Some(Usage {
1457        bytes:  900,
1458        walked: unix_secs(start),
1459      })
1460    );
1461    // 500 bytes the tally never saw: an insertion of 50 that keeps it at 950 walks nothing.
1462    write_bytes(&entry(12), &[b'x'; 500]);
1463    prune_if_due(&root, 50, cap, start);
1464    assert_eq!(present(), (3..13).collect::<Vec<u64>>());
1465    assert_eq!(
1466      tally(),
1467      Some(Usage {
1468        bytes:  950,
1469        walked: unix_secs(start),
1470      })
1471    );
1472    // The next 100 pass the cap: the walk finds 1400 and keeps the newest 900 (entry 12 is newest).
1473    prune_if_due(&root, 100, cap, start);
1474    assert_eq!(present(), vec![8, 9, 10, 11, 12]);
1475    assert_eq!(
1476      tally(),
1477      Some(Usage {
1478        bytes:  900,
1479        walked: unix_secs(start),
1480      })
1481    );
1482    // Two hours on, an insertion under the cap walks: the stale tmp goes, the entries stay.
1483    let tmp = entry(13).with_extension("png.tmp.17.1");
1484    write_bytes(&tmp, b"partial");
1485    let later = start + std::time::Duration::from_secs(7200);
1486    prune_if_due(&root, 0, cap, later);
1487    assert!(!tmp.exists(), "the stale tmp is reclaimed");
1488    assert_eq!(present(), vec![8, 9, 10, 11, 12]);
1489    assert_eq!(
1490      tally(),
1491      Some(Usage {
1492        bytes:  900,
1493        walked: unix_secs(later),
1494      })
1495    );
1496  }
1497
1498  #[test]
1499  fn a_prune_reclaims_the_tmp_files_of_killed_installs() {
1500    let root = temp_dir("prune-tmp");
1501    let shard = root.join("ab");
1502    let old = shard.join("abcdef.png.tmp.17.1");
1503    let old_dims = shard.join("abcdef.png.dims.tmp.17.2");
1504    let entry = shard.join("abcdef.png");
1505    let output = root.join("out.png");
1506    for path in [&old, &old_dims, &entry, &output] {
1507      write_bytes(path, b"bytes");
1508    }
1509    let two_hours_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(7200);
1510    for path in [&entry, &output] {
1511      fs::File::options()
1512        .write(true)
1513        .open(path)
1514        .unwrap()
1515        .set_modified(two_hours_ago)
1516        .unwrap();
1517    }
1518    // The kernel stamps inode times from a coarse clock: a margin on each side of the cutoff.
1519    std::thread::sleep(std::time::Duration::from_millis(50));
1520    let stale_before = std::time::SystemTime::now();
1521    std::thread::sleep(std::time::Duration::from_millis(50));
1522    // An install in flight, hard-linked from an old output: its mtime is the output's, its ctime the link's.
1523    fs::hard_link(&output, shard.join("abcdef.png.tmp.18.3")).unwrap();
1524    prune(
1525      &root,
1526      DEFAULT_MAX_MB << 20,
1527      std::time::SystemTime::now(),
1528      stale_before,
1529    );
1530    // On Unix the link's ctime keeps the in-flight tmp. Elsewhere the age is the mtime (std exposes no ctime), so it
1531    // is reclaimed: the install's rename then fails and the image is just not cached that time.
1532    let in_flight_kept: Vec<String> = if cfg!(unix) {
1533      vec!["abcdef.png.tmp.18.3".to_string()]
1534    } else {
1535      Vec::new()
1536    };
1537    assert_eq!(tmp_names(&shard), in_flight_kept);
1538    assert!(
1539      entry.is_file(),
1540      "an entry under the cap is kept, however old"
1541    );
1542  }
1543}