Unverified Commit bdbbb1e8 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Block prefetch task until sufficient response is received (#96017)

This is a refactor of the prefetching algorithm to block the prefetch
task from completing until the response is received.

Currently, a prefetch task is fire-and-forget: once a prefetch's
requests are spawned, the scheduler marks the originating task as
complete regardless of what the server ends up returning. However,
certain planned optimizations require us to verify the response from the
server to determine whether additional work is necessary. For example,
we may attempt to do a static prefetch instead of a runtime prefetch if
we optimistically assume that the static prefetch does not vary on
runtime data. We need to verify that assumption is correct before
marking the task as complete.

Now, whenever a pass over the task spawns a segment request, or
encounters an entry whose response hasn't arrived yet, the task
registers itself on the entry and exits as Blocked instead of Done. When
the entry resolves, the blocked task is pinged and the pass re-runs
against the received data. Only a pass that observes every response it
cares about advances the task to the next phase or completes it.

Rejected entries are handled per segment: a rejection counts as an
observed response, so the pass skips that segment and keeps prefetching
the rest. The task never registers on a rejected entry, since nothing
ever pings one. Retries are governed by the existing per-entry logic.

Also fixes a cache bug this exposed: when a revalidation response is
keyed at a more generic vary path than the stale partial entry that
prompted it (because the segment turned out not to vary on some param),
the stale entry shadowed the result on every lookup — the upgraded data
was unreachable and the revalidation was wasted. With blocking, that
dead end became an infinite loop: each fulfillment re-pinged the blocked
task, which re-read the same stale entry and spawned another
revalidation. Upserting (or re-keying) a segment now deletes settled
entries at more specific vary paths that the incoming entry supersedes.

The router-act test helper's "at least one request initiated" watchdog
is adjusted to account for the new blocking behavior: countable requests
can now be legitimately gated on an in-flight App Shell response (which
the watchdog intentionally doesn't count). On expiry it now proceeds to
response processing if the act scope intercepted a shell request, and
keeps waiting while shell requests are in flight elsewhere on the page,
instead of timing out.
parent a619237b
......@@ -266,6 +266,7 @@ type SegmentCacheEntryShared = {
export type EmptySegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Empty
blockedTasks: Set<PrefetchTask> | null
rsc: null
isPartial: true
promise: null
......@@ -273,6 +274,7 @@ export type EmptySegmentCacheEntry = SegmentCacheEntryShared & {
export type PendingSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Pending
blockedTasks: Set<PrefetchTask> | null
rsc: null
isPartial: boolean
promise: null | PromiseWithResolvers<FulfilledSegmentCacheEntry | null>
......@@ -280,6 +282,7 @@ export type PendingSegmentCacheEntry = SegmentCacheEntryShared & {
type RejectedSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Rejected
blockedTasks: Set<PrefetchTask> | null
rsc: null
isPartial: true
promise: null
......@@ -287,6 +290,7 @@ type RejectedSegmentCacheEntry = SegmentCacheEntryShared & {
export type FulfilledSegmentCacheEntry = SegmentCacheEntryShared & {
status: EntryStatus.Fulfilled
blockedTasks: null
rsc: React.ReactNode | null
isPartial: boolean
promise: null
......@@ -1009,10 +1013,50 @@ export function overwriteRevalidatingSegmentCacheEntry(
return pendingEntry
}
/**
* Whether an existing cache entry is preferred over an incoming candidate —
* i.e. the candidate does NOT supersede it. (On an exact tie — same fetch
* strategy, same partialness — this returns false, so the candidate replaces
* the existing entry.) This is the precedence rule used both when deciding
* whether an upsert may replace the entry at its own keypath, and when
* deciding whether an entry at a more specific keypath may be evicted because
* it shadows a just-inserted candidate (see `evictShadowingSegmentEntries`).
*
* Note that "less/more specific" in the comments below refers to fetch
* strategy content tiers (how much content a strategy can produce), not the
* vary-path specificity the eviction docs are concerned with.
*/
function isExistingSegmentEntryPreferred(
existingEntry: SegmentCacheEntry,
candidateEntry: SegmentCacheEntry
): boolean {
return (
// We fetched the new segment using a different, less specific fetch
// strategy than the segment we already have in the cache, so it can't
// have more content.
(candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&
!canNewFetchStrategyProvideMoreContent(
existingEntry.fetchStrategy,
candidateEntry.fetchStrategy
)) ||
// The existing entry isn't partial, but the new one is.
// (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)
(!existingEntry.isPartial && candidateEntry.isPartial)
)
}
export function upsertSegmentEntry(
now: number,
varyPath: SegmentVaryPath,
candidateEntry: SegmentCacheEntry
candidateEntry: SegmentCacheEntry,
// The fully concrete vary path a read for this segment position resolves
// against (all concrete param values, i.e. `tree.varyPath`) — the most
// specific path a read would use. Note this is the opposite of the
// generalized keying path that `getSegmentVaryPathForRequest` computes.
// Used to detect and evict stale entries at more specific keypaths that
// would otherwise shadow the candidate. Pass null when there's no request
// context; the shadow check is skipped.
lookupVaryPath: SegmentVaryPath | null
): SegmentCacheEntry | null {
// We have a new entry that has not yet been inserted into the cache. Before
// we do so, we need to confirm whether it takes precedence over the existing
......@@ -1031,20 +1075,9 @@ export function upsertSegmentEntry(
// Don't replace a more specific segment with a less-specific one. A case where this
// might happen is if the existing segment was fetched via
// `<Link prefetch={true}>`.
if (
// We fetched the new segment using a different, less specific fetch strategy
// than the segment we already have in the cache, so it can't have more content.
(candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&
!canNewFetchStrategyProvideMoreContent(
existingEntry.fetchStrategy,
candidateEntry.fetchStrategy
)) ||
// The existing entry isn't partial, but the new one is.
// (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)
(!existingEntry.isPartial && candidateEntry.isPartial)
) {
// The existing entry supersedes the candidate. Leave the existing entry
// in place and discard the candidate by not inserting it.
if (isExistingSegmentEntryPreferred(existingEntry, candidateEntry)) {
// The candidate does not supersede the existing entry. Leave the
// existing entry in place and discard the candidate by not inserting it.
//
// We must not mutate the candidate here (e.g. downgrade it to Rejected or
// null out its `rsc`). The caller does not transfer exclusive ownership
......@@ -1058,15 +1091,106 @@ export function upsertSegmentEntry(
return null
}
// Ping any tasks blocked on the existing entry before evicting it so they
// re-run and pick up the new entry. Without this, tasks waiting on the
// existing Empty/Pending entry would be stranded — the new fulfilled
// candidate has no blockedTasks of its own.
if (
existingEntry.status === EntryStatus.Empty ||
existingEntry.status === EntryStatus.Pending
) {
pingBlockedTasks(existingEntry)
}
// Evict the existing entry from the cache.
deleteFromCacheMap(existingEntry)
}
const isRevalidation = false
setInCacheMap(segmentCacheMap, varyPath, candidateEntry, isRevalidation)
if (lookupVaryPath !== null) {
evictShadowingSegmentEntries(now, lookupVaryPath, candidateEntry)
}
return candidateEntry
}
/**
* Evicts stale entries at more specific keypaths that shadow a just-inserted
* candidate entry.
*
* A response can be written to the cache at a MORE GENERIC vary path than the
* path the request was issued against — for example, the server may report
* that a segment doesn't vary on a param, so the entry is re-keyed with that
* param as Fallback. Meanwhile, an older, less useful entry can exist at a
* more specific path within the same fallback chain — for example, a partial
* shell entry keyed with root params concrete (see
* `getShellSegmentVaryPath`). Because segment lookup is
* most-specific-match-wins, every subsequent read at the concrete request
* path keeps returning the stale specific entry, and the more complete
* generic entry is unreachable from that URL. That both wastes the completed
* request and can loop: a prefetch task that revalidated the segment reads
* back the same stale entry, decides it needs to revalidate again, and
* repeats forever.
*
* The upsert is the one moment we know the ordering between the two entries:
* the candidate was produced by a request for this segment position, and
* `lookupVaryPath` is the fully concrete path a read for that position
* resolves against, so any entry that a read at that path would return in the
* candidate's stead is directly comparable to it. If such an entry is settled
* and the candidate supersedes it — under the same precedence rules the
* upsert applies at its own keypath — we know we never want to match against
* it again, so delete it, making the candidate reachable.
*
* Non-settled entries are never evicted here: a Pending entry is owned by an
* in-flight request that will settle it, and an Empty entry is a placeholder
* that a scheduler pass may still claim and upgrade.
*/
function evictShadowingSegmentEntries(
now: number,
lookupVaryPath: SegmentVaryPath,
candidateEntry: SegmentCacheEntry
): void {
// There can in principle be multiple shadowing entries at successively less
// specific keypaths, so loop until the read returns the candidate (or an
// entry we don't supersede). Each iteration re-reads and re-checks from
// scratch (in part because `deleteFromCacheMap` can promote a settled
// Revalidation-slot value into the just-vacated slot, surfacing a new entry
// at the same keypath). Each iteration deletes an entry from the map, so
// the loop terminates naturally; the bound is defensive, and 32 is far
// beyond any real fallback chain, which is bounded by the vary
// path's length.
for (let i = 0; i < 32; i++) {
const shadowEntry = readSegmentCacheEntry(now, lookupVaryPath)
if (shadowEntry === null || shadowEntry === candidateEntry) {
// The candidate is reachable from the lookup path (or the read missed
// entirely, e.g. because the candidate expired). Done.
return
}
if (
shadowEntry.status !== EntryStatus.Fulfilled &&
shadowEntry.status !== EntryStatus.Rejected
) {
// Only settled entries may be evicted. A Pending entry is held by an
// in-flight request and will settle on its own.
return
}
if (isExistingSegmentEntryPreferred(shadowEntry, candidateEntry)) {
// The shadowing entry is preferred over the candidate (e.g. it's a
// complete entry fetched with a more specific strategy). Leave it —
// reads at this path should keep matching it.
return
}
// The candidate supersedes the shadowing entry. Evict it. Settled entries
// shouldn't have blocked tasks (Fulfilled always has `blockedTasks:
// null`, and Rejected entries were pinged at rejection), but ping
// defensively before deleting, matching the upsert-evict pattern above.
pingBlockedTasks(shadowEntry)
deleteFromCacheMap(shadowEntry)
}
}
export function createDetachedSegmentCacheEntry(
now: number
): EmptySegmentCacheEntry {
......@@ -1075,6 +1199,7 @@ export function createDetachedSegmentCacheEntry(
const staleAt = now + 30 * 1000
const emptyEntry: EmptySegmentCacheEntry = {
status: EntryStatus.Empty,
blockedTasks: null,
// Default to assuming the fetch strategy will be PPR. This will be updated
// when a fetch is actually initiated.
fetchStrategy: FetchStrategy.PPR,
......@@ -1230,7 +1355,15 @@ export function attemptToUpgradeSegmentFromBFCache(
FetchStrategy.Full,
tree
)
const upserted = upsertSegmentEntry(now, segmentVaryPath, newEntry)
const upserted = upsertSegmentEntry(
now,
segmentVaryPath,
newEntry,
// The concrete lookup path this BFCache upgrade applies to. (In
// practice a Full request path is already fully concrete, so nothing
// can shadow the new entry and the shadow check is a no-op.)
tree.varyPath
)
if (upserted !== null && upserted.status === EntryStatus.Fulfilled) {
return upserted
}
......@@ -1386,6 +1519,7 @@ function fulfillSegmentCacheEntry(
// Free the promise for garbage collection.
fulfilledEntry.promise = null
}
pingBlockedTasks(segmentCacheEntry)
return fulfilledEntry
}
......@@ -1412,6 +1546,7 @@ function rejectSegmentCacheEntry(
entry.promise.resolve(null)
entry.promise = null
}
pingBlockedTasks(entry)
}
type RouteTreeAccumulator = {
......@@ -2366,6 +2501,17 @@ function writeSegmentBundleResponse(
// Null data means this segment has prefetching disabled. Skip it
// without creating a cache entry.
if (data === null || node.tree === null) {
// The server's and the client's prefetch-disabled hints normally agree,
// so there shouldn't be a spawned entry for a segment the server
// skipped. But if they disagree, a Pending entry that a task blocked on
// would otherwise never settle, stranding the task forever. Settle
// it defensively.
if (node.entry !== null && node.entry.status === EntryStatus.Pending) {
rejectSegmentCacheEntry(
node.entry as PendingSegmentCacheEntry,
now + 10 * 1000
)
}
node = node.parent
dataIndex++
continue
......@@ -2416,8 +2562,13 @@ function writeSegmentBundleResponse(
)
}
// Set the fulfilled entry into the canonical cache slot.
upsertSegmentEntry(now, canonicalVaryPath, fulfilled)
// Set the fulfilled entry into the canonical cache slot. Pass the
// concrete lookup path — the most specific path a read for this segment
// position would use — so that if the canonical path is more generic
// (i.e. the server re-keyed the segment), any stale settled entry at a
// more specific path (e.g. a partial shell entry) that would shadow this
// one is evicted. See evictShadowingSegmentEntries.
upsertSegmentEntry(now, canonicalVaryPath, fulfilled, node.tree.varyPath)
node = node.parent
dataIndex++
......@@ -3261,6 +3412,14 @@ function fulfillEntrySpawnedByRuntimePrefetch(
fulfilledEntry,
isRevalidation
)
// The re-key moved the entry to a more generic path (and, for a spawned
// revalidation, vacated its Revalidation slot). A stale settled entry
// at a more specific path — e.g. the partial entry that prompted the
// revalidation — would shadow every read at the concrete lookup path,
// causing the scheduler to keep re-reading the stale entry and respawn
// the revalidation forever. Evict it so the fulfilled entry is
// reachable. See evictShadowingSegmentEntries.
evictShadowingSegmentEntries(now, tree.varyPath, fulfilledEntry)
}
} else {
// There's no matching entry. Attempt to create a new one. This is a
......@@ -3291,6 +3450,12 @@ function fulfillEntrySpawnedByRuntimePrefetch(
fulfilledEntry,
isRevalidation
)
// Same as the owned-entry re-key above. Usually the entry really is
// new — the read a moment ago returned nothing at the concrete lookup
// path, so nothing can shadow it and this is a no-op — but this
// branch also claims a pre-existing Empty entry, and re-keying that
// away can expose a stale settled entry at an intermediate path.
evictShadowingSegmentEntries(now, tree.varyPath, fulfilledEntry)
}
} else {
// There was already an entry in the cache. But we may be able to
......@@ -3312,7 +3477,11 @@ function fulfillEntrySpawnedByRuntimePrefetch(
fulfilledVaryPath !== null
? fulfilledVaryPath
: getSegmentVaryPathForRequest(fetchStrategy, tree)
upsertSegmentEntry(now, varyPath, newEntry)
// Pass the concrete lookup path so that if the entry was re-keyed to
// a more generic path, any stale settled entry at a more specific path
// that would shadow it is evicted (the upsert handles this; the other
// branches above call evictShadowingSegmentEntries themselves).
upsertSegmentEntry(now, varyPath, newEntry, tree.varyPath)
}
}
}
......
......@@ -132,6 +132,20 @@ export type PrefetchTask = {
* They are reset after each iteration of the task queue.
*/
hasBackgroundWork: boolean
/**
* Set during a pass when the task spawned a segment request, or encountered
* one that was already in flight (a Pending entry) — i.e. a response the
* pass cares about but hasn't received yet. The task blocks instead of
* advancing, and is re-pinged as each awaited entry settles; see
* blockTaskOnPendingResponse for the full rationale. Each ping re-runs a
* full traversal for the task, so expect roughly one re-pass per settling
* entry. Re-runs don't re-spawn revalidations: when a completed
* revalidation was re-keyed, its upsert evicts any superseded entry that
* would shadow it (see upsertSegmentEntry in cache.ts), and when its upsert
* was declined, the settled entry left in the revalidation slot dedupes
* further attempts (see pingFullSegmentRevalidation).
*/
hasPendingResponses: boolean
spawnedRuntimePrefetches: Set<SegmentRequestKey> | null
/**
......@@ -193,10 +207,6 @@ const enum PrefetchTaskExitStatus {
/**
* The task is blocked. It needs more data before it can proceed.
*
* Currently the only reason this happens is we're still waiting to receive a
* route tree from the server, because we can't start prefetching the segments
* until we know what to prefetch.
*/
Blocked,
......@@ -307,6 +317,7 @@ export function schedulePrefetchTask(
priority,
phase: PrefetchPhase.RouteTree,
hasBackgroundWork: false,
hasPendingResponses: false,
spawnedRuntimePrefetches: null,
fetchStrategy,
sortId: sortIdCounter++,
......@@ -556,10 +567,13 @@ function processQueueInMicrotask() {
const exitStatus = pingRoute(now, task)
// These fields are only valid for a single attempt. Reset them after each
// iteration of the task queue.
// These fields are only valid for a single "pass" — one pingRoute
// invocation for a task, which is what the comments here also call an
// attempt or an iteration. Reset them after each iteration of the
// task queue.
const hasBackgroundWork = task.hasBackgroundWork
task.hasBackgroundWork = false
task.hasPendingResponses = false
task.spawnedRuntimePrefetches = null
switch (exitStatus) {
......@@ -598,7 +612,9 @@ function processQueueInMicrotask() {
: PrefetchPhase.Speculative
heapResift(taskHeap, task)
} else if (task.phase === PrefetchPhase.Shell) {
// Shell phase complete. Always advance to Speculative regardless
// Shell phase complete — a Done exit means the pass observed every
// response it cares about (otherwise it would have exited Blocked;
// see hasPendingResponses). Always advance to Speculative regardless
// of whether Shell-phase work fired — Speculative is responsible
// for the per-link concrete work and runs even on routes whose
// shell phase was a no-op.
......@@ -611,6 +627,16 @@ function processQueueInMicrotask() {
heapResift(taskHeap, task)
} else {
// The prefetch is complete. Continue to the next task.
//
// Completion is terminal in the normal flow: a task only completes
// after a full pass observed every response it cares about. In rare
// cases, though, a task can complete while still registered on an
// entry from an earlier pass whose subtree the final pass no longer
// reached; when that entry later settles, it re-pings the completed
// task. The re-run is a harmless idempotent no-op, but any
// per-completion side effect added here must be idempotent or
// once-guarded — in particular, the navigation-lock release below
// must not fire twice (hence the nulling).
if (
process.env.__NEXT_EXPOSE_TESTING_API &&
task._navigationLockPrefetch != null
......@@ -621,9 +647,19 @@ function processQueueInMicrotask() {
// count reaches 0 — i.e. every spawned entry has also fulfilled, so
// the navigation reads present data rather than a still-in-flight
// entry. If everything already fulfilled, it resolves synchronously.
//
// TODO: Now that a task only completes after a full pass observes
// every segment response it spawned or found in flight, the
// navigation-testing lock's per-entry ref counting (pendingCount /
// trackNavigationLockPrefetchEntry) is redundant — a single resolve
// fired here would suffice.
const { finishNavigationLockPrefetchSpawning } =
require('./navigation-testing-lock') as typeof import('./navigation-testing-lock')
finishNavigationLockPrefetchSpawning(task._navigationLockPrefetch)
// Release at most once per task: a stale registration from an
// earlier pass can re-ping a completed task (see above), so it can
// pass through here again.
task._navigationLockPrefetch = null
}
heapPop(taskHeap)
}
......@@ -713,6 +749,13 @@ function pingRoute(now: number, task: PrefetchTask): PrefetchTaskExitStatus {
}
}
if (exitStatus === PrefetchTaskExitStatus.Done && task.hasPendingResponses) {
// The pass traversed the whole tree, but some segment responses haven't
// arrived yet, so the current phase isn't actually complete. Block until
// they do (see blockTaskOnPendingResponse for the full rationale).
return PrefetchTaskExitStatus.Blocked
}
return exitStatus
}
......@@ -1404,17 +1447,18 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
// of a larger redesign of the request protocol.
// Add the pending cache entry to the result map.
spawnedEntries.set(
tree.requestKey,
upgradeToPendingSegment(
segment,
// Set the fetch strategy to LoadingBoundary to indicate that the server
// might not include it in the pending response. If another route is able
// to issue a per-segment request, we'll do that in the background.
FetchStrategy.LoadingBoundary,
task._navigationLockPrefetch ?? null
)
const pendingSegment = upgradeToPendingSegment(
segment,
// Set the fetch strategy to LoadingBoundary to indicate that the server
// might not include it in the pending response. If another route is able
// to issue a per-segment request, we'll do that in the background.
FetchStrategy.LoadingBoundary,
task._navigationLockPrefetch ?? null
)
spawnedEntries.set(tree.requestKey, pendingSegment)
// The pass blocks on every request it spawns, not just requests it
// finds already in flight.
blockTaskOnPendingResponse(task, pendingSegment)
if (refetchMarkerContext !== 'refetch') {
refetchMarker = refetchMarkerContext = 'refetch'
} else {
......@@ -1444,11 +1488,17 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
case EntryStatus.Pending: {
// There's another prefetch currently in progress. Don't add the refetch
// marker yet, so the server knows it can skip rendering this segment.
// The pass still depends on the in-flight response, so wait for it
// before the phase can complete.
blockTaskOnPendingResponse(task, segment)
break
}
case EntryStatus.Rejected: {
// The segment failed to load. We shouldn't issue another request until
// the stale time has elapsed.
// The segment failed to load, or the server intentionally omitted it
// from a response (both are encoded as Rejected). Skip it and keep
// prefetching the rest of the tree; the entry's staleAt governs when it
// may be retried. Don't register the task on the rejected entry —
// nothing ever pings a Rejected entry.
break
}
default:
......@@ -1480,6 +1530,39 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
return requestTree
}
/**
* Called during a pass when a segment's response hasn't been received yet —
* whether the request was just spawned by this pass or was already in flight.
* Marks the task as blocked: a phase only completes once a full pass observes
* every segment response it cares about, because later decisions (like
* whether a segment needs a follow-up runtime request) are made against the
* contents of those responses, and a phase may need to restart its work based
* on what they contain. The task is re-pinged (via pingBlockedTasks in
* cache.ts) when the entry resolves, re-running the pass against the
* received data. Only a pass that observes every response may advance the
* phase or complete the task.
*
* Never call this for an entry that's already Rejected — nothing ever pings
* a Rejected entry, so registering on one would strand the task. A rejected
* segment is simply skipped: the pass keeps prefetching the rest of the tree
* without it.
*/
function blockTaskOnPendingResponse(
task: PrefetchTask,
segment: { blockedTasks: Set<PrefetchTask> | null }
): void {
// This state is reset after each iteration of the task queue. We use it to
// inform the scheduler that the task is blocked.
task.hasPendingResponses = true
// Add the task to this segment's blocked tasks, so it can be rescheduled
// once the segment finishes loading.
if (segment.blockedTasks === null) {
segment.blockedTasks = new Set([task])
} else {
segment.blockedTasks.add(task)
}
}
function pingRouteTreeAndIncludeDynamicData(
now: number,
task: PrefetchTask,
......@@ -1588,11 +1671,36 @@ function pingRouteTreeAndIncludeDynamicData(
fetchStrategy
)
}
if (segment.status === EntryStatus.Pending) {
// A response for this segment is still in flight. The pass must
// observe it before the phase can complete.
blockTaskOnPendingResponse(task, segment)
} else {
// The segment failed to load, or the server intentionally omitted it
// from a response (both are encoded as Rejected). Skip it and keep
// prefetching the rest of the tree; the entry's staleAt governs when
// it may be retried. Don't register the task on the rejected entry —
// nothing ever pings a Rejected entry.
//
// TODO: The cache encodes real failures and intentional server
// omissions identically (both Rejected); with per-segment skipping
// this has no task-lifecycle consequence, but distinguishing them
// could still be useful someday.
}
break
}
default:
segment satisfies never
}
if (spawnedSegment !== null) {
// A pass must observe the response for every request it spawns before
// its phase can complete — not just requests it finds already in flight.
// Block on the entry we just spawned; the task is re-pinged when it's
// fulfilled or rejected.
blockTaskOnPendingResponse(task, spawnedSegment)
}
const requestTreeChildren: Record<string, FlightRouterState> = {}
if (tree.slots !== null) {
for (const [parallelRouteKey, childTree] of tree.slots) {
......@@ -1717,6 +1825,9 @@ function pingSegmentBundle(
task._navigationLockPrefetch ?? null
)
needsFetch = true
// The pass blocks on every request it spawns, not just requests it
// finds already in flight.
blockTaskOnPendingResponse(task, nodeEntry)
break
case EntryStatus.Pending:
if (
......@@ -1738,12 +1849,16 @@ function pingSegmentBundle(
)
node.entry = revalidatingEntry
needsFetch = true
// Block on the revalidation request we just spawned, in
// addition to the original in-flight entry (blocked below).
blockTaskOnPendingResponse(task, revalidatingEntry)
} else {
node.entry = null
}
} else {
node.entry = null
}
blockTaskOnPendingResponse(task, nodeEntry)
break
case EntryStatus.Rejected:
if (
......@@ -1765,12 +1880,24 @@ function pingSegmentBundle(
)
node.entry = revalidatingEntry
needsFetch = true
// Block on the retry revalidation we just spawned, like any
// other pending response. If the retry succeeds, its upsert
// evicts the rejected entry (see evictShadowingSegmentEntries
// in cache.ts) and the re-run pass reads the healed data. If it
// rejects too, the re-run observes a settled revalidation and
// moves on.
blockTaskOnPendingResponse(task, revalidatingEntry)
} else {
node.entry = null
}
} else {
node.entry = null
}
// The segment failed to load, or the server intentionally omitted it
// from a response (both are encoded as Rejected). Skip it and keep
// prefetching the rest of the bundle; the entry's staleAt governs
// when it may be retried. Don't register the task on the rejected
// entry itself — nothing ever pings a Rejected entry.
break
case EntryStatus.Fulfilled: {
// For shell entries (less specific than PPR), upgrade during the
......@@ -1814,12 +1941,23 @@ function pingSegmentBundle(
)
node.entry = revalidatingEntry
needsFetch = true
// The pass blocks on every request it spawns, including
// revalidations of an already-fulfilled entry.
blockTaskOnPendingResponse(task, revalidatingEntry)
} else {
// A non-empty revalidating entry means a request is already in
// flight (or recently settled), so we dedupe and don't issue a
// competing one — including for ISR-fallback upgrades, which then
// share the same revalidation across tasks.
node.entry = null
if (revalidatingEntry.status === EntryStatus.Pending) {
// The deduped-against revalidation is still in flight, and this
// pass depends on its response. Wait for it before the phase
// can complete. (A settled revalidation we chose not to use
// needs no waiting and is not a prefetch failure — the base
// entry here is already Fulfilled.)
blockTaskOnPendingResponse(task, revalidatingEntry)
}
}
} else {
node.entry = null
......@@ -2015,6 +2153,9 @@ function pingFullSegmentRevalidation(
switch (nonEmptyRevalidatingSegment.status) {
case EntryStatus.Pending:
// There's already an in-progress prefetch that includes this segment.
// The pass needs the contents of that response, too. Wait for it
// before the phase can complete.
blockTaskOnPendingResponse(task, nonEmptyRevalidatingSegment)
return null
case EntryStatus.Fulfilled:
case EntryStatus.Rejected:
......
......@@ -6,23 +6,25 @@ import { equals } from '@jest/expect-utils'
// prefetches carry the value '3' (FetchStrategy.RuntimeShell). The App Shell is
// the param/searchParam-independent chrome of a route — conceptually part of the
// route itself, not prefetch data in the way we normally think of it. By default
// we therefore exclude App Shell requests from all `act` assertion logic
// (`includes` matching, `no-requests`, `block: 'reject'`, and the "at least one
// request" check). They are still intercepted, fulfilled, and awaited so that the
// browser caches the shell and no requests are left in flight. Pass
// `includeAppShellRequests: true` to `createRouterAct` to assert on them directly
// (e.g. when testing App Shell behavior specifically).
// we therefore exclude App Shell requests from `act` assertion logic
// (`includes` matching, `no-requests`, and `block: 'reject'`). They are still
// intercepted, fulfilled, and awaited so that the browser caches the shell and
// no requests are left in flight — and they do satisfy the "at least one
// request" check, since they prove the router reacted to the scope. Pass
// `includeAppShellRequests: true` to `createRouterAct` to assert on them
// directly (e.g. when testing App Shell behavior specifically).
const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch'
const APP_SHELL_PREFETCH_VALUE = '3'
type Batch = {
pendingRequestChecks: Set<Promise<void>>
pendingRequests: Set<PendingRSCRequest>
// The number of pending requests in `pendingRequests` that are NOT App Shell
// requests. App Shell requests don't count toward the "at least one request"
// check, so we track this separately rather than scanning the set. Maintained
// in lockstep with `pendingRequests` membership.
pendingNonAppShellRequests: number
// Whether any router request — including an App Shell request — was
// received by this batch. Used by the "at least one request" watchdog:
// any router request proves the router reacted to the `act` scope, even
// ones that are excluded from the assertion logic. Also set when an inner
// `act`'s blocked responses are transferred to this batch.
didReceiveRouterRequest: boolean
}
type PendingRSCRequest = {
......@@ -98,6 +100,41 @@ export function createRouterAct(
}
): <T>(scope: () => Promise<T> | T, config?: ActConfig) => Promise<T> {
const includeAppShellRequests = options?.includeAppShellRequests ?? false
// Track App Shell requests that are currently in flight anywhere on the
// page — including ones initiated outside an `act` scope, like viewport
// prefetches during the initial page load. The "at least one request"
// watchdog consults this set: the prefetch scheduler's Shell phase does not
// complete until its shell responses have arrived, so while a shell request
// is in flight, follow-up requests (which ARE countable) may be
// legitimately waiting on it. In that case the watchdog keeps waiting
// instead of timing out. See the watchdog logic inside `act`.
const inFlightAppShellRequests = new Set<Playwright.Request>()
const onRequestStarted = (request: Playwright.Request) => {
if (
request.headers()[NEXT_ROUTER_PREFETCH_HEADER] ===
APP_SHELL_PREFETCH_VALUE
) {
inFlightAppShellRequests.add(request)
}
}
const onRequestSettled = (request: Playwright.Request) => {
inFlightAppShellRequests.delete(request)
}
// A hard navigation can orphan in-flight requests: Playwright doesn't
// reliably emit `requestfinished`/`requestfailed` for requests aborted by
// page teardown, which would leave stale entries in the set for the rest
// of the test — and a stale entry keeps the watchdog alive forever,
// turning what should be a clean timeout error into a hang. The destroyed
// document's shell requests can't gate anything anymore, and the new
// document's requests re-add themselves, so drop them all.
const onFrameDetached = () => {
inFlightAppShellRequests.clear()
}
page.on('request', onRequestStarted)
page.on('requestfinished', onRequestSettled)
page.on('requestfailed', onRequestSettled)
page.on('framedetached', onFrameDetached)
/**
* Helper function to wait for requestIdleCallback with retry logic.
* Retries up to 3 times if "Execution context was destroyed" error occurs.
......@@ -296,14 +333,14 @@ export function createRouterAct(
})(),
didProcess: false,
})
// App Shell requests don't count toward the "at least one request"
// check, so only track and signal for non-App-Shell requests.
if (!isAppShell) {
batch.pendingNonAppShellRequests++
if (onDidIssueFirstRequest !== null) {
onDidIssueFirstRequest()
onDidIssueFirstRequest = null
}
// Any router request — including an App Shell request, which is
// otherwise excluded from assertion logic — satisfies the "at least
// one request" watchdog, since it proves the router reacted to the
// `act` scope.
batch.didReceiveRouterRequest = true
if (onDidIssueFirstRequest !== null) {
onDidIssueFirstRequest()
onDidIssueFirstRequest = null
}
return
}
......@@ -327,7 +364,7 @@ export function createRouterAct(
const orphanedRequests = batch.pendingRequests
batch.pendingRequests = new Set()
batch.pendingRequestChecks = new Set()
batch.pendingNonAppShellRequests = 0
batch.didReceiveRouterRequest = false
await Promise.all(
Array.from(orphanedRequests).map((item) => item.route?.continue())
)
......@@ -345,7 +382,7 @@ export function createRouterAct(
const batch: Batch = {
pendingRequestChecks: new Set(),
pendingRequests: new Set(),
pendingNonAppShellRequests: 0,
didReceiveRouterRequest: false,
}
currentBatch = batch
await page.route('**/*', routeHandler)
......@@ -354,17 +391,26 @@ export function createRouterAct(
// Call the user-provided scope function
const returnValue = await scope()
// Wait until the first request is initiated, up to some timeout. App Shell
// requests don't count, so check the non-App-Shell pending request count.
if (
expectedResponses !== null &&
batch.pendingNonAppShellRequests === 0
) {
// Wait until the first request is initiated, up to some timeout.
if (expectedResponses !== null && !batch.didReceiveRouterRequest) {
await new Promise<void>((resolve, reject) => {
const timerId = setTimeout(() => {
let timerId: ReturnType<typeof setTimeout>
const onExpiry = () => {
// Before timing out, check for App Shell requests in flight
// elsewhere on the page (e.g. spawned by a viewport prefetch
// during page load, before this `act` scope began, so it was
// never intercepted here). The prefetch scheduler's Shell phase
// doesn't complete until its shell responses arrive, so the
// first observable request may be legitimately gated on one.
// Keep the watchdog alive until it settles.
if (inFlightAppShellRequests.size > 0) {
timerId = setTimeout(onExpiry, 500)
return
}
error.message = 'Timed out waiting for a request to be initiated.'
reject(error)
}, 500)
}
timerId = setTimeout(onExpiry, 500)
onDidIssueFirstRequest = () => {
clearTimeout(timerId)
resolve()
......@@ -402,14 +448,6 @@ export function createRouterAct(
const route = item.route
const url = item.url
// This request is being removed from `pendingRequests` for
// processing. Keep the non-App-Shell counter in lockstep. (If it ends
// up blocked and transferred to the outer batch, that batch's counter
// is incremented when the transfer happens, below.)
if (!item.isAppShell) {
batch.pendingNonAppShellRequests--
}
let shouldBlock = false
const fulfilled = await item.result
if (item.didProcess) {
......@@ -606,9 +644,7 @@ ${fulfilled.body}
// Shell prefetch.
isAppShell: false,
})
// Keep the counter in lockstep with the add above (drained
// and decremented on the next iteration of the while loop).
batch.pendingNonAppShellRequests++
batch.didReceiveRouterRequest = true
page.off('response', handleResponse)
page.off('requestfailed', handleFailure)
resolve()
......@@ -681,10 +717,10 @@ ${fulfilled.body}
if (remaining.size !== 0 && prevBatch !== null) {
for (const item of remaining) {
prevBatch.pendingRequests.add(item)
if (!item.isAppShell) {
prevBatch.pendingNonAppShellRequests++
}
}
// The outer batch inherits pending work, so its "at least one
// request" check is satisfied.
prevBatch.didReceiveRouterRequest = true
}
return returnValue
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment