Skip to content

ci(python-unit): run the unit suite in parallel with pytest-xdist - #44178

Merged
hainenber merged 3 commits into
apache:masterfrom
mikebridge:ci-unit-tests-xdist
Sep 12, 2026
Merged

hainenber merged 3 commits into
apache:masterfrom
mikebridge:ci-unit-tests-xdist

Conversation

@mikebridge

@mikebridge mikebridge commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

SUMMARY

The unit-tests (current) job in Python-Unit has been getting killed at its 30-minute timeout-minutes wall 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:

run Python unit tests step then total
passing 26m45s ✅ coverage 1m27s + upload 0m20s 29m24s — 36 s to spare
killed 28m04s ✅ killed during the coverage gate 30m21s
killed 27m43s ✅ coverage ✅, killed during codecov upload 30m11s

Same 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 pytest single-process with coverage instrumentation on, and pytest-xdist wasn't installed.

This PR runs the step with pytest -n auto --dist loadfile:

  • --dist loadfile keeps every test in a file on one worker, so module-scoped fixture state is preserved.
  • pytest-cov combines the per-worker data into the single .coverage that the later 100%-coverage gates and the codecov upload already read — verified: one combined, fully populated data file, no leftover fragments.
  • The two short 100%-coverage gates stay serial (tiny subtrees; xdist startup would cost more than it saves). timeout-minutes is 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=0 is added so the pre-existing --durations-min actually emits a report; it immediately shows the critical path under loadfile: one 68 s test and ~15 s of module-scoped app setup per file — follow-up material.)
  • Lockfile delta is exactly pytest-xdist==3.8.0 plus its one dependency execnet==2.1.2 (regenerated with scripts/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:

  1. Non-deterministic collection order. tests/unit_tests/commands/report/base_test.py parametrized over Python sets, 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 two PYTHONHASHSEED values showed it was the only such file out of 15,132 tests. Sets → tuples, with a comment so it doesn't get tidied back.

  2. A hidden import-order dependency (a flake class, not a one-off). 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 AttributeError under a frozen clock; Superset's clickhouse.py guard only catches ImportError. Serially, some earlier test had always paid that import outside freeze_time, hiding the dependency. Fifteen unit-test files use freeze_time, so on xdist whichever is first on its worker fails — a flake that moves with worker assignment. A session-scoped autouse fixture in tests/unit_tests/conftest.py pre-imports only clickhouse_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 cache product_name="dev" for the session) and not full load_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 in tests/unit_tests/test_clock_reading_driver_preload.py.

  3. A leaked ContextVar (found by the first CI run). tests/unit_tests/mcp_service/test_middleware_logging.py failed on CI with assert 1 == 42: sync tests that call _setup_user_context() (chart/test_gauge_chart.py resolves a real user through the resource path; six test_auth_user_resolution.py 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 — 2,735 mcp_service tests ran with a polluted context. on_call_tool's finally then overrides the patched user id with the leaked one. Serially it passed only because test_mcp_e2e_smoke.py 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, 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

  1. The Python-Unit workflow on this PR is the primary test — unit-tests (current) should finish well inside the timeout with all lanes green and coverage uploaded.
  2. Locally, with the dev requirements installed:
    SUPERSET_TESTENV=true SUPERSET_SECRET_KEY=not-a-secret \
    pytest -n auto --dist loadfile --cov=superset --cov-report= ./tests/common ./tests/unit_tests --cache-clear
    then coverage report shows a populated combined file.
  3. Collection determinism: pytest --collect-only -q tests/unit_tests under PYTHONHASHSEED=1 and =2 produces identical output.
  4. The freeze_time control: stash the conftest.py change and run pytest tests/unit_tests/sql_lab_test.py::test_get_sql_results_oauth2 in a fresh process — it fails with AttributeError: 'NoneType' object has no attribute 'replace' from dateutil/tz; restore the change and it passes.

ADDITIONAL INFORMATION

  • Has associated issue:
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

🤖 Generated with Claude Code

https://claude.ai/code/session_01EA4MGEkUcDpyLReqjQBhPy

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
@bito-code-review

bito-code-review Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #cd26c9

Actionable Suggestions - 0
Review Details
  • Files reviewed - 4 · Commit Range: 6d741a4..6d741a4
    • pyproject.toml
    • requirements/development.txt
    • tests/unit_tests/commands/report/base_test.py
    • tests/unit_tests/conftest.py
  • Files skipped - 1
    • .github/workflows/superset-python-unittest.yml - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@github-actions github-actions Bot added github_actions Pull requests that update GitHub Actions code dependencies:python labels Sep 11, 2026
@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.16%. Comparing base (36361d9) to head (414a95a).
⚠️ Report is 4 commits behind head on master.

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     
Flag Coverage Δ
hive 37.34% <ø> (ø)
mysql 56.86% <ø> (?)
postgres 56.89% <ø> (?)
presto 39.22% <ø> (ø)
python 84.55% <ø> (+27.83%) ⬆️
sqlite 56.59% <ø> (ø)
unit 75.87% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…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
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Sep 11, 2026
@netlify

netlify Bot commented Sep 11, 2026

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit e365dc6
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6aa47549692ceb000882553b
😎 Deploy Preview https://deploy-preview-44178--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

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 rusackas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@bito-code-review

bito-code-review Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #292ea9

Actionable Suggestions - 0
Additional Suggestions - 1
  • tests/unit_tests/commands/report/base_test.py - 1
    • Redundant constant annotations · Line 40-40
      Per BITO.md rule 13982, explicit annotations on module-level constants are redundant when mypy infers correctly. `REPORT_TYPES`, `TEST_SCHEDULES_EVERY_MINUTE`, `TEST_SCHEDULES_SINGLE_MINUTES`, and `TEST_SCHEDULES` all have inferable tuple types, so the added `tuple[...]` hints add verbosity without type-safety gain.
Review Details
  • Files reviewed - 4 · Commit Range: 6d741a4..414a95a
    • tests/unit_tests/commands/report/base_test.py
    • tests/unit_tests/conftest.py
    • tests/unit_tests/mcp_service/conftest.py
    • tests/unit_tests/test_clock_reading_driver_preload.py
  • Files skipped - 1
    • .github/workflows/superset-python-unittest.yml - Reason: Filter setting
  • Tools
    • MyPy (Static Code Analysis) - ✔︎ Successful
    • Astral Ruff (Static Code Analysis) - ✔︎ Successful
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers an incremental AI Review.

  • /review full - Manually triggers a full AI Review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

@hainenber

Copy link
Copy Markdown
Contributor

Can confirm it landed at ~14m :D

image

@hainenber
hainenber merged commit 3e7bdec into apache:master Sep 12, 2026
98 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies:python github_actions Pull requests that update GitHub Actions code size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants