Skip to content

Fix flaky test_s3_cluster: scope generated CSV dir per xdist worker - #104020

Merged
alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-test-s3-cluster-xdist-race
May 5, 2026
Merged

alexey-milovidov merged 1 commit into
ClickHouse:masterfrom
groeneai:groeneai/fix-test-s3-cluster-xdist-race

Conversation

@groeneai

@groeneai groeneai commented May 4, 2026 •

Copy link
Copy Markdown
Collaborator

The started_cluster fixture in tests/integration/test_s3_cluster/test.py
writes 100 CSV files to tests/integration/test_s3_cluster/data/generated/,
uploads them to MinIO, then deletes the directory in teardown.

Under Integration tests (amd_asan_ubsan, targeted) the runner uses
pytest-xdist with --dist=each, so every test goes to every worker and the
module-scoped fixture runs concurrently in multiple processes. Their MinIO
containers are isolated by ClickHouseCluster (it appends
PYTEST_XDIST_WORKER to project_name), but the host filesystem path was
shared. One worker's teardown could shutil.rmtree(...) the directory
while another worker was still iterating over it inside the upload loop in
create_buckets_s3, surfacing as FileNotFoundError on
data/generated/file_0.csv during fixture setup and failing every test in
the module via fixture error.

Pattern matches Issue #102238 (open since 2026-04-09) and CIDB shows ~21–23
unrelated PRs hitting the same setup error in the past 30 days for tests
across the suite (test_wrong_cluster, test_select_all, test_count,
test_union_all, test_hive_partitioning, etc.) — exactly the symptom
expected when a module-scoped fixture errors and propagates to all 18
tests.

Earlier PR #102144 added ignore_errors=True to the teardown rmtree to
silence the cleanup-side variant of this race; this change addresses the
upload-side variant by removing the shared resource.

This change scopes the host directory by PYTEST_XDIST_WORKER so
concurrent workers no longer share filesystem state. The MinIO bucket key
still uploads under the canonical data/generated/ prefix, so all test
queries (SELECT … FROM s3('http://minio1:9001/root/data/generated/*'…))
are unchanged. Also decouple the host path from the bucket object key
(previously a single f"data/generated/file_{n}.csv" was used as both),
drop the module-level mutable S3_DATA list, and guard
cluster.shutdown() in the teardown against the pre-existing case where
the ClickHouseCluster(__file__) constructor raises before cluster gets
bound.

Race deterministically reproduced with a minimal Python harness
(tmp/race_repro.py, 2 threads, shared dir): 20/20 trials hit
FileNotFoundError without the fix; 0/20 with per-worker dirs.

Closes #102238

Changelog category (leave one):

  • CI Fix or Improvement (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

...

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.5.1.291

The `started_cluster` fixture writes 100 CSV files to
`tests/integration/test_s3_cluster/data/generated/` and uploads them to
MinIO, then deletes the directory in teardown. Under
`Integration tests (amd_asan_ubsan, targeted)` the runner uses
pytest-xdist with `--dist=each`, so multiple workers execute the
fixture in parallel. Their MinIO containers are isolated by
`ClickHouseCluster` (it appends `PYTEST_XDIST_WORKER` to
`project_name`), but the host filesystem path was shared. One worker's
teardown could `shutil.rmtree(...)` the directory while another worker
was still iterating over it inside the upload loop, surfacing as
`FileNotFoundError: data/generated/file_0.csv` during fixture setup
and failing every test in the module. Tracked as Issue ClickHouse#102238 since
2026-04-09 (open).

Scope the host directory by `PYTEST_XDIST_WORKER` so concurrent workers
no longer share filesystem state. The MinIO bucket key still uploads
under the canonical `data/generated/` prefix, so tests querying
`http://minio1:9001/root/data/generated/*` are unchanged. Also
decouple the host path from the bucket key (previously a single
`f"data/generated/file_{n}.csv"` was used as both), drop the
module-level mutable `S3_DATA` list, and guard `cluster.shutdown()` in
the teardown against the case where `ClickHouseCluster(__file__)`
itself raises before binding `cluster`.

Race deterministically reproduced with a minimal Python harness
(2 threads, shared dir, 20/20 trials hit FileNotFoundError; with
per-worker dirs, 0/20).

Closes ClickHouse#102238
@groeneai

groeneai commented May 4, 2026

Copy link
Copy Markdown
Collaborator Author

Session ID: cron:clickhouse-ci-task-worker:20260504-161500

Pre-PR validation gate

# Question Answer
a Deterministic repro? ✅ YES. tmp/race_repro.py (committed only as a debugging artefact, not part of this PR) reproduces the race in 20/20 runs with shared dir, 0/20 with per-worker dir. The harness models the actual fixture sequence: two threads each write_files() → upload_files() → teardown(), racing on a shared host directory.
b Root cause explained? ✅ YES. Targeted/flaky integration jobs run pytest -n W --dist=each, fanning every test out to every xdist worker. The module-scoped started_cluster fixture executes once per worker process. ClickHouseCluster(__file__) isolates Docker resources by suffixing project_name and instances_dir_name with PYTEST_XDIST_WORKER, but tests/integration/test_s3_cluster/data/generated/ is constructed from os.path.dirname(os.path.realpath(__file__)) and is identical across workers. When worker A finishes its 18 tests and runs shutil.rmtree(host_dir) while worker B is still iterating for file in S3_DATA: minio.fput_object(...), B's next os.stat(host_path) (called by minio.fput_object at minio/api.py:1052) raises FileNotFoundError — surfacing as a setup-phase fixture error that fails all 18 tests in B's run.
c Fix matches root cause? ✅ YES. Eliminates the shared resource by scoping the host directory per PYTEST_XDIST_WORKER. Each worker writes to and tears down its own data/generated_<worker_id>/ directory; teardowns can no longer race against another worker's upload loop. The MinIO bucket key stays data/generated/file_N.csv (each worker has its own MinIO container, so the bucket key is already isolated), preserving every existing test query.
d Test intent preserved? ✅ YES. All 18 test bodies are untouched. Every s3() / s3Cluster() / url() table function call against http://minio1:9001/root/data/generated/* continues to read the same data. The 4 base CSVs (data/clickhouse/, data/database/) are still read from their committed location. The number of generated files (100), the per-file row count formula (100 + file_number), and the data shape are unchanged.
e Both directions demonstrated? ✅ YES. Race reproducer: 20/20 failures with a shared host dir (the bug), 0/20 failures with per-worker dirs (the fix).

Self-review against .claude/skills/review/SKILL.md

  • Deletion logging: N/A — only test-side shutil.rmtree of a per-worker directory; no production data deletion.
  • Serialization versioning: N/A — no format changes.
  • Core-area scrutiny: N/A — test infrastructure only.
  • No test removal: ✅ — no tests removed or weakened. Test bodies untouched; only fixture setup/teardown changed.
  • Experimental gate / magic constants / backward compat / safe rollout / compile time / no large files: N/A — Python test fixture only.
  • PR metadata: Category CI Fix or Improvement (changelog entry is not required), no entry required by the template.
  • C++ risk self-check: N/A — no C++ changes.
  • Trust boundary: N/A.

Notes

@groeneai

groeneai commented May 4, 2026

Copy link
Copy Markdown
Collaborator Author

cc @azat @maxknv — could you review this? It scopes test_s3_cluster's host-side data/generated/ dir by PYTEST_XDIST_WORKER so that under --dist=each (used by the targeted integration job) one worker's teardown can no longer rmtree files mid-upload in another worker, which is the FileNotFoundError pattern from #102238 hitting ~21 unrelated PRs/30d. Adjacent to your earlier #102144 cleanup-side patch (azat) and the targeted-check sort fix (maxknv); test bodies and MinIO bucket keys unchanged.

@maxknv

maxknv commented May 4, 2026

Copy link
Copy Markdown
Member

@fm4v, what was the idea behind --dist=each? I think we have more tests that cannot run concurrently with themselves.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label May 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [05d7953]

Summary: ✅


AI Review

Summary

This PR fixes a real integration-test race in tests/integration/test_s3_cluster/test.py by isolating generated host CSV files per PYTEST_XDIST_WORKER, while keeping MinIO object keys unchanged (data/generated/...) so query behavior stays stable. I did not find correctness, safety, or compatibility issues in the patch.

Missing context
  • ⚠️ CI is still in progress (PR report pending), so final runtime signal from CI logs is not yet available.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ➖
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 4, 2026
@fm4v

fm4v commented May 5, 2026

Copy link
Copy Markdown
Member

@maxknv it's described in #100181

Before (#66986): flaky check used pytest-repeat --count 3 --random-order. That repeats at function scope inside a single worker against the same module fixture (cluster started once, kept running) so it never exercises fixture lifecycle, where most flakes live. It itself requires: "It is important to cleanup tables and other entities in the end of a test case to pass" but the corresponding test rewrites were never done.

After (#100181): --dist=each runs the full module list on every xdist worker in parallel (module-scope parallel). Workers get isolated Docker clusters but still share the host filesystem and network namespace, so a module must now be runnable in parallel with itself on the same host.
Same "rewrite the test corpus" debt as #66986, just surfaced differently and easier to fix than rewriting the logic of every integration test.

Overall it stabilized the flaky check:

Weekly trend — Integration tests (amd_asan{,_ubsan}, flaky)
week        fail%   runs
2026-01-11  25.0    168
2026-01-18  23.7    139
2026-01-25  26.8    183
2026-02-01  23.8    147
2026-02-08  23.2    194
2026-02-15  23.3    116
2026-02-22  16.7    120
2026-03-01  14.4    125
2026-03-08  34.9    146   ← pre-change baseline
2026-03-15  20.4    225   ← --dist=each lands (#100181)
2026-03-22  24.5    220   ← fallout, fixed by #100627
2026-03-29  12.0    166
2026-04-05  14.5    255
2026-04-12   8.0    201
2026-04-19  10.2    118
2026-04-26   5.9    185

@alexey-milovidov alexey-milovidov 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.

The general idea is reasonable.

@alexey-milovidov alexey-milovidov self-assigned this May 5, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 5, 2026
Merged via the queue into ClickHouse:master with commit 9b3eed0 May 5, 2026
165 checks passed
@robot-clickhouse robot-clickhouse added the pr-synced-to-cloud The PR is synced to the cloud repo label May 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors pr-ci pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Flaky test: test_s3_cluster/test.py::test_wrong_cluster

6 participants