Skip to content

Fix client router cache collision for repeated search param keys - #93368

Open
genie-ru wants to merge 2 commits into
vercel:canaryfrom
genie-ru:fix/issue-92152
Open

genie-ru wants to merge 2 commits into
vercel:canaryfrom
genie-ru:fix/issue-92152

Conversation

@genie-ru

Copy link
Copy Markdown

When a search param key was used multiple times in a URL (e.g. ?color=red&color=green&color=blue), three client-side call sites computed the page cache key by passing Object.fromEntries(new URLSearchParams(...)) into addSearchParamsIfPageSegment. That collapsed repeated entries down to the last value, so the URL above and the shorter ?color=red&color=blue both reduced to {"color":"blue"}. The server passed a Record<string, string | string[]> instead and preserved arrays, so the two formats disagreed. When the user unchecked a value other than the last one, the new URL collided with the previous cache entry, the client served the stale render, and the Suspense boundary never re-suspended to reflect the change.

This change introduces a searchStringToRecord helper in packages/next/src/shared/lib/router/utils/ that builds the same Record<string, string | string[]> shape as the server, preserving arrays for keys that appear more than once. The three client call sites now use it: createSegmentFromRouteTree in router-reducer/ppr-navigations.ts (the regression source, added by #87256 in v16.2.0), doesCurrentSegmentMatchCachedSegment in segment-cache/scheduler.ts, and getCacheKeyForDynamicParam in route-params.ts. The latter two have used the same buggy pattern since v16.0 and are updated together so cache-key generation stays consistent across the routing layer.

A new e2e suite at test/e2e/app-dir/repeated-search-params-cache reproduces the scenario from the issue: the test navigates from ?color=red&color=green&color=blue to ?color=red&color=blue and asserts the result list updates from [red, green, blue] to [red, blue]. Without the fix the second navigation hits the stale cache entry and the list keeps green; with the fix it updates correctly. A unit test for searchStringToRecord covers single values, repeated keys, empty values, and mixed cases. Existing prefetch-searchparam, searchparams-reuse-loading, search-params-react-key, and conflicting-search-and-route-params suites continue to pass.

fixes #92152

When a search param key was used multiple times (e.g.
`?color=red&color=blue&color=green`), three client-side call sites
collapsed the values to the *last* one only via
`Object.fromEntries(new URLSearchParams(...))`. This produced cache
keys that disagreed with the server-side shape, which uses
`Record<string, string | string[]>` and preserves arrays. Removing a
non-last value from a repeated key (e.g. unchecking `green` above)
yielded a URL whose collapsed key matched the previous entry, so the
client returned a stale cached entry rendered with the old filter
state — Suspense never re-suspended and the page contents did not
update.

The new `searchStringToRecord` helper in
`shared/lib/router/utils/` mirrors the server-side shape, preserving
arrays for keys that appear more than once. All three client call
sites now use it: `createSegmentFromRouteTree` in
`router-reducer/ppr-navigations.ts` (the regression source, added by
vercel#87256 in v16.2.0), `doesCurrentSegmentMatchCachedSegment` in
`segment-cache/scheduler.ts`, and `getCacheKeyForDynamicParam` in
`route-params.ts`. The latter two have shared the pattern since v16.0
and are corrected together to keep cache key generation consistent.

Fixes vercel#92152
@genie-ru
genie-ru marked this pull request as ready for review May 22, 2026 19:41
klasolsson81 added a commit to klasolsson81/jobbliggaren that referenced this pull request Jul 29, 2026
…each it

The unit suite can only pin that `commit()` CALLS `router.refresh()`. Whether
that call actually repairs the navigation is unmeasurable in jsdom, which has no
router cache and mocks `router.push` synchronously, so the `useOptimistic`
overlay never outlives its transition.

This spec measures the effect in Chromium: pick two kommuner through the real
popover, remove the FIRST chip — the colliding transition — and require the chip
row to end at one. It asserts the collision predicate itself (repeated keys
collapse to the last value, per vercel/next.js#93368) so that if the href builder
ever stops producing the colliding shape, the spec says so instead of quietly
measuring a transition that was never at risk.

Counterfactual, run rather than argued: with `router.refresh()` removed and the
app rebuilt, the URL still moves and the chip row stays at TWO. The second spec —
two picks in a row must put two DIFFERENT sentences in the live region — failed
against the pre-fix build with the axis-named string twice, which is the defect
design-reviewer and code-reviewer both found.

Two harness traps met and fixed rather than worked around: the chip row repaints
from the overlay instantly while the URL commits with the navigation, so reading
`page.url()` after a chip assertion reads a stale URL (it reported zero applied
kommuner); and the real SCB län is "Stockholm" where the unit fixture says
"Stockholms län", so a name-matched selector passes in jsdom and times out here.

`e2e.yml` is observe-only, so this REPORTS a regression rather than blocking it —
stated in the spec's own header so nobody reads it as a merge gate.

Co-Authored-By: Claude Opus 5 <[email protected]>
github-actions Bot pushed a commit to klasolsson81/jobbliggaren that referenced this pull request Jul 29, 2026
… waiting for a button (#1125)

* feat(companies): a bransch or ort chip applies the filter, instead of waiting for a button

/foretag/sok had two interaction models in one island and only one of them was visible: the name
field submits, the filter chips edited a DRAFT that did nothing until you found the button again.
Framing §2.3 (`docs/reviews/2026-07-25-foretag-sok-followup-design.md`). The filters now commit live,
copied from `jobb-hero-filters.tsx` rather than re-derived.

The URL is the single truth and `useOptimistic` is the overlay that makes a chip respond instantly
while the RSC navigation is in flight. Two rules from the precedent, both load-bearing:

- **`next` is built from `selection`** — the optimistic value — never from props. Build it from
  props and removals two and three in a fast sequence each undo the one before, because the props
  have not landed yet.
- **The WHOLE state is pushed, never a delta**, so every commit is idempotent and a temporary revert
  of the overlay between transitions is self-healing.

This also deletes a latent bug rather than only the latency: the island renders without a `key` and
never remounts, so the old `useState` initialisers ran exactly once. Press Back and the chips kept
showing the search you had just left. An overlay derived from props cannot.

**V1 (ADR 0087 D8(c), Blocker class) is the invariant that makes any of this safe: a filter commit
carries the `namn` PROP — what is already applied — and NEVER the field's value.** Click a chip
while ten unsubmitted digits sit in the input and a value-carrying commit would put a possible
personnummer into `?namn=`, in history, in access logs and in any shared link. The org.nr branch
guards the SUBMIT path; before live commit there was no other route from the field to the URL, and
now there is. Two tests pin it, one of them asserting the pnr-shaped digits appear nowhere in the
pushed href.

**The re-seed gate moved from the applied signature to `namn` alone, and that is now load-bearing.**
Under draft-commit a filter change and a name change always arrived together, so a signature-wide
gate was harmless. Under live commit a chip changes the signature on its own — the old gate would
have reset the field to the applied name on every chip, wiping a half-typed company name
mid-keystroke.

`scroll: false` on filter commits (a chip narrows the list you are already reading); the explicit
name submit keeps default scroll. `draftDiffersFromApplied` shrinks to the name axis, because the
filters can no longer diverge by construction. `sameCodeSet` went with it.

The change is announced from ONE persistent polite region, always in the DOM and empty at first
paint (a region mounted with its content in place is not reliably announced). It names the FILTER
change, never the result count — the count arrives with the streamed results, and a screen reader
would hear a number for a list it has not reached. Five new keys in sv and en.

Tests: the suite encoded the draft model, so ten cases asserted behaviour this PR removes. Rewritten
to the precedent's shape — what a click DOES is measured on the navigation, what the UI SHOWS is
seeded through props. One test is explicitly seeded rather than picked twice, because `useOptimistic`
holds its overlay only while its transition is in flight and `router.push` is a synchronous mock:
two sequential picks would measure jsdom, not the component.

* test(web): pin the re-seed gate against a commit that actually lands

The RESEED mutation (gate on the applied signature instead of on `namn`) survived, and so did RACE
— both because `router.push` is a synchronous mock, so props never change and anything depending on
them landing is invisible to jsdom. RESEED is reachable anyway: rerender with the filter axis changed
and `namn` untouched, which is exactly what a filter commit produces. The signature-wide gate then
wipes a half-typed name; the `namn` gate cannot fire at all. Both directions asserted.

* fix(companies): a second filter change in a row was silent, and a chip commit never fetched

Four mandatory reviewers reported against ca08bff; this applies the fixes CTO
triage bound in-block.

The announcement named the AXIS, so two picks in a row produced a byte-identical
string: React bails out on Object.is, the DOM never mutates and aria-live never
fires. Measured in Chromium before the fix — ticking two kommuner announced
"Filtret Ort eller län är tillagt." twice, so every change after the first was
silent to a screen reader (WCAG 4.1.3). Both call sites now name the OBJECT,
derived from the same functions the chips are, so the announcement and the chip
that appears cannot disagree.

A chip commit whose target URL collides with the current one in Next's client
router cache changed the URL and fetched NOTHING: the chips snapped back and the
results kept answering the old filter. The cache collapses repeated query keys to
the last value, so ?kommun=0180&kommun=1480 and ?kommun=1480 are one entry
(vercel/next.js#92152, fix PR #93368, both open; we are on 16.2.9). That
predicate explains all seven measured transitions, and the silent one reproduced
5/5 in fresh contexts. router.refresh() alongside the push, with the exit
condition written at the call site. {scroll:false} was suspected and disproven.

The org.nr answer now SURVIVES a filter commit. The lookup is independent of the
filter axes and renders as its own headed section, so the browse cannot make it
stale; dropping it was task B destroying task A's result (ADR 0047). This deletes
appliedSignature/seededFrom entirely — one gate, on the name, doing both jobs.

Also: focus moves deterministically after a commit that unmounts the control that
was clicked (the chip × is the primary gesture now, not an edit to a draft);
unappliedChanges says which field it means; and the file header plus page.tsx no
longer describe the draft model this PR removed.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(companies): pin the router-cache workaround where jsdom cannot reach it

The unit suite can only pin that `commit()` CALLS `router.refresh()`. Whether
that call actually repairs the navigation is unmeasurable in jsdom, which has no
router cache and mocks `router.push` synchronously, so the `useOptimistic`
overlay never outlives its transition.

This spec measures the effect in Chromium: pick two kommuner through the real
popover, remove the FIRST chip — the colliding transition — and require the chip
row to end at one. It asserts the collision predicate itself (repeated keys
collapse to the last value, per vercel/next.js#93368) so that if the href builder
ever stops producing the colliding shape, the spec says so instead of quietly
measuring a transition that was never at risk.

Counterfactual, run rather than argued: with `router.refresh()` removed and the
app rebuilt, the URL still moves and the chip row stays at TWO. The second spec —
two picks in a row must put two DIFFERENT sentences in the live region — failed
against the pre-fix build with the axis-named string twice, which is the defect
design-reviewer and code-reviewer both found.

Two harness traps met and fixed rather than worked around: the chip row repaints
from the overlay instantly while the URL commits with the navigation, so reading
`page.url()` after a chip assertion reads a stale URL (it reported zero applied
kommuner); and the real SCB län is "Stockholm" where the unit fixture says
"Stockholms län", so a name-matched selector passes in jsdom and times out here.

`e2e.yml` is observe-only, so this REPORTS a regression rather than blocking it —
stated in the spec's own header so nobody reads it as a merge gate.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(web): two different /foretag/sok filters could be one router-cache entry

Next's client router cache keys a route by its URL and collapses REPEATED query
keys to the last value only. So `?kommun=A&kommun=B` and `?kommun=B` hashed to
the same entry: navigating from the first to the second targeted a URL the cache
believed it already held. No RSC request, no re-render — the URL would say one
filter while the page still showed the other. Upstream vercel/next.js#92152 and
its fix PR #93368, both open on 2026-07-29; we run 16.2.9.

Each axis is now ONE param whose codes are joined, so two different applied
states cannot produce the same cache key — at any latency, on any machine.

A timing-based workaround was built and measured first (`router.refresh()` beside
the push). It was correct for one removal and WRONG for two or more in quick
succession: past ~600 ms of server latency the whole sequence was undone and the
original filter came back. Measured at 300/600/900/1500 ms; this surface's own
navigation measures ~0.9 s. A structural defect needed a structural answer.

Back-compat is a real obligation here, not a footnote: every link shared or
bookmarked before today carries the repeated form. `parseCodeAxis` (renamed from
`toStringList`, which described only the array/scalar half of what it now does)
accepts BOTH forms and yields the same codes, so no redirect and no migration.
Pinned in both directions, including a mixed link.

Separator is `-`: `URLSearchParams` leaves it unencoded where `,` becomes `%2C`
and would disfigure every shared link on a surface whose value IS shareability.
No code on either axis can contain it — SNI leaves are five digits, kommun codes
four — and `normalizeCodes` drops anything outside the SCB reference regardless.

`namn` is untouched, byte for byte: same serialisation, same parser, same
`parseNamn` gate and the same proxy wash. This change reaches only `sni` and
`kommun`, so the ADR 0087 D8(c) surface is unchanged.

On main today the collision is NOT reachable — no current gesture removes a
non-last value from a repeated axis and keeps the rest. This is latent-defect
prevention plus the enabling change for #1125's live-commit chips, which is the
gesture that reaches it. Rendered check: a legacy repeated link and the joined
link render the identical four chips, and the surface now writes the joined form.

Co-Authored-By: Claude Opus 5 <[email protected]>

* refactor(companies): drop the router.refresh workaround, the collision is gone at the source

#1134 makes each filter axis one query param, so two applied states can no longer
share a router-cache key. The timing-based repair this branch carried is now
dead weight, and dead weight that was measured WRONG: correct for one chip
removal, but two or more in quick succession were undone entirely once server
latency passed ~600 ms, because a refresh fired before its push committed
requests the pre-push URL and lands last.

Removed with it: the unit pin on the call site, and the mock that existed only
to satisfy it. The e2e spec stays and is now the pin for the structural fix
instead — it asserts the same user-visible guarantee, so what it protects did
not change when the mechanism did.

Measured on the merged tree, no refresh() present: the seven-form matrix is 7/7
fetch-and-re-render, and three fast removals are correct at 300/600/900/1500 ms
of injected latency — the exact regime that falsified the workaround.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(companies): the e2e spec measured a URL contract this branch no longer writes

Round-2 review, both reviewers, four Majors.

The worst is mine and it is the session's own defect class one more time. The
rebase rewrote the e2e spec's DOCBLOCK to the joined URL contract and left its
BODY reading repeated params, so `getAll("kommun")` returned one element where
the helper polled for two and the test could not reach a single assertion. The
commit that did it claimed the spec "asserts the same user-visible guarantee".
Measured before fixing: red at the poll, exactly as reported. Nothing said so —
vitest does not run Playwright and the e2e lane is observe-only. It now parses
codes rather than counting params, and its collision oracle is INVERTED: under
one-param-per-axis there is no collision left to confirm, so it asserts the
property the contract delivers instead, that the two states have different keys.

`ortChangeLabel`'s bulk branch was unasserted inside a block whose docblock
claims to cover every announcement this surface emits — both harnesses filtered
"Hela …" out of their selectors, so `return lan` could be swapped for the axis
label with the suite green. Now pinned, including that the change really was
multi-code.

An org.nr lookup that resolves after a chip commit no longer steals focus. The
answer deliberately survives a filter commit, and a commit deliberately places
focus; both are right and neither is if the late `focus()` runs unconditionally.
It is gated on a focus generation captured at submit — the answer still renders
and is still announced, only the focus move is withheld.

Three claims in the test file named mutants that cannot be written: "all three
draft pieces are useState initialisers" (one is), "deleting setBranch(seedBranch(...))"
(both symbols were deleted by this PR), and "the signature is not just the name"
(the gate IS the name alone, so the named mutant is the shipped code). Corrected
to the shipped mechanics rather than quietly retitled.

Minors: `role="status"` on the live region matching the precedent it mirrors;
the `aria-busy` breadth now carries its reason; `ortChangeLabel`'s grounds were
false (there are TWO bulk controls — what carries the conclusion is the omitted
`groupAxis`); the focus effect's ordering assumption written down; the unapplied
line moved into the field it names and wired via `aria-describedby` instead of
sitting four blocks below it; and the announcement's never-reset limitation
declared, with the obvious repair recorded as rejected and why.

Co-Authored-By: Claude Opus 5 <[email protected]>

* test(companies): pin the three round-2 guarantees a mutation sweep found unpinned

A sweep over the round-2 fixes killed one of four. The focus guard on the late
org.nr resolve, role=status on the live region, and the aria-describedby link
between the field and its unapplied line could each be removed with the whole
suite green — the exact class the round-2 review was about, reproduced inside
its own fix.

The focus case holds the fetch open on purpose so the chip click lands inside
the request window. That window is the subject; a mock that resolves at once
would measure something else and pass either way.

Co-Authored-By: Claude Opus 5 <[email protected]>

* fix(companies): the unapplied line shifted the whole surface on the first keystroke

Round-3 review, both Minors, and the layout one was measurable so it was
measured rather than argued.

Moving `unappliedChanges` into the field put it ABOVE the filter group, the chip
row, the clear control and the streamed table — so rendering it conditionally
pushed all of them down 26 px at the first character typed, and back up when the
field matched the applied name again. Measured at 1280 px against the prod build:
chip row 668→694, clear control 661→687, results table 856→882, document height
+26. That is the class `showClear` is gated on applied state to avoid, and this
element sits higher, so it moved more.

Reserving the ELEMENT alone would not have fixed it: `.jp-field`'s gap accounts
for 6 px of the 26, the caption line itself for the other 20. Hence `min-h-5`
rather than an empty span. Re-measured after: zero shifted keys. The cost is
stated where it is paid — the field block is 26 px taller at all times, which is
the price of a surface that does not move under the pointer while you type.
`aria-describedby` stays conditional, so the description gains a sentence only
while one is true.

Also removed an orphaned docblock that claimed the org.nr answer is "not part of
the applied signature". There is no applied signature any more — this PR deleted
it — and the block immediately below already describes the shipped model.

Co-Authored-By: Claude Opus 5 <[email protected]>

---------

Co-authored-by: Claude Opus 5 <[email protected]>
@transfer1992

Copy link
Copy Markdown

Because we are severely impacted by #92152, we decided to build a local patch-package setup from this. We cannot wait until this is merged.
This is very critical for many projects.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Next 16.2 router cache issue, if search param name is used multiple times

2 participants