Repository navigation
Description
I found this while working on sqlfluff, finding a random failure in CI. This is incredibly difficult to reliably reproduce, and even when I can reproduce it it's a small percentage thing. Reproducing it basically requires sqlfluff's test suite including pinned versions, so I'm just going to tell you what you are doing that is undefined behavior so you can fix it.
I'm sure that the problem is real, and the workaround definitely fixes it. That much I can vouch for.
Workaround on the sqlfluff side: sqlfluff#9075 (the change).
The details below about why exactly it happens, I'm less sure about.
Model loading forks worker processes from a process that has running threads, and the workers then run Python. POSIX does not allow the child of a multi-threaded fork() to call anything but a short list of async-signal-safe functions, so this is undefined behavior. One way it shows up is an intermittent segfault in a worker. This is likely the crash that #6145 worked around.
Where: create_process_pool_executor always uses the fork start method:
sqlmesh/sqlmesh/utils/process.py
Line 69 in 7975a8d
| mp_context=mp.get_context("fork"), |
It is used for model loading and the optimized query cache:
sqlmesh/sqlmesh/core/loader.py
Line 778 in 7975a8d
| with create_process_pool_executor( |
sqlmesh/sqlmesh/core/model/cache.py
Line 190 in 7975a8d
| return create_process_pool_executor( |
How it crashes: a Context that is no longer used waits in a reference cycle for the garbage collector, still holding an open DuckDB connection. When a new context loads, the pool forks. If the collector then runs in a worker, the worker frees the old connection. DuckDB's destructor joins its worker threads, which do not exist in the child, and the worker segfaults.
Context.close() does not prevent this. It closes the snapshot evaluator and the state sync, but not the context's own engine adapter, which is what loading opens. A context that has only rendered never builds a snapshot evaluator, so its DuckDB connection stays open after close():
sqlmesh/sqlmesh/core/context.py
Line 2751 in 7975a8d
| def close(self) -> None: |
Fixes:
Context.close()should also closeself._engine_adapterand any cachedengine_adapters.- Calling
gc.collect()increate_process_pool_executor, before the pool forks, frees dropped objects in the process that owns their threads. This is what sqlfluff now does before creating a context, and it stopped the crash there (0 of 60 runs, against about 10% before). It narrows the problem; the fork is still undefined behavior. - The real fix is a start method that does not fork the multi-threaded process (
forkserverorspawn). Python 3.14 madeforkserverthe POSIX default for this reason. That likely needs the poolinitargs(console, cache) to be picklable.
Evidence
Native backtrace from a crashed worker (same in 12 cores):
#5 __pthread_clockjoin_ex
#6 std::thread::join()
#7 duckdb::TaskScheduler::RelaunchThreadsInternal(int, bool)
#8 duckdb::TaskScheduler::~TaskScheduler()
#9 duckdb::DatabaseInstance::~DatabaseInstance()
#11 duckdb::ClientContext::~ClientContext()
#13 duckdb::DuckDBPyConnection::~DuckDBPyConnection()
#18 subtype_dealloc
...
#24 gc_collect_main
The parent then fails with A process in the process pool was terminated abruptly and SchemaError: Failed to update model schemas from process_models. Python 3.12 warns at each fork: DeprecationWarning: This process ... is multi-threaded, use of fork() may lead to deadlocks in the child.
Seen in the sqlfluff SQLMesh templater tests, which create one context per test against a DuckDB :memory: gateway. Whether it fires depends on when the garbage collector runs, so it comes and goes with unrelated changes to allocation patterns.
Versions: sqlmesh 0.235.4 (code unchanged on main at 7975a8d), duckdb 1.5.6, sqlglot 30.8.0, CPython 3.12.16, Linux x86_64.
Activity
connordouglashanna commentedon Dec 2, 2026
Adding a data point to this issue: on macOS the same mechanism makes model loading hang forever instead of segfaulting. Below is a deterministic repro, an isolated DuckDB repro, and test results for the
gc.collect()fix.I subjected this to a lot of agentic review and verification, but for transparency, this was mostly diagnosed by AI while I worked on another feature.
Symptom on macOS
There is no crash and no error. The parent waits forever in
concurrent.futures.as_completed(sqlmesh/core/loader.py:820, underContext.__init__→load). One worker spins at 100% CPU inGarbage-collecting. Its native stack (from macOSsample) is the same chain as in the Linux backtrace above, but it busy-loops instead of crashing inpthread_join:Nothing detects a dead worker, so the pool never breaks. The process has to be killed, and when it is, its forked workers are left behind as orphans.
Environment:
mainat f4a4192 (0.0.1.dev4813), duckdb 1.5.6, sqlglot 30.8.0, CPython 3.12.13, macOS 26.7.3 (Apple Silicon).MAX_FORK_WORKERSwas unset, which on macOS meansNone→cpu_count()workers, all started withfork(sqlmesh/utils/process.py:69).Deterministic repro (hung 3/3)
On the machine above it always hangs while loading the 5th Context. Which iteration hangs depends on GC thresholds, and 2-3 Contexts usually pass. Two independent sets of runs (hung/total):
MAX_FORK_WORKERS=2ctx.close()after each loadclose()leaves the engine adapter open)MAX_FORK_WORKERS=1gc.collect()before eachContext(...)_data_file_to_adapter,sqlmesh/core/config/connection.py:329, and never become garbage;:memory:is skipped at line 501)A failed load is not needed, but it is a common way to hit this: a
Contextwhose__init__raised (e.g. aConfigError) is kept in a cycle through the traceback. The error type and the model count (1 to 2000) made no difference.Isolated DuckDB repro
Destroying any DuckDB connection inherited across
fork()never returns in the child. It doesn't need a cycle, GC or a query:So sqlmesh's
Context↔ loader cycle (context.py:459/loader.py:182) is just the most common way a connection ends up finalized in a worker. A user-owned DuckDB connection that becomes cyclic garbage right before a load hangs sqlmesh the same way (3/3).Fix results
I applied the issue's proposed
gc.collect()increate_process_pool_executor, before returning theProcessPoolExecutor, in a local copy of sqlmesh. Results (hung/total):Notes on the fix:
loader.py:808,model/schema.py:83,snapshot/cache.py:62).fork, Python 3.12'sProcessPoolExecutorforks all workers together inside the firstsubmit(), and every call site submits immediately.gc.freeze()first, so workers never collect inherited objects. A small window remains between the fork and the initializer.Context.close()would make the user-side workaround work. Moving toforkserver/spawnremains the real fix.A possible regression test, in
tests/test_forking.py(alreadyfork_isolated):MAX_FORK_WORKERS=2;duckdb.connect()inside a reference cycle anddelit without collecting;Context(paths="examples/sushi")in a subprocess with a timeout, and assert that it completes.Not verified: whether other engines' connections misbehave when finalized in a forked child, and Python versions other than 3.12.