Hot reload API
Hot reload of a @rust_crate crate's library while it is in use. The Hot Reload guide walks through it with a runnable example.
Hot reload (src/loading/hot_reload.jl)
RustCall.HOT_RELOAD_DEBOUNCE_SECONDS — Constant
HOT_RELOAD_DEBOUNCE_SECONDSHow long to keep coalescing file events after the first one before rebuilding.
100 ms is long enough to swallow an editor's write-rename-touch sequence and a multi-file save, and short enough to be invisible in a dev loop. The issue asks for two saves within 200 ms to produce one reload, which this satisfies with room to spare.
RustCall.HOT_RELOAD_ENABLED — Constant
Global flag to enable/disable all hot reload functionality.
RustCall.HOT_RELOAD_REGISTRY — Constant
Registry of hot-reloadable crates. Maps library name to HotReloadState.
RustCall.MAX_DEBOUNCE_WINDOWS — Constant
MAX_DEBOUNCE_WINDOWSHow many times a burst of file events may extend the debounce window before the rebuild happens anyway.
The cap is what keeps "coalesce a burst" from becoming "never rebuild": some platforms hand back an already-queued directory event immediately, so an uncapped extension would spin. Ten windows is a tenth of a second times ten — long enough for any editor's save sequence, short enough that a pathological event source costs one second, not the session.
RustCall.MAX_RELOAD_CHASES — Constant
MAX_RELOAD_CHASESHow many times a reload may immediately follow itself because the sources changed while it was building.
Three is enough for "save, notice a typo, save again" and small enough that a file being written continuously costs three builds, not a livelock.
RustCall.RELOAD_LOCKS — Constant
Per-library locks to serialize reload operations for the same library. Prevents concurrent hot reloads of the same crate from corrupting state.
RustCall.SOURCE_SCANS — Constant
SOURCE_SCANSHow many times a watcher has scanned a crate's sources (check_for_changes), process-wide.
Diagnostic, and the way the "no polling loop when idle" criterion of #255 is actually checked: an idle watcher must leave this number alone, however long it waits. Before the timeout check in _await_source_change, watch_folder returning "nothing happened" was treated as an event and every interval cost a stat of every source file.
RustCall.HotReloadState — Type
HotReloadStateState for a hot-reloadable Rust crate.
Fields
record::CrateBuildRecord: every input of the build a reload reproduces — crate, registry name, profile, features, kind, build environment, Cargo configuration, toolchain. The only source of a rebuild's inputs (#474).state.crate_path,state.lib_nameandstate.build_optionsread it.lib_path::String: Path to the compiled librarysource_files::Vector{String}: Tracked .rs source fileslast_modified::Dict{String, Float64}: Last modification timeswatch_task::Union{Task, Nothing}: File watching taskenabled::Bool: Whether hot reload is enabledrebuild_callback::Union{Function, Nothing}: Callback after rebuild
RustCall._await_source_change — Method
_await_source_change(state, timeout) -> BoolBlock until a .rs file under the crate changes, or timeout elapses.
This is the difference between an idle watcher costing nothing and one waking up every second to stat every source file (#255). FileWatching.watch_folder blocks in the kernel — inotify on Linux, kqueue on the BSDs, ReadDirectoryChanges on Windows — so an idle watch task consumes no CPU at all.
The timeout is what lets the task notice state.enabled going false, and is also the polling interval of the fallback: on a filesystem where the kernel notification does not work (NFS, some container mounts), poll = true on start_watch_task restores the old stat-based loop.
Returns whether something actually changed — a rename into place and a temporary file both produce events, and only the mtime check decides.
Every directory, not just src/
watch_folder is not recursive — inotify watches one directory — while find_rust_source_files tracks the whole tree, src/foo/mod.rs included. When a timeout still triggered a scan the difference was invisible: the poll caught what the watch missed. Now that a timeout does nothing, watching only src/ would mean an edit to a nested module never reloads on Linux at all. So every directory that contains a tracked source is watched, and the set is recomputed each time — a reload can add files, and new files can be in new directories.
RustCall._drain_source_changes — Method
_drain_source_changes(state, window)Keep absorbing file events for window seconds, so one burst of saves becomes one rebuild.
An event seen inside the window restarts it, which is what makes a "save every file in the project" refactor rebuild once at the end rather than once per file — but only up to MAX_DEBOUNCE_WINDOWS extensions. Without that cap a directory that produces events continuously (a build writing into it, a watch API that hands back an already-queued event immediately) would keep the debounce open forever and the reload would never happen.
Whatever arrives is folded into the mtime table, so the wait that follows starts from a clean slate.
RustCall._get_library_filename — Method
_get_library_filename(crate_name::String) -> StringGet the platform-specific library filename for a crate.
RustCall._get_reload_lock — Method
_get_reload_lock(lib_name::String) -> ReentrantLockGet or create a per-library lock for serializing reload operations.
RustCall._reload_failure_fingerprint — Method
_reload_failure_fingerprint(e) -> StringWhat decides whether a failed reload is "the same failure as last time": the rendered error, minus Cargo's transient status lines. A CargoBuildError carries Cargo's stderr, and a line such as Blocking waiting for file lock on package cache or Compiling dep v1.0 depends on what else was building at that moment, not on the failure — keeping it would report one compile error again on every attempt (#461).
RustCall._reload_library_locked — Method
_reload_library_locked(state::HotReloadState) -> BoolInternal implementation of reload_library, called while holding the per-library lock.
Rebuild first, swap last (#255)
Everything that can fail — the environment check against the record, the rescan, cargo build, the copy, the dlopen — completes before the previous library is touched, and a failure in any of them fails the reload the same way: false, last_failure set, the callback told, and the old library still loaded, with its function-pointer cache, its symbol mappings, its monomorphizations and CURRENT_LIB intact, instead of emptying the registry and leaving the user with no library at all (#473). The swap itself is one load_artifact! under REGISTRY_LOCK that replaces the registry entry and retires the previous image — it is not closed. A call already running inside it finishes there, and objects it allocated keep its destructor and its still-true liveness flag, so they are freed by their own allocator whenever they are collected (RETIRED_HANDLES, #277). Retired images are closed only by an explicit unload_library(name; close = true).
Rescan before the build
The scan describes the sources; the build compiles them. Scanning after the build would describe sources that may have changed in between and hand the freshly built library another build's symbol table. So the sources are fingerprinted by content — the scan's own inputs, the Rust sources and the manifest — scanned, built, and fingerprinted again: if the digest moved, the scan is discarded rather than trusted, and the library is registered with no symbol mappings (a #[julia] function is then reachable only by its exported symbol until the next reload). A (mtime, size) stamp would miss a same-size edit with a restored mtime, which is exactly what an editor or a git checkout produces.
RustCall._scan_crate_signatures — Method
_scan_crate_signatures(record::CrateBuildRecord) -> Vector
_scan_crate_signatures(crate_path; build_options = crate_build_options()) -> VectorThe #[julia] function signatures of the crate record names, scanned under that build's own configuration: its profile and features, read from the record and nothing else (#474).
_crate_build_cfg_text probes the crate in place (cargo rustc --lib -- --print cfg), so its features and its build script's cargo:rustc-cfg output decide the #[cfg] predicates. Two mutually exclusive #[cfg(feature = ...)] variants of one #[julia] fn then collapse to the one that exists, and its return type is registered instead of being suppressed as ambiguous (#279).
When the probe comes back empty — cargo unavailable, a crate Cargo will not probe — the scan falls back to the lenient one, which decides only target predicates. That is the fail-safe: an ambiguous function keeps its symbol mapping and loses only its return-type hint, so the call falls through to inference or an explicit ::T rather than to the wrong ABI.
A failed scan throws. It is the first step of a reload, and a reload that cannot describe what it is about to publish fails like one whose build fails: the previous library stays current (#473). It used to return nothing, and the rebuilt library was then published with no symbol mappings and reported as a success.
The path method is a thin constructor of a record with no environment, for callers that only want the scan.
RustCall._source_fingerprint — Method
_source_fingerprint(crate_path) -> StringA content digest of exactly what the scan reads: the crate's Rust sources and its Cargo.toml.
The question this answers is narrow — "does the manifest I just produced still describe the files that were compiled?" — so the input set is the scan's input set, hashed by content (_file_content_digest, the same primitive src/artifacts/artifact_id.jl uses). Content, not (mtime, size): the edit most likely in that window is one character for another, same length, with the mtime restored by an editor, a formatter or a version-control checkout.
It is deliberately not crate_content_digest, which is the artifact identity and therefore hashes everything a build reads — including Cargo.lock. Cargo writes Cargo.lock during the very build this check straddles, so a crate that does not have one yet (it is ignored by version control here, and in most repositories) changed its identity digest between the scan and the build every single time. The check then declared the manifest untrustworthy and registered the rebuilt library with no symbol mappings — precisely the failure this function exists to prevent: @rust f(...) hunting for f while the library exports rustcall_f.
Returns "" when the digest cannot be taken, which the caller treats as "no evidence" and therefore as "unchanged": failing to hash a crate that just built successfully should not throw the rebuilt library away.
RustCall._wait_for_file_event — Method
_wait_for_file_event(dirs, timeout) -> Union{Bool, Nothing}Wait for a filesystem event in any of dirs. true when one fired, false when the wait expired everywhere, nothing when the directories cannot be watched at all (the caller then treats it as a poll and scans).
One task per directory, first one wins. The losers are released with unwatch_folder rather than left holding a kernel watch until their own timeout: a watch task that reloads every few seconds would otherwise accumulate them.
RustCall._watched_directories — Method
_watched_directories(state) -> Vector{String}Every directory below src/, including empty nested directories, plus the parents of tracked sources elsewhere. Recomputed per wait: directory creation may precede the first source write and must establish that directory's watch.
RustCall.check_for_changes — Method
check_for_changes(state::HotReloadState) -> BoolCheck if any source files have been modified since last check. Updates the last_modified times if changes are detected.
RustCall.disable_all_hot_reload — Method
disable_all_hot_reload()Disable hot reload for all registered crates.
RustCall.disable_hot_reload — Method
disable_hot_reload(lib_name::String)Disable hot reload for a Rust crate.
Arguments
lib_name::String: Name of the library to disable hot reload for
RustCall.enable_hot_reload — Method
enable_hot_reload(lib_name::String, crate_path::String; kwargs...) -> HotReloadStateEnable hot reload for a Rust crate.
Arguments
lib_name::String: Name of the loaded librarycrate_path::String: Path to the Rust crate root
Keyword Arguments
interval::Float64: seconds; the timeout of each wait for a file event, or the polling period withpoll = true(default: 1.0)poll::Bool: check modification times everyintervalinstead of waiting on filesystem events, for filesystems that do not deliver them (default: false)callback::Union{Function, Nothing}: called after each rebuild attempt ascallback(lib_name, success, error)build_options: the build a reload makes (crate_build_options; default: release, default features)
Returns
HotReloadState: The hot reload state for the crate
A reload rebuilds the crate (a cdylib) with build_options and swaps it in under lib_name. The build environment, Cargo configuration and toolchain are recorded when hot reload is enabled, and a reload under different ones is refused. For an @rust_crate module, prefer enable_hot_reload_for_crate(module), which takes all of it from the module.
Example
crate_path = "path/to/my_crate" # a #[julia] crate with crate-type = ["cdylib"]
MyCrate = @rust_crate crate_path
lib_name = MyCrate._LIB_NAME # the name @rust_crate loaded the library as
state = RustCall.enable_hot_reload(lib_name, crate_path; interval = 0.5)
# Edit the sources and the watcher rebuilds; or rebuild now:
RustCall.trigger_reload(lib_name) # true once the new library is loaded
RustCall.disable_hot_reload(lib_name)RustCall.enable_hot_reload_for_crate — Method
enable_hot_reload_for_crate(mod::Module, crate_path = nothing; kwargs...) -> HotReloadState
enable_hot_reload_for_crate(bindings::CrateBindings, crate_path = nothing; kwargs...) -> HotReloadState
enable_hot_reload_for_crate(crate_path::String; release = true, features = String[],
default_features = true, lib_name = nothing, kwargs...) -> HotReloadStateEnable hot reload for a crate loaded via @rust_crate.
A reload publishes a new image under the module's registry name, so it has to rebuild exactly the build the module was generated for. Every generated module records that build as one immutable CrateBuildRecord, _BUILD_RECORD: the crate directory, the registry name, the profile, the features, the kind of build, the build environment (the allowlisted variables such as RUSTFLAGS), the effective Cargo configuration and the toolchain. The module form — the value @rust_crate returns, or the generated module itself, including one written by write_bindings_to_file — reads that record once and rebuilds from it alone (#474).
Arguments never supplement the record; they are compared with it. crate_path may be omitted, and when given must name the recorded crate (compared by realpath); lib_name, release, features and default_features may be given and must equal the recorded ones. A mismatch is an ArgumentError, and so is a current build environment, Cargo configuration or toolchain that differs from the recorded one — at enable time, and again at every reload, where the rebuild fails and the previous library stays loaded. A module without a record (a file written by an older RustCall) is refused: regenerate it.
The path form is a thin constructor of the same record: it takes the build as keywords — release, features, default_features, the @rust_crate options of the same names — records the current environment, and computes the registry name @rust_crate gives that build of the crate as it is now, so call it before editing the sources; lib_name names the entry instead of computing it. It does not guess: a crate loaded with other options is reached only when they are passed.
Only a crate that is its own cdylib can be reloaded, and both forms check it when hot reload is enabled: a module built through a generated wrapper crate, or a crate whose [lib] has no crate-type = ["cdylib"], is refused with an ArgumentError rather than replaced by a build of the bare crate. Registering under the module name, as before, reached nothing (#461).
Keyword Arguments
release,features,default_features,lib_name: the build (path form); compared with the record (module form)interval,poll,callback: as forenable_hot_reload
Example
crate_path = "path/to/my_crate" # a #[julia] crate with crate-type = ["cdylib"]
MyCrate = @rust_crate crate_path features=["simd"]
state = RustCall.enable_hot_reload_for_crate(MyCrate; # crate_path and features=["simd"] kept
callback = (lib_name, success, error) -> @info "reloaded" lib_name success)
# Edit the sources and the watcher rebuilds; or rebuild now:
RustCall.trigger_reload(state.lib_name) # true once the new library is loaded
RustCall.disable_hot_reload(state.lib_name)RustCall.find_rust_source_files — Method
find_rust_source_files(crate_path::String) -> Vector{String}Find all .rs files in a crate's src directory.
RustCall.get_file_mtime — Method
get_file_mtime(path::String) -> Float64Get the modification time of a file as a Float64 timestamp. Returns 0.0 if the file doesn't exist.
RustCall.is_hot_reload_enabled — Method
is_hot_reload_enabled(lib_name::String) -> BoolCheck if hot reload is enabled for a library.
RustCall.list_hot_reload_crates — Method
list_hot_reload_crates() -> Vector{String}List all crates with hot reload enabled.
RustCall.module_build_record — Method
module_build_record(mod::Module) -> CrateBuildRecordThe _BUILD_RECORD a generated @rust_crate module holds: every input of the build its library is. An ArgumentError for a module that is not generated by @rust_crate, or that predates the record (a file written by an older RustCall, which records no build).
RustCall.rebuild_crate — Method
rebuild_crate(record::CrateBuildRecord) -> String
rebuild_crate(crate_path::String; build_options = crate_build_options()) -> StringRebuild a Rust crate and return the path to the compiled library.
The build is the one @rust_crate runs for a crate that is its own cdylib (build_crate_directly): build_cargo_project with RustToolChain's cargo, --offline under RUSTCALL_OFFLINE, and the output under RustCall's crate_target_directory — never the crate's own target/, and never wherever an ambient CARGO_TARGET_DIR points — found again under the library's [lib] name. A bare cargo build --manifest-path into target/ ignored all four (#461).
The crate, the profile and the feature selection are the record's and nothing else's (#474): a reload rebuilds the build the replaced library was, never a default one, and only a :direct build — the crate as its own cdylib — can be rebuilt here. The path method is a thin constructor of such a record.
RustCall.reload_library — Method
reload_library(state::HotReloadState) -> BoolRebuild and reload a Rust library.
Returns true if successful, false otherwise.
RustCall.set_hot_reload_global — Method
set_hot_reload_global(enabled::Bool)Enable or disable hot reload functionality globally.
When disabled, all watch tasks will stop.
RustCall.source_scan_count — Method
source_scan_count() -> IntThe value of SOURCE_SCANS.
RustCall.start_watch_task — Method
start_watch_task(state::HotReloadState; interval::Float64=1.0)Start a background task that watches for file changes.
RustCall.stop_watch_task — Method
stop_watch_task(state::HotReloadState)Stop the file watching task for a crate.
RustCall.trigger_reload — Method
trigger_reload(lib_name::String) -> BoolManually trigger a reload for a library.
Returns true if successful, false otherwise.