Skip to main content

nodejs/
cache.rs

1//! rkyv-backed bytecode cache for compiled JS scripts (mirrors the fleet's
2//! pythonrs/zshrs/rubylang design). Every ordinary `node foo.js` run is
3//! transparently cached: the source is hashed, the shard consulted, and on a hit
4//! the compiled `fusevm::Chunk`s run directly — lex/parse/lower are skipped
5//! entirely. On a miss the program is compiled, stored, then run. `node --build`
6//! warms the same shard ahead of time.
7//!
8//! Layout: a single shard at `~/.node-js/scripts.rkyv`. The *outer* container is
9//! a zero-copy rkyv archive (`Shard`), validated on load; each *inner* entry blob
10//! is a bincode-encoded `CProg` (the compiled `fusevm::Chunk`s + func/try
11//! tables), because `fusevm::Chunk` is serde-owned, not `rkyv::Archive`. The key
12//! is a 64-bit hash of the source plus a schema version, the release version and
13//! an identity for the running BINARY, so a source, format, release or codegen
14//! change misses cleanly instead of loading stale bytecode.
15
16use crate::compiler::Program;
17use crate::host::{FuncDef, TryDef};
18use fusevm::Chunk;
19use rkyv::{Archive, Deserialize as RkyvDe, Serialize as RkyvSer};
20use serde::{Deserialize, Serialize};
21use std::hash::{Hash, Hasher};
22use std::path::PathBuf;
23
24/// Bump on any incompatible change to `CProg` / the lowering / the shard layout.
25/// v1: initial JS bytecode cache — a Chunk/func/try layout change here must miss
26///     cleanly so an older cached `.js` never loads incompatible bytecode.
27/// v2: BigInt/RegExp/tagged-template/for-await lowering — new builtin ops
28///     (MKBIGINT/MKREGEX/NUM_STEP/TAG_TMPL/…) and the type-preserving `++`/`--`
29///     codegen; old cached bytecode would run the stale POS-based increment.
30/// v6: `FuncDef.is_method` (a method owns no `prototype`) and the class-body
31///     emission order (methods before static fields). A v5 blob deserializes
32///     with `is_method: false` and replays the old source order, so every class
33///     and every object method would report the wrong own-property set.
34/// v7: NamedEvaluation (10.2.9 SetFunctionName) at every site the grammar calls
35///     for it — assignment to an identifier, object property definitions and
36///     concise methods/accessors, class fields, and destructuring/parameter
37///     defaults — plus the new `NAMED_EVAL` builtin and `DEF_FIELD`'s fourth
38///     argument. A v6 blob calls `DEF_FIELD` with three arguments and emits no
39///     naming, so every affected function would keep the empty `.name` and the
40///     field's flag would be read off the wrong stack slot. v7 also carries the
41///     class-body environment (15.7.14 step 17), whose `PUSH_SCOPE`/`DECLARE`
42///     pair a v6 blob does not emit, so a static initializer reading the class
43///     by name would still throw `ReferenceError`.
44/// v8: `**` lowers to `CallBuiltin(ops::POW, 2)` instead of the native
45///     `Op::Pow`. fusevm's native op is IEEE-754 `pow`, which answers 1 for
46///     `(-1) ** Infinity` and `1 ** NaN` where the spec says NaN; a v7 blob
47///     still carries `Op::Pow` and would keep replaying the IEEE answer from
48///     cache long after the source fix. (The `Math.*` additions in the same
49///     change need no bump: a `Math.f(..)` call emits the name as a constant
50///     and dispatches on the string at run time, so `--dump-bytecode` for a
51///     known and an unknown method name is byte-identical.)
52/// v9: locals that no closure can reach are addressed as fusevm frame slots
53///     (`Op::GetSlot`/`SetSlot`) instead of `CallBuiltin(GETLOCAL)` by name —
54///     see `crate::slots`. A v8 blob is still CORRECT, since it carries the
55///     name-lookup form and nothing else changed about it; it is simply the
56///     slow bytecode, and a cache that kept replaying it would hide the whole
57///     change from every script already run once. The bump is what makes the
58///     speedup reach existing scripts.
59/// v10: the entry carries the compiler's SIDE TABLES (call-site texts, yield-site
60///     iterator depths). They live in thread-local registries that only
61///     `finish_chunk` fills, so every cache hit ran without them: a generator's
62///     parked `for…of`/`yield*` iterators were not closed when a `.return()` or
63///     `.throw()` was injected, and their `finally` never ran — the same script
64///     printed one thing on its first run and another on its second. A v9 blob
65///     has no tables to restore, so it must not be replayed.
66/// v11: assignment to a PROPERTY evaluates its target reference before the
67///     right-hand side (13.15.2). `o[k()] = v()` now emits the object, then the
68///     key, then the value, and calls `SETATTR`/`SETITEM` on the result directly
69///     instead of the old `value`-first sequence with its `Dup`/`Rot`/`Pop`. A
70///     v10 blob still carries that sequence, so every cached script would keep
71///     running its side effects in the wrong order — the exact bug the change
72///     fixes, replayed from disk.
73const SCHEMA: u64 = 11;
74
75/// The outer, rkyv-archived shard: a flat list of (key, bincode-blob) entries.
76#[derive(Archive, RkyvSer, RkyvDe, Default)]
77#[archive(check_bytes)]
78struct Shard {
79    entries: Vec<Entry>,
80}
81
82#[derive(Archive, RkyvSer, RkyvDe)]
83#[archive(check_bytes)]
84struct Entry {
85    key: u64,
86    /// A second, independent hash of the source. A cache hit requires BOTH `key`
87    /// and `verify` to match, so an `FxHash` collision on `key` can never return
88    /// a different program's bytecode (which would silently produce wrong
89    /// results — far worse than a cache miss).
90    verify: u64,
91    /// The [`build_id`] that wrote this entry. Every key already mixes the build
92    /// id in, so an entry from a DIFFERENT build can never be hit again — it is
93    /// dead weight from the moment the binary is rebuilt. Recording it lets
94    /// `store` drop those entries instead of accumulating one full copy of the
95    /// shard per rebuild, which matters because `load_shard` reads and
96    /// deserializes the WHOLE file on every lookup.
97    build: u64,
98    blob: Vec<u8>,
99}
100
101/// The inner, serde/bincode form of a compiled program.
102#[derive(Serialize, Deserialize)]
103struct CProg {
104    main: Chunk,
105    functions: Vec<(String, FuncDef)>,
106    tries: Vec<TryDef>,
107    /// The compiler's side tables — call-site texts and yield-site iterator
108    /// depths — which a cache hit would otherwise never build. See
109    /// [`crate::host::SiteTables`] for what silently degrades without them.
110    #[serde(default)]
111    sites: crate::host::SiteTables,
112    /// Whether the program's top level is strict. `#[serde(default)]` so a
113    /// shard written before this field existed still decodes — as sloppy,
114    /// which is what those entries were compiled as anyway.
115    #[serde(default)]
116    strict: bool,
117}
118
119/// The release this binary was built as, hashed into every cache key so a shard
120/// written by one release can never be read by another.
121const BUILD_VERSION: &str = env!("CARGO_PKG_VERSION");
122
123/// An identity for the BINARY doing the lookup — its own mtime, read once.
124///
125/// `SCHEMA` and `BUILD_VERSION` are both bumped BY HAND, and a codegen change
126/// that forgets either ships a binary that silently replays the previous
127/// build's bytecode for every script already run once. That failure is
128/// invisible: the right answer for the old program, no error, and the symptom
129/// is "my change did not take". Measured on this crate: with the key depending
130/// on `(SCHEMA, src)` alone, lowering `**` to a deliberately wrong opcode and
131/// rebuilding still printed the OLD result for a previously-cached script,
132/// while a byte-different script printed the new (wrong) one — the binary had
133/// changed and the cache had not noticed.
134///
135/// The mtime changes on every rebuild without anyone having to remember, and is
136/// stable for an installed binary, so it costs one `stat` per process and
137/// nothing else. `0` when the path or metadata is unreadable, which degrades to
138/// the previous behavior rather than failing the run.
139fn build_id() -> u64 {
140    use std::sync::OnceLock;
141    static ID: OnceLock<u64> = OnceLock::new();
142    *ID.get_or_init(|| {
143        std::env::current_exe()
144            .and_then(|p| p.metadata())
145            .and_then(|m| m.modified())
146            .ok()
147            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
148            .map(|d| d.as_nanos() as u64)
149            .unwrap_or(0)
150    })
151}
152
153/// A stable content key for a source string (fast `FxHash`, used for lookup).
154pub fn key_for(src: &str) -> u64 {
155    let mut h = rustc_hash::FxHasher::default();
156    SCHEMA.hash(&mut h);
157    BUILD_VERSION.hash(&mut h);
158    build_id().hash(&mut h);
159    src.hash(&mut h);
160    h.finish()
161}
162
163/// An independent verification hash (std `DefaultHasher`/SipHash), so a hit
164/// requires both hashes to agree — collision-proof for correctness.
165fn verify_for(src: &str) -> u64 {
166    use std::collections::hash_map::DefaultHasher;
167    let mut h = DefaultHasher::new();
168    SCHEMA.hash(&mut h);
169    BUILD_VERSION.hash(&mut h);
170    build_id().hash(&mut h);
171    src.len().hash(&mut h);
172    src.hash(&mut h);
173    h.finish()
174}
175
176fn shard_path() -> Option<PathBuf> {
177    let dir = dirs::home_dir()?.join(".node-js");
178    let _ = std::fs::create_dir_all(&dir);
179    Some(dir.join("scripts.rkyv"))
180}
181
182/// The shard file's identity as `(mtime, len)` — what "unchanged since we read
183/// it" is decided on. `None` when there is no file (or it cannot be stat'd),
184/// which compares equal to a later `None` and so still means "unchanged".
185type Stamp = Option<(std::time::SystemTime, u64)>;
186
187fn shard_stamp() -> Stamp {
188    let path = shard_path()?;
189    let md = std::fs::metadata(&path).ok()?;
190    Some((md.modified().ok()?, md.len()))
191}
192
193fn load_shard() -> Shard {
194    let Some(path) = shard_path() else {
195        return Shard::default();
196    };
197    let Ok(bytes) = std::fs::read(&path) else {
198        return Shard::default();
199    };
200    rkyv::from_bytes::<Shard>(&bytes).unwrap_or_default()
201}
202
203fn write_shard(shard: &Shard) -> Result<(), String> {
204    let path = shard_path().ok_or("no home dir for cache")?;
205    let bytes = rkyv::to_bytes::<_, 4096>(shard).map_err(|e| format!("cache serialize: {e}"))?;
206    // Atomic replace (write temp + rename) so a concurrent reader — up to 16
207    // instances run against the shared shard — never sees a torn file. A losing
208    // concurrent writer just drops its entry (recompiled next run); it can never
209    // corrupt the shard. The temp name is unique per WRITE (pid + a monotonic
210    // counter), not just per process, so concurrent writers within one process
211    // (e.g. parallel test threads) never clobber each other's temp file.
212    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
213    let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
214    let tmp = path.with_extension(format!("rkyv.tmp.{}.{n}", std::process::id()));
215    std::fs::write(&tmp, &bytes).map_err(|e| format!("cache write: {e}"))?;
216    std::fs::rename(&tmp, &path).map_err(|e| {
217        let _ = std::fs::remove_file(&tmp);
218        format!("cache rename: {e}")
219    })
220}
221
222/// The shard, resident in memory for the life of the process.
223///
224/// It used to be read and fully deserialized from disk on every `load`, and
225/// read-modify-WRITTEN on every `store`. That was affordable only because
226/// exactly one lookup happened per run — the top-level script. Caching each
227/// `require`d module makes it 118 lookups for an express tree, and measured on
228/// a 3 MB shard a single `load` costs 67-347 ms, so the disk-per-call design
229/// would have turned a 138 ms saving into a 16 SECOND regression. Reading once
230/// and writing once is what makes per-module caching possible at all.
231#[derive(Default)]
232struct ShardMem {
233    /// The shard file exactly as read, kept resident so an entry's blob can be
234    /// BORROWED out of it rather than copied.
235    ///
236    /// This used to be a map of owned blobs built by deserializing the whole
237    /// archive, which meant a run paid to materialize EVERY cached program in
238    /// order to look up the one it was about to execute — and `load` then cloned
239    /// the blob a second time. rkyv is a zero-copy format, so the archive is
240    /// instead indexed in place and only the matching entry is decoded. Measured
241    /// on a 227 KB shard of 300 scripts (debug build), a cache-hit run went from
242    /// 15.3 ms to 11.4 ms against an 8.7 ms floor for `--version`, which touches
243    /// no cache at all; the cost it removes grows with the shard, so a 3 MB one
244    /// pays it back roughly thirteen times over.
245    backing: Vec<u8>,
246    /// `key -> (verify, blob range within `backing`)` for entries read from disk.
247    disk: rustc_hash::FxHashMap<u64, (u64, std::ops::Range<usize>)>,
248    /// Entries stored by THIS process, which are not in `backing`.
249    added: rustc_hash::FxHashMap<u64, (u64, Vec<u8>)>,
250    /// Whether this process added anything, so an all-hits run writes nothing.
251    dirty: bool,
252    /// The file's `(mtime, len)` when this process read it. [`flush`] re-reads
253    /// the shard only when this no longer matches — i.e. when a peer actually
254    /// wrote while we were running.
255    stamp: Stamp,
256}
257
258impl ShardMem {
259    /// The blob for `key`, borrowed from wherever it lives.
260    fn get(&self, key: u64) -> Option<(u64, &[u8])> {
261        if let Some((v, b)) = self.added.get(&key) {
262            return Some((*v, b.as_slice()));
263        }
264        let (v, r) = self.disk.get(&key)?;
265        Some((*v, &self.backing[r.clone()]))
266    }
267
268    /// Every live entry as `(key, verify, blob)`, this process's own additions
269    /// shadowing the on-disk copy of the same key.
270    fn iter(&self) -> impl Iterator<Item = (u64, u64, &[u8])> {
271        self.added
272            .iter()
273            .map(|(k, (v, b))| (*k, *v, b.as_slice()))
274            .chain(
275                self.disk
276                    .iter()
277                    .filter(|(k, _)| !self.added.contains_key(k))
278                    .map(|(k, (v, r))| (*k, *v, &self.backing[r.clone()])),
279            )
280    }
281}
282
283/// Read the shard and index it WITHOUT deserializing it: the archive is
284/// validated once, then each entry contributes only its key and the byte range
285/// its blob occupies inside `backing`.
286///
287/// Entries from another build can never be hit (the build id is part of every
288/// key), so they are skipped here and dropped on the next write.
289fn load_shard_indexed() -> ShardMem {
290    let mut mem = ShardMem {
291        stamp: shard_stamp(),
292        ..ShardMem::default()
293    };
294    let Some(path) = shard_path() else {
295        return mem;
296    };
297    let Ok(bytes) = std::fs::read(&path) else {
298        return mem;
299    };
300    let build = build_id();
301    let Ok(shard) = rkyv::check_archived_root::<Shard>(&bytes) else {
302        // A corrupt or older-layout shard is simply not readable; every lookup
303        // misses and the next write replaces it.
304        return mem;
305    };
306    let base = bytes.as_ptr() as usize;
307    for e in shard.entries.iter() {
308        if u64::from(e.build) != build {
309            continue;
310        }
311        // The archived blob points INTO `bytes`, so its offset is the difference
312        // between the two addresses — no copy, and the range stays valid for as
313        // long as `backing` holds those bytes.
314        let blob: &[u8] = &e.blob;
315        let off = blob.as_ptr() as usize - base;
316        mem.disk
317            .insert(e.key.into(), (e.verify.into(), off..off + blob.len()));
318    }
319    mem.backing = bytes;
320    mem
321}
322
323thread_local! {
324    static SHARD: std::cell::RefCell<Option<ShardMem>> = const { std::cell::RefCell::new(None) };
325}
326
327/// Run `f` against the resident shard, loading it from disk on first use.
328fn with_shard<T>(f: impl FnOnce(&mut ShardMem) -> T) -> T {
329    SHARD.with(|c| {
330        let mut slot = c.borrow_mut();
331        // Stamped BEFORE the read (inside `load_shard_indexed`): a peer writing
332        // between the two makes the stamp look older than the bytes we hold,
333        // which only costs `flush` a re-read it did not need. The other
334        // direction — a stamp newer than the content — would silently drop a
335        // peer's entries, and cannot happen this way round.
336        let mem = slot.get_or_insert_with(load_shard_indexed);
337        f(mem)
338    })
339}
340
341/// Look up a compiled program for `src`, if present and current.
342pub fn load(src: &str) -> Option<Program> {
343    let key = key_for(src);
344    let verify = verify_for(src);
345    // Decoded INSIDE the borrow, straight out of the resident shard bytes. The
346    // blob used to be cloned out first, which copied the whole program a second
347    // time for no reason.
348    let cp: CProg = with_shard(|m| {
349        let (v, blob) = m.get(key)?;
350        if v != verify {
351            return None;
352        }
353        bincode::deserialize(blob).ok()
354    })?;
355    let mut prog = Program {
356        main: cp.main,
357        functions: cp.functions,
358        tries: cp.tries,
359        strict: cp.strict,
360    };
361    // `Chunk::op_hash` is `#[serde(skip)]` in fusevm — it is a CACHE of the
362    // hash of ops+constants, computed by `ChunkBuilder::build`, so every chunk
363    // that comes back from a blob carries 0. Anything keyed by it then looks up
364    // the wrong entry: the compiler's side tables below, and fusevm's own JIT
365    // cache, which would see every cached chunk as the same key. Recomputing it
366    // with `build`'s own algorithm is what makes a loaded chunk indistinguishable
367    // from a compiled one.
368    rehash(&mut prog);
369    // A hit skips lex/parse/lower, and with it every `register_*` the compiler
370    // would have run — so the tables come back from the entry instead.
371    crate::host::restore_site_tables(&cp.sites);
372    Some(prog)
373}
374
375/// Recompute `op_hash` on every chunk of `prog`, exactly as
376/// `fusevm::ChunkBuilder::build` does: `DefaultHasher` over `ops` then
377/// `constants`.
378///
379/// The two must stay in step; a blob is only ever read back by the binary that
380/// wrote it (the cache key carries `BUILD_VERSION` and the binary's own mtime),
381/// so the hasher cannot change underneath an entry.
382fn rehash(prog: &mut Program) {
383    fn one(c: &mut Chunk) {
384        use std::collections::hash_map::DefaultHasher;
385        use std::hash::{Hash, Hasher};
386        let mut h = DefaultHasher::new();
387        c.ops.hash(&mut h);
388        c.constants.hash(&mut h);
389        c.op_hash = h.finish();
390    }
391    one(&mut prog.main);
392    for (_, f) in &mut prog.functions {
393        one(&mut f.chunk);
394    }
395    for t in &mut prog.tries {
396        one(&mut t.block);
397        if let Some((_, h)) = &mut t.handler {
398            one(h);
399        }
400        if let Some(f) = &mut t.finalizer {
401            one(f);
402        }
403    }
404}
405
406/// Record `prog` (compiled from `src`) in the resident shard. Reaches disk at
407/// [`flush`], not here.
408pub fn store(src: &str, prog: &Program) -> Result<(), String> {
409    let cp = CProg {
410        main: prog.main.clone(),
411        functions: prog.functions.clone(),
412        tries: prog.tries.clone(),
413        // Taken after the compile that produced `prog`, so the entry carries
414        // what that compile registered.
415        sites: crate::host::site_tables(),
416        strict: prog.strict,
417    };
418    let blob = bincode::serialize(&cp).map_err(|e| format!("cache encode: {e}"))?;
419    let key = key_for(src);
420    let verify = verify_for(src);
421    with_shard(|m| {
422        m.added.insert(key, (verify, blob));
423        m.dirty = true;
424    });
425    Ok(())
426}
427
428/// Write the resident shard back, once, at the end of the run.
429///
430/// The on-disk shard is re-read and MERGED rather than overwritten: up to 16
431/// instances share it, and a plain overwrite would drop whatever a peer stored
432/// while this process was running. A losing writer still only loses entries
433/// (they recompile next run); it can never corrupt the file, since the write
434/// itself is a temp-plus-rename.
435pub fn flush() {
436    let build = build_id();
437    // Materialized here and nowhere else: writing is the one operation that
438    // genuinely needs owned blobs, and it happens at most once per run.
439    let pending = SHARD.with(|c| {
440        let mut slot = c.borrow_mut();
441        match slot.as_mut() {
442            Some(m) if m.dirty => {
443                m.dirty = false;
444                Some(
445                    m.iter()
446                        .map(|(k, v, b)| (k, (v, b.to_vec())))
447                        .collect::<rustc_hash::FxHashMap<u64, (u64, Vec<u8>)>>(),
448                )
449            }
450            _ => None,
451        }
452    });
453    let Some(mut merged) = pending else { return };
454    // Re-read the shard only if it CHANGED since this process read it.
455    //
456    // The merge exists for the concurrent case — up to 16 instances share the
457    // file — but the common case is that nobody else wrote, and there the
458    // re-read deserializes and validates the whole shard a second time for a
459    // result already resident in `merged`. Measured on a 2 MB shard (debug
460    // build), that second `load_shard` is ~0.4 s of a ~2 s run, paid by every
461    // run that compiles anything. An unchanged `(mtime, len)` means no peer
462    // committed a write (the writer renames a temp file into place, so any
463    // commit moves both), and the entries we would merge back are exactly the
464    // ones we already hold.
465    let stamp = SHARD.with(|c| c.borrow().as_ref().and_then(|m| m.stamp));
466    if shard_stamp() != stamp {
467        for e in load_shard().entries {
468            if e.build == build {
469                merged.entry(e.key).or_insert((e.verify, e.blob));
470            }
471        }
472    }
473    let shard = Shard {
474        entries: merged
475            .into_iter()
476            .map(|(key, (verify, blob))| Entry {
477                key,
478                verify,
479                build,
480                blob,
481            })
482            .collect(),
483    };
484    let _ = write_shard(&shard);
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490
491    /// Both cache hashes must depend on the BUILD, not on `SCHEMA` alone.
492    ///
493    /// `SCHEMA` and `BUILD_VERSION` are bumped by hand, so the codegen change
494    /// that forgets one would otherwise read the previous build's bytecode out
495    /// of the shared shard and run the wrong program with no error. This was a
496    /// real, reproduced failure: with the key depending on `(SCHEMA, src)`
497    /// alone, lowering `**` to a wrong opcode and rebuilding still printed the
498    /// OLD answer for an already-cached script.
499    ///
500    /// Each hash is recomputed here with a component left out and required to
501    /// differ, so DELETING any one of the four `hash` lines in `key_for` /
502    /// `verify_for` fails this test rather than silently restoring the bug.
503    #[test]
504    fn cache_keys_depend_on_the_build_not_just_the_schema() {
505        use std::collections::hash_map::DefaultHasher;
506        let src = "console.log(1)\n";
507
508        // key_for without the version+build id.
509        let mut bare = rustc_hash::FxHasher::default();
510        SCHEMA.hash(&mut bare);
511        src.hash(&mut bare);
512        assert_ne!(
513            key_for(src),
514            bare.finish(),
515            "key_for must hash the build identity, not just SCHEMA"
516        );
517
518        // key_for with the version but WITHOUT the per-build id: this is what
519        // the fleet's version-only design hashes, and it is what leaves two dev
520        // builds of one version sharing a shard.
521        let mut version_only = rustc_hash::FxHasher::default();
522        SCHEMA.hash(&mut version_only);
523        BUILD_VERSION.hash(&mut version_only);
524        src.hash(&mut version_only);
525        assert_ne!(
526            key_for(src),
527            version_only.finish(),
528            "key_for must hash the per-build id, so two dev builds of one \
529             version cannot share cached bytecode"
530        );
531
532        // verify_for, same two omissions.
533        let mut bare = DefaultHasher::new();
534        SCHEMA.hash(&mut bare);
535        src.len().hash(&mut bare);
536        src.hash(&mut bare);
537        assert_ne!(
538            verify_for(src),
539            bare.finish(),
540            "verify_for must hash the build identity, not just SCHEMA"
541        );
542
543        let mut version_only = DefaultHasher::new();
544        SCHEMA.hash(&mut version_only);
545        BUILD_VERSION.hash(&mut version_only);
546        src.len().hash(&mut version_only);
547        src.hash(&mut version_only);
548        assert_ne!(
549            verify_for(src),
550            version_only.finish(),
551            "verify_for must hash the per-build id"
552        );
553
554        // The version that is hashed is THIS build's, so a release bump rotates
555        // the whole shard.
556        assert_eq!(BUILD_VERSION, env!("CARGO_PKG_VERSION"));
557        // A `0` build id means the stat failed and the per-build guarantee is
558        // gone; under `cargo test` the binary is always readable.
559        assert_ne!(build_id(), 0, "build_id must read the running binary");
560        // Distinct sources still land on distinct keys.
561        assert_ne!(key_for(src), key_for("console.log(2)\n"));
562    }
563}