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