pypy / pypy

PyPy is a very fast and compliant implementation of the Python language.
https://pypy.org
Other
790 stars 38 forks source link

`os.utime` not setting correct timestamp in some situations #4916

Open mbway opened 3 months ago

mbway commented 3 months ago

When running the following script with pypy3.10 on Windows 10:

import os
from pathlib import Path

my_file = Path("my_file")
my_file.touch()
s = my_file.stat()
print(s.st_mtime_ns)

os.utime(my_file, ns=(s.st_atime_ns, s.st_mtime_ns))

s2 = my_file.stat()
print(s2.st_mtime_ns)
assert s2.st_mtime_ns == s.st_mtime_ns

the expected result is that the assertion passes as the call to os.utime should set the same timestamp as the file already has, but when running on windows, sometimes the assertion fails. The failure is more likely when adding time.sleep(0.1) between the call to stat() and the call to utime. When running with cpython 3.10.11 (or any other cpython version) the assertion never seems to fail.

note: the problem occurs when using times=() or ns=() in the os.utime call

mattip commented 3 months ago

In the documentation for utime it states

Note that the exact times you set here may not be returned by a subsequent stat() call, depending on the resolution with which your operating system records access and modification times; see stat(). The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from the os.stat() result object with the ns parameter to utime.

This may be connected to a failing cython test on windows where there is a check that ctime.time() matches time.time(). I think we should carefully check the time module on windows to make sure it matches the CPython implementation more closely.