Skip to content

Result cache: when should two analyses share a cache file, and when should they have their own? #15163

Open

Description

@SanderMuller

Feature request

Follow-up to phpstan/phpstan-src#1469, at @ondrejmirtes's request: what we know now about when two analyses should share a result cache file and when they need their own, with the measurements behind it. Where a measurement needed a vendor-installed PHPStan (so that %rootDir% moves with the project) it was run with the 2.2.12 phar; the rest is a source build of 2.2.x.

What relative paths already solved

Your suspicion is right, and it holds in the strongest form. A project copied to a different directory on disk, with PHPStan installed in its own vendor and no local tmpDir (so the system one), reuses the cache:

projA (first run)   Result cache not used because the cache file does not exist.
projB (the copy)    Result cache restored. 0 files will be reanalysed.

The same holds when the project carries its own tmpDir along in the copy: 0 files will be reanalysed in the copy as well.

The anchor is %rootDir%, so a vendor-installed PHPStan moves with the project and every path in the metadata and the storage relativizes against it. Two consequences worth writing down:

  • a fresh CI checkout at a different path, a git worktree, or a copy-on-write clone can all reuse a cache produced elsewhere;
  • it does not apply when PHPStan lives outside the project (a global or phar install), because then the anchor does not move with it.

What still throws the cache away

Two configs in one project, run alternately, sharing a tmpDir:

app run1  cache file does not exist
lib run1  metadata do not match: projectConfig, analysedPaths
app run2  metadata do not match: projectConfig, analysedPaths
lib run2  metadata do not match: projectConfig, analysedPaths

Neither config is ever warm. And because the default tmpDir is sys_get_temp_dir() . '/phpstan' (CommandHelper.php:396), the same happens between two unrelated projects on one machine when neither sets tmpDir: 6 runs, 5 full re-analyses. Nobody would recognise that as a cache problem; it just looks like PHPStan is slow.

Git worktrees, since you raised them

setup outcome
worktree with its own default tmpDir cache file does not exist - cold
worktree pointed at a shared tmpDir restored. 0 files will be reanalysed.
a copy of the project directory, tmpDir included restored. 0 files will be reanalysed.

So worktrees are cold by default and warm by configuration today. Two worktrees on divergent branches sharing one cache file re-analyse each other's delta rather than everything - measured with a one-file difference between two worktrees, each alternating run reports restored. 1 file will be reanalysed. That is churn, not corruption, now that the save renames into place. If cache discovery ever looks upward or into a shared location, worktrees get this for free.

Where the discussion starts: the metadata decides

Two analyses should share a file exactly when their metadata agrees, which is the rule the code already enforces - it just has one file to enforce it in. Naming the cache file after the identity part of the metadata would make sharing and separation fall out of the same rule: two copies of a similar project land on one file and reuse it, two configs or two projects land on different files and stop evicting each other, whatever tmpDir says.

The open question is which keys are identity and which are validity, because hashing all of the metadata into the name would create a new file on every composer update and orphan the old one. analysedPaths, projectConfig, level and phpVersionForAnalysis look like identity; executedFilesHashes, composerInstalled and composerLocks are validity and belong inside the file, where they already are.

phpstan/phpstan-src#1469 is the per-config version of this. Two things I noticed while reproducing with it: it only applies when neither tmpDir nor resultCachePath is set, so a repository that keeps its cache in the tree for CI keeps thrashing; and the name is an md5 of analysedPaths plus bootstrapFiles, so two configs over the same paths that differ only in level still collide.

Two more measurements that bear on it

  • What to copy between machines is resultCache.php alone. tmpDir after analysing 2485 files is 27 MB of resultCache.php and 128 MB of cache/, and dropping the latter costs nothing on a full cache hit (1.50s against 1.93s) and about 1s of CPU on a partial one (2.40s against 3.41s). Of those 5569 files, 88% contain an absolute path; sampling their keys gives ftm- 142, odsl- 140, osfsl- 71, phpinternal- 47, and it is the odsl-/osfsl- ones - the source locators, keyed by absolute path - that cannot hit at another path at all.
  • tmpDir is currently part of the key, so moving the cache directory alone invalidates it (metadata do not match: projectConfig). Do not invalidate the result cache when tmpDir changes phpstan-src#6359 takes it out; where the cache is stored cannot change what it holds. That matters here because a shared cache directory is spelled differently on different machines.

Happy to write the e2e fixtures for any of this - the result-cache blocks are plain shell now, so alternating two configs, or clearing the system temp directory first, is a few lines. That was the concern that stalled #1469 in 2022 and it no longer applies.

Activity

  1. staabm commented on Sep 3, 2026

    @staabm
    Contributor

    one thing we should ask/answer is, whether we can/should have more than a single result-cache file in the global sys_get_temp_dir() . '/phpstan' which would allow people working with PHPStan to switch between projects and still have a warm cache - without additional configuration needed.

    we need to balance such a feature with the required filespace in the sys_get_temp_dir() . '/phpstan' folder. how many result cache files can we afford? how can we build a stable result-cache file-path inside sys_get_temp_dir() . '/phpstan' which is unique per project and can still be cleaned up (not flooding the temp dir; when can/should we delete/overwrite pre-existing result cache files?)

    see also #7379

  2. SanderMuller commented on Sep 3, 2026

    @SanderMuller
    ContributorAuthor

    Both of those look answerable now, so I built a prototype and ran it on real projects instead of reasoning about it.

    Yes to more than one file, and the file name can do the deciding. The metadata comparison already enforces the rule "these two analyses may share results"; deriving the name from the identity half of that metadata makes sharing and separation fall out of it, whatever tmpDir says. Identity in the prototype: analysedPaths relativized against the anchor, projectConfig stripped of parametersNotInvalidatingCache, ksorted and relativized exactly as isMetaDifferent() normalizes it, level, phpVersionForAnalysis, the Composer root package names, and the installed package versions. Validity keys stay inside the file, so a file edit or a composer.lock rewrite changes what is in the cache and not which cache is used.

    Six projects sharing one tmpDir, which is what the default sys_get_temp_dir()/phpstan is: four unrelated ones (analysed directories of 4524, 1960, 1960 and 53 PHP files), a real git worktree of one of them with its own installed vendor, a plain copy of another, and a second config inside one project. Level 5, no project rule sets. The same 15-run sequence three times:

    total CPU warm hits
    today, one file per directory 1501.4s 0 of 15
    identity keys 980.3s 6
    identity keys + Composer package state 534.9s / 544.9s 9

    Today's arm never gets a warm hit after the first cold run. Of the 14 remaining runs, 13 report a metadata mismatch and one reports Composer packages changed (100 packages) and register a class in the container; re-analysing everything.

    The part I had wrong until the real projects showed it: identity keys alone are not enough. Two checkouts of one project relativize to the same paths and carry the same config, so they land on one file, and since their vendor directories were installed at different times every visit is a full re-analysis (149.1s, 152.9s, 145.5s). Adding the installed package versions and references, minus the root package whose reference is the current commit, gives each checkout its own file: 148.9s once, then 2.2s and 2.1s. A plain copy with the same vendor state still hits the file the original wrote (restored. 0 files will be reanalysed), so relocation keeps working. That is the one real trade here: a dependency update starts a new file instead of going through the partial invalidation from phpstan/phpstan-src#5933 and phpstan/phpstan-src#6086, so it costs one cold run per update. I have not measured a CI-shaped sequence, which is where that would hurt most.

    How many we can afford: those 6 files are 164.3 MB, reproduced to the byte across two runs, ranging from 3.3 to 52.2 MB. cache/ in the same directory, holding reflection data and compiled containers for the same projects, is 716 MB, and that one is already per-path (two byte-identical configs at two paths compile two containers; my shared temp dir holds 179 of them, all written the same day). The naming also costs nothing where it buys nothing: one project with its own tmpDir, warm, flag off against on, interleaved 5 rounds, medians 2.23s and 2.18s with fully overlapping ranges.

    When to delete: resultCacheSkipIfOlderThanDays gives that for free. restore() already refuses a cache whose last full analysis is older than the window (checked by rewriting lastFullAnalysisTime 8 days back), and mtime is touched on every save, so a file past the window would be refused anyway. The prototype deletes those on save and on clear-result-cache, with no new parameter. One hole I have not closed, by construction rather than by measurement: the prune applies the invoking project's window to every file in the directory, so a project at the default 7 would delete a neighbour's 10-day-old cache that the neighbour, configured at 30, would still have restored. Either prune only with the default window, or record the window somewhere.

    Two things a multi-file design has to fix besides the name, both of which bit the prototype:

    • ResultCacheClearer and result-cache-info read %resultCachePath% directly. Until they went through the same resolver, clear-result-cache printed "Result cache cleared" while deleting nothing and result-cache-info printed a path that did not exist. clear-result-cache also passes '0' as the level to CommandHelper::begin(), so even through the resolver it named a different file until I gave it -l. Anything that has to name the same cache file needs the same identity-determining inputs.
    • use a separate resultCache per project config file phpstan-src#1469 clears by globbing resultCache*.php in the directory, which in a shared temp dir deletes other projects' caches.

    Gate: self-analysis clean, 21295 tests green, 9 new resolver tests with each of the four invariants checked by breaking it, and the 44 unix result-cache e2e blocks replayed locally at the same 36 pass / 8 fail as 2.2.x under the same harness. The replay is what caught the one real bug: in result-cache-relative-path, the only fixture with ignoreErrors, restore() hashed the raw config while save() hashed the stripped one, so every run wrote a file the next run did not look for. That is unreachable rather than stale, and every unit test passed.

    Happy to push the branch if this is the direction, or to split it: the naming and the age rule are one concern, teaching the two commands about it is another, and the Composer package state is the third and the only one with a trade-off in it.

    Correction to my description above: phpstan/phpstan-src#1469's name is an md5 of analysedPaths and the PHPStan version, not bootstrapFiles. The point it was supporting holds and is measured now (two configs differing only in level land on one file and neither is ever warm), and its key hashes absolute analysedPaths, so a relocated copy misses the file it wrote, which is the case the relativization just made possible.

  3. SanderMuller commented on Sep 3, 2026

    @SanderMuller
    ContributorAuthor

    Four more measurements, and the first one amends what I wrote above.

    The trade I called "the one real trade" is removable

    I measured the CI-shaped sequence I said I hadn't: one 1960-file project with its own tmpDir, six steps of cold, code edit, dependency update, code edit, dependency update, code edit, where the update moves what composer update psr/log moves in the metadata. Two runs per arm:

    total CPU per dependency update
    today 70.0s / 74.2s 2.0 - 2.2s, Composer packages changed (psr/log); re-analysing only the files depending on them
    Composer state in the file name 199.7s / 196.8s 61.0 - 64.0s, fully cold
    Composer state in the name, with a read fallback 69.7s / 72.3s 2.1 - 2.2s

    So the switching sequence and the update sequence pull in opposite directions, and the fix is that the name does not have to be the only place a run looks. The file is resultCache-<identity>-<composer state>.php; a run whose own file does not exist reads the most recently written resultCache-<identity>-*.php and then writes under its own name. The metadata comparison in that sibling does its usual package-granular work, so an update is partial again, while two checkouts of one project still keep separate files and stay warm. The switching sequence keeps its numbers: 544 to 574s across three passes with 9 warm hits, against 1501s and 1578s with none at all today.

    One trap in case it saves you the same hour: extractComposerPackageVersions() reads reference first, so my first simulated update moved only pretty_version and version, and every run printed Composer metadata changed but no package versions changed. It measured nothing until the mutation moved the reference too.

    A hash in the file name cannot serve stale results

    Worth checking rather than asserting. Forcing 7 distinct identities into 2 cache files and comparing every run's error output against a per-project cold baseline gives 14 runs and 0 differences. Two independent gates make that hold, and it took two controls to see it: making isMetaDifferent() always return false broke nothing, because a project reading a foreign cache still re-analysed all 1960 of its own files, their hashes matching nothing in that cache. Only after also forcing filesToAnalyse: [] did the harness report staleness, 1 error against 4279 expected, which is what tells me the check has teeth rather than never looking. Same check on the fallback path: after each of the six CI steps I recomputed the tree state with a wiped cache and diffed, 441 errors, identical every step, including the two steps that read a sibling written under a different Composer state.

    How many files we can afford, and what the number buys

    The age rule alone does not bound the directory once every Composer state writes its own file, so I looked at how often that state moves: git log -- composer.lock in two real applications gives 560 changes in 12 months, about 11 a week, and 27. Lock commits are a proxy for local installs rather than a count of them, but at eleven a week a seven-day window would hold eleven files of one identity.

    So there is a cap on files per identity, and it is not a free parameter, it is how many checkouts of one project can be warm at once. Same 15-run switching sequence:

    cap total CPU warm hits the worktree alternation
    2 544 - 574s (3 passes) 9 2.5s, 2.6s
    1 1062.1s 6 157.8s, 158.1s, 173.6s, every visit full

    At 1 the two checkouts delete each other's file and the naming buys them nothing. For scale: on that shared directory the 6 cache files are 164.3 MB, and cache/ next to them, for the same projects, is 716 MB.

    A global or phar install gets half of it

    This is how most people run PHPStan, and it is the case where %rootDir% does not move with the project. Measured with the released 2.2.12 phar placed outside the projects, cwd in the project, one shared tmpDir, against the prototype in the same topology:

    2.2.12 phar prototype
    two unrelated projects, alternating 0 warm hits in 4 runs both warm, 0.4s and 0.9s after one cold run each
    the same project at a second path cold, 88.2s cold, 59.4s, and it gets its own file instead of evicting

    So the switching case works for a global install and the relocation case does not, because nothing relativizes against an anchor outside the project. Relocation sharing is a vendor-install property rather than a general one, which seems worth writing down since the phar is the common install.

    clear-result-cache now removes every Composer state of the invoking config's identity, since each one is a file the next run could read through the fallback, and nothing outside that identity: 3 files in a directory, two of this identity and one of another, one left afterwards.

    Gate: self-analysis clean, 21307 tests green, phpcs clean, 12 resolver tests with every invariant checked by breaking it, e2e replay 36 pass / 8 fail, the identical set to 2.2.x. Four commits, splittable as naming plus age rule, the two commands, the Composer state with its fallback, and the cap.

  4. staabm commented on Sep 3, 2026

    @staabm
    Contributor

    When/How will a outdated/old result-cache file be deleted when phpstan is no longer invoked for a codebase

  5. SanderMuller commented on Sep 3, 2026

    @SanderMuller
    ContributorAuthor

    Good question, and my first answer to it was wrong in a way worth writing down.

    The prune globs every resultCache-*-*.php in the directory rather than only the running project's, so an abandoned codebase's file is reclaimed by any other project's run once it is past resultCacheSkipIfOlderThanDays. Nobody has to go back to the abandoned project. Verified with two genuinely different codebases sharing one tmpDir: backdate the second one's file 8 days, run only the first, and the abandoned 24 MB file is gone. My first attempt at that proved nothing, because the two projects I used were copies of each other and shared an identity, so it only showed reclamation inside one identity.

    Checking it did find a real gap, now closed. The prune only ran when a run saved, and two shapes never save: --debug, and a run given individual file paths (Result cache was not saved because only files were passed as analysed paths). It now runs at the top of restore(), above both early returns, so every run reclaims regardless of what it then does with its own cache. Verified both ways: with the prune on save only, a --debug run left the expired file behind; with it in restore(), a --debug run and a file-path run each reclaim it. The file the run has just decided to read is excluded, so an expired own cache still reports Result cache not used because it's more than 7 days since last full analysis. rather than the less helpful "the cache file does not exist". Cost is one glob plus a filemtime per file, 0.142 ms over a 40-file directory.

    clear-result-cache sweeps the whole directory by age too, from whichever project you run it in: two files, one of them another project's and expired, none left afterwards.

    What stays true: if nothing ever runs in that directory again, nothing reclaims, and the files sit there until the OS cleans its temp directory. That is the same position as today's single resultCache.php, and better than the cache/ directory next to it, which has no age rule at all. Its key is path-dependent as well as config-dependent, so every copy or worktree of a project adds another compiled container: my machine's shared temp directory currently holds 1040 of them, 667 MB, every one written today. That is an unusually heavy day on my side, but nothing will ever delete them.

    If you would rather not rely on other projects running, the alternatives I can see are a hard cap on total bytes in the directory, or writing an index file so a run can reclaim without stat-ing everything. Neither seems worth it while the sibling cache in the same directory is unbounded, but I am happy to be told otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions