Skip to content

Enable more ruff rules - #7470

Merged
danielhollas merged 8 commits into
aiidateam:mainfrom
danielhollas:enable-more-ruff
Aug 13, 2026
Merged

Enable more ruff rules#7470
danielhollas merged 8 commits into
aiidateam:mainfrom
danielhollas:enable-more-ruff

Conversation

@danielhollas

@danielhollas danielhollas commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator

This is a follow-up to the recent ruff upgrades, where I purposefully disabled some rules that had a lot of hits to ease review.

Here I enable three more rules and fix (or add noqas) all the hits

RUFF043

What it does

Checks for non-raw literal string arguments passed to the match parameter
of pytest.raises() where the string contains at least one unescaped
regex metacharacter.

Why is this bad?

The match argument is implicitly converted to a regex under the hood.
It should be made explicit whether the string is meant to be a regex or a "plain" pattern
by prefixing the string with the r suffix, escaping the metacharacter(s)
in the string using backslashes, or wrapping the entire string in a call to
re.escape().

RUF059 (unused-unpacked-variable)

What it does

Checks for the presence of unused variables in unpacked assignments.

Why is this bad?

A variable that is defined but never used can confuse readers.
If a variable is intentionally defined-but-not-used, it should be
prefixed with an underscore, or some other value that adheres to the
[lint.dummy-variable-rgx] pattern.

### PLR0911 (too-many-return-statements)

@codecov

codecov Bot commented Jul 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 80.68%. Comparing base (2f36f79) to head (8b58545).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7470      +/-   ##
==========================================
+ Coverage   80.68%   80.68%   +0.01%     
==========================================
  Files         581      581              
  Lines       47068    47068              
==========================================
+ Hits        37971    37974       +3     
+ Misses       9097     9094       -3     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: QUIET

Plan: Pro Plus

Run ID: 6f2b0e69-b11d-41e1-928b-537e8e71e7cc

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR narrows Ruff ignores, adds targeted PLR0911 suppressions, marks unused values explicitly, and corrects pytest regex literals and expected message patterns. Runtime behavior is otherwise unchanged.

Changes

Lint cleanup and warning compliance

