Artifact identity and caching
Every compiled artifact — a direct rustc build, a generated Cargo project, a monomorphized generic, a @rust_crate library — is named by an RustCall.ArtifactId and looked up by its RustCall.artifact_key. Identity is computed in exactly one place, src/artifacts/artifact_id.jl; the cache in src/artifacts/cache.jl stores what that identity names, in a Scratch.jl space (#252, #278).
Artifact identity (src/artifacts/artifact_id.jl)
RustCall.ARTIFACT_ENV_ABSENT — Constant
ARTIFACT_ENV_ABSENTMarker recorded for a build variable that is not set, as opposed to one set to the empty string. The two are different to Cargo — an empty RUSTFLAGS suppresses the rustflags a Cargo config would otherwise contribute — so they must never share a key. A variable that is set is recorded as "present:" * value, which can never equal this marker.
RustCall.ARTIFACT_ID_SCHEMA_VERSION — Constant
ARTIFACT_ID_SCHEMA_VERSIONVersion of the ArtifactId encoding itself. Bumping it invalidates every key produced by artifact_key, which is what you want whenever a field is added, removed or re-ordered.
RustCall.ARTIFACT_SHORT_ID_LEN — Constant
ARTIFACT_SHORT_ID_LENThe single truncation rule of the artifact-identity design: artifact_short_id keeps this many leading hex characters (64 bits of the SHA-256 digest).
Truncation is for human-readable names only — library names, temporary Cargo project directories, debug output. Lookup keys (artifact_key) are never truncated.
RustCall.CARGO_TREE_INVOCATIONS — Constant
CARGO_TREE_INVOCATIONSHow many times cargo tree has been spawned this session. A test hook for the performance requirement of #278.
RustCall.CRATE_INPUT_VCS_DIRS — Constant
CRATE_INPUT_VCS_DIRSDirectories not treated as crate inputs: version-control metadata, plus Cargo's build output. target is excluded only at the package root — src/target/mod.rs is ordinary source, not build output — while the VCS directories are excluded at any depth. Everything else under a package directory is an input.
RustCall.CRATE_INPUT_VCS_DIRS_ANY_LEVEL — Constant
CRATE_INPUT_VCS_DIRS_ANY_LEVELVersion-control metadata directories, never a crate input at any depth.
RustCall.RUSTCALL_RELEASE_CRATES — Constant
RUSTCALL_RELEASE_CRATESThe crates this package builds from its own deps/ — the only packages whose [package] version is left out of an artifact identity (_identity_file_bytes). Their version moves on its own — a crates.io release for the published three, the package's for the internal ones — while their behaviour is their sources, which the identity hashes separately; a version-only bump must move nothing (#372, #409). A user's crate, or any other path dependency, keeps its version in the key: a crate can read env!("CARGO_PKG_VERSION") in its source or build script, so a bump of its version alone can change what it compiles to.
A name is not provenance. The exception applies to a manifest only when it is this package's deps/<name>/Cargo.toml, and to a lockfile entry only when the lockfile's own crate takes that dependency by path from this package's deps/ — _rustcall_release_crate_dir, _rustcall_release_names_in. A fork or an unrelated crate that happens to be called rustcall_julia_core keeps its version like any other.
RustCall.ArtifactId — Type
ArtifactIdExhaustive record of everything that can change the binary produced for one compilation request. Construct it with keyword arguments; every field has a neutral default so a caller only names what applies to it.
Fields
kind::String: which pipeline produced the artifact ("rustc","cargo","crate","monomorphization", …). Keeps otherwise-identical inputs from different pipelines apart.source::String: the Rust source after#[julia]expansion and wrapping — the text actually handed to the compiler.type_params::Vector{Pair{String, String}}: generic parameter bindings in declaration order, e.g.["T" => "i32", "U" => "i64"]. Order is part of the identity (#247).target_triple::String: target triple.codegen::Vector{Pair{String, String}}: codegen options (optimization level, debug info, release/debug profile, LTO, …), in a caller-fixed order.cfg::Vector{String}:--cfgsnapshot / feature-gate state.dependencies::Vector{String}: canonical, sorted description of the dependency set (seeartifact_dependency_strings).features::Vector{String}: crate features enabled for the build.build_env::Vector{Pair{String, String}}: build environment that reaches the compiler (RUSTFLAGS,CARGO_*, …), sorted by name.toolchain::String:toolchain_fingerprint— extractor digest, manifest schema,rustcall_julia_core/rustcall_julia_macrossources.compiler::String: identity of the compiler that actually runs, fromRustToolChain(seeartifact_compiler_identity).extra::Vector{Pair{String, String}}: escape hatch for pipeline-specific inputs that do not yet deserve a field of their own.
Two ArtifactIds are == exactly when they encode identically, which is exactly when artifact_key agrees.
RustCall.ArtifactId — Method
ArtifactId(; kind, source, ...) -> ArtifactIdKeyword constructor. toolchain defaults to toolchain_fingerprint and compiler to artifact_compiler_identity; pass them explicitly only in tests that need to vary them.
RustCall._artifact_reset_digest_caches! — Method
_artifact_reset_digest_caches!()Forget the memoized dependency graphs. Nothing else is memoized, so this only ever forces a re-resolution.
RustCall._declared_path_dependencies — Method
_declared_path_dependencies(manifest::AbstractString) -> Vector{String}Fallback manifest traversal: the path = "..." values of every dependency table in manifest, including target-specific tables ([target.<key>.dependencies] and its dev-/build- variants) and { workspace = true } entries resolved against the nearest [workspace.dependencies], searched in this manifest and then upwards.
Returned paths are what the caller should join to the manifest's own directory. An inherited path is relative to the workspace root manifest, not to the member, so it is returned already resolved as an absolute path (joinpath against the member directory then leaves it unchanged).
Used only when cargo tree cannot answer; see local_path_dependency_dirs.
RustCall._hashed_relative_path — Method
_hashed_relative_path(rel::AbstractString) -> StringA crate-relative path in the form that goes into a digest: forward slashes always, case-folded on Windows. Used only for hashed bytes; crate_input_files still reports the real relative names.
RustCall._identity_file_bytes — Method
_identity_file_bytes(path) -> Vector{UInt8}The bytes of path as they enter an artifact identity: Cargo.toml and Cargo.lock with the release-coupled version lines described at _identity_file_digest removed and nothing else touched, every other file as it is. For a lockfile, the release crates whose lines go are read from the manifest beside it, or given as release_names when there is none (a file in the lockfile store). A manifest or lockfile that does not parse is hashed as it is; the build that follows fails on it anyway.
RustCall._release_names_for_dependencies — Method
_release_names_for_dependencies(deps) -> Set{String}The release crates a // cargo-deps: block resolves by path — each path = dependency that is one of this package's release crates (provenance-checked), and the release crates those take by path in turn — which is what a lockfile persisted for that set records without a manifest beside it to read (_identity_file_bytes, _refresh_stored_lockfile!).
RustCall._workspace_root_dir — Method
_workspace_root_dir(dir) -> Union{String, Nothing}The directory of the workspace dir belongs to, or nothing when it belongs to none.
That manifest decides the graph without appearing in it: a member writing dep = { workspace = true } takes the path from [workspace.dependencies] there, and a virtual workspace root is not a package at all, so it can never show up in the package list cargo tree reports.
Cargo resolves the root two ways, and so does this:
- an explicit
[package] workspace = "../elsewhere"in the crate's own manifest, relative to that manifest's directory. It need not be an ancestor — a sibling is legal — so an ancestor-only search misses it entirely; - otherwise, the nearest manifest at or above
dirdeclaring a[workspace]table.
The explicit key is only consulted on the crate's own manifest, which is where Cargo reads it; an ancestor's package.workspace describes that ancestor, not this crate.
RustCall.artifact_build_env — Method
artifact_build_env(names; env = ENV) -> Vector{Pair{String, String}}As above but for an explicit list of variable names, sorted, with absent variables recorded as ARTIFACT_ENV_ABSENT rather than dropped (so "unset" and "set to the empty string" produce different keys). Names that artifact_build_env_captured rejects — anything that looks like a credential — are skipped even when named explicitly.
RustCall.artifact_build_env — Method
artifact_build_env(; env = ENV) -> Vector{Pair{String, String}}Snapshot of every build variable in env that artifact_build_env_captured accepts, sorted by name so the encoding is deterministic. Values carry their presence explicitly (see ARTIFACT_ENV_ABSENT). Suitable for the build_env field of ArtifactId.
RustCall.artifact_codegen_options — Method
artifact_codegen_options(compiler) -> Vector{Pair{String, String}}Codegen options of a RustCompiler in a fixed order, for the codegen field of ArtifactId.
RustCall.artifact_compiler_identity — Method
artifact_compiler_identity() -> StringIdentity of the toolchain that actually compiles: the --version strings of RustToolChain.rustc() and RustToolChain.cargo() — the very commands src/build/compiler.jl and src/build/cargobuild.jl invoke — together with any RUSTC_WRAPPER / RUSTC_WORKSPACE_WRAPPER standing between Cargo and rustc, since a wrapper changes what is produced.
This deliberately replaced _get_rustc_version() (deleted from src/artifacts/cache.jl in #278 Phase B), which shelled out to a bare rustc from PATH and degraded to the string "unknown", so upgrading the real toolchain need not invalidate anything (#252). Here a version that cannot be determined throws a RustError instead, because an unidentifiable compiler cannot produce a trustworthy cache key. toolchain_fingerprint catches that and stays total; the paths about to compile do not.
The result is memoized for the session.
RustCall.artifact_dependency_strings — Method
artifact_dependency_strings(deps) -> Vector{String}Canonical, sorted string form of a dependency set, suitable for the dependencies field of ArtifactId.
Accepts anything with the DependencySpec shape (name, version, features, git, path) as well as plain strings, so it can be used before dependencies.jl types are in scope. Every component is netstring-framed, so distinct specs can never collapse onto the same string.
How each kind of dependency is identified
- Registry dependencies: name, version requirement and feature set — the requested range. The resolved version is not in the string on purpose: the strings name a dependency set, and
cargo_lockfile_iduses exactly them to name theCargo.lockpersisted for that set, which must be the same file on every machine. The resolution reaches a build's key as the content digest of that lockfile (_cargo_block_id'scargo_lock, #256). - Git dependencies: name and the git URL (plus rev/branch/tag when the spec carries them). A floating branch is resolved to a commit in the same lockfile.
- Local path dependencies: a content digest of the crate's inputs (see
artifact_path_dependency_digest), not the path text. Editing a local dependency's sources therefore changes the key, while moving the checkout to a different directory does not — cache hits survive a move, which is the point of hashing content rather than location.
RustCall.artifact_encoding — Method
artifact_encoding(id::ArtifactId) -> Vector{UInt8}Canonical, injective byte encoding of id: a fixed field order, every field netstring-framed, prefixed by ARTIFACT_ID_SCHEMA_VERSION. Distinct records always encode to distinct bytes.
Exposed mainly so tests can assert injectivity directly; production code wants artifact_key.
RustCall.artifact_key — Method
artifact_key(id::ArtifactId) -> StringThe artifact-identity function: the SHA-256 of the canonical encoding of id, as 64 lowercase hex characters.
Never truncated — the lookup key carries the full digest. Use artifact_short_id when you need a name a human will read.
id = RustCall.ArtifactId(kind = "rustc", source = code, target_triple = triple)
key = RustCall.artifact_key(id)RustCall.artifact_key — Method
artifact_key(; kwargs...) -> StringConvenience form: build an ArtifactId from the keyword arguments and hash it.
RustCall.artifact_path_dependency_digest — Method
artifact_path_dependency_digest(path::AbstractString) -> StringDeterministic SHA-256 digest of the inputs of a local path dependency: the contents of the crate directory, plus the contents of every other local crate reachable from it through Cargo's resolved dependency graph.
Only content is hashed — never the absolute location — so an identical crate in a differently named directory yields the same digest and a checkout move does not invalidate the cache. Crates are folded in as a sorted set of per-crate digests for the same reason: the order Cargo happens to report them in, and the directory names they happen to live under, must not reach the key.
The file set of each crate comes from crate_input_files (a directory walk), and the set of local crates from local_path_dependency_dirs (Cargo's resolved graph). Both name the strategy they used, and both strategy names are hashed, so results obtained different ways can never collide.
Only inputs that live inside a package directory are captured. A #[path = "../../elsewhere/mod.rs"] module, an include_str!("../data") or an include_bytes! of a file above the package root is compiled into the binary and will not change this digest. The only complete answer is Cargo's own fingerprint, which this cannot reimplement. This digest is therefore a rebuild trigger and never a proof of freshness: a change means stale, but no change does not by itself license reuse.
A path that does not exist is recorded as such rather than silently ignored, and the function never throws.
RustCall.artifact_short_id — Function
artifact_short_id(id::ArtifactId, n::Int = ARTIFACT_SHORT_ID_LEN) -> String
artifact_short_id(key::AbstractString, n::Int = ARTIFACT_SHORT_ID_LEN) -> StringThe one place in the design where a key is truncated: the first n hex characters of artifact_key, for human-readable names (library names, Rust symbols inside their own library, log lines).
Never use the result as a cache lookup key: correctness must depend on the full digest. Where a short id has to be a location — a path, or a Cargo package whose output lands in a shared directory — it is spelled and owned by the full key in src/artifacts/short_name.jl (short_name_path, claim_short_name!, with_short_name, with_owned_short_name; #504), and scripts/lint_artifact_identity.sh rejects any other use not marked as a label.
RustCall.artifact_type_params — Method
artifact_type_params(param_order, bindings::AbstractDict) -> Vector{Pair{String, String}}As above, but looking each parameter of param_order up in bindings (a Symbol-keyed mapping such as the type_params argument of monomorphize_function). The declared order wins; the dictionary's iteration order is irrelevant.
RustCall.artifact_type_params — Method
artifact_type_params(names, types) -> Vector{Pair{String, String}}Build the type_params field from the declared parameter names and the concrete types bound to them, preserving declaration order.
This is the ordered replacement for the sorted-values key src/macros/generics.jl used before #278 Phase B: sorting the values discards which parameter got which type, so Dict(:T => Int32, :U => Int64) and Dict(:T => Int64, :U => Int32) produced the same monomorphization key (#247).
RustCall.cargo_lockfile_id — Method
cargo_lockfile_id(deps) -> ArtifactIdThe identity of the resolution of a dependency set: what names the Cargo.lock RustCall persists for a // cargo-deps: block (lockfile_path, #256). Deliberately narrower than a build's identity — the dependency strings of artifact_dependency_strings and nothing else, with the toolchain and compiler fields empty — because the point of the persisted lockfile is to be the same file on every machine that declares the same dependencies, whatever rustc each of them runs; the build key then folds the lockfile's content in (_cargo_block_id's cargo_lock), so the resolved versions, not the requested ranges, decide a cache hit.
A path = dependency contributes its content digest, as in every dependency string, so editing a local crate re-resolves rather than replaying a lockfile that pins the old graph.
The root package's naming scheme (CARGO_BLOCK_PACKAGE_PREFIX) is in the key too: the root appears in Cargo.lock by name, so a lockfile written under one scheme does not fit a project named under another. A scheme change therefore names a new store entry rather than replaying a file --locked would reject — which is what a CI cache that carries the scratch space across runs would otherwise do (#313 review).
RustCall.crate_content_digest — Method
crate_content_digest(dir::AbstractString) -> StringSHA-256 over one crate directory: the sorted relative path and a content digest of every file crate_input_files reports, netstring-framed. Location independent; see artifact_path_dependency_digest.
Per-file digests rather than raw bytes, netstring-framed exactly as the contents were, so the encoding stays injective and the intermediate buffer stays small. Every byte is read on every call; file contents are never memoized.
RustCall.crate_input_dirs — Method
crate_input_dirs(dir::AbstractString) -> Vector{String}Every directory crate_input_files walks, dir itself included, as paths relative to dir ("." for the root). Same walk, same exclusions — Cargo's target/ at the package root, VCS metadata at any depth — so the two cannot drift.
Separate from the file list because a directory is what tells a consumer that a file appeared. crate_content_digest hashes the list of files, so creating the first file in a directory that was empty changes the artifact; the parent's own entry list does not move (the directory was already there), and neither does any file. A caller that tracks directories therefore has to know about the empty ones too (#339 review).
RustCall.crate_input_files — Method
crate_input_files(dir::AbstractString) -> (strategy::String, files::Vector{String})Every regular file under the package directory, as relative /-separated paths, sorted, excluding CRATE_INPUT_VCS_DIRS.
The walk is deliberately the only strategy. cargo package --list was tried here first and is weaker: it enumerates the distributable package, not what a local build reads, so a #[path = "../ignored/mod.rs"] module, an include_str! of a gitignored file, or anything removed by an exclude key is compiled but never listed — and a successful listing would suppress a walk that would have caught them. A walk of the package directory is a superset of the package list for everything inside that directory, and costs no process spawn. Cargo.lock is therefore included whenever it exists, like any other file.
The strategy name is returned so callers can fold it into a digest.
RustCall.crate_target_id — Method
crate_target_id(crate_path) -> ArtifactIdThe identity of the Cargo target directory RustCall uses for a crate it runs Cargo on in place: a cdylib crate @rust_crate builds directly, and the --print cfg probe of such a crate (#445). It names the crate (its canonical path) and nothing else. The directory holds no artifact RustCall looks up by content; Cargo's own fingerprint decides what inside it is reused, so the toolchain and compiler are left out, exactly as cargo_lockfile_id leaves them out.
RustCall.external_lib_tree_digest — Method
external_lib_tree_digest(crate_dir, lib_root) -> Union{String, Nothing}The digest of a library root that lives outside its package directory — [lib] path = "../shared/lib.rs", a layout Cargo allows and the crate scan follows (crate_lib_root) — and of everything beside it: every file under the root's directory that crate_input_files reports (the same walk and the same exclusions as the package directory), by sorted relative path and content digest, netstring-framed like crate_content_digest. nothing when lib_root is nothing or lies inside crate_dir, where crate_content_digest already covers it.
crate_content_digest hashes the package directory, so an edit to such an external root — or to a mod foo; file next to it — left the artifact key unchanged and the cache answered with the previous wrapper while the fresh manifest described the new source (#307 review). Every file counts, not only .rs: an include_str! / include_bytes! of a data file beside the root compiles different bytes when that file changes, exactly as inside the package directory.
RustCall.local_path_dependency_dirs — Method
local_path_dependency_dirs(root::AbstractString) -> (strategy::String, dirs::Vector{String})Directories of every local (path) crate reachable from the crate at root, including root itself.
Cargo's resolved graph is the source of truth, so the answer covers path dependencies declared anywhere — [dependencies], [dev-dependencies], [build-dependencies], target-specific [target.'cfg(unix)'.dependencies], and workspace-inherited { workspace = true } entries — at any depth:
cargo tree --offline --target all --edges normal,build,dev --prefix none --format {p}names every package in the resolved graph and prints the directory of the local ones in parentheses. (cargo metadatareports the same graph, but only as JSON, and RustCall.jl has no JSON dependency; the tree output is line-oriented and needs no parser. Registry packages print without a directory and git ones print a URL, so both are filtered out by theisdirtest.)- If that fails — no network and nothing resolvable offline, a bare workspace manifest, cargo unavailable — fall back to reading the manifests directly, traversing every dependency table including target-specific ones and resolving
workspace = trueagainst the nearest[workspace.dependencies].
The strategy name is returned and hashed by callers, so a set found one way can never collide with one found the other.
Short names owned by the full key (src/artifacts/short_name.jl)
Where Windows' path limit makes a short id a location — a crate's Cargo target directory, the PyO3 wrapper's Cargo package, the PyO3 host extension's cache directory, a debug build's files — the name is spelled and owned here: a persistent name is claimed for good by the full key, and a build holds the name's lock from build start through copy-out (#504). A location with files but no owner record is emptied or refused, never adopted; on a file system without locking, emptying it is refused too and it must be removed by hand, since the claim lock cannot keep two claimants apart there (#507 review).
RustCall.SHORT_NAME_CLAIM_LOCK — Constant
SHORT_NAME_CLAIM_LOCKThe lock file, in the parent directory of short-named locations, that a claim holds while it decides whether an unrecorded location is empty and records its owner (claim_short_name!).
RustCall.SHORT_NAME_KEY_FILE — Constant
SHORT_NAME_KEY_FILEThe owner record of a persistent short name that is a directory: a file inside it holding the full key the name was derived from (claim_short_name!). The spelling is the one #495 gave the crate target directory's record, so a target directory created before #504 stays owned by the key it already records.
RustCall.SHORT_NAME_LOCK_FILE — Constant
SHORT_NAME_LOCK_FILEThe lock file inside a persistent short-named directory (with_owned_short_name).
RustCall.claim_short_name! — Method
claim_short_name!(path, key; stem = false, foreign = :refuse, what = "artifact",
wait = 10.0)Record key as the owner of the persistent short name path, or confirm it already is. A name another key owns is refused with a RustError, never shared: its outputs are looked up again later by the name alone, so sharing it could hand one key another key's build. path is a directory (created; the record is SHORT_NAME_KEY_FILE inside it) or, with stem = true, a file stem whose record sits beside it.
The record is created with the exclusive-create claim of _claim_lockfile! (O_CREAT | O_EXCL), so of two claimants exactly one creates it and the other compares the full key. A check-then-rename was not that: both could pass the check (#495 review). The winner writes the key after creating the file, so a loser that finds it empty or partial waits wait seconds for the whole key before deciding.
A location with contents but no record is foreign, never adopted. It was written by a RustCall that kept no record (the PyO3 host cache before #504), or by something else, for a key nobody can name any more; claiming it as it stood would hand its contents to whichever key asked first (#507 review). Only an empty or absent location is claimed as it is. For anything else foreign decides: :clear removes the contents first — for locations whose contents are RustCall's own cache, rebuilt on demand — and :refuse raises. The decision and the record are made under SHORT_NAME_CLAIM_LOCK in the parent directory, so a concurrent claimant can neither see the contents half-removed nor lose a record to another claimant's clearing; a location that already has a record never takes that lock. Where the file system offers no locking at all (_try_lock_lease returns nothing), the lock cannot make clearing safe, so :clear degrades to :refuse for a location with contents; an empty one is still claimed by the exclusive create alone, and the owner record and lock files are never among what :clear removes. try_lock is the locking primitive, a seam for tests.
RustCall.short_name — Method
short_name(key; prefix = "", n = ARTIFACT_SHORT_ID_LEN) -> Stringprefix followed by the first n hex characters of the full artifact key: the on-disk or Cargo-package spelling of a key where the full 64 characters do not fit (#486). Pure — it names; claim_short_name! / with_short_name_lock own. Every short name that is a location is spelled here (#504).
RustCall.short_name_path — Method
short_name_path(root, key; prefix = "", n = ARTIFACT_SHORT_ID_LEN) -> Stringjoinpath(root, short_name(key; prefix, n)), touching nothing. A caller that writes there claims it first (claim_short_name! / with_owned_short_name).
RustCall.with_owned_short_name — Method
with_owned_short_name(f, path, key; stem = false, foreign = :refuse,
what = "artifact", wait = 10.0, poll = 0.05)claim_short_name!(path, key), then f() under the name's lock: full-key ownership for the lifetime of the use — a colliding key is refused, and two uses by the owning key serialize from build start through copy-out.
RustCall.with_short_name — Method
with_short_name(f, root, key; prefix = "", n = ARTIFACT_SHORT_ID_LEN, poll = 0.05)f(name) with name = short_name(key; prefix, n) held under the lock <root>/<name>.lock for the whole call: for a short name that is reused over time rather than owned for good — the PyO3 wrapper's Cargo package, whose <profile>/lib<name>.* in the crate's shared target directory root is rewritten by every wrapper build of that name. Two builds whose full keys share the short id take turns from the build until the output is copied out under the full key, so neither can copy the other's output (#495 review, #504).
RustCall.with_short_name_lock — Method
with_short_name_lock(f, lock_path; poll = 0.05)Run f() holding an exclusive lock on lock_path, waiting while another holder has it — another process, or another task of this one (the lock belongs to the open file description, _try_lock_lease). A build that writes an output under a short name holds it from the build until the output is copied out, so two builds of one name take turns (#495 review, #504). The lock is released when the file is closed, and a holder that dies releases it with the process; the file itself is left in place, since removing it would let a waiter lock a file a newcomer no longer opens. Where the file system has no locking at all, f runs unlocked: that is the one limitation left on such a file system — two builds of one reused name (with_short_name) are then not serialized — while a claim there still never adopts or clears a location (claim_short_name!, #507 review).
Cache (src/artifacts/cache.jl)
RustCall.CACHE_FORMAT_VERSION — Constant
CACHE_FORMAT_VERSIONVersion of the on-disk cache layout, and only of the layout: it names the directory every cached artifact lives under, the scratch space cache-v$(CACHE_FORMAT_VERSION) (CACHE_SCRATCH_NAME, get_cache_dir).
Bump it whenever the meaning of the files under get_cache_dir changes in a way that makes older entries unreachable — as issue #278 Phase B does by routing every key through artifact_key. Namespacing rather than deleting means old trees stay on disk for rollback and for bisecting RustCall versions, and no intermediate state can serve a stale hit from the previous format.
The identity record has its own version, ARTIFACT_ID_SCHEMA_VERSION, which is part of every key; this constant covers the directory layout only.
Version history:
1— implicit, pre-#278: cache files directly under~/.julia/compiled/.../RustCall.2— every key produced byartifact_key(#278 Phase B); under~/.julia/compiled/.../RustCall/v2until #252 moved the cache into thecache-v2scratch space.
RustCall.CACHE_INPUT_DIRS — Constant
CACHE_INPUT_DIRSEntries directly under the cache directory that clear_cache leaves in place: they hold build inputs RustCall persisted, not compiled output. Today the lockfiles store (#256).
RustCall.CACHE_LOCK — Constant
CACHE_LOCKReentrantLock guarding concurrent access to the cache directory. Prevents corruption when multiple tasks/threads save or load cached artifacts simultaneously.
RustCall.CACHE_SCRATCH_NAME — Constant
CACHE_SCRATCH_NAMEThe name of the scratch space every cached artifact lives in, cache-v<N> for CACHE_FORMAT_VERSION N (#252).
Scratch spaces are namespaced by the owning package's UUID, not by its version, so the format version has to be part of the name for two RustCalls that disagree about the on-disk layout to keep separate trees.
RustCall.RUSTC_BUILD_ENV_NAMES — Constant
RUSTC_BUILD_ENV_NAMESEnvironment that changes what a direct rustc invocation produces: rustc itself ignores RUSTFLAGS, but rustup's proxy honours RUSTUP_TOOLCHAIN, and RUSTFLAGS is tracked so a user who sets it sees the same rebuild behaviour as with Cargo-backed blocks. An allowlist by name, never a CARGO_* sweep, so a credential can never reach a key (see artifact_build_env_captured).
RustCall._CACHE_SCRATCH_SIBLING — Constant
_CACHE_SCRATCH_SIBLINGA scratch space belonging to another on-disk cache format: cache-v<n>, the naming CACHE_SCRATCH_NAME produces. Nothing else in scratchspaces/<RustCall UUID> is swept, so a future RustCall that keeps a differently named space of its own is never touched.
RustCall._LEGACY_CACHE_DIRS — Constant
_LEGACY_CACHE_DIRSSubdirectories the pre-#278 (unversioned) layout created directly under _legacy_cache_root(): save_cached_library wrote metadata to metadata/ and build_cargo_project_cached wrote to cargo/. Both names are RustCall's own — Julia creates no directory there — so they are safe to remove.
RustCall._LEGACY_CACHE_FILE — Constant
_LEGACY_CACHE_FILEThe exact naming the pre-#278 layout used for loose files in _legacy_cache_root(), taken from the code that wrote them, not guessed:
save_cached_library→<cache_key><lib_ext>_save_checksum→<cache_key><lib_ext>.sha256- the LLVM IR cache of the LLVM path removed in 0.3.0 (#265) →
<cache_key>.ll
cache_key was always a stable_content_hash digest, i.e. lowercase hex (64 characters, or 32 for the Cargo-side keys). That is what makes the pattern safe to delete by: Julia's precompile images in the same directory are named after a package slug (qLtCw_2ChqG.ji, qLtCw_2ChqG.dylib) which contains uppercase letters and an underscore and therefore can never match, and anything else in the directory is by definition not ours.
A file that does not match this is never removed, whatever it looks like.
RustCall.CacheMetadata — Type
CacheMetadataMetadata stored with cached libraries.
RustCall._cache_dir_override — Method
_cache_dir_override() -> StringRUSTCALL_CACHE_DIR, expanded and absolutised, or "" when unset or empty.
The documented escape hatch for air-gapped and CI setups that need the cache in a specific place (#252): when it is set, no depot is consulted at all.
RustCall._compute_file_checksum — Method
_compute_file_checksum(path::String) -> StringCompute SHA-256 checksum of a file for integrity verification.
RustCall._directory_size — Method
_directory_size(dir; skip = ()) -> Int64The total size of the files under dir, leaving out the top-level entries named in skip.
The cache holds live Cargo target directories (crate_target_directory, #445), where Cargo creates and deletes temporary directories while it builds: an entry that vanishes, or cannot be read, between listing and descending is skipped rather than failing a size query.
RustCall._legacy_cache_dirs — Method
_legacy_cache_dirs() -> Vector{String}Cache directories under _legacy_cache_root() — the pre-#252 root inside Julia's precompile directory. Every v<n> subdirectory counts, not just the older ones: since #252 RustCall writes none of them, so all of them are abandoned, whatever their number. _LEGACY_CACHE_DIRS (the unversioned pre-#278 layout) counts too.
Everything else in that directory is Julia's, or someone else's, and is never returned — see the warning on _legacy_cache_root. The root itself is never created and never removed.
RustCall._legacy_cache_files — Method
_legacy_cache_files() -> Vector{String}Loose files directly under _legacy_cache_root() that the pre-#278 layout wrote, identified by _LEGACY_CACHE_FILE and nothing else. Everything the pattern does not match — Julia's .ji and native images above all — is not RustCall's and is never returned.
RustCall._legacy_cache_root — Method
_legacy_cache_root() -> StringThe pre-#252 cache root, $(DEPOT_PATH[1])/compiled/vX.Y/RustCall.
This is Julia's own package precompile directory for RustCall, where Julia writes <slug>.ji and <slug>.dylib/.so/.dll native images (and .dSYM bundles beside them). RustCall used to keep its compiled Rust libraries here too; since #252 it writes to a scratch space instead (get_cache_dir) and never creates this directory — it is only ever read, and only by the opt-in legacy sweep.
Nothing here may be deleted unless RustCall demonstrably wrote it: only its own version subdirectories and _LEGACY_CACHE_DIRS, plus loose files matching the exact naming the pre-#278 layout used (_LEGACY_CACHE_FILE). Removing a fresh .ji would throw away Julia's precompilation output and can race a concurrent Julia process writing it.
RustCall._publish_cache_file — Method
_publish_cache_file(src, dst) -> (path = dst, published::Bool)Put src into the cache at dst so that no concurrent reader can ever see a missing or half-written file there (#394).
Why this cannot be a cp
cp(src, dst; force = true) unlinks dst and then writes it, and the write of a multi-megabyte .dylib is not instant. Every RustCall cache key is the complete artifact identity, so two processes routinely want the same dst — and the test suite runs sixteen of them against one cache directory. CACHE_LOCK does not help: it is process-local. Measured on one such destination, a reader polling while twelve cps ran saw it absent 1182 times and short 32971 times out of 34615 observations. That is the flake of #394: the reader is another worker that had just looked the key up and then got SystemError: No such file or directory from include_dependency, or could not load library from dlopen.
The two rules
- An existing
dstis never touched. The key is the whole identity of the artifact, so a file already there is this artifact; rewriting it could only replace equivalent bytes with equivalent bytes, while exposing every reader to the window above. It may also bedlopened or mapped right now, which on Windows makes the rewrite fail outright and on any platform makes it pointless. - A new
dstappears whole, and exactly once. The copy goes to a private temporary name in the same directory, anddstis then created as a hard link to it.linkis the one filesystem operation that both publishes atomically and refuses an existing destination: the name appears already pointing at the finished copy, so a reader never sees a partial file, and a second publisher getsEEXISTinstead of replacing the first.
The isfile check above is only a fast path — it cannot be the guarantee, because two processes can both pass it before either publishes. A rename would not close that hole: mv checks for an existing destination in Julia and then calls rename, which replaces whatever appeared in between, so the nominal loser could overwrite the winner. Two direct-rustc builds of one key come from different temporary directories and need not be byte-identical, and the checksums would then describe bytes that are no longer there — a concurrent verifier deletes such an entry as corrupt. Hence the link.
Losing the race is not an error: the publisher that arrives second drops its temporary file and keeps what is already there, which is the same artifact.
published says whether this call is the one that created dst. Only the publisher knows its own bytes are the ones in the cache, which is what save_cached_library needs in order to write a checksum that cannot be wrong.
Why there is no fallback
A filesystem that rejects hard links — exFAT, some network mounts — is reachable, because RUSTCALL_CACHE_DIR overrides the location outright. There the write simply fails, and every caller treats a failed cache write as "not cached" and carries on (build_cargo_project_cached, the inline string literal path in src/macros/ruststr.jl and _cache_generic_library all warn and continue). A rename fallback was tried and removed: it publishes atomically for a reader but cannot refuse an existing destination, so it reinstates exactly the replacement — and the checksum corruption behind it — that the link exists to prevent. No cache is better than a cache that can delete its own entries.
RustCall._publish_temp_path — Method
_publish_temp_path(path) -> StringThe temporary file a publisher writes before renaming it onto path. Unique per process and per call: a fixed path * ".tmp" is shared by two publishers of the same key — two sessions, or two tasks — and one then truncates or renames away the other's half-written file (#394, #460). Every write-then-rename in the cache takes its name from here.
RustCall._reset_cache_dir_memo! — Method
_reset_cache_dir_memo!()Drop the memoized cache directory. Only needed by tests that move DEPOT_PATH or RUSTCALL_CACHE_DIR out from under a running session; normal use is invalidated automatically because both inputs are part of the memo key.
RustCall._save_checksum — Method
_save_checksum(cache_key::String, lib_path::String)Save a SHA-256 checksum file alongside a cached library.
RustCall._stale_cache_format_dirs — Method
_stale_cache_format_dirs() -> Vector{String}Scratch spaces of older cache formats — cache-v<n> with n < CACHE_FORMAT_VERSION, beside the current get_cache_dir().
These are unambiguously RustCall's own (the directory is namespaced by its package UUID) and unreadable by this version, so a plain sweep_stale_cache_formats() removes them. Newer-versioned siblings are deliberately left alone: a future RustCall sharing the depot keeps its cache.
Empty when RUSTCALL_CACHE_DIR is set — an explicitly chosen directory has no sibling namespace to sweep.
RustCall._verify_cached_checksum — Method
_verify_cached_checksum(cache_key::String, lib_path::String)Verify the SHA-256 checksum of a cached library. Throws an error if the checksum doesn't match (possible corruption or tampering).
RustCall.cleanup_old_cache — Function
cleanup_old_cache(max_age_days::Int = 30)Remove cache entries older than maxagedays.
Arguments
max_age_days::Int: Maximum age in days (default: 30)
Returns
Int: Number of removed cache entries
Example
# Remove cache entries older than 7 days
count = cleanup_old_cache(7)
println("Removed $count old cache entries")RustCall.clear_cache — Method
clear_cache(; sweep_legacy::Bool = false)Clear all cached libraries and metadata: the current scratch space, plus the scratch spaces older cache formats left behind.
The pre-#252 tree under _legacy_cache_root() is removed only with sweep_legacy = true. It lives inside Julia's own precompile directory for RustCall (see the warning there), so removing it is opt-in even though every name matched is exact.
The persisted Cargo.lock files (lockfile_dir, #256) are kept: they are inputs of a build — the resolution a // cargo-deps: block is pinned to — not compiled output, and clearing compiled artifacts must not silently re-resolve every dependency set. clear_lockfiles() removes them on request.
On Windows, some files may be locked and cannot be deleted immediately.
RustCall.generate_cache_key — Method
generate_cache_key(code::AbstractString, compiler::RustCompiler; kwargs...) -> StringThe identity of one direct-rustc artifact: artifact_key of an ArtifactId describing the source, the compiler snapshot, the #[cfg] set it was expanded under, the tracked rustc environment, the toolchain fingerprint and — since #252 — the identity of the compiler that actually runs (artifact_compiler_identity, from RustToolChain, never a bare rustc on PATH that could degrade to "unknown").
This is the only key formula of the direct-rustc path: the on-disk cache key and the in-memory library name (_rustc_block_identity) are the same value, so the two can no longer drift apart (#278).
Keyword arguments
cfg_text: the#[cfg]snapshot the wrappers were generated from;nothing(the default) means the current strict snapshot, as inexpand_inline.dependencies,build_env: extra identity components for callers that have them; both default to empty, andbuild_envis merged with the tracked rustc environment.
Throws a RustError when the compiler cannot be identified: a request that is about to compile must not be cached under an unidentifiable toolchain (#252).
RustCall.get_cache_dir — Method
get_cache_dir() -> StringThe directory RustCall keeps compiled libraries, checksums, metadata and Cargo build products in.
Since #252 this is a scratch space — Scratch.get_scratch!(RustCall, CACHE_SCRATCH_NAME), i.e. <depot>/scratchspaces/<RustCall UUID>/cache-vN. Scratch spaces are the standard, Pkg.gc()-tracked, writable-by-construction per-package store; RustCall writes nothing under ~/.julia/compiled/, which is Julia's own precompile directory and is read-only in many deployments.
Resolution order:
RUSTCALL_CACHE_DIR, when set — a documented, absolute escape hatch.- The scratch space in the first writable
DEPOT_PATHentry.Scratch's own default is the first depot only; scanning means a read-onlyDEPOT_PATH[1]in front of a writable depot is not fatal.
Throws a RustError when no depot can be written to, naming the depots tried and the override.
RustCall.get_cache_size — Method
get_cache_size() -> Int64Get the total size of the cache directory in bytes.
RustCall.get_cached_library — Method
get_cached_library(cache_key::String) -> Union{String, Nothing}Check if a cached library exists for the given cache key. Returns the path to the cached library if it exists, nothing otherwise.
RustCall.get_metadata_dir — Method
get_metadata_dir() -> StringGet the directory for cache metadata files.
RustCall.is_cache_valid — Method
is_cache_valid(cache_key::String, code::String, compiler::RustCompiler; cfg_text = nothing) -> BoolCheck if a cached library is still valid for the given code and compiler settings. cfg_text must be the same snapshot the key was generated under (see generate_cache_key), or the recomputed key cannot match by construction.
RustCall.list_cached_libraries — Method
list_cached_libraries() -> Vector{String}List all cache keys for cached libraries.
RustCall.load_cache_metadata — Method
load_cache_metadata(cache_key::String) -> Union{CacheMetadata, Nothing}Load cache metadata from a JSON file.
Arguments
cache_key::String: The cache key identifying the cached library
Returns
Union{CacheMetadata, Nothing}: The loaded metadata, ornothingif not found
Reads back the flat JSON object save_cache_metadata writes; a file it cannot parse is reported with a warning and treated as absent.
Example
meta = load_cache_metadata("abc123...")
if meta !== nothing
println("Cache created at: $(meta.created_at)")
endRustCall.load_cached_library — Method
load_cached_library(cache_key::String) -> StringThe path of the cached library for cache_key, verified and ready to be opened.
It does not dlopen any more (#277 Phase B): opening a compiled artifact, choosing its dlopen flags and registering the resulting handle are one decision that lives in load_artifact! (src/loading/loadpolicy.jl). This function owns the cache half — the lookup and the checksum verification (#198) — under CACHE_LOCK, and hands the caller a path.
RustCall.save_cache_metadata — Method
save_cache_metadata(cache_key::String, metadata::CacheMetadata)Save cache metadata to a JSON file.
Arguments
cache_key::String: The cache key identifying the cached librarymetadata::CacheMetadata: Metadata to save
Example
metadata = CacheMetadata(
"abc123...", # cache_key
stable_content_hash(source), # code_hash
"2_false", # compiler_config
"x86_64-unknown-linux-gnu", # target_triple
now(), # created_at
["add", "multiply"], # functions
)
save_cache_metadata("abc123...", metadata)RustCall.save_cached_library — Method
save_cached_library(cache_key::String, lib_path::String, metadata::CacheMetadata)Save a compiled library to the cache along with its metadata and checksum.
RustCall.stable_content_hash — Method
stable_content_hash(data::String) -> StringCompute a deterministic, session-stable hex digest of data using SHA-256.
This function MUST be used instead of Julia's hash() whenever the result is persisted to disk or must be reproducible across Julia processes. Julia's built-in hash() is intentionally randomized per session for hash-flooding protection and therefore unsuitable for persistent cache keys, library names, or file names.
Returns
- A 64-character lowercase hex string (SHA-256 digest).
Examples
h = stable_content_hash("fn add(a: i32, b: i32) -> i32 { a + b }")
@assert length(h) == 64
@assert h == stable_content_hash("fn add(a: i32, b: i32) -> i32 { a + b }")RustCall.sweep_stale_cache_formats — Method
sweep_stale_cache_formats(; legacy::Bool = false) -> IntBest-effort removal of cache trees this RustCall can no longer read. Returns the number of entries removed and never throws: a locked or unreadable entry is skipped and simply stays on disk.
Older scratch siblings (_stale_cache_format_dirs) are always swept — they are RustCall's own, in a directory namespaced by its package UUID.
The pre-#252 tree under _legacy_cache_root() is swept only when legacy is true, because it lives inside Julia's own precompile directory for RustCall; see the warning there. Even then only RustCall's own version subdirectories, _LEGACY_CACHE_DIRS, and loose files matching _LEGACY_CACHE_FILE are touched, and the root directory itself is left in place.