Skip to content

test(#239): flag bare type aliases at the floor, and report what cannot be decided - #241

Merged
fdaviddpt merged 1 commit into
mainfrom
feat/239-pep604-assign-guard
Jul 30, 2026
Merged

fdaviddpt merged 1 commit into
mainfrom
feat/239-pep604-assign-guard

Conversation

@fdaviddpt

Copy link
Copy Markdown
Contributor

The #237 guard walked AnnAssign annotations and isinstance()/issubclass() arguments. It did not walk Handler = str | None — an ast.Assign, evaluated at import in exactly the same way, raising the same TypeError on 3.9 and taking out the whole leg at collection. Same for TypeVar(..., bound=X | None), NewType("Id", X | None) and cast(X | None, v).

I re-ran the scan rather than trusting the issue's number: an independent AST walk over all 81 files in the guard's scope, checking every module- and class-level Assign whose value contains a BitOr (including inside Call nodes) and every cast/TypeVar/NewType call anywhere. Zero hits, confirming the issue. Nothing is broken today; this is about what the guard catches tomorrow.

The discriminator

The issue listed four candidates. I rejected all four and used a fifth.

Rejected:

  • Naming convention (CapWords = alias) — wrong the first time someone writes MASK = A | B, and wrong again on handler = str | None. It guesses.
  • typing proximity alone — needs name resolution it cannot actually do, and misses Handler = str | None in a module that imports nothing from typing.
  • Operand shape as "not a known int constant" — an open-ended negative; the set of things that aren't int flags is not enumerable.
  • Accept-and-document — I took this seriously and it was close. What tipped it is that a strictly-safe rule exists, so declining coverage would have been leaving free ground.

Shipped: a language-guaranteed type operand. A | chain is a union when any operand is something that cannot be bitwise-or'd on any Python:

  • the literal None — x | None is a TypeError on every version, so it has no legitimate bitwise reading;
  • a builtin type name (int, str, dict, …) — classes have no __or__ before 3.10, so int | str is always a union attempt;
  • a name imported from typing/typing_extensions, or a module attribute of one (typing.List);
  • a subscript of any of the above (Dict[str, int] | None).

A name the module rebinds itself (str = SomeFlag) stops counting as a type, and name collection deliberately over-collects — over-collecting only ever moves a verdict toward undecided, which is the safe direction.

The point is that this is not a judgement call. The language decides. MASK = READ | WRITE, FLAGS = re.I | re.M, MASK = 1 | 2 and total = a | b are all untouched, not because a heuristic tolerated them but because none of them contains an operand that is definitely a type.

What it misses, and which direction it errs

It misses an alias whose operands it cannot resolve: Ids = A | B where A and B are locally-defined or third-party names. That is a real violation and it ships unflagged.

I chose to err toward silence on a real violation rather than toward noise on legitimate bitwise code, and the asymmetry is the reason. A missed violation costs one red CI leg on the day someone writes it — visible, attributable, fixed in minutes. A false positive on MASK = READ | WRITE costs the guard its credibility permanently, and a guard nobody reads catches nothing at all. That is claude-supertool #577's lesson and the same reasoning by which #238 correctly declined to flag function-local annotations.

Also deliberately out of scope, and documented: function-local assignments (evaluated at call, not import — they fail one test, not a whole leg) and the body of if TYPE_CHECKING: (never executed at runtime).

The three-state contract

The miss is not silence. A | in an import-time assignment that resolves to neither a type nor arithmetic comes back as GuardReport.undecided, and the count appears in the report's reason on both ok and violations. The repo-wide test asserts that set is currently empty, so the first ambiguous construct anyone adds gets a human's eye once instead of disappearing.

An absence the checker produced, read as an absence in the world, is this repo's recurring defect. Building an instance of it into the guard written to catch one would have been a poor trade.

Two false positives fixed in passing

Both were already reachable by the old walk, and my addition would have made them worse:

  • if TYPE_CHECKING: bodies are no longer scanned (the else: branch still is);
  • X: TypeAlias = str | None now has its value checked — the future import rescues the annotation but not the assigned expression.

TDD

Tests first, run red: 19 failed, 28 passed — each new behaviour failing on its own assertion, with the 28 pre-existing (including every must-not-flag case) still green. Then implemented, green: 49 passed in the guard file, 1081 passed / 42 skipped for the full suite at 94% coverage.

"Would this test still pass if the discriminator did nothing?" is answerable no in both directions: flag nothing and the nine must-flag tests fail; flag everything and the seven must-not-flag tests fail; record nothing as undecided and the three-state tests fail.

Teeth check, both directions in one run — planted in pipeline/types.py, then removed:

E   pipeline/types.py:130  type alias assignment: str | None          <- Handler = str | None
E   AssertionError: ['  pipeline/types.py:131  READ | WRITE']         <- MASK = READ | WRITE, undecided, not a violation

Docs: CHANGELOG.md, and the README's "The Python floor guard" section now states the limitation plainly — a user who believes bare aliases are fully covered when they are not is worse off than one who reads the caveat.

Closes #239

…ot be decided

`Handler = str | None` is an ast.Assign, not an ast.AnnAssign. It is
evaluated at import exactly like the annotations the guard already walked,
and raises the same TypeError on 3.9 — a collection error that takes out the
whole leg. Same for TypeVar(bound=), NewType() and cast(). Zero live
instances today; this is about what the guard catches tomorrow.

The discriminator is the language, not a heuristic: a `|` chain is a union
when some operand cannot be bitwise-or'd on any Python (None, a builtin type
name, a name imported from typing, or a subscript of one). So it cannot
false-positive on `MASK = READ | WRITE`. It errs toward silence instead —
`Ids = A | B` is not flagged — because a guard people learn to ignore is
worse than no guard.

What it cannot classify comes back as GuardReport.undecided and is counted in
the report's reason, rather than passing quietly as clean.

Co-Authored-By: Max <noreply>
@fdaviddpt
fdaviddpt merged commit 2bb0d4f into main Jul 30, 2026
12 checks passed
@fdaviddpt
fdaviddpt deleted the feat/239-pep604-assign-guard branch July 30, 2026 17:11
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.

The floor guard walks annotations but not bare assignments, so a module-level Handler = str | None alias passes and still kills every 3.9 leg

2 participants