Layer / File(s) Summary
Ruff configuration and suppressions
pyproject.toml, src/aiida/..., .molecule/..., tests/orm/...
Removed selected global Ruff ignores and added targeted PLR0911 suppressions.
Runtime unused-value cleanup
src/aiida/restapi/resources.py, src/aiida/transports/plugins/async_backend.py
Renamed unused parsed values and command outputs with underscore-prefixed names.
Test fixture and return-value cleanup
tests/cmdline/..., tests/conftest.py, tests/engine/test_run.py
Updated tuple unpacking and return-value assignments to discard unused values explicitly.
Raw regex assertion updates
tests/**
Converted exception-message patterns to raw strings and aligned escaped punctuation and trailing message text.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: agoscinski, geigerj2

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 67.12% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change: enabling additional Ruff lint rules.
Description check ✅ Passed The description explains the enabled Ruff rules and the fixes applied for their violations.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/schedulers/test_slurm.py`:
- Around line 59-61: Update the ValueError match pattern in the SlurmJobResource
test to use a single escaped asterisk in the raw regex, so it matches the
literal “*” in the error message rather than backslashes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5be77c4f-4616-4935-a97b-bd1e076c56ad

📥 Commits

Reviewing files that changed from the base of the PR and between 45e53ed and e0b8433.

📒 Files selected for processing (35)
  • .molecule/default/files/polish/lib/expression.py
  • pyproject.toml
  • src/aiida/engine/processes/calcjobs/calcjob.py
  • src/aiida/engine/processes/workchains/restart.py
  • src/aiida/orm/nodes/data/array/bands.py
  • src/aiida/orm/utils/node.py
  • src/aiida/restapi/resources.py
  • src/aiida/storage/sqlite_zip/orm.py
  • src/aiida/tools/dbimporters/plugins/icsd.py
  • src/aiida/transports/plugins/async_backend.py
  • tests/cmdline/params/types/test_calculation.py
  • tests/cmdline/params/types/test_code.py
  • tests/cmdline/params/types/test_group.py
  • tests/cmdline/utils/test_common.py
  • tests/conftest.py
  • tests/engine/daemon/test_client.py
  • tests/engine/processes/test_control.py
  • tests/engine/test_run.py
  • tests/engine/test_runners.py
  • tests/engine/test_work_chain.py
  • tests/manage/configuration/test_config.py
  • tests/orm/data/code/test_abstract.py
  • tests/orm/data/code/test_containerized.py
  • tests/orm/data/code/test_installed.py
  • tests/orm/data/code/test_portable.py
  • tests/orm/models/test_models.py
  • tests/orm/nodes/data/test_array.py
  • tests/orm/nodes/data/test_data.py
  • tests/orm/nodes/data/test_jsonable.py
  • tests/orm/nodes/data/test_remote.py
  • tests/orm/nodes/data/test_trajectory.py
  • tests/schedulers/test_slurm.py
  • tests/test_conftest.py
  • tests/tools/archive/migration/test_v06_to_v07.py
  • tests/transports/test_all_plugins.py

Comment thread tests/schedulers/test_slurm.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/engine/daemon/test_client.py (2)

94-94: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Include the trailing periods in the exception-message assertions.

DaemonNotRunningException and DaemonTimeoutException raise messages that end with periods, so the assertions at tests/engine/daemon/test_client.py:94 and :106 should match r'The daemon is not running\.' and r'Connection to the daemon timed out\.'.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/engine/daemon/test_client.py` at line 94, Update the exception message
patterns in the relevant pytest.raises assertions to match the trailing periods
emitted by DaemonNotRunningException and DaemonTimeoutException, escaping the
periods in the regex while preserving the existing message text.

166-166: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove the hard-coded temporary path from the fixture.

Ruff reports S108 for /tmp/aiida-core on Line 166. The value is test metadata, not a file operation, but it still violates the lint check in this lint-cleanup PR. Use a non-temporary sentinel or derive the value with pathlib.Path.

Proposed fix
-            'aiida-core': {'version': '2.6.0', 'editable_path': '/tmp/aiida-core'},
+            'aiida-core': {
+                'version': '2.6.0',
+                'editable_path': str(pathlib.Path('aiida-core').resolve()),
+            },

Ruff 0.16.1 reports this S108 finding.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/engine/daemon/test_client.py` at line 166, Replace the hard-coded
`/tmp/aiida-core` value in the fixture metadata with a non-temporary sentinel or
a value derived through pathlib.Path, while preserving the fixture’s expected
editable_path metadata.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@tests/engine/daemon/test_client.py`:
- Line 94: Update the exception message patterns in the relevant pytest.raises
assertions to match the trailing periods emitted by DaemonNotRunningException
and DaemonTimeoutException, escaping the periods in the regex while preserving
the existing message text.
- Line 166: Replace the hard-coded `/tmp/aiida-core` value in the fixture
metadata with a non-temporary sentinel or a value derived through pathlib.Path,
while preserving the fixture’s expected editable_path metadata.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7bda5155-3b71-4c23-8070-0b3af5a71194

📥 Commits

Reviewing files that changed from the base of the PR and between 60dc191 and aaa4c41.

📒 Files selected for processing (8)
  • pyproject.toml
  • src/aiida/engine/processes/calcjobs/calcjob.py
  • src/aiida/transports/plugins/async_backend.py
  • tests/conftest.py
  • tests/engine/daemon/test_client.py
  • tests/engine/test_work_chain.py
  • tests/orm/models/test_models.py
  • tests/orm/nodes/data/test_array.py
🚧 Files skipped from review as they are similar to previous changes (7)
  • tests/conftest.py
  • src/aiida/engine/processes/calcjobs/calcjob.py
  • pyproject.toml
  • tests/orm/models/test_models.py
  • tests/orm/nodes/data/test_array.py
  • tests/engine/test_work_chain.py
  • src/aiida/transports/plugins/async_backend.py

@GeigerJ2 GeigerJ2 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks, @danielhollas. Always LGTM for enabling more ruff rules! Red CI is just because of the merge of main, that re-introduced two hits. Should be easy to resolve by re-running pre-commit on all files. Then, good to merge and I will approve.

The many times we return tuples, just to unpack them and immediately throw away half of its members, hints that we should be using more proper datastructures. Underscore prefix is the right, well-scoped fix for this PR, though.

@danielhollas

Copy link
Copy Markdown
Collaborator Author

I've added PLR0911 back to the ignore list, since this rule is not included in the new expanded set of default rules in ruff 0.16, which I think we should migrate into, see more info in https://astral.sh/blog/ruff-v0.16.0#better-default-rule-set

Otherwise this should be ready @GeigerJ2

@danielhollas
danielhollas requested a review from GeigerJ2 August 13, 2026 11:20

@GeigerJ2 GeigerJ2 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks, @danielhollas, already approve. One minor nit:

tests/cmdline/utils/test_common.py:107,112, tests/orm/nodes/data/test_remote.py:160

    with pytest.raises(TypeError, match=r'.*passed for validation.'):
    with pytest.raises(FileExistsError, match=r'.*use `--overwrite` to overwrite.'):
    with pytest.raises(ValueError, match=r'.*is not an valid input. Please choose either.*.'):

The trailing . is a real period in each message, but now reads as a wildcard. Escape it if you want to keep asserting the period (match=r'passed for validation\\.'), or drop it. test_all_plugins.py:1362 is the inverse: match=r'Error while creating the tar archive' has no metacharacter left, so the r is inert; its twin at :1520 has none.

@danielhollas

danielhollas commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

The trailing . is a real period in each message, but now reads as a wildcard. Escape it if you want to keep asserting the period (match=r'passed for validation\.'), or drop it.

Thanks, I dropped the trailing periods. Also, the .* pattern is superfluous so I dropped it in a few places as well.

Will merge after tests pass unless somebody stops me. :-)

@danielhollas
danielhollas merged commit e56a906 into aiidateam:main Aug 13, 2026
48 of 49 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in aiida-core v3.1.0 Aug 13, 2026
@danielhollas
danielhollas deleted the enable-more-ruff branch August 13, 2026 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants