Skip to content

Stop four POSIX-only test modules from failing to collect on Windows - #11457

Merged
danielhanchen merged 21 commits into
mainfrom
tests/windows-collect-geteuid
Sep 21, 2026
Merged

danielhanchen merged 21 commits into
mainfrom
tests/windows-collect-geteuid

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 21, 2026 •

Copy link
Copy Markdown
Member

A @pytest.mark.skipif decorator is evaluated at collection, so an unguarded os.geteuid() in one does not skip the test on Windows. It raises AttributeError while the module is being imported and takes the whole file down with it, and every test in that file is reported as a collection error rather than a skip.

The org CI runs the Python suites on Linux only, so none of this is visible here. It surfaced on a windows-latest staging run of tests/python/test_docker_rocm.py, which errored out entirely while the same file reported 70 passed on ubuntu-latest and macos-15:

tests/python/test_docker_rocm.py:548: in TestRocmEntrypoint
    @pytest.mark.skipif(os.geteuid() == 0, reason = "root reads a mode-0 file")
E   AttributeError: module 'os' has no attribute 'geteuid'

The fix

Six decorators across four files:

file tests lost on Windows
tests/python/test_docker_rocm.py the whole module (70 on this branch)
tests/python/test_docker_run_output_publish.py the whole module
tests/python/test_docker_studio_home_volume.py the whole module
tests/python/test_docker_nb_sync_publish_ownership.py the whole module

All six are POSIX-semantics tests: mode bits, CAP_DAC_OVERRIDE, chown to another uid. So the guard is os.name rather than a fake euid. On Windows they should skip, and the condition now says so, which also reads as the intent: "needs POSIX mode bits, and root ignores them".

Three guarded forms were already in the tree (os.name != "posix" or ..., ... if hasattr(os, "geteuid") else ..., getattr(os, "geteuid", lambda: 1)()), so this is bringing four stragglers in line rather than inventing a convention.

Why a test came with it

The next one will be just as invisible. tests/python/test_posix_only_marks_import_on_windows.py walks every module under tests/ for an os.geteuid evaluated at import time with nothing to spare it, accepting all three existing guard forms, and ignoring calls inside a function body, which only run on a platform the test already reached.

Reverting the four file edits with the scan kept lists exactly the six sites:

E   AssertionError: os.geteuid is evaluated at import with nothing to spare it on Windows,
E   so the whole module fails to collect there rather than skipping:
E       tests/python/test_docker_nb_sync_publish_ownership.py:168
E       tests/python/test_docker_nb_sync_publish_ownership.py:202
E       tests/python/test_docker_rocm.py:548
E       tests/python/test_docker_run_output_publish.py:95
E       tests/python/test_docker_run_output_publish.py:144
E       tests/python/test_docker_studio_home_volume.py:467

It also carries two tests of its own, so a scan that silently stopped matching anything fails rather than passes.

Tests

111 passed, 2 skipped across the four files plus the new one. No production code is touched.

The Windows run

Staged on an owned repo, since the org Actions queue is 200+ runs deep and runs the Python suites on Linux only anyway. The five files, on windows-latest:

before after
collection 1 error, 0 tests from four modules collects
result - 61 passed, 35 skipped, 50 failed

ubuntu-latest is 144 passed, 2 skipped. The new scan file contributes no failure on any of the three.

The 50 are a different, pre-existing class and not this PR's to fix: test_docker_studio_home_volume.py and test_docker_nb_sync_publish_ownership.py run the Linux container's own shell scripts (bash docker/studio_home.sh, ln -T, mv -T) against the host, which Git-Bash on Windows cannot serve, and macos-15 fails 24 of the same for the same reason (ln: illegal option -- T, BSD coreutils). They have never run on either platform, so nothing regresses; they were invisible behind the collection error before. Whether those suites should carry a module-level POSIX skip or the scripts should be made portable is a separate decision, and I have not made it here.

What this PR claims is only the first row of that table.

What the scan does not do

Written down in _import_time_expressions rather than approximated, after a long review thread established that each approximation rejects somebody's correct code:

  • only the module body, class bodies, if (by the Windows value of its test), and a definition's decorators, defaults and eager annotations are modelled. try, while, for, with and match are skipped whole.
  • a module-level helper called at import (def is_root(): return os.geteuid() == 0, then ROOT = is_root()) is not followed into.
  • a module that writes os.geteuid = lambda: 0 and reads it back is reported although it would work. That is the loudest failure mode available and one line to fix in the module that provokes it; nothing in this tree does it.

All three boundaries would still have caught the six sites this PR fixes, because all six are decorators in a module or class body, which is the only spelling pytest reads at collection time.

A @pytest.mark.skipif decorator is evaluated at COLLECTION, so an unguarded
os.geteuid() in one does not skip the test on Windows: it raises AttributeError
while the module is being imported and takes the whole file down with it. Every
test in that file is then reported as a collection error, not as a skip.

The org CI runs the Python suites on Linux only, so this is invisible here. It
showed up on a windows-latest run of tests/python/test_docker_rocm.py, which
errored out entirely while the same file reported 70 passed on ubuntu-latest and
macos-15:

  tests/python/test_docker_rocm.py:548: in TestRocmEntrypoint
      @pytest.mark.skipif(os.geteuid() == 0, reason = "root reads a mode-0 file")
  E   AttributeError: module 'os' has no attribute 'geteuid'

Six decorators across four files, all of them POSIX-semantics tests (mode bits,
CAP_DAC_OVERRIDE, chown to another uid), so the guard is os.name rather than a
fake euid: on Windows they should skip, which is what the condition now says.
Three guarded forms were already in the tree; this uses the one that also reads
as an intent, "needs POSIX mode bits".

The scan that found them is added as a test, because the next one will be just
as invisible: it walks every module under tests/ for an os.geteuid evaluated at
import time with nothing to spare it, accepting all three existing guard forms
and ignoring calls inside a function body, which only run on a platform the test
already reached. It fails with those six listed when the fix is reverted.

