Skip to content

fix(reconcile): keep what is known about an indexed value when the index is narrowed - #13344

Merged
orklah merged 6 commits into
vimeo:masterfrom
jirkace:fix/keep-index-dependents-on-refinement
Nov 23, 2026
Merged

orklah merged 6 commits into
vimeo:masterfrom
jirkace:fix/keep-index-dependents-on-refinement

Conversation

@jirkace

@jirkace jirkace commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Psalm forgets that $arr[$key] is set when $key is narrowed inside if (isset($arr[$key])).

Before

<?php
/** @param array<string, string> $arr */
function takesArray(array $arr, string $key): void {
    if (isset($arr[$key])) {
        if ("foo" === $key) {
            echo $arr[$key]; // PossiblyUndefinedStringArrayOffset
        } elseif ("bar" === $key) {
            echo $arr[$key]; // PossiblyUndefinedStringArrayOffset
        } else {
            echo $arr[$key];
        }
    }
}

After

            echo $arr[$key]; // no issue

Fixes #7221
Fixes #7656

@jirkace

jirkace commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • After isset($arr[$key]), narrowing $key itself (if ("foo" === $key), elseif, else, instanceof, type checks) no longer drops what is known about $arr[$key]. Narrowing does not change the value of an index, so the remembered fact stays valid. Facts about variables that start with the narrowed variable ($o->i after $o instanceof A, $o['x']) are still dropped as before (PropertyTypeTest case dontMemoizePropertyTypeAfterRootVarAssertion passes); assigning to the index variable still drops them too (new test testEnsureArrayOffsetsExistAfterAssigningTheIssetKey, which passes on master as well).
  • The rule lives in Reconciler::dependsOnNarrowedVar() and is used by Reconciler and the three places in IfAnalyzer, ElseIfAnalyzer and ElseAnalyzer that removed the same dependent keys.
  • The @psalm-suppress PossiblyUndefinedStringArrayOffset for PossiblyUndefined*ArrayOffset with refined key #7656 in Config::getReportingLevelForFunction() became unused (self-analysis reported it) and is removed; PossiblyUndefined*ArrayOffset with refined key #7656 is the same bug.
  • Verified: the two new ArrayAccessTest cases that expect no issue fail on master (PossiblyUndefinedStringArrayOffset / PossiblyUndefinedArrayOffset) and pass on the branch; IssetTest cases arrayAccessAfterOneIsset, arrayAccessAfterTwoIssets, noRedundantConditionAfterIsset, mixedArrayIssetGetStringVar pass; phpcs and full self-analysis are clean.
  • Not fixed: with a literal key narrowed from a loop (foreach (["foo", "bar"] as $key)), $in["foo"] (the literal) is still reported inside if ("foo" === $key), as the maintainer expected in the issue; only $in[$key] is kept.
  • Not run: the full PHPUnit suite and Infection.

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: decreased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint Dead code
✅ laravel 1 772 74.5 $\color{gray}{\textsf{+0.5\%}}$ 25 787 53 067 743 0
✅ symfony 3 619 287.1 $\color{gray}{\textsf{+7.0\%}}$ 51 739 $\color{red}{\textsf{+1}}$ $\color{green}{\textsf{-1}}$ 100 455 1 582 0
✅ doctrine-orm 381 24.4 $\color{gray}{\textsf{+0.3\%}}$ 3 453 6 194 0 0
✅ psl 618 28.3 $\color{gray}{\textsf{+0.9\%}}$ 1 387 5 600 1 0
✅ phpunit 456 21.4 $\color{gray}{\textsf{-0.7\%}}$ 1 735 3 418 18 0
✅ php-parser 226 14.4 $\color{gray}{\textsf{+0.6\%}}$ 17 113 21 177 0 0
✅ tempest 898 38.6 $\color{gray}{\textsf{-0.8\%}}$ 5 091 10 536 275 0
✅ amphp-amp 48 1.0 29 49 0 0
✅ webmozarts-assert 274 2.9 $\color{gray}{\textsf{+1.4\%}}$ 575 2 714 0 0
✅ guzzle-promises 46 1.2 $\color{gray}{\textsf{+7.4\%}}$ 155 433 2 0
✅ monolog 136 4.1 $\color{gray}{\textsf{+0.7\%}}$ 918 2 491 11 0
✅ drupal 4 847 256.4 $\color{gray}{\textsf{+3.8\%}}$ 97 847 $\color{gray}{\textsf{+0}}$ $\color{green}{\textsf{-25}}$ 169 346 $\color{green}{\textsf{-47}}$ 575 0
✅ wordpress 2 060 175.2 $\color{gray}{\textsf{+0.5\%}}$ 143 504 $\color{red}{\textsf{+3}}$ $\color{green}{\textsf{-126}}$ 678 371 $\color{green}{\textsf{-119}}$ 505 1
Total 15 381 929.4 $\color{gray}{\textsf{+3.3\%}}$ 349 333 $\color{red}{\textsf{+4}}$ $\color{green}{\textsf{-152}}$ 1 053 851 $\color{green}{\textsf{-166}}$ 3 712 1
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 +10 % 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. Its wall time warns above +5 % (±5 % is noise); the other thresholds apply per project.
  • 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 +1 −1

