Skip to content

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

Merged
danielhanchen merged 14 commits into
mainfrom
dup-def-lint
Aug 25, 2026
Merged

danielhanchen merged 14 commits into
mainfrom
dup-def-lint

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What this adds

A lint that refuses a name bound twice in the same scope of a Python file the PR changes:

  • a def / async def / class / ALL_CAPS constant defined twice as a direct child of one module or class body,
  • a name imported twice inside one from x import a, a, or twice from the same module.

scripts/lint_duplicate_definitions.py is AST-only and stdlib-only, with 18 self-test cases (positive and negative). Two steps in Lint CI: the self-test, then a sweep over the changed .py files, using the same merge-base pinning the import-hoist step already uses.

Why, concretely

This is a merge-resolution failure mode, and it is invisible to everything we run today. compileall parses both copies happily. The ruff rule set here is E9 / F63 / F7 / F82, which does not include F811, and F811 would not fire on a duplicated constant or on a name repeated inside a single import statement anyway. When git splits a function into a conflict over part of its body, the rest of that function can auto-merge below the resolved region as an ordinary addition, so the diff looks like a normal one.

Two real cases from the studiobench branches:

  1. reasoning_toggle_one in tests/studio/studiobench/scene/actions.py ended up defined twice, along with the REASONING_ONE_JS constant below it. The action registry refuses a double registration, so the effect was 22 collection errors and ValueError: action 'reasoning_toggle_one' is already registered before a single test ran. The two copies differed only in their comments, which is why reading the diff did not find it. This lint reports it in under a second.

  2. latest_attempt_rows appeared twice inside one from ... import line in the sweep code. That one passed ruff and a green 1419-test run. It was found only by an AST sweep after the fact.

The second shape is the one worth having a gate for. Case 1 fails loudly and stops the branch. Case 2 is silent: the later binding wins, the earlier one is dead, and whatever covered the earlier one now covers nothing.

A regex cannot do this job. The first version of this check was regex-based and truncated on a paren inside a comment, reporting 2 findings where there were 13. That case is in the self-test.

Scope, and what it will not do

The rule is narrow on purpose, so a finding is always worth acting on:

  • only direct children of a module or class body count, so one definition per branch of an if / else, and the try / except ImportError fallback import, are not findings,
  • @typing.overload and the @property / @x.setter / @x.deleter family are exempt,
  • assignments are ALL_CAPS only, and X = frozenset(X) style self-transforms are exempt, since those rebind by transforming rather than redefining,
  • import urllib.parse beside import urllib.request both bind urllib and are correct, so plain imports are keyed on the full dotted path,
  • a name imported from two different modules is a deliberate shadow more often than not, so only same-module repeats count.

A finding fails the job only when it sits on a line the PR added. One that was already in the file is printed and ignored. Without that, a PR touching a large existing file would be blocked by something it did not introduce.

Pre-existing findings on main

The whole-tree scan reports about 29 today. They do not fail anything here, since none of them sits on a line a PR added. Two are worth a separate cleanup:

  • unsloth/models/rl.py:4322 and :4332 are two byte-identical copies of patch_trl_vllm_generation.
  • tests/kaggle/test_launch_cleanup.py:855 and :947 are two copies of _failing_kaggle that differ only in their docstring, which is exactly the shape described above.

Left out of this PR to keep it to the gate.

Verification

  • python3 scripts/lint_duplicate_definitions.py --self-test passes 18 cases.
  • Paired negative control on a scratch repo: a branch-added duplicate fails with exit 1, and the same file with the duplicate removed passes, while a pre-existing duplicate in a second touched file is reported and does not fail either way.
  • ruff check, compileall, and yaml.safe_load of the workflow all clean.
  • tests/studio/test_absorbed_lanes_still_run.py still passes (13 tests), since it asserts on this workflow's structure.

danielhanchen and others added 2 commits August 24, 2026 08:25
A bad merge resolution can leave two complete top-level copies of one def, or
a name repeated inside a single 'from x import a, a'. Nothing in CI catches
that today: compileall parses both copies, the ruff rule set here is
E9 / F63 / F7 / F82 with no F811, and the two copies usually differ only in
their comments so the diff reads as normal.

