Skip to content

Model loading can fork a multi-threaded process and do illegal things causing an intermittent segfault in just the right conditions #6201

Open

Description

@rfanth

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:

mp_context=mp.get_context("fork"),

It is used for model loading and the optimized query cache:

with create_process_pool_executor(

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():

def close(self) -> None:

Fixes:

  • Context.close() should also close self._engine_adapter and any cached engine_adapters.
  • Calling gc.collect() in create_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 (forkserver or spawn). Python 3.14 made forkserver the POSIX default for this reason. That likely needs the pool initargs (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

  1. connordouglashanna commented on Dec 2, 2026

    @connordouglashanna

    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, under Context.__init__ → load). One worker spins at 100% CPU in Garbage-collecting. Its native stack (from macOS sample) is the same chain as in the Linux backtrace above, but it busy-loops instead of crashing in pthread_join:

    gc_collect_main → dict_dealloc → subtype_dealloc
      → ~DuckDBPyConnection → ~DuckDBPyRelation → ~DuckDBPyResult → ~StreamQueryResult
      → ~ClientContext → ~DatabaseInstance → ~TaskScheduler
      → TaskScheduler::RelaunchThreadsInternal → semaphore_signal_trap
    

    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: main at 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_WORKERS was unset, which on macOS means None → cpu_count() workers, all started with fork (sqlmesh/utils/process.py:69).

    Deterministic repro (hung 3/3)

    import faulthandler, tempfile
    from pathlib import Path
    
    from sqlmesh import Context
    from sqlmesh.core.config import Config, DuckDBConnectionConfig, GatewayConfig, ModelDefaultsConfig
    
    faulthandler.dump_traceback_later(60, exit=True)  # dump stacks instead of hanging forever
    
    config = Config(
        gateways={"local": GatewayConfig(connection=DuckDBConnectionConfig())},  # in-memory DuckDB
        default_gateway="local",
        model_defaults=ModelDefaultsConfig(dialect="duckdb"),
    )
    
    for i in range(10):
        project = Path(tempfile.mkdtemp())
        (project / "models").mkdir()
        (project / "models" / "m.sql").write_text("MODEL (name db.m, kind FULL); SELECT 1 AS a")
        ctx = Context(paths=[project], config=config)  # the previous ctx becomes cyclic garbage
        print(i, "loaded", flush=True)
    print("done")

    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):

    Variant Result
    As above hung 3/3
    MAX_FORK_WORKERS=2 hung 3/3
    ctx.close() after each load hung 3/3 (as #6201 says, close() leaves the engine adapter open)
    MAX_FORK_WORKERS=1 0/3
    gc.collect() before each Context(...) 0/3
    Same DuckDB file for every Context 0/3 (file-backed adapters are cached in the class-level _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 Context whose __init__ raised (e.g. a ConfigError) 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:

    import duckdb, os
    conn = duckdb.connect()
    if os.fork() == 0:
        del conn      # hangs on macOS
        os._exit(0)

    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() in create_process_pool_executor, before returning the ProcessPoolExecutor, in a local copy of sqlmesh. Results (hung/total):

    Variant Unpatched Patched
    Repro above 3/3 0/3
    A user-owned DuckDB connection in a cycle, dropped before each load 3/3 0/3
    Failed or discarded Context, then 2000 models 3/3 0/3

    Notes on the fix:

    • Placement. It covers all three pool call sites (loader.py:808, model/schema.py:83, snapshot/cache.py:62).
    • No race. With fork, Python 3.12's ProcessPoolExecutor forks all workers together inside the first submit(), and every call site submits immediately.
    • Cost. About 1% of load time: 24-52 ms at 200 models, 118-143 ms at 2000 models, once per pool.
    • A zero-parent-cost alternative also worked (0/3). Wrap the pool initializer so the child calls gc.freeze() first, so workers never collect inherited objects. A small window remains between the fork and the initializer.
    • The issue's other proposals. Closing the engine adapters in Context.close() would make the user-side workaround work. Moving to forkserver/spawn remains the real fix.

    A possible regression test, in tests/test_forking.py (already fork_isolated):

    • patch MAX_FORK_WORKERS=2;
    • create duckdb.connect() inside a reference cycle and del it without collecting;
    • load 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.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions