Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions monai/handlers/tensorboard_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ class TensorBoardHandler:

def __init__(self, summary_writer: SummaryWriter | SummaryWriterX | None = None, log_dir: str = "./runs"):
if summary_writer is None:
if SummaryWriter is None:
raise RuntimeError(
"TensorBoardHandler requires tensorboard to be installed. "
"Please install it with: pip install tensorboard"
)
Comment on lines +53 to +57
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

No test covers the new RuntimeError path.

The guard is the sole new behavior in this PR; without a test, a regression (or the current dead-code bug) could go unnoticed. Add a unit test that mocks _tb_available as False and asserts the RuntimeError with the expected message is raised.

As per coding guidelines, "Ensure new or modified definitions will be covered by existing or new unit tests."

🧰 Tools
🪛 Ruff (0.15.1)

[warning] 54-57: Avoid specifying long messages outside the exception class

(TRY003)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@monai/handlers/tensorboard_handlers.py` around lines 53 - 57, Add a unit test
that ensures the new RuntimeError path in tensorboard_handlers.py is covered:
patch or monkeypatch the module-level flag _tb_available to False and then
import/instantiate TensorBoardHandler (or call the code path that references
SummaryWriter) and assert it raises a RuntimeError with the exact message
"TensorBoardHandler requires tensorboard to be installed. Please install it
with: pip install tensorboard"; reference the module symbol names _tb_available,
TensorBoardHandler and SummaryWriter when locating the code to patch and the
call to trigger the exception.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find and examine the optional_import function
fd optional_import --type py

Repository: Project-MONAI/MONAI

Length of output: 232


🏁 Script executed:

#!/bin/bash
# Look for the optional_import definition
rg -n "def optional_import" --type py -A 20

Repository: Project-MONAI/MONAI

Length of output: 1539


🏁 Script executed:

#!/bin/bash
# Examine the full context of optional_import return behavior
find . -name "*.py" -path "*utils*" | grep -E "(module|optional)" | head -20

Repository: Project-MONAI/MONAI

Length of output: 170


🏁 Script executed:

#!/bin/bash
# Read the specific file mentioned in the review
cat -n monai/handlers/tensorboard_handlers.py | head -100

Repository: Project-MONAI/MONAI

Length of output: 4740


🏁 Script executed:

#!/bin/bash
# Read the full optional_import implementation
sed -n '315,400p' monai/utils/module.py

Repository: Project-MONAI/MONAI

Length of output: 4194


🏁 Script executed:

#!/bin/bash
# Check for _LazyRaise class definition
rg -n "_LazyRaise" monai/utils/module.py -A 10 -B 2 | head -50

Repository: Project-MONAI/MONAI

Length of output: 997


🏁 Script executed:

#!/bin/bash
# Check TensorBoardHandler docstring for Raises section
sed -n '40,63p' monai/handlers/tensorboard_handlers.py

Repository: Project-MONAI/MONAI

Length of output: 1005


🏁 Script executed:

#!/bin/bash
# Check test file for TensorBoardHandler
fd test_tensorboard -type f

Repository: Project-MONAI/MONAI

Length of output: 233


🏁 Script executed:

#!/bin/bash
# Search for tests of TensorBoardHandler
rg -n "TensorBoardHandler" tests/ --type f -l | head -5

Repository: Project-MONAI/MONAI

Length of output: 88


🏁 Script executed:

#!/bin/bash
# Check if there are tests that verify the RuntimeError is raised
rg -n "RuntimeError" monai/handlers/tensorboard_handlers.py tests/

Repository: Project-MONAI/MONAI

Length of output: 6031


The SummaryWriter is None guard is dead code and will never execute.

optional_import returns a _LazyRaise() instance on failure, not None. Since the boolean flag indicating success/failure is discarded on line 34, there's no way to check import availability—the guard always evaluates to False, and the intended RuntimeError path is unreachable. The original OptionalImportError will surface instead.

Fix: Capture the availability flag and check it:

Proposed fix
-    SummaryWriter, _ = optional_import("torch.utils.tensorboard", name="SummaryWriter")
+    SummaryWriter, _tb_available = optional_import("torch.utils.tensorboard", name="SummaryWriter")
         if summary_writer is None:
-            if SummaryWriter is None:
+            if not _tb_available:
                 raise RuntimeError(
                     "TensorBoardHandler requires tensorboard to be installed. "
                     "Please install it with: pip install tensorboard"
                 )

Also add Raises: section to TensorBoardHandler docstring documenting the RuntimeError, and add a test verifying this error path.

🧰 Tools
🪛 Ruff (0.15.1)

[warning] 54-57: Avoid specifying long messages outside the exception class

(TRY003)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@monai/handlers/tensorboard_handlers.py` around lines 53 - 57, The guard
checking "if SummaryWriter is None" is unreachable because optional_import
returns a (module, flag) pair; update the import call that produces
SummaryWriter to capture both the symbol and the availability flag (e.g.,
SummaryWriter, _tb_available = optional_import(...)), then change the runtime
check to "if not _tb_available: raise RuntimeError(...)" in the
TensorBoardHandler initializer; also update the TensorBoardHandler docstring to
include a "Raises: RuntimeError" entry describing this error and add a unit test
that simulates tensorboard missing to assert the RuntimeError is raised.

self._writer = SummaryWriter(log_dir=log_dir)
self.internal_writer = True
else:
Expand Down
7 changes: 1 addition & 6 deletions monai/transforms/croppad/functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,7 @@ def pad_nd(
return _np_pad(img, pad_width=to_pad, mode=mode, **kwargs)
try:
_pad = _np_pad
if mode in {"constant", "reflect", "edge", "replicate", "wrap", "circular"} and img.dtype not in {
torch.int16,
torch.int64,
torch.bool,
torch.uint8,
}:
if mode in {"constant", "reflect", "edge", "replicate", "wrap", "circular"}:
_pad = _pt_pad
return _pad(img, pad_width=to_pad, mode=mode, **kwargs)
except (ValueError, TypeError, RuntimeError) as err:
Expand Down
Loading