Skip to content

gtest-ify JIT tests, through the letter c - #45020

Closed
suo wants to merge 5 commits into
gh/suo/357/basefrom
gh/suo/357/head
Closed

suo wants to merge 5 commits into
gh/suo/357/basefrom
gh/suo/357/head

Conversation

@suo

@suo suo commented Sep 19, 2020 •

Copy link
Copy Markdown
Member

Stack from ghstack:

See #45018 for context.

Differential Revision: D23802296

See #45018 for context.

[ghstack-poisoned]
@facebook-github-bot facebook-github-bot added the oncall: jit Add this issue/PR to JIT oncall triage queue label Sep 19, 2020
suo added a commit that referenced this pull request Sep 19, 2020
See #45018 for context.

ghstack-source-id: 6e7f846
Pull Request resolved: #45020
@dr-ci

dr-ci Bot commented Sep 19, 2020 •

Copy link
Copy Markdown

💊 CI failures summary and remediations

As of commit 07baf87 (more details on the Dr. CI page):


  • 1/1 failures possibly* introduced in this PR
    • 1/1 non-CircleCI failure(s)

ci.pytorch.org: 1 failed


This comment was automatically generated by Dr. CI (expand for details).Follow this link to opt-out of these comments for your Pull Requests.

Please report bugs/suggestions on the GitHub issue tracker or post in the (internal) Dr. CI Users group.

See how this bot performed.

This comment has been revised 46 times.

suo added a commit that referenced this pull request Sep 19, 2020
See #45018 for context.

ghstack-source-id: 26c4798
Pull Request resolved: #45020
@suo
suo requested a review from ZolotukhinM September 21, 2020 17:53

@ZolotukhinM ZolotukhinM 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.

LGTM assuming the change was mostly mechanical.

@codecov

codecov Bot commented Sep 21, 2020 •

Copy link
Copy Markdown

Codecov Report

Merging #45020 into gh/suo/357/base will not change coverage.
The diff coverage is n/a.

Impacted file tree graph

@@               Coverage Diff                @@
##           gh/suo/357/base   #45020   +/-   ##
================================================
  Coverage            67.84%   67.84%           
================================================
  Files                  384      384           
  Lines                49984    49984           
================================================
  Hits                 33912    33912           
  Misses               16072    16072           

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 0e7a51b...07baf87. Read the comment docs.

@facebook-github-bot

Copy link
Copy Markdown
Contributor

@suo merged this pull request in d2b0450.

suo added a commit that referenced this pull request Sep 24, 2020
Reland of #45055 and
#45020

See #45018 for context.

[ghstack-poisoned]
suo added a commit that referenced this pull request Sep 24, 2020
Reland of #45055 and
#45020

See #45018 for context.

ghstack-source-id: 8e86ac3
Pull Request resolved: #45249
facebook-github-bot pushed a commit that referenced this pull request Sep 24, 2020
Summary:
Pull Request resolved: #45249

Reland of #45055 and
#45020

See #45018 for context.

Test Plan: Imported from OSS

Reviewed By: jamesr66a

Differential Revision: D23892645

Pulled By: suo

fbshipit-source-id: e7fe58d5e1a5a0c44f4e2aec9694145afabde0fd
@facebook-github-bot
facebook-github-bot deleted the gh/suo/357/head branch September 27, 2020 14:15
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…y its resolved path (#197428)

**Problem.** Given the roots from #197262, the lint still has to turn one module into a verdict (shipped with torch or the stdlib, shipped elsewhere, or no evidence), and a naive `__file__` read runs user code and misclassifies relative, driveless or NUL-bearing paths and frozen apps.

**Fix.** Add `_classify_file`, which resolves a path against the roots behind explicit None gates and a cache, and `_located`, which reads `__file__`, `__loader__` and `__spec__` out of the module dict without triggering `__getattr__` and trusts the builtin and frozen importers by identity.

**Summary.** The risky-drop lint that later commits add waives a dropped identity guard when the value it guarded is owned by torch or the standard library, and the root finders added two commits earlier (`_stdlib_roots`, `_install_roots`, `_torch_roots`) say where each of those lives; this commit adds the two helpers that turn a module into a verdict against those roots, and the consumer, `_is_library_module`, follows in the next commit. `_classify_file(file, stdlib)` answers for one `__file__` -- shipped here (True), shipped elsewhere (False), or no evidence (None) -- judging the path `_norm` resolves against the torch roots (`stdlib=False`) or the stdlib roots minus the install roots (`stdlib=True`), with None reserved for a path that cannot be resolved (relative, driveless on Windows, or carrying a NUL) and for any stdlib question in a frozen app, where the bundle root holds the stdlib and every third party alike. `_located(module, name, stdlib)` answers the same three ways for a `sys.modules` entry, reading `__file__`, `__loader__` and `__spec__` out of the module DICT through `object.__getattribute__` so that no PEP 562 `__getattr__`, `_LazyModule` body or user `__eq__` runs, letting a placed `__file__` decide first and only then trusting `BuiltinImporter` or `FrozenImporter` by identity under the caller's full dotted `name`. Every read that remains user code is inside one `try` that answers None, so nothing escapes a lint, and `_classify_file` is `functools.cache`d on the (file, flag) pair because everything else it reads is fixed for the process while the module a name resolves to is not. Two tests pin every arm, gate and ordering, each row against a named mutation, on paths spelled so they cannot pre-exist and with the Windows path module replayed so the driveless and NUL gates hold on every platform.

## The two helpers

```python
@functools.cache
def _classify_file(file: str, stdlib: bool) -> bool | None:
    # True: shipped here; False: shipped elsewhere; None: no evidence

def _located(module: object, name: str, stdlib: bool) -> bool | None:
    # the same three answers for a sys.modules entry, which need not be a module
```

`_is_library_module` refuses None for a top-level name and keeps the package's waiver for an inner one, so an unplaceable inner `__file__` counts as no evidence there.

## `_classify_file`: the gates

```python
driveless = sys.platform == "win32" and not os.path.splitdrive(file)[0]
if driveless or not os.path.isabs(file):
    return None                                   # would resolve against the wrong cwd
if "\x00" in file:
    return None                                   # no file has one; see gh-106242
path = _norm(file)
```

A relative path is None, because `realpath` would resolve it against the process cwd rather than the one it was recorded under (on Windows before 3.13 `ntpath.isabs` accepts a driveless `\Lib\x.py`, the stdlib's own LEGACY BUG comment, so the gate also asks `splitdrive` for a drive there). So is a path with an embedded NUL, which no file has: `posixpath.realpath` raises `ValueError` on one from `os.lstat`, but from 3.11.5/3.12 on (gh-106242) `ntpath.realpath` swallows that and returns the path unresolved, NUL intact, and `_within` would then match the prefix before the NUL and waive the file, so the gate is an explicit check ahead of `realpath` rather than a catch around it. None comes from those two gates and from the frozen-app gate below. Every arm judges the path `_norm` returns, never the string as recorded: a venv or symlink-farm `__file__` must be placed by where the file is, not by where its link sits.

## `_classify_file`: the torch arm

```python
if not stdlib:
    return _within(path, _torch_roots())          # never None past the gates
```

With `stdlib=False` the verdict is whether the path lies under a torch root and is never None: with no torch root (a frozen torch) every path is elsewhere, which `_is_library_module` never reaches because it waives torch names before asking. The install-root exclusion below is the stdlib arm's alone: torch ships platform wheels, `Root-Is-Purelib: false`, so a pip-installed torch lies under platlib. The torch arm is not gated on `sys.frozen` either: its root is torch's own package directory, taken from where this file sits (`_torch_roots`), so in a bundle nothing outside torch lies under it, where the stdlib root is the bundle root itself.

## `_classify_file`: the stdlib arm

```python
_INSTALL_DIR_NAMES = frozenset({"site-packages", "dist-packages"})

if getattr(sys, "frozen", False):
    return None
if _within(path, _install_roots()):
    return False
for root in _stdlib_roots():                      # sorted: the first match is the outermost
    if _within(path, (root,)):
        below = path[len(root) + 1 :].lower().split(os.sep)
        return _INSTALL_DIR_NAMES.isdisjoint(below)
return False
```

With `stdlib=True` the path must be under a stdlib root and NOT under an install root, since `purelib` nests inside `stdlib` in a conda layout and inside `platstdlib` in a venv, so the exclusion is what does the work. A `site-packages` or `dist-packages` component (`_INSTALL_DIR_NAMES`, compared case folded: `normcase` is the identity on posix and a macOS filesystem is case-insensitive, so a mis-cased `Site-Packages` entry on `sys.path` would otherwise slip past both the install roots and this check) BELOW the stdlib root the file was found under also refuses, a cheap belt-and-braces check for an install directory none of the roots name, matched at any depth below the root rather than on the whole path, so that an interpreter bundled inside another environment's site-packages keeps its own stdlib (the roots are sorted, so of nested roots the outermost is matched, the part below it is the longest and the check the strictest). The match is on `os.sep`, not `/`, since `_norm` yields the platform's separator.

## Frozen apps

In a frozen app (`sys.frozen` truthy, as `multiprocessing.spawn` reads it: PyInstaller and cx_Freeze set the flag to True, py2exe to a string, `"console_exe"`, `"windows_exe"` or `"dll"`) the stdlib arm answers None instead: such a bundle holds the stdlib and every third party under one root with no `site-packages` component between them, and PyInstaller's `_fixup_frozen_stdlib` names that root in `sys._stdlib_dir` and in the `__file__` it gives the CPython-frozen modules, so every bundled file would lie under a stdlib root and a bundled module named after a stdlib module (a `graphlib` or `dataclasses` backport, an app module that shadows one) would be waived as interpreter-owned, the wrong-True direction. None rather than False so that `_located` still reads the loader: the modules CPython itself freezes or links in keep their waiver through the `FrozenImporter` and `BuiltinImporter` arms, and the rest of the stdlib is merely unwaived, lint noise and not a wrong drop.

## The cache

The function is `functools.cache`d on the (file, flag) pair rather than on a module name: everything else it reads, the roots and `sys.frozen`, is fixed once the process is running, so the answer for a path never changes, while the module a name resolves to can (a test that patches either clears the cache on both sides of the patch).

## `_located`: reading the module dict

```python
try:
    attrs = object.__getattribute__(module, "__dict__")   # not getattr, not module.__dict__
    file = attrs.get("__file__")
    if isinstance(file, str):
        verdict = _classify_file(file, stdlib)
        if verdict is not None:
            return verdict                                # a placed file decides
    loader = attrs.get("__loader__")
    if loader is None:
        loader = getattr(attrs.get("__spec__"), "loader", None)
    if loader is importlib.machinery.BuiltinImporter:
        return name in sys.builtin_module_names
    if loader is importlib.machinery.FrozenImporter:
        return importlib.machinery.FrozenImporter.find_spec(name) is not None
except Exception:
    return None
return None
```

`_located` is typed on `object` because a `sys.modules` entry need not be a module. None covers no `__file__` and no known loader, a `__file__` that `_classify_file` cannot place (relative, non-string, NUL, or any stdlib path in a frozen app) with no known loader, and a read that raised.

It reads `__file__` out of the module DICT, not through `getattr`: a class attribute is not evidence about where the module came from (torch.ops is a `ModuleType` subclass carrying the class's relative `"_ops.py"` as its `__file__`, which a dict read does not see), and on an entry whose dict is missing one of the three dunders read here `getattr` would fall through to a PEP 562 module `__getattr__`, user code a lint must not run (a raise would be caught, but not its side effects). The dict itself is read with `object.__getattribute__`, not the module's: `importlib.util.LazyLoader` leaves a `_LazyModule` in `sys.modules` whose `__getattribute__` executes the module body on ANY attribute read, `__dict__` included, so a plain `getattr(module, "__dict__")` would import the module the lint was only inspecting (and if the body raised, or the name was rebound in `sys.modules` meanwhile, leave it half-initialised behind the catch); the lazy module's dict already carries the seeded `__file__`, `__spec__` and `__loader__`, so the read through `object` loses nothing.

`sys.modules` can hold any object, so the reads that remain user code, a `__dict__` descriptor defined on the type and the spec's `loader` on a hand-rolled spec, are caught, answering None, as is the `AttributeError` that `object`'s read itself raises for a slotted entry with no `__dict__` (a `__getattr__` on it is never consulted), and since the `try` also spans the `_classify_file` call and the loader arms, a raise out of the classifier's own gates or out of `FrozenImporter.find_spec` (an `ImportError` on an excluded or invalid frozen table entry) lands there as None too rather than escaping a lint. A `__file__` that is not a string (a namespace package sets None) is skipped by an `isinstance` gate, and like a relative one it is evidence in neither direction, so the loader is still read (`isabs` accepts `bytes` and a `PathLike`, so the gate is what keeps them out; unguarded they would raise from the NUL check into the same catch).

## `_located`: the file decides before the loader is read

A located file decides, and only then is the loader read, an order that matters: with importlib on disk, `importlib._bootstrap` carries a stdlib `__file__` (importlib/__init__.py assigns it, inside a `try/except NameError` that a frozen importlib skips) next to a `FrozenImporter` whose table knows the module only as `_frozen_importlib`, so with the arms swapped it would lose its waiver; with importlib frozen too there is no `__file__`, the frozen arm answers False under the dotted name and the waiver is lost either way, a fail-closed corner that costs lint noise, not a wrong drop.

```python
bootstrap = types.ModuleType("importlib._bootstrap")
bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py")
bootstrap.__loader__ = importlib.machinery.FrozenImporter   # find_spec("importlib._bootstrap") is None
pp._located(bootstrap, "importlib._bootstrap", True)        # True: the file decides; loader-first would answer False
```

## `_located`: the loader arms

The loader (`__loader__` in the dict, else the spec's: a `__loader__` in the dict skips the `spec.loader` read, the only user-code half of this, and is compared with None rather than for truth, so no `__bool__` of user code runs; a hand-made `ModuleType` carries the `None` that `ModuleType.__init__` seeds and falls through, where an imported module's dict carries `spec.loader`, copied in by `_init_module_attrs`) is read, not `spec.origin`: `BuiltinImporter.find_spec` and `FrozenImporter.find_spec` both call `spec_from_loader(fullname, cls, origin=cls._ORIGIN)` (the frozen one adds `is_package`, then fills in `loader_state` and the package's search path) and `_init_module_attrs` copies `spec.loader` into `__loader__`, so the origin string never says anything the loader class does not, and the class is the stronger signal.

Both tables are looked up under the caller's `name`, the `sys.modules` key `_is_library_module` was asked about, not the module's own `__name__` (the entry for `os.path` is `posixpath`). Both arms match the loader class by identity, not equality, for the same reason the dict is read through `object`: under `==` a `__loader__` whose `__eq__` answers true for anything would take the waiver. `BuiltinImporter` is trusted only if the FULL dotted `name` is in `sys.builtin_module_names` (the inittab is keyed on it, so a fabricated `sys.sub` is refused), `FrozenImporter` only if the frozen table has the name (`zipimport`, not `zipimport.sub`), and a module with neither (namespace package, exec'd in memory with no loader) is None; a REPL, `-c` or stdin `__main__` is not one of these, since the interpreter seeds `BuiltinImporter` as its `__loader__`, so it is False, `__main__` not being in the inittab.

Both arms answer on the name alone whichever roots `stdlib` selects: built-in and frozen precede the path finder on `sys.meta_path`, so on import no file on `sys.path` is reachable under such a name, and a module compiled into the interpreter has its code fixed by the interpreter binary, which is what either waiver needs. The `stdlib=False` case is not the stdlib's `sys` asked under the wrong flag (`_is_library_module` routes a name to a flag by its top component) but an embedding that registers `torch._C` through `PyImport_AppendInittab` while torch's Python files stay on disk, so `_torch_roots` is non-empty and torch is not waived on its name; in an ordinary build `torch._C` is an extension module and not in `sys.builtin_module_names`. A spec assigned straight into `sys.modules` is taken at its word.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

stdlib_root = sysconfig.get_paths()["stdlib"]
pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)                  # True
pp._classify_file(torch.__file__, False)                                           # True: the torch arm reads the torch roots
pp._classify_file(torch.__file__, True)                                            # False: torch lies under no stdlib root, or under an install root
pp._classify_file(os.path.join(stdlib_root, "torch", "__init__.py"), False)        # False: the stdlib dir itself is never a pip target, so no torch root holds it
pp._classify_file("graphlib.py", True)                                             # None: relative
pp._classify_file("graphlib.py", False)                                            # None: the gates precede the flag split
pp._classify_file(os.path.join(stdlib_root, "graph\x00lib.py"), True)              # None: embedded NUL, on every platform
platlib_torch = os.path.join(sysconfig.get_paths()["platlib"], "torch")
pp._classify_file.cache_clear()                                                    # in a wheel install the next file IS torch.__file__, judged above
with mock.patch.object(pp, "_torch_roots", return_value=(pp._norm(platlib_torch),)):
    pp._classify_file(os.path.join(platlib_torch, "__init__.py"), False)            # True: the torch arm is exempt from the install-root exclusion
for flag in (True, "console_exe"):                                                 # a frozen app: PyInstaller and cx_Freeze set True, py2exe a string
    pp._classify_file.cache_clear()
    with mock.patch.object(sys, "frozen", flag, create=True):
        pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)          # None: the bundle root holds the stdlib and third parties alike
        pp._classify_file(torch.__file__, False)                                   # True: the torch arm keeps torch's own package directory
        pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), False)         # False: and that root holds nothing outside torch
pp._classify_file.cache_clear()
pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)                  # True again: the answer changed with sys.frozen, hence the clear
import ntpath
with mock.patch.object(sys, "platform", "win32"), mock.patch.object(os, "path", ntpath), mock.patch.object(os, "sep", "\\"), mock.patch.object(pp, "_stdlib_roots", return_value=(r"c:\python312\lib",)), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._classify_file(r"\Lib\graphlib.py", True)                                   # None: driveless, so resolved against the current drive
    pp._classify_file("C:\\Python312\\Lib\\graphlib.py\x00C:\\evil\\evil.py", True)   # None: without the gate ntpath.realpath returns it unresolved and it lies under the root
    pp._classify_file(r"c:\python312\lib\vendored\site-packages\graphlib.py", True)  # False: the part below the root is split on os.sep, so the name is seen
with mock.patch.object(pp, "_install_roots", return_value=()):
    pp._classify_file(os.path.join(stdlib_root, "vendored", "site-packages", "g.py"), True)   # False: _INSTALL_DIR_NAMES alone, two components below the root
    pp._classify_file(os.path.join(stdlib_root, "vendored", "dist-packages", "g.py"), True)   # False: same
    pp._classify_file(os.path.join(stdlib_root, "vendored", "Site-Packages", "g.py"), True)   # False: case folded
    pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True)  # True: nothing installed there
    with mock.patch.object(pp, "_stdlib_roots", return_value=()):
        pp._classify_file(os.path.join(stdlib_root, "os.py"), True)                    # False: under no stdlib root at all
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)):
    pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True)  # False: the install-root exclusion alone
tmp = tempfile.mkdtemp()                                                           # a tree of its own: a real <stdlib>/site-packages is a symlink out of the stdlib on some layouts
bundled = os.path.join(tmp, "site-packages", "runtime", "lib")                     # a stdlib that itself sits under site-packages
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(bundled),)):
    pp._classify_file(os.path.join(bundled, "graphlib.py"), True)                  # True: site-packages ABOVE the stdlib root does not count
    pp._classify_file(os.path.join(bundled, "site-packages", "graphlib.py"), True) # False: below it does
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp), pp._norm(bundled))):
    pp._classify_file(os.path.join(bundled, "graphlib.py"), True)                  # False: of nested roots the outermost is matched
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp),)):
    pp._classify_file(os.path.join(tmp, "site-packages", os.pardir, "g.py"), True) # True: judged after _norm resolves it, not as recorded
```

```python
module = types.ModuleType("graphlib")
module.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
pp._located(module, "graphlib", True)              # False: a placed file decides either way
module.__file__ = os.path.join(stdlib_root, "graphlib.py")
pp._located(module, "graphlib", True)              # True
on_disk = types.ModuleType("torch")
on_disk.__file__ = torch.__file__
pp._located(on_disk, "torch", False)               # True: the flag reaches the file arm (the production torch shape)
pp._located(on_disk, "torch", True)                # False
class Shadow(types.ModuleType):
    __file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
pp._located(Shadow("graphlib"), "graphlib", True)  # None: a class attribute is not in the module dict
pp._located(torch.ops, "torch.ops", False)         # None: same shape, the real one (a canary: a getattr read would answer None too)
raising = types.ModuleType("graphlib")
raising.__getattr__ = mock.Mock(side_effect=RuntimeError)
del raising.__spec__, raising.__loader__            # ModuleType seeds both into the dict
pp._located(raising, "graphlib", True)             # None, and __getattr__ was not called for __file__, __spec__ or __loader__
eager = mock.Mock(**{"create_module.return_value": None})
wrapped = importlib.util.LazyLoader(eager)
lazy_spec = importlib.util.spec_from_file_location("graphlib", os.path.join(stdlib_root, "site-packages", "graphlib.py"), loader=wrapped)
lazy = importlib.util.module_from_spec(lazy_spec)
wrapped.exec_module(lazy)                      # now a _LazyModule: any attribute read runs eager.exec_module
pp._located(lazy, "graphlib", True)                # False, and eager.exec_module was not called
pp._located(types.ModuleType("graphlib"), "graphlib", True)   # None: no file, no spec
odd = types.ModuleType("graphlib")
odd.__file__ = 42
pp._located(odd, "graphlib", True)                 # None: not a path
class Proxy:                                       # a non-module sys.modules entry
    __slots__ = ()
    def __getattr__(self, attr): raise RuntimeError(attr)
pp._located(Proxy(), "graphlib", True)             # None: object's __dict__ read raises AttributeError on a slotted entry; caught, __getattr__ never consulted
odd.__spec__ = Proxy()
pp._located(odd, "graphlib", True)                 # None: so is spec.loader
odd.__file__ = os.path.join(stdlib_root, "graphlib.py")
pp._located(odd, "graphlib", True)                 # True: a placed file decides, the loader is never read
spec_poisoned = types.ModuleType("sys")
spec_poisoned.__spec__ = Proxy()
spec_poisoned.__loader__ = importlib.machinery.BuiltinImporter
pp._located(spec_poisoned, "sys", True)            # True: __loader__ is read first, so the spec never is
bootstrap = types.ModuleType("importlib._bootstrap")
bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py")
bootstrap.__loader__ = importlib.machinery.FrozenImporter   # the real module's shape; FrozenImporter.find_spec("importlib._bootstrap") is None
pp._located(bootstrap, "importlib._bootstrap", True)        # True: the file decides before the loader is read
shadow_sys = types.ModuleType("sys")
shadow_sys.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
shadow_sys.__loader__ = importlib.machinery.BuiltinImporter
pp._located(shadow_sys, "sys", True)               # False: the converse, an installed file under a built-in name
odd_sys = types.ModuleType("sys")
odd_sys.__file__ = 42
odd_sys.__loader__ = importlib.machinery.BuiltinImporter
pp._located(odd_sys, "sys", True)                  # True: a __file__ that cannot be placed is no evidence, so the loader is read
relative = types.ModuleType("zipimport")
relative.__file__ = "zipimport.py"
relative.__loader__ = importlib.machinery.FrozenImporter
pp._located(relative, "zipimport", True)           # True: same for a relative one
frozen_zip = types.ModuleType("zipimport")                  # frozen on every version; os only from 3.11 on (gh-45020)
frozen_zip.__file__ = os.path.join(stdlib_root, "zipimport.py")
frozen_zip.__loader__ = importlib.machinery.FrozenImporter
with mock.patch.object(sys, "frozen", True, create=True):
    pp._located(frozen_zip, "zipimport", True)     # True: in a frozen app the file arm is no evidence, so the loader decides
pp._located(sys, "sys", True)                      # True: built in
pp._located(sys, "sys.sub", True)                  # False: the caller's name is looked up, not the module's __name__
zipimport_by_name = types.ModuleType("zipimport")
zipimport_by_name.__loader__ = importlib.machinery.FrozenImporter
pp._located(zipimport_by_name, "zipimport.sub", True)  # False: same in the frozen arm
sub = types.ModuleType("sys.sub")
sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in")
pp._located(sub, "sys.sub", True)                  # False: the inittab is keyed on the full dotted name
frozen = importlib.machinery.FrozenImporter
zipimport_frozen = types.ModuleType("zipimport")
zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen")
pp._located(zipimport_frozen, "zipimport", True)   # True: the frozen table has zipimport
zipimport_sub = types.ModuleType("zipimport.sub")
zipimport_sub.__spec__ = importlib.machinery.ModuleSpec("zipimport.sub", frozen, origin="frozen")
pp._located(zipimport_sub, "zipimport.sub", True)  # False: keyed on the full dotted name, not its top component
graphlib_frozen = types.ModuleType("graphlib")
graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen")
pp._located(graphlib_frozen, "graphlib", True)     # False: a frozen spec under a name the frozen table does not have
with mock.patch.object(frozen, "find_spec", side_effect=ImportError):
    pp._located(zipimport_by_name, "zipimport", True)  # None: find_spec raises on an excluded or invalid frozen table entry, and nothing escapes _located
lying_eq = types.ModuleType("sys")
lying_eq.__loader__ = mock.ANY                     # a stdlib object whose __eq__ answers true for anything
pp._located(lying_eq, "sys", True)                 # None: the arms match the loader class by identity
by_loader = types.ModuleType("sys")
by_loader.__loader__ = importlib.machinery.BuiltinImporter
pp._located(by_loader, "sys", True)                # True: __loader__ alone in the dict, no spec
by_loader = types.ModuleType("zipimport")
by_loader.__loader__ = frozen
pp._located(by_loader, "zipimport", True)          # True: same, frozen
pp._located(by_loader, "zipimport", False)         # True: both arms answer under either flag
by_loader = types.ModuleType("sys")
by_loader.__loader__ = importlib.machinery.BuiltinImporter
pp._located(by_loader, "sys", False)               # True: same, built in
with mock.patch.object(sys, "builtin_module_names", (*sys.builtin_module_names, "torch._C")):
    embedded = types.ModuleType("torch._C")
    embedded.__loader__ = importlib.machinery.BuiltinImporter
    pp._located(embedded, "torch._C", False)       # True: the torch shape, an embedded torch._C with torch's Python files on disk
```

## Tests

Both tests call `_clear_root_caches` first, like every other root test, and clear the `_classify_file` cache on entry and on cleanup: its keys are stdlib-rooted paths that other tests judge under patched roots.

**`test_classify_file_places_a_path_by_the_roots_it_lies_under`** pins every arm of `_classify_file` on paths spelled relative to sysconfig's `stdlib` (the stdlib dir itself is never a pip target, so no torch root holds the fake torch path):

- the stdlib True, and the torch arm reading the torch roots and not the stdlib ones;
- the torch arm exempt from the install-root exclusion: with `_torch_roots` patched to `<platlib>/torch`, after asserting that `<platlib>/torch/__init__.py` lies under a real install root and clearing the cache, that file is True. A checkout's `torch.__file__` is under no install root, so the plain torch row cannot see this, while in a wheel install that file IS `torch.__file__`, and without the clear the row would only re-read the torch-arm row's cached verdict;
- the frozen-app None: with `sys.frozen` patched to True and then to py2exe's `"console_exe"`, a stdlib-rooted file under `stdlib=True` is None while `torch.__file__` under `stdlib=False` stays True and that stdlib file under `stdlib=False` is False, the torch arm still telling torch from the rest of a bundle. The cache is cleared before each flag and after the block, and the stdlib file is then re-read as True, the row that shows the answer for a path changing with `sys.frozen` and so what the clears are for;
- the relative None under both flags (the gates precede the flag split) and the embedded-NUL None on every platform;
- the driveless Windows spelling, the NUL path under a Windows stdlib root and an installed file two components below one, with `sys.platform`, `os.path` and `os.sep` patched to `win32`, `ntpath` and a backslash and the root finders patched to `c:\python312\lib` and `()`, so the rows run on every platform. The second replays what gh-106242 does: without the gate `ntpath.realpath` returns the path unresolved, `_within` matches the prefix before the NUL, and the file is waived. The third is the only row that reaches `_INSTALL_DIR_NAMES` with a non-posix separator, which is what splitting the part below the root on `os.sep` rather than `/` is for;
- both `_INSTALL_DIR_NAMES` refusing with `_install_roots` patched to `()`, and a mis-cased `Site-Packages` refusing on every platform (case folded, since `normcase` only folds on Windows);
- a stdlib-rooted file under no stdlib root at all (both root finders patched to `()`) refused, which pins the terminal False without depending on where torch is installed (in a wheel or conda install `torch.__file__` lies under an install root and returns from the exclusion instead);
- one file under a nested `vendored` directory judged twice, with the cache cleared in between: stdlib with nothing installed there, third party once that directory is an install root;
- `_INSTALL_DIR_NAMES` scoped below the root: with `_stdlib_roots` patched to a root that itself sits under `site-packages`, a file directly under it is stdlib and one under a further `site-packages` is not, and with both that root and the one above it patched in, the same file is refused, since the outermost root is the one matched;
- that judging happens after `_norm`: a path naming `site-packages` and then `os.pardir` is stdlib, since it resolves to a plain file directly under the root.

The rows that turn on where an install directory sits relative to a root are spelled on paths that cannot pre-exist -- a `vendored` component under sysconfig's `stdlib`, and a `TemporaryDirectory` for the bundled-interpreter fixture -- because a real `<stdlib>/site-packages` is a symlink out of the stdlib on some layouts (a relocated site-packages, a Windows junction), which resolves such a path out of the root it is meant to be judged under, and then those rows either assert the wrong verdict or pass through the terminal False.

Each row fails under the matching mutation: the `_INSTALL_DIR_NAMES` check or the install-root exclusion removed; `_INSTALL_DIR_NAMES` matched on the whole path, case-sensitively, on `/` in place of `os.sep` or on the first component below the root alone; `_norm` weakened to `normcase` so the recorded path is judged unresolved; the roots walked innermost first; the terminal False turned into None; the `isabs` gate, the driveless gate or the NUL gate removed; the install-root exclusion hoisted above the flag split; the torch arm reading the stdlib roots; the `stdlib` flag ignored; the frozen-app gate removed, answering False, hoisted above the flag split, or asking `is True` of the flag, which the string row alone fails.

**`test_located_reads_the_file_from_the_module_dict`** starts with a placed `__file__` deciding either way (an installed one False, a stdlib one True) and the production torch shape, a module carrying `torch.__file__` asked under `stdlib=False` (True) and `stdlib=True` (False), the only rows on which the flag is not a constant of the file arm. It then pins:

- the module-dict read, with a `ModuleType` subclass whose class attribute `__file__` would classify False if seen (the row that fails under a `getattr` read of `__file__`), the real `torch.ops` as a canary for that shape (asserting first that its dict has no `__file__`; a `getattr` read of its relative `"_ops.py"` would answer the same None, so this row documents rather than pins), and a module whose PEP 562 `__getattr__` raises, with `__spec__` and `__loader__` deleted from its dict, since `ModuleType.__init__` seeds both and a `getattr` read of either would otherwise never reach `__getattr__`;
- a module built through `importlib.util.LazyLoader` over a mock loader, carrying the installed `__file__` (False, and the loader's `exec_module` was not called: under a `getattr` read of `__dict__` the `_LazyModule` runs it, and since the real `graphlib` is in `sys.modules` under that name then raises inside the catch, answering None);
- no file and no spec; a non-string `__file__`; a slotted proxy whose `__getattr__` raises (standing in for a non-module `sys.modules` entry) both as the module and as its `__spec__`; that module again once it has a placeable `__file__`; a `sys` with that proxy as `__spec__` next to a `BuiltinImporter` `__loader__` (True: the dict's `__loader__` is read first, so the spec never is);
- the two rows that pin the arm order: the `importlib._bootstrap` shape, a stdlib `__file__` plus `FrozenImporter`, asserting first that the frozen table does not know the name, is True; an installed `__file__` plus `BuiltinImporter` under `sys` is False;
- the two that cross unusable file evidence with a loader: a non-string `__file__` under `sys` with `BuiltinImporter`, a relative one under `zipimport` with `FrozenImporter`, both True;
- the frozen-app shape: a `zipimport` carrying a stdlib `__file__` and `FrozenImporter` is True with `sys.frozen` patched in, the file arm being no evidence there, so the loader decides. `zipimport` rather than `os` because CPython freezes `os` only from 3.11 on, gh-45020, and the row must hold on 3.10;
- the real `sys` under its own name and under `sys.sub`, and a fabricated `zipimport` with `FrozenImporter` asked under `zipimport.sub` (False: in both arms the caller's name is looked up, not the module's `__name__`); the fabricated `sys.sub`; a frozen spec under a frozen name, under a dotted name whose top component is frozen (`zipimport.sub`) and under a non-frozen name;
- `FrozenImporter.find_spec` patched to raise `ImportError` (None: the loader arms are inside the `try`); a `__loader__` that is `mock.ANY`, a stdlib object whose `__eq__` answers true for anything (None: the arms match by identity, so nothing of its runs);
- each importer as a bare `__loader__` with no spec asked under both flags, and the torch shape, `torch._C` with `BuiltinImporter` under `stdlib=False` with the inittab patched to list it (asserting first that the real one does not).

Each of these mutations fails a row: a `getattr` read of `__file__`, of `__spec__` or of `__loader__` (the first fails the `Shadow` row, the other two the `assert_not_called`); a `getattr` read of `__dict__` (the LazyLoader row); the `stdlib` flag hardcoded on the file arm; the `try/except` removed; the arms swapped or the loader read before the file arm; the `__loader__` read dropped for the spec's loader alone or read after it; either arm's identity comparison loosened to `==`; an inittab or frozen-table lookup on the top component; the name taken from the module's `__name__`; an unconditional frozen True; a False for no evidence; `stdlib and` in front of either loader arm; the `isinstance(file, str)` gate loosened to truthiness; and the fall-through from a None `_classify_file` to the loader replaced by a return. The last two are killed only by rows that cross an unplaceable file with a loader: the loosened gate by the non-string crossing row alone (the catch covers the `TypeError` that `os.path.isabs` raises on a non-string, so it answers the same None as the real one until the module also carries a loader that should have decided), the return by the relative crossing row and the frozen-app row, where `_classify_file` answers None and the loader was to decide.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_classify_file_places_a_path_by_the_roots_it_lies_under -k test_located_reads_the_file_from_the_module_dict
lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Pull Request resolved: #197428
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…y its resolved path (#197428) (#197963)

**Problem.** Given the roots from #197262, the lint still has to turn one module into a verdict (shipped with torch or the stdlib, shipped elsewhere, or no evidence), and a naive `__file__` read runs user code and misclassifies relative, driveless or NUL-bearing paths and frozen apps.

**Fix.** Add `_classify_file`, which resolves a path against the roots behind explicit None gates and a cache, and `_located`, which reads `__file__`, `__loader__` and `__spec__` out of the module dict without triggering `__getattr__` and trusts the builtin and frozen importers by identity.

**Summary.** The risky-drop lint that later commits add waives a dropped identity guard when the value it guarded is owned by torch or the standard library, and the root finders added two commits earlier (`_stdlib_roots`, `_install_roots`, `_torch_roots`) say where each of those lives; this commit adds the two helpers that turn a module into a verdict against those roots, and the consumer, `_is_library_module`, follows in the next commit. `_classify_file(file, stdlib)` answers for one `__file__` -- shipped here (True), shipped elsewhere (False), or no evidence (None) -- judging the path `_norm` resolves against the torch roots (`stdlib=False`) or the stdlib roots minus the install roots (`stdlib=True`), with None reserved for a path that cannot be resolved (relative, driveless on Windows, or carrying a NUL) and for any stdlib question in a frozen app, where the bundle root holds the stdlib and every third party alike. `_located(module, name, stdlib)` answers the same three ways for a `sys.modules` entry, reading `__file__`, `__loader__` and `__spec__` out of the module DICT through `object.__getattribute__` so that no PEP 562 `__getattr__`, `_LazyModule` body or user `__eq__` runs, letting a placed `__file__` decide first and only then trusting `BuiltinImporter` or `FrozenImporter` by identity under the caller's full dotted `name`. Every read that remains user code is inside one `try` that answers None, so nothing escapes a lint, and `_classify_file` is `functools.cache`d on the (file, flag) pair because everything else it reads is fixed for the process while the module a name resolves to is not. Two tests pin every arm, gate and ordering, each row against a named mutation, on paths spelled so they cannot pre-exist and with the Windows path module replayed so the driveless and NUL gates hold on every platform.

## The two helpers

```python
@functools.cache
def _classify_file(file: str, stdlib: bool) -> bool | None:
    # True: shipped here; False: shipped elsewhere; None: no evidence

def _located(module: object, name: str, stdlib: bool) -> bool | None:
    # the same three answers for a sys.modules entry, which need not be a module
```

`_is_library_module` refuses None for a top-level name and keeps the package's waiver for an inner one, so an unplaceable inner `__file__` counts as no evidence there.

## `_classify_file`: the gates

```python
driveless = sys.platform == "win32" and not os.path.splitdrive(file)[0]
if driveless or not os.path.isabs(file):
    return None                                   # would resolve against the wrong cwd
if "\x00" in file:
    return None                                   # no file has one; see gh-106242
path = _norm(file)
```

A relative path is None, because `realpath` would resolve it against the process cwd rather than the one it was recorded under (on Windows before 3.13 `ntpath.isabs` accepts a driveless `\Lib\x.py`, the stdlib's own LEGACY BUG comment, so the gate also asks `splitdrive` for a drive there). So is a path with an embedded NUL, which no file has: `posixpath.realpath` raises `ValueError` on one from `os.lstat`, but from 3.11.5/3.12 on (gh-106242) `ntpath.realpath` swallows that and returns the path unresolved, NUL intact, and `_within` would then match the prefix before the NUL and waive the file, so the gate is an explicit check ahead of `realpath` rather than a catch around it. None comes from those two gates and from the frozen-app gate below. Every arm judges the path `_norm` returns, never the string as recorded: a venv or symlink-farm `__file__` must be placed by where the file is, not by where its link sits.

## `_classify_file`: the torch arm

```python
if not stdlib:
    return _within(path, _torch_roots())          # never None past the gates
```

With `stdlib=False` the verdict is whether the path lies under a torch root and is never None: with no torch root (a frozen torch) every path is elsewhere, which `_is_library_module` never reaches because it waives torch names before asking. The install-root exclusion below is the stdlib arm's alone: torch ships platform wheels, `Root-Is-Purelib: false`, so a pip-installed torch lies under platlib. The torch arm is not gated on `sys.frozen` either: its root is torch's own package directory, taken from where this file sits (`_torch_roots`), so in a bundle nothing outside torch lies under it, where the stdlib root is the bundle root itself.

## `_classify_file`: the stdlib arm

```python
_INSTALL_DIR_NAMES = frozenset({"site-packages", "dist-packages"})

if getattr(sys, "frozen", False):
    return None
if _within(path, _install_roots()):
    return False
for root in _stdlib_roots():                      # sorted: the first match is the outermost
    if _within(path, (root,)):
        below = path[len(root) + 1 :].lower().split(os.sep)
        return _INSTALL_DIR_NAMES.isdisjoint(below)
return False
```

With `stdlib=True` the path must be under a stdlib root and NOT under an install root, since `purelib` nests inside `stdlib` in a conda layout and inside `platstdlib` in a venv, so the exclusion is what does the work. A `site-packages` or `dist-packages` component (`_INSTALL_DIR_NAMES`, compared case folded: `normcase` is the identity on posix and a macOS filesystem is case-insensitive, so a mis-cased `Site-Packages` entry on `sys.path` would otherwise slip past both the install roots and this check) BELOW the stdlib root the file was found under also refuses, a cheap belt-and-braces check for an install directory none of the roots name, matched at any depth below the root rather than on the whole path, so that an interpreter bundled inside another environment's site-packages keeps its own stdlib (the roots are sorted, so of nested roots the outermost is matched, the part below it is the longest and the check the strictest). The match is on `os.sep`, not `/`, since `_norm` yields the platform's separator.

## Frozen apps

In a frozen app (`sys.frozen` truthy, as `multiprocessing.spawn` reads it: PyInstaller and cx_Freeze set the flag to True, py2exe to a string, `"console_exe"`, `"windows_exe"` or `"dll"`) the stdlib arm answers None instead: such a bundle holds the stdlib and every third party under one root with no `site-packages` component between them, and PyInstaller's `_fixup_frozen_stdlib` names that root in `sys._stdlib_dir` and in the `__file__` it gives the CPython-frozen modules, so every bundled file would lie under a stdlib root and a bundled module named after a stdlib module (a `graphlib` or `dataclasses` backport, an app module that shadows one) would be waived as interpreter-owned, the wrong-True direction. None rather than False so that `_located` still reads the loader: the modules CPython itself freezes or links in keep their waiver through the `FrozenImporter` and `BuiltinImporter` arms, and the rest of the stdlib is merely unwaived, lint noise and not a wrong drop.

## The cache

The function is `functools.cache`d on the (file, flag) pair rather than on a module name: everything else it reads, the roots and `sys.frozen`, is fixed once the process is running, so the answer for a path never changes, while the module a name resolves to can (a test that patches either clears the cache on both sides of the patch).

## `_located`: reading the module dict

```python
try:
    attrs = object.__getattribute__(module, "__dict__")   # not getattr, not module.__dict__
    file = attrs.get("__file__")
    if isinstance(file, str):
        verdict = _classify_file(file, stdlib)
        if verdict is not None:
            return verdict                                # a placed file decides
    loader = attrs.get("__loader__")
    if loader is None:
        loader = getattr(attrs.get("__spec__"), "loader", None)
    if loader is importlib.machinery.BuiltinImporter:
        return name in sys.builtin_module_names
    if loader is importlib.machinery.FrozenImporter:
        return importlib.machinery.FrozenImporter.find_spec(name) is not None
except Exception:
    return None
return None
```

`_located` is typed on `object` because a `sys.modules` entry need not be a module. None covers no `__file__` and no known loader, a `__file__` that `_classify_file` cannot place (relative, non-string, NUL, or any stdlib path in a frozen app) with no known loader, and a read that raised.

It reads `__file__` out of the module DICT, not through `getattr`: a class attribute is not evidence about where the module came from (torch.ops is a `ModuleType` subclass carrying the class's relative `"_ops.py"` as its `__file__`, which a dict read does not see), and on an entry whose dict is missing one of the three dunders read here `getattr` would fall through to a PEP 562 module `__getattr__`, user code a lint must not run (a raise would be caught, but not its side effects). The dict itself is read with `object.__getattribute__`, not the module's: `importlib.util.LazyLoader` leaves a `_LazyModule` in `sys.modules` whose `__getattribute__` executes the module body on ANY attribute read, `__dict__` included, so a plain `getattr(module, "__dict__")` would import the module the lint was only inspecting (and if the body raised, or the name was rebound in `sys.modules` meanwhile, leave it half-initialised behind the catch); the lazy module's dict already carries the seeded `__file__`, `__spec__` and `__loader__`, so the read through `object` loses nothing.

`sys.modules` can hold any object, so the reads that remain user code, a `__dict__` descriptor defined on the type and the spec's `loader` on a hand-rolled spec, are caught, answering None, as is the `AttributeError` that `object`'s read itself raises for a slotted entry with no `__dict__` (a `__getattr__` on it is never consulted), and since the `try` also spans the `_classify_file` call and the loader arms, a raise out of the classifier's own gates or out of `FrozenImporter.find_spec` (an `ImportError` on an excluded or invalid frozen table entry) lands there as None too rather than escaping a lint. A `__file__` that is not a string (a namespace package sets None) is skipped by an `isinstance` gate, and like a relative one it is evidence in neither direction, so the loader is still read (`isabs` accepts `bytes` and a `PathLike`, so the gate is what keeps them out; unguarded they would raise from the NUL check into the same catch).

## `_located`: the file decides before the loader is read

A located file decides, and only then is the loader read, an order that matters: with importlib on disk, `importlib._bootstrap` carries a stdlib `__file__` (importlib/__init__.py assigns it, inside a `try/except NameError` that a frozen importlib skips) next to a `FrozenImporter` whose table knows the module only as `_frozen_importlib`, so with the arms swapped it would lose its waiver; with importlib frozen too there is no `__file__`, the frozen arm answers False under the dotted name and the waiver is lost either way, a fail-closed corner that costs lint noise, not a wrong drop.

```python
bootstrap = types.ModuleType("importlib._bootstrap")
bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py")
bootstrap.__loader__ = importlib.machinery.FrozenImporter   # find_spec("importlib._bootstrap") is None
pp._located(bootstrap, "importlib._bootstrap", True)        # True: the file decides; loader-first would answer False
```

## `_located`: the loader arms

The loader (`__loader__` in the dict, else the spec's: a `__loader__` in the dict skips the `spec.loader` read, the only user-code half of this, and is compared with None rather than for truth, so no `__bool__` of user code runs; a hand-made `ModuleType` carries the `None` that `ModuleType.__init__` seeds and falls through, where an imported module's dict carries `spec.loader`, copied in by `_init_module_attrs`) is read, not `spec.origin`: `BuiltinImporter.find_spec` and `FrozenImporter.find_spec` both call `spec_from_loader(fullname, cls, origin=cls._ORIGIN)` (the frozen one adds `is_package`, then fills in `loader_state` and the package's search path) and `_init_module_attrs` copies `spec.loader` into `__loader__`, so the origin string never says anything the loader class does not, and the class is the stronger signal.

Both tables are looked up under the caller's `name`, the `sys.modules` key `_is_library_module` was asked about, not the module's own `__name__` (the entry for `os.path` is `posixpath`). Both arms match the loader class by identity, not equality, for the same reason the dict is read through `object`: under `==` a `__loader__` whose `__eq__` answers true for anything would take the waiver. `BuiltinImporter` is trusted only if the FULL dotted `name` is in `sys.builtin_module_names` (the inittab is keyed on it, so a fabricated `sys.sub` is refused), `FrozenImporter` only if the frozen table has the name (`zipimport`, not `zipimport.sub`), and a module with neither (namespace package, exec'd in memory with no loader) is None; a REPL, `-c` or stdin `__main__` is not one of these, since the interpreter seeds `BuiltinImporter` as its `__loader__`, so it is False, `__main__` not being in the inittab.

Both arms answer on the name alone whichever roots `stdlib` selects: built-in and frozen precede the path finder on `sys.meta_path`, so on import no file on `sys.path` is reachable under such a name, and a module compiled into the interpreter has its code fixed by the interpreter binary, which is what either waiver needs. The `stdlib=False` case is not the stdlib's `sys` asked under the wrong flag (`_is_library_module` routes a name to a flag by its top component) but an embedding that registers `torch._C` through `PyImport_AppendInittab` while torch's Python files stay on disk, so `_torch_roots` is non-empty and torch is not waived on its name; in an ordinary build `torch._C` is an extension module and not in `sys.builtin_module_names`. A spec assigned straight into `sys.modules` is taken at its word.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

stdlib_root = sysconfig.get_paths()["stdlib"]
pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)                  # True
pp._classify_file(torch.__file__, False)                                           # True: the torch arm reads the torch roots
pp._classify_file(torch.__file__, True)                                            # False: torch lies under no stdlib root, or under an install root
pp._classify_file(os.path.join(stdlib_root, "torch", "__init__.py"), False)        # False: the stdlib dir itself is never a pip target, so no torch root holds it
pp._classify_file("graphlib.py", True)                                             # None: relative
pp._classify_file("graphlib.py", False)                                            # None: the gates precede the flag split
pp._classify_file(os.path.join(stdlib_root, "graph\x00lib.py"), True)              # None: embedded NUL, on every platform
platlib_torch = os.path.join(sysconfig.get_paths()["platlib"], "torch")
pp._classify_file.cache_clear()                                                    # in a wheel install the next file IS torch.__file__, judged above
with mock.patch.object(pp, "_torch_roots", return_value=(pp._norm(platlib_torch),)):
    pp._classify_file(os.path.join(platlib_torch, "__init__.py"), False)            # True: the torch arm is exempt from the install-root exclusion
for flag in (True, "console_exe"):                                                 # a frozen app: PyInstaller and cx_Freeze set True, py2exe a string
    pp._classify_file.cache_clear()
    with mock.patch.object(sys, "frozen", flag, create=True):
        pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)          # None: the bundle root holds the stdlib and third parties alike
        pp._classify_file(torch.__file__, False)                                   # True: the torch arm keeps torch's own package directory
        pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), False)         # False: and that root holds nothing outside torch
pp._classify_file.cache_clear()
pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)                  # True again: the answer changed with sys.frozen, hence the clear
import ntpath
with mock.patch.object(sys, "platform", "win32"), mock.patch.object(os, "path", ntpath), mock.patch.object(os, "sep", "\\"), mock.patch.object(pp, "_stdlib_roots", return_value=(r"c:\python312\lib",)), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._classify_file(r"\Lib\graphlib.py", True)                                   # None: driveless, so resolved against the current drive
    pp._classify_file("C:\\Python312\\Lib\\graphlib.py\x00C:\\evil\\evil.py", True)   # None: without the gate ntpath.realpath returns it unresolved and it lies under the root
    pp._classify_file(r"c:\python312\lib\vendored\site-packages\graphlib.py", True)  # False: the part below the root is split on os.sep, so the name is seen
with mock.patch.object(pp, "_install_roots", return_value=()):
    pp._classify_file(os.path.join(stdlib_root, "vendored", "site-packages", "g.py"), True)   # False: _INSTALL_DIR_NAMES alone, two components below the root
    pp._classify_file(os.path.join(stdlib_root, "vendored", "dist-packages", "g.py"), True)   # False: same
    pp._classify_file(os.path.join(stdlib_root, "vendored", "Site-Packages", "g.py"), True)   # False: case folded
    pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True)  # True: nothing installed there
    with mock.patch.object(pp, "_stdlib_roots", return_value=()):
        pp._classify_file(os.path.join(stdlib_root, "os.py"), True)                    # False: under no stdlib root at all
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)):
    pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True)  # False: the install-root exclusion alone
tmp = tempfile.mkdtemp()                                                           # a tree of its own: a real <stdlib>/site-packages is a symlink out of the stdlib on some layouts
bundled = os.path.join(tmp, "site-packages", "runtime", "lib")                     # a stdlib that itself sits under site-packages
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(bundled),)):
    pp._classify_file(os.path.join(bundled, "graphlib.py"), True)                  # True: site-packages ABOVE the stdlib root does not count
    pp._classify_file(os.path.join(bundled, "site-packages", "graphlib.py"), True) # False: below it does
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp), pp._norm(bundled))):
    pp._classify_file(os.path.join(bundled, "graphlib.py"), True)                  # False: of nested roots the outermost is matched
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp),)):
    pp._classify_file(os.path.join(tmp, "site-packages", os.pardir, "g.py"), True) # True: judged after _norm resolves it, not as recorded
```

```python
module = types.ModuleType("graphlib")
module.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
pp._located(module, "graphlib", True)              # False: a placed file decides either way
module.__file__ = os.path.join(stdlib_root, "graphlib.py")
pp._located(module, "graphlib", True)              # True
on_disk = types.ModuleType("torch")
on_disk.__file__ = torch.__file__
pp._located(on_disk, "torch", False)               # True: the flag reaches the file arm (the production torch shape)
pp._located(on_disk, "torch", True)                # False
class Shadow(types.ModuleType):
    __file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
pp._located(Shadow("graphlib"), "graphlib", True)  # None: a class attribute is not in the module dict
pp._located(torch.ops, "torch.ops", False)         # None: same shape, the real one (a canary: a getattr read would answer None too)
raising = types.ModuleType("graphlib")
raising.__getattr__ = mock.Mock(side_effect=RuntimeError)
del raising.__spec__, raising.__loader__            # ModuleType seeds both into the dict
pp._located(raising, "graphlib", True)             # None, and __getattr__ was not called for __file__, __spec__ or __loader__
eager = mock.Mock(**{"create_module.return_value": None})
wrapped = importlib.util.LazyLoader(eager)
lazy_spec = importlib.util.spec_from_file_location("graphlib", os.path.join(stdlib_root, "site-packages", "graphlib.py"), loader=wrapped)
lazy = importlib.util.module_from_spec(lazy_spec)
wrapped.exec_module(lazy)                      # now a _LazyModule: any attribute read runs eager.exec_module
pp._located(lazy, "graphlib", True)                # False, and eager.exec_module was not called
pp._located(types.ModuleType("graphlib"), "graphlib", True)   # None: no file, no spec
odd = types.ModuleType("graphlib")
odd.__file__ = 42
pp._located(odd, "graphlib", True)                 # None: not a path
class Proxy:                                       # a non-module sys.modules entry
    __slots__ = ()
    def __getattr__(self, attr): raise RuntimeError(attr)
pp._located(Proxy(), "graphlib", True)             # None: object's __dict__ read raises AttributeError on a slotted entry; caught, __getattr__ never consulted
odd.__spec__ = Proxy()
pp._located(odd, "graphlib", True)                 # None: so is spec.loader
odd.__file__ = os.path.join(stdlib_root, "graphlib.py")
pp._located(odd, "graphlib", True)                 # True: a placed file decides, the loader is never read
spec_poisoned = types.ModuleType("sys")
spec_poisoned.__spec__ = Proxy()
spec_poisoned.__loader__ = importlib.machinery.BuiltinImporter
pp._located(spec_poisoned, "sys", True)            # True: __loader__ is read first, so the spec never is
bootstrap = types.ModuleType("importlib._bootstrap")
bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py")
bootstrap.__loader__ = importlib.machinery.FrozenImporter   # the real module's shape; FrozenImporter.find_spec("importlib._bootstrap") is None
pp._located(bootstrap, "importlib._bootstrap", True)        # True: the file decides before the loader is read
shadow_sys = types.ModuleType("sys")
shadow_sys.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
shadow_sys.__loader__ = importlib.machinery.BuiltinImporter
pp._located(shadow_sys, "sys", True)               # False: the converse, an installed file under a built-in name
odd_sys = types.ModuleType("sys")
odd_sys.__file__ = 42
odd_sys.__loader__ = importlib.machinery.BuiltinImporter
pp._located(odd_sys, "sys", True)                  # True: a __file__ that cannot be placed is no evidence, so the loader is read
relative = types.ModuleType("zipimport")
relative.__file__ = "zipimport.py"
relative.__loader__ = importlib.machinery.FrozenImporter
pp._located(relative, "zipimport", True)           # True: same for a relative one
frozen_zip = types.ModuleType("zipimport")                  # frozen on every version; os only from 3.11 on (gh-45020)
frozen_zip.__file__ = os.path.join(stdlib_root, "zipimport.py")
frozen_zip.__loader__ = importlib.machinery.FrozenImporter
with mock.patch.object(sys, "frozen", True, create=True):
    pp._located(frozen_zip, "zipimport", True)     # True: in a frozen app the file arm is no evidence, so the loader decides
pp._located(sys, "sys", True)                      # True: built in
pp._located(sys, "sys.sub", True)                  # False: the caller's name is looked up, not the module's __name__
zipimport_by_name = types.ModuleType("zipimport")
zipimport_by_name.__loader__ = importlib.machinery.FrozenImporter
pp._located(zipimport_by_name, "zipimport.sub", True)  # False: same in the frozen arm
sub = types.ModuleType("sys.sub")
sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in")
pp._located(sub, "sys.sub", True)                  # False: the inittab is keyed on the full dotted name
frozen = importlib.machinery.FrozenImporter
zipimport_frozen = types.ModuleType("zipimport")
zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen")
pp._located(zipimport_frozen, "zipimport", True)   # True: the frozen table has zipimport
zipimport_sub = types.ModuleType("zipimport.sub")
zipimport_sub.__spec__ = importlib.machinery.ModuleSpec("zipimport.sub", frozen, origin="frozen")
pp._located(zipimport_sub, "zipimport.sub", True)  # False: keyed on the full dotted name, not its top component
graphlib_frozen = types.ModuleType("graphlib")
graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen")
pp._located(graphlib_frozen, "graphlib", True)     # False: a frozen spec under a name the frozen table does not have
with mock.patch.object(frozen, "find_spec", side_effect=ImportError):
    pp._located(zipimport_by_name, "zipimport", True)  # None: find_spec raises on an excluded or invalid frozen table entry, and nothing escapes _located
lying_eq = types.ModuleType("sys")
lying_eq.__loader__ = mock.ANY                     # a stdlib object whose __eq__ answers true for anything
pp._located(lying_eq, "sys", True)                 # None: the arms match the loader class by identity
by_loader = types.ModuleType("sys")
by_loader.__loader__ = importlib.machinery.BuiltinImporter
pp._located(by_loader, "sys", True)                # True: __loader__ alone in the dict, no spec
by_loader = types.ModuleType("zipimport")
by_loader.__loader__ = frozen
pp._located(by_loader, "zipimport", True)          # True: same, frozen
pp._located(by_loader, "zipimport", False)         # True: both arms answer under either flag
by_loader = types.ModuleType("sys")
by_loader.__loader__ = importlib.machinery.BuiltinImporter
pp._located(by_loader, "sys", False)               # True: same, built in
with mock.patch.object(sys, "builtin_module_names", (*sys.builtin_module_names, "torch._C")):
    embedded = types.ModuleType("torch._C")
    embedded.__loader__ = importlib.machinery.BuiltinImporter
    pp._located(embedded, "torch._C", False)       # True: the torch shape, an embedded torch._C with torch's Python files on disk
```

## Tests

Both tests call `_clear_root_caches` first, like every other root test, and clear the `_classify_file` cache on entry and on cleanup: its keys are stdlib-rooted paths that other tests judge under patched roots.

**`test_classify_file_places_a_path_by_the_roots_it_lies_under`** pins every arm of `_classify_file` on paths spelled relative to sysconfig's `stdlib` (the stdlib dir itself is never a pip target, so no torch root holds the fake torch path):

- the stdlib True, and the torch arm reading the torch roots and not the stdlib ones;
- the torch arm exempt from the install-root exclusion: with `_torch_roots` patched to `<platlib>/torch`, after asserting that `<platlib>/torch/__init__.py` lies under a real install root and clearing the cache, that file is True. A checkout's `torch.__file__` is under no install root, so the plain torch row cannot see this, while in a wheel install that file IS `torch.__file__`, and without the clear the row would only re-read the torch-arm row's cached verdict;
- the frozen-app None: with `sys.frozen` patched to True and then to py2exe's `"console_exe"`, a stdlib-rooted file under `stdlib=True` is None while `torch.__file__` under `stdlib=False` stays True and that stdlib file under `stdlib=False` is False, the torch arm still telling torch from the rest of a bundle. The cache is cleared before each flag and after the block, and the stdlib file is then re-read as True, the row that shows the answer for a path changing with `sys.frozen` and so what the clears are for;
- the relative None under both flags (the gates precede the flag split) and the embedded-NUL None on every platform;
- the driveless Windows spelling, the NUL path under a Windows stdlib root and an installed file two components below one, with `sys.platform`, `os.path` and `os.sep` patched to `win32`, `ntpath` and a backslash and the root finders patched to `c:\python312\lib` and `()`, so the rows run on every platform. The second replays what gh-106242 does: without the gate `ntpath.realpath` returns the path unresolved, `_within` matches the prefix before the NUL, and the file is waived. The third is the only row that reaches `_INSTALL_DIR_NAMES` with a non-posix separator, which is what splitting the part below the root on `os.sep` rather than `/` is for;
- both `_INSTALL_DIR_NAMES` refusing with `_install_roots` patched to `()`, and a mis-cased `Site-Packages` refusing on every platform (case folded, since `normcase` only folds on Windows);
- a stdlib-rooted file under no stdlib root at all (both root finders patched to `()`) refused, which pins the terminal False without depending on where torch is installed (in a wheel or conda install `torch.__file__` lies under an install root and returns from the exclusion instead);
- one file under a nested `vendored` directory judged twice, with the cache cleared in between: stdlib with nothing installed there, third party once that directory is an install root;
- `_INSTALL_DIR_NAMES` scoped below the root: with `_stdlib_roots` patched to a root that itself sits under `site-packages`, a file directly under it is stdlib and one under a further `site-packages` is not, and with both that root and the one above it patched in, the same file is refused, since the outermost root is the one matched;
- that judging happens after `_norm`: a path naming `site-packages` and then `os.pardir` is stdlib, since it resolves to a plain file directly under the root.

The rows that turn on where an install directory sits relative to a root are spelled on paths that cannot pre-exist -- a `vendored` component under sysconfig's `stdlib`, and a `TemporaryDirectory` for the bundled-interpreter fixture -- because a real `<stdlib>/site-packages` is a symlink out of the stdlib on some layouts (a relocated site-packages, a Windows junction), which resolves such a path out of the root it is meant to be judged under, and then those rows either assert the wrong verdict or pass through the terminal False.

Each row fails under the matching mutation: the `_INSTALL_DIR_NAMES` check or the install-root exclusion removed; `_INSTALL_DIR_NAMES` matched on the whole path, case-sensitively, on `/` in place of `os.sep` or on the first component below the root alone; `_norm` weakened to `normcase` so the recorded path is judged unresolved; the roots walked innermost first; the terminal False turned into None; the `isabs` gate, the driveless gate or the NUL gate removed; the install-root exclusion hoisted above the flag split; the torch arm reading the stdlib roots; the `stdlib` flag ignored; the frozen-app gate removed, answering False, hoisted above the flag split, or asking `is True` of the flag, which the string row alone fails.

**`test_located_reads_the_file_from_the_module_dict`** starts with a placed `__file__` deciding either way (an installed one False, a stdlib one True) and the production torch shape, a module carrying `torch.__file__` asked under `stdlib=False` (True) and `stdlib=True` (False), the only rows on which the flag is not a constant of the file arm. It then pins:

- the module-dict read, with a `ModuleType` subclass whose class attribute `__file__` would classify False if seen (the row that fails under a `getattr` read of `__file__`), the real `torch.ops` as a canary for that shape (asserting first that its dict has no `__file__`; a `getattr` read of its relative `"_ops.py"` would answer the same None, so this row documents rather than pins), and a module whose PEP 562 `__getattr__` raises, with `__spec__` and `__loader__` deleted from its dict, since `ModuleType.__init__` seeds both and a `getattr` read of either would otherwise never reach `__getattr__`;
- a module built through `importlib.util.LazyLoader` over a mock loader, carrying the installed `__file__` (False, and the loader's `exec_module` was not called: under a `getattr` read of `__dict__` the `_LazyModule` runs it, and since the real `graphlib` is in `sys.modules` under that name then raises inside the catch, answering None);
- no file and no spec; a non-string `__file__`; a slotted proxy whose `__getattr__` raises (standing in for a non-module `sys.modules` entry) both as the module and as its `__spec__`; that module again once it has a placeable `__file__`; a `sys` with that proxy as `__spec__` next to a `BuiltinImporter` `__loader__` (True: the dict's `__loader__` is read first, so the spec never is);
- the two rows that pin the arm order: the `importlib._bootstrap` shape, a stdlib `__file__` plus `FrozenImporter`, asserting first that the frozen table does not know the name, is True; an installed `__file__` plus `BuiltinImporter` under `sys` is False;
- the two that cross unusable file evidence with a loader: a non-string `__file__` under `sys` with `BuiltinImporter`, a relative one under `zipimport` with `FrozenImporter`, both True;
- the frozen-app shape: a `zipimport` carrying a stdlib `__file__` and `FrozenImporter` is True with `sys.frozen` patched in, the file arm being no evidence there, so the loader decides. `zipimport` rather than `os` because CPython freezes `os` only from 3.11 on, gh-45020, and the row must hold on 3.10;
- the real `sys` under its own name and under `sys.sub`, and a fabricated `zipimport` with `FrozenImporter` asked under `zipimport.sub` (False: in both arms the caller's name is looked up, not the module's `__name__`); the fabricated `sys.sub`; a frozen spec under a frozen name, under a dotted name whose top component is frozen (`zipimport.sub`) and under a non-frozen name;
- `FrozenImporter.find_spec` patched to raise `ImportError` (None: the loader arms are inside the `try`); a `__loader__` that is `mock.ANY`, a stdlib object whose `__eq__` answers true for anything (None: the arms match by identity, so nothing of its runs);
- each importer as a bare `__loader__` with no spec asked under both flags, and the torch shape, `torch._C` with `BuiltinImporter` under `stdlib=False` with the inittab patched to list it (asserting first that the real one does not).

Each of these mutations fails a row: a `getattr` read of `__file__`, of `__spec__` or of `__loader__` (the first fails the `Shadow` row, the other two the `assert_not_called`); a `getattr` read of `__dict__` (the LazyLoader row); the `stdlib` flag hardcoded on the file arm; the `try/except` removed; the arms swapped or the loader read before the file arm; the `__loader__` read dropped for the spec's loader alone or read after it; either arm's identity comparison loosened to `==`; an inittab or frozen-table lookup on the top component; the name taken from the module's `__name__`; an unconditional frozen True; a False for no evidence; `stdlib and` in front of either loader arm; the `isinstance(file, str)` gate loosened to truthiness; and the fall-through from a None `_classify_file` to the loader replaced by a return. The last two are killed only by rows that cross an unplaceable file with a loader: the loosened gate by the non-string crossing row alone (the catch covers the `TypeError` that `os.path.isabs` raises on a non-string, so it answers the same None as the real one until the module also carries a loader that should have decided), the return by the relative crossing row and the frozen-app row, where `_classify_file` answers None and the loader was to decide.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_classify_file_places_a_path_by_the_roots_it_lies_under -k test_located_reads_the_file_from_the_module_dict
lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Reverted in 7d01447 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197963
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Merged oncall: jit Add this issue/PR to JIT oncall triage queue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants