Repository navigation
Add ruff linter to catch undefined names and other Python bugs - #105171
Conversation
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]>
|
Workflow [PR], commit [87cc6d9] Summary: ✅ AI ReviewSummaryThis PR adds a narrow Final VerdictStatus: ✅ Approve |
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.
`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]>
|
Addressed in 9d5c43f by passing |
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]>
# Conflicts: # ci/jobs/check_style.py
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.
|
@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. |
|
@alexey-milovidov investigated the Fix in #105819: ports the |
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
|
@groeneai, thanks - #105819 fixed the global-timeout half, but a second symptom is now surfacing behind it on this PR's The synthetic Could you handle this in a follow-up (separate PR), mirroring the existing |
|
@alexey-milovidov fix PR opened: #106658 — mirrors the existing |
|
Path B follow-up opened: #106698. It reduces |
…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]>
|
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 |
|
@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
Possible directions, your call which fits best: stagger or cap concurrent workers for modules whose cluster footprint exceeds the per-worker memory budget under |
|
@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 The PR moves the three heavy delta modules ( |
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]>
|
CI triage: the only red is 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 ( The failing tests are pre-existing flakes, unrelated to the changes here. Over the last 30 days on
This PR's edits to those two files are inert with respect to the failures: in
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]>
…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]>
#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]>
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
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]>
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 triggeredNameErroron 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]inpyproject.toml. The initial rule set is deliberately narrow - only rules where every hit was a real bug or unreachable reference:F402import shadowed by loop varF522/F523.formatcalled with unused argsF601duplicate dict-literal keysF632iscomparison with a literalF811redefinition of an unused name (silently shadowed tests, duplicate route handlers, etc.)F821undefined name (the PR Fix NameError masking test_migration diagnostic on count mismatch #105159 class)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_datareferenced in an exception branch but never assignedtests/fuzz/runner.py-PIPEreferenced withoutfrom subprocess import PIPEtest_backup_restore_on_cluster_with_checksum_data_file_name/test.py-os.path.joinwithosnot importedtest_database_iceberg/test.py-BASE_URL_DOCKERtypo forBASE_URLtest_keeper_remove_acl/test.py-node_zkreferenced in afinallycleanup; the bareexceptsilently swallowed theNameErroron every run, so the cleanup never happenedtest_storage_delta_disks/test.py- missingfrom helpers.config_cluster import minio_secret_keyF811silently-shadowed tests (laterdefoverwrites earlier, dropping the first test):test_disk_types::test_different_typestest_storage_s3::test_empty_filetest_executable_table_function- one of the two same-named functions renamed totest_executable_storage_*test_storage_delta::test_partition_columns_3- second def renamed totest_partition_columns_jumbledtest_merge_tree_s3_failoverendpoint had twodef fail_request; the throttle one was unreachable, renamed tothrottle_requestF601duplicate dict-literal keys with divergent values intest_storage_s3_queue/test_5.py- same setting specified twice with different values; cleaned up to make the intended value explicit.F522/F523.formatdrift - templates updated without dropping the corresponding args (test_jbod_ha,test_manipulate_statistics,test_mysql_protocol,test_storage_kafka,helpers/dictionary).F632assert error is ""->==intest_allow_feature_tier.F402loop variable namedfieldshadowingfrom dataclasses import fieldinpraktika/issue.py.Plus auto-fixed duplicate imports across CI scripts and integration tests.
Two cases use
# noqa: F821for legitimate self-referential type annotations (aTypeVarbound=and a nested-dataclass forward reference) inpraktika/utils.pyandpraktika/gh.py.Reference: #105159
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
...
Documentation entry for user-facing changes
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
ruffto thestyle-testenvironment and wires a newruffstep intoci/jobs/check_style.py, with configuration inpyproject.tomllimited 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: F821annotations 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
26.6.1.1007