Expand description
Content-addressed graphics cache.
Every convert_image / convert_image_svg call rasterises a
self-contained source file (PDF / EPS / PNG / SVG) with a small set
of render-shaping inputs (page, density, target format). Across a
canvas of arXiv submissions the same byte content recurs constantly
— common journal logos, reused author-affiliation marks, and
regenerated runs of the same paper. PERFORMANCE.md §5 records the
graphics phase as 36.5% of corpus wall, so a cache that hits
even a third of the time shaves ~11% off corpus wall.
§Heritage: Perl LaTeXML.cache
The Perl post-processor stores a tied BerkeleyDB hash named
LaTeXML.cache per output directory. Keys are built from the
processor class, the source path, and the transform string; values
are "dest|width|height" strings. The features we mirror are
listed below.
- Disable flag (Perl:
nocache) → envLATEXML_GRAPHICS_CACHE_OFF. - Names (Perl:
key → dest) → the document cache,LaTeXML-oxide.cachein the destination directory (crate::document::DocCache,crate::resource_cache); this cache holds the converted bytes only. - Re-use across runs (Perl: one .cache per dest dir) → global XDG cache, shared across all conversions on the host. This is a strict superset of the Perl behaviour: cross-paper sharing, plus reproducible content-keying instead of path-keying.
- Source-staleness check (Perl compared source mtime to cached output mtime) → unnecessary here: the cache key is SHA-256 of the source bytes, so any source edit produces a different key.
- Cached dimensions (Perl: width/height in the cached value) → sidecar
<hash>.<ext>.dimsfile containingwidth\nheight\n. Lookup returns(success, dims); callers skip theread_image_dimensionssyscall on hits.
Beyond Perl: content-hash keying gives stricter staleness; XDG placement gives cross-paper reuse; multi-process safety (below) lets canvas sweeps share the cache without corruption.
§Cache key
SHA-256 of:
source bytes ‖ page ‖ density ‖ target-extension [‖ SVG_KEY_VERSION]
The page/density bytes are appended as 4-byte little-endian; the
extension is appended as ASCII lower-case bytes, and an svg key ends
with SVG_KEY_VERSION, which retires cached SVGs. Bytes-only keying
makes the cache reproducible across machines and gives near-zero
collision risk for our use.
§On-disk layout
$XDG_CACHE_HOME/latexml-oxide/graphics/<aa>/<full-hash>.<ext>
$XDG_CACHE_HOME/latexml-oxide/graphics/<aa>/<full-hash>.<ext>.dims
$XDG_CACHE_HOME/latexml-oxide/graphics/.prune.lock
$XDG_CACHE_HOME/latexml-oxide/graphics/.usage
Sharded by the first two hex characters of the hash to keep any one directory’s entry count bounded (worst case ~1/256th of the total cache size).
$XDG_CACHE_HOME falls back to $HOME/.cache per the XDG spec.
§Multi-process safety
The cache is designed to be shared by parallel cortex_worker
processes within a canvas sweep. Concurrency guarantees:
- Concurrent writes to the same key: each writer copies into a private
.<stem>.tmp.<pid>.<seq>.<ext>file (crate::writer::Staged) then issues a singlerename(2)into the final path.renameis atomic on the same filesystem; if two writers race, the lastrenamewins, and because both sources are byte-equivalent the outcome is correct. - Concurrent reads + writes: a reader copies the cached file into the destination the same way (a staged copy renamed onto it). An entry the writers replace by rename is never written through, so the reader’s open file keeps the bytes it opened. If the cache file is unlinked between hash computation and the copy, the reader gets a miss and falls through — no data corruption.
- Concurrent prunes: prune holds
flock(LOCK_EX | LOCK_NB)on.prune.lock. If another process already holds the lock, this one skips its prune attempt. Only one prune runs at a time per machine. The prune itself walks the dir, sorts by mtime, deletes oldest until under the low-water mark — and toleratesENOENT(another writer could have re-used the entry concurrently). It also removes every.tmp.sidecar changed (ctime on Unix) over an hour ago: a killed process’s unfinished install. - The usage tally:
.usageholds the bytes the last walk counted plus every insertion since, and when that walk ran; an insertion adds its size under an exclusive lock on the file (held for one read and one write). Drift — an entry two racing writers both count, one removed by hand, one an older binary added — lasts until the next walk recounts. - Destination ↔ cache: every destination holds its own copy, so an output edited in place (a post-processing step, a user) changes neither the cache entry nor another document’s copy, and a prune that deletes the entry leaves every destination whole.
These guarantees hold on any POSIX filesystem, and on Windows, where File::lock is
LockFileEx. (The prune lock there was a create_new sentinel no one removed, so no prune ran
after a cache’s first insertion.)
§Lifecycle
- Hit: copy the cache file into the destination (
fs::copy, which shares the extents where the filesystem can: Linuxcopy_file_rangeon btrfs or XFS). Read the.dimssidecar if present. - Miss-then-success: copy the produced destination back into the cache. Write the
.dimssidecar alongside. - LRU prune: each insertion adds its size to the usage tally and checks it against the cap
(
LATEXML_GRAPHICS_CACHE_MAX_MB, default 2048 = 2 GB). Over the cap, or an hour after the last walk (which also recounts the tally and reclaims stale.tmp.files), it holds the prune lock, walks the cache, sorts entries by mtime ascending and deletes the oldest until the total is under 90 % of the cap, so the next tenth of the cap is inserted without a walk (each walk stats every entry: 20-29 ms on a 2 GB cache, GCACHECHURN). File access on read also refreshes the mtime so frequently-hit entries survive.
§Disable / tune
LATEXML_GRAPHICS_CACHE_OFF=1— bypass entirely (read+write both skipped). The wrapper devolves to the bare conversion call.LATEXML_GRAPHICS_CACHE_DIR=/path— override the cache directory.LATEXML_GRAPHICS_CACHE_MAX_MB=N— cache size cap.
Structs§
- Cache
Hit - Result of a cache lookup.
- Cached
Dims - Cached dimensions for an image. Mirrors Perl
LaTeXML.cache"dest|width|height"value triple (we already have the dest path at the call site — only the dimensions need round-tripping). - Render
Key - Render-shaping inputs that go into the cache key alongside source
bytes. Two calls with the same
RenderKeyMUST produce byte-equivalent output (modulo metadata variation tools like ImageMagick are known to introduce — seecompare_outputs_strictaudit in the spawn paths). - Source
Digest - A source file’s SHA-256 state after its bytes: its content identity (the graphics pass’s dedupe key) and, extended
by a
RenderKey, its cache key, from one read of the file.
Enums§
- Cache
Policy - Whether a given conversion consults the shared graphics cache.
- Convert
Result - Three-state result from a cached conversion. Disambiguates the two
failure modes that would otherwise collapse to
None:
Functions§
- cached_
output - The cache’s entry for
(source, key)whenpolicyconsults the cache and it holds one: what a conversion of the source installs (digest: the source’s, when read already). - lookup
- Look the cache up. On hit: copy into
dest, refresh the cache entry’s mtime, returnSome(CacheHit{dims}). On miss or any I/O hiccup, returnNoneso the caller falls through to a real conversion. - stats
- Return
(hits, misses)since process start. Useful for telemetry and the post-run summary log line. - store
- Insert
dest(and optionally its dimensions) into the cache under(source, key). Idempotent and best-effort: any I/O failure leaves the cache unchanged. - with_
cache - Bytes-only cache wrapper. Use when the caller doesn’t need
dimensions cached (e.g. SVG path where viewBox dims are cheap to
re-read from disk). Returns
trueon success. - with_
cache_ dims - Cache-aware wrapper around any
(source, dest) -> boolconversion that also wants to round-trip dimensions through the cache.