← Back to Pull requests

pre-commit: adopt ruff 0.17.3 #6743

Closed
unknown closed this pull request without merging on Nov 11, 2026 15:27 UTC
View on GitHub
unknown unknown commented on Oct 29, 2026 13:51 UTC
Author

##### What this PR does / why we need it:

Second half of the pre-commit autoupdate from #6639 (the flake8/mypy/check-jsonschema bumps landed in #6742): adopts ruff v0.16.4 → v0.17.3. Rebased on main after #6742 merged. With preview = true, ruff 0.17's newly promoted rules flagged 80 violations, ruff-format started formatting markdown code blocks (touching generated docs/site), and ruff RUF100 stripped the flake8-fork FCN001 noqas. This PR resolves all of it:

  • docs/site excluded from ruff entirely (pyproject.toml) — generated docs must never be modified in PRs

  • force-exclude = true in [tool.ruff]: extend-exclude only applies when ruff walks the tree, so direct ruff check <file> invocations (and any hook not passing --force-exclude) silently still linted the excluded paths; making it explicit keeps the config self-contained

  • restored the two FCN001 noqas in libs/vm/vm.py that RUF100 stripped; external = ["FCN"] added so ruff leaves flake8-fork codes alone

  • PLW0108 ignored: TimeoutSampler func=lambda: x.instance.to_dict() lambdas rely on late binding of the dynamic .instance attribute — ruff's suggested inline would freeze a stale snapshot

  • Style-only rewrite rules ignored (pure readability rewrites with provably identical behavior — the affected files are reverted to main's content): FURB113 (append-in-loop→extend), FURB142 (add-in-loop→update), C420 (dict comprehension→fromkeys), RUF055 (re.sub with plain pattern→replace), PLC0207 (split→maxsplit), FURB156 (hardcoded charset), SIM110 (for-loop→any), FURB145 (slice→copy), UP042 ((str, Enum)→StrEnum)

  • RUF075 fixed: 11 fallible context managers wrapped in plain try/finally (the two verification-type CMs, _confirm_status_success_on_update and wait_for_resize, keep their post-yield wait unconditional for simplicity)

  • PT012 fixed without losing diagnostics: ruff 0.17 tightened the rule — it now also flags a single trailing statement after the expected-to-fail call, which the five negative tests below had. A bare LOGGER.error inside the block does not satisfy it (verified with 0.17.3: two statements are still flagged), so each site is now try/except/else with the original wording in pytest.fail: the message stops being unreachable dead code and becomes the failure reason in the report, with no suppression and no ignore entry:

  • - tests/virt/cluster/common_templates/custom_namespace/test_custom_namespace.py (the LOGGER.error about a template that unexpectedly reconciled post-revert)
    - tests/virt/cluster/migration_and_maintenance/rbac_hardening/test_migration_rights.py
    - tests/virt/node/hotplug/test_cpu_memory_hotplug.py (CPU and memory above the max value)
    - tests/virt/node/migration_and_maintenance/test_node_maintenance.py
    - tests/storage/cdi_import/test_import_http.py consumes its TimeoutSampler with an intentionally empty loop body, so the rule is satisfied without any suppression and the reason sits next to the code in a plain comment
  • PLC2801: utilities/unittests is excluded from linting only ([tool.ruff.lint] exclude = ["utilities/unittests/"]), mirroring the flake8 hook exclusion — those hook unit tests embed intentionally non-compliant fixtures and drive mock context managers' __enter__ directly (PLC2801), plus deliberately loose pytest patterns (RUF043, PLR0133, PT012): 13 findings, none of them introduced or in scope of a revision bump. ruff format reports every file there already formatted, so there is no formatting exclusion. The / suffix is load-bearing: section-level exclude patterns are matched against files, so a bare directory name is silently ignored (verified with ruff 0.17.3). The paramiko FIPS monkey-patch now assigns through cast(Any, ...) and needs no directive at all (a plain assignment fails mypy method-assign, setattr trips B010, and type.__setattr__ trips PLC2801 — the cast satisfies all three while staying an ordinary attribute assignment)

  • RUF027: 5 assertion messages were missing their f prefix (they printed literal {placeholders} on failure) — fixed; the shared .format() log template in tests/network/utils.py keeps its eager .format() call sites, with only the placeholder names decoupled from in-scope variables ({iface}/{address}) — RUF027 fires when placeholders shadow local variable names

  • UP052 (context-manager Generator annotations), RUF043 (raw match= patterns), RUF045 (dataclass field annotations), RUF069, FURB110 (or-operator), D301 (raw docstrings) fixed inline (production/test code only; utilities/unittests is ruff-excluded, see above)
  • There are no suppressions in this change at all: scripts/pre_commit_hooks/exceptions.toml stays exceptions = [], no file carries a noqa or type: ignore, and no per-file-ignore was added — every site is handled by config or by restructuring the code.

    Verification: all pre-commit hooks pass at commit time on this branch (including check-linter-directives, also validated against the workflow's net-diff staging semantics); tox -e utilities-unittests — 931 passed, 99.33% coverage (threshold 95%); scripts/tests_analyzer — 136 passed. ruff 0.17.3 was verified to be a no-op for this repo: ruff check . and ruff format --check . report zero findings on it (its only behavioural additions are the preview rule shared-clock-mock, a more conservative UP032 fix, and speedups), and all hooks pass with the bumped rev. On the review-fix commit (97dc91ac): ruff check . and ruff format --check . clean, all pre-commit hooks pass for the touched files, utilities/unittests fingerprint/prompt tests pass, and the try/except/else shape was probed in isolation (expected exception → pass; no exception → Failed: <original message>).

    ##### Which issue(s) this PR fixes:

    ##### Special notes for reviewer:

    Split 2/2 of #6639 (supersedes it); #6742 already merged — this PR is rebased on main and its diff is exactly the ruff adoption. Contains no docs/site changes (the bot's markdown reformat was dropped, not reverted file-by-file) and no changes to utilities/unittests (lint-excluded, see above). Utilities unit-test note: touched utilities/ modules (virt.py, infra.py, storage.py — coverage-omitted; pytest_utils.py, console.py — docstring/or-operator and monkey-patch refactor) carry no behavior change beyond lint-mandated try/finally wrapping. The two non-omitted spots CodeRabbit flagged are covered by existing tests, which pass: test_get_fingerprint_returns_fips_safe_md5 (exercises the patch_paramiko_for_fips refactor through the patched PKey.get_fingerprint) and the test_default_prompt cases in utilities/unittests/test_console.py (the prompt if prompt else ... → prompt or ... rewrite).

    ##### jira-ticket:

    ---
    Assisted-by: PI (rits/zai-org/glm-5-3)

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

    Bug Fixes
    Improved cleanup and state restoration in test helpers, including when operations fail or are interrupted.
    Ensured status checks run after updates and improved several test failure messages to display relevant values.
    Chores
    Updated linting and formatting configuration and refreshed the Ruff pre-commit version.
    * Made minor documentation and test-maintenance updates; no user-facing product behavior changes are included.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: RoniKishner Review duration: 18816m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #6743"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%