Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

lint: refuse a name bound twice in one scope of a changed Python file (#9618)

Daniel Han90f85fdbf8fd
diff --git a/.github/workflows/lint-ci.yml b/.github/workflows/lint-ci.yml
index 5e5c2c43ff8..95c9a8ba807 100644
--- a/.github/workflows/lint-ci.yml
+++ b/.github/workflows/lint-ci.yml
@@ -239,6 +239,80 @@ jobs:
python scripts/verify_import_hoist.py \
--before "$MERGE_BASE" --after "$HEAD_SHA" "${CHANGED[@]}"
+ - name: Duplicate-definition verifier self-test
+ # scripts/lint_duplicate_definitions.py refuses a name bound twice in one
+ # scope: two top-level copies of a def / class / constant, or a name
+ # imported twice. That is what a bad merge resolution leaves behind, and
+ # every other check here passes it -- compileall parses both copies, the
+ # ruff rule set (E9 / F63 / F7 / F82) has no F811, and the two copies
+ # usually differ only in their comments.
+ # Runs the tool's self-test cases, positive and negative, so a regression in the
+ # rule fails before we trust it on a diff. Stdlib-only, sub-second.
+ run: |
+ python scripts/lint_duplicate_definitions.py --self-test
+
+ - name: Duplicate definitions (changed Python files)
+ # Same merge-base reasoning as the import-hoist step above: diff the merge
+ # base against the PR head SHA so the range is the PR's own commits and
+ # not every base commit since the branch point.
+ #
+ # --diff-filter=ACMRT, not M: a bad resolution can just as easily land in a
+ # file the PR adds, and a rename that also edits the file is reported as R
+ # (R093 and so on), which an ACM filter would drop. T is there because a path
+ # that changes TYPE -- a symlink replaced by a regular .py file -- is reported
+ # as neither M nor A, so the newly active source reached the verifier as no
+ # path at all and the step passed having checked nothing.
+ #
+ # The verifier scans BOTH revisions and compares findings by identity, so a
+ # duplicate that was already in the file is printed and ignored while one
+ # this PR introduced fails. Comparing added LINES instead would miss the
+ # case where the new copy is inserted ABOVE the old one, since the finding
+ # is reported at the second, unchanged definition. There are 37 pre-existing
+ # findings on main today; they are a separate cleanup, not a reason to leave
+ # the gate off. Four of those are only visible once each control-flow branch is
+ # scanned on its own: a repeated `from unsloth import is_bfloat16_supported`
+ # inside one `if __name__ == "__main__":` block in four of the saving tests.
+ if: github.event_name == 'pull_request'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ MERGE_BASE=$(gh api \
+ "repos/${{ github.repository }}/compare/${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}" \
+ --jq .merge_base_commit.sha)
+ git fetch --no-tags --depth=1 origin "$MERGE_BASE"
+ # refs/pull/N/head moves. On a rerun of an older run, or if the branch
+ # advanced since the event, that ref is no longer $HEAD_SHA, and a depth-1
+ # clone would not have the pinned commit at all. Fetch the ref first (it is
+ # what makes the SHA reachable on a fork PR), then the SHA itself, then
+ # REFUSE to continue if it is still missing. The old shape hid exactly this:
+ # git diff failed, the pipeline's `|| true` produced an empty file list, and
+ # the step reported success having checked nothing.
+ git fetch --no-tags --depth=1 origin \
+ "refs/pull/${{ github.event.pull_request.number }}/head"
+ git fetch --no-tags --depth=1 origin "$HEAD_SHA" 2>/dev/null || true
+ if ! git cat-file -e "${HEAD_SHA}^{commit}" 2>/dev/null; then
+ echo "::error::head commit $HEAD_SHA is not available locally; refusing to skip the check"
+ exit 1
+ fi
+ # -z / -d '', because core.quotePath defaults on: a non-ASCII path comes out of a
+ # line-oriented git diff as "caf\303\251.py", whose suffix is .py" rather than
+ # .py, so the verifier would skip it and report success having checked nothing.
+ mapfile -d '' -t CHANGED < <(
+ git diff -z --name-only --diff-filter=ACMRT \
+ "$MERGE_BASE" "$HEAD_SHA" -- '*.py' \
+ | grep -zvE '(^|/)(unsloth_compiled_cache|node_modules|build|dist)/' || true
+ )
+ if [ "${#CHANGED[@]}" -eq 0 ]; then
+ echo "no changed Python files to check"
+ exit 0
+ fi
+ printf 'merge base: %s\n' "$MERGE_BASE"
+ printf 'pr head: %s\n' "$HEAD_SHA"
+ printf 'checking %d file(s)\n' "${#CHANGED[@]}"
+ python scripts/lint_duplicate_definitions.py \
+ --before "$MERGE_BASE" --after "$HEAD_SHA" "${CHANGED[@]}"
+
- name: No silent llama-server parallel-slot downgrades
# #7717 clamped --parallel to 1 whenever MTP resolved, costing batched
# callers 4x throughput. Launch fewer slots only for a real capability
diff --git a/scripts/lint_duplicate_definitions.py b/scripts/lint_duplicate_definitions.py
new file mode 100644
index 00000000000..e5bc3a38e50
--- /dev/null
+++ b/scripts/lint_duplicate_definitions.py
@@ -0,0 +1,788 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Refuse a name bound twice in one scope of a Python file.
+
+This exists for one failure mode: merge resolution. When git splits a function into a
+conflict over part of its body, the remainder can auto-merge below the resolved region
+as an ordinary addition, leaving two complete top-level copies of it. Nothing about the
+result looks wrong. Both copies are valid Python, so `compileall` passes. Ruff's rule set
+here (E9 / F63 / F7 / F82) does not include F811, and F811 would not fire on a duplicated
+constant or on a name repeated inside a single `from x import a, a` anyway. The two copies
+routinely differ only in their comments, so reading the diff does not flag it either.
+
+What it costs when it slips through is either everything or nothing, and nothing is worse:
+
+ - everything: the second copy runs a registration decorator again and the whole suite
+ fails to COLLECT, which at least stops the branch.
+ - nothing: the second copy silently wins, the first is dead code, and the tests that
+ covered the first now cover neither.
+
+Two checks, both AST-only. A regex cannot do this job -- a stray paren inside a comment is
+enough to make a hand-rolled scanner truncate and under-report, which is how the first of
+these landed.
+
+ 1. duplicate definition -- def / async def / class / ALL_CAPS assignment bound twice as a
+ DIRECT child of the same module or class body.
+ 2. duplicate import binding -- a name imported twice inside one `from x import a, a`, or
+ twice from the same module by two separate statements.
+
+Deliberately narrow, so a finding is always worth acting on:
+
+ - Branches are scanned INDEPENDENTLY of each other. One definition per branch of an
+ if/else, or a fallback import in try/except, is the normal conditional idiom and stays
+ clean; two copies inside ONE branch is the same merge damage as anywhere else.
+ - @typing.overload is exempt: any number of copies is legitimate. The accessor family is
+ exempt PER KIND -- one @x.setter, one @x.deleter, one @x.getter -- so a second accessor
+ of the same kind is still a finding. A bare @property is NOT exempt at all, since it is
+ the FIRST binding of the name and two of them are ordinary merge damage.
+ - Assignments are ALL_CAPS only, and `X = frozenset(X)` style self-transforms are exempt.
+ A lowercase module-level name being rebound is common enough to be noise.
+ - Imports are keyed on the name they BIND, with one carve-out: an IMPLICIT binding takes
+ whatever its source is called, so two of them from different sources are the ordinary
+ `import urllib.parse` / `import urllib.request` and `from a import x` / `from b import x`
+ shapes and stay legitimate. An explicit `as` alias is a name the author chose, so a second
+ binding of it is always a dead first binding.
+
+Exit codes: 0 = clean, 1 = findings, 2 = usage error.
+
+Run from repo root:
+ python3 scripts/lint_duplicate_definitions.py --self-test
+ python3 scripts/lint_duplicate_definitions.py unsloth studio # paths or dirs
+ python3 scripts/lint_duplicate_definitions.py --before SHA --after SHA FILE.py [FILE.py ...]
+
+In --before/--after mode both revisions are scanned and their findings compared by identity,
+so a finding fails only if the diff INTRODUCED it. A duplicate that was already there is
+printed and does not fail, which keeps the gate on the branch that creates one without
+blocking an unrelated branch that touches the same file.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import io
+import re
+import subprocess
+import sys
+import tokenize
+from collections import Counter
+from pathlib import Path
+from typing import NamedTuple
+
+
+class Finding(NamedTuple):
+ """`key` identifies WHICH duplicate this is, independently of where it sits.
+
+ Compare mode needs that. Gating on "is this line new" is not sound: a merge that inserts
+ the FIRST copy above an existing definition reports on the SECOND, unchanged line, and a
+ duplicate alias added to a multi-line import reports at the statement's opening line.
+ Both are the exact bug this gate exists for, and both would read as pre-existing. So the
+ before and after revisions are scanned and their finding keys compared.
+ """
+
+ line: int
+ key: str
+ message: str
+
+
+OVERLOAD_DECORATORS = {"overload", "typing.overload", "typing_extensions.overload"}
+PROPERTY_ATTRS = {"setter", "deleter", "getter"}
+SKIP_DIRS = re.compile(r"(^|/)(unsloth_compiled_cache|node_modules|build|dist|\.git|\.venv)/")
+
+
+def _decorator_name(node) -> str:
+ """Dotted name of a decorator expression, ignoring any call arguments."""
+ if isinstance(node, ast.Call):
+ node = node.func
+ parts = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if not isinstance(node, ast.Name):
+ return ""
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+
+def _overload_names(tree) -> set:
+ """Every spelling of `typing.overload` this module actually binds.
+
+ The exact-name set alone reads the decorator as written, so `import typing as t` with
+ `@t.overload`, or `from typing import overload as ov` with `@ov`, was not recognised and
+ the overload signatures were reported as duplicate definitions. That is the wrong way for
+ a gate to be wrong: a conventional typing pattern would block CI on correct code.
+
+ MODULE-SCOPED, and not by a whole-tree walk. An alias bound INSIDE a function is not in
+ effect at module level, so collecting it globally let a local `import typing as t` exempt
+ module-level `@t.overload` definitions where `t` is something else entirely -- widening the
+ exemption is the one direction that hides merge damage.
+
+ Nested statements are still descended into, because the conventional spellings are wrapped:
+ `try: from typing import overload / except ImportError: from typing_extensions import ...`
+ is an ast.Try at module level. Function and class bodies are what get skipped.
+ """
+ return _overload_names_in(tree.body, OVERLOAD_DECORATORS)
+
+
+def _overload_names_in(body, base) -> set:
+ """`base` plus every overload spelling bound directly by THIS body.
+
+ Called once for the module and again for each class body, because a class that does its own
+ `import typing as t` binds `t` in the class namespace, where its `@t.overload` methods resolve
+ it. Collecting only module-level aliases reported those valid overloads as duplicates, which
+ blocks CI on correct code.
+ """
+ names: set = set(base)
+ modules = {"typing", "typing_extensions"}
+
+ def visit(nested) -> None:
+ for node in nested:
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ continue # a binding in here belongs to a scope of its own, not to this one
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ if alias.name in modules and alias.asname:
+ names.add(f"{alias.asname}.overload")
+ elif isinstance(node, ast.ImportFrom) and node.module in modules and not node.level:
+ for alias in node.names:
+ if alias.name == "overload" and alias.asname:
+ names.add(alias.asname)
+ for field in ("body", "orelse", "finalbody"):
+ visit(getattr(node, field, []) or [])
+ for handler in getattr(node, "handlers", []) or []:
+ visit(handler.body)
+ # Same blind spot as _branch_bodies, mirrored: an alias bound inside a match case
+ # would go unseen and its @t.overload defs would read as a duplicate.
+ for case in getattr(node, "cases", []) or []:
+ visit(case.body)
+
+ visit(body)
+ return names
+
+
+def _branch_bodies(node):
+ """Each nested statement body of a control-flow node, to be scanned INDEPENDENTLY.
+
+ One definition per branch of an if/else, or a fallback import in try/except, is the normal
+ conditional idiom, so the branches are never compared with each other or with the body around
+ them. But two copies of one def inside ONE branch is the same merge damage as anywhere else,
+ and skipping the branch entirely meant never looking.
+
+ Functions and classes are excluded: a function body is a scope this gate does not scan, and a
+ class body is recursed into separately so it gets its own name prefix and its own aliases.
+ """
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return
+ for field in ("body", "orelse", "finalbody"):
+ nested = getattr(node, field, None)
+ if isinstance(nested, list) and nested:
+ yield nested
+ for handler in getattr(node, "handlers", []) or []:
+ if handler.body:
+ yield handler.body
+ # A match keeps its branches in `cases[*].body`, so the loop above walked straight past
+ # them and two copies of one def inside a SINGLE case scanned clean. Each case is a
+ # branch on the same terms as an if/else arm: yielded separately, never compared with a
+ # sibling case, where one definition apiece is the ordinary conditional idiom.
+ for case in getattr(node, "cases", []) or []:
+ if case.body:
+ yield case.body
+
+
+def _is_overload_def(node, overloads) -> bool:
+ """True for `@overload`, the one family where any number of copies is legitimate."""
+ return any(
+ _decorator_name(decorator) in overloads for decorator in getattr(node, "decorator_list", [])
+ )
+
+
+def _accessor_kind(node) -> str:
+ """`setter` / `deleter` / `getter` for the accessor form, else "".
+
+ `@property` itself is NOT one of them. It is the FIRST binding of the name, so exempting it
+ hid two complete copies of a property in one class, which is the same merge damage as any
+ other duplicated def. What legitimately rebinds is `@v.setter` / `@v.deleter` / `@v.getter`.
+ """
+ for decorator in getattr(node, "decorator_list", []):
+ name = _decorator_name(decorator)
+ if name.count(".") == 1 and name.split(".")[1] in PROPERTY_ATTRS:
+ return name.split(".")[1]
+ return ""
+
+
+def _constant_targets(target):
+ """The uppercase names a single assignment target binds.
+
+ A tuple target is not one binding but several: `B, H, N, D = 1, 16, 50345, 128` is a
+ shape this repo declares module constants with, and duplicating that line rebinds
+ every one of them at once.
+ """
+ if isinstance(target, ast.Name):
+ return [target.id] if target.id.isupper() else []
+ if isinstance(target, (ast.Tuple, ast.List)):
+ return [name for element in target.elts for name in _constant_targets(element)]
+ return []
+
+
+def _defined_names(node, overloads):
+ """[(name, kind)] bound by a direct child of a module/class body."""
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ if _is_overload_def(node, overloads):
+ return []
+ # ONE ACCESSOR OF EACH KIND IS LEGITIMATE; A SECOND OF THE SAME KIND IS NOT. Discarding
+ # every accessor meant a getter followed by two copies of the same `@value.setter`
+ # scanned clean, with the later setter silently replacing the earlier one -- which is
+ # exactly the merge damage this gate is for. Keying on the KIND keeps the getter and the
+ # setter apart while making two setters collide.
+ kind = _accessor_kind(node)
+ if kind:
+ return [(f"{node.name}.{kind}", f"{kind} accessor")]
+ return [(node.name, "def")]
+ if isinstance(node, ast.ClassDef):
+ return [(node.name, "class")]
+ # `X: int = 1` is an AnnAssign, not an Assign, and a typed module-level constant is
+ # common in this repo (MAX_FUSED_SIZE: int = 65536). Duplicating one is the same bug.
+ # EVERY target, not a lone one: a chained `N = K = 256` (which this repo writes, in
+ # tests/test_grouped_gemm_optional_gather_indices.py) parks two names in one statement,
+ # and requiring exactly one target dropped both, so duplicating the line rebound both
+ # while the scan reported clean.
+ if isinstance(node, ast.Assign):
+ targets, value = node.targets, node.value
+ elif isinstance(node, ast.AnnAssign) and node.value is not None:
+ targets, value = [node.target], node.value
+ else:
+ return []
+ # `X = frozenset(X)` / `X = X + (...)` transforms a constant rather than redefining
+ # it. Only a value computed WITHOUT the old one replaces it, decided per name so
+ # that `A, B = B, A` exempts both while `A, B = 1, 2` exempts neither.
+ referenced = {sub.id for sub in ast.walk(value) if isinstance(sub, ast.Name)}
+ names = []
+ for target in targets:
+ for name in _constant_targets(target):
+ # One statement binding a name twice (`X = X = 1`) still binds it once, so it
+ # is not the two-copies damage this looks for.
+ if name not in referenced and name not in names:
+ names.append(name)
+ return [(name, "constant") for name in names]
+
+
+def _scope_duplicates(body, scope, out, overloads, module_overloads) -> None:
+ """Names bound twice as direct children of one body; recurses into class bodies.
+
+ `overloads` is what a decorator in THIS body resolves to; `module_overloads` is what a
+ decorator in a fresh class body resolves to. They differ because a class body is not part
+ of the scope chain of a class nested inside it.
+ """
+ seen = {}
+ for node in body:
+ for name, kind in _defined_names(node, overloads):
+ if name in seen:
+ first_line, first_kind = seen[name]
+ out.append(
+ Finding(
+ node.lineno,
+ f"def:{scope}{name}",
+ f"{scope}{name} is defined twice "
+ f"({first_kind} at line {first_line}, {kind} here)",
+ )
+ )
+ else:
+ seen[name] = (node.lineno, kind)
+ if isinstance(node, ast.ClassDef):
+ # The class gets the MODULE's aliases plus any it binds itself -- never the
+ # enclosing class's. "The scope of names defined in a class block is limited to
+ # the class block", and a class body resolves an unbound name in the GLOBAL
+ # namespace, so a nested class does not see `import typing as t` from the class
+ # around it. Passing the outer set down exempted `@t.overload` in the inner class
+ # where `t` is whatever the MODULE bound it to, and two copies of one def scanned
+ # clean -- widening the exemption is the one direction that hides merge damage.
+ _scope_duplicates(
+ node.body,
+ f"{scope}{node.name}.",
+ out,
+ _overload_names_in(node.body, module_overloads),
+ module_overloads,
+ )
+ for nested in _branch_bodies(node):
+ # A control-flow branch is not a scope, so it keeps the aliases of the body it
+ # sits in -- only a class body starts over.
+ _scope_duplicates(nested, scope, out, overloads, module_overloads)
+
+
+def _import_duplicates(body, scope, out) -> None:
+ """A name imported twice within one statement, or twice from the same module.
+
+ Keyed on the name each alias BINDS, not on the name it comes from: `from m import x as v`
+ followed by `from m import y as v` binds `v` twice and the second silently wins, which is
+ the dead-binding this is here to catch. Plain `import a.b` keeps the full dotted path in
+ its key too, since `import urllib.parse` beside `import urllib.request` is correct.
+ """
+ seen_implicit: dict = {} # (bound name, source) -> line; a name nobody chose
+ seen_explicit: dict = {} # bound name -> line; a name the author wrote after `as`
+ for node in body:
+ if isinstance(node, ast.ImportFrom):
+ # `level` carries the leading dots, so `from .a` and `from ..a` stay distinct.
+ module = f"{'.' * node.level}{node.module or ''}"
+ elif isinstance(node, ast.Import):
+ module = None # the source is per-alias for a plain import, not per-statement
+ else:
+ # Class bodies are scanned too: two `from m import x` inside one class bind x
+ # twice in that scope exactly as they would at module level.
+ if isinstance(node, ast.ClassDef):
+ _import_duplicates(node.body, f"{scope}{node.name}.", out)
+ # Each control-flow branch on its own: `try: import x / except: import x` is the
+ # fallback idiom and stays clean, while two of the same import INSIDE one branch is
+ # the ordinary duplicate this looks for and used to be skipped with the branch.
+ for nested in _branch_bodies(node):
+ _import_duplicates(nested, scope, out)
+ continue
+ for alias in node.names:
+ if alias.name == "*":
+ continue
+ # `import a.b` binds `a`, not `a.b`; only an `as` clause binds the dotted name.
+ # Using `alias.asname` raw here instead missed `import urllib.parse` followed by
+ # `import urllib.parse as urllib`, which silently repoints `urllib` from the
+ # package to the submodule.
+ source = module if module is not None else alias.name
+ bound = alias.asname or (alias.name if module is not None else alias.name.split(".")[0])
+ # Keyed on the BOUND NAME, because that is what gets shadowed, with one carve-out
+ # for the case where the name was never chosen: an IMPLICIT binding takes whatever
+ # the source happens to be called, so two of them from different sources are the
+ # ordinary `import urllib.parse` / `import urllib.request` and `from a import x` /
+ # `from b import x` shapes and stay legitimate. An EXPLICIT `as` alias is a name the
+ # author picked, so a second binding of it is always dead -- which is how
+ # `import urllib.parse as client` beside `import urllib.request as client` slipped
+ # past a key that carried the source.
+ implicit = alias.asname is None
+ # EVERY IMPLICIT SOURCE IS REMEMBERED, not just the first. Keeping one entry per
+ # bound name and skipping the legitimate different-source case left `seen` pointing
+ # at the first source forever, so in `from a import x` / `from b import x` /
+ # `from b import x` the third was compared with `a`, looked like the legitimate
+ # shape again, and the exact repeat of `b` went unreported.
+ #
+ # So an implicit binding collides with the SAME source, and an explicit one -- a name
+ # the author chose -- collides with any earlier binding of that name at all.
+ first = seen_explicit.get(bound)
+ if implicit:
+ first = seen_implicit.get((bound, source), first)
+ elif first is None:
+ first = min(
+ (line for (name, _), line in seen_implicit.items() if name == bound),
+ default = None,
+ )
+ if first is not None:
+ where = (
+ "twice in this statement"
+ if first == node.lineno
+ else f"twice from the same module (first at line {first})"
+ )
+ out.append(
+ Finding(
+ node.lineno,
+ # The emitted identity must mirror the detection key. Keyed on the
+ # bound name alone, two DIFFERENT plain-import duplicates both read
+ # as `import:None:x`, so compare mode charged a newly introduced one
+ # against a pre-existing counter entry and passed.
+ #
+ # DELIMITED, because `scope` ends in a dot and `source` may contain
+ # them: a module-level `from A.m import x` and a `from m import x`
+ # inside `class A` both spelled `import:A.m:x`, so compare mode let a
+ # branch swap one for the other and charged the new one to the old.
+ f"import:{scope}|{source}:{bound}",
+ f"{scope}{bound} is imported {where}",
+ )
+ )
+ elif implicit:
+ seen_implicit[(bound, source)] = node.lineno
+ else:
+ seen_explicit[bound] = node.lineno
+
+
+def scan_source(source: str, filename: str = "<unknown>"):
+ """Findings for one Python source string. A file that does not parse is itself a finding."""
+ try:
+ tree = ast.parse(source, filename = filename)
+ except SyntaxError as exc:
+ return [Finding(exc.lineno or 0, "parse", f"does not parse ({exc.msg})")]
+ found = []
+ module_overloads = _overload_names(tree)
+ _scope_duplicates(tree.body, "", found, module_overloads, module_overloads)
+ _import_duplicates(tree.body, "", found)
+ return sorted(found)
+
+
+def _git(args, cwd = None):
+ return subprocess.run(["git", *args], cwd = cwd, capture_output = True, text = True)
+
+
+def _decode_source(data: bytes) -> str:
+ """Decode Python source by ITS OWN declared encoding, the way the parser would.
+
+ `text = True` decodes with the runner's locale, so a valid `# coding: cp1252` file holding
+ a non-UTF-8 byte raised UnicodeDecodeError out of `subprocess` and took the whole run down
+ -- on an unrelated edit, and on a file `compileall` and ruff both accept. PEP 263 says the
+ declaration decides, and `tokenize.detect_encoding` is the parser's own reader for it.
+ """
+ try:
+ encoding, _ = tokenize.detect_encoding(io.BytesIO(data).readline)
+ except SyntaxError:
+ encoding = "utf-8"
+ return data.decode(encoding)
+
+
+def _revision_findings(revision: str, path: str):
+ """Findings for `path` at `revision`, or None if the file does not exist there."""
+ shown = subprocess.run(["git", "show", f"{revision}:{path}"], capture_output = True)
+ if shown.returncode != 0:
+ return None
+ try:
+ source = _decode_source(shown.stdout)
+ except (UnicodeDecodeError, LookupError) as exc:
+ return [Finding(0, "parse", f"does not decode ({exc})")]
+ return scan_source(source, f"{revision}:{path}")
+
+
+def _rename_map(before: str, after: str):
+ """{new path: old path} for the renames in this range.
+
+ The changed-file sweep reports a renamed file under its NEW name, so looking the before
+ side up under that name finds nothing and every finding in it reads as introduced. A
+ branch that only moves a file carrying one of the duplicates already on main would then
+ be blocked for a duplicate it did not write.
+ """
+ # -z, because git quotes and backslash-escapes any non-ASCII path by default
+ # (core.quotePath), and the escaped spelling matches nothing. Under -z each rename is
+ # three NUL-terminated records, "R100", old, new -- the status is its own field rather
+ # than tab-joined to the paths.
+ listed = _git(["diff", "--name-status", "-z", "-M", "--diff-filter=R", before, after])
+ if listed.returncode != 0:
+ return {}
+ fields = [field for field in listed.stdout.split("\0") if field]
+ renames = {}
+ for index in range(0, len(fields) - 2, 3):
+ status, old, new = fields[index : index + 3]
+ if status.startswith("R"):
+ renames[new] = old
+ return renames
+
+
+def _iter_paths(targets):
+ for target in targets:
+ path = Path(target)
+ if path.is_dir():
+ for child in sorted(path.rglob("*.py")):
+ if not SKIP_DIRS.search(child.as_posix()):
+ yield child
+ elif path.suffix == ".py":
+ yield path
+
+
+_SELF_TEST_CASES = [
+ # (expected finding count, source)
+ # 1. The real artefact: two top-level copies of one def, differing only in comments.
+ (
+ 1,
+ "def toggle(page):\n # click it\n page.click('#r')\n\n\n"
+ "def toggle(page):\n # open the panel\n page.click('#r')\n",
+ ),
+ # 2. The other real one: a name repeated inside a single ImportFrom.
+ (1, "from floor_table import latest_attempt_rows, refuse_collisions, latest_attempt_rows\n"),
+ # 3. A constant defined twice.
+ (1, "TOGGLE_JS = '() => 1'\nOTHER = 2\nTOGGLE_JS = '() => 2'\n"),
+ # 4. A class, and a method inside one.
+ (1, "class A:\n pass\n\n\nclass A:\n pass\n"),
+ (1, "class A:\n def go(self):\n pass\n\n def go(self):\n pass\n"),
+ # 5. The same name imported twice from the same module by two statements.
+ (1, "from a import x\nfrom a import x\n"),
+ # 6. A stray paren inside a comment must not truncate the scan (the regex version did).
+ (1, "def go(): # takes (a, b\n pass\n\n\ndef go():\n pass\n"),
+ # 7. A conflict marker left in the tree does not parse, and that is a finding.
+ (1, "<<<<<<< HEAD\ndef go():\n pass\n"),
+ # 8. A typed constant is an AnnAssign, and duplicating one is the same bug.
+ (1, "MAX_FUSED_SIZE: int = 65536\nMAX_FUSED_SIZE: int = 131072\n"),
+ (1, "REGISTRY: dict = {}\nOTHER = 1\nREGISTRY = {'a': 1}\n"),
+ # 9. Two aliases from one module landing on the same bound name: the second wins and
+ # the first is dead, which is the silent half of this bug.
+ (1, "from m import x as value\nfrom m import y as value\n"),
+ (1, "from m import x as value, y as value\n"),
+ # 10. A class body is a scope too, for imports as well as for defs.
+ (1, "class A:\n from m import x\n from m import x\n"),
+ # 11. A duplicated @property getter. Exempting @property hid two complete copies.
+ (
+ 1,
+ "class A:\n @property\n def v(self):\n return 1\n\n"
+ " @property\n def v(self):\n return 2\n",
+ ),
+ (
+ 1,
+ "import functools\n\n\nclass A:\n @functools.cached_property\n"
+ " def v(self):\n return 1\n\n @functools.cached_property\n"
+ " def v(self):\n return 2\n",
+ ),
+ # 12. Constants declared together in one tuple target: duplicating the line rebinds
+ # every one of them, so each is its own finding.
+ (4, "B, H, N, D = 1, 16, 50345, 128\nB, H, N, D = 2, 3, 4, 5\n"),
+ # 13. A plain import binds the ROOT of its dotted path, so this repoints `urllib` from
+ # the package to the submodule and the first binding is dead.
+ (1, "import urllib.parse\nimport urllib.parse as urllib\n"),
+ # Negative controls: each of these is correct code and must report nothing.
+ (0, "if FAST:\n def go():\n pass\nelse:\n def go():\n pass\n"),
+ (0, "try:\n from fast import x\nexcept ImportError:\n from slow import x\n"),
+ (
+ 0,
+ "from typing import overload\n\n\n@overload\ndef go(a: int) -> int: ...\n"
+ "@overload\ndef go(a: str) -> str: ...\ndef go(a):\n return a\n",
+ ),
+ (
+ 0,
+ "class A:\n @property\n def v(self):\n return self._v\n\n"
+ " @v.setter\n def v(self, x):\n self._v = x\n",
+ ),
+ (0, "import urllib.parse\nimport urllib.request\n"),
+ (0, "import sys as _sys\nimport sys\n"),
+ (0, "from a import x\nfrom b import x\n"),
+ (0, "NAMES = ['a']\nNAMES = frozenset(n.lower() for n in NAMES)\n"),
+ (0, "COUNT: int = 1\nCOUNT = COUNT + 1\n"),
+ (0, "REGISTRY: dict\nREGISTRY = {}\n"), # a bare annotation binds nothing
+ (0, "from m import x\nfrom m import x as other\n"),
+ (0, "ROWS = (1,)\nROWS = ROWS + (2,)\n"),
+ # A tuple self-transform is decided per name, so a swap exempts both sides.
+ (0, "A = 1\nB = 2\nA, B = B, A\n"),
+ # Distinct submodules of one package each bind the package name and are correct.
+ (0, "import urllib.parse as parse\nimport urllib.request as request\n"),
+ (0, "value = 1\nvalue = 2\n"),
+ (0, "import os\nfrom a import b\n\nX = 1\n\n\ndef go():\n return os, b, X\n"),
+ # A chained assignment binds every name in the chain, so duplicating the line rebinds
+ # every one of them. `N = K = 256` is written in this repo; requiring a single target
+ # dropped the whole statement and the duplicate went unreported.
+ (2, "N = K = 256\nN = K = 512\n"),
+ (0, "N = K = 256\nM = 512\n"),
+ (0, "X = X = 1\n"), # one statement, one live binding
+ # Overload signatures reached through an import alias are still overloads. Reporting
+ # them is a FALSE POSITIVE that blocks CI on a conventional typing pattern.
+ (
+ 0,
+ "import typing as t\[email protected]\ndef f(x: int) -> int: ...\n"
+ "@t.overload\ndef f(x: str) -> str: ...\ndef f(x):\n return x\n",
+ ),
+ (
+ 0,
+ "from typing import overload as ov\n@ov\ndef f(x: int) -> int: ...\n"
+ "@ov\ndef f(x: str) -> str: ...\ndef f(x):\n return x\n",
+ ),
+ # ...but the alias has to be typing's. `t` bound to anything else is not an overload.
+ (1, "import types as t\[email protected]\ndef f(x): ...\[email protected]\ndef f(x): ...\n"),
+ # One explicit alias, two sources: the second silently replaces the first, so the first
+ # is a dead binding. Keying on the source made the two look unrelated.
+ (1, "import urllib.parse as client\nimport urllib.request as client\n"),
+ (1, "from os import path as v\nfrom sys import modules as v\n"),
+ # The shape that legitimately binds one name twice, and must stay legitimate: two plain
+ # imports of different submodules, both binding the package root.
+ (0, "import urllib.parse\nimport urllib.request\n"),
+ # Still caught: the same package root rebound from the package to a submodule.
+ (1, "import urllib.parse\nimport urllib.parse as urllib\n"),
+ # EVERY implicit source is remembered, not just the first. Keeping one entry per bound name
+ # compared the third statement with the FIRST source, which looked like the legitimate
+ # different-source shape again, so an exact repeat went unreported.
+ (1, "from a import x\nfrom b import x\nfrom b import x\n"),
+ (1, "import urllib.parse\nimport urllib.request\nimport urllib.request\n"),
+ (0, "from a import x\nfrom b import x\nfrom c import x\n"),
+ # An explicit alias collides with a name already bound implicitly, in either order.
+ (1, "import urllib.parse as urllib\nimport urllib.request\n"),
+ # A typing alias bound INSIDE a function is not in effect at module level, so it may not
+ # exempt a module-level decorator. Widening the exemption is what hides merge damage.
+ (
+ 1,
+ "import types as t\n\n\ndef helper():\n import typing as t\n return t\n\n\n"
+ "@t.overload\ndef f(x): ...\[email protected]\ndef f(x): ...\n",
+ ),
+ # ...but the conventional wrapped spellings are still found, since they are module level.
+ (
+ 0,
+ "try:\n from typing import overload as ov\nexcept ImportError:\n"
+ " from typing_extensions import overload as ov\n"
+ "@ov\ndef f(x: int) -> int: ...\n@ov\ndef f(x: str) -> str: ...\ndef f(x):\n return x\n",
+ ),
+ # ONE accessor of each kind is legitimate; a SECOND of the same kind replaces the first.
+ (
+ 1,
+ "class C:\n @property\n def v(self):\n return 1\n"
+ " @v.setter\n def v(self, x):\n pass\n"
+ " @v.setter\n def v(self, x):\n pass\n",
+ ),
+ (
+ 0,
+ "class C:\n @property\n def v(self):\n return 1\n"
+ " @v.setter\n def v(self, x):\n pass\n"
+ " @v.deleter\n def v(self):\n pass\n",
+ ),
+ # A class binds its own names, so a class-local typing alias resolves its own decorators.
+ (
+ 0,
+ "class C:\n import typing as t\n"
+ " @t.overload\n def f(self, x: int): ...\n"
+ " @t.overload\n def f(self, x: str): ...\n def f(self, x):\n return x\n",
+ ),
+ # ...but that alias stops at ITS OWN class body. A class nested inside it resolves an
+ # unbound name in the MODULE namespace, not in the class around it, so `@t.overload` in
+ # the inner class is `types.overload` here and the two copies are ordinary merge damage.
+ # Handing the outer class's aliases down exempted both and the scan reported clean.
+ (
+ 1,
+ "import types as t\n\n\nclass Outer:\n import typing as t\n\n class Inner:\n"
+ " @t.overload\n def f(self, x: int): ...\n"
+ " @t.overload\n def f(self, x: str): ...\n",
+ ),
+ # A nested class binding the alias ITSELF still resolves its own decorators.
+ (
+ 0,
+ "import types as t\n\n\nclass Outer:\n class Inner:\n import typing as t\n"
+ " @t.overload\n def f(self, x: int): ...\n"
+ " @t.overload\n def f(self, x: str): ...\n",
+ ),
+ # ...and a MODULE-level alias reaches every class body at every depth, so narrowing the
+ # inner class to its own bindings alone would be a false positive on correct code.
+ (
+ 0,
+ "import typing as t\n\n\nclass Outer:\n class Inner:\n"
+ " @t.overload\n def f(self, x: int): ...\n"
+ " @t.overload\n def f(self, x: str): ...\n",
+ ),
+ # Each control-flow branch scanned on its own: duplicated INSIDE one branch is merge damage,
+ # one per branch is the conditional idiom.
+ (
+ 1,
+ "import os\nif os.name:\n def go():\n return 1\n def go():\n return 2\n",
+ ),
+ (
+ 0,
+ "import os\nif os.name:\n def go():\n return 1\nelse:\n"
+ " def go():\n return 2\n",
+ ),
+ (0, "try:\n import json\nexcept ImportError:\n import json\n"),
+ (1, "try:\n import json\n import json\nexcept ImportError:\n pass\n"),
+]
+
+# Guarded, not inlined above: `match` is 3.10 syntax and this tool supports 3.9, where
+# ast.parse raises SyntaxError and every case below would report a parse finding instead.
+if sys.version_info >= (3, 10):
+ _SELF_TEST_CASES += [
+ (
+ 1,
+ "import os\nmatch os.name:\n case 'posix':\n def go():\n"
+ " return 1\n def go():\n return 2\n"
+ " case _:\n pass\n",
+ ),
+ (
+ 1,
+ "match 1:\n case 1:\n import json\n import json\n"
+ " case _:\n pass\n",
+ ),
+ # One definition per case is the conditional idiom, exactly as for if/else.
+ (
+ 0,
+ "match 1:\n case 1:\n def go():\n return 1\n"
+ " case 2:\n def go():\n return 2\n",
+ ),
+ # The alias walk reaches into a case too, so this stays an overload pair.
+ (
+ 0,
+ "match 1:\n case 1:\n import typing as t\n\n @t.overload\n"
+ " def f(x: int): ...\n\n @t.overload\n def f(x: str): ...\n",
+ ),
+ ]
+
+
+def _self_test() -> int:
+ failures = 0
+ for expected, source in _SELF_TEST_CASES:
+ got = len(scan_source(source, "<self-test>"))
+ if got != expected:
+ failures += 1
+ print(
+ f"self-test: expected {expected} finding(s), got {got} for:\n{source}",
+ file = sys.stderr,
+ )
+ if failures:
+ print(f"self-test FAILED ({failures} case(s))", file = sys.stderr)
+ return 1
+ print(f"self-test passed ({len(_SELF_TEST_CASES)} cases)")
+ return 0
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(
+ description = __doc__, formatter_class = argparse.RawDescriptionHelpFormatter
+ )
+ parser.add_argument("targets", nargs = "*", help = "Python files or directories to scan")
+ parser.add_argument("--self-test", action = "store_true", help = "check the rule, scan nothing")
+ parser.add_argument("--before", help = "base revision; only findings this diff adds fail")
+ parser.add_argument("--after", help = "head revision, used with --before")
+ args = parser.parse_args()
+
+ if args.self_test:
+ return _self_test()
+ if bool(args.before) != bool(args.after):
+ print("--before and --after must be given together", file = sys.stderr)
+ return 2
+ if not args.targets:
+ print("nothing to scan (pass files or directories, or --self-test)", file = sys.stderr)
+ return 2
+
+ paths = list(_iter_paths(args.targets))
+ blocking, existing = [], []
+ renames = _rename_map(args.before, args.after) if args.before else {}
+ for path in paths:
+ if args.before:
+ # Read both revisions out of git rather than the working tree. On a
+ # pull_request event the checkout is refs/pull/N/merge, which is neither end
+ # of the range being judged.
+ after = _revision_findings(args.after, str(path))
+ if after is None:
+ continue # not present at the head revision (deleted, or renamed away)
+ # Only follow a rename back to a path that was ITSELF Python. Renaming
+ # `mod.txt` to `mod.py` is what makes those definitions active code, so the
+ # duplicates in it are introduced by this branch, not inherited: mapping onto
+ # the non-Python original consumed them as pre-existing.
+ old = renames.get(str(path), str(path))
+ before = _revision_findings(args.before, old) if old.endswith(".py") else None
+ # A file the branch ADDS has no before side, so every finding in it is new.
+ was = Counter(f.key for f in (before or []))
+ for finding in after:
+ text = f"{path}:{finding.line}: {finding.message}"
+ if was[finding.key] > 0:
+ was[finding.key] -= 1
+ existing.append(text)
+ else:
+ blocking.append(text)
+ else:
+ try:
+ source = _decode_source(path.read_bytes())
+ except (OSError, UnicodeDecodeError) as exc:
+ blocking.append(f"{path}: unreadable ({exc})")
+ continue
+ for finding in scan_source(source, str(path)):
+ blocking.append(f"{path}:{finding.line}: {finding.message}")
+
+ if existing:
+ print(f"pre-existing in files this diff touches ({len(existing)}; not failing):")
+ for finding in existing:
+ print(f" {finding}")
+ if blocking:
+ print(f"duplicate definitions ({len(blocking)}):")
+ for finding in blocking:
+ print(f" {finding}")
+ print(
+ "A name bound twice in one scope is almost always merge damage: delete the "
+ "duplicate copy. The later one wins silently, so the first is dead code and "
+ "whatever tested it now tests nothing."
+ )
+ return 1
+ print(f"clean: {len(paths)} file(s) checked")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_lint_duplicate_definitions.py b/tests/test_lint_duplicate_definitions.py
new file mode 100644
index 00000000000..b9b77fd35e4
--- /dev/null
+++ b/tests/test_lint_duplicate_definitions.py
@@ -0,0 +1,224 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""Compare mode of the duplicate-definition gate, driven over a throwaway git repo.
+
+`--self-test` already covers the AST rule. What is only reachable through git is the
+question compare mode answers: did THIS diff introduce the duplicate, or was it already
+there? Getting that wrong in either direction is how the gate stops being useful, so each
+case here runs the real script against real commits.
+"""
+
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "lint_duplicate_definitions.py"
+
+DUPLICATE = "def go():\n return 1\n\n\ndef go():\n return 2\n"
+SINGLE = "def go():\n return 1\n"
+
+
+def _git(repo, *args):
+ done = subprocess.run(["git", *args], cwd = repo, capture_output = True, text = True, check = True)
+ return done.stdout.strip()
+
+
+def _commit(repo, message):
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-q", "-m", message)
+ return _git(repo, "rev-parse", "HEAD")
+
+
+def repo(tmp_path):
+ _git(tmp_path, "init", "-q", ".")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "test")
+ return tmp_path
+
+
+def _run(repo, before, after, *paths):
+ return subprocess.run(
+ [sys.executable, str(SCRIPT), "--before", before, "--after", after, *paths],
+ cwd = repo,
+ capture_output = True,
+ text = True,
+ )
+
+
+def test_duplicate_inserted_above_the_original_is_blocked(repo):
+ """The copy lands first, so the finding is reported at the OLD, unchanged line.
+
+ This is the shape that made the gate silent: judging by which lines the diff added
+ classifies it as pre-existing even though the branch is what created it.
+ """
+ (repo / "mod.py").write_text(SINGLE)
+ before = _commit(repo, "base")
+ (repo / "mod.py").write_text("def go():\n return 2\n\n\ndef go():\n return 1\n")
+ after = _commit(repo, "duplicate above")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 1, result.stdout
+ assert "go is defined twice" in result.stdout
+
+
+def test_pre_existing_duplicate_does_not_block_an_unrelated_edit(repo):
+ (repo / "mod.py").write_text(DUPLICATE)
+ before = _commit(repo, "base with duplicate")
+ (repo / "mod.py").write_text(DUPLICATE + "\n\ndef other():\n return 3\n")
+ after = _commit(repo, "unrelated edit")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 0, result.stdout
+ assert "not failing" in result.stdout
+
+
+def test_duplicate_in_a_file_the_branch_adds_is_blocked(repo):
+ (repo / "keep.py").write_text(SINGLE)
+ before = _commit(repo, "base")
+ (repo / "added.py").write_text(DUPLICATE)
+ after = _commit(repo, "add a file")
+
+ result = _run(repo, before, after, "added.py")
+ assert result.returncode == 1, result.stdout
+
+
+def test_rename_carrying_a_pre_existing_duplicate_does_not_block(repo):
+ """The sweep reports a rename under its NEW name, which does not exist at `before`."""
+ (repo / "mod.py").write_text(DUPLICATE)
+ before = _commit(repo, "base with duplicate")
+ _git(repo, "mv", "mod.py", "moved.py")
+ (repo / "moved.py").write_text(DUPLICATE + "\n\ndef other():\n return 3\n")
+ after = _commit(repo, "rename and edit")
+
+ result = _run(repo, before, after, "moved.py")
+ assert result.returncode == 0, result.stdout
+
+
+def test_rename_that_also_adds_a_duplicate_still_blocks(repo):
+ (repo / "mod.py").write_text(DUPLICATE)
+ before = _commit(repo, "base with duplicate")
+ _git(repo, "mv", "mod.py", "moved.py")
+ (repo / "moved.py").write_text(
+ DUPLICATE + "\n\ndef nu():\n return 1\n\n\ndef nu():\n return 2\n"
+ )
+ after = _commit(repo, "rename and duplicate")
+
+ result = _run(repo, before, after, "moved.py")
+ assert result.returncode == 1, result.stdout
+ assert "nu is defined twice" in result.stdout
+
+
+def test_a_scoped_duplicate_is_not_absorbed_by_a_module_level_one(repo):
+ """The finding identity has to keep the SCOPE and the SOURCE apart.
+
+ Concatenated, a module-level `from A.m import x` and a `from m import x` inside `class A`
+ both spell `A.m:x`, so a branch that deletes the first and writes the second had its new
+ finding charged to the old one's counter and passed. They are different duplicates in
+ different scopes and only a delimiter can say so.
+ """
+ (repo / "mod.py").write_text("from A.m import x\nfrom A.m import x\n")
+ before = _commit(repo, "module-level duplicate")
+ (repo / "mod.py").write_text("class A:\n from m import x\n from m import x\n")
+ after = _commit(repo, "swap it for a scoped one")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 1, result.stdout
+ assert "A.x is imported twice" in result.stdout
+
+
+def test_a_file_declaring_a_non_utf8_source_encoding_is_read_not_crashed_on(repo):
+ """PEP 263 says the file's own declaration decides how it decodes.
+
+ Reading the blob with the runner's UTF-8 locale raised UnicodeDecodeError out of
+ `subprocess` and took the whole run down -- on a file the parser, `compileall` and ruff all
+ accept, and on an edit that had nothing to do with it. Decoded properly the file is ordinary
+ source, so the duplicate in it is found like any other.
+ """
+ (repo / "mod.py").write_bytes(b'# coding: cp1252\nS = "caf\xe9"\n\n\ndef go():\n return 1\n')
+ before = _commit(repo, "base")
+ (repo / "mod.py").write_bytes(
+ b'# coding: cp1252\nS = "caf\xe9"\n\n\ndef go():\n return 1\n\n\ndef go():\n return 2\n'
+ )
+ after = _commit(repo, "duplicate it")
+
+ result = _run(repo, before, after, "mod.py")
+ assert "UnicodeDecodeError" not in result.stderr, result.stderr
+ assert result.returncode == 1, result.stdout + result.stderr
+ assert "go is defined twice" in result.stdout
+
+
+def test_a_rename_from_a_non_python_file_is_treated_as_an_addition(repo):
+ """Renaming `mod.txt` to `mod.py` is what makes those definitions active code.
+
+ The before side is not an eligible Python file, so its duplicates were never live and
+ cannot be inherited. Following the rename onto it consumed them as pre-existing and let
+ the branch turn a duplicate-carrying text file into a duplicate-carrying module for free.
+ """
+ (repo / "mod.txt").write_text(DUPLICATE)
+ before = _commit(repo, "base with a duplicate in a text file")
+ _git(repo, "mv", "mod.txt", "mod.py")
+ after = _commit(repo, "promote the text file to a module")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 1, result.stdout
+ assert "go is defined twice" in result.stdout
+
+
+def test_a_second_copy_of_an_already_duplicated_name_is_blocked(repo):
+ """Two copies before, three after. Counting by identity has to notice the third."""
+ (repo / "mod.py").write_text(DUPLICATE)
+ before = _commit(repo, "base with duplicate")
+ (repo / "mod.py").write_text(DUPLICATE + "\n\ndef go():\n return 3\n")
+ after = _commit(repo, "a third copy")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 1, result.stdout
+
+
+def test_a_new_plain_import_duplicate_is_not_absorbed_by_a_different_one(repo):
+ """Same bound name, different source: two distinct duplicates, not one carried over.
+
+ Both findings would read as `import:None:x` if the identity dropped the module the
+ alias came from, so the counter for the pre-existing `alpha` pair would absorb the
+ `beta` pair this diff introduces and the gate would pass.
+ """
+ (repo / "mod.py").write_text("import alpha as x\nimport alpha as x\n")
+ before = _commit(repo, "base with a duplicate import")
+ (repo / "mod.py").write_text("import beta as x\nimport beta as x\n")
+ after = _commit(repo, "swap the source, keep the duplication")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 1, result.stdout
+ assert "x is imported" in result.stdout
+
+
+def test_rename_of_a_non_ascii_path_is_matched_to_its_old_name(repo):
+ """core.quotePath escapes the path, and the escaped spelling matches nothing.
+
+ The before side then looks absent, every finding in the file reads as introduced, and
+ a branch that only moves a file gets blocked for a duplicate already on main.
+ """
+ (repo / "café.py").write_text(DUPLICATE)
+ before = _commit(repo, "base with duplicate")
+ _git(repo, "mv", "café.py", "resumé.py")
+ (repo / "resumé.py").write_text(DUPLICATE + "\n\ndef other():\n return 3\n")
+ after = _commit(repo, "rename and edit")
+
+ result = _run(repo, before, after, "resumé.py")
+ assert result.returncode == 0, result.stdout
+ assert "not failing" in result.stdout
+
+
+def test_file_deleted_at_head_is_skipped(repo):
+ (repo / "mod.py").write_text(DUPLICATE)
+ before = _commit(repo, "base with duplicate")
+ (repo / "mod.py").unlink()
+ (repo / "keep.py").write_text(SINGLE)
+ after = _commit(repo, "delete it")
+
+ result = _run(repo, before, after, "mod.py")
+ assert result.returncode == 0, result.stdout