Skip to content

Add ruff linter to catch undefined names and other Python bugs - #105171

Merged
alexey-milovidov merged 22 commits into
masterfrom
add-ruff-linter
Jun 18, 2026
Merged

alexey-milovidov merged 22 commits into
masterfrom
add-ruff-linter

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented May 17, 2026 •

Copy link
Copy Markdown
Member

Adds ruff to the style-test job to catch a class of Python bugs that PR #105159 ran into: an undefined variable inside an assert False, f"..." diagnostic message that only triggered NameError on the failure path, masking the real error. CIDB showed 81 such failures over the previous 90 days. A linter would have caught the original mistake before merge.

Configuration lives in [tool.ruff] in pyproject.toml. The initial rule set is deliberately narrow - only rules where every hit was a real bug or unreachable reference:

Stylistic noise rules (F401, F541, F841, F403, F405) are intentionally off so the initial signal is bug-class only. They can be turned on in follow-ups.

Real bugs found and fixed by the initial run

F821 (same pattern as PR #105159):

  • ci/jobs/scripts/check_ci.py - commit_status_data referenced in an exception branch but never assigned
  • tests/fuzz/runner.py - PIPE referenced without from subprocess import PIPE
  • test_backup_restore_on_cluster_with_checksum_data_file_name/test.py - os.path.join with os not imported
  • test_database_iceberg/test.py - BASE_URL_DOCKER typo for BASE_URL
  • test_keeper_remove_acl/test.py - node_zk referenced in a finally cleanup; the bare except silently swallowed the NameError on every run, so the cleanup never happened
  • test_storage_delta_disks/test.py - missing from helpers.config_cluster import minio_secret_key

F811 silently-shadowed tests (later def overwrites earlier, dropping the first test):

  • test_disk_types::test_different_types
  • test_storage_s3::test_empty_file
  • test_executable_table_function - one of the two same-named functions renamed to test_executable_storage_*
  • test_storage_delta::test_partition_columns_3 - second def renamed to test_partition_columns_jumbled
  • test_merge_tree_s3_failover endpoint had two def fail_request; the throttle one was unreachable, renamed to throttle_request

F601 duplicate dict-literal keys with divergent values in test_storage_s3_queue/test_5.py - same setting specified twice with different values; cleaned up to make the intended value explicit.

F522 / F523 .format drift - templates updated without dropping the corresponding args (test_jbod_ha, test_manipulate_statistics, test_mysql_protocol, test_storage_kafka, helpers/dictionary).

F632 assert error is "" -> == in test_allow_feature_tier.

F402 loop variable named field shadowing from dataclasses import field in praktika/issue.py.

Plus auto-fixed duplicate imports across CI scripts and integration tests.

Two cases use # noqa: F821 for legitimate self-referential type annotations (a TypeVar bound= and a nested-dataclass forward reference) in praktika/utils.py and praktika/gh.py.

Reference: #105159

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)

Note

Medium Risk
Medium risk because it introduces a new CI gate (ruff check) that may fail existing or future PRs, and touches many test files (mostly mechanical fixes/renames) that could subtly affect test discovery or behavior.

Overview
Adds ruff to the style-test environment and wires a new ruff step into ci/jobs/check_style.py, with configuration in pyproject.toml limited to a small set of bug-catching rules (e.g., undefined names, duplicate definitions, duplicate dict keys).

Updates CI scripts and a broad set of Python tests to pass these checks by fixing missing/duplicate imports, correcting undefined variables/typos, removing duplicate keys/unused .format() args, renaming accidentally shadowed tests/handlers, and adding a couple of targeted # noqa: F821 annotations for legitimate forward references.

Reviewed by Cursor Bugbot for commit 64cca06. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.1007

