Skip to content

Commit 7d43f41

Browse files
ondrejmirtesclaude
andcommitted
Store file cache entries serialized instead of as var_export()ed PHP
FileCacheStorage wrote every entry as a PHP file returning a var_export()ed CacheItem and loaded it with include. Compiling such a file costs more than unserializing the same data, every object in it is hydrated through a userland __set_state() call, and the compiled code stays in memory for the rest of the process. Entries are now serialize() payloads in *.dat files - the separate extension keeps an older PHPStan sharing the directory from including a payload that is not PHP. clearUnusedFiles() (cache version v3-serialized) deletes the *.php entries of the former formats once. src/Analyser src/Rules src/Type single process, 8 interleaved pairs, warm cache: 20.27 s -> 19.69 s user CPU (-2.86 %, 8/8, t = -53), peak RSS 589 MB -> 526 MB (-11 %), output identical. IntermediaryNameScope::intern() stays: serialize() keeps objects shared within an entry but stores arrays by value, and skipping the interning measured +38 MB for no CPU gain. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QSGnoYacTfJv3taAhZkj5o
1 parent 271c496 commit 7d43f41

4 files changed

Lines changed: 80 additions & 47 deletions

File tree

‎src/Analyser/IntermediaryNameScope.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,8 @@ public function unsetTemplatePhpDocNodes(array $namesToUnset): self
119119
/**
120120
* Restores sharing of identical property values and parent scopes after hydration from the file cache.
121121
*
122-
* var_export() used by the cache cannot represent shared references, so every hydrated
123-
* scope carries its own copy of the same uses maps and of the whole parent chain.
122+
* serialize() keeps objects shared within an entry but stores arrays by value, so
123+
* every hydrated scope carries its own copy of the same uses maps.
124124
* Without interning, the name scope map of a file with many members takes up
125125
* many times more memory when loaded from the cache than when freshly created.
126126
*

‎src/Cache/Cache.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public function load(string $key, string $variableKey)
2828
// Every entry is also shared across the run's parallel workers
2929
// through the shared-memory arena (turbo extension only; the seam is
3030
// a no-op otherwise): whichever process loads or saves an entry first
31-
// publishes it, and the others skip the include() of the var_export'd
31+
// publishes it, and the others skip reading and unserializing the
3232
// cache file. The arena's codec covers scalars, arrays and plain
3333
// value objects, and interns repeated strings on read like include()
3434
// does; payloads it cannot represent just stay per-worker.

‎src/Cache/FileCacheStorage.php‎

Lines changed: 39 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,37 @@
1717
use function closedir;
1818
use function dirname;
1919
use function error_get_last;
20+
use function file_get_contents;
2021
use function hash;
2122
use function is_dir;
2223
use function is_file;
2324
use function opendir;
2425
use function readdir;
2526
use function rename;
2627
use function rmdir;
28+
use function serialize;
2729
use function sprintf;
28-
use function str_starts_with;
30+
use function str_ends_with;
2931
use function strlen;
3032
use function substr;
3133
use function uksort;
3234
use function unlink;
33-
use function var_export;
35+
use function unserialize;
3436
use const DIRECTORY_SEPARATOR;
3537

38+
/**
39+
* Entries are stored as serialize() payloads in *.dat files. They used to be
40+
* var_export()ed PHP files loaded with include: compiling such a file costs
41+
* more than unserializing the same data, every hydrated object goes through
42+
* a userland __set_state() call, and the compiled code stays in memory for the
43+
* rest of the process - 11 % of the peak memory of a single-process analysis.
44+
* The separate extension keeps an older PHPStan sharing the directory from
45+
* including a payload that is not PHP.
46+
*/
3647
final class FileCacheStorage implements CacheStorage
3748
{
3849

39-
private const CACHED_CLEARED_VERSION = 'v2-new';
50+
private const CACHED_CLEARED_VERSION = 'v3-serialized';
4051

4152
public function __construct(private string $directory)
4253
{
@@ -60,17 +71,20 @@ public function load(string $key, string $variableKey)
6071
return null;
6172
}
6273

63-
return (static function ($variableKey, $filePath) {
64-
$cacheItem = @include $filePath;
65-
if (!$cacheItem instanceof CacheItem) {
66-
return null;
67-
}
68-
if (!$cacheItem->isVariableKeyValid($variableKey)) {
69-
return null;
70-
}
74+
$contents = @file_get_contents($filePath);
75+
if ($contents === false) {
76+
return null;
77+
}
78+
79+
$cacheItem = @unserialize($contents);
80+
if (!$cacheItem instanceof CacheItem) {
81+
return null;
82+
}
83+
if (!$cacheItem->isVariableKeyValid($variableKey)) {
84+
return null;
85+
}
7186

72-
return $cacheItem->getData();
73-
})($variableKey, $filePath);
87+
return $cacheItem->getData();
7488
}
7589

7690
/**
@@ -86,15 +100,12 @@ public function save(string $key, string $variableKey, $data): void
86100

87101
$tmpPath = sprintf('%s/%s.tmp', $this->directory, Random::generate());
88102
$errorBefore = error_get_last();
89-
$exported = @var_export(new CacheItem($variableKey, $data), true);
103+
$serialized = @serialize(new CacheItem($variableKey, $data));
90104
$errorAfter = error_get_last();
91105
if ($errorAfter !== null && $errorBefore !== $errorAfter) {
92106
throw new ShouldNotHappenException(sprintf('Error occurred while saving item %s (%s) to cache: %s', $key, $variableKey, $errorAfter['message']));
93107
}
94-
FileWriter::write(
95-
$tmpPath,
96-
"<?php declare(strict_types = 1);\n\n" . '// ' . $key . "\nreturn " . $exported . ';',
97-
);
108+
FileWriter::write($tmpPath, $serialized);
98109

99110
$renameSuccess = @rename($tmpPath, $path);
100111
if ($renameSuccess) {
@@ -117,7 +128,7 @@ private function getFilePaths(string $key): array
117128
$keyHash = hash('sha256', $key);
118129
$firstDirectory = sprintf('%s/%s', $this->directory, substr($keyHash, 0, 2));
119130
$secondDirectory = sprintf('%s/%s', $firstDirectory, substr($keyHash, 2, 2));
120-
$filePath = sprintf('%s/%s.php', $secondDirectory, $keyHash);
131+
$filePath = sprintf('%s/%s.dat', $secondDirectory, $keyHash);
121132

122133
return [
123134
$firstDirectory,
@@ -144,38 +155,22 @@ public function clearUnusedFiles(): void
144155
}
145156
}
146157

158+
// every entry written before the serialize() format is a *.php file;
159+
// none of them is read anymore
147160
$iterator = new RecursiveDirectoryIterator($this->directory);
148161
$iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
149162
$files = new RecursiveIteratorIterator($iterator);
150-
$beginFunction = sprintf(
151-
"<?php declare(strict_types = 1);\n\n%s",
152-
sprintf('// %s', 'variadic-function-'),
153-
);
154-
$beginMethod = sprintf(
155-
"<?php declare(strict_types = 1);\n\n%s",
156-
sprintf('// %s', 'variadic-method-'),
157-
);
158-
$beginNew = "<?php declare(strict_types = 1);\n\n//";
159163
$emptyDirectoriesToCheck = [];
160164
foreach ($files as $file) {
161-
try {
162-
$path = $file->getPathname();
163-
$contents = FileReader::read($path);
164-
if (
165-
!str_starts_with($contents, $beginFunction)
166-
&& !str_starts_with($contents, $beginMethod)
167-
&& str_starts_with($contents, $beginNew)
168-
) {
169-
continue;
170-
}
171-
172-
$emptyDirectoriesToCheck[dirname($path)] = true;
173-
$emptyDirectoriesToCheck[dirname($path, 2)] = true;
174-
175-
@unlink($path);
176-
} catch (CouldNotReadFileException) {
165+
$path = $file->getPathname();
166+
if (!str_ends_with($path, '.php')) {
177167
continue;
178168
}
169+
170+
$emptyDirectoriesToCheck[dirname($path)] = true;
171+
$emptyDirectoriesToCheck[dirname($path, 2)] = true;
172+
173+
@unlink($path);
179174
}
180175

181176
uksort($emptyDirectoriesToCheck, static fn ($a, $b) => strlen($b) - strlen($a));

‎tests/PHPStan/Cache/FileCacheStorageTest.php‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
use PHPStan\Testing\PHPStanTestCase;
99
use RecursiveDirectoryIterator;
1010
use RecursiveIteratorIterator;
11+
use function file_put_contents;
1112
use function is_dir;
13+
use function mkdir;
1214
use function rmdir;
1315
use function sys_get_temp_dir;
1416
use function uniqid;
@@ -86,4 +88,40 @@ public function testEntryWithDifferentVariableKey(): void
8688
$this->assertSame(['data' => 1], $storage->load('key', 'v1'));
8789
}
8890

91+
/**
92+
* @throws DirectoryCreatorException
93+
*/
94+
public function testEntryWithObjectsRoundTrips(): void
95+
{
96+
$storage = new FileCacheStorage($this->directory);
97+
$shared = new CacheItem('inner', ['a' => 1]);
98+
$storage->save('key', 'v1', [$shared, $shared]);
99+
100+
$loaded = $storage->load('key', 'v1');
101+
$this->assertIsArray($loaded);
102+
$this->assertInstanceOf(CacheItem::class, $loaded[0]);
103+
$this->assertSame(['a' => 1], $loaded[0]->getData());
104+
$this->assertSame($loaded[0], $loaded[1]);
105+
}
106+
107+
/**
108+
* @throws DirectoryCreatorException
109+
*/
110+
public function testClearUnusedFilesRemovesEntriesOfTheFormerFormat(): void
111+
{
112+
$storage = new FileCacheStorage($this->directory);
113+
$storage->save('key', 'v1', ['data' => 1]);
114+
115+
$formerEntryDirectory = $this->directory . '/ab/cd';
116+
mkdir($formerEntryDirectory, 0777, true);
117+
$formerEntry = $formerEntryDirectory . '/abcd.php';
118+
file_put_contents($formerEntry, "<?php declare(strict_types = 1);\n\n// key\nreturn null;");
119+
120+
$storage->clearUnusedFiles();
121+
122+
$this->assertFileDoesNotExist($formerEntry);
123+
$this->assertDirectoryDoesNotExist($this->directory . '/ab');
124+
$this->assertSame(['data' => 1], $storage->load('key', 'v1'));
125+
}
126+
89127
}

0 commit comments

Comments
 (0)