Skip to content

fix(list): a write under the key array_key_last() returned for a list keeps it a list - #14428

Merged
orklah merged 7 commits into
vimeo:masterfrom
jirkace:fix/14267-array-key-last-list-write
Nov 22, 2026
Merged

orklah merged 7 commits into
vimeo:masterfrom
jirkace:fix/14267-array-key-last-list-write

Conversation

@jirkace

@jirkace jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Writing under the key array_key_last() (or array_key_first()) returned for a list turns the list into an array, although that key exists.

Before

/**
 * @param list<string> $names
 * @return list<array{name: string, note: ?string}>
 */
function annotate(array $names, string $note): array {
    $entries = [];
    foreach ($names as $name) {
        $entries[] = ["name" => $name, "note" => null];
        $key = array_key_last($entries);
        $entries[$key]["note"] = $note;
    }
    return $entries; // LessSpecificReturnStatement, MoreSpecificReturnType: array<int<0, max>, ...>
}

After

    return $entries; // no issue

Fixes #14267

… keeps it a list vimeo#14267

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Behaviour change

  • array_key_first() and array_key_last() of a list held by a variable (or a property/offset with a var id) return the key of that list the way the key of a foreach over it is typed (int<0, max> bound to the list, plus null when the list may be empty), so a write under that key keeps the list a list, as it already does for the key of a foreach. New ArrayFunctionCallTest case, which fails on master, with guards: a key that is null-checked first also keeps the list, and a write under an arbitrary int still makes it non-empty-array<int, ...>. Reassigning the list in between drops the binding, as for foreach.
  • New return type provider ArrayKeyFirstLastReturnTypeProvider (only for a list with a var id; everything else falls back to the stub). The inferred types themselves are unchanged (int<0, max>|null, int<0, 1> for ['a', 'b']): arrayKeyFirst*/arrayKeyLast*/ArrayKeysTest cases and the taint cases on these functions (dontTaintTheKeyOfAnArrayWithItsValues, taintTheKeyABuiltinReturns) ran alone and pass.
  • Self-analysis: only the 2 PoolEventLoopDriverTest errors that master reports too here. Not run: the full suite (CI), corpus benchmarks.

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

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

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

Reviewed by Cursor Bugbot for commit 19cbde7. Configure here.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Performance: unchanged · Types: decreased

Project Memory (MB) Wall (s) Issues Weighted (types) Taint Dead code
✅ laravel 1 768 96.7 $\color{gray}{\textsf{+0.9\%}}$ 25 691 52 996 682 0
✅ symfony 3 596 198.3 $\color{gray}{\textsf{-0.2\%}}$ 50 609 $\color{red}{\textsf{+1}}$ $\color{green}{\textsf{-2}}$ 98 400 $\color{green}{\textsf{-3}}$ 1 528 0
✅ doctrine-orm 380 16.2 $\color{gray}{\textsf{+1.0\%}}$ 3 481 6 143 0 0
✅ psl 617 20.0 $\color{gray}{\textsf{-2.3\%}}$ 1 375 5 615 1 0
✅ phpunit 455 20.2 $\color{gray}{\textsf{+2.1\%}}$ 1 731 3 410 18 0
✅ php-parser 226 13.8 $\color{gray}{\textsf{+0.8\%}}$ 17 154 21 245 0 0
✅ tempest 895 36.6 $\color{gray}{\textsf{+0.2\%}}$ 5 047 10 528 252 0
✅ amphp-amp 45 1.5 29 49 0 0
✅ webmozarts-assert 272 4.6 $\color{gray}{\textsf{-3.7\%}}$ 577 2 720 0 0
✅ guzzle-promises 44 1.6 155 434 2 0
✅ monolog 135 5.8 $\color{gray}{\textsf{+1.8\%}}$ 913 2 479 10 0
✅ drupal 4 839 197.3 $\color{gray}{\textsf{-0.3\%}}$ 97 591 169 293 583 0
✅ wordpress 2 038 187.8 $\color{gray}{\textsf{+1.9\%}}$ 142 704 676 684 461 1
Total 15 311 800.4 $\color{gray}{\textsf{+0.4\%}}$ 347 057 $\color{red}{\textsf{+1}}$ $\color{green}{\textsf{-2}}$ 1 049 996 $\color{green}{\textsf{-3}}$ 3 537 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 −2

Memory 3 596 → 3 596 MB (+0.0 %) · Wall 198.7 → 198.3 s (−0.2 %)

Weighted 98 403 → 98 400 (−3, <0.01 %): L3 −1

Issue type added removed
ArgumentTypeCoercion 1 1
PropertyTypeCoercion 0 1

Changed in place (1)

@​@​ src/Symfony/Component/HttpKernel/Controller/ArgumentResolver/RequestPayloadValueResolver.php:210 ArgumentTypeCoercion @​@​
- …mixed>, but parent type array<array-key, mixed> provided
+ …mixed>, but parent type array<array-key, array<array-key, mixed>|mixed|null|object> provided

Removed (1)

  • src/Symfony/Component/Translation/Extractor/Visitor/CallResolver.php:87 PropertyTypeCoercion (error): $this->returns expects 'list<list<Expr>>', parent type 'non-empty-array<int<0, max>, list<Expr>>' provided

head a8eeb12 · base 708bf98 (merge-base) · workflow run

…amed argument vimeo#14267

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

@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 #14267, but the key stays bound to the list after the list changes, so writes that create a gap are no longer reported. Each of these returns LessSpecificReturnStatement on master and nothing on this branch:

/**
 * @param non-empty-list<int> $l
 * @return list<int>
 */
function popTwice(array $l): array {
    $k = array_key_last($l);
    array_pop($l);
    array_pop($l);
    $l[$k] = 1; // gap
    return $l;
}

/**
 * @param list<int> $a
 * @param non-empty-list<int> $b
 * @return list<int>
 */
function reassign(array $a, array $b): array {
    $k = array_key_last($b);
    $b = $a;
    $b[$k] = 1; // gap
    return $b;
}

/**
 * @param non-empty-list<int> $l
 * @return list<int>
 */
function sliced(array $l): array {
    $k = array_key_last($l);
    $l = array_slice($l, 1);
    $l[$k] = 1; // gap
    return $l;
}

final class Bag {
    /** @var list<int> */
    public array $items = [];

    public function reset(): void { $this->items = []; }

    public function m(): void {
        $k = array_key_last($this->items);
        if ($k === null) return;
        $this->reset();
        $this->items[$k] = 1; // PropertyTypeCoercion on master
    }
}

Reassigning the list does not drop the binding (only $l = [] happens to work): nothing invalidates dependent_list_key, its only reader is ArrayAssignmentAnalyzer. That is #13920, which the foreach key already has; with array_key_last() the key lives outside any loop, so it is much easier to hit. Could you drop the binding whenever the list variable changes (assignment, by-reference argument, property invalidated by a method call), and add these cases as invalid-code tests? That fixes #13920 too.

Minor: ArrayKeyFirstLastReturnTypeProvider is registered out of alphabetical order in FunctionReturnTypeProvider.

jirkace and others added 2 commits November 21, 2026 16:49
Context::$list_key_bound_lists records the lists a key type is bound to (array_key_first/last,
foreach); the binding is dropped from the types in scope when the list variable changes
(assignment, by-reference argument, method call). A write under an offset keeps it.

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Pushed b979588. Context::$list_key_bound_lists records the lists a key type is bound to (array_key_first/last(), the foreach key), and removeVarFromConflictingClauses() drops the binding from the types in scope when that list variable changes: assignment, by-reference argument (array_pop), a method call invalidating the property, a branch merge. A write under an offset of the list ($l[$k] = 1) keeps it, so your writeUnderTheLastKey... cases and writing twice still pass.

Invalid-code cases, all but the last failing before: popTwice, reassign, sliced, the Bag property (PropertyTypeCoercion), plus the foreach key after $l = [] (already reported on master, so a guard). Valid: writes under the key twice and of a property. ArrayKeyFirstLastReturnTypeProvider is registered in alphabetical order now. @orklah

…ere any change of it is reported

The binding is released by an assignment of the list, a by-reference argument, an unset, a call that
forgets the property, and when a nested scope released it; a write under an offset (also from a
branch or a loop) keeps it. Psalm's own analysis reported the list/non-list change of loops that
write $a[$i] under the key of a foreach.

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

jirkace commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Pushed 1275d2c: the build jobs of the previous push failed because Psalm's own analysis reported list<...> returns as array<int<0, max>, ...> in 7 places (TypeCombiner::setIterablePurity(), ...): releasing the binding in removeVarFromConflictingClauses() also caught foreach ($l as $i => ...) { if (...) { $l[$i] = ...; } }, where a branch merge reports the write as a change of $l. The binding is released now where the list is invalidated (assignment of the list, by-reference argument, unset, a call forgetting the property) and, when a nested scope released it, in the scope it merges into; a write under an offset keeps it. The review's cases and the earlier ones still behave as in the last comment, and a full self-analysis is clean except the two PoolEventLoopDriverTest lines caused by Revolt missing in my local vendor/. @orklah

jirkace and others added 2 commits November 22, 2026 12:46
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	tests/ArrayFunctionCallTest.php
@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 28e192b into vimeo:master Nov 22, 2026
116 of 118 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.

Writing to $list[array_key_last($list)][...] turns a list into array<int<0, max>, ...>

2 participants