# Flaky Test Investigation: prefetch-runtime.test.ts
## Summary
The test file `test/e2e/app-dir/segment-cache/prefetch-runtime/prefetch-runtime.test.ts` has multiple flaky tests. The root cause appears to be **React's internal scheduler not preserving Node.js AsyncLocalStorage context** when continuing rendering after promise resolution.
## Key Finding: AsyncLocalStorage Context Loss
### The Problem
When a component awaits a runtime API (like `params`, `searchParams`, `cookies()`, etc.) and then calls sync IO like `Date.now()`, the sync IO detection mechanism fails because the AsyncLocalStorage context is lost.
**Debug output showing the issue:**
```
[io] called with expression: `Date.now()` workUnitStore: undefined workStore: false
[io] called with expression: `Date.now()` workUnitStore: undefined workStore: false
...
```
The `workUnitStore` is `undefined` when `Date.now()` is called, meaning the async context was lost.
When `advanceStage()` resolves the `runtimeStagePromise`:
1. Promise `.then()` callbacks are queued as **microtasks**
2. But all three `setTimeout` callbacks run in the same timer phase
3. Microtasks run **after** all timer callbacks complete
4. So Task 3 checks the abort signal **before** React continues rendering
I tried adding `queueMicrotask()` delays before the abort check, but it didn't fully fix the issue because the AsyncLocalStorage context is still lost when React's scheduler continues the render.
// when continuing rendering after a promise resolves. When params resolve and
// the component calls Date.now(), the io() function can't access the workUnitStore
// because the async context is lost, so no abort is triggered.
```
## Reproduction Steps
1. Run the test in isolation:
```bash
pnpm test-start test/e2e/app-dir/segment-cache/prefetch-runtime/prefetch-runtime.test.ts --testNamePattern="aborts the prerender without logging an error when sync IO is used after awaiting dynamic params"
```
2. Add debug logging to `io()` function to see context loss:
```typescript
console.log(
'[io] workUnitStore:',
workUnitStore?.type,
'workStore:',
!!workStore
)
```
3. The test will fail with "Timed out waiting for a request to be initiated"
## Related Issues
This is likely related to:
- React's async rendering and microtask scheduling
- Node.js AsyncLocalStorage not being preserved across certain async boundaries
- The interaction between React's Suspense/streaming and server-side async context
## Broader Flakiness: Multiple Test Files Affected
The flakiness is not limited to `prefetch-runtime.test.ts`. Other tests using `router-act.ts` are also affected:
**Key Finding:** The `bindSnapshot` fix **DOES** preserve context for the `.then()` callback, but by the time React's scheduler continues the component and calls `Date.now()`, the context is already lost.
### The Real Issue: React's Scheduler
The sequence of events:
1. Component calls `await params`
2. `delayUntilRuntimeStage` creates a chained promise with bound context
This confirms the root cause is AsyncLocalStorage context loss through React's scheduler.
### Correct Solutions for Next.js
1. **Use `AsyncLocalStorage.snapshot()` in React**: React would need to capture the FULL async context using Node.js's `AsyncLocalStorage.snapshot()` (not just its own `requestStorage.run()`), then restore it when continuing work. This requires React core changes.
2. **Track at API access time**: Mark the render as dynamic when runtime APIs are first accessed, not when sync IO is detected later:
```typescript
export function delayUntilRuntimeStage<T>(
prerenderStore: PrerenderStoreModernRuntime,
result: Promise<T>
): Promise<T> {
if (prerenderStore.runtimeStagePromise) {
// Mark as dynamic immediately when runtime API is accessed
prerenderStore.markAsDynamic() // <-- New approach
3.**Alternative detection that doesn't rely on AsyncLocalStorage**: Use a different mechanism to track dynamic content that survives React's scheduler.