python runtime_error ai_generated true

worker 'gw3' 在运行 'tests/test_db.py::test_insert' 时崩溃 正在替换崩溃的 worker gw3 ... INTERNALERROR> psycopg2.OperationalError: 连接已关闭

worker 'gw3' crashed while running 'tests/test_db.py::test_insert' replacing crashed worker gw3 ... INTERNALERROR> psycopg2.OperationalError: connection already closed

ID: python/pytest-xdist-worker-crash-fixture-scope

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-08-30首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

会话级 fixture 持有跨 xdist worker 共享的数据库连接,但每个 worker 在独立进程运行,连接不是 fork 安全的。

English

A session-scoped fixture holds a database connection that is shared across xdist workers, but each worker runs in a separate process and the connection is not fork-safe.

generic

解决方案

  1. 90% 成功率
    import pytest
    
    @pytest.fixture(scope='function')
    def db_conn():
        conn = psycopg2.connect(dsn)
        yield conn
        conn.close()
    
    # or use worker id: os.environ['PYTEST_XDIST_WORKER']
  2. 85% 成功率
    pytest -n 4 --dist loadscope
    # conftest.py
    import os
    worker = os.environ.get('PYTEST_XDIST_WORKER', 'master')
    DB_NAME = f'test_{worker}'

无效尝试

常见但无效的做法:

  1. 85% 失败

    More workers means more concurrent connections to a non-fork-safe fixture; crash rate increases.

  2. 65% 失败

    Retries mask the fork-safety issue and cause flaky tests under load.