Skip to content

Relative path in ResultCache #8599

Closed
phpstan/phpstan-src
#6190

Description

@aalbarca

Feature request

In some cases (e.g. gitlab with runners) the relative path of the files to be analysed is the same but the absolute path changes and this causes the cache to be invalid. Would it be possible to add an option to take only the relative path into consideration? Maybe it can be a global solution without the need to create new command line option.

See #8576 (reply in thread)

Did PHPStan help you today? Did it make you happy in any way?

We used it in an team with more than 20 developers and it has allowed us to find dozens of problems that would be causing problems in production. Greetings from Spain!

Activity

  1. ondrejmirtes commented on Jan 4, 2023

    @ondrejmirtes
    Member

    We used it in an team with more than 20 developers...

    Awesome, that's great to hear! Please consider sponsoring PHPStan's development. The options are:

    Thank you for considering.

  2. zer0uno commented on Feb 2, 2023

    @zer0uno

    I add the same problem, this feature would be very helpful

  3. zer0uno commented on Feb 27, 2023

    @zer0uno

    Hi @ondrejmirtes is there any estimate for this bug resolution? Thank you

  4. jdreesen commented on May 12, 2023

    @jdreesen

    We're also using GitLab, and it would be great to be able to use the cache.

  5. TwanVermeulen commented on Sep 4, 2023

    @TwanVermeulen

    We could really use this feature as well

  6. SonOfHarris commented on Mar 13, 2024

    @SonOfHarris

    +1 for this feature please. We are using GitLab as well and when the cache can not be used it increases the runtime by around 10-15 minutes.

  7. thomas-0816 commented on Apr 16, 2024

    @thomas-0816

    GitLab pipelines creates a new directory on every run, e.g. /builds/6637522964/phpstan.neon, /builds/6637426831/phpstan.neon, etc.
    That way even valid caches seems to be treated as invalid.

    I'm currently using bind mounts in gitlab pipelines to normalize the paths. But yes, support for relative paths in ResultCache would be very good!

    mkdir /tmp/testing/
    mount --bind $(pwd) /tmp/testing
    cd /tmp/testing
    phpstan ...
    
  8. ZZromanZZ commented on Jun 18, 2024

    @ZZromanZZ

    I run today to this very same issue on Azure Pipeline

  9. janedbal commented on May 12, 2025

    @janedbal
    Contributor

    We are successfully reusing CI result cache locally with few tweaks:

    • simple str_replace('/ci/path/to/project', '/local/docker/path', file_get_contents('resultCache.php')) upon reuse
    • symfony extension adjustments:
      • custom ParameterMapFactory that also changes paths like above (e.g. kernel.project_dir)
      • custom ServiceMapFactory that removes 2 randomly named services (1_ServiceLocator... and 1_Serializer...)
  10. SanderMuller commented on Jul 27, 2026

    @SanderMuller
    Contributor

    This keeps coming up (GitLab, Azure, the reactions above), and @janedbal's workaround is a good map of what actually breaks. Reviving it with the mechanism and a few concrete directions, so we can agree on an approach before anyone writes code.

    Why the cache is not portable today

    Two independent layers, and both have to be handled or nothing changes:

    1. The cache meta is compared as a whole with a strict !==, and it embeds absolute analysedPaths plus the absolute paths that expandRelativePaths bakes into the stored projectConfig (the configured paths, excludePaths, and so on). A fresh CI checkout path makes the meta differ, so the entire cache is discarded before any per-file logic runs (ResultCacheManager::getMeta() / isMetaDifferent()).
    2. Every stored entry (the dependency graph, errors, exported nodes, per-file data) is keyed by absolute path. On restore, matching is array_key_exists($absolutePath, ...), so with a new prefix every file looks new and nothing is reused.

    There is a third layer outside core: ResultCacheMetaExtension hashes are opaque strings that PHPStan stores verbatim, so an extension's hash can carry an absolute path. Per @janedbal's workaround above, the Symfony container extension is one such case (its kernel.project_dir). Core path normalization will not touch that, so those extensions need a matching change.

    The correctness constraint

    Making paths relative naively is not safe. Two genuinely different files can share the same relative path across environments (monorepo or symlink layouts, a file outside the project root, or a vendored src/Foo.php versus the project's own). Collapse them onto one key and you get a false cache hit, which for a static analyser is a wrong result, not just a slow run. Some tracked files also cannot be relativized to the project root at all: vendor/composer files, stub files, bootstrap and autoload files, and phar-internal files. Whatever we do has to keep a correct identity for those.

    The useful precedent is ccache's CCACHE_BASEDIR: rewrite an absolute path to relative only when it lives under a chosen base directory, and leave everything else absolute. That is exactly the inside-vs-outside-project split we need, and it is a proven design. https://ccache.dev/manual/latest.html

    PHPStan already has most of the machinery

    • The baseline feature already stores paths relative to the baseline file and re-absolutizes them on load (ParentDirectoryRelativePathHelper plus the expandRelativePaths step). That "store relative, resolve on load" round-trip is the model to copy.
    • RelativePathHelper (FuzzyRelativePathHelper) already computes a base as the common prefix of the working directory and the analysed paths, with a fallback for files outside it.
    • expandRelativePaths already turns config-relative paths into absolute at load. The reverse direction is the missing piece.

    Options, for discussion rather than a decision

    Option A, rewrite on load (smallest change). Keep storing absolute paths, record the base dir in the cache, and translate the old base to the new base across the meta and the keys on restore, before the comparison and the lookups. This is @janedbal's str_replace, done properly and inside PHPStan.

    • Pros: minimal, the cache format barely changes; the translation is a one-to-one mapping so it cannot alias distinct files; paths outside the base simply do not translate and stay a real difference, which is safe.
    • Cons: needs the save-time base captured reliably; awkward when there is more than one root; does not touch the extension-hash layer.

    Option B, store relative and re-absolutize on load (the fuller fix, mirrors baselines and ccache). Rewrite paths under the base dir to base-relative at save, leave outside-base paths absolute, and resolve them back on load. Applies to the meta and to all per-file storage.

    • Pros: portable by construction; reuses the baseline round-trip and the ccache "only under base" rule, which keeps correctness for vendor/stub/bootstrap files; no translation guesswork.
    • Cons: the largest change; every path-bearing field has to be transformed consistently or you get partial invalidation; needs a reverse resolver; a one-time cache invalidation via a CACHE_VERSION bump.

    Base dir selection (a sub-decision that both A and B need). Candidates: the working directory, the common prefix PHPStan already computes for relative paths, %rootDir%, or an explicit parameter. And: on by default (what the people here want, it should just work) or opt-in (safer for backward compatibility). The original request asked for "maybe a global solution without a new CLI option," which points at a sensible default rather than a flag.

    Option C, an extension-hash contract (needed for Symfony users regardless of A or B). Give ResultCacheMetaExtension a way to emit a portable hash, for example by handing it the base dir, so kernel.project_dir stops leaking an absolute path into the meta.

    • Pros: closes the third layer, which Symfony projects hit (see @janedbal's note above).
    • Cons: touches the extension API and needs coordination with phpstan-symfony.

    One thing that already works today, as a stopgap while this is designed: the bind-mount trick from the comments (mount the CI directory at a fixed path) makes the cache reusable with no code change.

    If a starting position helps: I lean toward Option B with the ccache "only under base" rule as the destination, and Option A as an incremental first step if a quick win is useful before committing to the storage change. Happy to be argued out of it.

    What is worth settling before code

    1. Base dir: default-on with a computed base, or an explicit opt-in parameter?
    2. Adopt the ccache "only rewrite under the base" rule, so out-of-root files keep absolute identity and cross-context false hits are prevented?
    3. Incremental (A first, then B), or straight to relative storage (B)?
    4. Change the ResultCacheMetaExtension contract now (C), or land core first and follow up?
    5. Anything beyond a one-time CACHE_VERSION bump that counts as a backward-compatibility break?

    Does one of these directions match what you had in mind? For anyone here who hits this on GitLab or Azure, feedback on the base-dir default and the correctness angle is especially useful.

  11. staabm commented on Jul 27, 2026

    @staabm
    Contributor

    I do not have a concrete opinion on the way how it could be solved.

    maybe we should even let AI build both approaches in separate PRs and compare them than

  12. ondrejmirtes commented on Jul 27, 2026

    @ondrejmirtes
    Member

    It's a question of what the paths should be relative to. We're able to rewrite all paths to relative (see the baseline mention). Should the paths be related to the used config file path? Config file is not required, only when a level is specified. This means that simple phpstan analyse calls with default level 0 would not be saved in the result cache? It currently is.

    I don't like the CWD proposal. PHPStan is not sensitive to the current working directory, except for maybe influencing the contents $composerAutoloaderProjectPaths in bin/phpstan, which a lot of things are derived from. Worth a side quest - should result cache be invalidated when the contents of this array changes? I suspect that even when we're in a different directory and run PHPStan on a project that uses Composer, the project's directory might end up in this array, because bin/phpstan will discover that from being in vendor/phpstan/phpstan.

    Why is still both composerLocks and composerInstalled part of getMeta in ResultCacheManager? I'd expect composerInstalled only since phpstan/phpstan-src#6086.

    The big challenge is to recognize and relativize all paths referenced in the result cache, and making them absolute for the rest of the codebase (relativize them when they enter result cache, absolutize them when they leave the result cache). There's a lot of them.

  13. SanderMuller commented on Jul 27, 2026

    @SanderMuller
    Contributor

    On composerLocks vs composerInstalled: you're right that composerInstalled is the one that matters. PackageDependencyResolver::getChangedComposerPackages() reads only composerInstalled and never composerLocks, and since phpstan/phpstan-src#6086 a composer-only meta diff is routed there (the array_diff($diffs, ['composerLocks', 'composerInstalled']) === [] gate), so a composer.lock-only change already resolves to "no packages changed" and keeps the cache. composerLocks in getMeta is now just a redundant trigger; dropping it is behaviour-preserving (a lock-only churn would then produce no meta diff at all, so the cache is used without even calling the resolver). I can send that as a small cleanup if useful.

    On what the paths are relative to: agreed the config file path doesn't work, since configless default-level runs have no config yet are cached today. The always-available anchor is the project root(s) in $composerAutoloaderProjectPaths. To your CWD point, FuzzyRelativePathHelper seeds its common-prefix base with the working directory (so it carries some CWD sensitivity), whereas $composerAutoloaderProjectPaths comes from Composer's autoloader discovery rather than getcwd(), so it stays stable across a cd and keeps configless runs cacheable. That also answers your side quest: basing relativization on those paths makes a change in them a deliberate re-base rather than silent staleness.

  14. ondrejmirtes commented on Jul 27, 2026

    @ondrejmirtes
    Member

    What about projects that don't use Composer? You can just download phpstan.phar and run it on whatever, no Composer in sight.

    Anyway, I'd like a PR on the composerLocks sidequest.

  15. 2 remaining items

  16. ondrejmirtes commented on Jul 28, 2026

    @ondrejmirtes
    Member

    PHPStan needs to be aware of being in a worktree if: the project uses a non-default relative tmpDir and the result cache does not exist in the expected place. Then we need to reach into the main checkout and get that warmed up result cache.

    Please also note that (I don’t know if it has an iisue or not, @staabm might be able to find it) we have an ongoing problem of result caches being rewritten. If multiple projects have a default system tmpDir, there can only ever be one result cache, meaning there are more cold runs than would be neccesary.

    We could keep multiple result caches, even in one project if we account for branches/worktrees, the question is by what keys and how long to keep them.

    Maybe it’s not so close to the relative paths problem but it’s adjacent.

  17. SanderMuller commented on Jul 28, 2026

    @SanderMuller
    Contributor

    A datapoint for the worktree case: Polyscope CoW-clones a repo per agent session (macOS clonefile), gitignored files included, so with tmpDir: .cache/phpstan each clone starts with a warm 47 MB resultCache.php, same md5 as the origin's. PHPStan discards it entirely: the ~140k paths inside still point at the original checkout. Same bug as a worktree, minus the "cache isn't there" half, so it isolates the prefix as the only cause.

    It also makes worktree detection a dead end. A CoW clone has its own .git with no link back, same as cp -r, rsync, or a bind mount.

    Two things I found tracing it:

    • composerInstalled leaks absolute paths through its values: getComposerInstalled() does $data[$filePath] = require $filePath, and composer's installed.php resolves 'install_path' => __DIR__ . '/…' at require time. 326 of them in my cache. That breaks worktrees too, after composer install, independently of analysedPaths.
    • tmpDir sits in the stored projectConfig as an absolute path and isn't in parametersNotInvalidatingCache. Adding [parameters, tmpDir] is a cheap independent win; can go with the composerLocks PR.
  18. staabm commented on Jul 28, 2026

    @staabm
    Contributor

    maybe we can infer the "project" root from composer/installed.phps install_path ?

    Image
  19. SanderMuller commented on Jul 28, 2026

    @SanderMuller
    Contributor

    Correction to my earlier comment: I claimed $composerAutoloaderProjectPaths comes from autoloader discovery rather than getcwd() and is stable across a cd. That's wrong. bin/phpstan does $cwd = getcwd(), then ComposerHelper::getComposerJsonPath($cwd), and pushes dirname($composerJsonPath) as the first entry. Only the second entry, dirname($path, 2) from phpstan's own install location, is CWD-independent. @ondrejmirtes was right to be wary of CWD here.

    Which makes @staabm's suggestion the better anchor, because it sidesteps that. The root entry in installed.php is 'install_path' => __DIR__ . '/../../', resolved at require time, so it re-anchors to wherever vendor/ physically sits regardless of how you got there. I checked my CoW clone: it resolves to the clone, not the origin. That covers /builds/<id>, Azure, a worktree after composer install, and the clone case.

    Where it runs out:

    • No Composer, which is your phpstan.phar on an arbitrary directory case. No installed.php, no anchor, so there needs to be a fallback.
    • If the working directory has no vendor/autoload.php, the surviving entry is phpstan's own install directory, so the anchor points at phpstan rather than the analysed code. With a ccache-style "only rewrite under the base" rule that degrades to nothing relativizing rather than a false hit, so it's safe but useless.
    • Monorepos put two entries in that array and would need longest-prefix matching against several bases.
    • Stubs, path-repository packages installed as ../sibling, and paths: entries outside the root stay absolute by design and keep invalidating.

    It also leaves the other two layers untouched: finding the cache at all in a fresh worktree with a relative tmpDir, and the ResultCacheMetaExtension hashes, which is what bites @janedbal via kernel.project_dir.

  20. ondrejmirtes commented on Jul 28, 2026

    @ondrejmirtes
    Member

    BTW using phpstan.neon as the anchor is also problematic because soe people use a single phpstan.neon to analyse different projects.

  21. ondrejmirtes commented on Aug 5, 2026

    @ondrejmirtes
    Member

    I think I finally cracked it. The best anchor for relative paths is phpstan.phar location. It always works and it also solves worktrees out of the box.

    For phpstan-src development we can fall back to bin/phpstan location for example.

  22. SanderMuller commented on Aug 5, 2026

    @SanderMuller
    Contributor

    Nice, that's cleaner than the installed.php route and needs no Composer. bin/phpstan already derives the project root from the phar this exact way (dirname(Phar::running(false), 4), with === '' as the dev fallback), so it reuses an anchor that's already trusted rather than a new guess.

    One thing to keep the base rule correct: the source sits above the phar (../../../src), so "only rewrite under base" has to key off that derived root, not the phar's own dir. Paths outside the root (monorepo siblings, external paths:, global stubs) stay absolute.

  23. staabm commented on Aug 6, 2026

    @staabm
    Contributor

    @SanderMuller please open a PR so we can iterate on the idea

  24. ondrejmirtes commented on Aug 6, 2026

    @ondrejmirtes
    Member

    I think the objects that contain absolute paths like Error need some API (methods) to absolutize/relativize the paths.

  25. staabm commented on Aug 10, 2026

    @staabm
    Contributor

    Hey everyone,

    Please try downloading phpstan.phar from the "Compile PHAR " workflows build artifacts in phpstan/phpstan-src#6190 and give it a shot.

    When all goes according to plan it should be able to give you a working result cache based on relative paths.

    Please report back

  26. SanderMuller commented on Aug 10, 2026

    @SanderMuller
    Contributor

    Heads-up before anyone spends time on this: the phar currently built for phpstan/phpstan-src#6190 does not reuse the result cache at all, so it will look as if the feature changes nothing. It is a phar:// path-handling bug inside the PR rather than anything about your project or setup.

    Details, a minimal reproduction and the root cause are on phpstan/phpstan-src#6190. Worth waiting for a fixed build before testing.

  27. SanderMuller commented on Aug 19, 2026

    @SanderMuller
    Contributor

    Ready to test now. Both problems are fixed: the phar not reusing the result cache at all, and the absolute paths inside collected data that @ondrejmirtes found. The second fix landed this morning, so grab a fresh build:

    gh run download -R phpstan/phpstan-src -n phar-file \
      $(gh run list -R phpstan/phpstan-src -b relative-path-result-cache -w "Compile PHAR" -L 1 --json databaseId -q '.[0].databaseId')
    

    (or phpstan/phpstan-src#6190 → Checks → Compile PHAR → Artifacts → phar-file; needs a GitHub login)

    What to check, all with -vvv:

    1. Run twice in the same place - the second run should say Result cache restored.
    2. Then reuse a cache produced at a different absolute path: another CI checkout directory, another machine, a different container mount. Locally: cp -R project project-copy (a real copy, not a symlink) and run in the copy. It should restore instead of saying Result cache not used because the metadata do not match: ....
    3. The cache file should contain no absolute paths: grep -c "$(pwd)" <tmpDir>/resultCache.php → 0.

    One thing to know: paths are relative to PHPStan's install location, so the project and PHPStan have to travel together - the usual vendor/bin/phpstan layout does. If you keep the phar outside the project and move only the project, the cache is discarded, which is correct.

    Please report on phpstan/phpstan-src#6190 with the -vvv line, and if it did not restore, the metadata keys it named.

  28. github-actions commented on Sep 23, 2026

    @github-actions

    This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

  29. locked as resolved and limited conversation to collaborators on Sep 23, 2026
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