Backtestspytestrun-20261106-234554#14864

Issue #14864 Merged fix PR #14865 Run 6 Nov 2026 · run-20261106-234554 pytest-dev/pytest

(Windows) passing a file path collects the whole suite, on a network drive where st_ino is 0

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches fix the reported collection bug at the same place: samefile_nofollow() now returns False when either lstat() reports st_ino == 0, so Session.collect()'s Windows fallback stops matching every node and plain path comparison takes over. The independent tests confirm both pass every scenario from the issue (relative/absolute file arg, file::Class, running, subdirectory, --deselect), so on the issue's own scenarios correctness is equal.

Patch A goes further on the same root cause: os.path.samefile()/samestat() is also used in _is_same() (import_path's module/file mismatch detection) and LocalPath.samefile(). On a zero-inode drive those would silently treat two different files as the same, e.g. import_path returning an already-imported module from another directory instead of raising ImportPathMismatchError. A routes all three through one _samestat() helper that refuses to conclude identity without inode numbers, and keeps the UNC path-equality short-circuit. The non-Windows behaviour change in _is_same (adding a Path equality short-circuit before stat) is benign. The `p1 == p2 or` added to samefile_nofollow is redundant with the caller but harmless.

Tests: A adds an end-to-end regression test that reproduces the issue (zero-inode lstat plus a win32 sys proxy, relative and absolute args, and the file::TestProcess case), plus unit tests for import_path mismatch detection and LocalPath.samefile under zero inodes, and correctly updates test_samefile_false_negatives since _is_same no longer calls samefile. The sys proxy and global os.stat monkeypatching are somewhat hacky but scoped via monkeypatch. B adds two focused unit tests for samefile_nofollow (a sanity test and a zero-file-ID test that would fail before the fix); they are clean but never exercise collection itself.

Scope/craft: B is the minimal fix exactly as proposed in the issue, with a precise comment citing the underlying CPython behaviour and a good changelog; it is tidy and low-risk. A touches more code (including the legacy _py path module), which carries some risk, but the extra changes address the identical failure mode in sibling call sites rather than unrelated churn, and its tests demonstrate the actual user-visible bug is fixed. On balance A is the stronger fix: same core change, broader coverage of the root cause, and a regression test that reproduces the issue scenario.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

10m 34s

Wall-clock time in the container

Full test suite

No new failures

1,288 passed · 34 skipped · 1,349 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

172vs 44 merged

Changed lines, ours vs merged

Hi,
when developing psutil on Windows, I do it by mapping X: to a sshfs share, so from Linux I can SSH into Windows and run tests there. Problem: pytest ignores the file I pass and collects everything:

$ python -m pytest tests/test_memleaks.py --collect-only -o addopts=""
platform win32 -- Python 3.14.6, pytest-9.1.1, pluggy-1.6.0
rootdir: X:\svn\psutil
collected 961 items

That file ( tests/test_memleaks.py ) has 130 tests, while 961 is the whole repo. Using absolute paths does the same.

I think the culprit is samefile_nofollow(), which Session.collect() falls back to on Windows when two paths don't compare equal. On this drive every file has st_ino == 0, so it says any two files are the same one:

$ python -c "
import os
a = os.stat('tests/test_memleaks.py')
b = os.stat('tests/test_process.py')
print(a.st_dev, a.st_ino)
print(b.st_dev, b.st_ino)
print(os.path.samestat(a, b))
"
3816903231 0
3816903231 0
True

So every node matches, nothing gets pruned, and I get the whole tree. The name parts still work, which fits: :: filtering happens after the path level.

$ python -m pytest "tests/test_memleaks.py::TestProcess" --collect-only -q
tests/test_windows.py::TestProcess::test_wait
175 tests collected

That's TestProcess from every file, not the one I asked for.

Maybe the fallback should just bail out when either st_ino is 0, since it can't tell anything apart at that point:

 def samefile_nofollow(p1: Path, p2: Path) -> bool:
-    return os.path.samestat(p1.lstat(), p2.lstat())
+    s1, s2 = p1.lstat(), p2.lstat()
+    if not s1.st_ino or not s2.st_ino:
+        return False
+    return os.path.samestat(s1, s2)

Returning False falls back to plain path comparison, which is what the other platforms do anyway. The short-path case this was added for (#11895) is on local NTFS, so it keeps working.

-m and -k work fine. Anything taking a path (--ignore, --deselect, plain args) doesn't.

The two patches

Our patch+157 −15
changelog/14864.bugfix.rstnew file mode 100644index 000000000..6d1a3f86d@@ -0,0 +1 @@+Fixed passing a file path on the command line collecting every test file on filesystems which report ``st_ino == 0`` for all files (for example network drives mapped via sshfs on Windows): such files are no longer considered to be the same file.src/_pytest/_py/path.pyindex 998a78199..62a3ce08d 100644@@ -591,7 +591,13 @@ class LocalPath:             return True         if not hasattr(os.path, "samefile"):             return False-        return error.checked_call(os.path.samefile, self.strpath, other)+        s1 = error.checked_call(os.stat, self.strpath)+        s2 = error.checked_call(os.stat, other)+        # Filesystems which do not report inode numbers (e.g. network drives on+        # Windows) report st_ino == 0 for every file; samestat() can't tell them apart.+        if not s1.st_ino or not s2.st_ino:+            return False+        return os.path.samestat(s1, s2)      def remove(self, rec=1, ignore_errors=False):         """Remove a file or directory (or a directory tree if rec=1).src/_pytest/pathlib.pyindex 10326e1c9..fa8d1b2f1 100644@@ -789,17 +789,11 @@ def spec_matches_module_path(module_spec: ModuleSpec | None, module_path: Path)     return False  -# Implement a special _is_same function on Windows which returns True if the two filenames-# compare equal, to circumvent os.path.samefile returning False for mounts in UNC (#7678).-if sys.platform.startswith("win"):--    def _is_same(f1: str, f2: str) -> bool:-        return Path(f1) == Path(f2) or os.path.samefile(f1, f2)--else:--    def _is_same(f1: str, f2: str) -> bool:-        return os.path.samefile(f1, f2)+def _is_same(f1: str, f2: str) -> bool:+    # Return True if the two filenames compare equal, to circumvent os.path.samefile+    # returning False for mounts in UNC on Windows (#7678), and to not depend on+    # inode numbers for identical paths on filesystems without them (#14864).+    return Path(f1) == Path(f2) or _samestat(os.stat(f1), os.stat(f2))   def module_name_from_path(path: Path, root: Path) -> str:@@ -1095,4 +1089,17 @@ def samefile_nofollow(p1: Path, p2: Path) -> bool:      Unlike Path.samefile(), does not resolve symlinks.     """-    return os.path.samestat(p1.lstat(), p2.lstat())+    return p1 == p2 or _samestat(p1.lstat(), p2.lstat())+++def _samestat(s1: os.stat_result, s2: os.stat_result) -> bool:+    """Like os.path.samestat(), but never considers files the same when the+    filesystem does not report inode numbers.++    Some filesystems (e.g. network drives/sshfs mounts on Windows) report+    ``st_ino == 0`` for every file, in which case ``os.path.samestat()`` would+    consider any two files on the same device to be the same file (#14864).+    """+    if not s1.st_ino or not s2.st_ino:+        return False+    return os.path.samestat(s1, s2)testing/_py/test_local.pyindex a233b916a..979f32863 100644@@ -1209,6 +1209,25 @@ def test_samefile(tmpdir):         assert p1.samefile(p2)  +def test_samefile_without_inodes(tmpdir, monkeypatch):+    """Files are not considered the same when the filesystem reports+    st_ino == 0 for every file (#14864)."""+    p1 = tmpdir.ensure("foo.txt")+    p2 = tmpdir.ensure("bar.txt")+    original_stat = os.stat++    def stat(path, *args, **kwargs):+        st = original_stat(path, *args, **kwargs)+        return os.stat_result(+            (st.st_mode, 0, st.st_dev, st.st_nlink, st.st_uid, st.st_gid)+            + (st.st_size, int(st.st_atime), int(st.st_mtime), int(st.st_ctime))+        )++    monkeypatch.setattr(os, "stat", stat)+    assert p1.samefile(p1)+    assert not p1.samefile(p2)++ @pytest.mark.skipif(not hasattr(os, "symlink"), reason="os.symlink not available") def test_samefile_symlink(tmpdir):     p1 = tmpdir.ensure("foo.txt")testing/test_collection.pyindex 093162dde..f3978b6fd 100644@@ -1888,6 +1888,56 @@ def test_do_not_collect_symlink_siblings(     result.assert_outcomes(passed=1)  +def _zero_inode_lstat(monkeypatch: MonkeyPatch) -> None:+    """Make Path.lstat() report st_ino == 0 for every file, as some network+    drives (e.g. sshfs mapped drives on Windows) do."""+    original_lstat = Path.lstat++    def lstat(self: Path) -> os.stat_result:+        st = original_lstat(self)+        return os.stat_result(+            (st.st_mode, 0, st.st_dev, st.st_nlink, st.st_uid, st.st_gid)+            + (st.st_size, int(st.st_atime), int(st.st_mtime), int(st.st_ctime))+        )++    monkeypatch.setattr(Path, "lstat", lstat)+++class _Win32Sys:+    """Proxy for the sys module, pretending to run on Windows."""++    platform = "win32"++    def __getattr__(self, name: str) -> object:+        return getattr(sys, name)+++@pytest.mark.parametrize("absolute", [False, True])+def test_collect_file_arg_on_filesystem_without_inodes(+    pytester: Pytester, monkeypatch: MonkeyPatch, absolute: bool+) -> None:+    """Regression test for #14864: passing a file path should only collect that+    file, even when the filesystem reports st_ino == 0 for every file, which made+    the Windows short-path fallback (#11895) consider every file a match."""+    pytester.makepyfile(+        test_a="class TestProcess:\n    def test_a(self): pass",+        test_b="class TestProcess:\n    def test_b(self): pass",+    )+    import _pytest.main++    monkeypatch.setattr(_pytest.main, "sys", _Win32Sys())+    _zero_inode_lstat(monkeypatch)++    arg = str(pytester.path / "test_a.py") if absolute else "test_a.py"+    result = pytester.runpytest_inprocess(arg, "--collect-only", "-q")+    result.stdout.fnmatch_lines(["test_a.py::TestProcess::test_a", "1 test collected*"])+    result.stdout.no_fnmatch_line("*test_b*")++    result = pytester.runpytest_inprocess(f"{arg}::TestProcess", "--collect-only", "-q")+    result.stdout.fnmatch_lines(["test_a.py::TestProcess::test_a", "1 test collected*"])+    result.stdout.no_fnmatch_line("*test_b*")++ @pytest.mark.parametrize(     "exception_class, msg",     [testing/test_pathlib.pyindex bd85b7e8f..0d0461a9a 100644@@ -560,16 +560,75 @@ def test_samefile_false_negatives(tmp_path: Path, monkeypatch: MonkeyPatch) -> N     monkeypatch.syspath_prepend(tmp_path)      with monkeypatch.context() as mp:-        # Forcibly make os.path.samefile() return False here to ensure we are comparing+        # Forcibly make os.path.samestat() return False here to ensure we are comparing         # the paths too. Using a context to narrow the patch as much as possible given         # this is an important system function.-        mp.setattr(os.path, "samefile", lambda x, y: False)+        mp.setattr(os.path, "samestat", lambda x, y: False)         module = import_path(             module_path, root=tmp_path, consider_namespace_packages=False         )     assert getattr(module, "foo")() == 42  +def _zero_inode_stat(monkeypatch: MonkeyPatch) -> None:+    """Make os.stat() report st_ino == 0 for every file, as some network drives+    (e.g. sshfs mapped drives on Windows) do."""+    original_stat = os.stat++    def stat(path: Any, *args: Any, **kwargs: Any) -> os.stat_result:+        st = original_stat(path, *args, **kwargs)+        return os.stat_result(+            (st.st_mode, 0, st.st_dev, st.st_nlink, st.st_uid, st.st_gid)+            + (st.st_size, int(st.st_atime), int(st.st_mtime), int(st.st_ctime))+        )++    monkeypatch.setattr(os, "stat", stat)+++def test_import_path_mismatch_on_filesystem_without_inodes(+    tmp_path: Path, monkeypatch: MonkeyPatch+) -> None:+    """Regression test for #14864: import_path() must still detect that an+    already imported module of the same name comes from a different file when+    the filesystem reports st_ino == 0 for every file."""+    for name in ("a", "b"):+        tmp_path.joinpath(name).mkdir()+        tmp_path.joinpath(name, "mod_14864.py").write_text(+            f"WHERE = {name!r}", encoding="utf-8"+        )+    monkeypatch.delitem(sys.modules, "mod_14864", raising=False)+    monkeypatch.syspath_prepend(tmp_path)++    mod = import_path(+        tmp_path / "a" / "mod_14864.py",+        mode=ImportMode.prepend,+        root=tmp_path,+        consider_namespace_packages=False,+    )+    monkeypatch.setitem(sys.modules, "mod_14864", mod)+    assert mod.WHERE == "a"++    with monkeypatch.context() as mp:+        _zero_inode_stat(mp)+        # The very same file is still recognized as such.+        assert (+            import_path(+                tmp_path / "a" / "mod_14864.py",+                mode=ImportMode.prepend,+                root=tmp_path,+                consider_namespace_packages=False,+            )+            is mod+        )+        with pytest.raises(ImportPathMismatchError):+            import_path(+                tmp_path / "b" / "mod_14864.py",+                mode=ImportMode.prepend,+                root=tmp_path,+                consider_namespace_packages=False,+            )++ def test_scandir_with_non_existent_directory() -> None:     # Test with a directory that does not exist     non_existent_dir = "path_to_non_existent_dir" 
Merged fix · PR #14865+43 −1
changelog/14864.bugfix.rstnew file mode 100644index 000000000..5f4c19dca@@ -0,0 +1 @@+Fixed collection on Windows collecting the whole suite instead of the given path, on file systems which do not support file IDs (``st_ino`` is ``0`` for every file, as seen for example on ``sshfs-win``/WinFsp mounts).src/_pytest/pathlib.pyindex 10326e1c9..c7bbc9394 100644@@ -1095,4 +1095,12 @@ def samefile_nofollow(p1: Path, p2: Path) -> bool:      Unlike Path.samefile(), does not resolve symlinks.     """-    return os.path.samestat(p1.lstat(), p2.lstat())+    s1, s2 = p1.lstat(), p2.lstat()+    # On Windows st_ino is the file ID, which file systems are free to not support,+    # in which case it is 0 for every file -- WinFsp mounts such as sshfs-win are one+    # example. os.path.samestat() would then consider any two files on the volume to+    # be the same (python/cpython#78116), so treat a zero file ID as "unknown" and+    # leave the caller with plain path comparison (#14864).+    if s1.st_ino == 0 or s2.st_ino == 0:+        return False+    return os.path.samestat(s1, s2)testing/test_pathlib.pyindex bd85b7e8f..6f37ecf51 100644@@ -38,6 +38,7 @@ from _pytest.pathlib import module_name_from_path from _pytest.pathlib import resolve_package_path from _pytest.pathlib import resolve_pkg_root_and_module_name from _pytest.pathlib import safe_exists+from _pytest.pathlib import samefile_nofollow from _pytest.pathlib import scandir from _pytest.pathlib import spec_matches_module_path from _pytest.pathlib import symlink_or_skip@@ -570,6 +571,38 @@ def test_samefile_false_negatives(tmp_path: Path, monkeypatch: MonkeyPatch) -> N     assert getattr(module, "foo")() == 42  +def test_samefile_nofollow(tmp_path: Path) -> None:+    p1 = tmp_path / "test_one.py"+    p2 = tmp_path / "test_two.py"+    p1.touch()+    p2.touch()++    assert samefile_nofollow(p1, p1)+    assert not samefile_nofollow(p1, p2)+++def test_samefile_nofollow_zero_file_id(+    tmp_path: Path, monkeypatch: MonkeyPatch+) -> None:+    """On Windows file systems which do not support file IDs, st_ino is 0 for every+    file, which must not make two distinct files compare equal (#14864)."""+    p1 = tmp_path / "test_one.py"+    p2 = tmp_path / "test_two.py"+    p1.touch()+    p2.touch()++    # st_dev is a real value (the volume serial number), only the file ID is missing.+    zero_file_id = os.stat_result((0o100644, 0, 3816903231, 1, 0, 0, 0, 0, 0, 0))+    with monkeypatch.context() as mp:+        # Use a context to narrow the patch as much as possible, given how central+        # Path.lstat() is.+        mp.setattr(Path, "lstat", lambda self: zero_file_id)++        assert not samefile_nofollow(p1, p2)+        # Also for the same file -- the caller compares paths first anyway.+        assert not samefile_nofollow(p1, p1)++ def test_scandir_with_non_existent_directory() -> None:     # Test with a directory that does not exist     non_existent_dir = "path_to_non_existent_dir"