Skip to content

Commit 4ccb476

Browse files
MImmesbergerdependabot[bot]claude
authored
Fix beartype claw skipping BooleanLevel; make claw warnings fatal in tests (#154)
## The bug Every `import ttsim` (and so every `import gettsim`) emitted: ``` BeartypeClawDecorWarning: Function namedtuple_BooleanLevel.BooleanLevel.__new__() not decoratable by @beartype, as: BeartypeDecorHintForwardRefException: Forward reference 'str | None' not valid Python attribute name. ``` `BooleanLevel` in `_unit_inference.py` was a `NamedTuple`. Under `from __future__ import annotations`, the `__new__` that `collections.namedtuple` synthesizes carries *stringified* annotations, which beartype resolves as forward references: a bare name like `bool` resolves, `str | None` does not. The claw therefore skipped the class — runtime checking on it was silently absent, not merely noisy. ## The fix Make `BooleanLevel` a `@dataclass(frozen=True)` (which the project prefers anyway) and read its fields by attribute at the three unpacking call sites. Verified empirically that a frozen dataclass with the identical `str | None` field decorates cleanly under the claw while the `NamedTuple` form does not. ## Making it loud The warning had been scrolling past unnoticed in CI. `BeartypeClawDecorWarning` is now `error::` in `ini_options.filterwarnings`, so any future skipped decoration fails the suite. The `@interface_input` metadata dataclasses are the one known-benign case (a non-callable data holder has nothing to check) and stay exempt. That exemption needs to be in the pytest config as well as in `ttsim/__init__.py`, because pytest resets warning filters per item — which is why 7 of them were showing up in `pytest ttsim/tests` output despite the import-time filter. `tests/test_beartype_gate.py` gains `test_import_leaves_no_claw_decoration_skipped`, covering plain `import ttsim` outside pytest too. Written first, confirmed red on the `BooleanLevel` warning, green after the fix. ## Verification - `pytest ttsim/tests`: 1674 passed, 6 skipped, 0 claw warnings. - Reverting only the `_unit_inference.py` change makes the suite error out, confirming the guard fires. - gettsim and gettsim-personas suites: 0 claw warnings, all green. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01VCkEDhUCi4aJ6uLGTQeeNH --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 335407d commit 4ccb476

6 files changed

Lines changed: 65 additions & 17 deletions

File tree

‎.github/workflows/main.yml‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ jobs:
4949
- os: windows-latest
5050
environment: py313
5151
steps:
52-
- uses: actions/checkout@v6
53-
- uses: prefix-dev/setup-pixi@v0.9.6
52+
- uses: actions/checkout@v7
53+
- uses: prefix-dev/setup-pixi@v0.10.2
5454
with:
5555
pixi-version: v0.70.0
5656
cache: true
@@ -78,15 +78,15 @@ jobs:
7878
shell: bash -el {0}
7979
- name: Upload coverage reports
8080
if: runner.os == 'Linux' && matrix.environment == 'py314'
81-
uses: codecov/codecov-action@v6.0.1
81+
uses: codecov/codecov-action@v7.0.0
8282
with:
8383
token: ${{ secrets.CODECOV_TOKEN }}
8484
run-ty:
8585
name: Run ty
8686
runs-on: ubuntu-latest
8787
steps:
88-
- uses: actions/checkout@v6
89-
- uses: prefix-dev/setup-pixi@v0.9.6
88+
- uses: actions/checkout@v7
89+
- uses: prefix-dev/setup-pixi@v0.10.2
9090
with:
9191
pixi-version: v0.70.0
9292
cache: true

‎.github/workflows/publish-to-pypi.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,9 @@ jobs:
88
permissions:
99
id-token: write
1010
steps:
11-
- uses: actions/checkout@v6
11+
- uses: actions/checkout@v7
1212
- name: Set up Python 3.12
13-
uses: actions/setup-python@v6
13+
uses: actions/setup-python@v7
1414
with:
1515
python-version: '3.12'
1616
- name: Install pypa/build

‎CHANGES.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ releases are available on [Anaconda.org](https://anaconda.org/conda-forge/ttsim)
66

77
## Unreleased
88

9+
- {gh}`154` Make `BooleanLevel` a frozen dataclass so beartype's package claw can
10+
decorate it. Turn `BeartypeClawDecorWarning` into a test-suite error so the next such
11+
hole fails loudly. ({ghuser}`MImmesberger`)
12+
13+
## v1.3.0 — 2026-08-20
14+
915
- {gh}`138` Implement GEP 10: Mandatory unit annotations for functions and parameters.
1016
Automatic checks of unit arithmetic and DAG unit consistency. ({ghuser}`MImmesberger`,
1117
{ghuser}`hmgaudecker`)

‎pyproject.toml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,10 +314,17 @@ ini_options.markers = [
314314
"skipif_numpy: skip test if backend is numpy",
315315
]
316316
ini_options.filterwarnings = [
317+
# A claw warning means beartype silently skipped an object, leaving a hole in
318+
# the package-wide runtime checking. Fail the run instead of burying it in the
319+
# warnings summary; the `ignore` below exempts the one known-benign case.
320+
"error::beartype.roar.BeartypeClawDecorWarning",
317321
"ignore:.*'tree.iter()'*:PendingDeprecationWarning",
318322
"ignore:.*Sorting*:FutureWarning",
319323
"ignore:.*XMLParser*:DeprecationWarning",
320324
"ignore:Explicitly requested dtype .*64 requested in zeros_like",
325+
# A non-callable metadata dataclass has nothing to type-check, so beartype's
326+
# package claw skips every `@interface_input` object with a warning.
327+
'ignore:Object "InterfaceInput\(:beartype.roar.BeartypeClawDecorWarning',
321328
"ignore:Repeated execution of the test suite",
322329
"ignore:The TerminalReporter.writer attribute is",
323330
"ignore:Using or importing the ABCs from 'collections'",

‎src/ttsim/_unit_inference.py‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
import functools
1010
import inspect
1111
from collections.abc import Callable, Mapping
12+
from dataclasses import dataclass
1213
from typing import (
1314
Any,
14-
NamedTuple,
1515
NoReturn,
1616
cast,
1717
)
@@ -198,7 +198,8 @@ def _has_grouping_component(unit: pint.Unit) -> bool:
198198
return bool(_grouping_levels_with_exponent(unit))
199199

200200

201-
class BooleanLevel(NamedTuple):
201+
@dataclass(frozen=True)
202+
class BooleanLevel:
202203
"""A unit's classification as a (possibly leveled) boolean."""
203204

204205
is_boolean: bool
@@ -1044,19 +1045,19 @@ def _logical_result(self, other: Any, op: str) -> _UnitCheckQuantity: # noqa: A
10441045
mismatch downcasts to the bare individual level. A bare literal carries no
10451046
unit and stays a lenient, bare boolean.
10461047
"""
1047-
self_is_boolean, self_level = _as_boolean_level(
1048+
self_boolean = _as_boolean_level(
10481049
unit=cast("pint.Unit", self.q.units), registry=self._registry
10491050
)
10501051
other_q = _unwrap(other)
10511052
if isinstance(other_q, _UnitCheckStructuredValue):
10521053
other_q._raise_used_as_quantity(op) # noqa: SLF001
10531054
if isinstance(other_q, pint.Quantity):
1054-
other_is_boolean, other_level = _as_boolean_level(
1055+
other_boolean = _as_boolean_level(
10551056
unit=cast("pint.Unit", other_q.units), registry=self._registry
10561057
)
10571058
else:
1058-
other_is_boolean, other_level = True, None
1059-
if not self_is_boolean or not other_is_boolean:
1059+
other_boolean = BooleanLevel(is_boolean=True, level=None)
1060+
if not self_boolean.is_boolean or not other_boolean.is_boolean:
10601061
right = (
10611062
cast("pint.Unit", other_q.units)
10621063
if isinstance(other_q, pint.Quantity)
@@ -1066,7 +1067,9 @@ def _logical_result(self, other: Any, op: str) -> _UnitCheckQuantity: # noqa: A
10661067
op=op, left=cast("pint.Unit", self.q.units), right=right
10671068
)
10681069
return self._controlled_bool_at(
1069-
level=_combined_boolean_level(left=self_level, right=other_level),
1070+
level=_combined_boolean_level(
1071+
left=self_boolean.level, right=other_boolean.level
1072+
),
10701073
label=self._composed_label(other=other, op=op),
10711074
)
10721075

@@ -1384,17 +1387,17 @@ def __rxor__(self, other: Any) -> _UnitCheckQuantity: # noqa: ANN401
13841387
return self._logical_result(other=other, op="^")
13851388

13861389
def __invert__(self) -> _UnitCheckQuantity:
1387-
is_boolean, level = _as_boolean_level(
1390+
boolean = _as_boolean_level(
13881391
unit=cast("pint.Unit", self.q.units), registry=self._registry
13891392
)
1390-
if not is_boolean:
1393+
if not boolean.is_boolean:
13911394
raise _UnitMixError(
13921395
op="~",
13931396
left=cast("pint.Unit", self.q.units),
13941397
right=_dimensionless_unit(self._registry),
13951398
)
13961399
return self._controlled_bool_at(
1397-
level=level,
1400+
level=boolean.level,
13981401
label=f"~{self._label}" if self._label is not None else None,
13991402
)
14001403

‎tests/test_beartype_gate.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,35 @@ def test_runtime_checking_fully_off_when_opted_out() -> None:
9696
"perimeter": "O0",
9797
"forwarder_checks": "0",
9898
}
99+
100+
101+
# Imports ttsim under the inherited env and reports every claw decoration that
102+
# beartype had to skip. A skipped decoration is a silent hole in the runtime
103+
# checking the claw is supposed to install package-wide.
104+
_CLAW_WARNING_PROBE = textwrap.dedent(
105+
"""
106+
import warnings
107+
108+
with warnings.catch_warnings(record=True) as caught:
109+
warnings.simplefilter("always")
110+
import ttsim
111+
112+
from beartype.roar import BeartypeClawDecorWarning
113+
114+
for warning in caught:
115+
if issubclass(warning.category, BeartypeClawDecorWarning):
116+
print(str(warning.message).splitlines()[0])
117+
"""
118+
)
119+
120+
121+
def test_import_leaves_no_claw_decoration_skipped() -> None:
122+
"""Importing ttsim decorates every object the claw touches, warning-free."""
123+
proc = subprocess.run( # noqa: S603
124+
[sys.executable, "-c", _CLAW_WARNING_PROBE],
125+
capture_output=True,
126+
text=True,
127+
check=False,
128+
)
129+
assert proc.returncode == 0, proc.stderr
130+
assert proc.stdout == ""

0 commit comments

Comments
 (0)