Model loading can fork a multi-threaded process and do illegal things causing an intermittent segfault in just the right conditions
Mantenedores costumam responder em até 4 dias
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 5/5
- Tempo estimado
- Mais de uma semana
- Facilidade para iniciantes
- 45/100
Direção de pesquisa
Start with create_process_pool_executor in sqlmesh/utils/process.py, then trace its uses in sqlmesh/core/loader.py and sqlmesh/core/model/cache.py. Read Context.close() in sqlmesh/core/context.py and check how it handles the engine adapter and cached adapters. Reproduce the reported worker crash with the SQLMesh templater tests and DuckDB setup; done means closing contexts releases their connections and model loading no longer triggers the fork-related crash.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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:
https://github.com/SQLMesh/sqlmesh/blob/7975a8d5841fe8f31217e27752e5cbb892f16ffc/sqlmesh/utils/process.py#L69
It is used for model loading and the optimized query cache:
https://github.com/SQLMesh/sqlmesh/blob/7975a8d5841fe8f31217e27752e5cbb892f16ffc/sqlmesh/core/loader.py#L778
https://github.com/SQLMesh/sqlmesh/blob/7975a8d5841fe8f31217e27752e5cbb892f16ffc/sqlmesh/core/model/cache.py#L190
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():
https://github.com/SQLMesh/sqlmesh/blob/7975a8d5841fe8f31217e27752e5cbb892f16ffc/sqlmesh/core/context.py#L2751
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.
- Linguagem predominante
- Python
- Estrelas
- 3.3k
- Forks
- 471
- Merge médio
- 6d 7h
- PRs com merge (30d)
- 35
Preparar o ambiente
Inicia o contêiner de desenvolvimento do projeto no navegador, com a sua própria conta do GitHub.
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de SQLMesh/sqlmesh
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 86/100
Mantenedores costumam responder em até 4 dias
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
Mantenedores costumam responder em até 4 dias
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 67/100
SQLMesh/sqlmesh#6008 · 1 comentário ·
Mantenedores costumam responder em até 4 dias
-
VSCode Extension: SQLMesh LSP crashes on startup: ImportError: cannot import name 'WorkspaceDiagnosticRefreshRequest' with lsprotocol 2025.xTalvez já em andamento @boomesh11 assumiu há 15 dias. AbertaBug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 66/100
Mantenedores costumam responder em até 4 dias
-
Improvement
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 85/100
SQLMesh/sqlmesh#5696 · 6 comentários ·
Mantenedores costumam responder em até 4 dias
Todas as issues de SQLMesh/sqlmesh
Issues semelhantes
-
[BUG][Low–Medium] founder_numbers.py silently reads a SAFE discount or pool target given as a fraction (0.2) as 0.2%Talvez já em andamento @sumitkhond111-del assumiu hoje. Abertabug
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 72/100
bmad-code-org/BMAD-METHOD#3358 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 86/100
open-mmlab/mmcv#3352 ·
-
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 68/100
OpenGithubs/weekly#263 ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
Mantenedores costumam responder em até 1 dia
-
comp/cli P3 type/feature
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 76/100
NousResearch/hermes-agent#162784 ·
Mantenedores costumam responder em até 1 dia