Memory 3 619 → 3 619 MB (<0.1 %) · Wall 268.2 → 287.1 s (+7.0 %)

Issue type added removed
MixedArgument 1 1

Changed in place (1)

@​@​ src/Symfony/Component/JsonSchema/Schema.php:182 MixedArgument @​@​
- Argument 2 of array_key_exists cannot be mixed, expecting array<array-key, mixed>
+ Argument 2 of array_key_exists cannot be array<array-key, array<array-key, mixed>|mixed>|mixed, expecting array<array-key, mixed>
✅ drupal: issues +0 −25

Memory 4 847 → 4 847 MB (<0.1 %) · Wall 247.1 → 256.4 s (+3.8 %)

Weighted 169 393 → 169 346 (−47, −0.03 %): L1 −14 · L3 −11

Issue type added removed
MixedArrayAccess 0 1
MixedArrayAssignment 0 10
MixedArrayOffset 0 2
PossiblyNullOperand 0 1
PossiblyNullReference 0 1
PossiblyUndefinedVariable 0 10

Removed (25)

  • core/lib/Drupal/Core/Pager/PagerPreprocess.php:142 MixedArrayOffset (error): Cannot access value on variable $items['pages'] using mixed offset
  • core/lib/Drupal/Core/Render/Renderer.php:601 PossiblyNullOperand (error): Right operand cannot be nullable, got float|null
  • core/lib/Drupal/Core/Render/Renderer.php:601 PossiblyUndefinedVariable (error): Possibly undefined variable $render_start, first seen on line 279
  • core/modules/ckeditor5/src/HTMLRestrictions.php:789 MixedArrayAssignment (error): Cannot access array value on mixed variable $intersection[$tag][$attr]
  • core/modules/ckeditor5/src/HTMLRestrictions.php:794 MixedArrayAssignment (error): Cannot access array value on mixed variable $intersection[$tag][$attr]
  • core/modules/ckeditor5/src/HTMLRestrictions.php:799 MixedArrayAssignment (error): Cannot access array value on mixed variable $intersection[$tag][$attr]
  • core/modules/ckeditor5/src/HTMLRestrictions.php:809 MixedArrayAssignment (error): Cannot access array value on mixed variable $intersection[$tag][$attr]
  • core/modules/ckeditor5/src/HTMLRestrictions.php:814 MixedArrayAssignment (error): Cannot access array value on mixed variable $intersection[$tag][$attr]
  • core/modules/config/src/Form/ConfigSync.php:158 MixedArrayAssignment (error): Cannot access array value on mixed variable $form[$collection][$config_change_type]['heading']['#value']
  • core/modules/config/src/Form/ConfigSync.php:162 MixedArrayAssignment (error): Cannot access array value on mixed variable $form[$collection][$config_change_type]['heading']['#value']
  • … and 15 more
✅ wordpress: issues +3 −126

Memory 2 061 → 2 060 MB (<0.1 %) · Wall 174.4 → 175.2 s (+0.5 %)

Weighted 678 490 → 678 371 (−119, −0.02 %): L1 −125 · L3 +2

Issue type added removed
MixedArgument 0 2
MixedArrayAccess 1 10
MixedArrayAssignment 0 112
MixedArrayOffset 0 2
PossiblyFalseArgument 2 0

Changed in place (2)

@​@​ src/wp-includes/ID3/module.audio-video.riff.php:1819 @​@​
- MixedArgument:         Argument 2 of preg_match cannot be mixed, expecting string
- MixedArrayAccess:      Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]
+ PossiblyFalseArgument: Argument 2 of preg_match cannot be false, possibly string value expected

@​@​ src/wp-includes/ID3/module.audio-video.riff.php:1898 @​@​
- MixedArgument:         Argument 1 of trim cannot be mixed, expecting string
- MixedArrayAccess:      Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']
+ PossiblyFalseArgument: Argument 1 of trim cannot be false, possibly string value expected

Added (1)

  • src/wp-includes/theme.php:3046 MixedArrayAccess (error): Cannot access array value on mixed variable $_wp_theme_features[$feature]

Removed (122)

  • src/wp-includes/ID3/module.audio-video.riff.php:1817 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['data']
  • src/wp-includes/ID3/module.audio-video.riff.php:1825 MixedArrayAccess (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]
  • src/wp-includes/ID3/module.audio-video.riff.php:1840 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['data']
  • src/wp-includes/ID3/module.audio-video.riff.php:1841 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']
  • src/wp-includes/ID3/module.audio-video.riff.php:1841 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']['alter']
  • src/wp-includes/ID3/module.audio-video.riff.php:1842 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']
  • src/wp-includes/ID3/module.audio-video.riff.php:1842 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']['attrib']
  • src/wp-includes/ID3/module.audio-video.riff.php:1843 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']
  • src/wp-includes/ID3/module.audio-video.riff.php:1843 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']['artnum']
  • src/wp-includes/ID3/module.audio-video.riff.php:1844 MixedArrayAssignment (error): Cannot access array value on mixed variable $RIFFchunk[$chunkname][$thisindex]['parsed']
  • … and 112 more

head 4666ca1 · base eda66f2 (merge-base) · workflow run

@jirkace

jirkace commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Checked against current master (dad9fdb80): issetOnAnIndexIsKeptWhenTheIndexIsNarrowedInALoop fails on master (run singly) and passes here, so the PR does fix the case it adds.

Not changed, read only: finding 1 (dependsOnNarrowedVar() keeps the whole stale entry of $arr[$key], not only its "defined" part; the perf report's PossiblyInvalidArrayOffset on drupal ConfigSync.php ($form[$collection][$config_change_type]['heading']) is that effect) and finding 2 (the case runs with ensure_array_string_offsets_exist off, so PossiblyUndefinedStringArrayOffset is not exercised).

Ran: the PR's case on master. No code change pushed.

@alies-dev alies-dev 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.

🤖 The idea is right (narrowing an index variable does not change what is known about $arr[$key]) and it fixes the issue's case, but by the author's own account it adds a new false-positive class on a benchmark project, and the branch conflicts with master.

Already fixed on master: no. On upstream/master the issue's snippet still reports PossiblyUndefinedStringArrayOffset for 'foo' and 'bar' inside if ("foo" === $key) / elseif ("bar" === $key).

Overlap / conflicts: GitHub shows the PR as conflicting. Against current master src/Psalm/Type/Reconciler.php and tests/ArrayAccessTest.php conflict (master added getPathType() and a series of offset-assertion changes around it). With #12633, #13087 and #13118 only tests/ArrayAccessTest.php conflicts.

Findings

  1. New issues in the perf report: drupal ConfigSync.php:158/162/166/170 PossiblyInvalidArrayOffset ($form[$collection][$config_change_type]['heading'], "expecting -7|...|6"), symfony Schema.php:182 MixedArgument, doctrine QueryBuilder.php:677 MixedArrayAssignment. The author's note says the ConfigSync ones come from keeping the whole stale entry of $arr[$key], not only its "is set" part. That is a new false positive caused by the change, not noise. The remembered entry should keep only what narrowing $key cannot invalidate (e.g. the possibly-undefined flag cleared), or be re-derived from $arr's value type, instead of preserving a stale type. (I could not reproduce the ConfigSync shape with a reduced copy of the foreach + switch ($type) pattern.)
  2. A retained entry also bypasses the offset check of the narrowed key: @param array<string, string|int> $arr, string|int $key, if (isset($arr[$key])) { if (is_int($key)) { echo $arr[$key]; } } reports InvalidArrayOffset on master and nothing on the PR. Contrived, but it shows the entry is trusted beyond what the narrowing justifies.

Recommendations (non-blocking)

  • Reconciler::dependsOnNarrowedVar() is a public static textual check used from Reconciler, IfAnalyzer, ElseIfAnalyzer, ElseAnalyzer; fine as a consolidation, but Context is where removeDescendents() has the same rule, so consider one shared helper.
  • issetOnAnIndexIsKeptWhenTheIndexIsNarrowedInALoop runs with ensure_array_string_offsets_exist off and 'assertions' => [], so on its own it asserts little; the two testEnsureArrayOffsetsExist... cases carry the weight.

@jirkace

jirkace commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Not changed in this round: the open point of the review is the perf report (new issues in drupal, symfony and doctrine), and I could not reproduce them with reduced copies either, so I cannot say whether they are false positives or genuine, and changing the code blindly would risk regressions. Master was merged into the branch earlier today and nothing else changed. If a maintainer can point at the exact snippet of one of the perf deltas, I will reduce and fix it.

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Local benchmark run for the triage report's perf findings (the benchmark runner itself is not available to me): Psalm on src/Illuminate of laravel/framework (shallow clone of its default branch, errorLevel 1, PHP 8.3, ensureArrayStringOffsetsExist, no baseline, --no-cache), this branch merged with current master vs master itself, issues compared as sorted lines.

Limits: laravel only. Not run: the full suite (CI).

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Local benchmark run for the triage report's perf findings (the benchmark runner itself is not available to me), now on symfony: Psalm on a shallow clone of symfony/symfony, directories src/Symfony/Component/{Config,Console,DependencyInjection,HttpFoundation,Serializer,Yaml,VarExporter,JsonSchema} and src/Symfony/Contracts (tests and resources excluded), errorLevel 1, PHP 8.4, ensureArrayStringOffsetsExist, no baseline, library plugins off, --no-cache; this branch merged with current master vs master itself, issues compared as sorted lines.

  • fix(reconcile): keep what is known about an indexed value when the index is narrowed #13344: +1 / -5. The added one is JsonSchema/Schema.php:182 MixedArgument for array_key_exists, which master also reports at that position (expecting array<array-key, mixed>) with the type mixed instead of array<array-key, array<array-key, mixed>|mixed>|mixed, so it is the same issue worded differently; the five removed ones are PossiblyUndefinedStringArrayOffset (HeaderBag.php:151, Schema.php:176, :178, :182) and that MixedArgument of master. The drupal (ConfigSync.php) and doctrine-orm (QueryBuilder.php:677) deltas of the review are not covered.

Limits: a subset of symfony only. Not run: the full suite (CI).

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Local benchmark run on drupal (shallow clone of drupal/core: lib/Drupal and the modules config, content_translation, layout_builder, path_alias, options, system; tests excluded), errorLevel 1, PHP 8.3, ensureArrayStringOffsetsExist, no baseline, library plugins off, --no-cache; this branch merged with current master vs master (a worktree at master, same vendor), issues compared as sorted lines. Taint (SECURITY) lines are left out: they differ between two runs of the same code here.

  • fix(reconcile): keep what is known about an indexed value when the index is narrowed #13344: +4 / -7. Added: four PossiblyInvalidArrayOffset at modules/config/src/Form/ConfigSync.php lines 158, 162, 166, 170 ($form[$collection][$config_change_type]['heading'] with 'heading' "expecting -7|...|6"); I could not tell the stale-type problem of the review from the correct behaviour without more work. What I checked: on master the same report already exists at line 152 (the first write $form[$collection][$config_change_type]['heading'] = [...]) and at line 177 (['list']), because the entry $form[$collection][$config_change_type] has the type 'actions'|array{...} (a string possible), and an offset of a string must be an int. This PR keeps that entry after the first write, so the following writes of the same container report the same thing, while master forgets the entry after the first write and reports once. So these four are the same cause as the first one repeated, not a new kind; whether to report each write is the question. Removed: seven (not listed).

Limits: a subset of drupal only. Not run: the full suite (CI).

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Local run on doctrine/orm (shallow clone, src, errorLevel 1, PHP 8.4, ensureArrayStringOffsetsExist, no baseline, library plugins off), this branch merged with current master vs master (a worktree at master, same vendor; two runs of master give identical output): +1 / -0, the one the report cites for QueryBuilder.php: src/QueryBuilder.php:679 MixedArrayAssignment: Cannot access array value on mixed variable $this->dqlParts[$dqlPartName] (line 677 of the report's head), in add(): $this->dqlParts[$dqlPartName][] = $dqlPart; after $isMultiple = is_array($this->dqlParts[$dqlPartName]) && !(...).

I reproduced it as a regression of this PR (master: the entry is array<array-key, mixed> there, branch: mixed) with this reduction ($__t is read after the if that holds the loop):

final class Q {
    /** @var array<string, mixed> */
    private array $parts = ['select' => [], 'join' => []];

    public function add(string $name, array $part, bool $append = false): void {
        $isMultiple = is_array($this->parts[$name]) && ! ($name === 'join' && ! $append);

        if ($name === 'join') {
            $new = [];
            foreach ($part as $k => $v) {
                $new[$k] = $v;
            }
            $part = $new;
        }

        if ($append && $isMultiple) {
            $__t = $this->parts[$name];
            /** @psalm-trace $__t */ // master: array<array-key, mixed>, this branch: mixed
        }
    }
}

It needs the foreach inside the if ($name === 'join'); without the loop (or with the loop outside the if) master and branch agree. Bisect on this snippet: putting the original preg_match back in Reconciler::reconcileKeyedTypes() alone, or in IfAnalyzer alone, restores array<array-key, mixed>; doing it in ElseAnalyzer or ElseIfAnalyzer alone does not. So it comes from the if branch keeping $this->parts[$name] while $name is narrowed to 'join', and the merge after the if then losing what the is_array() clause of $isMultiple knew. I have not fixed it; this PR should not land as is. Not run: the full suite (CI).

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 6b53dda for the doctrine/orm regression of the previous comment (QueryBuilder.php:679, MixedArrayAssignment).

  • Cause as far as I got: the IfAnalyzer site. Putting the original preg_match back there makes the reduction from my last comment give array<array-key, mixed> again, and issetOnAnIndexIsKeptWhenTheIndexIsNarrowedInALoop (the case of this PR) passes without that site, so it is back to the original; Reconciler, ElseAnalyzer and ElseIfAnalyzer keep the change. I did not find why keeping the entry in the if branch loses what the is_array() clause gave after the merge; the revert is the fix, not an explanation.
  • New isArrayOfAnOffsetByAVariableIsKeptAfterAnIfThatNarrowsTheVariableAndHasALoop: fails on the previous head with MixedArrayAssignment ... $this->parts[$name], passes now (and on master).
  • Cost: the @psalm-suppress PossiblyUndefinedStringArrayOffset of Config::...getReportingLevelForFunction() that the IfAnalyzer part had made unnecessary is back (self-analysis reports it without), so the description now says Refs #7656 instead of Fixes #7656; Fixes #7221 stays.
  • Corpus runs with the fix against a master at the same commit: doctrine-orm +0 / -0 (was +1), laravel +0 / -0, symfony +1 / -4 (was +1 / -5), drupal +4 / -4 (was +4 / -7; the four added are the repeated ConfigSync.php reports described earlier).

Ran single: the new case and the case of this PR, self-analysis clean. Not run: the full suite (CI), neighbouring if/elseif narrowing cases of other test files.

@jirkace

jirkace commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Correction to my comment about 6b53dda: its cause was wrong and that commit broke this PR's own case. Pushed 6089ddc.

  • 6b53dda put the original regular expression back in IfAnalyzer and brought back the suppression in Config.php. CI of that head failed ArrayAccessTest::testEnsureArrayOffsetsExistAfterNarrowingTheIssetKey (the example of this PR's description with ensure_array_string_offsets_exist): the IfAnalyzer part is needed. I had run only the other case of this PR, not that test method, which I should have said.
  • Real cause of the doctrine/orm regression, found by dumping the clauses of the context after the if: LoopAnalyzer, when a loop is left, dropped the clauses (removeVarFromConflictingClauses()) of every variable that is mixed in the loop context, whether the loop touched it or not. With this PR the entry $this->parts[$name] is in scope inside the if ($name === 'join') { foreach ... } branch (narrowing $name no longer removes it), so the loop dropped the (!$isMultiple) || ($this->parts[$name] is array) clause; on master the entry was already missing there, so the clause survived by accident. LoopAnalyzer now drops the clauses only of a variable the loop changed (stamped in the loop's context, compared with the parent's), as removeClausesOfVarsChangedIn() does for an if. IfAnalyzer and the removal of the suppression of Config.php are as in the original head, so the description says Fixes #7656 again.
  • Corpora against a master at the same commit: doctrine-orm +0 / -0 (was +1), laravel +0 / -3, symfony +1 / -5, drupal +4 / -7 (the four added are the ConfigSync.php reports described earlier), guzzle and tempest (without tests/) no difference.
  • Ran single: testEnsureArrayOffsetsExistAfterNarrowingTheIssetKey, the case of this PR, the regression case isArrayOfAnOffsetByAVariableIsKeptAfterAnIfThatNarrowsTheVariableAndHasALoop (it fails on 6b53dda's parent with the orm message, passes now) and three neighbouring cases about mixed values left by a loop or a ternary (mixedIteratedByForeachIsNonEmptyInTheBodyAndMixedAfterIt, useOfANonEmptyMixedDefinedByAPreviousIterationBindsItToMixed, nonEmptyMixedStaysNonEmptyMixedAfterATernaryOnItsType), self-analysis clean. Not run: the rest of the loop tests and the full suite (CI); the LoopAnalyzer change reaches every loop, so that CI run is the real check.

@alies-dev alies-dev 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.

🤖 Re-checked against the current head: nothing blocks this anymore, and it is ready to merge. Since the last review, other PRs landed on master and this branch now conflicts in tests/ArrayAccessTest.php (test cases only; #13087 adds cases at the same spot, so rebase after it lands to avoid a second round). Please rebase onto master and keep both sides' test cases; I'll merge once CI is green.

@jirkace

jirkace commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

From the triage report generated 2026-11-20 05:22 UTC (reviewed head 9e43f1a), finding 5 (the LoopAnalyzer stamp condition has no invalid-code case). Pushed 55ea608, a test only, no source change.

  • Added isArrayClauseOfAVariableTheLoopChangesIsDroppedAfterTheLoop: $isArray = is_array($m), a loop assigns $m, and $m[] = 1 under if ($isArray) after it still reports MixedArrayAssignment (pinned by position). Run alone with --filter 'testInvalidCode@isArrayClauseOfAVariableTheLoopChangesIsDroppedAfterTheLoop': passes.
  • It is a guard, not a proof of the new condition: with the line removeVarFromConflictingClauses($var_id) of that branch (LoopAnalyzer.php:751) disabled the case still passes, because for a variable the loop assigns another path drops the clause (the earlier call at line 713/763). The new condition only matters for a mixed variable the loop does not change, which isArrayOfAnOffsetByAVariableIsKeptAfterAnIfThatNarrowsTheVariableAndHasALoop covers (fails without the condition).
  • Not run: the other loop tests and the full suite (CI does that). Splitting the loop change into its own PR: I left it here because the doctrine QueryBuilder regression this PR caused is fixed by exactly that line.

@alies-dev alies-dev added the release:fix The PR will be included in 'Fixes' section of the release notes label Nov 20, 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 for the follow-ups. The LoopAnalyzer part holds up: I tried twelve loop shapes that change a mixed variable (by-ref call, foreach value, list(), nested loops, use (&$m), while/do/for assignments, break, unset) and base and head agree on all of them, only the untouched-variable case changes.

One problem remains with the narrowing part, the stale type of the kept entry. It is reproducible:

function takesString(string $s): void {}

/**
 * @param array{foo: string, bar: int} $a
 * @param 'foo'|'bar' $k
 */
function f(array $a, string $k): void {
    echo (string) $a[$k];          // same with `if (isset($a[$k]))`
    if ($k === 'foo') {
        takesString($a[$k]);       // master: string, no issue
                                   // this PR: int|string, InvalidScalarArgument
    }
}

The entry $a[$k] is kept with the type it got for 'foo'|'bar'. That is only safe when the value type does not depend on the key (array<K, V>, list<V>); for a keyed array it should be recomputed, keeping only the "is defined" part. The same mechanism repeats the drupal ConfigSync.php report on every case of the switch. Could you restrict the kept entry accordingly and add this snippet as a test with an assertion on the type?

The branch also conflicts with master in tests/ArrayAccessTest.php since #13118 landed; please rebase and keep both sides' cases.

@jirkace
jirkace force-pushed the fix/keep-index-dependents-on-refinement branch from f8346b6 to 85edc16 Compare November 22, 2026 23:46
@jirkace

jirkace commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@orklah Rebased onto master (28e192b), new head 85edc16. The conflicts were in tests/ArrayAccessTest.php (both sides' cases are kept), plus Reconciler.php and the imports of IfAnalyzer.php.

@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, the shape case is fixed: with array{foo: string, bar: int} the narrowed offset is string again, and uniform shapes, list<string> and $a['p'][$k] keep the defined offset as intended. The drupal ConfigSync.php repetition is gone from the perf report too.

Only a rebase is left: the branch conflicts again with master in tests/ArrayAccessTest.php (#14499 added cases at the top of the same two providers), please keep both sides. The red Unit Tests 4/8 jobs are not from this PR: master itself hung in that chunk this afternoon and is green again, so the new push will rerun them.

Optional: Reconciler is not @internal, so dependsOnNarrowedVar() becomes public API; marking the method @internal would avoid that.

@jirkace
jirkace force-pushed the fix/keep-index-dependents-on-refinement branch from 2905977 to 83ac55b Compare November 23, 2026 21:42
@jirkace

jirkace commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@orklah Rebased onto master, new head 83ac55b. tests/ArrayAccessTest.php and Reconciler.php conflicted, and I kept both sides. After #14646, isset($b[$l]) && $l === "foo" kept the int|string offset, because $b[$l] was reconciled before its index. An offset asserted along with its index variable is now reconciled after it (new case offsetOfAShapeIsRecomputedWhateverTheOrderOfItsNameAndOfTheConditions). dependsOnNarrowedVar() is @internal now. Self-analysis has the same errors as master.

jirkace and others added 6 commits November 23, 2026 23:08
…dex is narrowed vimeo#7221 vimeo#7656

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…fter an if that narrows the variable

Keeping `$this->parts[$name]` while `$name` is narrowed in the if branch lost what the
`is_array($this->parts[$name])` clause of `$isMultiple` gave after the if, when the branch held a loop
(doctrine/orm QueryBuilder::add(): new MixedArrayAssignment). IfAnalyzer drops them as before; the
case this PR is about (an isset of an index narrowed in a loop or an elseif chain) does not need that
site. The suppression of Config::getReportingLevelForFunction() that the IfAnalyzer part made
unnecessary is back, so vimeo#7656 is only referenced.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…rvive it; restore the index relaxation

6b53dda put the original regular expression back in IfAnalyzer after the doctrine/orm regression
(QueryBuilder::add(): `$isMultiple` clause `is_array($this->dqlParts[$dqlPartName])` lost after an
`if ($name === 'join') { foreach ... }`), which broke the case of this PR (an isset of an index narrowed
in nested ifs with ensureArrayStringOffsetsExist) and needed Config.php's suppression back.

The cause was not the relaxation: LoopAnalyzer dropped the clauses of every `mixed` variable that was in
scope when the loop is left, whether the loop touched it or not. The entry $this->parts[$name] is in scope
again now that narrowing $name no longer removes it, so its clause was dropped; on master the entry was
missing and the clause survived by accident. LoopAnalyzer drops the clauses only of a variable the loop
changed (stamped in the loop context). IfAnalyzer and Config.php are as in dceb988.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…after it vimeo#7221

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…mputed when the index is narrowed vimeo#7221

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ead under the narrowed index vimeo#7221

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@orklah
orklah force-pushed the fix/keep-index-dependents-on-refinement branch from 83ac55b to 4666ca1 Compare November 23, 2026 22:08

@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 d1e5743 into vimeo:master Nov 23, 2026
72 checks passed
orklah added a commit to orklah/psalm that referenced this pull request Nov 23, 2026
…x type on it

vimeo#13344 fixed the same forgetting of items keyed by a narrowed variable with
Reconciler::dependsOnNarrowedVar(), so its src is kept. On top of it:
- an item is still forgotten when the array's keys don't include the
  narrowed index, as PHP casts it, so that its fetch reports the offset
- a loop pass doesn't restore an item that assigning the foreach
  variables forgot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

PossiblyUndefined*ArrayOffset with refined key "Consider using isset beforehand" when isset is in fact used

3 participants