111 passed, 2 skipped across the four files plus the new one.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-21T18:43:56.107434Z b5bbe24 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

ℹ️ 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 +93 to +94
if isinstance(guard, ast.Call): # the getattr form
return True

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Restrict call guards to the validated getattr form

Any call returned by _guards is treated as protective here, not just getattr(os, "geteuid", ...). For example, @pytest.mark.skipif(is_ci() or os.geteuid() == 0, ...) passes this scan because is_ci() is an ast.Call, but on Windows it still raises AttributeError whenever is_ci() is false. This lets the exact collection regression this test is intended to prevent pass unnoticed; validate the call itself as the accepted getattr form instead of accepting every call.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, and it is the hole that matters most: is_ci() or os.geteuid() == 0 short-circuits only when is_ci() is true, so on Windows it still raises the rest of the time, and the scan would have waved through exactly what it exists to catch. Only os.name and hasattr(os, "geteuid") count now.

Dropping the call branch cost nothing in the end: getattr(os, "geteuid", lambda: 1)() names the function with a string, so it has no os.geteuid attribute node and never reaches the scan in the first place. Fixed in f569240, with a test on the is_ci() shape.

Comment on lines +104 to +107
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
for decorator in child.decorator_list:
yield decorator
yield from walk(child, isinstance(child, ast.ClassDef) and import_time)

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 function defaults evaluated during import

When the scanner encounters a function definition, it yields only its decorators and traverses everything else with import_time=False. Default argument expressions are nevertheless evaluated when the module defines the function, so a test helper such as def helper(uid=os.geteuid()): ... still makes collection fail on Windows while this new repository-wide check reports success. Include defaults and other eagerly evaluated definition expressions in the import-time scan.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct. A default is evaluated where the def is, not where the call is, so def helper(uid = os.geteuid()): ... breaks collection exactly like a decorator does, and walking it with import_time False was wrong. Defaults and keyword-only defaults are scanned in f569240, with a test. Widening it found no new offenders in the tree.

…default is import time

Both from review, both real.

Any ast.Call returned by _guards was treated as protective, so that
`is_ci() or os.geteuid() == 0` passed the scan while still raising on Windows
every time is_ci() is false: the exact regression the scan exists to catch. Only
os.name and hasattr(os, "geteuid") count now. The getattr(os, "geteuid",
lambda: 1)() form needs no case of its own after all, because it names the
function with a string and so has no os.geteuid attribute node to find.

A function's default arguments were walked with import_time False along with its
body, but a default is evaluated where the `def` is, not where the call is, so
`def helper(uid = os.geteuid()): ...` breaks collection exactly like a decorator
does. Defaults and keyword-only defaults are now scanned.

Two tests, one per hole. No new offenders in the tree from the widened scan.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: f569240401

ℹ️ 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 +92 to +94
return any(
_mentions_os_name(guard) or _is_hasattr_geteuid(guard) for guard in _guards(expr)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Validate the polarity of os.name guards

When a site uses os.name == "posix" or os.geteuid() == 0 (or os.name != "posix" and os.geteuid() == 0), Windows still evaluates the missing geteuid attribute, but _mentions_os_name makes _is_guarded accept it merely because os.name appears in a preceding operand. Validate the comparison and Boolean polarity rather than the presence of os.name; otherwise this repository-wide check can pass the same collection failure it is meant to prevent.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it is the sharpest of the three: the guard was matched by presence, so os.name == "posix" or os.geteuid() == 0 passed while sparing nothing. There is now a small evaluator that asks what a subexpression is worth ON WINDOWS and returns None when the source does not say. or needs a True to its left, and needs a False, and the conditional form is read by which branch the call sits in. Tests cover the mirrored ("posix" != os.name), negated (not (os.name == "posix")) and == "nt" spellings, and both failing polarities. 67617c7.

Comment on lines +109 to +111
args = child.args
for default in (*args.defaults, *(d for d in args.kw_defaults if d)):
yield default

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 eagerly evaluated function annotations

In a test module without from __future__ import annotations on supported Python 3.9–3.13, def helper(uid: os.geteuid()): ... evaluates the annotation while defining the function and therefore still fails collection on Windows. The fresh evidence after the earlier default-argument report is that this revision now yields only positional and keyword defaults, while argument and return annotations are traversed with import_time=False, so the scan reports success for this import-time call.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes. Annotations are evaluated at the def unless the module carries from __future__ import annotations, so they are scanned now, and only when that import is absent. The test asserts both halves of that: the same source is flagged without the future import and clean with it. 67617c7.

Comment on lines +103 to +105
if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
for decorator in child.decorator_list:
yield decorator

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 runtime context for nested function definitions

When a local function is defined inside a test or helper, its decorators and defaults are not evaluated until the enclosing function runs, but this branch yields them unconditionally even after entering the outer body with import_time=False. Consequently a runtime-only local decorator containing os.geteuid() makes this new repository-wide test fail despite being unable to break module collection; process these expressions only when the enclosing definition itself is evaluated at import time.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, and this one cuts the other way: it would have made the scan report a runtime-only local decorator as an import-time failure. Definition expressions are only yielded when the definition itself is reached at import, so a method of a module-level class still counts and a def (or class) inside a function does not. 67617c7.

danielhanchen pushed a commit that referenced this pull request Sep 21, 2026
…CUDA image does (#11286)

The ROCm Studio image from #11218 runs Studio alone, so an AMD user who follows the
Docker quickstart has nowhere to open a notebook. The CUDA core image already carries
JupyterLab, the notebook tooling and the notebooks, which Dockerfile.studio inherits;
the ROCm base carries none of it, so Dockerfile.studio-rocm installs it itself, piece
by piece against the CUDA files, with a suite pinning the two together.

supervisord and studio_launch.sh are not new here: both are already on main driving the
CUDA Studio image, and this points the ROCm image at them rather than adding a second
way to run two services in one container.

An earlier revision also enabled key-only sshd on :22. That rode along with the
notebooks and had no argument of its own, so it was stripped: openssh-server is not
installed, EXPOSE is 8000 8888, and studio_launch.sh's existing `command -v sshd` gate
keeps the shared supervisord program down.

The org Actions queue is 200+ runs deep, so this PR's own checks never reported. Run on
staging instead: 70 passed on ubuntu-latest and on macos-15, and the full repo suite at
8034 + 11465 passed. Eight failures there, seven of which reproduce on a clean
origin/main worktree and one of which pre-commit.ci fixed on the branch. The
windows-latest leg errors on an unguarded os.geteuid() that has been in
tests/python/test_docker_rocm.py since #10820, byte-identical on main; fixed separately
in #11457.

Not verified: the GPU. The author's run went through Docker Desktop's /dev/dxg, where
the torch wheel's bundled HSA runtime has no DXG path, so torch.cuda.is_available() was
False and no notebook in this image has trained.

Closes #11235
…alone

Three more from review, all real, all in the scan rather than the fix.

The guard was matched by presence. `os.name == "posix" or os.geteuid() == 0`
names the same attribute as the real guard and spares nothing, since on Windows
the left side is false and the call is reached, and the scan accepted it. There
is now a small evaluator that asks what a subexpression is worth ON WINDOWS and
returns None when the source does not say, so `or` needs a True to its left and
`and` needs a False, and the conditional form is read by which branch the call
is in. The mirrored, negated and "nt" spellings are covered by tests.

Annotations are evaluated at the `def` unless the module carries
`from __future__ import annotations`, so `def helper(uid: os.geteuid()): ...`
breaks collection exactly like a default does. They are scanned, and only when
that future import is absent.

A `def` nested inside another function is the other way round: nothing of it is
evaluated until the outer one runs, so its decorators and defaults cannot break
collection. They were being yielded unconditionally, which would have reported a
runtime-only local decorator as an import-time failure. Only definitions reached
at import are scanned now, which still includes a method of a module-level class
and excludes a class defined inside a function.

Three tests, one per item, plus a _flagged() helper so each reads as a source
snippet and its verdict. 116 passed, 2 skipped across the five files.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: 67617c7848

ℹ️ 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 +47 to +50
isinstance(node, ast.Attribute)
and node.attr == "geteuid"
and isinstance(node.value, ast.Name)
and node.value.id == "os"

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 string-based geteuid lookups

An import-time expression such as @pytest.mark.skipif(getattr(os, "geteuid")() == 0, ...) still raises AttributeError on Windows, but this detector only recognizes ast.Attribute nodes, so the repository scan reports success. Detect getattr uses too and accept them only when they provide a callable fallback, rather than assuming every string-based lookup is the safe three-argument form.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed: getattr(os, "geteuid")() raises exactly as os.geteuid() does, and it is the THREE-argument form whose fallback makes it safe. The scan was reading any string lookup as the safe one. Both spellings are sites now, the three-argument form still is not, and the test asserts both halves. 24213c3.

Comment on lines +192 to +196
if import_time:
# the WHOLE statement, never its subexpressions as well: a guard
# lives in the enclosing `or`, and yielding the bare call too would
# report every guarded site as unguarded
yield child

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 lambda bodies out of the import-time scan

For a module-level assignment such as helper = lambda: os.geteuid(), yielding the whole Assign lets the later ast.walk descend into the lambda body and report an import-time violation, even though that body is not evaluated until the helper is called. This contradicts the scan's runtime-body exclusion and will make the repository test fail for safe lambda helpers; traverse lambda defaults eagerly but exclude their bodies, as is already done for named functions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it contradicted the scan's own rule. Sites are now collected with a traversal that skips a lambda body and keeps its defaults, since those are evaluated at the lambda rather than at the call: helper = lambda: os.geteuid() is clean, helper = lambda uid = os.geteuid(): uid is flagged. 24213c3.

…s runtime

Two more from review.

getattr(os, "geteuid")() raises on Windows exactly as os.geteuid() does; it is
the THREE-argument form whose fallback makes it safe, and the scan was reading
any string lookup as the safe one. Both spellings are sites now, and the
three-argument form still is not.

A lambda body is not evaluated where the lambda is written, so
`helper = lambda: os.geteuid()` is as safe as the same line inside a def. The
scan yielded the whole assignment and then walked into the body, which would
have reported a safe helper. Sites are collected with a traversal that skips a
lambda's body and keeps its defaults, since those are evaluated at the lambda.

Two tests, one per item, each asserting the safe counterpart as well: the
three-argument getattr, and a lambda default.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 24213c3fdb

ℹ️ 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 +62 to +63
and len(node.args) == 2
and not 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 Validate callable fallbacks before accepting getattr

The fresh implementation after the earlier getattr report still treats every three-argument form as safe by recognizing only len(node.args) == 2. On Windows, @pytest.mark.skipif(getattr(os, "geteuid", None)() == 0, ...) selects None and raises TypeError during collection, while this scanner reports no offender; Linux masks the problem because the real function is selected. Only exclude an invoked three-argument lookup after verifying that its fallback can be called with the supplied arguments.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes. getattr(os, "geteuid", None)() picks None on Windows and raises TypeError during collection, and Linux never shows it because the real function is picked there. A three-argument form is only excluded now if the fallback can be called: a literal is a site, and a name, attribute, call or lambda is taken at its word, since whether it accepts no arguments is not decidable from the file. Four fallbacks covered by test. 32bb88d.

Comment on lines +224 to +228
if import_time:
# the WHOLE statement, never its subexpressions as well: a guard
# lives in the enclosing `or`, and yielding the bare call too would
# report every guarded site as unguarded
yield child

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 Honor statement-level platform guards

When a test module safely places a lookup under if os.name == "posix":, yielding the entire ast.If causes _geteuid_sites to descend into its body, but _spared_on_windows understands only Boolean expressions and IfExp, so the lookup is reported even though Windows never evaluates it. The same traversal also reaches runtime-only function bodies nested under a module-level compound statement. This repository-wide test will therefore reject valid guarded code; preserve statement control flow or traverse only the expressions that are actually evaluated on Windows.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct on both halves, and the second is the worse one: yielding whole statements reached function bodies at any nesting depth, which are never evaluated at import. The walk is over statements now. An if yields its test and then only the branch Windows can reach, a def yields its decorators, defaults and eager annotations and never its body, a class recurses, and any other compound statement yields its header expressions and recurses its blocks. A plain statement is still yielded whole, since a guard lives in the enclosing or. Tested in both polarities plus an undecidable test, and a def body under try/for against the same def's decorator. 32bb88d.

… it is callable

Two more from review, both about the scan reading more than actually runs.

A lookup under `if os.name == "posix":` is never reached on Windows, and the
scan yielded the whole `if` and then walked it, so it reported the body anyway.
The same traversal reached function bodies nested under any compound statement,
which are not evaluated at import however deep the nesting. The walk is now over
statements: an `if` yields its test and then only the branch Windows can reach,
a def yields its decorators, defaults and eager annotations and never its body,
a class recurses, and any other compound statement yields its header expressions
and recurses its blocks. A plain statement is still yielded whole, because a
guard lives in the enclosing `or`.

getattr(os, "geteuid", None)() picks None on Windows and raises TypeError during
collection, which Linux never shows because the real function is picked there.
A three-argument form is only safe if the fallback can be called, so a literal
fallback is now a site; a name, attribute, call or lambda is taken at its word,
since whether it accepts no arguments is not decidable from the file.

Three tests: the statement guard in both polarities plus an undecidable test, a
def body under try/for against the same def's decorator, and the four getattr
fallbacks. 13 in the file, 116 passed and 2 skipped across the five files.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: 32bb88d3c0

ℹ️ 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 +52 to +56
isinstance(node, ast.Attribute)
and node.attr == "geteuid"
and isinstance(node.value, ast.Name)
and node.value.id == "os"
):

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 direct geteuid imports

When a test uses from os import geteuid, the import succeeds on Linux but raises ImportError during collection on Windows; _is_os_geteuid only recognizes attributes whose base name is literally os (plus getattr), so this repository-wide check reports success for that spelling and cannot prevent the same collection failure. Treat the direct import itself, and import-bound calls where applicable, as unsafe on Windows.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agreed. from os import geteuid fails at the import line, earlier than anything a skipif could reach. The import statement is a site now, and the statement-level os.name guard applies to it like any other statement, which the test asserts alongside the aliased-list spelling. fa86c02.

Comment on lines +192 to +194
yield from node.decorator_list
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Scan class header expressions at definition time

For a module-level class such as class C(Base if os.geteuid() else Other): ..., the base expression is evaluated during import and fails on Windows, but this branch returns for every ClassDef after yielding only decorators. Class bases and keyword expressions such as metaclass= therefore bypass the new scan even though the class body itself is traversed; include those header expressions in _definition_expressions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, and the asymmetry was the giveaway: the class BODY was traversed while its header was not. Bases and keywords are scanned now, so both class C(Base if os.geteuid() else Other) and metaclass = meta(os.geteuid()) are caught, with a guarded base asserted clean. fa86c02.

Comment on lines +72 to +77
# A fallback saves the lookup, but only if it can then be called: getattr(os,
# "geteuid", None)() picks None on Windows and raises TypeError instead, which Linux
# never shows because the real function is picked there. A literal is never callable;
# a name, attribute, call or lambda is taken at its word, since whether it accepts no
# arguments is not decidable from this file.
return isinstance(node.args[2], ast.Constant)

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 lambda fallback arity before exempting it

Fresh evidence after the earlier fallback report is that every non-constant fallback is now accepted without checking whether it can handle the actual invocation. For example, getattr(os, "geteuid", lambda required: 1)() succeeds on Linux because the real zero-argument function is selected, but raises TypeError on Windows while this scan reports no site; inspect directly knowable lambda signatures and call arguments before excluding the lookup.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fair, "the fallback is a lambda" was not the rule I stated. A lambda fallback is now checked against the actual call, and anything the source does not settle (a starred argument at the call site) is left alone, since a false alarm is worse than a miss in a scan everybody has to keep green.

This one also found a bug of mine: _is_guarded was still walking the flat tree rather than the site traversal, because ruff-format had collapsed the line my earlier edit matched on, so the lambda-body exclusion reached only two of its three callers. All three go through _geteuid_sites now. fa86c02.

…ot be called

Three more from review, and one bug of my own found while fixing them.

`from os import geteuid` raises ImportError on Windows at the import line, so no
skipif downstream can help, and the scan only knew the attribute spelling. The
import statement is a site now, and the statement-level `os.name` guard applies
to it like anything else.

A class header runs where the class is written: `class C(Base if os.geteuid()
else Other)` and `metaclass = meta(os.geteuid())` both fail on Windows, and only
the class BODY was being traversed. Bases and keywords are scanned.

getattr(os, "geteuid", lambda required: 1)() picks the lambda on Windows and
then calls it wrongly, so "the fallback is a lambda" was not enough. A lambda
fallback is checked against the actual call, and anything the source does not
settle (a starred argument at the call site) is left alone, because a false
alarm is worse than a miss in a scan everybody has to keep green.

The bug: _is_guarded was still walking the flat tree rather than the site
traversal, because ruff-format had collapsed the line an earlier edit matched
on. So the lambda-body exclusion only applied to two of its three callers. All
three go through _geteuid_sites now, which is what made these three tests fail
until it was fixed.

16 tests in the file. 135 passed, 2 skipped across the five files.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: fa86c0271f

ℹ️ 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 +139 to +141
for child in ast.iter_child_nodes(node):
if isinstance(node, ast.Lambda) and child is node.body:
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 bodies of immediately invoked lambdas

Fresh evidence beyond the earlier lambda-body fix is that this exclusion is unconditional even when the lambda is the callee of an enclosing ast.Call. For example, a module-level ROOT = (lambda: os.geteuid())() executes the body during import and fails on Windows, but _flagged returns no sites because the traversal skips that body; only defer the body when the lambda is not invoked as part of the import-time expression.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right: the body is deferred because it has not been called yet, and (lambda: os.geteuid())() calls it on the spot. Only a lambda that is not the callee of a call in the same expression keeps the deferral, with a plain lambda helper asserted clean beside it. e565f67.

Comment on lines +53 to +56
isinstance(node, ast.Attribute)
and node.attr == "geteuid"
and isinstance(node.value, ast.Name)
and node.value.id == "os"

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 aliases of the os module

When a test imports the module as an alias, such as import os as _os followed by an import-time _os.geteuid(), this predicate rejects the attribute solely because its base identifier is not literally os. The repository scan then passes even though that module still raises AttributeError while collecting on Windows; collect aliases from ast.Import nodes and recognize them in lookups and guards.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes. Rather than thread an alias set through every predicate, names bound by import os as X are normalised back to os before anything is scanned, so a guard spelled _os.name != "posix" moves with the lookup. Tested both ways, plus a name that is not the alias. e565f67.

# never shows because the real function is picked there. A literal is never callable;
# a name, attribute, call or lambda is taken at its word, since whether it accepts no
# arguments is not decidable from this file.
return isinstance(node.args[2], ast.Constant)

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 literal-fallback errors to invoked lookups

A three-argument lookup with a literal fallback is safe unless its result is called: GETEUID = getattr(os, "geteuid", None) simply binds None on Windows. Returning true here without inspecting the parent makes the new repository-wide test reject that valid feature-detection pattern, even though import and collection succeed; report the non-callable fallback only when this lookup is actually used as a call target.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is the one that mattered most of the three, because it is a false positive rather than a miss: GETEUID = getattr(os, "geteuid", None) is ordinary feature detection and the scan would have rejected it. The three-argument form is judged where the surrounding call is visible now, so an uninvoked lookup is never a site and the invoked one still is. e565f67.

Three more from review, the last of which is a false POSITIVE rather than a miss
and so the one worth having.

`GETEUID = getattr(os, "geteuid", None)` binds None on Windows and collects
fine; only calling the result fails. The scan rejected the bind, which is
ordinary feature detection. The three-argument form is judged where the call
around it is visible now, and an uninvoked one is never a site.

A lambda body is deferred because it has not been called yet, which
`(lambda: os.geteuid())()` is not: it runs on the spot. Only a lambda that is
not the callee of a call in the same expression keeps the deferral.

`import os as _os` then `_os.geteuid()` raises the same AttributeError. Aliases
are normalised back to `os` before anything is scanned, rather than threading an
alias set through every predicate, so guards written against the alias move with
it. Only names bound by `import os as X` are rewritten.

Three tests, each with its safe counterpart: a plain lambda helper, a guard
spelled through the alias, and a name that is not the alias. 19 in the file, 138
passed and 2 skipped across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: 245ab31327

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

and node.value.id == "os"
# `os.geteuid = lambda: 0` CREATES the attribute on Windows rather than reading
# it, and tests/test_allow_cpu_import_driverless.py does exactly that
and not isinstance(node.ctx, ast.Store)

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 Treat augmented attribute assignments as reads

Unlike the previously fixed plain-store case, an augmented assignment such as os.geteuid += 1 reads the existing attribute before writing it. Its AST attribute still has Store context, so this condition suppresses it and _flagged returns no offender, even though the statement succeeds on Linux and raises AttributeError during Windows collection. Distinguish ordinary assignment targets from AugAssign targets rather than excluding every Store node.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct: an augmented target carries a Store context but is fetched before it is stored, so the rule that spares os.geteuid = lambda: 0 was sparing os.geteuid += 1 too. Admitted as a site, with the plain assignment asserted clean beside it. ab39fce.

From review. `os.geteuid += 1` carries a Store context in the AST, so the rule
that spares `os.geteuid = lambda: 0` was sparing it too, but an augmented
target is fetched before it is stored and so raises on Windows like any read.
Admitted as a site, with the plain assignment asserted clean beside it.

30 in the file, 149 passed and 2 skipped across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: ab39fce553

ℹ️ 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 +181 to +182
if _is_os_geteuid(node):
yield 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 Track definitions before flagging later reads

Fresh evidence beyond the earlier store-context report is os.geteuid = lambda: 0; ROOT = os.geteuid(): on Windows the first statement creates the attribute, so the later call succeeds, but expressions are scanned independently and this load is always yielded as an offender. The repository-wide check therefore rejects a valid module-level platform shim unless the statement walker tracks that geteuid has already been defined.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is the one of the three that would have bitten a real file: tests/test_allow_cpu_import_driverless.py writes os.geteuid = lambda: 0, and a read after it finds the attribute even on Windows. Sites are walked in source order now and stop at the definition, with reads before it still reported. os.geteuid += 1 does not count as a definition, since it reads first and has already raised.

The repo scan and the test helper share one _offending_sites now, so an ordering rule cannot apply to one and not the other, which is how an earlier fix here went half-applied. bf6aa65.

Comment on lines +205 to +209
if isinstance(node, ast.GeneratorExp) and node not in unpacked:
# `GEN = (os.geteuid() for _ in xs)` only builds a generator; nothing but the
# first iterable is evaluated until something iterates it, and whether a call
# around it does cannot be read off the source: `iter(...)` does not.
stack.append(node.generators[0].iter)

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 generators consumed by destructuring assignments

Fresh evidence beyond the starred-unpacking fix is ROOT, = (os.geteuid() for _ in range(1)): assignment unpacking necessarily advances the generator during module import, so Linux succeeds while Windows raises AttributeError. Because every non-starred generator is reduced to its first iterable here, _flagged returns no offender; treat a generator used as the RHS of an unpacking assignment as consumed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, unpacking has to advance the generator, same as the starred form. Both are consumption the source states outright rather than something to infer from a call. bf6aa65.

Comment on lines +135 to +139
return not isinstance(
fallback,
(
ast.Constant,
ast.List,

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 statically numeric arithmetic fallbacks

Fresh evidence beyond the earlier literal and unary-fallback reports is getattr(os, "geteuid", 1 + 2)(): Linux selects the real zero-argument function, but Windows evaluates the fallback to integer 3 and raises TypeError when calling it. A literal ast.BinOp is absent from this non-callable check, so the repository scan reports no offender; recognize arithmetic expressions whose operands make their non-callable result statically certain.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, 1 + 2 is a BinOp and still a number nobody can call. Rejected only when every leaf is a literal, since a + b could be anything. bf6aa65.

…al arithmetic

Three from review, and the first is the one that would have bitten a real file.

`os.geteuid = lambda: 0` puts the attribute there, so every read after it finds
it even on Windows, and expressions were scanned independently so the later read
was still reported. tests/test_allow_cpu_import_driverless.py writes exactly
that line. Sites are walked in source order now and stop at the definition;
reads BEFORE it are still reported, and `os.geteuid += 1` is not a definition,
since it reads first and has already raised.

`ROOT, = (os.geteuid() for _ in xs)` has to advance the generator to unpack it,
like the starred form already handled.

`1 + 2` is a BinOp rather than a Constant, and still a number nobody can call.
Only when every leaf is a literal: `a + b` could be anything.

The repo scan and the test helper now share _offending_sites, so the ordering
rule cannot apply to one and not the other, which is how an earlier fix went
half-applied. 33 in the file, 152 passed and 2 skipped across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: bf6aa65dbd

ℹ️ 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 +412 to +413
if _assigns_os_geteuid(expr):
return # from here on the attribute exists, even on Windows

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 only after an unconditional geteuid definition

Fresh evidence after the earlier store-tracking fix is that a yielded assignment is not necessarily executed: for if is_ci(): os.geteuid = lambda: 0 followed by ROOT = os.geteuid(), Linux always succeeds because the native attribute exists, while Windows fails whenever is_ci() is false. The walker explores an undecidable if branch, but this unconditional return treats its store as definite and suppresses the later failing lookup; only terminate after definitions that are guaranteed on the Windows path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct, and it was the previous fix overreaching: any store the walker reached was treated as settling the question, including one in an if branch the scan cannot decide. The cutoff is now the first plain assignment in the MODULE BODY, which is where tests/test_allow_cpu_import_driverless.py writes its shim. A store inside an if, a try or a function counts for nothing, and neither does an augmented target. 3a83503.

From review. `if is_ci(): os.geteuid = lambda: 0` is not guaranteed to run on
Windows, so a read after it can still fail, and the previous version treated any
store the walker reached as settling the question.

The cutoff is now the first plain assignment in the MODULE BODY, which is where
tests/test_allow_cpu_import_driverless.py writes its shim. A store inside an
`if`, a `try` or a function counts for nothing, and neither does an augmented
target, which reads before it writes.

One test, with the unconditional form asserted clean beside it. 34 in the file,
153 passed and 2 skipped across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: 3a835037b8

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

(
statement.lineno
for statement in tree.body
if isinstance(statement, (ast.Assign, ast.AnnAssign)) and _assigns_os_geteuid(statement)

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 a value before treating AnnAssign as a definition

When a module contains os.geteuid: object without an RHS, Python does not create the attribute, so a later os.geteuid() still raises AttributeError on Windows. Including every ast.AnnAssign in defined_at suppresses that later lookup and lets the collection failure through; only an annotated assignment with a value should count as defining the attribute.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right, os.geteuid: int states a type and binds nothing. An AnnAssign needs a value to count as a definition. c9a0d28.

if _is_guarded(expr):
continue
for node in _geteuid_sites(expr):
if defined_at is None or node.lineno < defined_at:

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 a defining assignment's RHS before applying the cutoff

For os.geteuid = os.geteuid, Python evaluates the RHS before performing the store, so Linux succeeds but Windows raises before the attribute can be defined. Because the lookup has the same line as defined_at, this strict comparison suppresses it; the defining statement itself must still be scanned before later reads are ignored.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, os.geteuid = wrap(os.geteuid) looks the attribute up to wrap it, and that lookup is the one that fails. The definer's own right-hand side is scanned before it settles anything, which also let the lineno arithmetic go: the walk already yields module-body statements in order, so the definer is recognised as itself rather than by position. c9a0d28.

Comment on lines +412 to +416
defined_at = next(
(
statement.lineno
for statement in tree.body
if isinstance(statement, (ast.Assign, ast.AnnAssign)) and _assigns_os_geteuid(statement)

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 Normalize aliases before locating the definition cutoff

When a portable shim uses the recognized alias form—import os as _os; _os.geteuid = lambda: 0; ROOT = _os.geteuid()—defined_at is computed before _import_time_expressions normalizes _os to os, so the store is missed while the later read is normalized and incorrectly reported. Normalize the tree before this search so valid aliased shims are not rejected.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This one was a plain ordering bug: _normalise_os_aliases runs inside _import_time_expressions, which is called after the cutoff was computed, so import os as _os then _os.geteuid = lambda: 0 was not recognised as settling the reads after it. Normalised first now, with a test in both directions. c9a0d28.

All three from review, all in the cutoff added two commits ago.

The alias normalisation ran inside _import_time_expressions, which is called
AFTER the cutoff was computed, so `import os as _os` then
`_os.geteuid = lambda: 0` was not recognised as settling the reads that follow
it. Normalised first now. That one was a plain ordering bug.

`os.geteuid: int` states a type and binds nothing, so it settles nothing. An
AnnAssign needs a value to count.

`os.geteuid = wrap(os.geteuid)` looks the attribute up to wrap it, and that
lookup is the one that fails on Windows. The definer's own right-hand side is
scanned before it settles anything, which also drops the lineno arithmetic: the
walk already yields module-body statements in order, so the definer is
recognised as itself rather than by position.

Three tests, each with its counterpart. 37 in the file, 156 passed and 2 skipped
across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: c9a0d2801e

ℹ️ 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 +492 to +496
if statement.value is not None:
yield statement.value
if not isinstance(statement.target, ast.Name):
yield statement.target
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve annotated assignments as definition cutoffs

Fresh evidence beyond the earlier annotation reports is that, when annotations are deferred by from __future__ import annotations or Python 3.14, this branch yields only the RHS and target before returning. _offending_sites can therefore never match the original AnnAssign in definers, so the safe Windows shim os.geteuid: object = lambda: 0 followed by os.geteuid() is incorrectly reported; on supported Python 3.14 this also makes test_an_annotation_without_a_value_defines_nothing fail.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correct: the deferred branch yielded only the value and the target, so _offending_sites never matched the AnnAssign itself and nothing after it was spared. It yields the statement when it is a definer now, asserted with and without the future import. b5bbe24.

Comment on lines +224 to +228
if isinstance(node, ast.GeneratorExp) and node not in unpacked:
# `GEN = (os.geteuid() for _ in xs)` only builds a generator; nothing but the
# first iterable is evaluated until something iterates it, and whether a call
# around it does cannot be read off the source: `iter(...)` does not.
stack.append(node.generators[0].iter)

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 generators consumed by eager comprehensions

Fresh evidence beyond the starred and destructuring consumers is an inner generator used as the iterable of a list, set, or dict comprehension, such as ROOT = [x for x in (os.geteuid() for _ in range(1))]. The outer comprehension necessarily advances that generator during module import, so Windows raises AttributeError, but this blanket deferral visits only the generator's first iterable and _flagged returns no offender.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes, and it belongs with the starred and destructuring forms rather than with the call case: a list, set or dict comprehension runs on the spot, which the source states outright. A generator iterating a generator still defers, and that is asserted beside it. b5bbe24.

Comment on lines +206 to +209
isinstance(node, ast.ImportFrom)
and node.module == "os"
and any(alias.name == "geteuid" for alias in node.names)
):

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 relative imports from the stdlib os check

When a test package contains its own os.py, from .os import geteuid has node.module == "os" but imports that local module rather than the platform's stdlib os; it can therefore collect successfully on Windows. Because this condition ignores ImportFrom.level, the repository-wide scan flags both .os and ..os imports as missing Windows attributes and rejects valid modules; restrict this case to absolute imports.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

ImportFrom.level was simply not consulted, so .os and ..os both read as the stdlib. Fixed, with the absolute form asserted beside them. b5bbe24.

…efiner

Three from review.

`from .os import geteuid` names a package's own os.py, not the stdlib, and the
check ignored ImportFrom.level, so both .os and ..os were reported.

A list, set or dict comprehension runs on the spot, so a generator it iterates
is advanced there: `[x for x in (os.geteuid() for _ in xs)]`. Same class as the
starred and destructuring forms, which the source also states outright. A
generator iterating a generator still defers.

`os.geteuid: object = lambda: 0` is a definition whatever the annotation does,
and the deferred-annotation branch yielded only the value and target, so
_offending_sites never matched it and nothing after it was spared.

Three tests, each with its counterpart. 40 in the file, 159 passed and 2 skipped
across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 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: b5bbe24ad1

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

# _offending_sites matches the definer by identity, and it would never
# see this one otherwise: `os.geteuid: object = lambda: 0` under a
# deferred annotation settles the attribute like any other assignment
yield statement

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 rescanning deferred annotations on definers

When annotations are deferred by from __future__ import annotations or Python 3.14, the new full-statement yield makes _geteuid_sites inspect the annotation that the earlier branch intentionally skipped. For example, os.geteuid: os.geteuid() = lambda: 0 safely defines the attribute without evaluating its annotation, but _flagged reports the annotation and rejects the module. Preserve the AnnAssign as a cutoff marker without scanning its deferred annotation.

Useful? React with 👍 / 👎.

Comment on lines +423 to +428
definers = {
statement
for statement in tree.body
if isinstance(statement, ast.Assign)
or (isinstance(statement, ast.AnnAssign) and statement.value is not None)
if _assigns_os_geteuid(statement)

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 Count definitions on Windows-guaranteed branches

A definite Windows branch is different from the previously discussed undecidable conditional: if os.name == "nt": os.geteuid = lambda: 0 is guaranteed to define the attribute before a following os.geteuid() on Windows. The walker already proves that branch is reached, but restricting definers to direct tree.body assignments makes the later safe call get reported, so a valid platform shim fails this repository-wide check.

Useful? React with 👍 / 👎.

Comment on lines +384 to +386
for node in ast.walk(tree):
if isinstance(node, ast.Name) and node.id in aliases:
node.id = "os"

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 alias normalization after the alias is rebound

The normalization rewrites every matching name in the module regardless of later bindings. Thus import os as _os; _os = shim; ROOT = _os.geteuid() is safe on Windows when shim supplies the method, but the final load is rewritten to os.geteuid() and falsely rejected. Alias handling needs to respect source-order rebinding rather than globally mutating all uses of the name.

Useful? React with 👍 / 👎.

The cutoff was added to spare a module that writes os.geteuid itself and then
reads it back, on the strength of tests/test_allow_cpu_import_driverless.py.
That line is inside a source STRING, a probe script the test writes out and runs
in a subprocess, so ast.parse never reaches it as code and the scan has never
seen it. There is no module in this tree the cutoff protects.

What it cost is measurable: four review rounds, a dozen items, and two bugs of
my own. The alias normalisation ran after the cutoff was computed. The deferred
annotation branch never yielded the statement the cutoff matched on. Every fix
in it produced three more, because knowing whether a module has really replaced
os.geteuid means knowing which branch ran, whether the alias was rebound, and
whether the annotation was deferred, which is the interpreter this scan already
declined to be two commits earlier.

So it goes, and the boundary is stated instead: a module that writes the
attribute and reads it back IS reported, wrongly, and that is the loudest and
cheapest failure mode available, one line to fix in the module that provokes it.
The simple half stays, because it needs nothing tracked: an assignment is not a
lookup, and an augmented assignment is.

Six tests pinned the cutoff and go with it, replaced by one that asserts the
boundary and says why. 35 in the file, 154 passed and 2 skipped across the five.
@danielhanchen

Copy link
Copy Markdown
Member Author

All three are correct, and all three are about the definition cutoff, as were the three before them and three of the three before those. That is the answer: the cutoff is gone in 9b62720.

It was added to spare a module that writes os.geteuid itself and then reads it back, on the strength of tests/test_allow_cpu_import_driverless.py. That line turns out to be inside a source string, a probe script the test writes out and runs in a subprocess, so ast.parse never reaches it as code and the scan has never seen it. There is no module in this tree the cutoff protects.

What it cost is measurable: four rounds, a dozen items, and two bugs of my own, both of which you found. The alias normalisation ran after the cutoff was computed. The deferred-annotation branch never yielded the statement the cutoff matched on. This round would have added a third, since a definer yielded back into the scan gets its deferred annotation rescanned. Every fix in it produced three more, because knowing whether a module has really replaced os.geteuid means knowing which branch ran, whether the alias was rebound and whether the annotation was deferred: the interpreter this scan already declined to be.

So the boundary is stated instead, beside the one about helpers: a module that writes the attribute and reads it back is reported, wrongly, and that is the loudest and cheapest failure mode available, one line to fix in the module that provokes it. The simple half stays because it needs nothing tracked: an assignment is not a lookup, and an augmented assignment is.

Six tests pinned the cutoff and go with it, replaced by one that asserts the boundary and says why it is there. 35 in the file, 154 passed and 2 skipped across the five.

On the PR as a whole: the change that fixes anything is six decorators in four files, and it has not moved in fifteen rounds. It is proven on a real windows-latest runner, where those four modules went from a collection error contributing zero tests to 45 passed and 35 skipped. Everything since has been the regression scan, which now has a boundary written down. I am merging on that basis.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 21, 2026
@danielhanchen
danielhanchen merged commit 1d8a608 into main Sep 21, 2026
17 of 18 checks passed
@danielhanchen
danielhanchen deleted the tests/windows-collect-geteuid branch September 21, 2026 19:09
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…CUDA image does (unslothai#11286)

The ROCm Studio image from unslothai#11218 runs Studio alone, so an AMD user who follows the
Docker quickstart has nowhere to open a notebook. The CUDA core image already carries
JupyterLab, the notebook tooling and the notebooks, which Dockerfile.studio inherits;
the ROCm base carries none of it, so Dockerfile.studio-rocm installs it itself, piece
by piece against the CUDA files, with a suite pinning the two together.

supervisord and studio_launch.sh are not new here: both are already on main driving the
CUDA Studio image, and this points the ROCm image at them rather than adding a second
way to run two services in one container.

An earlier revision also enabled key-only sshd on :22. That rode along with the
notebooks and had no argument of its own, so it was stripped: openssh-server is not
installed, EXPOSE is 8000 8888, and studio_launch.sh's existing `command -v sshd` gate
keeps the shared supervisord program down.

The org Actions queue is 200+ runs deep, so this PR's own checks never reported. Run on
staging instead: 70 passed on ubuntu-latest and on macos-15, and the full repo suite at
8034 + 11465 passed. Eight failures there, seven of which reproduce on a clean
origin/main worktree and one of which pre-commit.ci fixed on the branch. The
windows-latest leg errors on an unguarded os.geteuid() that has been in
tests/python/test_docker_rocm.py since unslothai#10820, byte-identical on main; fixed separately
in unslothai#11457.

Not verified: the GPU. The author's run went through Docker Desktop's /dev/dxg, where
the torch wheel's bundled HSA runtime has no DXG path, so torch.cuda.is_available() was
False and no notebook in this image has trained.

Closes unslothai#11235
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…nslothai#11457)

A @pytest.mark.skipif decorator is evaluated at COLLECTION, so an unguarded
os.geteuid() in one does not skip the test on Windows: it raises AttributeError
while the module is being imported and takes the whole file down with it. Every
test in that file is then reported as a collection error rather than a skip.

The org CI runs the Python suites on Linux only, so this has never been visible
here. It surfaced on a windows-latest staging run of tests/python/test_docker_rocm.py,
which errored out entirely while the same file reported 70 passed on ubuntu-latest
and macos-15. Six decorators across four files, all POSIX-semantics tests (mode
bits, CAP_DAC_OVERRIDE, chown to another uid), so the guard is os.name rather
than a fake euid: on Windows they should skip, which is what the condition now
says.

Measured on windows-latest across the five files: a collection error contributing
zero tests from four modules becomes 61 passed, 35 skipped, 50 failed. The 50 are
a separate pre-existing class, the Linux container's own shell scripts run against
a Windows host, which macos-15 fails 24 of for the same reason (BSD coreutils has
no ln -T). They have never run on either platform; they were invisible behind the
collection error. ubuntu-latest is 144 passed, 2 skipped.

The scan that found the six comes with them, because the next one would be just as
invisible: it walks every module under tests/ for an os.geteuid evaluated at import
with nothing to spare it. It is deliberately incomplete and says so, after a long
review thread established that each approximation of Python's semantics rejects
somebody's correct code. It models the module body, class bodies, `if` by the
Windows value of its test, and a definition's decorators, defaults and eager
annotations; try, while, for, with and match are skipped whole; a helper called at
import is not followed into; a module that writes os.geteuid and reads it back is
reported although it would work. All three boundaries would still have caught all
six sites, because all six are decorators in a module or class body, which is the
only spelling pytest reads at collection.

The org Actions queue is 200+ runs deep and none of this PR's checks reported;
pre-commit.ci passed. Run on staging instead, per the numbers above. No production
code is touched.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant