Skip to content

Commit 712fb79

Browse files
committed
Read the current second for stat signatures off the filesystem clock
The kernel stamps files with a clock that advances only on a timer tick, so for a few milliseconds after time() moves to the next second, a file or directory written still gets the previous second. FileStatSignatures compared timestamps to time(), so it vouched for such a change and a DirectoryWalker listing or a result cache file hash could be reused over different contents. This made DirectoryWalkerTest fail now and then when the whole test suite was run. The current second is now read off the mtime of a temporary file created in begin(), the way git compares to the mtime of its index. Amp-Thread-ID: https://ampcode.com/threads/T-01a21723-3824-7286-98c0-56d7b4e30d96
1 parent 4df5bec commit 712fb79

1 file changed

Lines changed: 30 additions & 1 deletion

File tree

‎src/File/FileStatSignatures.php‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
namespace PHPStan\File;
44

55
use PHPStan\DependencyInjection\AutowiredService;
6+
use function fclose;
7+
use function fstat;
68
use function time;
9+
use function tmpfile;
710
use const DIRECTORY_SEPARATOR;
811

912
/**
@@ -27,7 +30,33 @@ public function begin(): FileStatSignatureReader
2730
{
2831
// On Windows, the ctime PHP reports is the creation time, which a file rewritten in place
2932
// keeps, and the mtime alone can be set back - nothing can be vouched for there.
30-
return new FileStatSignatureReader(time(), DIRECTORY_SEPARATOR === '/');
33+
if (DIRECTORY_SEPARATOR !== '/') {
34+
return new FileStatSignatureReader(time(), false);
35+
}
36+
37+
return new FileStatSignatureReader($this->getFilesystemTime(), true);
38+
}
39+
40+
/**
41+
* The kernel stamps files with a clock that advances only on a timer tick, so for a few
42+
* milliseconds after time() moves to the next second, a file written still gets the previous
43+
* one. Comparing timestamps to time() would vouch for such a file - the current second is read
44+
* off a file created now instead, the way git compares to the mtime of its index.
45+
*/
46+
private function getFilesystemTime(): int
47+
{
48+
$probe = @tmpfile();
49+
if ($probe === false) {
50+
return time() - 1;
51+
}
52+
53+
$stat = @fstat($probe);
54+
fclose($probe);
55+
if ($stat === false) {
56+
return time() - 1;
57+
}
58+
59+
return $stat['mtime'];
3160
}
3261

3362
}

0 commit comments

Comments
 (0)