Skip to content

tests: read checked-in files as UTF-8 instead of the platform default - #7438

Merged
danielhanchen merged 24 commits into
unslothai:mainfrom
LeoBorcherding:fix-test-source-encoding
Jul 27, 2026
Merged

danielhanchen merged 24 commits into
unslothai:mainfrom
LeoBorcherding:fix-test-source-encoding

Conversation

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

The bug

Path.read_text() with no encoding uses locale.getpreferredencoding(): UTF-8 on the Linux runners, cp1252 on a stock Windows install. Nine module-level reads of checked-in source files were relying on that default.

studio/backend/routes/inference.py carries the DeepSeek tool-call token regexes, so it holds U+FF5C and U+2581. Under cp1252 that read raises:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 97806

Because the reads run at import time, this doesn't show up as a test failure. It takes test_cancel_atomicity.py and test_cancel_id_wiring.py out at collection, so 20 tests silently don't run. Green on CI, permanently broken for a Windows contributor running the suite locally.

The fix

Pass encoding = "utf-8" at the 9 sites. The repo already spells it that way in 464 other places, so this just aligns the stragglers with existing house style.

The guard

tests/test_source_read_encoding.py keeps it from coming back.

The trick that makes it enforceable: at module scope there is no tmp_path fixture, so a bare read_text() / write_text() / open() there is always touching a checked-in file. That makes the rule mechanical with no allowlist and no false positives, while staying quiet about temp-dir I/O inside test bodies where the platform default is harmless. Binary-mode open() is skipped since it has no encoding to name.

Uses only ast and pathlib: no new dependencies. It sits at tests/ root, which repo-cpu-tests already auto-discovers, so no workflow change is needed.

Verification

  • Collection on Windows: 4103 collected / 50 errors → 4124 collected / 48 errors. The +21 is 20 recovered tests plus the new guard. Precisely additive, nothing else moved.
  • Stashing the encoding fixes makes the guard fail and list all 13 offending sites, so it does catch the bug it's written for.
  • 29 tests pass locally.
  • scripts/enforce_kwargs_spacing.py clean, ruff check clean, and the diff is already run through the repo's own scripts/run_ruff_format.py (ruff 0.6.9) so pre-commit.ci has nothing to reformat.

Scope

Test-only. No runtime or user-facing behavior changes.

Not covered here: tests/python/test_e2e_no_torch_sandbox.py builds open(...) snippets that run in subprocesses and hit the same decode error through a different mechanism. Different fix, separate PR.

Path.read_text() with no encoding uses locale.getpreferredencoding(), which
is UTF-8 on the Linux runners and cp1252 on a stock Windows install. Nine
module-level reads of checked-in source files were relying on that default.

studio/backend/routes/inference.py carries the DeepSeek tool-call token
regexes, so it holds U+FF5C and U+2581. Under cp1252 that read raised
UnicodeDecodeError on byte 0x81 at position 97806, and because the reads run
at import time it took test_cancel_atomicity.py and test_cancel_id_wiring.py
out at collection, not as failures. Green on CI, permanently broken for a
Windows contributor running the suite locally.

Adds a guard: at module scope there is no tmp_path fixture, so a bare
read_text()/write_text()/open() there is always touching a checked-in file.
That makes the rule mechanical enough to enforce with no allowlist, while
staying quiet about temp-dir I/O inside test bodies where the platform
default is harmless.

The repo already spells this correctly in 464 other places; this only stops
the stragglers coming back.

@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: 5f77627fbc

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread tests/test_source_read_encoding.py Resolved
Comment thread tests/test_source_read_encoding.py Resolved
Comment thread tests/test_source_read_encoding.py Resolved
Follows up on the Codex review:

- add `from __future__ import annotations`, since `str | None` in
  `_offender` is evaluated at import on Python 3.9 and pyproject declares
  requires-python ">=3.9,<3.15".
- widen the guard from module scope to import time. Class bodies and the
  bodies of module-level helpers called from an executing statement run
  during collection too, so `CODE = _extract_mixed_precision_code()` was
  the same hazard as an inline read. `if __name__ == "__main__":` blocks
  are skipped: pytest never executes them.
- scan studio/backend/tests/ as well as tests/. Both trees are collected
  on Windows by separate CI jobs, and the offender that started this,
  test_tool_xml_strip.py reading routes/inference.py, lives there.

Widening it surfaced seven more import-time reads of checked-in sources;
all now name utf-8.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Thanks, all three addressed in a603ce3.

P1 from __future__ import annotations is now the first statement after the docstring, so str | None in _offender stays lazy on 3.9.

P2 The guard now walks import time rather than module scope: class bodies, and the bodies of module-level helpers reached from an executing statement. CODE = _extract_mixed_precision_code() is the same hazard as an inline read, so the old version would have let it through. Bodies are only entered through a statement that actually runs, never by walking into a def, which keeps the no-allowlist property. if __name__ == "__main__": blocks are skipped since pytest never runs them.

ROOTS now covers studio/backend/tests/ too. Both trees are collected on Windows by separate jobs, and test_tool_xml_strip.py reading routes/inference.py (the file with U+FF5C and U+2581) is exactly the failure this PR is about. That one now names utf-8.

Widening surfaced seven more import-time reads of checked-in sources; all fixed in the same commit.

Base is merged in.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator 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: 793bb6a43e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread tests/test_source_read_encoding.py Outdated
left = node.test.left
if not (isinstance(left, ast.Name) and left.id == "__name__"):
return False
return any(isinstance(c, ast.Constant) and c.value == "__main__" for c in node.test.comparators)

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 Require equality in the main-guard check

When a test contains if __name__ != "__main__":, this predicate still returns true because it checks only the operands and ignores the comparison operator. Pytest executes that branch, but _import_time_calls skips it entirely, allowing an encoding-less source read—and the Windows collection failure this guard is intended to prevent—to pass unnoticed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. _is_main_guard ignored node.test.ops, so if __name__ != "__main__": counted as script-only while its body actually runs at import. Fixed in 4fee3b3 by requiring ast.Eq.

if isinstance(func, ast.Name) and func.id in helpers and func.id not in entered:
entered.add(func.id)
frontier.append(list(helpers[func.id].body))
stack.extend(ast.iter_child_nodes(node))

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 Exclude deferred expression bodies from the import-time scan

When module-level test data contains a lambda or generator whose body performs read_text() or write_text() later—for example, a lambda passed through parametrization and invoked with a temporary path—walking every child node descends into that deferred body and reports it as an import-time operation. Such reads do not run during collection, so this creates false CI failures for the temporary-file I/O the guard explicitly intends to ignore.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. Lambda bodies and comprehension elements were walked even though neither runs at definition. Fixed in 4fee3b3, which now follows only the outermost comprehension iterable.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +79 to +80
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or _is_main_guard(node):
continue

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 Inspect expressions evaluated while defining functions

When a source read appears in a function decorator, default argument, or annotation—for example, @pytest.mark.parametrize("case", Path("cases.txt").read_text())—Python evaluates it during module import, but this unconditional skip discards the entire FunctionDef, including those definition-time expressions. The guard therefore misses a common collection-time read and allows the Windows decoding regression it is meant to prevent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. Decorators and argument defaults are evaluated when the def executes, but were skipped with the body. Fixed in 4fee3b3; the body still waits for a call.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +104 to +109
func = call.func
if isinstance(func, ast.Attribute) and func.attr in GUARDED_METHODS:
return f"{func.attr}()"
# Binary handles have no encoding to name.
if isinstance(func, ast.Name) and func.id == "open" and "b" not in _open_mode(call):
return "open()"

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 Detect text reads opened through Path.open

When a test opens checked-in text with Path.open() at module scope, omitting encoding has the same locale-dependent behavior as builtin open(), but _offender ignores the call because "open" is absent from GUARDED_METHODS and the function is an attribute rather than an ast.Name. A standard with source_path.open() as handle: source read can therefore reintroduce the Windows collection failure without tripping this guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. Only builtin open() was matched, so a text-mode Path.open() was invisible. Fixed in 4fee3b3, with a receiver check so tarfile.open and fitz.open are not misread as file opens.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +79 to +80
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) or _is_main_guard(node):
continue

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 Scan the else arm of a main guard

When an if __name__ == "__main__": statement has an else arm, that arm executes during pytest collection, but treating the entire If as script-only skips both its body and its orelse. An encoding-less read in the import-only else branch is therefore invisible to the guard even though it can fail collection on Windows.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. The else arm runs at import but was discarded along with the rest of the If node. Fixed in 4fee3b3.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +102 to +103
if any(kw.arg == "encoding" for kw in call.keywords):
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 Reject encoding=None as a platform-default read

When a call explicitly passes encoding=None, Python still selects the locale-dependent default encoding, but this check treats the mere presence of the keyword as safe. Thus Path.read_text(encoding=None) or open(path, encoding=None) can still raise the same cp1252 decoding failure on Windows while passing the new guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed. encoding = None and encoding = "locale" both re-select the platform default, so the keyword merely being present was not enough. Fixed in 4fee3b3.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +92 to +97
if len(call.args) > 1 and isinstance(call.args[1], ast.Constant):
return str(call.args[1].value)
for kw in call.keywords:
if kw.arg == "mode" and isinstance(kw.value, ast.Constant):
return str(kw.value.value)
return "r"

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 Avoid assuming dynamic open modes are text

When binary mode is supplied through a constant or variable, such as MODE = "rb"; open(path, MODE), _open_mode cannot see a literal and defaults to "r", so the guard reports an encoding violation for a binary handle. Binary opens cannot accept an encoding argument, leaving legitimate module-level binary fixture reads with no valid way to satisfy this test other than rewriting the call to inline the mode.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed, and this is the one that could have blocked a compliant contributor. A non-literal mode fell through to the "r" default, so open(p, mode) was flagged even when mode resolves to "rb", where adding encoding= raises ValueError and no edit satisfies the rule. Fixed in 4fee3b3: an unresolvable mode is treated as unknown rather than text, and the same applies to open(*args) and a **kwargs splat, which hide the mode and can hide an encoding.

Close the detector gaps raised in review, all of which I reproduced against
the actual AST before changing anything.

False negatives (the guard let a real hazard through):
- _is_main_guard ignored the comparison operator, so if __name__ != "__main__"
  counted as script-only even though its body runs at import.
- The else arm of a main guard was discarded with the rest of the If node.
- Decorators and argument defaults on a module-level def were skipped with the
  body, though both are evaluated when the def executes.
- Path.open() in text mode was invisible; only builtin open() was matched.
- encoding = None and encoding = "locale" both re-select the platform default,
  but the keyword merely being present counted as pinned.

False positives (the guard would have blocked a compliant contributor):
- A non-literal mode fell through to the "r" default, so open(p, mode) was
  flagged even when mode is "rb", where adding encoding= is a ValueError and
  there is no edit that satisfies the rule.
- Same for open(*args) and a **kwargs splat, which hide the mode and can hide
  an encoding.
- Lambda bodies and comprehension elements were walked even though neither runs
  at definition.

Verified: still reports the same 22 offenders on unpatched main, green on this
branch and on the tree merged with latest main (557 files), and an adversarial
corpus of 33 cases now scores zero false positives and zero false negatives.
Also corrected two docstring claims: neither collecting job runs on Windows,
and the read is governed by locale.getencoding().
@danielhanchen

Copy link
Copy Markdown
Member

@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: 4fee3b3fcf

ℹ️ 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 tests/test_source_read_encoding.py Outdated
Comment on lines +114 to +118
if isinstance(node, (ast.GeneratorExp, ast.ListComp, ast.SetComp, ast.DictComp)):
# Only the outermost iterable is evaluated where it is written.
if node.generators:
stack.append(node.generators[0].iter)
continue

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 Inspect eager comprehension bodies

When a module-level list, set, or dict comprehension performs the file read in its element, filter, or a nested iterator (for example, CONTENTS = [path.read_text() for path in PATHS]), those expressions execute during import, but this branch visits only the outer iterable and then skips the rest of the comprehension. The guard therefore remains green even though the same Windows collection-time decoding failure has been reintroduced; walk the executed clauses and result expressions for eager comprehensions rather than treating them like lazy generator expressions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and this was a regression I introduced in 4fee3b3 by lumping the eager comprehensions in with generator expressions. Only a genexp is lazy: a list, set or dict comprehension runs its element, filters and nested iterators immediately, so CONTENTS = [p.read_text() for p in PATHS] at module scope was being missed. Fixed in 41d70ec; comprehensions are walked in full and only the genexp keeps the outermost-iterable-only treatment. Checked all five forms, including the filter and nested-iterator cases you named.

Comment thread tests/test_source_read_encoding.py Outdated
"dbm",
"fitz",
"gzip",
"io",

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 Guard qualified io.open calls

When an import-time read uses io.open(CHECKED_IN_FILE) rather than the built-in open, it has the same platform-default text encoding behavior that this test is intended to prevent, but listing io here causes _offender to unconditionally ignore it. The guard consequently stays green and the Windows collection failure can recur; handle io.open with the built-in opener's mode position instead of classifying it as an unrelated module opener.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, also mine from 4fee3b3. io.open is the builtin, so putting io in the not-a-path-opener list made io.open(CHECKED_IN_FILE) invisible to the exact rule this guard exists for. Fixed in 41d70ec: it is matched with the builtin's mode position, binary modes and a pinned encoding stay exempt, and tarfile.open and fitz.open remain exempt since neither has an encoding to name.

Two regressions from the previous commit, both reproduced against the AST
before changing anything.

Lumping list, set and dict comprehensions in with generator expressions was
wrong. Only a genexp is lazy; the other three run their element expression,
their filters and their nested iterators immediately, so
CONTENTS = [p.read_text() for p in PATHS] at module scope is an import-time
read the guard was silently missing. Comprehensions are now walked in full and
only the genexp keeps the outermost-iterable-only treatment.

io was also in the not-a-path-opener list, but io.open is the builtin, with the
same mode position and the same platform default. io.open(CHECKED_IN_FILE) is
exactly the hazard this guard exists for, so it is matched now, with binary
modes and a pinned encoding still exempt. tarfile.open and fitz.open stay
exempt since neither has an encoding to name.

Verified: 13 targeted cases covering all five eager comprehension forms and
io.open in text, binary and pinned shapes all classify correctly; still 22
offenders on unpatched main; green on this branch and on the tree merged with
latest main.
@danielhanchen

Copy link
Copy Markdown
Member

@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: 41d70ec52f

ℹ️ 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 tests/test_source_read_encoding.py Outdated
Comment on lines +114 to +118
if isinstance(node, ast.GeneratorExp):
# Lazy: only the outermost iterable is evaluated where written.
if node.generators:
stack.append(node.generators[0].iter)
continue

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 Traverse eagerly consumed generator expressions

When a generator expression is immediately consumed at module scope, such as DATA = list(p.read_text() for p in paths) or DATA = "".join(p.read_text() for p in paths), its element executes during import, but this branch visits only the outer iterable and therefore misses the encoding-less read. That allows the same Windows collection regression this guard is intended to prevent while the guard still passes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct. A genexp handed straight to a call is consumed there, so list(...) and "".join(...) run the element at import while only an unconsumed one bound to a name stays lazy. Fixed in 1c342f4: consumed generator expressions are walked in full, the rest keep the outermost-iterable-only treatment.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +64 to +69
left = node.test.left
if not (isinstance(left, ast.Name) and left.id == "__name__"):
return False
if not all(isinstance(op, ast.Eq) for op in node.test.ops):
return False
return any(isinstance(c, ast.Constant) and c.value == "__main__" for c in node.test.comparators)

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 Recognize reversed main-guard comparisons

A valid script-only guard written as if "__main__" == __name__: is not recognized because this requires __name__ to be the left operand. The walker consequently treats that guard's body as import-time code and will fail the suite on encoding-less temporary-file I/O that pytest never executes, creating a false positive for an equivalent and commonly accepted spelling of the main guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and this one was a false positive rather than a miss: requiring name on the left meant the body of an equivalent guard was treated as import-time code and could fail the suite on I/O pytest never runs. Fixed in 1c342f4; both operand orders are recognised.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +93 to +97
helpers = {
node.name: node
for node in tree.body
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
}

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 Follow helpers invoked from class bodies

The helper table contains only functions defined directly in tree.body, so a class-body pattern such as class Fixtures: def _load(): return SOURCE.read_text(); DATA = _load() is missed even though _load() executes while the class is constructed at import time. This contradicts the walker's stated coverage of class bodies and allows an encoding-less checked-in source read to restore the Windows collection failure without tripping the guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and it contradicted the walker's own docstring. The helper table was built from tree.body only, so a def in a class body invoked while the class is constructed was never followed. Fixed in 1c342f4; helpers are collected from the module body and from class bodies at any nesting.

All three reproduced against the AST first.

A generator expression handed straight to a call is consumed there, so
DATA = "".join(p.read_text() for p in paths) runs its element at import. Only
an unconsumed genexp bound to a name stays lazy, so the walker now follows the
consumed ones in full and keeps the outermost-iterable-only treatment for the
rest.

if "__main__" == __name__ is an equivalent and accepted spelling of the main
guard, but requiring __name__ on the left meant its body was treated as
import-time code. That is a false positive on a block pytest never runs, so
both operand orders are recognised now.

The helper table was built from module-level defs only, so a def in a class
body invoked while the class is constructed was never followed, contradicting
the walker's stated coverage of class bodies. Helpers are now collected from
the module body and from class bodies at any nesting.

Verified: 15 targeted cases including all three fixes and the earlier ones
still classify correctly; still 22 offenders on unpatched main; green on this
branch and on the tree merged with latest main.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@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: 1c342f42ff

ℹ️ 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 tests/test_source_read_encoding.py Outdated
Comment on lines +198 to +199
if func.attr == "read_text" and call.args:
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 Validate positional read_text encodings before exempting calls

When an import-time source read is written as path.read_text(None) or path.read_text("locale"), it still selects the platform encoding and can reproduce the Windows UnicodeDecodeError, but this unconditional exemption treats every positional argument as proof that the receiver is Distribution.read_text. Since Path.read_text also accepts its encoding positionally, the new regression guard remains green for these locale-dependent calls; inspect the positional value or resolve the receiver before exempting it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct. p.read_text(None) and p.read_text("locale") were exempted on the assumption that any positional meant Distribution.read_text, which let a platform-default read through. Fixed in 230f168: a positional is now checked against the same platform-default set as the keyword, and only a real encoding value (or a filename, which is what Distribution takes) exempts the call.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +107 to +111
consumed = {
id(arg)
for call in ast.walk(tree)
if isinstance(call, ast.Call)
for arg in [*call.args, *(k.value for k in call.keywords)]

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 Do not assume every call consumes a generator

A generator expression passed directly to a call is not necessarily consumed there: for example, READS = iter(p.read_text() for p in paths) leaves every read_text() deferred, but this set marks the generator as consumed and the walker reports the read as import-time. The new guard can therefore reject valid lazy test setup even though its documented invariant says it only reports calls that definitely execute; consumption needs to be limited to known eager consumers rather than every ast.Call.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Right, and this was my regression from the previous round. iter, zip, map, filter, enumerate and reversed all hand back another lazy object, so a genexp passed to those still has not run and marking it consumed hid a real offender. 230f168 replaces "any call" with an explicit EAGER_CONSUMERS set (list/tuple/set/dict/sorted/sum/min/max/all/any/frozenset plus join/extend/update/writelines).

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +101 to +102
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
helpers.setdefault(node.name, node)

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 Follow nested helpers reached from import-time loaders

If an import-time loader defines and calls a nested helper containing the file read, this collector records the outer function but never searches its body for nested definitions. The execution walk subsequently skips the nested def, and a call such as _read() is absent from helpers, so SRC = _load() can still perform an unencoded read_text() during collection while this guard passes; collect nested definitions when their enclosing helper is entered.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Agreed. Helpers were collected once from the module and class bodies, so a def nested inside a helper we later followed was never registered and its calls resolved to nothing. 230f168 pulls the collection into a _collect closure and re-runs it on each helper body as that helper is entered, so nested definitions become callable at the point they actually exist. Uncalled nested defs still stay out, which is what keeps the walk import-time only.

@danielhanchen

Copy link
Copy Markdown
Member

@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: 230f168991

ℹ️ 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 on lines +153 to +157
# The body waits for a call; these two run right now.
stack.extend(node.decorator_list)
stack.extend(d for d in node.args.defaults if d is not None)
stack.extend(d for d in node.args.kw_defaults if d is not None)
continue

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 Scan source reads executed inside tests

Skipping every function body unless the function is invoked during import leaves checked-in source reads during test execution unguarded. For example, tests/test_gemma4_chat_template.py:16-17 calls bare open() on unsloth/chat_templates.py through _extract_template() during its tests, and that checked-in file currently raises UnicodeDecodeError when decoded as cp1252 (at byte 0x90). Consequently, Windows contributors can still hit the same failure class while this new guard passes; the scan needs to distinguish fixture/temp-file I/O from test-reachable reads rather than excluding ordinary test bodies wholesale.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed and fixed. _extract_template() in test_gemma4_chat_template.py does open unsloth/chat_templates.py bare, and that file carries nine cp1252-undefined bytes, so under a cp1252 shim all 15 tests in the module fail on byte 0x90. Two more spellings of the same read were hiding in test bodies as well, including test_gguf_load_cache_reuse.py reading routes/inference.py through Path(__file__).parent.parent and dying on the same byte 0x81 in position 98431 that the two cancel modules hit at collection.

The scan now flags a call when the path itself proves the file is checked in, which is decidable without dataflow: it runs at import, or the path is a module-level constant (a tmp_path arrives as a fixture parameter, so it can never be one), or the path is built from __file__. Names shadowed by a parameter or a local rebind are excluded, and __main__ bodies and unconsumed generator expressions are skipped exactly as the import-time rule already skipped them. That took the tree from 22 offenders to 177, all now pinned.

Measured on the four affected files under a cp1252 shim: main 26 failed / 65 passed, this branch 1 failed / 90 passed. The remaining failure is test_rag_project_source_upload.py, which fails identically under UTF-8 and is unrelated.

One shape is deliberately left out of the guard and fixed by hand at test_studio_install_workspace_guard.py:851: text read from a checked-in file and then written back to a tmp_path is only unsafe because of where the string came from, and tracing that needs dataflow rather than a look at the call. It is noted in the docstring.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +229 to +237
if func.attr == "read_text" and call.args:
first = call.args[0]
# Path.read_text takes encoding first, so None or "locale" there
# is a platform-default read. Any other positional means the
# receiver is importlib.metadata's Distribution, whose argument
# is a filename and which has no encoding parameter at all.
if isinstance(first, ast.Constant) and first.value in PLATFORM_DEFAULT_ENCODINGS:
return "read_text()"
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 Recognize unbound Path.read_text calls

At import time, Path.read_text(SOURCE_PATH) is a valid unbound invocation of the same API and still selects the platform-default encoding, but this branch returns None whenever its first positional argument is not the literal None or "locale", based on the assumption that such calls must target Distribution.read_text. A module-level source read written in that form therefore passes the new guard and can reintroduce the Windows collection failure; receiver/API identification must account for unbound Path.read_text rather than exempting every non-default positional call.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, the reasoning behind that exemption was unsound. Path.read_text(SRC) is the unbound spelling of the same API and still takes the platform default, so treating every non-default positional as Distribution.read_text let it through.

Receiver identification now handles it: when the receiver is a Path class the instance occupies slot 0 and every argument shifts one place right, so the encoding is looked for at the shifted position for read_text, write_text and open alike. Fixing it this way also closed a false positive in the other direction, since positional encodings were not being read at all: p.write_text(data, "utf-8"), open(p, "r", -1, "utf-8") and p.open("r", -1, "utf-8") were each being flagged despite naming an encoding. A splat still counts as named, since positions mean nothing once one is present.

@danielhanchen

Copy link
Copy Markdown
Member

@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: 3e0dd8678e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +292 to +295
name = expr.id if isinstance(expr, ast.Name) else None
if expr is not None and (
_rooted_at_file(expr) or (name in module_names and name not in shadowed)
):

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 Trace paths derived from module-level constants

When a test body constructs its source path from a module constant, such as (_BACKEND / rel).read_text(), expr is an ast.BinOp, so name becomes None and the call is skipped. Fresh evidence in the final tree is studio/backend/tests/test_consent_gate.py:434: its loop includes routes/inference.py, which still raises UnicodeDecodeError under cp1252, while this guard reports zero offenders for that module. Consequently the Windows failure remains and the new regression test stays green; inspect names used within the path expression rather than requiring the receiver itself to be a module-level Name.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Confirmed live and fixed. test_consent_gate.py:434 reads routes/inference.py as (_BACKEND / rel) and failed under a cp1252 shim on byte 0x81 in position 98431, the same byte the two cancel modules hit at collection, while the guard reported zero offenders for that module.

The rule now resolves the anchor of the path expression instead of requiring the receiver to be a bare Name. It follows / joins to the left operand, path methods to their receiver so SRC_DIR.rglob("*.py") anchors on SRC_DIR, Path(x) and os.path.join(x, ...) to the first argument, and the locals and loop variables of the enclosing function to a fixed point, so route = Path(_BACKEND_DIR) / "routes" / "inference.py" followed by route.read_text() counts as well.

Anchoring is what decides it, deliberately, not any name appearing in the expression: tmp_path / SUBDIR anchors on the fixture, so a module constant used as a leaf cannot drag temp-dir I/O into scope. A name assigned a checked-in path in one place and something else in another stays out, since only one of the two is provable.

That took the tree to 238 offenders on unpatched main, all pinned. On the 22 affected files the cp1252 and UTF-8 runs are now identical, 932 passed with the same 2 failures either way, and those 2 are a missing diceware module unrelated to encoding.

Two shapes stay out of reach and are fixed by hand with the limitation recorded in the docstring: a path arriving from another function, as for path in _iter_caller_files() in test_security_gate_consistency.py, and text read from a checked-in file then written back to a tmp_path at test_studio_install_workspace_guard.py:851. Both need whole-program dataflow rather than a look at the call, and guessing there would produce exactly the false positives this guard is built to avoid.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +188 to +192
if isinstance(func, ast.Name) and func.id in helpers and func.id not in entered:
entered.add(func.id)
body = list(helpers[func.id].body)
_collect(body) # a def nested in this helper is now callable
frontier.append(body)

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 Avoid entering generator helper bodies on construction

When a module-level call invokes a generator function, such as READS = _load(paths), the call only constructs a generator and does not execute its body, but this branch unconditionally schedules the helper body for traversal. A bare read_text() inside _load is therefore reported as import-time I/O even when it remains deferred until a test consumes the generator, creating a false CI failure for the same lazy behavior already handled for generator expressions. Detect helpers containing yield or yield from and enter them only when the resulting generator is eagerly consumed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Agreed, and this was the same mistake as the generator-expression one a round earlier, just at function granularity. READS = _load(paths) on a generator function only builds the generator, so reporting its body as import-time I/O would be a false CI failure with no correct fix available.

The walker now checks for yield or yield from in the helper, ignoring any that belong to a nested def, and enters a generator helper only when the call sits somewhere that drains it. The consumption test is shared with the generator-expression rule and covers an eager consumer such as list(_load()), a for-loop iterable, and a comprehension iterable, which also fixed the pre-existing gap where for x in (open(P) for _ in y) was treated as lazy despite the loop pulling every item.

Verified against _import_time_calls in isolation so the change is visible independently of the path rules: a generator helper reading a parameter path is not reported when unconsumed and is reported when wrapped in list(...), and a plain non-generator helper is still entered as before.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +390 to +391
if receiver in NOT_PATH_RECEIVERS:
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 Guard compressed text openers

When a test reads a checked-in compressed text fixture with gzip.open(path, "rt"), bz2.open(path, "rt"), or lzma.open(path, "rt") and omits encoding, these standard-library functions wrap the binary stream in TextIOWrapper using the locale encoding, so UTF-8 contents can fail on Windows exactly like builtin open. This unconditional exclusion makes every such import-time call invisible to the guard; distinguish their binary modes from text modes and require an encoding for the latter instead of classifying the modules as unrelated openers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and the blanket exclusion was wrong for exactly the reason given: for a "t" mode these wrap the decompressed stream in a TextIOWrapper built with the locale encoding, so a checked-in .gz text fixture fails on Windows just as builtin open does.

gzip, bz2 and lzma are out of NOT_PATH_RECEIVERS and handled on their own terms. They default to "rb" rather than "r", so only an explicit text mode is in scope and gzip.open(p) or gzip.open(p, "rb") stays exempt, while gzip.open(p, "rt"), bz2.open(p, "wt") and lzma.open(p, "rt") now require an encoding. Positions differ across the three: gzip and bz2 take encoding as the fourth positional, lzma takes it keyword-only, so lzma is checked by keyword alone rather than pretending it has a slot it does not.

tarfile, codecs and the rest keep the blanket exemption, since their modes are compression modes rather than text modes. No such call exists in the tree today, so this closes the hole ahead of the first one.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 63a1c55bbc

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026

@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: 9ed67c80c2

ℹ️ 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 on lines +282 to +285
if isinstance(node, ast.Assign) and len(node.targets) == 1:
target = node.targets[0]
if isinstance(target, ast.Name) and isinstance(node.value, ast.GeneratorExp):
named.setdefault(target.id, node.value)

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 Track stored generator-function calls before consumption

When import-time code stores a generator-function result before consuming it, such as reads = _load(); list(reads), named records only GeneratorExp assignments. The later consumer therefore resolves to the Name rather than the original _load() call, so _import_time_calls() never enters the generator body. An unencoded read reached through a dynamically discovered path inside that body can execute during collection while this guard reports nothing; map assigned generator-function calls back to their call nodes as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Checked this one against the guard rather than the code, and it already holds. _import_time_calls enters a generator function's body whenever the call itself is reached at import; the laziness carve-out at the _is_generator check only applies when the call is not in consumed, and _eagerly_consumed resolves reads back to the _load() call through the named map. Both spellings flag:

stored in a variable   flags=['f.py:5: open()']
consumed directly      flags=['f.py:5: open()']

using a dynamic path (os.listdir) so only the import-time rule could have caught it. No change made.

Comment on lines +879 to +883
# Any other module receiver is somebody else's opener: tarfile.open
# takes a compression mode, Image.open takes a binary file. Neither
# has an encoding to name, so demanding one leaves no correct edit.
if receiver is not None and receiver in modules and receiver not in PATH_CLASSES:
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 Recognize builtins.open as the builtin opener

When a test uses import builtins; builtins.open(CHECKED_IN).read(), this branch classifies builtins as an arbitrary imported module and skips the call, even at module scope. builtins.open is the same locale-default text API as bare open, so this spelling can still trigger the Windows decode failure while the guard passes; classify the builtins receiver alongside io and the bare builtin.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. builtins.open is the builtin under a module receiver, so it now resolves through a shared BUILTIN_OPEN_MODULES = {"builtins", "io"} in _offender, _open_alias and _is_module_receiver. No live site uses this spelling today, so this is purely to stop it becoming a way around the rule.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

Comment on lines +847 to +850
receiver = func.value.id if isinstance(func.value, ast.Name) else None
# An unbound `Path.read_text(p)` puts the instance in slot 0.
shift = 1 if receiver in PATH_CLASSES else 0
if func.attr in GUARDED_METHODS:

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 aliases of pathlib path classes

When pathlib is imported as from pathlib import Path as P, an unbound call such as P.read_text(SOURCE) leaves shift at zero because only literal class names are recognized. The first path argument is then mistaken for a bound encoding argument and the call is exempted, so an unencoded checked-in read passes the guard even during collection; determine path classes from the imports map rather than only the bound identifier.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Added _is_path_class, which resolves through the imports map, so from pathlib import Path as P gets the same shift = 1 as the bare name and P.read_text(SOURCE) no longer reads the path argument as an encoding. The repo has 7 pathlib aliases but no unbound reads through one, so again this closes the route rather than a live hole.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +463 to +466
func = call.func
if isinstance(func, ast.Attribute):
if isinstance(func.value, ast.Name) and _is_module_receiver(func.value.id, modules):
return call.args[0] if call.args else 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 Extract compressed paths supplied by filename keyword

When an ordinary test body uses gzip.open(filename=CHECKED_IN, mode="rt") (likewise bz2 or lzma), this branch returns no path because compressed openers have no positional argument and their keyword is named filename, not file. The text-mode call consequently never reaches _offender, allowing another locale-default read of repository data to bypass the guard; inspect the compressed APIs' filename keyword when the positional path is absent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _path_expr now falls back to a _path_keyword helper that accepts both spellings, file for open and filename for gzip, bz2 and lzma, whenever there is no positional path. Applies to the aliased form (from gzip import open as gzopen) as well.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +672 to +676
funcs = {
node.name: node
for node in ast.walk(tree)
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
}

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 helpers by lexical identity instead of name

When two tests define nested helpers with the same name, this dictionary keeps only one definition and all same-named calls in the module are analyzed against it. For example, a _read(ROOT) helper in one test and an unrelated _read(tmp_path) helper in another cause the temporary caller to mark the shared (name, parameter) pair bad, so the checked-in helper's bare path.read_text() is omitted. Key definitions and propagated parameters by lexical function identity rather than the unqualified name.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _checked_in_params keyed definitions by unqualified name, so two tests each nesting a _read helper were merged and the tmp_path caller poisoned what the checked-in caller proved. Definitions are now indexed per scope and a call resolves through _lookup, walking the enclosing scope chain the way Python does; the good/bad sets are keyed by id(func). 5 test modules define a duplicated nested helper that does file I/O, so the shape is live.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

Comment on lines +331 to +335
names = set()
for node in tree.body:
if isinstance(node, ast.Assign):
for target in node.targets:
names.update(_bound(target))

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 Track checked-in paths stored on test classes

When a test class stores a source path as SOURCE = ROOT / "x.py" and a method reads it through self.SOURCE.read_text(), only module-body assignments are collected, so _path_root() ends at the shadowed self parameter and the call is skipped. This is a statically provable checked-in path and the repository already uses analogous self._SETUP_SH source attributes; include class-level path bindings so removing their explicit encodings cannot bypass the guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed, and this was the one with real sites behind it. Added _class_path_attrs, which collects class-body names bound to a checked-in path, plus a self/cls stop in _path_root so self.SOURCE anchors on the attribute instead of bottoming out at the shadowed self parameter. That brings 7 existing reads under the guard:

tests/studio/install/test_rocm_support.py:3058,3063,3078,3085  self._MAIN_PATH / self._TRAINING_WORKER_PATH
tests/studio/install/test_selection_logic.py:3482,3506,3694    self._SETUP_SH / self._SETUP_PS1

All 7 already pin utf-8; they just had nothing stopping a later edit from dropping it.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +498 to +499
elif node.args:
node = node.args[0]

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 Stop treating every function call as path-preserving

When a helper receives a checked-in path but returns a temporary copy, such as copied_to_temp(ROOT / "x.py").read_text(), this fallback follows the helper's first argument and incorrectly classifies the returned temp path as checked in. The guard then fails even though locale-default I/O on that test-created file is explicitly intended to remain out of scope; only follow known path constructors and path-preserving functions rather than every call with a positional argument.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed, and this was live on main rather than hypothetical. _path_root followed args[0] of any call, so it is now gated on _is_path_preserving: the pathlib classes plus a PATH_FUNCTIONS set (str, os.fspath, os.path.join and kin). Anything else stops there, unresolved.

Running both guard versions over unpatched main, the only detection this removes is:

unsloth_cli/tests/test_start.py:634: read_text()

which is path = start.write_codex_subagent_bridge(BASE, ..., tmp_path, ...) followed by path.read_text(). The helper returns home / "subagent.json", so the file is squarely in tmp_path; the old walk just followed BASE. Count on main goes 250 -> 249 and every remaining one is genuine. I left the utf-8 already added at that line, since it is harmless on a JSON file.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +356 to +358
for node in ast.walk(func):
if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
names.add(node.id)

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 Keep comprehension targets in their own scope

When a function reads a module-level source constant and also reuses that name as a comprehension target, such as ROOT.read_text(); [x for ROOT in values], Python 3 keeps the comprehension binding in its implicit nested scope. This walk nevertheless adds ROOT to the enclosing function's shadowed names, causing the real global ROOT.read_text() to be skipped; exclude comprehension-local bindings when collecting names for the surrounding function.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _local_names used ast.walk, which flattens the comprehension's implicit scope into the enclosing function. It now walks explicitly and skips only generator.target, keeping iter, the filters and the element since those do bind and reference out here. No collisions exist in the tree today, so this is a correctness fix with no change in output.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

body = list(helper.body)
_collect(body) # a def nested here is now callable
frontier.append(body)
stack.extend(ast.iter_child_nodes(node))

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 Skip calls in statically unreachable import-time branches

When a module contains a call under a statically dead branch such as if False: Path(dynamic_path()).read_text() or the right side of False and ..., this unconditional child traversal reports it as import-time I/O even though Python never evaluates it. That creates a false CI failure for code that cannot trigger the collection-time Windows error; honor at least literal branch conditions and constant short-circuit expressions before scheduling their children.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Added _static_truth and _live_branches, applied in both rules next to the existing __main__ handling, covering if/else on a literal, IfExp, and and/or short-circuits. Same reasoning as the __main__ guard: the arm never runs, so a report there has no reachable cause and no compliant edit.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026

@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: cd27e7597a

ℹ️ 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 tests/test_source_read_encoding.py Outdated
Comment on lines +525 to +527
if isinstance(func, ast.Name):
return func.id in PATH_CLASSES or func.id in PATH_FUNCTIONS
return isinstance(func, ast.Attribute) and func.attr in PATH_FUNCTIONS

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 Follow qualified pathlib constructors

Handle qualified constructors such as pathlib.Path(...) and pl.Path(...) here. _is_path_preserving recognizes only bare path-class names, so a checked-in read like pathlib.Path(ROOT / "source.py").read_text() produces no offender and allows the Windows decoding regression this guard is intended to prevent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _is_path_preserving now matches on the callee's trailing name through a shared _callee_name, so pathlib.Path(...) and pl.Path(...) anchor the same way the bare name does. 15 qualified constructors exist in the test tree today.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

return False
if root.id in derived:
return True
return root.id == "__file__" or (root.id in module_names and root.id not in shadowed)

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 Trace module bindings before treating paths as checked in

Do not classify every module-level name or import as a checked-in path. For example, TMP = Path(tempfile.mkdtemp()) followed by (TMP / "created.txt").read_text() is reported even though it accesses a test-created temporary file; imported package attributes pointing to caches or user configuration have the same problem. This makes the new guard reject valid platform-default I/O despite its stated intent to leave temporary-file operations alone.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed, and a fair catch against the docstring's own claim that a module-level name is something a fixture can never be. Added TEMP_FACTORIES (mkdtemp, mkstemp, TemporaryDirectory, NamedTemporaryFile, gettempdir); _module_level_names now skips any binding whose value calls one, so TMP = Path(tempfile.mkdtemp()) is no longer an anchor. No live instance in the tree, so this closes the hole rather than unblocking anything today.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

Comment thread tests/test_source_read_encoding.py Outdated
else:
walk(child, visible)

walk(tree, _imported_names(tree))

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 Respect import execution order when resolving open

Build the visible-import map in statement order rather than applying every import in the scope to every call. With DATA = open(ROOT / "x").read() followed later by from gzip import open, the first call resolves to the builtin at runtime, but this map classifies it as gzip.open and reports no missing encoding; an import inside an untaken conditional causes the same false negative.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _imports_at_each_call applied a scope's whole import set to every call in it. It now threads a mutable map through in statement order, snapshotting at each call, with a fresh copy per nested scope so a local alias stays local. Factored the per-statement part out as _import_bindings and _imported_names reuses it.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +849 to +850
for call in ast.walk(tree):
if not isinstance(call, ast.Call) or not isinstance(call.func, ast.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 Trace checked-in arguments through method helpers

Resolve method calls when propagating checked-in helper parameters. The current filter ignores every attribute callee, so a common class helper such as self._read(ROOT / "source.py"), where _read calls path.read_text(), never seeds path as checked in and the unpinned read passes the guard.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _checked_in_params only resolved ast.Name callees, so every self._read(...) was invisible to it. It now tracks the enclosing ClassDef per call and resolves self/cls attribute callees against that class's own methods, dropping the receiver's slot when matching positional parameters. The tree has 1953 self.X(...) call sites, so this was the largest blind spot of the set.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

Comment thread tests/test_source_read_encoding.py Outdated
Comment on lines +781 to +785
for element in values.elts:
paired = len(argnames) > 1 and isinstance(element, (ast.Tuple, ast.List))
row = element.elts if paired else [element]
for argname, value in zip(argnames, row):
supplied.setdefault(argname, []).append(value)

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 Unwrap pytest.param rows before checking path provenance

Handle pytest.param(...) entries in parametrization values. For @pytest.mark.parametrize("path", [pytest.param(ROOT / "source.py", id="source")]), this code records the wrapper call rather than its first argument, so path is not recognized as checked in and path.read_text() without an encoding is silently accepted.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Added _unwrap_param, applied where _parametrized_values records each row, so pytest.param(SOURCE, id = "source") contributes SOURCE rather than the wrapper call. 2 live pytest.param rows in the backend tests.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

Comment thread unsloth_cli/__init__.py Outdated
Comment on lines +10 to +14
for _name in ("stdout", "stderr"):
_stream = getattr(_sys, _name, None)
try:
if "utf" not in (_stream.encoding or "").lower():
_stream.reconfigure(encoding = "utf-8", errors = "replace")

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 Do not override explicit POSIX stream encodings

Restrict this process-wide stream mutation to the affected Windows case or otherwise preserve explicit overrides. On Linux and macOS, importing unsloth_cli now changes any non-UTF-8 sys.stdout and sys.stderr, including encodings deliberately selected with PYTHONIOENCODING or by an embedding application, so subsequent CLI or host-process output is emitted with a different encoding than the caller requested; the analogous guard in unsloth/__init__.py is Windows-only.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Agreed, and fixed rather than narrowed to Windows, since the crash is not Windows-only: unsloth --help also dies under LC_ALL=C on Linux, which is a normal state in a minimal container.

Windows still gets UTF-8, matching unsloth/__init__.py. Everywhere else the encoding is left exactly as the caller chose and only the error handler is relaxed, so the box characters degrade to ? instead of raising:

LC_ALL=C            stdout: ascii replace        all three --help paths exit 0
PYTHONIOENCODING=latin-1  stdout: iso8859-1 replace
UTF-8 host          utf-8 surrogateescape -> unchanged, same object

So an explicit PYTHONIOENCODING still picks the bytes, and a UTF-8 host sees no mutation at all.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

Comment on lines +349 to +351
if isinstance(node, ast.Call) and _is_eager_consumer(node.func):
consumed.update(id(_resolve(a)) for a in node.args)
consumed.update(id(_resolve(k.value)) for k in node.keywords)

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 Propagate eager consumption through lazy wrappers

Follow consumption transitively through lazy adapters rather than marking only the direct argument of an eager consumer. For example, DATA = list(enumerate(_paths())) executes _paths() at import time, but only the enumerate(...) call is marked consumed, so an unpinned read_text() in the generator body is skipped by the import-time rule.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _eagerly_consumed marked only the direct argument, so a wrapper hid the generator. Added LAZY_ADAPTERS (enumerate, zip, map, filter, islice, reversed) and a transitive pass that walks through them, resolving names back to their generator as the direct case already did.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

Comment on lines +1007 to +1018
if func.attr in GUARDED_METHODS:
if func.attr == "read_text" and not shift and call.args:
first = call.args[0]
# Bound read_text takes encoding first, so None or "locale"
# there is a platform-default read. Any other positional means
# the receiver is importlib.metadata's Distribution, whose
# argument is a filename and which takes no encoding at all.
if isinstance(first, ast.Constant) and first.value in PLATFORM_DEFAULT_ENCODINGS:
return "read_text()"
return None
position = ENCODING_POSITION[func.attr] + shift
return None if _pins_encoding(call, position) else f"{func.attr}()"

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 Limit guarded methods to pathlib-compatible receivers

Do not classify every no-argument method named read_text or write_text as pathlib I/O. At module or class execution time, an unrelated API such as response.read_text() is sent directly to _offender and reported even when the method does not accept an encoding argument, leaving no valid compliant edit and causing the guard to reject legitimate tests.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Added _non_path_names: module-level names bound to a call that is neither path-preserving nor a path method. _scan skips read_text/write_text on those receivers, so the import-time rule no longer demands an encoding from an API that has none.

Kept deliberately narrow, since over-reaching here would lose real coverage:

response = requests.get(...); response.read_text()   not flagged
source = ROOT.resolve();      source.read_text()     still flagged
SOURCE = Path(__file__).parent / "x.py"; SOURCE.read_text()  still flagged

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, still parses as Python 3.9.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@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: 8c0c4ed22a

ℹ️ 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 tests/test_source_read_encoding.py Outdated
Comment on lines +1117 to +1119
receiver = func.value.id if isinstance(func.value, ast.Name) else None
# An unbound `Path.read_text(p)` puts the instance in slot 0.
shift = 1 if _is_path_class(receiver, modules) else 0

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 Recognize qualified Path class calls

When a test uses the fully qualified spelling pathlib.Path.read_text(SOURCE) (or a module alias such as pl.Path.read_text(SOURCE)), func.value is an ast.Attribute, so receiver becomes None and shift remains zero. The following branch then mistakes the path argument for an encoding argument and returns no offender; the same positional error also lets qualified Path.write_text and Path.open calls evade the guard. This allows the exact platform-default reads this test is intended to prevent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Added _is_path_attr, used in both _offender and _path_expr, so pathlib.Path.read_text(SOURCE) and pl.Path.read_text(SOURCE) get the same shift = 1 and the same argument-as-path treatment as the bare name. Covers write_text and open in the qualified spelling too, since all three go through the same two helpers.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 and 15 fixtures all still correct, parses as Python 3.9.

Comment on lines +536 to +540
for child in ast.iter_child_nodes(node):
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
walk(child, dict(visible)) # its own scope, so its own copy
else:
walk(child, visible)

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 Keep conditional imports from leaking into sibling scopes

When an opener is imported conditionally, this traversal shares and mutates the same visible mapping across both branches and all following statements, even if the branch is statically dead. For example, after if False: from PIL.Image import open, a subsequent open(SOURCE) is the builtin at runtime, but the scanner resolves it as Pillow's opener and permits the unpinned checked-in read. Branches need isolated import state, with only imports guaranteed to execute propagated afterward.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed, and this one was mine: making the import map statement-ordered last round introduced the shared mutable map you are describing. ast.If is now handled explicitly. The test is walked with the live map, then each arm that can run gets its own copy unless the branch is statically decided, so a conditional from PIL.Image import open no longer binds anything for the code after it and a dead arm is not explored at all.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 and 15 fixtures all still correct, parses as Python 3.9.

"""Offenders from both rules, reported once each and in source order."""
modules = _imported_names(tree)
visible_at = _imports_at_each_call(tree)
calls = {id(c): c for c in _import_time_calls(tree)}

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 Exclude module-level temporary-file I/O from the guard

Every import-time call is added without checking its path provenance, so safe module-level temporary I/O such as TMP = Path(tempfile.mkdtemp()) / "x"; TMP.write_text("data") is reported even though the platform default is harmless for a file the test just created. This contradicts the TEMP_FACTORIES handling used by the checked-in-path analysis and will make the new repository-wide test reject legitimate module-scoped fixtures unless they add an unnecessary encoding.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed, and you are right that it contradicted the TEMP_FACTORIES handling I added for the checked-in analysis: that only stopped such a name being an anchor, while rule 1 flags every import-time call regardless of provenance. Added _temp_rooted_names and a skip in _scan, so TMP = Path(tempfile.mkdtemp()) / "x"; TMP.write_text(...) is quiet, which is the same position the docstring already takes on temp-dir I/O.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 and 15 fixtures all still correct, parses as Python 3.9.

Comment on lines +1160 to +1163
return (
None
if _pins_encoding(call, ENCODING_POSITION["Path.open"] + shift)
else "Path.open()"

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 Distinguish arbitrary instance open methods from Path.open

Any attribute call named open that is not attached directly to a recognized module falls through to the Path.open logic, even when the receiver is an unrelated object. For example, module-level ARCHIVE = zipfile.ZipFile(...); ARCHIVE.open("member.txt") is reported as Path.open() although ZipFile.open returns a binary member stream and does not accept an encoding argument, leaving no valid way to satisfy the guard. Only receivers proven to be path objects should use this signature.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. _scan already skipped read_text/write_text on a receiver _non_path_names can see is not a path; that skip now covers open as well, so ARCHIVE = zipfile.ZipFile(...); ARCHIVE.open("entry.txt") no longer reports as Path.open().

Worth noting my first fixture for this hid the bug: "member.txt" contains a b, so the mode heuristic read it as binary and it passed for the wrong reason. With "entry.txt" it reproduced. Checked the fix is narrow:

ARCHIVE.open("entry.txt")      not flagged
(ROOT / "x.py").open().read()  still flagged

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 and 15 fixtures all still correct, parses as Python 3.9.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@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: 3932ffc8b1

ℹ️ 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 unsloth_cli/__init__.py Outdated
_stream = getattr(_sys, _name, None)
try:
if "utf" not in (_stream.encoding or "").lower():
_stream.reconfigure(encoding = "utf-8" if _to_utf8 else None, errors = "replace")

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 Restrict stream reconfiguration to the CLI entry point

When a host application imports unsloth_cli or any unsloth_cli.commands.* module while using a non-UTF stream, this package initializer now mutates the process-wide sys.stdout and sys.stderr: on Windows it can change redirected cp1252 output into UTF-8 bytes, and elsewhere it changes strict encoding failures into silent replacement. This behavior is needed only for the unsloth console entry point, so importing CLI helpers should not alter an embedding application's global streams; gate the reconfiguration on the actual console-script invocation or move it into the entry-point wrapper.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed, and a fair objection: a package initializer had no business touching the host's streams. The file already computed an _entry_base further down to gate the -np<N> rewrite for exactly this reason, so I hoisted that to the top as _is_entry_point and gated the stream block on it too, then reused the one flag for both.

library import, LC_ALL=C   before ('ascii', 'surrogateescape') after ('ascii', 'surrogateescape')
console script, LC_ALL=C   ascii replace, `unsloth --help` exits 0

So importing unsloth_cli.commands.* is now inert and the console script keeps the fix.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 to 16 fixtures all still correct.

log_text = LOG_FILE.read_text(encoding = "utf-8")
raise RuntimeError(f"Server exited early (code {proc.returncode}):\n{log_text[-2000:]}")
log_text = LOG_FILE.read_text()
log_text = LOG_FILE.read_text(encoding = "utf-8")

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 Force the child process to emit UTF-8 before decoding its log

When this integration test runs on a non-Windows host with a non-UTF locale or an explicit setting such as PYTHONIOENCODING=cp1252, the spawned unsloth process writes bytes directly to the log file descriptor using the child's encoding; the encoding="utf-8" on the parent's file object does not transcode those bytes. If the banner or model path contains a locale-encodable non-ASCII character, these new UTF-8 reads raise UnicodeDecodeError before the API-key regex can run. Set a UTF-8 encoding in the child's environment or decode the captured output with a compatible error policy instead of assuming the descriptor contains UTF-8.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Right that the parent's encoding on the file object does nothing here, since the child writes to the descriptor itself. _start_server now passes PYTHONIOENCODING=utf-8 and PYTHONUTF8=1 in the child's environment, so the bytes in the log actually are utf-8 by the time the three read_text(encoding = "utf-8") calls run.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 to 16 fixtures all still correct.

launcher_path.write_text(template)
# template comes out of install.sh, so it carries whatever non-ASCII that
# file holds and cp1252 cannot encode it back out.
launcher_path.write_text(template, encoding = "utf-8")

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 Use UTF-8 for the matching temporary-file read

This now writes the extracted launcher template as UTF-8, but the same test still reads launcher_path with a bare read_text() at line 869. Because the template contains U+2500, running this test with a genuine non-UTF filesystem encoding—for example LC_ALL=C PYTHONUTF8=0—raises UnicodeDecodeError at that final read; the new source-encoding guard also misses it because it blanket-exempts tmp_path-derived files. Read the file back with encoding="utf-8" so the explicit writer and reader agree.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed. Line 869 read back, with a bare read_text(), the same file written as utf-8 fifteen lines above, and the template carries U+2500, so the pair really was inconsistent. It now names utf-8 as well.

Your point about the guard missing it is correct and deliberate: the file is tmp_path-derived, so rule 2 exempts it by design. This is the second of the three shapes the module docstring already records as out of reach, text from a checked-in file written to a temp path, which is why that note also recommends an LC_ALL=C run to catch them.

Verified: guard test green, whole-tree scan 0 offenders on the branch and 249 on unpatched main, adversarial corpus 0 false positives / 0 false negatives, rounds 14 to 16 fixtures all still correct.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 49de4d8fa1

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 1dd2fc4 into unslothai:main Jul 27, 2026
46 of 47 checks passed
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.

2 participants