Skip to content

Add HashMismatchError for download hash validation failures#8861

Open
AlexanderSanin wants to merge 5 commits into
Project-MONAI:devfrom
AlexanderSanin:fix/hash-mismatch-exception-8832
Open

Add HashMismatchError for download hash validation failures#8861
AlexanderSanin wants to merge 5 commits into
Project-MONAI:devfrom
AlexanderSanin:fix/hash-mismatch-exception-8832

Conversation

@AlexanderSanin
Copy link
Copy Markdown
Contributor

Summary

Fixes #8832

As suggested by @ericspod in #8699, the hash check failure in download_url should raise a specific exception rather than a generic RuntimeError, so it isn't accidentally suppressed by skip_if_downloading_fails.

  • Added HashMismatchError(RuntimeError) in monai/apps/utils.py
  • download_url now raises HashMismatchError when check_hash fails
  • skip_if_downloading_fails re-raises HashMismatchError immediately (hash mismatch = real failure, not network issue)
  • Removed "md5 check" from DOWNLOAD_FAIL_MSGS since hash failures are now a distinct exception type
  • Backward compatible: HashMismatchError inherits from RuntimeError, so existing except RuntimeError handlers still work

Test plan

  • Existing TestDownloadUrl test updated to expect HashMismatchError for bad hash values
  • Network errors still correctly skip tests via skip_if_downloading_fails
  • Hash mismatches no longer silently skipped in CI

Signed-off-by: Oleksandr Sanin alexaaander.sanin@gmail.com

)

Catching BaseException inadvertently suppresses KeyboardInterrupt,
SystemExit, and GeneratorExit, which should nearly always propagate.
All 17 occurrences across monai/ and tests/ are replaced with
Exception, which is the appropriate base class for catchable errors.

Signed-off-by: Oleksandr Sanin <alexaaander.sanin@gmail.com>
…MONAI#8832)

Introduce a dedicated HashMismatchError (subclass of RuntimeError) to
distinguish hash validation failures from network errors in download_url.
This allows skip_if_downloading_fails to let hash mismatches propagate
as real test failures instead of silently skipping them.

- Add HashMismatchError class in monai/apps/utils.py
- Use it in download_url when check_hash fails
- Update skip_if_downloading_fails to re-raise HashMismatchError
- Remove "md5 check" from DOWNLOAD_FAIL_MSGS (no longer needed)
- Update test to expect HashMismatchError for bad hash values

Signed-off-by: Oleksandr Sanin <alexaaander.sanin@gmail.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 18, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ac956d82-455a-4a2a-afc0-7c0199a0dc6b

📥 Commits

Reviewing files that changed from the base of the PR and between 5f9ad75 and 2165fe9.

📒 Files selected for processing (1)
  • monai/apps/utils.py

📝 Walkthrough

Walkthrough

This PR tightens exception handling by replacing multiple except BaseException clauses with except Exception across infrastructure, inference, auto3dseg, detection, nnUNet, and tests so system-level exceptions propagate. It also adds and exports HashMismatchError in monai.apps.utils and updates tests to expect/re-raise that specific error for download hash failures. Some imports were reformatted to multi-line lists without behavioral changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Most changes (BaseException→Exception narrowing across 13 files) are unrelated to the HashMismatchError objective and appear to be incidental refactoring outside the linked issue scope. Separate the BaseException→Exception changes into a distinct PR focused on exception handling narrowing; keep this PR focused solely on HashMismatchError implementation.
Docstring Coverage ⚠️ Warning Docstring coverage is 61.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed Title directly identifies the primary change: introducing HashMismatchError for download hash validation failures, which aligns with the main objective.
Description check ✅ Passed Description covers the core change (HashMismatchError addition), affected files, backward compatibility, and test plan, though some checklist items remain unchecked.
Linked Issues check ✅ Passed PR fully addresses #8832: introduces HashMismatchError as a distinct exception for hash failures, updates skip_if_downloading_fails to re-raise it, and removes related DOWNLOAD_FAIL_MSGS entries.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
tests/test_utils.py (1)

196-201: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix stale exception type in test docstring.

The docstring says hash mismatch raises RuntimeError, but the test now validates HashMismatchError.

Proposed patch
@@
-        Raises:
-            RuntimeError: When the downloaded file's hash does not match.
+        Raises:
+            HashMismatchError: When the downloaded file's hash does not match.

As per coding guidelines, "Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings."

🤖 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/test_utils.py` around lines 196 - 201, The test_download_url docstring
currently states that a hash mismatch raises RuntimeError but the test actually
asserts HashMismatchError; update the Raises section in the test_download_url
docstring to list HashMismatchError (the exact exception class name) and
optionally add a brief description, ensuring consistency with the test's
assertions that raise HashMismatchError.
🤖 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 `@monai/apps/utils.py`:
- Around line 283-286: The docstring for download_url incorrectly lists
RuntimeError for checksum failures; update the "Raises" section to state
HashMismatchError (the actual exception raised in the implementation) and
include a short description (e.g., when the downloaded file's checksum does not
match expected hash) so the docstring matches the behavior of download_url and
references HashMismatchError.

---

Outside diff comments:
In `@tests/test_utils.py`:
- Around line 196-201: The test_download_url docstring currently states that a
hash mismatch raises RuntimeError but the test actually asserts
HashMismatchError; update the Raises section in the test_download_url docstring
to list HashMismatchError (the exact exception class name) and optionally add a
brief description, ensuring consistency with the test's assertions that raise
HashMismatchError.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: dc3bdf66-94b7-4379-8371-8e06a7a92356

📥 Commits

Reviewing files that changed from the base of the PR and between ef2acfb and 5f9ad75.

📒 Files selected for processing (15)
  • monai/__init__.py
  • monai/apps/__init__.py
  • monai/apps/auto3dseg/data_analyzer.py
  • monai/apps/auto3dseg/ensemble_builder.py
  • monai/apps/auto3dseg/utils.py
  • monai/apps/detection/metrics/coco.py
  • monai/apps/nnunet/nnunetv2_runner.py
  • monai/apps/utils.py
  • monai/config/deviceconfig.py
  • monai/data/__init__.py
  • monai/inferers/inferer.py
  • monai/utils/tf32.py
  • tests/apps/detection/networks/test_retinanet.py
  • tests/networks/nets/test_resnet.py
  • tests/test_utils.py

Comment thread monai/apps/utils.py
Comment on lines +283 to 286
raise HashMismatchError(
f"{hash_type} check of downloaded file failed: URL={url}, "
f"filepath={filepath}, expected {hash_type}={hash_val}."
)
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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Update download_url Raises docs to HashMismatchError for hash mismatch.

The implementation now raises HashMismatchError, but the docstring still declares RuntimeError for this path.

Proposed patch
@@
-        RuntimeError: When the hash validation of the ``url`` downloaded file fails.
+        HashMismatchError: When the hash validation of the ``url`` downloaded file fails.

As per coding guidelines, "Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings."

🤖 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 `@monai/apps/utils.py` around lines 283 - 286, The docstring for download_url
incorrectly lists RuntimeError for checksum failures; update the "Raises"
section to state HashMismatchError (the actual exception raised in the
implementation) and include a short description (e.g., when the downloaded
file's checksum does not match expected hash) so the docstring matches the
behavior of download_url and references HashMismatchError.

AlexanderSanin and others added 3 commits May 19, 2026 09:29
…@gmail.com>

I, Oleksandr Yizchak Sanin <alexaaander.sanin@gmail.com>, hereby add my Signed-off-by to this commit: 5f9ad75

Signed-off-by: Oleksandr Yizchak Sanin <alexaaander.sanin@gmail.com>
Signed-off-by: Oleksandr Yizchak Sanin <alexaaander.sanin@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Raise different exception when hash value of download is wrong

2 participants