Skip to content
Merged
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
11 changes: 9 additions & 2 deletions 03_implementation/src/hermes3d/api/routes/design.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,8 +901,15 @@ def _probe_python_provider(
try:
import importlib.metadata as meta_mod
version_str = meta_mod.version(module_name)
except Exception:
pass
except Exception as exc: # noqa: BLE001 -- Wave Agent 7: surface the silent fallback
try:
import logging
logging.getLogger(__name__).debug(
"design.module_version_lookup: metadata.version(%r) failed: %s: %s",
module_name, type(exc).__name__, exc,
)
except Exception: # noqa: BLE001
pass
Comment on lines +905 to +912

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The nested try...except Exception: pass block around the logging call is redundant and adds unnecessary complexity. In a pull request specifically aimed at cleaning up silent broad-except fallbacks, adding a new one for the logger is contradictory. If the concern is that logging might fail (e.g., during interpreter shutdown), it is better to import logging at the top level to ensure it is available in sys.modules and remove the inner try block.

        import logging
        logging.getLogger(__name__).debug(
            "design.module_version_lookup: metadata.version(%r) failed: %s: %s",
            module_name, type(exc).__name__, exc,
        )


if spec.origin:
module_path = str(spec.origin)
Expand Down
11 changes: 9 additions & 2 deletions 03_implementation/src/hermes3d/api/routes/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,8 +551,15 @@ def _host_telemetry() -> dict[str, Any]:

cpu_pct = int(round(psutil.cpu_percent(interval=0.05)))
ram_pct = int(round(psutil.virtual_memory().percent))
except Exception:
pass
except Exception as exc: # noqa: BLE001 -- Wave Agent 7: psutil import/probe is optional; log for observability
try:
import logging
logging.getLogger(__name__).debug(
"system.metrics: psutil unavailable; cpu/ram default to 0: %s: %s",
type(exc).__name__, exc,
)
except Exception: # noqa: BLE001
pass
Comment on lines +555 to +562

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The nested try...except Exception: pass block around the logging call is redundant. Additionally, import logging should ideally be moved to the top level of the module to follow PEP 8 and avoid repeated imports during exception handling.

        import logging
        logging.getLogger(__name__).debug(
            "system.metrics: psutil unavailable; cpu/ram default to 0: %s: %s",
            type(exc).__name__, exc,
        )

try:
disk_pct = int(round(shutil.disk_usage(implementation_path()).used / shutil.disk_usage(implementation_path()).total * 100))
except OSError:
Expand Down
11 changes: 9 additions & 2 deletions 03_implementation/src/hermes3d/api/routes/update_center.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,15 @@ def update_center() -> dict[str, Any]:
as_json({"updater_status": velopack["status"], "providers": provider_summary}),
),
)
except Exception:
pass
except Exception as exc: # noqa: BLE001 -- Wave Agent 7: log the proof-event insert fallback
try:
import logging
logging.getLogger(__name__).warning(
"update_center.read: proof_events insert failed: %s: %s",
type(exc).__name__, exc,
)
except Exception: # noqa: BLE001
pass
Comment on lines +271 to +278

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The nested try...except Exception: pass block around the logging call is redundant. Moving import logging to the top level of the module is recommended to adhere to standard practices and improve efficiency.

        import logging
        logging.getLogger(__name__).warning(
            "update_center.read: proof_events insert failed: %s: %s",
            type(exc).__name__, exc,
        )


return payload