groeneai and others added 2 commits May 17, 2026 19:49
The diagnostic branch in `test_storage_s3_queue/test_migration.py::test_migration`
referenced undefined variables `total_rows`, `count1`, `count2` in its assertion
f-string. When the inner wait loop timed out (count didn't converge in 50s),
Python raised `NameError` at f-string evaluation, masking what should have
been a clear convergence failure.

CIDB confirms 81 failures of this form over the last 90 days, with a sharp
spike to 32 hits on 2026-05-16 across every sanitizer build (`amd_msan`,
`amd_asan_ubsan/db disk/old analyzer`, `amd_tsan`, `amd_llvm_coverage`,
`arm_binary/distributed plan`). All hits are PR-only — `pull_request_number > 0`
across 6+ unrelated PRs.

The diagnostic also computed `expected_files` using a wrong file naming
pattern (`{files_path}/test_{x}.csv`) — the actual files use `{use_prefix}_{i}.csv`
where `use_prefix` advances through `["a","b","c","d","e"]` across each
`add_files_and_check` call, and `i` starts at the cumulative `start_ind`.
The resulting `missing_files` list would always report every expected file
as missing, even when convergence was correct.

This change:
- Computes `count1` and `count2` from per-node `SELECT count()` queries
  (the variables the original author intended)
- Uses `expected_rows[0]` instead of the never-defined `total_rows`
- Drops the broken `expected_files`/`missing_files` calculation
- Reports `distinct files processed` from the existing `processed_files` list,
  which is a useful proxy for diagnostic without the buggy naming logic
- Switches the `processed_files` query from `node` (last value from a for-loop)
  to `node1` for clarity

Demonstration in both directions:
- Without fix: `NameError: name 'total_rows' is not defined`
- With fix: `AssertionError: Expected 1000 rows in total, got 300 on node1
  and 200 on node2 (500), distinct files processed: 5`

CIDB reference (last seen 2026-05-16 06:55 UTC):
https://play.clickhouse.com/?user=play&query=SELECT+test_name%2C+check_name%2C+count%28%29+FROM+default.checks+WHERE+test_name+LIKE+%27test_storage_s3_queue%2Ftest_migration.py%25%27+AND+test_context_raw+LIKE+%27%25NameError%25%27+GROUP+BY+test_name%2C+check_name+ORDER+BY+count%28%29+DESC

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Configures ruff via [tool.ruff] in pyproject.toml and wires it into
the existing style-test job in ci/jobs/check_style.py. The initial
rule set is narrow on purpose - only rules whose every hit is a real
bug or unreachable reference:

- F402 import-shadowed-by-loop-var
- F522/F523 unused .format args
- F601 duplicate dict-literal keys
- F632 is comparison with a literal
- F811 redefinition of an unused name (silently shadowed tests,
  duplicate route handlers, etc.)
- F821 undefined name (the PR #105159 class - undefined variable
  inside an f-string evaluated only on an error/diagnostic branch,
  masking the original failure with NameError)

Stylistic rules (F401, F541, F841, F403, F405) are intentionally
left off for follow-up cleanups so the initial signal is bug-class
only.

Bugs found and fixed by the initial run:

  F821 (same pattern as PR #105159):
  - ci/jobs/scripts/check_ci.py - commit_status_data referenced in
    an exception branch but never assigned
  - tests/fuzz/runner.py - PIPE referenced without
    `from subprocess import PIPE`
  - tests/integration/test_backup_restore_on_cluster_with_checksum_data_file_name/test.py
    - os.path.join with os not imported
  - tests/integration/test_database_iceberg/test.py - BASE_URL_DOCKER
    typo for BASE_URL
  - tests/integration/test_keeper_remove_acl/test.py - node_zk
    referenced in a finally cleanup that was unreachable; the bare
    except silently swallowed the NameError on every run
  - tests/integration/test_storage_delta_disks/test.py - missing
    `from helpers.config_cluster import minio_secret_key`

  F811 silently-shadowed tests (later def overwrites earlier):
  - test_disk_types::test_different_types
  - test_storage_s3::test_empty_file
  - test_executable_table_function - one of the two same-named
    functions renamed to test_executable_storage_*
  - test_storage_delta::test_partition_columns_3 - second def
    renamed to test_partition_columns_jumbled

  F811 dead route handler:
  - test_merge_tree_s3_failover endpoint had two `def fail_request`;
    the throttle one was unreachable, renamed to throttle_request

  F601 duplicate dict-literal keys with divergent values in
  test_storage_s3_queue/test_5.py - same setting specified twice
  with different values; cleaned up to make the intended value
  explicit

  F522/F523 .format-string drift - templates updated without
  dropping the corresponding args (test_jbod_ha,
  test_manipulate_statistics, test_mysql_protocol,
  test_storage_kafka, helpers/dictionary)

  F632 `assert error is ""` -> `==` in test_allow_feature_tier

  F402 loop variable named `field` shadowing
  `from dataclasses import field` in praktika/issue.py

  Plus auto-fixed duplicate imports across CI scripts and
  integration tests.

Two cases use `# noqa: F821` for legitimate self-referential type
annotations (TypeVar bound and nested dataclass forward reference)
in praktika/utils.py and praktika/gh.py.

Reference: #105159

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

clickhouse-gh Bot commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [87cc6d9]

Summary: ✅


AI Review

Summary

This PR adds a narrow ruff gate to Style check for Python bug-class rules such as F821, F811, duplicate dict keys, and invalid literal comparisons, then fixes the current hits. Earlier review points around check_ruff, test_keeper_remove_acl, and transient integration flaky-check logic are addressed or no longer part of the current PR diff. I found no remaining correctness, safety, or test-coverage issues that warrant inline review comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-ci label May 17, 2026
Comment thread ci/jobs/check_style.py Resolved
The directive `# noqa: ignore E203, false positive` is not a valid
suppression syntax. `ruff` parses `# noqa: <comma-separated codes>`,
so the malformed body produced a warning on stderr:

    Invalid `# noqa` directive on tests/ci/git_helper.py:49:
    expected a comma-separated list of codes (e.g., `# noqa: F401, F841`).

`check_ruff` in `ci/jobs/check_style.py` appends stderr to its output,
so the warning made the new `ruff` gate red on this PR even though
no rule was actually violated.

Rewrite the directive in the canonical form `# noqa: E203` so the
suppression intent is preserved and `ruff` no longer warns.
Comment thread ci/jobs/check_style.py Resolved
alexey-milovidov and others added 2 commits May 19, 2026 16:11
`Result.from_commands_run` interprets a truthy return value from a
Python check callable as failure. The default `ruff check
--output-format=concise` invocation prints `All checks passed!` on
success, which the framework saw as a non-empty (truthy) string and
flagged the `ruff` step as failed even though no violations were
found. CI report: #105171

Adding `--quiet` suppresses the success message so the function
returns an empty string on success and violation lines on failure,
matching the convention used by every other check in this file.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed in 9d5c43f by passing --quiet to ruff check so the "All checks passed!" success message is suppressed, matching the silent-on-success convention used by every other check in check_style.py. Merged master to refresh CI.

alexey-milovidov and others added 5 commits May 20, 2026 16:12
The `delete_node` helper opens a Kazoo connection, calls
`node_zk.delete("/test_acl_node")`, then closes the connection. On the
expected `NoAuthError` path, the delete raises before the cleanup line
runs, so `stop_zk_connection` is skipped and the connection stays open.

Wrap the helper body in `try/finally` so cleanup always runs.

Address review comment on #105171

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The prior commit deleted/modified workflow files in this branch as a
workaround for GitHub's workflow-scope check. Restoring them to match
`master` so the PR diff no longer contains unrelated changes.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, check what is the "ERROR" in the integration tests flaky check. I suspect it might be due to timeout while running too many modified tests to check. In that case, apply the same logic as we do in functional tests - the flaky check should stop running tests after a certain soft timeout threshold, to avoid bumping on the global timeout. Send a PR with the fix.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov investigated the Integration tests (amd_asan_ubsan, flaky) ERROR per your directive. Confirmed root cause: the flaky-check job runs for 2h18m54s before being hard-killed by the workflow global timeout, producing Unknown error (exit status: None) (the pytest jsonl has no session-finish record because the subprocess was SIGKILLed mid-run). Log: https://github.com/ClickHouse/ClickHouse/actions/runs/26416267614/job/77763513026

Fix in #105819: ports the FLAKY_CHECK_TIME_LIMIT pattern from ci/jobs/functional_tests.py:544-554 into ci/jobs/integration_test_job.py, bounding total pytest time to 90 min (longer than functional's 45 min because integration is slower) so the job has headroom for cleanup, log collection, and reporting before the global timeout fires. Once #105819 lands, this PR's flaky check should report properly instead of erroring out.

alexey-milovidov pushed a commit that referenced this pull request May 31, 2026
The integration tests flaky check runs each modified test ~50 times across
all changed test modules. With existing per-phase timeouts of `session_timeout_parallel`
= 2h and `session_timeout_sequential` = 1h x N attempts, the total wall-clock
time can far exceed the workflow's global job timeout. When the global timeout
fires, the pytest subprocess is hard-killed via `Shell.run`'s subprocess
timeout, leaving no session-finish record in the pytest jsonl report and
producing `Unknown error (exit status: None)` on the report instead of a
proper FAIL/OK summary.

Reproduced on `Integration tests (amd_asan_ubsan, flaky)` for #105171:
job ran 2h18m54s before the global timeout, errored with the above message,
and the report shows ERROR / no test results.

The functional tests flaky check already handles this via a soft
`FLAKY_CHECK_TIME_LIMIT` (see `ci/jobs/functional_tests.py:544-554`): it
bounds the time spent inside `clickhouse-test`, so the job has headroom for
cleanup, log collection, and reporting before the global timeout fires.

This commit ports the same logic to `ci/jobs/integration_test_job.py`:

1. `FLAKY_CHECK_TIME_LIMIT = 90 * 60` (90 min, longer than functional's 45
   min because integration tests are slower).

2. Cap both `session_timeout_parallel` and `session_timeout_sequential` to
   the remaining budget at the start, so a single phase cannot consume the
   entire budget.

3. In the sequential-attempts loop, recompute the remaining budget every
   iteration. Break out of the loop early when the budget is exhausted
   (< 60s left). Cap each iteration's session-timeout to the remaining
   budget.

4. Treat session-timeout in flaky check as expected (do not propagate as a
   job-level error and filter out the synthetic `Timeout` result), matching
   how targeted checks already handle session-timeout.

Reference: #105171
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, thanks - #105819 fixed the global-timeout half, but a second symptom is now surfacing behind it on this PR's Integration tests (amd_asan_ubsan, flaky) (run https://github.com/ClickHouse/ClickHouse/actions/runs/26987765500/job/79643750220):

Timeout exceeded [5921], sending SIGTERM to process group
test_storage_delta/test.py::test_single_log_file[1-s3] ERROR: command failed after 1/1 attempt(s), exit code: -15
Fail [Integration tests (amd_asan_ubsan, flaky)]
  | Failures: 1/310
  Fail [OOM in dmesg]

The synthetic Timeout is correctly suppressed for flaky/targeted checks (integration_test_job.py:1063-1064), so the soft limit now behaves as intended. The remaining failure is the OOM in dmesg check (integration_test_job.py:1043-1058), which is not exempted for flaky checks. Because this PR mechanically touches many integration test files, the flaky check enumerates ~310 changed-test instances and runs them with --dist=each; under ASan+UBSan that parallel overload triggers a host-level kernel OOM. That OOM is a consequence of the deliberate flaky-check overload, not a regression attributable to any individual changed test - exactly the same class of "expected risk of overload" as the Timeout that is already filtered out.

Could you handle this in a follow-up (separate PR), mirroring the existing Timeout exemption - i.e. do not propagate the synthetic OOM in dmesg result as a failure when is_flaky_check or is_targeted_check? Alternatively, cap the number of distinct changed test modules the flaky check schedules so a broad mechanical diff (like this one) doesn't overload the runner. If a fix is already in progress, please link it here.

@groeneai

groeneai commented Jun 7, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov fix PR opened: #106658 — mirrors the existing Timeout exemption from #105819 to also drop the synthetic OOM in dmesg result for flaky and targeted integration test checks. The detection (and dmesg.log attachment) is preserved for debugging; only the synthetic FAIL propagation is gated, exactly matching the Timeout precedent.

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Path B follow-up opened: #106698. It reduces spark.driver.memory and spark.executor.memory from 8g to 2g in all three delta-lake test files (test_storage_delta/test.py, test_storage_delta/test_cdf.py, test_storage_delta_disks/test.py), bringing the per-Spark-JVM heap from 16 GiB to 4 GiB. With ~12 xdist workers under --dist=each flaky/targeted runs, this drops total JVM heap demand from ~192 GiB to ~48 GiB — comfortably below the runner's RAM, while still leaving 4× the Spark 1g/1g default to preserve the intent of 0302eb0c3af ("Try fix spark out of memory", 2025-08-29).

alexey-milovidov pushed a commit to amosbird/ClickHouse that referenced this pull request Jun 8, 2026
…g/2g

Under integration `flaky` and `targeted` checks, pytest is launched with
`--dist=each`, which spawns N xdist workers (typically 12 on the CI runner,
sized by `min(ncpu/MAX_CPUS_PER_WORKER, mem_gb/MAX_MEM_PER_WORKER)`), each
running its own isolated Docker cluster with a fresh PySpark JVM.

`get_spark` in the three delta-lake integration tests pinned
`spark.driver.memory` and `spark.executor.memory` to `8g` each, i.e. 16 GiB
of JVM heap per worker. With 12 workers under flaky-check `--dist=each` plus
ASan+UBSan overhead in the ClickHouse processes themselves, the host runs out
of memory and the kernel kills the JVMs, after which every subsequent Spark
call from `generate_data` fails (`spark._sc._jvm` AttributeError) and the
runner records an `OOM in dmesg` synthetic failure.

This is what happened on the flaky check for PR ClickHouse#105171 (run
https://github.com/ClickHouse/ClickHouse/actions/runs/26987765500/job/79643750220):
19 `test_storage_delta/*` failures, all sharing the dead-JVM signature, plus
the synthetic `OOM in dmesg`.

The data the tests actually feed Spark is tiny: `generate_data` calls top out
at `spark.range(0, 1300)`, and most call sites use 100 rows or fewer. The
8g/8g heap was added in commit `0302eb0c3af` (2025-08-29, "Try fix spark out
of memory") to address per-process Spark OOM on a different code path, but
4 GiB total per JVM (driver+executor at 2g each) leaves comfortable headroom
above the 1g/1g Spark default while making 12-worker `--dist=each` runs fit:
12 × 4 GiB = 48 GiB, well under the runner's ~256 GiB.

Apply the same change to all three delta-lake test files that share the
8g/8g pattern (`test_storage_delta/test.py`, `test_storage_delta/test_cdf.py`,
`test_storage_delta_disks/test.py`) so the same OOM does not surface on any
PR that touches one of the sibling files. `test_storage_iceberg/test.py` and
`test_storage_iceberg_disks/test.py` already use Spark defaults
(no `spark.driver.memory` / `spark.executor.memory` config), so they do not
need a similar change.

Related: ClickHouse#105171 (originating run).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Merged master to refresh CI. This pulls in #106698 (merged 2026-06-08), which reduces the Spark JVM heap in the delta-lake integration tests from 8g to 2g and was the Path B fix for the OOM in dmesg symptom behind this PR's Integration tests (amd_asan_ubsan, flaky) ERROR. Combined with the soft-timeout from #105819 (already on master), the flaky check should no longer hit the OOM/timeout that ran the full 24-file changed-test set under --dist=each. Verified locally that ruff check --output-format=concise --quiet passes with no violations on the merged tree.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://github.com/ClickHouse/ClickHouse/actions/runs/27175604347/job/80226138143 and provide a fix in a separate PR. If the fix is already in progress, link it here.

This run already includes the Path B Spark heap reduction (#106698, pulled in by the master merge at 72488abb), and it helped — the run got through ~60% of 327 tests, including many test_storage_delta tests that previously hung at module startup — but the job still failed the same way: Failures: 1/327 plus Fail [OOM in dmesg]. New data points beyond the #106698 analysis:

Possible directions, your call which fits best: stagger or cap concurrent workers for modules whose cluster footprint exceeds the per-worker memory budget under --dist=each; shrink the test_storage_delta fixture footprint; and/or make the session timeout robust to in-test hangs so a hang degrades into a per-test failure instead of a job-level SIGTERM plus lost artifacts (the praktika report upload for this job was cancelled, so result_*.json and dmesg.log were never uploaded).

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov Fix PR: #107049

Root cause is concurrency x cluster-size, not per-JVM heap (which #106698 already cut 8g->2g). The flaky/targeted parallel bucket runs -n {workers} --dist=each, so on AMD_MEDIUM (workers = min(16//5, 61//11) = 3) all 3 workers enter test_storage_delta/test.py at once, each starting its 5-node cluster + Spark JVM — ~15 ASan servers + 3 JVMs on 61 GiB -> OOM, surfacing as the in-test hang at test_checkpoint[1-s3] you saw.

The PR moves the three heavy delta modules (test.py, test_cdf.py, test_storage_delta_disks/test.py) out of the --dist=each bucket into the looped sequential bucket (-n 1, repeated >=3x) for the flaky/targeted path only — at most one delta cluster at a time, flakiness signal preserved. Normal --dist=loadfile runs (one file -> one worker -> one cluster) are unaffected. Done via an extensible FLAKY_FORCE_SEQUENTIAL_PREFIXES list with a regression test in ci/tests/.

alexey-milovidov and others added 2 commits June 14, 2026 01:08
The latest master merge brought `ci/jobs/integration_test_job.py` into a
state where it has both `from more_itertools import tail` and a local
`def tail` that shadows it. The import is unused - the only call site
resolves to the local function - so `ruff`'s `F811` rule (one of the
rules this PR enables) correctly flagged it, which failed the new `ruff`
gate on this PR's own head.

Remove the shadowed, unused import.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

CI triage: the only red is Integration tests (amd_asan_ubsan, flaky). It is not caused by this PR.

What happened: the integration flaky-check re-runs every changed integration test, and this PR touches 26 integration test files. In that run, several Delta Lake tests hung waiting on Spark/minio (ConnectionRefusedError / Py4JError → Failed: Timeout (>900.0s) each), which pushed the whole session past its wall-clock limit (xdist.dsession.Interrupted: session-timeout: 5323.0 sec exceeded), so the job ended with exit code 2 (11 failed, 933 passed).

The failing tests are pre-existing flakes, unrelated to the changes here. Over the last 30 days on play.clickhouse.com:

  • test_storage_delta/test.py::test_checkpoint[*], test_metadata[1] — ~21 fails / ~29000 runs across ~1826 distinct PRs
  • test_refreshable_mat_view_replicated/test.py::test_circular_dependencies_survive_restart — 42 fails / 17474 runs across 1173 distinct PRs

This PR's edits to those two files are inert with respect to the failures: in test_storage_delta it removes a duplicate LocalUploader import (still imported once) and renames test_partition_columns_3 → test_partition_columns_jumbled (a different test from the ones that failed); in test_refreshable_mat_view_replicated it drops the redundant import datetime that was already shadowed by from datetime import datetime.

CH Inc sync is red for the same single reason — the private mirror's only real failure is its own Integration tests (amd_asan_ubsan, flaky) job (the other red jobs there are CANCELLED from a superseded run).

Re-ran the failed job on both the public and the private sync PR.

The `Integration tests (amd_asan_ubsan, flaky)` job timed out and reported a
red failure with 0 results on PR #105171, which mechanically touches ~24
integration test modules. The flaky check runs every changed module under
`-n 3 --dist=each` (544 test items x 3 workers) and was killed before it could
produce a report.

Root cause: the soft `FLAKY_CHECK_TIME_LIMIT` was 90 min, measured from `main`
(~91.5 min from the job clock). A lone integration job is cancelled by an
external ceiling at ~80-90 min from job start, so the graceful xdist
`--session-timeout` and the subprocess hard-kill backstop (which still collects
partial results) never fired - the whole process was killed first, leaving an
empty result that surfaced as a failure rather than a best-effort partial report.
A ~19 min hang on `test_storage_delta` made it worse.

Changes to `ci/jobs/integration_test_job.py`:

- Lower `FLAKY_CHECK_TIME_LIMIT` from 90 to 45 min, matching the functional flaky
  check, so the internal timeout/backstop fires and a report is produced well
  before the external cancellation. Worst-case wall-clock is now ~66 min.
- Add `MAX_FLAKY_CHECK_MODULES` (10): when a PR changes more modules than fit the
  budget, run a deterministic sorted subset and skip the rest on a best-effort
  basis. The skipped modules are reported as `SKIPPED` entries so the reduced
  coverage is explicit, not silent.
- When no results are collected within the budget, report `SKIPPED` instead of
  letting an empty result default to `ERROR` and block the PR.

CI report: https://github.com/ClickHouse/ClickHouse/actions/runs/27483289227/job/81298702498
PR: #105171

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread ci/jobs/integration_test_job.py Resolved
…k only

The `empty_best_effort` downgrade (reporting `SKIPPED` instead of letting an
empty result set default to `ERROR`) was applied to both `is_flaky_check` and
`is_targeted_check`. It must not apply to targeted checks.

Targeted integration checks rerun tests selected from previous failures and do
not use `FLAKY_CHECK_TIME_LIMIT`, so the "time budget exhausted" rationale does
not hold for them. Their legitimate empty cases - no failed tests to rerun, and
all targets stale (removed or renamed) - already early-exit as `SKIPPED` above.
Therefore an empty result set reaching this point on a targeted check means
`pytest` was launched but wrote no JSONL test entries because it was killed
before producing any; `run_pytest_and_collect_results` returns an `ERROR`
wrapper with no child results. Downgrading that to `SKIPPED` would hide exactly
the targeted-check failure signal we need, so it must remain `ERROR`.

Restrict the condition to `is_flaky_check` only.

Review: #105171 (comment)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread ci/jobs/integration_test_job.py Resolved
alexey-milovidov and others added 2 commits June 16, 2026 11:58
#107453 ("Make integration flaky check finish within its time budget")
carries the canonical version of this logic and was refined in review to
distinguish an expected timeout from a real harness failure. Bring that
version into this PR so the two do not diverge.

Replace the previous `empty_best_effort = is_flaky_check and not test_results`
heuristic with the timeout-gated approach from #107453:

- `run_pytest_and_collect_results` now returns an explicit `timed_out` flag,
  set when the graceful xdist `--session-timeout` marker is found or when the
  hard subprocess backstop (`Shell.run` `timeout`) kills pytest before it
  finishes (a completed run always returns under `timeout`).
- A flaky/targeted check that produced no results is downgraded to `SKIPPED`
  (via the new `is_empty_best_effort_skip` helper) *only* when a timeout was
  actually observed. An empty result without a timeout - pytest crashed before
  writing `pytest_parallel.jsonl`, or exited with a plugin/internal error and no
  test rows - falls through to `create_from`'s default `ERROR` and stays red.

Add `ci/tests/test_integration_flaky_empty_result.py` (from #107453) covering
the decision truth table and the end-to-end status (timeout-empty -> `SKIPPED`,
non-timeout-empty -> `ERROR`).

The dead `from more_itertools import tail` import that #107453 still has is
intentionally not brought over: the local `tail` shadows it and `ruff` `F811`
(enabled by this PR) flags it - it was removed here in 408f1c3.

Related: #107453

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread ci/jobs/integration_test_job.py Resolved
pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request Jun 17, 2026
The `Integration tests (amd_asan_ubsan, flaky)` job timed out and reported a
red failure with 0 results on PR ClickHouse#105171, which mechanically touches ~24
integration test modules. The flaky check runs every changed module under
`-n 3 --dist=each` (544 test items x 3 workers) and was killed before it could
produce a report.

Root cause: the soft `FLAKY_CHECK_TIME_LIMIT` was 90 min, measured from `main`
(~91.5 min from the job clock). A lone integration job is cancelled by an
external ceiling at ~80-90 min from job start, so the graceful xdist
`--session-timeout` and the subprocess hard-kill backstop (which still collects
partial results) never fired - the whole process was killed first, leaving an
empty result that surfaced as a failure rather than a best-effort partial report.
A ~19 min hang on `test_storage_delta` made it worse.

Changes to `ci/jobs/integration_test_job.py`:

- Lower `FLAKY_CHECK_TIME_LIMIT` from 90 to 45 min, matching the functional flaky
  check, so the internal timeout/backstop fires and a report is produced well
  before the external cancellation. Worst-case wall-clock is now ~66 min.
- Add `MAX_FLAKY_CHECK_MODULES` (10): when a PR changes more modules than fit the
  budget, run a deterministic sorted subset and skip the rest on a best-effort
  basis. The skipped modules are reported as `SKIPPED` entries so the reduced
  coverage is explicit, not silent.
- When no results are collected within the budget, report `SKIPPED` instead of
  letting an empty result default to `ERROR` and block the PR.

CI report: https://github.com/ClickHouse/ClickHouse/actions/runs/27483289227/job/81298702498
PR: ClickHouse#105171

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
# Conflicts:
#	ci/jobs/integration_test_job.py
#	ci/jobs/scripts/find_tests.py
#	ci/tests/test_integration_flaky_empty_result.py
@alexey-milovidov alexey-milovidov self-assigned this Jun 18, 2026
@alexey-milovidov
alexey-milovidov merged commit 9fc0fb5 into master Jun 18, 2026
164 of 165 checks passed
@alexey-milovidov
alexey-milovidov deleted the add-ruff-linter branch June 18, 2026 22:37
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 18, 2026
pull Bot pushed a commit to sowelswl/ClickHouse that referenced this pull request Jun 21, 2026
Follow-up to ClickHouse#105171, which added `ruff` with a deliberately narrow,
bug-class-only rule set and left the unused-name and star-import rules
off pending a dedicated cleanup pass. This enables that second batch in
`pyproject.toml` and fixes every violation across the tree (the bulk in
integration tests):

- `F401` unused-import and `F841` unused-variable: removed, preserving
  any side-effecting right-hand side (e.g. `result = node.query(...)`
  becomes `node.query(...)`). Two `try: import ...` feature probes are
  kept with `# noqa: F401`.
- `F541` f-string-missing-placeholders: dropped the redundant `f` prefix.
- `F403`/`F405` star imports: every `from module import *` is expanded
  into explicit imports of the names actually used, taken from each
  name's real origin, so stdlib/third-party names import from their real
  source rather than through a test "convenience bundle". The now-empty
  `tests/integration/helpers/kafka/common_direct.py` bundle is removed and
  its three remaining consumers import `_VarintBytes`/`KafkaAdminClient`
  directly.

Eliminating the star imports surfaced a real bug the wildcard had masked
from `F821`: `generate_presets.py` in `test_prometheus_protocols` called
an undefined `execute_instant_query_with_http_api`; fixed to the existing
`execute_query_via_http_api`.

No `black`/`isort` reformatting was applied (neither is enforced in the
style check), so the diff is limited to the lint fixes themselves.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.

3 participants