Repository navigation
ci(python-unit): run the unit suite in parallel with pytest-xdist - #44178
Conversation
The serial unit-test step had grown to ~27-28 minutes against the job's 30-minute timeout, so the trailing coverage/upload steps were being killed on ordinary runner variance even though every test passed: on 2026-09-11 five ready PRs went red this way in one day, with `Python unit tests` SUCCESS at 27m43s-28m04s and the kill landing during the 100%-coverage gate or the codecov upload. The suite ran single-process with coverage instrumentation on; pytest-xdist was not installed. Run it with `-n auto --dist loadfile`. `loadfile` keeps every test in a file on one worker, preserving module-scoped fixture state; pytest-cov combines the per-worker data into the single `.coverage` the later gates and the codecov upload read. Locally, 15,126 tests pass in 3m38s at 8 workers with coverage on (vs ~27 min serial); CI runners are 4-core. Two latent suite problems that parallelism exposes, both fixed with a fail-without/pass-with control: - tests/unit_tests/commands/report/base_test.py parametrized over Python sets, so each worker collected the same ids in a different per-process hash order and xdist aborted with "Different tests were collected". Diffing full collections under two PYTHONHASHSEED values showed it was the only such file out of 15,132 tests. Sets -> tuples. - test_get_sql_results_oauth2 runs under freeze_time and happened to be the first lazy importer of the engine-spec modules on its worker; clickhouse_connect reads the local timezone via dateutil at import time, which raises under a frozen clock. Serially an earlier test had always paid that import outside freeze_time, hiding the dependency. Fifteen unit-test files use freeze_time, so on xdist this is a flake that moves with worker assignment. A session-scoped autouse fixture now pre-loads the engine specs once per worker before any test can freeze the clock. Lockfile delta is pytest-xdist==3.8.0 plus its one dependency execnet. The two short 100%-coverage gates stay serial (tiny subtrees; xdist startup would cost more than it saves). timeout-minutes is unchanged: with the main step at ~8-9 minutes it now has ~3x headroom, which is the point. Co-Authored-By: Claude Code <[email protected]> Claude-Session: https://claude.ai/code/session_01EA4MGEkUcDpyLReqjQBhPy
Code Review Agent Run #cd26c9Actionable Suggestions - 0Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #44178 +/- ##
===========================================
+ Coverage 66.18% 80.16% +13.98%
===========================================
Files 2925 2925
Lines 172563 172563
Branches 40058 40058
===========================================
+ Hits 114212 138337 +24125
+ Misses 55970 31629 -24341
- Partials 2381 2597 +216
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…extVar Addresses the first CI run and a three-lens cross-model review. CI: the parallel step ran in 14m07s on the 4-core runners with one failure, tests/unit_tests/mcp_service/test_middleware_logging.py (`assert 1 == 42`). That is a leaked ContextVar, not xdist: sync tests that call `_setup_user_context()` (test_gauge_chart's resource path resolves a real user, id 1; six test_auth_user_resolution tests leave mocks) set `_mcp_user_id_var` in the thread's base context and never clear it, and pytest-asyncio copies that context into every later async test's task. `on_call_tool`'s `finally` then overrides the patched user id with the leaked one. It passed serially only because test_mcp_e2e_smoke sorts between leaker and victim and exercises the real middleware, whose `finally` resets the var; `loadfile` put that file on another worker. A per-test reset fixture in tests/unit_tests/mcp_service/conftest.py scopes the var to each test. Control: gauge -> middleware_logging in one process reproduces the exact failure without the fixture and passes with it. Review (unanimous across lenses): the session-wide `load_engine_specs()` preload was the wrong seam -- full discovery, including third-party entry points, in every worker and both serial coverage gates, and importing Superset's ClickHouse spec before any app exists caches `product_name="dev"` for the session. Narrowed to pre-importing only `clickhouse_connect`, the third-party module that actually reads the clock at import; engine-spec discovery itself stays lazy, so tests that exercise it still see a cold state. Seven unit-test files combine freeze_time with engine-spec resolution, so a narrow autouse preload beats per-test opt-in. A direct pin of the preload's contract is added. Also from review: docstring opening line and deferred-import justification per the constitution; explicit annotations on the tuple constants; `--durations=0` so the pre-existing `--durations-min` actually emits a report (it only filters an enabled one) -- which immediately shows the critical path under loadfile: one 68s test and ~15s of module-scoped app setup per file; and a note on `--maxfail` semantics. Local full run, 8 workers, coverage on: 15,128 passed in 3m36s. Co-Authored-By: Claude Code <[email protected]> Claude-Session: https://claude.ai/code/session_01EA4MGEkUcDpyLReqjQBhPy
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
…fic spec, explain the preload seam - tests/unit_tests/mcp_service/conftest.py: annotate the ContextVar token local (`Token[int | None]`) per the explicit-typing rule. - tests/unit_tests/test_clock_reading_driver_preload.py: the frozen-clock pin now asserts the specific `ClickHouseConnectEngineSpec` resolves, not merely a non-None result (get_engine_spec falls back to BaseEngineSpec, so `is not None` could pass vacuously). Docstrings on both tests; the deferred package import carries its justification (it must run after the session preload, which is what the test exercises). - tests/unit_tests/conftest.py: the preload's comment says why it is a session fixture rather than a guarded module-top import (a module-top import ties the optional driver to collection on every invocation; the fixture runs once per worker after plugin loading and before any test can enter freeze_time). Changes authored by a Codex (gpt-6-astra) fix-worker pass against the committer re-review; verified locally (194 tests, ruff, pre-commit mypy). Co-Authored-By: Claude Code <[email protected]> Claude-Session: https://claude.ai/code/session_01EA4MGEkUcDpyLReqjQBhPy
rusackas
left a comment
There was a problem hiding this comment.
LGTM. This is exactly the fix for the timeout pattern I'd noticed independently across several other PRs today. Went through each claim rather than taking the writeup at face value: reproduced the clickhouse_connect/freeze_time AttributeError myself, traced the leaked _mcp_user_id_var through auth.py/middleware.py to confirm the reset really only happens in on_call_tool's finally, checked the set→tuple parametrize change is safe (no overlap between the two schedule collections, so concatenation matches the old union), and confirmed pytest-xdist==3.8.0's actual requirements against the pinned pytest/execnet versions. The two 100%-coverage gates correctly stay serial.
CI's still running as I approve this, worth confirming unit-tests (current) actually lands near the claimed ~14 min before merging, but nothing's failed.
Code Review Agent Run #292ea9Actionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |

SUMMARY
The
unit-tests (current)job inPython-Unithas been getting killed at its 30-minutetimeout-minuteswall even though every test passes. The serial suite has grown to ~27–28 minutes, so the trailing steps (the 100%-coverage gates and the codecov upload) no longer fit on an ordinary slow-runner day:Python unit testsstepSame tree all three times; the only variable was ~1.3 min of runner speed. Master's own runs take 25–29 min, so the whole repo sits at 85–97% of the budget. On 2026-09-11 alone this killed five otherwise-green PR runs. The step ran
pytestsingle-process with coverage instrumentation on, andpytest-xdistwasn't installed.This PR runs the step with
pytest -n auto --dist loadfile:--dist loadfilekeeps every test in a file on one worker, so module-scoped fixture state is preserved.pytest-covcombines the per-worker data into the single.coveragethat the later 100%-coverage gates and the codecov upload already read — verified: one combined, fully populated data file, no leftover fragments.timeout-minutesis unchanged on purpose: the first CI run measured the parallel step at 14m07s on the 4-core runners — ~2× headroom under the wall instead of 36 seconds. (--durations=0is added so the pre-existing--durations-minactually emits a report; it immediately shows the critical path underloadfile: one 68 s test and ~15 s of module-scoped app setup per file — follow-up material.)pytest-xdist==3.8.0plus its one dependencyexecnet==2.1.2(regenerated withscripts/uv-pip-compile.sh).Parallelism exposed two latent problems in the suite itself. Both are fixed here, each with a fail-without / pass-with control:
Non-deterministic collection order.
tests/unit_tests/commands/report/base_test.pyparametrized over Pythonsets, so every worker collected the same ids in a different per-process hash order and xdist aborted with "Different tests were collected between gw4 and gw2". Diffing full collections under twoPYTHONHASHSEEDvalues showed it was the only such file out of 15,132 tests. Sets → tuples, with a comment so it doesn't get tidied back.A hidden import-order dependency (a flake class, not a one-off).
test_get_sql_results_oauth2runs under@freeze_timeand happened to be the first lazy importer of the engine-spec modules on its worker.clickhouse_connectreads the local timezone viadateutilat import time, which raisesAttributeErrorunder a frozen clock; Superset'sclickhouse.pyguard only catchesImportError. Serially, some earlier test had always paid that import outsidefreeze_time, hiding the dependency. Fifteen unit-test files usefreeze_time, so on xdist whichever is first on its worker fails — a flake that moves with worker assignment. A session-scoped autouse fixture intests/unit_tests/conftest.pypre-imports onlyclickhouse_connect(the third-party module that reads the clock) once per worker, before any test can freeze the clock — deliberately not Superset's own spec modules (importing the ClickHouse spec pre-app would cacheproduct_name="dev"for the session) and not fullload_engine_specs()discovery (which would run every third-party entry point in every worker). Engine-spec discovery stays lazy. A direct pin of the guarantee is intests/unit_tests/test_clock_reading_driver_preload.py.A leaked
ContextVar(found by the first CI run).tests/unit_tests/mcp_service/test_middleware_logging.pyfailed on CI withassert 1 == 42: sync tests that call_setup_user_context()(chart/test_gauge_chart.pyresolves a real user through the resource path; sixtest_auth_user_resolution.pytests leave mocks) set_mcp_user_id_varin the thread's base context and never clear it, and pytest-asyncio copies that context into every later async test's task — 2,735 mcp_service tests ran with a polluted context.on_call_tool'sfinallythen overrides the patched user id with the leaked one. Serially it passed only becausetest_mcp_e2e_smoke.pysorts between leaker and victim and exercises the real middleware, whosefinallyresets the var;loadfileput that file on another worker. A per-test reset fixture intests/unit_tests/mcp_service/conftest.pyscopes the var to each test. Control: gauge → middleware_logging in one process reproduces the exact failure without the fixture, passes with it.Local result (8 workers, coverage on,
TZ=UTC): 15,128 passed, 5 skipped, 2 xfailed, 0 failed in 3m36s — versus ~27 min serial.BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
N/A (CI configuration).
TESTING INSTRUCTIONS
Python-Unitworkflow on this PR is the primary test —unit-tests (current)should finish well inside the timeout with all lanes green and coverage uploaded.coverage reportshows a populated combined file.pytest --collect-only -q tests/unit_testsunderPYTHONHASHSEED=1and=2produces identical output.conftest.pychange and runpytest tests/unit_tests/sql_lab_test.py::test_get_sql_results_oauth2in a fresh process — it fails withAttributeError: 'NoneType' object has no attribute 'replace'fromdateutil/tz; restore the change and it passes.ADDITIONAL INFORMATION
🤖 Generated with Claude Code
https://claude.ai/code/session_01EA4MGEkUcDpyLReqjQBhPy