Expand Down
14 changes: 10 additions & 4 deletions 03_implementation/src/hermes3d/core/agents/auto_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,11 @@ def auto_recover(
result.duration_seconds = time.time() - started
log.info("Recovered %s via soft restart", printer_id)
return result
except Exception:
pass
except Exception as exc: # noqa: BLE001 -- Wave Agent 7: log recovery-poll failure
log.debug(
"auto_recovery.printer_state_poll_soft fallback: %s: %s",
type(exc).__name__, exc,
)

# ---- Step 2: firmware restart ----
time.sleep(min(firmware_restart_wait_s, max(0.0, max_total_s - (time.time() - started))))
Expand Down Expand Up @@ -194,8 +197,11 @@ def auto_recover(
result.duration_seconds = time.time() - started
log.info("Recovered %s via firmware restart", printer_id)
return result
except Exception:
pass
except Exception as exc: # noqa: BLE001 -- Wave Agent 7: log firmware-recovery-poll failure
log.debug(
"auto_recovery.firmware_restart fallback: %s: %s",
type(exc).__name__, exc,
)

result.outcome = RecoveryOutcome.GAVE_UP
result.final_state = state if "state" in locals() else {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,11 @@ def _try_llm(self, esc: RepairEscalation) -> RepairResult | None:
from hermes3d.core.llm.providers import extract_json

suggestion = extract_json(getattr(result, "text", "")) or suggestion
except Exception:
pass
except Exception as exc: # noqa: BLE001 -- Wave Agent 7: log suggestion extraction failure
log.debug(
"repair_agent.extract_json fallback: %s: %s",
type(exc).__name__, exc,
)
return RepairResult(
outcome="fixed",
strategy_used="llm_suggestion",
Expand Down
16 changes: 15 additions & 1 deletion 03_implementation/src/hermes3d/services/module_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -2239,7 +2239,21 @@ def _private_runtime_env() -> dict[str, str]:
from hermes3d.services.agent_runtime import private_env

return private_env()
except Exception:
except Exception as exc: # noqa: BLE001 -- silent fallback was Wave Agent 7 finding
# Squad G follow-up (Remaining/Skipped Wave 2026-05-09): expose the
# silent-fallback so observability is preserved. Use ``redact_text``
# because env-import exceptions can carry path / token fragments.
try:
import logging

from hermes3d.gateways.redaction import redact_text

logging.getLogger(__name__).warning(
"_private_runtime_env: private_env import/load failed: %s",
redact_text(f"{type(exc).__name__}: {exc}")[:200],
)
except Exception: # noqa: BLE001 -- best-effort during teardown
pass
Comment on lines +2246 to +2256

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The nested try...except block and lazy imports inside the exception handler should be avoided. Furthermore, there is an inconsistency in the use of redaction: this block imports redact_text from hermes3d.gateways.redaction, while a local _redact_text function already exists in this module (line 3240). If the external redact_text is preferred for its more robust masking, it should be imported at the top level to maintain consistency and avoid circular dependency risks during lazy loading.

        import logging

        from hermes3d.gateways.redaction import redact_text

        logging.getLogger(__name__).warning(
            "_private_runtime_env: private_env import/load failed: %s",
            redact_text(f"{type(exc).__name__}: {exc}")[:200],
        )

return {}


Expand Down
100 changes: 100 additions & 0 deletions 04_testing/pytest/unit/test_broad_except_cleanup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
"""Wave Agent 7 broad-except cleanup — source-level pin tests.

Source pin tests that confirm the 7 silent-fallback sites Wave Agent 7
flagged now emit a ``logging.getLogger(__name__).{warning|debug}(...)``
call before the ``pass``. Catches accidental revert.

Sites covered (per Wave synthesis 2026-05-09):
- services/module_runtime.py:_private_runtime_env (warning + redact_text)
- api/routes/design.py:module_version_lookup (debug)
- api/routes/update_center.py:read fallback (warning)
- api/routes/system.py:metrics psutil fallback (debug)
- core/orchestration/repair_agent.py:extract_json fallback (debug)
- core/agents/auto_recovery.py:printer_state_poll_soft fallback (debug)
- core/agents/auto_recovery.py:firmware_restart fallback (debug)

Behavior is otherwise unchanged on every site (silent fallback semantics
preserved; observability added).

References:
- OWASP A09:2021 Logging & Monitoring Failures
- https://docs.python.org/3/library/logging.html
"""

from __future__ import annotations

import inspect

import pytest


def _read_source(dotted: str) -> str:
"""Read a Python source file under hermes3d by dotted module name."""
parts = dotted.split(".")
from pathlib import Path

src_root = Path(__file__).resolve().parents[3] / "03_implementation" / "src"
file_path = src_root / Path(*parts).with_suffix(".py")
return file_path.read_text(encoding="utf-8")
Comment on lines +31 to +38

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The hardcoded path depth (parents[3]) in _read_source is brittle and may cause tests to fail if run from a different environment or if the repository structure changes. Using importlib.util.find_spec is a more robust way to locate the source file for a given module regardless of the current working directory or test execution context.

Suggested change
def _read_source(dotted: str) -> str:
"""Read a Python source file under hermes3d by dotted module name."""
parts = dotted.split(".")
from pathlib import Path
src_root = Path(__file__).resolve().parents[3] / "03_implementation" / "src"
file_path = src_root / Path(*parts).with_suffix(".py")
return file_path.read_text(encoding="utf-8")
def _read_source(dotted: str) -> str:
"""Read a Python source file under hermes3d by dotted module name."""
import importlib.util
from pathlib import Path
spec = importlib.util.find_spec(dotted)
if spec is None or spec.origin is None:
raise ImportError(f"Could not find source for {dotted}")
return Path(spec.origin).read_text(encoding="utf-8")



@pytest.mark.parametrize(
"module_dotted,marker_substring,description",
[
(
"hermes3d.services.module_runtime",
"_private_runtime_env: private_env import/load failed",
"module_runtime._private_runtime_env logs + redacts on fallback",
),
(
"hermes3d.api.routes.design",
"design.module_version_lookup",
"design.module_version_lookup logs on metadata.version() fallback",
),
(
"hermes3d.api.routes.update_center",
"update_center.read",
"update_center.read logs on proof_events insert fallback",
),
(
"hermes3d.api.routes.system",
"system.metrics",
"system.metrics logs on psutil fallback",
),
(
"hermes3d.core.orchestration.repair_agent",
"repair_agent.extract_json",
"repair_agent logs on extract_json fallback",
),
(
"hermes3d.core.agents.auto_recovery",
"auto_recovery.printer_state_poll_soft",
"auto_recovery soft-restart logs on poll fallback",
),
(
"hermes3d.core.agents.auto_recovery",
"auto_recovery.firmware_restart",
"auto_recovery firmware-restart logs on poll fallback",
),
],
)
def test_broad_except_site_now_logs(
module_dotted: str, marker_substring: str, description: str
) -> None:
"""Each Wave Agent 7 site must contain a recognizable log marker."""
src = _read_source(module_dotted)
assert marker_substring in src, (
f"Wave Agent 7 broad-except cleanup regression — {description}: "
f"expected marker {marker_substring!r} not found in source."
)


def test_module_runtime_uses_redact_text_for_env_exception() -> None:
"""``_private_runtime_env`` exceptions can carry path/token fragments;
must run through ``redact_text`` before logging (Wave Agent 7 caveat)."""
src = _read_source("hermes3d.services.module_runtime")
# The redact_text call must appear in or near the _private_runtime_env block.
assert "redact_text" in src, (
"module_runtime must import redact_text for safe exception logging"
)
assert "_private_runtime_env" in src