Repository navigation
Description
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:189in_run_with_log_contextnanopynix/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
- Measure the formatting cost. The 139
debugsites in libstore fire per
store operation. Compare a large realise and a large closure copy with the
global atlvlVomitagainst the same atlvlInfo. - Confirm nothing else writes the global in this process. In Nix 2.34 the
writers arelibmain/common-args.cc,src/nix/*,libutil-c, the Perl
bindings, andlibstore/daemon.cc:239. nanopynix uses none of the first
four.daemon.cc:239runs in a process that serves the daemon protocol,
which nanopynix does not do -- confirm that stays true. - 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. - 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.txtalready 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
verbosityastd::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::verbosityis written once, before any thread starts, and no other
code in this repository writes it.PyLoggerfilters on a thread-local verbosity in all four oflog,
logEI,warnandstartActivity.set_verbosityandget_verbosityact 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
[-]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[/+]fix(bindings): pin nix::verbosity, and filter the log per thread
fix(bindings): pin nix::verbosity, and filter the log per thread
fix(bindings): pin nix::verbosity, and filter the log per thread
fix(bindings): pin nix::verbosity, and filter the log per thread
Lillecarl commentedon Aug 4, 2026
The ceiling is
chatty, notvomit, and here is the measurement that moved itThe first measurement of the ceiling covered evaluation and store work only:
an eval fold, 2000
query_path_infothrough the daemon, a 200-root closurewalk, and 300
query_path_info/is_valid_pathagainst an in-processLocalStore. Every cell said the same thing, that the spread inside oneceiling 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_31failed 9 tests, all of them flake tests,all on
DEADLINE_EXCEEDEDinsideeval_flake, three runs in a row, against adevelopbaseline that passes the same job.Reproduced on
pynix flake showof a git flake, Nix 2.31, rpc engine, coldfetch cache, and the 30 second deadline that CI gives an rpc call:
errorchattydebugvomitThe 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.
debugfails exactly asvomitdoes.printMsgcompareslvl <= nix::verbosity, so a ceiling ofdebugalready admits all 208debugsites, and the 5vomitsites above them add nothing. The cliff isbetween
chattyanddebug, 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 thecalling thread, but Nix drops a
debugmessage before the filter ever seesit, so no
debugmessage arrives.get_log_ceiling()reports the ceiling,and
NANOPYNIX_LOG_CEILINGraises it at import for anybody who wantsdebugmore 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::verbositywrittenonce, before any Nix thread exists. It never needed the value to be
vomit.fix(bindings): pin nix::verbosity, and filter the log per thread
Lillecarl commentedon Aug 4, 2026
Five of the six acceptance criteria are met. The sixth is #97.
Run 30934106841
on
ci-developat69486a99:The three failures are
test-asan-nix_2_34,test-asan-nix_2_35andtest-asan-git, all on the runaway-recursion stack overflow of #100. That isthe same shape as
developat689ec37c, run 30907694264, which thisbranch sits on: the same three jobs, the same three tests, and nothing else.
nix::verbositywritten once, before any thread startsPyLoggerfilters on a thread-local inlog,logEI,warn,startActivityset_verbosity/get_verbosityact on the thread-local, docstrings say the scopeThe last one is #97, and it is not an oversight. This change keeps the
contract that
protocols.pydocuments and thattest_verbosity_is_one_process_wide_setting_with_two_doorspins: verbosityis 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::verbosityreport appeared anywhere.One thing had to be corrected on the way.
test-tsan-gitreported a genuinerace in an earlier run, in sqlite's write-ahead log rather than in this code:
walTryBeginReadagainstwalIndexRecover, both undernix::LocalStore::openDB. sqlite excludes those two with POSIX byte-rangelocks, and TSAN models no happens-before edge for a file lock, so it reports
the pair whatever the code does.
nix/tsan-suppressions.txtnow carries thesuppression, scoped to the WAL layer and with sqlite's own source quoted.
Lillecarl commentedon Aug 5, 2026
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:
nix::verbositywritten once, before any thread startsPyLoggerfilters on a thread-local inlog,logEI,warn,startActivityset_verbosity/get_verbosityact on the thread-local, docstrings say the scopeThe sixth is not a gap in the race fix. It asks for per-evaluator verbosity,
which rewrites the contract that
protocols.pydocuments and thattest_verbosity_is_one_process_wide_setting_with_two_doorspins. Thatrewrite 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::verbosityis still a plain non-atomic global in every supportedversion, checked again today against the sources of 2.31, 2.34 and 2.35:
So the pin stays necessary, and it is not a workaround for one version.
feat(verbosity): give each evaluator a log level of its own
docs(verbosity): say what an evaluator's level covers, and what it do…
fix(bindings): pin nix::verbosity, and filter the log per thread
feat(verbosity): give each evaluator a log level of its own
docs(verbosity): say what an evaluator's level covers, and what it do…