8000 bindings: pin nix::verbosity and filter per thread, to fix a data race and get per-evaluator verbosity · Issue #92 · nixidae/nixidae · GitHub
[go: up one dir, main page]

Skip to content

bindings: pin nix::verbosity and filter per thread, to fix a data race and get per-evaluator verbosity #92

Closed

Description

@Lillecarl

What

ThreadSanitizer reports a data race on nix::verbosity whenever one thread
sets the verbosity while another evaluates or logs.

WARNING: ThreadSanitizer: data race (pid=8)
  Write of size 4 at 0x7fffeb71f578 by thread T76:
    #0 <null> (_ext.cpython-314-x86_64-linux-gnu.so+0x2cf9d)

  Previous read of size 4 at 0x7fffeb71f578 by thread T99:
    #0 derivationStrictInternal ../primops.cc:1504 (libnixexpr.so.2.34.8)
    nixidae/nixidae#30 prim_derivationStrict ../primops.cc:1404
    ...
    nixidae/nixidae#43 nix::EvalState::eval(nix::Expr*, nix::Value&) ../eval.cc:1173

  Location is global 'nix::verbosity' of size 4 (libnixutil.so.2.34.8)

  Thread T76 'nix-store_2' (tid=536, running)
  Thread T99 'nix-eval_0' (tid=576, running)

Why it is real

nix/util/logging.hh:304 declares the global with no synchronisation, and
the comment above it states its whole job:

/**
 * suppress msgs > this
 */
extern Verbosity verbosity;

nanopynix-bindings/src/nix_util.cpp:237 writes it:

static void set_verbosity(int lvl) {
    nix::verbosity = (nix::Verbosity) lvl;
}

Every log macro reads it, for example logging.hh:330:

#define printMsgUsing(loggerParam, level, args...) \
    do {                                           \
        auto __lvl = level;                        \
        if (__lvl <= nix::verbosity) {             \
            loggerParam->log(__lvl, fmt(args));    \
        }                                          \
    } while (0)

So a write from any thread races every other thread that logs or evaluates.
This is a race by the C++ memory model. The effect looks small: the object is
an aligned 4-byte enum, so a read returns the old value or the new one and not
a torn one, and a reader can act on a stale verbosity briefly.

Upstream Nix does not meet this, because it evaluates on one thread.
nanopynix runs an evaluator thread and store threads in one process, so it
does.

How it was found

The concurrency soak, tests/support/soak.py. It reproduces on 2 of 3 seeds:

seed result
1 race on nix::verbosity
2 clean, 4 passed in 90.19s
3 race on nix::verbosity, different threads
nix build .#nanopynix-tests-nix_2_34-tsan --out-link result
unshare --user --map-root-user --mount --pid --fork --mount-proc \
  env NANOPYNIX_TEST_SANITIZER=tsan ./result/bin/nanopynix-tests \
  --capture=no --run-temp-store-builds --nix-test-backends local,daemon \
  -m soak --soak-seed=1

The soak prints its schedule into the same log, so the line above the report
names the test that wrote:

SOAK 0.490 lane=0 START tests/nanopynix/inproc/test_inproc.py::test_inproc_session_verbosity_roundtrip
==================
WARNING: ThreadSanitizer: data race (pid=8)

Why it blocks

TSAN_OPTIONS sets halt_on_error=1, so the report kills the process (exit
66) and the job's grep for ThreadSanitizer: data race fails the run. The
TSAN soak job stays red until this is decided.

Proposed fix: pin the global, and filter per thread

Write nix::verbosity once, at initialisation, at the most verbose level.
Never write it again. Filter per thread in PyLogger instead.

This removes the race rather than hiding it: a global written once, before any
thread starts, is ordered before every reader. It also turns a process-wide
setting into a per-thread one, which is a capability nanopynix does not have
today.

Most of the work is already done

PyLogger already filters by verbosity itself. Four methods in
nanopynix-bindings/src/nix_util.cpp open with the same gate:

void log(nix::Verbosity lvl, std::string_view s) override {
    if (lvl > nix::verbosity) return;

logEI (line 108), warn (line 117) and startActivity (line 133) repeat
it. Those four reads are the whole filter, and each becomes a read of a
thread-local instead.

A thread-local log context already exists, with its plumbing on both
engines.
nix_util.cpp:88:

static thread_local int64_t logger_request_id = 0;

Both engines save, set and restore it around every Nix call, in the one
chokepoint each of them has:

  • nanopynix/inproc/_impl.py:189 in _run_with_log_context
  • nanopynix/rpc/worker/_state.py:100

A thread_local Verbosity set in those same two places gives per-request
verbosity for free. Because an EvalState is confined to its own thread,
per-thread also means per-evaluator.

What it costs

The gate is what keeps fmt(args) from running, and the macro is a macro for
exactly that reason -- logging.hh:326 says so: "this has to be implemented
as a macro to ensure that the arguments are evaluated lazily"
. Pinned at
lvlVomit, every site formats its message and calls into PyLogger, which
drops it.

Site counts in Nix 2.34:

macro libstore libexpr libutil libfetchers
vomit 3 1 1 0
debug 139 16 17 36
printTalkative 2 2 1 2
printInfo 31 0 1 0

The high-volume path is already unaffected, and this is the measurement
that makes the idea look affordable.
Activity::Activity
(libutil/logging.cc:186) calls the logger with no verbosity check at all:

Activity::Activity(Logger & logger, Verbosity lvl, ActivityType type, ...)
    : logger(logger), id(nextId++ + (((uint64_t) getPid()) << 32))
{
    logger.startActivity(id, lvl, type, s, fields, parent);
}

Nix constructs one Activity per derivation, store path and substitution --
hundreds of thousands for a big closure -- and every one of them already
reaches PyLogger::startActivity whatever nix::verbosity says. Pinning the
global changes nothing there.

That leaves the printMsg family. The evaluator hot path is libexpr, and it
has 19 sites between the four macros.

What to check before committing to it

  1. Measure the formatting cost. The 139 debug sites in libstore fire per
    store operation. Compare a large realise and a large closure copy with the
    global at lvlVomit against the same at lvlInfo.
  2. Confirm nothing else writes the global in this process. In Nix 2.34 the
    writers are libmain/common-args.cc, src/nix/*, libutil-c, the Perl
    bindings, and libstore/daemon.cc:239. nanopynix uses none of the first
    four. daemon.cc:239 runs in a process that serves the daemon protocol,
    which nanopynix does not do -- confirm that stays true.
  3. Decide what get_verbosity() returns. It reads the global today
    (nix_util.cpp:241). It should read the thread-local, or the API stops
    describing what the caller actually gets.
  4. Keep a process-wide default. A thread that never sets one needs a
    sensible floor, and it has to be published before any thread starts, for
    the same reason the pin does.

The alternatives, and why they are worse

  • Suppress it. nix/tsan-suppressions.txt already carries one entry of
    this shape. It costs nothing and buys nothing, and it leaves a real race in
    the tree with a note saying it is fine.
  • Make verbosity a std::atomic<Verbosity> upstream. Correct, and an
    ABI change in libnixutil that nanopynix does not control.
  • Serialise the write in nanopynix. Does not work. The readers are every
    log macro in Nix, so locking the writer alone leaves the race.

Acceptance criteria

  • nix::verbosity is written once, before any thread starts, and no other
    code in this repository writes it.
  • PyLogger filters on a thread-local verbosity in all four of log,
    logEI, warn and startActivity.
  • set_verbosity and get_verbosity act on the thread-local, and the
    docstring of each says the scope.
  • A test proves two evaluators can hold different verbosities at once, and
    that each one sees only its own events.
  • The measurement from check 1 is recorded, wherever the next reader of this
    code will find it.
  • The TSAN soak job passes over its five seeds.

Activity

  1. changed the title [-]bindings: setting the verbosity races every thread that logs, because nix::verbosity is a plain global[/-] [+]bindings: pin nix::verbosity and filter per thread, to fix a data race and get per-evaluator verbosity[/+] on Aug 4, 2026
  2. Lillecarl commented on Aug 4, 2026

    @Lillecarl
    ContributorAuthor

    The ceiling is chatty, not vomit, and here is the measurement that moved it

    The first measurement of the ceiling covered evaluation and store work only:
    an eval fold, 2000 query_path_info through the daemon, a 200-root closure
    walk, and 300 query_path_info / is_valid_path against an in-process
    LocalStore. Every cell said the same thing, that the spread inside one
    ceiling is wider than the gap between ceilings.

    That measurement had no flake or fetcher cell, and the conclusion was
    written as though it did.
    A flake evaluation fetches, and the fetch path
    logs far more than a store query does.

    CI found it. test-daemon-nix_2_31 failed 9 tests, all of them flake tests,
    all on DEADLINE_EXCEEDED inside eval_flake, three runs in a row, against a
    develop baseline that passes the same job.

    Reproduced on pynix flake show of a git flake, Nix 2.31, rpc engine, cold
    fetch cache, and the 30 second deadline that CI gives an rpc call:

    ceiling outcome
    error 5 passed
    chatty 5 passed
    debug 5 failed
    vomit 5 failed

    The arms ran in both orders, because the first pair shared a Nix store and the
    second arm could have inherited what the first one fetched. The outcome
    follows the ceiling and not the position.

    debug fails exactly as vomit does. printMsg compares
    lvl <= nix::verbosity, so a ceiling of debug already admits all 208
    debug sites, and the 5 vomit sites above them add nothing. The cliff is
    between chatty and debug, which is where the original analysis put it --
    what was missing was a workload that stands on the wrong side of it.

    So the default ceiling is chatty, the highest level that costs nothing.
    Verified under the conditions that failed: 14 tests passed, cold cache, 30
    second deadline, Nix 2.31, no environment override.

    What this costs a caller

    set_verbosity(DEBUG) is still accepted and still changes the level of the
    calling thread, but Nix drops a debug message before the filter ever sees
    it, so no debug message arrives. get_log_ceiling() reports the ceiling,
    and NANOPYNIX_LOG_CEILING raises it at import for anybody who wants debug
    more than they want the fetch path to be fast.

    This narrows what the library delivers at runtime, and it argues against the
    premise that pinning wide open would stay fast.
    It holds for evaluation and
    store work. It does not hold for fetching.

    The race fix is unaffected: removing the race needs nix::verbosity written
    once, before any Nix thread exists. It never needed the value to be vomit.

  3. Lillecarl commented on Aug 4, 2026

    @Lillecarl
    ContributorAuthor

    Five of the six acceptance criteria are met. The sixth is #97.

    Run 30934106841
    on ci-develop at 69486a99:

    {"failure": 3, "skipped": 2, "success": 22}
    

    The three failures are test-asan-nix_2_34, test-asan-nix_2_35 and
    test-asan-git, all on the runaway-recursion stack overflow of #100. That is
    the same shape as develop at 689ec37c, run 30907694264, which this
    branch sits on: the same three jobs, the same three tests, and nothing else.

    criterion state
    nix::verbosity written once, before any thread starts met
    PyLogger filters on a thread-local in log, logEI, warn, startActivity met
    set_verbosity/get_verbosity act on the thread-local, docstrings say the scope met
    The measurement is recorded where the next reader finds it met
    The TSAN soak passes over its five seeds met
    A test proves two evaluators hold different verbosities at once not met

    The last one is #97, and it is not an oversight. This change keeps the
    contract that protocols.py documents and that
    test_verbosity_is_one_process_wide_setting_with_two_doors pins: verbosity
    is one process-wide setting with two doors. Per-evaluator verbosity rewrites
    that contract and the tests that hold it. Landing the race fix and the
    contract change together would give a race fix that nobody can review on its
    own.

    So this issue stays open until #97 lands, or it closes and #97 carries the
    last criterion. That is a call for whoever owns the roadmap.

    The soak result, in detail

    The TSAN soak ran five seeds against both backends on 2.34, 2.35 and git.
    Every seed exited 0 on its first attempt, so the retry budget of #98 was
    never drawn on, and no nix::verbosity report appeared anywhere.

    One thing had to be corrected on the way. test-tsan-git reported a genuine
    race in an earlier run, in sqlite's write-ahead log rather than in this code:
    walTryBeginRead against walIndexRecover, both under
    nix::LocalStore::openDB. sqlite excludes those two with POSIX byte-range
    locks, and TSAN models no happens-before edge for a file lock, so it reports
    the pair whatever the code does. nix/tsan-suppressions.txt now carries the
    suppression, scoped to the WAL layer and with sqlite's own source quoted.

  4. Lillecarl commented on Aug 5, 2026

    @Lillecarl
    ContributorAuthor

    Closing this, and #97 carries the last criterion

    The previous comment left the choice open: this issue waits for #97, or it
    closes and #97 carries the sixth criterion. It closes.

    The race is fixed, and the fix stands on its own evidence:

    criterion state
    nix::verbosity written once, before any thread starts met
    PyLogger filters on a thread-local in log, logEI, warn, startActivity met
    set_verbosity/get_verbosity act on the thread-local, docstrings say the scope met
    The measurement is recorded where the next reader finds it met
    The TSAN soak passes over its five seeds met
    A test proves two evaluators hold different verbosities at once #68

    The sixth is not a gap in the race fix. It asks for per-evaluator verbosity,
    which rewrites the contract that protocols.py documents and that
    test_verbosity_is_one_process_wide_setting_with_two_doors pins. That
    rewrite is #97, and the mechanism it needs is already here: the level is
    thread-local now.

    Keeping this issue open until #97 lands would tie a proven race fix to an API
    change that has to be reviewed on its own terms.

    nix::verbosity is still a plain non-atomic global in every supported
    version, checked again today against the sources of 2.31, 2.34 and 2.35:

    nix_2_31  logging.hh:303:extern Verbosity verbosity;
    nix_2_34  logging.hh:304:extern Verbosity verbosity;
    nix_2_35  logging.hh:307:extern Verbosity verbosity;
    

    So the pin stays necessary, and it is not a workaround for one version.

  5. added
    source: nanopynix
    on Oct 19, 2026
  6. added theissue type on Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    source: nanopynix

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0