#10862·numba

IndexDataCacheFile.save: unlocked read-modify-write lets two cache keys share one .nbc, so a signature can load another signature's compiled code

Author: shauncCreated Sep 27, 2026Updated Sep 28, 2026
Labelsmore info needed

Reporting a bug

  • I have tried using the latest released version of Numba. Caveat, stated plainly: the measurements below are on 0.62.1. I have not re-run them on 0.67.0, but I read numba/core/caching.py on current main via the GitHub API today and the two code paths involved are unchanged — IndexDataCacheFile.save is identical, and Cache._index_key still reduces with hashlib.sha256. So I believe this is current; please tell me if you'd like it re-measured on 0.67.0 before you spend time on it.
  • I have included a self contained code sample to reproduce the problem.

Summary

IndexDataCacheFile.save is an unlocked read-modify-write over a shared index file, and the data-file number it picks is chosen from an index that a concurrent process may already have moved on from. Two processes saving different keys can both select ...1.nbc. The surviving index entry then points at a data file the other process overwrote, so a later load(key) returns compiled code for a different signature.

This is related to #10128 but is a distinct mechanism and I did not want to bury it in that thread: #10128 is about the abi-version counter and a GUFunc's paired .nbc files, whereas this is about the data-file numbering itself and needs neither GUFuncs nor a shared signature. They do share a root cause — save() has no cross-process synchronisation — so a fix for this one may well subsume #10128.

The code

numba/core/caching.py (current main, and 0.62.1):

python
def save(self, key, data):
    overloads = self._load_index()          # (1) read the whole index
    try:
        data_name = overloads[key]
    except KeyError:
        existing = set(overloads.values())
        for i in itertools.count(1):        # (2) pick the LOWEST unused number
            data_name = self._data_name(i)
            if data_name not in existing:
                break
        overloads[key] = data_name
        self._save_index(overloads)         # (3) write the whole index back
    self._save_data(data_name, data)        # (4) write the .nbc

_open_for_write makes each individual file write atomic (uuid temp + os.replace), which is why this reads as safe on inspection. But nothing serialises steps (1)–(4) across processes. Interleaving two processes P1 (key A) and P2 (key B), both starting from the same index state:

P1 (key A) P2 (key B)
1 reads index {}
2 reads index {}
3 picks ...1.nbc, writes index {A: 1}
4 picks ...1.nbc, writes index {B: 1}
5 writes 1.nbc = A's code
6 writes 1.nbc = B's code

Whichever index write lands last decides the mapping, and it may name a data file whose contents are now the other key's. A subsequent load(A) succeeds structurally and hands back B's compiled code.

The failure is not always loud. A lost index entry is benign (it just recompiles). The damaging outcome is a surviving entry pointing at overwritten data, which surfaces as a signature mismatch at call time — for us:

TypeError: can't unbox array from PyObject into native value.
           The object maybe of a different type

Reproducer

Self-contained, uses only Numba's own class with plain string payloads so a mismatch is unambiguous (no compilation, so it isolates the cache logic):

python
"""python numba_cache_collision.py  -> exits 1 if a key loads another's data."""
import multiprocessing as mp
import shutil
import sys
import tempfile
from pathlib import Path

from numba.core.caching import IndexDataCacheFile

N_PROCS = 24
N_ROUNDS = 5
_STAMP = ("proof", 1)
_BASE = "collision_probe"
_barrier = None


def _init(barrier):
    global _barrier
    _barrier = barrier


def _saver(args):
    idx, cache_dir = args
    cache = IndexDataCacheFile(
        cache_path=cache_dir, filename_base=_BASE, source_stamp=_STAMP
    )
    _barrier.wait()                       # make the saves overlap
    cache.save(f"k{idx}", f"payload-{idx}")


def main():
    ctx = mp.get_context("forkserver")
    total_wrong = 0
    for rnd in range(1, N_ROUNDS + 1):
        cache_dir = tempfile.mkdtemp(prefix="numba-cache-proof-")
        barrier = ctx.Barrier(N_PROCS)
        with ctx.Pool(N_PROCS, initializer=_init, initargs=(barrier,)) as pool:
            pool.map(_saver, [(i, cache_dir) for i in range(N_PROCS)])

        # A FRESH reader, as a later process would be.
        verifier = IndexDataCacheFile(
            cache_path=cache_dir, filename_base=_BASE, source_stamp=_STAMP
        )
        misses = wrong = 0
        for i in range(N_PROCS):
            got = verifier.load(f"k{i}")
            if got is None:
                misses += 1               # benign: recompiles
            elif got != f"payload-{i}":
                wrong += 1               # THE BUG: another key's data
                print(f"    WRONG: key 'k{i}' -> {got!r}")
        nbc = sorted(Path(cache_dir).glob(f"{_BASE}*.nbc"))
        print(
            f"round {rnd}: {len(nbc)} data files for {N_PROCS} distinct keys; "
            f"{misses} misses, {wrong} wrong-payload loads"
        )
        total_wrong += wrong
        shutil.rmtree(cache_dir, ignore_errors=True)
    sys.exit(1 if total_wrong else 0)


if __name__ == "__main__":
    main()

Measured, numba 0.62.1 / numpy 2.3.5 / CPython 3.13.1 / Linux 6.8 x86-64:

    WRONG: key 'k15' -> 'payload-17'
    WRONG: key 'k22' -> 'payload-20'
round 1: 3 data files for 24 distinct keys; 21 misses, 3 wrong-payload loads
    WRONG: key 'k3' -> 'payload-4'
round 2: 3 data files for 24 distinct keys; 21 misses, 1 wrong-payload loads
    WRONG: key 'k6' -> 'payload-21'
    WRONG: key 'k13' -> 'payload-1'
round 3: 3 data files for 24 distinct keys; 22 misses, 2 wrong-payload loads
    WRONG: key 'k9' -> 'payload-8'
    WRONG: key 'k17' -> 'payload-20'
round 4: 2 data files for 24 distinct keys; 22 misses, 2 wrong-payload loads
    WRONG: key 'k21' -> 'payload-0'
    WRONG: key 'k22' -> 'payload-8'
round 5: 2 data files for 24 distinct keys; 22 misses, 2 wrong-payload loads

Only 2-3 data files exist for 24 distinct keys — that is the collision. Ten wrong-payload loads across five rounds here; in Numba's terms, ten occasions where a signature's cache entry would have handed back another signature's compiled code.

The exact counts vary run to run (it is a race), but the collapse in data-file count is consistent and every run I have done produced at least one wrong-payload load. Note the misses are the benign half — those keys simply recompile.

Why it bit us in the field, in case the shape is useful

We hit this in a project that runs a pool of forkserver worker processes compiling concurrently. One @njit(cache=True) function in a dependency is defined inside a closure, so every specialisation it is ever used with shares one .nbi index (the cache key is qualname + source line, and the distinguishing type is only in the closure). That maximises the number of distinct keys racing for the same lowest-free data-file number.

The observable was that a ring-buffer constructor for one record type had loaded the compiled binary of a different record type. From 106 instrumented failures, all uniform:

  • argument: a 4-field record, itemsize 32
  • the signature the dispatcher actually held: a 10-field record, itemsize 56
  • cache_hits non-empty, cache_misses empty — i.e. it came off disk

For anyone who finds this by searching: two wrong theories cost us a day, so to save you the same —

  1. It is not key aliasing. _index_key hashes the closure cells with hashlib.sha256, so the distinguishing type does reach the key at full strength and two different types cannot collide on the key. The collision is one level down, in the file the key points at.
  2. A lock on save fixes new corruption but cannot repair entries already poisoned on disk, and the cache is persistent. We shipped the lock and the symptom persisted identically for three releases, because the poison was being re-read. That looked exactly like the fix not working.

Suggested fix

The read-modify-write needs to be atomic with respect to other processes. As a downstream mitigation we wrapped save in an inter-process file lock keyed on the index path, which was sufficient — with saves serialised, no two keys can select the same data-file number, and load reads files that _open_for_write replaces atomically. That is a blunt instrument for upstream, though; allocating the data-file name in a way that cannot collide (e.g. deriving it from a hash of the key rather than from a scan of the current index) would avoid the lock entirely and would also make step (3) idempotent.

Happy to open a PR for whichever direction you prefer.