Adds scripts/lint_duplicate_definitions.py (AST only, stdlib only, 18 self-test
cases) and two Lint CI steps: the self-test, and a sweep over the Python files
a PR changes. A finding fails only when it sits on a line the PR added, so a
duplicate that was already in the file does not block an unrelated branch that
edits it.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…nes moved

The added-line gate answered the wrong question. A merge that inserts the FIRST copy
above an existing definition reports the finding at the second, unchanged line, so the
branch that created the duplicate read as pre-existing and the check passed. Scan both
revisions and compare findings by identity instead, resolving a rename to its old path so
moving a file that already carries one of main's duplicates is not blamed on the mover.

Also cover the shapes the rule was missing: typed module constants (AnnAssign), two
aliases from one module landing on the same bound name, and imports inside a class body.

On the workflow side, include renames in the changed-file sweep (an ACM filter drops a
renamed-and-edited file entirely) and pin the head commit before diffing, refusing to
continue if it is unreachable rather than silently checking nothing.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f2e39a0be8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread scripts/lint_duplicate_definitions.py Outdated
Comment on lines +130 to +132
for sub in ast.walk(value):
if isinstance(sub, ast.Name) and sub.id == target.id:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve scoped names before exempting constant transforms

When an uppercase assignment shadows the same spelling inside a nested scope, such as FACTORY = lambda FACTORY: FACTORY + 1, the ast.Name belongs to the lambda parameter rather than the previous module constant. This textual walk nevertheless exempts every such assignment, so two merge-generated copies of that declaration—or of an equivalent comprehension whose target has the same name—produce no finding at all. Only references that resolve to the existing outer binding should trigger the self-transform exemption.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not taking this one. FACTORY = lambda FACTORY: FACTORY + 1 needs a module constant whose lambda parameter or comprehension target is spelled identically in ALL_CAPS, and an AST sweep of the whole tree for a module-level ALL_CAPS assignment shadowed by a nested binder finds zero. Resolving it properly means real lexical scope resolution inside a checker that is deliberately limited to direct children of a module or class body, which is a lot of machinery guarding a shape nobody writes. The self-transform exemption is meant to be generous in exactly this direction: the cost of missing one duplicate is a duplicate that ships, while a false positive here blocks correct code, and X = frozenset(X) is the common case it has to keep clean.

A bare @Property is the FIRST binding of its name, so exempting it hid two complete
copies of one property in a class. Only the accessor form (@v.setter / @v.deleter /
@v.getter) legitimately rebinds, and that stays exempt.

An ALL_CAPS 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 in 32 places, and duplicating that
line rebinds all four at once. The self-transform exemption is now decided per name, so
A, B = B, A still exempts both while A, B = 1, 2 exempts neither.

A plain import binds the ROOT of its dotted path, not the dotted path itself. Keying on
the raw optional alias missed import urllib.parse followed by import urllib.parse as
urllib, which silently repoints urllib from the package to the submodule.

The emitted finding identity for a plain import dropped the module it came from, so two
different duplicates both read as import:None:x and compare mode charged a newly
introduced one against a pre-existing counter entry.

Both changed-file sweeps now use -z. core.quotePath is on by default, so a non-ASCII path
arrives as "caf\303\251.py", whose suffix is .py" rather than .py; the workflow would
have checked zero files and reported success, and the rename map would have failed to
match its own before side.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d3aad7a695

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

out.append(
Finding(
node.lineno,
f"def:{scope}{name}",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve binding kinds in definition identities

In compare mode, a touched file that already has two constants named X can replace them with two classes or functions named X, yet both revisions emit the same def:X key and the new collision is consumed as pre-existing. This is especially relevant because the workflow deliberately tolerates existing duplicates; include the participating binding kinds in the identity so replacing an old duplicate group with a semantically different one cannot pass.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not taking this one. The scenario needs the file to already carry a tolerated duplicate of the same name, and in it the file goes from having a duplicate X to having a duplicate X. Compare mode tolerates pre-existing duplicates by design, so nothing that was blocked becomes unblocked.

Putting the binding kinds into the identity also costs more than it buys. The kinds would be positional, so reordering X = 1 and class X in a file that already carries that pair changes the key and the gate starts blocking a duplicate the branch did not write. That is a false positive on a legitimate edit, traded for an exotic false negative that leaves a tolerated duplicate tolerated.

The other four in this round are fixed in 1f9312a.

Four wrong answers, three of them false negatives and one a false positive.
The false positive is the one that matters most for a gate: it blocks correct
code, which is how a gate gets switched off.

Chained assignment. `N = K = 256` is two bindings in one statement, and this
repo writes it (tests/test_grouped_gemm_optional_gather_indices.py:46).
Requiring exactly one Assign target dropped the whole statement, so a
duplicated copy rebound both names and the scan still reported clean.

Overload through an import alias. The decorator was matched by its literal
text, so `import typing as t` with `@t.overload`, or `from typing import
overload as ov` with `@ov`, was not recognised and the signatures were
reported as duplicate definitions. The alias is now resolved from the module's
own imports, and only from typing / typing_extensions -- `import types as t`
with `@t.overload` is still a finding.

Explicit alias collisions. Imports are now keyed on the name they BIND. The
carve-out is for names the author never chose: an implicit binding takes
whatever its source is called, so `import urllib.parse` beside
`import urllib.request`, and `from a import x` beside `from b import x`,
stay legitimate. An explicit `as` alias is chosen, so a second binding of it
is always dead -- `import urllib.parse as client` beside
`import urllib.request as client` was invisible while the key carried the
source. `import urllib.parse` beside `import urllib.parse as urllib` still
reports, which the previous spelling was written to catch.

Renames from a non-Python file. Following `mod.txt` to `mod.py` back to the
text file consumed its duplicates as pre-existing, but the rename is precisely
what makes those definitions active code, so the destination is now treated as
an addition unless the before-side path was itself a .py file.

Run over the whole repo the findings are unchanged, 33 before and 33 after,
so none of this widens the gate on code already here.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 24, 2026 22:48
Two of these were introduced by the previous commit's own import rework.

Every implicit source is now 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. Implicit bindings are tracked
per source; an explicit as alias, being a name the author chose, still collides
with any earlier binding of that name at all.

Typing aliases are collected at MODULE scope. The whole-tree walk let an alias
bound inside a function exempt module-level decorators, so a local
import typing as t could excuse @t.overload where module-level t is something
else. Nested statements are still descended into, since try/except around the
import is the conventional spelling; function and class bodies are what get
skipped.

The finding identity now delimits scope from source. Concatenated, a
module-level from A.m import x and a from m import x inside class A both spelled
import:A.m:x, so a branch swapping one for the other had its new finding charged
to the old one's counter and passed.

Source is decoded by its own declared encoding. text=True decoded git show 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 a
file the parser and compileall both accept. tokenize.detect_encoding is the
parser's own reader for PEP 263, and the direct path now goes through it too so
the two agree.

The changed-file sweep adds T. 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.

Run over the whole repo the findings are still 33, unchanged from before this
PR, so none of this widens the gate on code already here.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 24, 2026 23:09
Three more, two of them consequences of the previous commit.

Accessors are exempt PER KIND, not wholesale. 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 the merge damage this
gate exists for. Keying on the kind keeps a getter, a setter and a deleter
apart while making two setters collide. @overload stays fully exempt, since any
number of copies there is legitimate, and a bare @Property is still not exempt
at all.

Overload aliases are collected per class scope as well as per module. Skipping
nested scopes fixed the cross-scope leak but left a class that does its own
import typing as t with its @t.overload methods unrecognised, so valid
overloads were reported as duplicates and would block CI. A class now gets the
module's aliases plus any it binds itself.

Control-flow branches are scanned independently. Only direct children of a
module or class body counted, so two copies of one def inside a single
if ENABLED: branch were never looked at, and two identical imports inside one
try body likewise. Each branch is now its own scan, so branches are still never
compared with each other or with the body around them: one definition per
branch of an if/else, and a fallback import in try/except, stay clean.

That last one finds four real duplicates already on main, a repeated
from unsloth import is_bfloat16_supported inside one if __name__ block in four
of the saving tests, so the pre-existing tally goes from 33 to 37 and the
workflow comment now says which four and why they were invisible. They are
pre-existing, so compare mode prints them and blocks nobody.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8387a3c41f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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[@]}"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Terminate options before passing changed paths

When a changed root-level Python filename begins with - (for example --edge.py), argparse treats the expanded path as another option even though it follows --after; the verifier exits with “unrecognized arguments” and the CI step blocks the PR without scanning the file. Add the conventional -- separator before expanding CHANGED so every Git-valid filename is passed as a positional target.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The mechanism is right and the -- separator is the correct remedy, but the trigger cannot arise here. git diff --name-only emits repo-relative paths, so only a root-level file can produce a leading dash; anything deeper arrives as dir/-x.py and parses as a positional. The root holds cli.py and unsloth-cli.py, and a file named --edge.py is not importable as a module in the first place.

The failure direction is also the safe one: the step exits with unrecognized arguments and names the file, which is fail-closed and self-diagnosing, the opposite of the silent under-reporting this gate exists to prevent. And the shape is not specific to this PR, the pre-existing verify_import_hoist step at lint-ci.yml:239-240 is byte-identical, so if it is worth doing it is a repo-wide sweep rather than a one-line change here. Leaving it.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: df40f90998

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

message: str


OVERLOAD_DECORATORS = {"overload", "typing.overload", "typing_extensions.overload"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Derive overload exemptions from actual typing imports

The unconditional spellings in this set exempt decorators based only on their text, so from custom import overload followed by two @overload definitions—or import custom as typing with @typing.overload—produces no finding even though neither decorator is typing.overload and the latter definition silently replaces the former. Start with no assumed bindings and add these spellings only when the corresponding typing or typing_extensions import is actually present in the definition's scope.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed the false negative (both from custom import overload and import custom as typing scan clean at 703d9d4), but the prescribed fix trades it for a reachable false positive, so I am leaving it.

Requiring a matching typing import in scope means from typing import * no longer exempts anything: it binds overload with no ImportFrom alias of that name. unsloth/models/rl.py:376 uses exactly that, so a star-importing file with repeated @overload signatures would start being reported as merge damage. The script's own docstring calls a false positive the wrong way for a gate to be wrong, and I agree: blocking correct code is worse than missing a shape nobody writes.

Reachability across 2010 tracked .py files: from <non-typing> import overload 0, import X as typing 0, files named typing.py or overload.py that could shadow 0. All 4 overload decorators in the tree are the literal @typing.overload.


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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Read symlink targets instead of parsing link blobs

When a PR adds or changes a Python symlink whose target is written relatively, such as links/alias.py -> ../pkg/mod.py, git show returns the symlink blob text ../pkg/mod.py rather than the target's Python source. This is parsed as invalid syntax and blocks the PR even though compileall follows the symlink and accepts the actual module; inspect the revision's file mode and resolve or deliberately skip symlink entries instead of parsing their link text as Python.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Verified end to end in a scratch repo: an added links/alias.py -> ../pkg/mod.py is stored as mode 120000 with the target path as its blob, git show prints ../pkg/mod.py, and --before/--after reports it as does not parse and exits 1. Path and directory mode are unaffected, since read_bytes follows the link.

Still rejecting on reachability: tracked symlinks at head 0 of any extension, .py symlinks in the worktree 0, and across all of history there is exactly one symlink ever, installer_files, added and deleted and not a .py path.

Two things narrow it further. Not every symlink blob trips it, a same-directory target like mod.py parses as a valid expression and reports nothing; only .. or absolute targets are syntax errors. And the type-change direction the workflow comment already reasons about is harmless, because the symlink sits on the before side where a parse finding only feeds the was counter and cannot block. If a .py symlink is ever committed the fix is a two-line ls-tree mode guard in _revision_findings, and that is the moment to add it.

A class body is not in the scope chain of a class nested inside it, so an
inner class resolves an unbound decorator name in the module namespace, not
in the enclosing class. Passing the outer class's aliases down exempted
@t.overload in the inner class where t is whatever the module bound, and two
copies of one def scanned clean. Widening the exemption is the direction that
hides merge damage, so start each class from the module-visible aliases and
add only its own bindings.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 703d9d430b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

it. Collecting only module-level aliases reported those valid overloads as duplicates, which
blocks CI on correct code.
"""
names: set = set(base)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drop overload aliases shadowed in the current scope

When a module imports typing as t but a class subsequently binds its own t to a non-typing object, seeding the class set with the module aliases leaves t.overload exempt. Thus import typing as t; class C: import custom as t; ... followed by two @t.overload methods scans clean even though the class-local decorator is not typing.overload and the second method replaces the first. Remove inherited spellings when the class rebinds their root, and likewise account for non-import rebindings.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reproduced (a class rebinding t to a non-typing module does leave @t.overload exempt), but there is nothing to shadow. Module-level import typing as X aliases in the tree: 0. Class bodies rebinding such an alias: 0. Aliased overload decorators: 0, all 4 in the repo are the literal @typing.overload. So the seeded set this item wants pruned is empty on every real input.

The second half, accounting for non-import rebindings, means tracking arbitrary class-body assignments for a name used as an overload alias, which is a scope-tracking interpreter added for an input the tool has never seen. Same standing reject as the argparse -- item above: real mechanism, no reachable input.

Comment on lines +197 to +200
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]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate the property name before classifying accessors

A decorator is treated as an accessor solely because its final attribute is setter, deleter, or getter, without checking that its base matches the function being defined. For example, an ordinary def v followed by @other.setter def v binds v twice, but the entries are keyed as v and v.setter, so the overwrite is missed. Only @v.setter/@v.deleter/@v.getter should receive the separate accessor key for a function named v.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reproduced: def v then @other.setter def v keys the two as v and v.setter, so the rebinding is missed. _accessor_kind checks only that the final attribute is in PROPERTY_ATTRS, never the base.

Not taking it, on reachability. Across the tree there are 16 accessor decorators and 0 where the base differs from the function name; nothing in unsloth, studio, tests or scripts applies @X.setter to a def not named X. This is also not a shape a bad merge produces: duplicating a def does not invent a mismatched decorator base.

This is the closest call of the round and the tightening is genuinely one line, so I may take it later as free hardening. But by the same standard I applied to the -- separator item, it is not a bug this repo's inputs can produce.

Comment on lines +220 to +222
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
if _is_overload_def(node, overloads):
return []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow throwaway singledispatch registration names

When a changed file uses the conventional singledispatch form @fun.register def _(arg: int): ... and repeats _ for another registered type, both decorated functions remain live through the dispatch registry even though the global _ binding is replaced. Since only typing overloads are exempted here, this valid stdlib pattern is reported as a duplicate definition and blocks the workflow; registration decorators with intentionally throwaway names need equivalent handling.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Confirmed the false positive: the textbook [email protected]_ form reports _ is defined twice and exits 1. But the pattern does not occur here and the only fix widens the exemption set.

Counts across unsloth, studio, tests and scripts: singledispatch anywhere 0, module or class level def _( 0, and one single @.register decorator, @atexit.register in studio/backend/utils/uv_path_safety.py:25, on a named function.

Blast radius is also already near zero: CI runs --before/--after, so it can only block a PR that introduces the second registration. And exempting _, or any decorator whose dotted tail is register, would silently swallow genuinely duplicated @atexit.register or @app.route copies. That is the trade this file refuses twice in its own comments, and it is the same reason I widened nothing when fixing the nested-class case. Worth revisiting the day singledispatch actually lands here.

Comment on lines +400 to +401
_scope_duplicates(tree.body, "", found, module_overloads, module_overloads)
_import_duplicates(tree.body, "", found)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Compare imports against other bindings in the scope

Because definitions/constants and imports are accumulated by two independent passes, a mixed collision is never reported. For example, def load(): ... followed by from helper import load—or the reverse order—scans clean even though the second statement replaces the first binding; the same happens for a class or uppercase constant colliding with an import. Share the scope's bound-name state between these checks so this merge-damage shape cannot bypass the gate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reproduced both orders (def load then from helper import load, and the reverse) scanning clean, and the two passes are genuinely independent at scan_source.

Not taking it here. I prototyped the unified check and swept the tree: 0 mixed def/class/constant-vs-import collisions exist in unsloth, studio, tests or scripts, so nothing is being missed today. And the import pass is not a plain name set, it carries the implicit/explicit carve-out that keeps import urllib.parse next to import urllib.request legitimate, plus the import:{scope}|{source}:{bound} identity that the before/after compare mode depends on. Sharing state means choosing a kind and a key for every cross-pair, and getting it wrong either breaks compare mode or fires on a legitimate try: from fast import x / except: def x(...).

Deliberately a different call from the match-case item, which I did take: that one was an implementation gap against what _branch_bodies already documented, while this asks for a third check the file explicitly scopes out. If it lands it should be its own change with its own test matrix.

Comment on lines +267 to +269
seen = {}
for node in body:
for name, kind in _defined_names(node, overloads):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Forget bindings removed by an unconditional del

When a direct del removes a name before that spelling is reused, the scanner retains the old entry forever and reports a duplicate even though the name was no longer bound. For example, import json; del json; import json is rejected, as is def f(): ...; old_f = f; del f; def f(): ..., despite the definitions occupying f at disjoint times. Process direct ast.Delete statements by removing their names from the relevant definition and import state so legitimate namespace cleanup does not block CI.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Both false positives reproduce as described. Rejecting on reachability and on the risk of the fix.

Module-level del <Name> in the tree: 142. Sites where a deleted name is later rebound in the same body: 0. The 142 are all the teardown idiom (del _TRUE, _var, _modules in unsloth/init.py, studio/backend/main.py, vendored truststore). I checked _TRUE specifically, since it is uppercase and therefore tracked as a constant and is assigned twice: it does not report, because the two assignments sit in opposite arms of one if/else and branches are already scanned independently.

import json; del json; import json is not code anyone writes. The fix would also have to touch both passes and reason about del inside branches: an if: del X is conditional, so dropping the binding unconditionally would create a new false negative, trading a false positive nobody hits for a miss on real damage.

A match keeps its branches in cases[*].body, which _branch_bodies never
enumerated, so two copies of one def inside a single case scanned clean while
the same shape under an if was reported. The alias walk had the mirror blind
spot: an overload alias bound inside a case went unseen, which would read a
legitimate overload pair as a duplicate.

Sibling cases are still never compared, one definition apiece being the
conditional idiom. Self-test cases are guarded on 3.10, since match is a syntax
error on the 3.9 this tool still supports and would otherwise report a parse
finding. Findings over unsloth, tests, studio and scripts are unchanged at 35.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

2 similar comments
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 17a0c8654d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

(line for (name, _), line in seen_implicit.items() if name == bound),
default = None,
)
if first is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retain aliases after reporting an import collision

When the before revision contains from a import x followed by from b import y as x, adding from c import x should create a second finding because it overwrites the currently bound explicit alias. However, this collision branch appends a finding without recording the second binding in seen_explicit, so the third implicit import is compared only with the original (x, a) source and produces no additional finding. Compare mode therefore sees one finding before and after, consumes it as pre-existing, and exits successfully despite the newly added overwrite; update the binding state after reporting a collision.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Reproduced exactly: from a import x, from b import y as x, from c import x gives 1 finding, and it is the same 1 before and after, so compare mode consumes it as pre-existing and exits 0. The cause is as you say, the collision branch emits without recording, so seen_explicit never holds x and the third import finds nothing to collide with.

Not taking it, because the gap is confined to that one mixed chain and every reachable shape is already correct. Measured, before and after adding a third import of the same name:

implicit same source (from a import x x2) 1 -> 2 findings
plain import (import json x2) 1 -> 2
explicit alias x2 1 -> 2
implicit, explicit alias, implicit 1 -> 1 <- only this one

Those three work because the FIRST binding stays recorded and later imports keep colliding with it. Only the implicit-after-a-collided-explicit path depends on the write that is missing.

Reachability: the shape needs one name bound by an explicit as alias and also by a plain import in the same scope, and there are 0 of those across the tree. The precondition of a pre-existing import collision is common, 31 findings over 18 files including unsloth/models/llama.py and unsloth/save.py, but every one of them is a plain or same-source implicit shape, which the table above shows is unaffected.

You are right that it is inconsistent, since the two-line version (from b import y as x then from c import x) is reported. It is a one-line fix and I will take it the day a real file grows an alias plus plain import of one name. Same standard I applied to the mismatched accessor base earlier in this PR.

@danielhanchen
danielhanchen merged commit 90f85fd into main Aug 25, 2026
15 checks passed
@danielhanchen
danielhanchen deleted the dup-def-lint branch August 25, 2026 01:47
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.

1 participant