Skip to content

fix(templates): a template of numeric can be identical to a string - #14430

Merged
orklah merged 4 commits into
vimeo:masterfrom
jirkace:fix/14054-template-numeric-identical-string
Nov 22, 2026
Merged

orklah merged 4 commits into
vimeo:masterfrom
jirkace:fix/14054-template-numeric-identical-string

Conversation

@jirkace

@jirkace jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

A template bounded by numeric compared with === to a string is reported as a contradiction and narrowed to never, although a numeric string is both.

Before

/**
 * @template T of numeric
 * @param T $t
 */
function f($t, string $s): void {
    if ($t === $s) { // DocblockTypeContradiction, TypeDoesNotContainType
        takesNumericString($t);
    }
}

After

    if ($t === $s) { // no issue, $t: T as numeric-string

Fixes #14054

…meo#14054

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • A template compared with === to a type its bound overlaps (T of numeric and string, T of array-key and string) is no longer a contradiction: AtomicTypeComparator::canBeIdentical() compares the other type with the atomics of the bound, the template is narrowed to its bound intersected with the other type (T as numeric-string, SimpleAssertionReconciler::reconcileString() now keeps a template bounded by numeric/array-key), and the other side keeps the overlap (AssertionReconciler). New FunctionTemplateTest case, which fails on master.
  • Unchanged, covered by a test: a bound with no overlap (T of int against string) is still DocblockTypeContradiction. The Identical/Contradiction cases of FunctionTemplateTest, ClassTemplateTest, RedundantConditionTest, TypeAlgebraTest and ValueTest ran alone and pass.
  • Self-analysis: only the 2 PoolEventLoopDriverTest errors that master reports too here. Corpus benchmarks: in a follow-up comment. Not run: the full suite (CI).

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: unchanged

Project Memory (MB) Wall (s) Issues Weighted (types) Taint
✅ laravel 1 751 75.8 $\color{gray}{\textsf{+0.3\%}}$ 25 908 53 462 682
✅ symfony 3 600 257.8 $\color{gray}{\textsf{+1.1\%}}$ 50 611 98 405 1 528
✅ doctrine-orm 381 21.5 $\color{gray}{\textsf{+0.9\%}}$ 3 481 6 143 0
✅ psl 617 26.9 $\color{gray}{\textsf{+0.3\%}}$ 1 375 5 615 1
✅ phpunit 455 14.1 1 731 3 410 18
✅ php-parser 226 9.3 $\color{gray}{\textsf{+0.7\%}}$ 17 132 21 025 0
✅ tempest 895 27.5 $\color{gray}{\textsf{+2.0\%}}$ 5 047 10 528 252
✅ amphp-amp 68 1.5 $\color{gray}{\textsf{-3.2\%}}$ 29 49 0
✅ webmozarts-assert 272 3.4 $\color{gray}{\textsf{-2.0\%}}$ 577 2 720 0
✅ guzzle-promises 44 1.2 $\color{gray}{\textsf{-0.8\%}}$ 155 434 2
✅ monolog 135 4.2 $\color{gray}{\textsf{+1.4\%}}$ 913 2 479 10
✅ drupal 4 841 157.8 $\color{gray}{\textsf{-6.4\%}}$ 97 591 169 293 583
Total 13 285 600.9 $\color{gray}{\textsf{-1.1\%}}$ 204 550 373 563 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.

head 25d147f · base c5f4dfd (merge-base) · workflow run

…eeps both branches vimeo#14054

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Corpus check (laravel and symfony sources, this branch vs origin/master 908f6e1)

  • symfony: no difference (11820 issues on both).
  • laravel: 28106 → 28104. The issue kinds at Illuminate/Http/Client/PendingRequest.php stay the same, but the inferred type in the InvalidReturnStatement messages changes from LazyPromise to LazyPromise|Response: $this->send() returns (TAsync is false ? Response : LazyPromise) with the class template TAsync of bool unresolved, and master picked only the else branch. Added the test conditionalOnAnUnresolvedBoolClassTemplateKeepsBothBranches (f26d516) for it: master reports DocblockTypeContradiction: docblock-defined type Lazy does not contain Response on $r instanceof Response, the branch reports nothing.
  • laravel also loses one RedundantCondition at Illuminate/Database/Query/Builder.php:4299; the same line disappears in the corpus run of the unrelated fix(reconciler): a loose comparison with a string keeps the scalars it can be equal to #14429, so I don't attribute it to this PR.

Not run: the full PHPUnit suite (CI runs it).

@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 for this. The goal is right, but the new branch in AssertionReconciler::refine() loses precision on the other side of ===.

The intersection replaces the existing atomic, and then count($acceptable_atomic_types) === count($existing_var_type->getAtomicTypes()) still holds, so $existing_var_type is returned unnarrowed. Before this PR the list was empty and the later code narrowed it:

/** @param positive-int $i */
function takesPositiveInt(int $i): void {}
/** @param list<string> $l */
function takesListOfStrings(array $l): void {}
/** @param numeric-string $s */
function takesNumericString(string $s): void {}

/**
 * @template T of positive-int
 * @param T $t
 */
function e1($t, int $i): void {
    if ($i === $t) {
        takesPositiveInt($i); // master: no issue; this PR: ArgumentTypeCoercion (T as int)
    }
}

/**
 * @template T of list<string>
 * @param T $t
 */
function e2($t, array $a): void {
    if ($a === $t) {
        takesListOfStrings($a); // master: no issue; this PR: ArgumentTypeCoercion (T as array<array-key, mixed>)
    }
}

/**
 * @template T of numeric
 * @param T $t
 */
function e3($t, string $s): void {
    if ($t === $s) {
        takesNumericString($s); // this PR: ArgumentTypeCoercion ($s: T as string)
    }
}

Tracking the replacement fixes all three (int<1, max>, list<string>, numeric-string, and int|numeric-string for an int|string operand), and your two test cases still pass:

             $acceptable_atomic_types = [];
+            $narrowed = false;
...
+                    $narrowed = true;
                     foreach ($overlap->getAtomicTypes() as $overlap_atomic_type) {
...
-                    count($acceptable_atomic_types) === count($existing_var_type->getAtomicTypes())
+                    !$narrowed && count($acceptable_atomic_types) === count($existing_var_type->getAtomicTypes())

Could you add e1, e2 and e3 as valid-code cases, plus one for is_string($t) on a T of numeric (the reconcileString() change is only covered through === for now)?

jirkace and others added 2 commits November 21, 2026 16:48
…ps instead of keeping the type

refine() tracks that the overlap replaced the existing atomic, so the unchanged type is
not returned just because the number of atomics is the same.

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 25d147f. refine() tracks that the overlap replaced the atomic ($narrowed), as in your diff. templateBoundIsNarrowedByAnIdenticalValueOfTheOtherSide has e1, e2 and e3 plus e4 (is_string($t) on T of numeric, then takesNumericString($t)); it fails on the previous head. @orklah

@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 ca669d6 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

Development

Successfully merging this pull request may close these issues.

False DocblockTypeContradiction on === between a template bounded by numeric and string

2 participants