Skip to content

fix(try): a variable assigned on some paths of a finally block keeps that type after the try - #14416

Merged
orklah merged 5 commits into
vimeo:masterfrom
jirkace:fix/14188-finally-conditional-assignment
Nov 22, 2026
Merged

orklah merged 5 commits into
vimeo:masterfrom
jirkace:fix/14188-finally-conditional-assignment

Conversation

@jirkace

@jirkace jirkace commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

A variable assigned inside a condition, a loop or a nested try of a finally block keeps the type it had before the try, as if the assignment never ran.

Before

function f(): void {
    $t = null;
    try {
        g();
    } finally {
        if (rand(0, 1)) {
            $t = new Exception();
        }
    }
    /** @psalm-check-type-exact $t = Exception|null */; // CheckType: $t = null
}

After

    /** @psalm-check-type-exact $t = Exception|null */; // no issue

The same in a closure writing a variable captured by reference was reported as TypeDoesNotContainType after the call (#13809).

Fixes #14188
Fixes #13809

…that type after the try vimeo#14188

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@jirkace

jirkace commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • A variable assigned on some paths of a finally block only (inside an if, a loop, the catch of a nested try, also inside a closure that captures it by reference) has, after the try, the type the finally block leaves it with, instead of the type it had before the try; a variable first assigned there is possibly undefined instead of undefined. New TryCatchTest cases, which fail on master; the closure case is the snippet of Variable written by a closure through use (&$x) is assumed to keep its initial null #13809 (TypeDoesNotContainType on master).
  • TryAnalyzer also records what a catch that goes on assigns as possibly assigned after the try, which is what made the nested-try case visible to the enclosing finally.
  • Known imprecision, same as for unconditional assignments in finally already: the finally block starts from every state of the try and the catches, including a catch that returns, so the type after the try can contain a value only that catch assigned (2|5|null where 2|null would be exact). It is a wider type, not a missed one.
  • Benchmarks (local, psalm_full.xml, --threads=1, fresh master runs): laravel 28106 vs 28106, symfony 11820 vs 11820, no difference. Self-analysis: only the 2 PoolEventLoopDriverTest errors that master reports too here. The neighbouring finally cases of TryCatchTest ran alone and pass. Not run: the full suite (CI).

@github-actions

github-actions Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: decreased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 751 59.3 $\color{gray}{\textsf{+1.8\%}}$ 25 908 53 462 682
✅ symfony 3 600 216.9 $\color{gray}{\textsf{-0.2\%}}$ 50 610 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-1}}$ 98 401 $\color{green}{\textsf{-4}}$ 1 528
✅ doctrine-orm 381 21.4 $\color{gray}{\textsf{+1.3\%}}$ 3 481 6 143 0
✅ psl 617 26.9 $\color{gray}{\textsf{-0.2\%}}$ 1 375 5 615 1
✅ phpunit 455 19.5 $\color{gray}{\textsf{-1.0\%}}$ 1 731 3 410 18
✅ php-parser 226 13.3 17 132 21 025 0
✅ tempest 895 36.1 $\color{gray}{\textsf{-1.3\%}}$ 5 047 10 528 252
✅ amphp-amp 68 2.0 $\color{gray}{\textsf{-0.5\%}}$ 29 49 0
✅ webmozarts-assert 272 4.8 $\color{gray}{\textsf{+0.6\%}}$ 577 2 720 0
✅ guzzle-promises 44 1.6 $\color{gray}{\textsf{-0.6\%}}$ 155 434 2
✅ monolog 135 5.9 $\color{gray}{\textsf{+0.5\%}}$ 913 2 479 10
✅ drupal 4 841 236.6 $\color{gray}{\textsf{+1.1\%}}$ 97 591 169 293 583
Total 13 285 644.2 $\color{gray}{\textsf{+0.4\%}}$ 204 549 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-1}}$ 373 559 $\color{green}{\textsf{-4}}$ 3 076
How to read this table
  • Memory: Psalm's own peak figure, threads=1. More than +5 % fails, unless the PR changes composer.json.
  • Wall: base and head run on the same runner; ±10 % is noise. Above +20 % warns, never fails. re-run: a reversed second run was taken and the faster kept.
  • Issues: head count over all categories, then $\color{red}{\textsf{+added}}$ $\color{green}{\textsf{-removed}}$ against base.
  • Weighted (types): type issues weighted by error level (levels 1–8 as is, always-errors 10, strictness checks 1). Taint and dead-code issues are not weighed. The projects' own code is pinned and their dependencies resolve identically for base and head, so a change means Psalm reports more, fewer or differently serious issues. A rise is not necessarily a regression.
  • Taint: head count of Tainted* issues, then $\color{orange}{\textsf{+added}}$ $\color{orange}{\textsf{-removed}}$ against base. Both are orange as either direction needs review: more can be new detection or false positives, fewer can be fixed false positives or lost detection.
  • Dead code: head count of unused-code issues, shown only when a run reported some (findUnusedCode). More is red, fewer is green.
  • Total: sum over the projects compared on both sides. Thresholds apply per project, not to the total.
  • Colors: $\color{red}{\textsf{red}}$ past a fail or warn threshold (or more issues), $\color{green}{\textsf{green}}$ an improvement past noise (or fewer issues), $\color{orange}{\textsf{orange}}$ needs review, $\color{gray}{\textsf{gray}}$ noise.
  • Performance: regressed if a head run crashed or timed out or a memory or wall delta is red, else improved if one is green, else unchanged. Its icon is the check result: ❌ fail · ⚠️ warn · ✅ pass; the icon next to each project is that project's result, 💥 = not comparable: base crashed or timed out (counts as ⚠️).
  • Types (heading): direction of the total weighted change, increased · decreased · unchanged. Taint and Dead code (heading): added and removed counts, present only when non-zero. Informational, never fails the check.
✅ symfony: issues +0 −1

Memory 3 600 → 3 600 MB (<0.1 %) · Wall 217.4 → 216.9 s (−0.2 %)

Weighted 98 405 → 98 401 (−4, <0.01 %): L4 −1

Issue type added removed
TypeDoesNotContainType 0 1

Removed (1)

  • src/Symfony/Component/Runtime/Runner/FrankenPhpWorkerRunner.php:87 TypeDoesNotContainType (error): Type null for $terminationException is always null, so its negation can never be true

head 18f54a5 · base 7bfe967 (merge-base) · workflow run

…keeps it possibly undefined vimeo#14188

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change (update, from the Bugbot finding)

  • A variable that the try leaves possibly undefined (assigned in the try, with a catch that goes on without it) and that the finally block assigns on some paths only stays possibly undefined after the try; only an assignment on every path of the finally block defines it. The previous head of this PR cleared it (a false negative); the new TryCatchTest case variablePossiblyUndefinedAfterACatchStaysSoWhenTheFinallyAssignsItOnSomePaths fails on that head and passes now (master reports it too).
  • Self-analysis: only the 2 PoolEventLoopDriverTest errors; the finally cases of TryCatchTest ran alone and pass. Not run: the full suite (CI).

@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit fb67a99. Configure here.

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this fixes both issues. One problem with the type the post-try scope gets for a variable the finally block assigns on some paths only: it is the finally block's end type, which starts from finally_scope, i.e. it includes the state before the try (and every return/throw state). The code after the try is only reached from the normal end of the try or of a continuing catch, so the pre-try type leaks and creates new false positives:

function g(): void {}

function f(): int {
    $t = null;
    try {
        $t = 1;
        g();
    } finally {
        if (rand(0, 1)) {
            $t = 2;
        }
    }
    /** @psalm-check-type-exact $t = 1|2 */; // head: 1|2|null
    return $t; // head: NullableReturnStatement
}

Same with a catch ($s = 'a' in the try, 'b' in the catch, 'c' conditionally in the finally: head gives 'a'|'b'|'c'|null) and with a return null inside the try (head: 0|1|2|null, PossiblyNullOperand).

For these variables the type after the try should be what the finally block leaves when it starts from the post-try state ($context after the catches), not from finally_scope. Could you fix that and add the case above as a valid-code test (it should fail on the current head)?

Optional: a conditional unset($t) in the finally is now reported as PossiblyUndefinedVariable after the try (master reports nothing); a test for it would pin that too.

jirkace and others added 2 commits November 21, 2026 16:53
…type of the post-try state

The finally block is analysed once more, silently, from the state after the try and the
catches that go on, and the variables it assigns on some paths only take the type that
analysis ends with: the end of the first one starts from every state, the state before
the try included.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@jirkace

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 8294f4e. For a variable the finally block assigns on some paths only, the type after the try is now what the block leaves when it starts from the post-try state ($context after the catches that go on): the block is analysed once more with its issues recorded and dropped, only when such a variable exists. variableAssignedInAConditionOfAFinallyBlockDoesNotKeepTheTypeBeforeTheTry is your f() (1|2, was 1|2|null), ...AfterACatchHasTheTypesOfTheTryAndTheCatch the catch variant ('a'|'b'|'c') and ...WithAReturnInTheTryHasNoNull the return in the try (1|2, was 0|1|2); all three fail on the previous head. variableUnsetInAConditionOfAFinallyBlockIsPossiblyUndefinedAfterTheTry pins the optional unset case (PossiblyUndefinedVariable). @orklah

…ollected without array_diff_key()

Psalm's own analysis took the property it was assigned [] before the analysis for a never-array.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@orklah orklah added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 22, 2026

@orklah orklah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jirkace!

@orklah
orklah merged commit 1e26c4d into vimeo:master Nov 22, 2026
71 of 72 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release:fix The PR will be included in 'Fixes' section of the release notes

Projects

None yet

2 participants