Skip to content

ci: run integration flaky/targeted check in module scope with --dist=each - #100181

Merged
fm4v merged 29 commits into
masterfrom
nik/integration-flaky-check-module-scope
Mar 24, 2026
Merged

fm4v merged 29 commits into
masterfrom
nik/integration-flaky-check-module-scope

Conversation

@fm4v

@fm4v fm4v commented Mar 20, 2026 •

Copy link
Copy Markdown
Member

Integration tests use `module`-scoped fixtures for cluster setup/teardown. The flaky check was using `pytest-repeat` with `--count 3 --random-order`, repeating each individual test function before moving to the next. This causes repetitions to be inconsistent with how tests run in normal CI (module scope).

This change replaces `pytest-repeat` for flaky/targeted checks with `--dist=each`: all test modules are sent to every xdist worker.

For this to work correctly, three bugs in `ClickHouseCluster` were fixed:

  1. `cluster.start()` re-entry after shutdown — when `--dist=each` causes tests from different modules to interleave on the same xdist worker, `scope="module"` fixtures are torn down and re-set-up multiple times within the same session. `cluster.shutdown()` does not remove `instances_dir`, and `ClickHouseCluster.init` only cleans it up at Python import time. On the second `cluster.start()`, `create_dir()` would fail with `FileExistsError`. Fixed by removing and recreating `instances_dir` at the top of `cluster.start()` when the cluster is not currently up.

  2. Premature filesystem mutation before `is_up` guard — the cleanup in `cluster.start()` must happen only when the cluster is down. Moving `shutil.rmtree` after the `if self.is_up: return` guard prevents destroying the live `instances_dir` (including the `.env` file) when `start()` is called on an already-running cluster (e.g. multiple module-scoped fixtures sharing the same cluster object).

  3. Stale `ipv6_address` on second `create_dir()` — `cluster.start()` sets `instance.ipv6_address` dynamically from the running container after startup. `cluster.shutdown()` reset `ip_address` to `None` but not `ipv6_address`. On the second `create_dir()` the stale address was inserted into the docker-compose.yml unquoted (`ipv6_address: 2001:3984:3989::5`), which Docker Compose v2 rejects with `ipv6_address must be a string`. Fixed by resetting `ipv6_address = None` in `shutdown()` and quoting the value in the template.

For sequential modules (those that require CPU isolation, e.g. `test_server_overload`): they cannot run in parallel, so they are executed in a loop at least 4 times, at most `workers` times, breaking early on the first failure.

Comments were added to several test files to trigger the flaky check CI job.

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.4.1.193

…cope

Integration tests use module-scoped fixtures (cluster setup/teardown).
In the flaky check, `pytest-repeat` was using the default `function` scope
(`--count N --random-order`), causing each test to be repeated individually
before the next one runs. This breaks module-scoped fixture semantics.

Add `--repeat-scope=module` so the entire module is repeated as a unit,
preserving module-scoped cluster fixtures.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8e081b0]

Summary: ✅


AI Review

Summary

This PR changes integration flaky/targeted execution to module-scope repetition and fixes ClickHouseCluster re-entry behavior (instances_dir cleanup ordering and stale ipv6_address reuse). The core functional direction looks right, but there are still comment/intent mismatches in integration_test_job.py that can mislead CI triage and maintenance.

Findings

⚠️ Majors

  • [ci/jobs/integration_test_job.py:840-841] The comment says "at least 3" and "at most workers", but code is sequential_repeat_cnt = max(4, workers). This mismatch makes intent unclear and can unexpectedly increase targeted/flaky runtime on larger hosts.
    Suggested fix: align comment and logic explicitly (either keep max(4, workers) and document it precisely, or adjust formula if "at most workers" was intended).

💡 Nits

  • [ci/jobs/integration_test_job.py:617] Comment says --count is not used for flaky/targeted checks, but repeat_option still applies when args.count is provided.
    Suggested fix: reword to "--count is not used by default".
  • [ci/jobs/integration_test_job.py:864] Branch condition is if not is_targeted_check, but comment starts with "In targeted checks...".
    Suggested fix: reword to "In non-targeted checks..." (and keep analogous text consistent in the sequential block).

ClickHouse Rules

Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ➖
No test removal ✅
Experimental gate ➖
No magic constants ⚠️ Repeat policy in code/comments is inconsistent; intended threshold behavior should be explicit and unambiguous.
Backward compatibility ➖
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ✅
Compilation time ✅

Final Verdict

  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Align stale/misaligned comments with actual behavior at lines around 617, 840, and 864 in ci/jobs/integration_test_job.py.

@clickhouse-gh clickhouse-gh Bot added the pr-ci label Mar 20, 2026
fm4v and others added 3 commits March 20, 2026 11:52
In the flaky check, the test is run multiple times within the same
cluster session. After `DROP TABLE`, the `rocksdb::DB` handle is not
released synchronously (storage object may still be alive due to
shared_ptr references), so the next run fails with "lock held by
current process" when attempting `CREATE TABLE` on the same path.

Fix by restarting ClickHouse at the start of the test to flush all
stale handles, and removing any leftover directory from a prior run.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
The flaky check was using --count N --random-order inside pytest, which
repeats individual test functions within the same session, sharing the
module-scoped cluster fixture across repetitions. This causes state
leakage between runs (e.g. RocksDB lock held from previous repetition).

The module_repeat_cnt loop already reruns the entire pytest session
FLAKY_CHECK_MODULE_REPEAT_COUNT times. Each iteration starts a fresh
cluster, runs the test, and tears down - fully isolated. Remove --count
from the flaky check pytest command so repetitions happen at the session
level (module scope) rather than within the same session (function scope).

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Previously, --count N --random-order repeated tests N times within the
same pytest session and worker. All repetitions shared the same
module-scoped cluster fixture, causing state leakage between runs
(e.g. RocksDB lock held from previous repetition, table already exists).

ClickHouseCluster already supports xdist isolation: it appends
PYTEST_XDIST_WORKER to the Docker project name, so each worker gets
a completely independent cluster. Use this by switching to --dist=each
with N workers instead of --count N:

- flaky check: -n FLAKY_CHECK_TEST_REPEAT_COUNT --dist=each
- targeted check: -n 10 --dist=each

Each xdist worker runs all test modules independently in its own process
with its own Docker cluster. Repetitions are fully parallel and isolated.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Comment thread ci/jobs/integration_test_job.py Outdated
for attempt in range(module_repeat_cnt):
test_result_sequential = run_pytest_and_collect_results(
command=f"{' '.join(sequential_test_modules)} --report-log-exclude-logs-on-passed-tests --tb=short {repeat_option} -n 1 --dist=loadfile --session-timeout={session_timeout_sequential}",
command=f"{' '.join(sequential_test_modules)} --report-log-exclude-logs-on-passed-tests --tb=short {repeat_option} -n {parallel_workers} {parallel_dist} --session-timeout={session_timeout_sequential}",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

sequential_test_modules are explicitly categorized as sequential in get_optimal_test_batch, but this change runs them with -n {parallel_workers} --dist=each for flaky/targeted checks.

With --dist=each, each worker executes the full sequential module list, so these suites run concurrently across workers and can interfere with each other (the exact class of conflicts this sequential bucket is meant to avoid).

Can we keep the sequential pass serialized (-n 1 --dist=loadfile) and do repetition/isolation at the module/session loop level instead?

fm4v and others added 7 commits March 20, 2026 13:39
With --dist=each -n N, a single pytest session already provides N fully
isolated parallel runs (each xdist worker has its own Docker cluster via
PYTEST_XDIST_WORKER). The module_repeat_cnt loop that re-ran the session
multiple times sequentially is no longer needed.

Remove FLAKY_CHECK_MODULE_REPEAT_COUNT, module_repeat_cnt, and the
early-break-on-failure loop. Flaky check runs FLAKY_CHECK_TEST_REPEAT_COUNT
workers in one session; targeted check runs 10 workers in one session.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

copilot-cli post test; ignore



def test_undrop_drop_and_undrop_loop(started_cluster):
if random.random() < 0.5:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

test inline comment from copilot; will delete

print(f"Failed to clear dmesg before integration tests: {ex}")

if is_flaky_check or is_targeted_check:
# Each xdist worker runs all modules independently with its own isolated Docker cluster.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This change makes flaky-check repetition count depend on workers by using --dist=each and -n {workers}. That can silently reduce flaky coverage to a single run when workers == 1 (the computed default allows this), while the previous implementation guaranteed fixed repetition (FLAKY_CHECK_TEST_REPEAT_COUNT + FLAKY_CHECK_MODULE_REPEAT_COUNT).

Could we keep deterministic repetition for flaky checks (independent of machine sizing), e.g. by introducing an explicit repeat-count parameter for module-level reruns instead of tying it to worker count?

)

if is_flaky_check and not test_result_sequential.is_ok():
print(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For flaky checks, sequential_test_modules are no longer repeated at all: repeat_option is empty (unless --count is passed manually) and this sequential pass runs only once with -n 1 --dist=loadfile.

So flaky detection coverage now excludes the sequential bucket, even though those modules can also be flaky. Please apply module-level repetition to sequential_test_modules as well (or otherwise preserve equivalent repetition coverage from the previous logic).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One more nit here: the updated comment says tests are "running in parallel", but this block executes with -n 1 --dist=loadfile.

Could we reword it to avoid implying concurrency in this sequential pass (e.g. "many heavy tests in one session")?

# For flaky/targeted checks, --count is not used. Instead, --dist=each runs N workers
# each executing all modules independently with their own isolated Docker cluster
# (ClickHouseCluster appends PYTEST_XDIST_WORKER to project_name for isolation).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This also changes targeted behavior: previously it always used --count 10 --random-order, now repetition depends on workers via --dist=each.

Could we keep deterministic targeted repetition independent of machine size?

fm4v and others added 3 commits March 20, 2026 19:37
…geted check

Sequential test modules must not run concurrently on the same host as they
may modify host-level state (e.g. `test_dns_cache`, `test_server_overload`).
Restore `-n 1 --dist=loadfile` for sequential modules in all modes, including
flaky and targeted check. Only parallel modules use `--dist=each` there.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Sequential tests cannot use `--dist=each` (they require isolated,
sequential execution). Instead, run them in a loop: at least 3 times
for a meaningful flakiness signal, up to `workers` times (matching the
parallelism budget used for parallel modules).

Break early on the first failure, matching the behavior of the parallel
path.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
# Sequential tests cannot run in parallel, so we loop over them instead.
# Run at least 3 times to have meaningful flakiness signal, at most workers times.
sequential_repeat_cnt = max(4, workers)
else:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

sequential_repeat_cnt = max(4, workers) does not match the comment right above it (at least 3, at most workers).

With current code this is actually at least 4 and potentially unbounded by host size. If the intent is module-level parity with the parallel pass, please clarify the comment and consider an explicit constant/setting for minimum repeats (or max(3, workers) if 3 is intended).

fm4v and others added 4 commits March 21, 2026 09:37
Updated test file duration estimates from current CIDB data to improve
batch distribution balance. Changes from previous data:
- 155 entries (was 128): +27 newly discovered long-running tests
- Removed 7 stale entries that now run faster than the 100s threshold
  (e.g. test_throttling is always SKIPPED; test_ttl_move halved from
  1060s to 457s; test_ttl_replicated tripled from 256s to 772s)
- Many duration corrections of 30-200% that were skewing LPT placement

The updated data should reduce the worst-case batch spread, especially
for amd_binary (currently 43.9-65.2 min range, 21-min spread).
Based on 7-day CIDB median execution times on master, the current batch
counts produce jobs well above the 60-minute target:

  amd_asan_ubsan (db disk, old analyzer): 6 batches, max 82 min → 8 batches
  amd_tsan:                               6 batches, max 76 min → 7 batches
  amd_msan:                               6 batches, max 79 min → 8 batches
  amd_llvm_coverage:                      5 batches, max 80 min → 7 batches

  amd_binary (max 65 min) and arm_binary (max 64 min) are left unchanged
  as their total work fits in 5 and 4 batches respectively at ~60 min
  after the RAW_TEST_DURATIONS refresh also in this PR.

Target batch time = total_work / N_batches (assuming balanced distribution):
  amd_asan_ubsan: 462 min / 8 = ~58 min
  amd_tsan:       416 min / 7 = ~59 min
  amd_msan:       443 min / 8 = ~55 min
  amd_llvm_coverage: 385 min / 7 = ~55 min
…st=loadfile sessions

`--dist=each` sends all test items to every xdist worker within a single
pytest session. When multiple test modules are present (typical for the
targeted check which runs all recently-failed tests), the xdist scheduler
interleaves tests from different modules on each worker. This breaks
`scope="module"` fixture isolation: the module fixture is torn down and
re-set-up multiple times per worker session, but `ClickHouseCluster.__init__`
only removes the instance directory once at Python import time. The second
`cluster.start()` call tries to create a directory that still exists from the
first run, causing `FileExistsError` in `create_dir()` for every worker.

Fix: replace the single `--dist=each` run with a loop of `--dist=loadfile`
sessions (`max(3, workers)` iterations). Each iteration is a fresh pytest
subprocess, so modules are re-imported and `ClickHouseCluster.__init__` cleans
up instance directories. `--dist=loadfile` groups all tests from the same file
onto the same worker, guaranteeing that module-scoped fixtures run exactly once
per session — matching how tests run in normal (non-flaky-check) CI.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
repeat_option = f"--count 10 --random-order"
if args.count:
repeat_option = f"--count {args.count} --random-order"
# For flaky/targeted checks, --count is not used. Instead, --dist=each runs N workers

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This note is stale after the latest refactor: flaky/targeted checks now execute repeated pytest sessions with --dist=loadfile (see parallel_repeat_cnt), not --dist=each.

Could you update this comment to match current behavior? Keeping old rationale here makes CI triage harder.

fm4v and others added 2 commits March 21, 2026 17:42
…ted --dist=loadfile sessions"

This reverts commit 21f5aaf.
When pytest-xdist uses `--dist=each`, tests from different modules can
interleave on the same worker within a single session. This forces
`scope="module"` fixtures to tear down and re-set-up multiple times.
`cluster.shutdown()` stops Docker containers but does not remove
`instances_dir`, and `ClickHouseCluster.__init__` only removes it at
Python import time (once per process). So the second `cluster.start()`
call found `instances_dir` already populated and `create_dir()` failed
with `FileExistsError` when trying `os.makedirs(instance.path)`.

Fix: when `instances_dir` already exists at the top of `start()`,
remove and recreate it so every call to `start()` gets a clean slate,
regardless of how many fixture setup/teardown cycles have occurred.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@fm4v

fm4v commented Mar 22, 2026

Copy link
Copy Markdown
Member Author

CI rerun

# interleave on the same xdist worker). cluster.shutdown() does not remove
# instances_dir, and ClickHouseCluster.__init__ only removes it at import time,
# so without this cleanup create_dir() would fail with FileExistsError.
shutil.rmtree(self.instances_dir, ignore_errors=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

start now deletes self.instances_dir before checking self.is_up. If cluster.start is called while the cluster is already up, this can remove instance directories of running containers and make subsequent operations fail in hard-to-debug ways.

Can we move this cleanup under if not self.is_up (or return early on self.is_up before any filesystem mutation), so repeated start calls remain non-destructive?

fm4v and others added 3 commits March 22, 2026 23:04
The previous commit moved the is_up early-return after the shutil.rmtree,
so calling cluster.start() on an already-running cluster would delete the
live instances_dir (including the .env file) before returning. Any subsequent
cluster.shutdown() call would then fail with "Couldn't find env file" when
running docker compose commands.

This broke test modules that define multiple module-scoped fixtures all
calling cluster.start()/cluster.shutdown() on the same cluster object
(e.g. test_replication_credentials: same_credentials_cluster sets up the
cluster, then no_credentials_cluster calls start() again while is_up=True).

Fix: move the is_up early-return before any filesystem mutation, so the
rmtree+mkdir cleanup only runs when the cluster is actually down (is_up=False)
and it is safe to wipe the stale instance directory.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
…yml template

When cluster.start() is called a second time (after shutdown) within the same
pytest session — which happens with --dist=each when tests from different
modules interleave on the same xdist worker — create_dir() regenerates the
docker-compose.yml for each instance.

After the first cluster.start(), instance.ipv6_address is set to the
Docker-assigned address (e.g. "2001:3984:3989::5") at line 3934.
cluster.shutdown() reset ip_address to None but not ipv6_address. On
the second create_dir() call, ipv6_address was therefore non-None and
got written into the YAML as an unquoted value:

  ipv6_address: 2001:3984:3989::5

Docker Compose v2 rejects this with "ipv6_address must be a string",
failing the docker compose kill/up commands for every worker.

Fix:
1. Reset instance.ipv6_address = None in shutdown(), symmetrically with
   ip_address, so the next create_dir() omits the field and lets Docker
   assign a fresh address automatically.
2. Quote the value in the template as a safety net for cases where
   ipv6_address is explicitly configured (e.g. network partition tests):
   ipv6_address: "2001:3984:3989::5"  — valid in both old and new Compose.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@fm4v fm4v changed the title ci: run integration flaky check in module scope ci: run integration flaky/targeted check in module scope with --dist=each Mar 23, 2026
repeat_option = f"--count 10 --random-order"
if args.count:
repeat_option = f"--count {args.count} --random-order"
# For flaky/targeted checks, --count is not used. Instead, --dist=each runs N workers

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This note currently says --count is not used for flaky/targeted checks, but the code still applies repeat_option when args.count is provided.

Could you either enforce that --count cannot be combined with flaky/targeted mode (explicit assert), or reword this comment to --count is not used by default?

# (--count N is used). In this mode, a session-timeout is an expected risk
# rather than an infrastructure problem, so we do not treat such errors as job-level
# failures and avoid setting the error flag for targeted runs.
# In targeted checks we may overload the run with many heavy tests running

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The condition here is if not is_targeted_check, but the comment starts with "In targeted checks...".

This inversion is misleading during CI triage. Please reword this (and the analogous comment in the sequential block below) to "In non-targeted checks...".

@fm4v
fm4v enabled auto-merge March 24, 2026 09:17
@fm4v
fm4v disabled auto-merge March 24, 2026 09:17
@fm4v
fm4v enabled auto-merge March 24, 2026 09:40
@fm4v
fm4v added this pull request to the merge queue Mar 24, 2026
Merged via the queue into master with commit a6973a5 Mar 24, 2026
148 checks passed
@fm4v
fm4v deleted the nik/integration-flaky-check-module-scope branch March 24, 2026 11:37
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Mar 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants