Skip to content

fix(instrumentation): await ensureInstrumentationRegistered in RouteModule.prepare - #93994

Closed
mgm1313 wants to merge 8 commits into
vercel:canaryfrom
mgm1313:mgm1313/fix-route-module-prepare-await-instrumentation
Closed

mgm1313 wants to merge 8 commits into
vercel:canaryfrom
mgm1313:mgm1313/fix-route-module-prepare-await-instrumentation

Conversation

@mgm1313

@mgm1313 mgm1313 commented May 20, 2026

Copy link
Copy Markdown
Contributor

The per-request call to ensureInstrumentationRegistered() inside RouteModule.prepare was missing an await, so when an adapter dispatches the compiled app-route template's handler without going through BaseServer.handleRequest (where prepareImpl awaits it via runInstrumentationHookIfAvailable), a cold-start request could begin executing the userland route handler before instrumentation.ts#register() resolved. The other two call sites (next-server.ts and web/adapter.ts) already await; this aligns the third.

The function memoizes a single promise per process, so the added await is a microtask no-op on every request after the first cold start.

Adds a with-async-node-app-route mirror of the existing with-async-node-page case to lock in the invariant for app-route handlers.

What?

RouteModule.prepare calls ensureInstrumentationRegistered(...) from lib/router-utils/instrumentation-globals.external without awaiting it. This PR adds the missing await so that adapters which dispatch the compiled app-route.ts template's handler directly (bypassing BaseServer.handleRequest) still observe instrumentation.ts#register() resolving before the userland route handler runs.

Why?

The ensureInstrumentationRegistered helper is awaited from the other two call sites:

Path File Awaited
Classic Node server packages/next/src/server/next-server.ts:373 (via BaseServer.handleRequest → prepareImpl) ✅
Edge adapter packages/next/src/server/web/adapter.ts:114 ✅
App Router per-request packages/next/src/server/route-modules/route-module.ts:674 ❌ (before this PR)

When an adapter invokes the compiled app-route template's handler directly (e.g. on a freshly cold-started Vercel serverless function under concurrent burst load) the RouteModule.prepare path is the only chance to register. The unawaited call lets the userland POST handler begin executing before register() finishes its top-level await import(...) chain. Module-scoped state that register() is supposed to populate (OTel patches, app-bootstrap globals, DB pools) reads as null/undefined on the first request; retries on the now-warm lambda succeed.

The function memoizes a single promise per process, so the added await is a microtask no-op on every request after the first cold start.

How?

One-line await added at the call site. Adds with-async-node-app-route, mirroring the existing with-async-node-page regression case: register() sleeps 1000ms and sets globalThis.instrumentationFinished; the app-route handler reads it and asserts { finished: true }.

Note on test coverage: under next start the request still enters via BaseServer.handleRequest, which already awaits prepare(), so the new test passes both before and after this change. It documents the intended invariant for the App Router route-handler path and locks it in against future regressions. A test that fails-without-fix would require exercising an adapter-level dispatch path (e.g. Vercel's @vercel/next) that bypasses BaseServer, which isn't covered by the existing test infrastructure.

Repro: https://github.com/mgm1313/next-instrumentation-race-repro

Fixes #93993

@mgm1313
mgm1313 force-pushed the mgm1313/fix-route-module-prepare-await-instrumentation branch from 0d4b713 to 2eca35a Compare May 20, 2026 21:23
…odule.prepare

The per-request call to ensureInstrumentationRegistered() inside
RouteModule.prepare was missing an await, so when an adapter dispatches
the compiled app-route template's handler without going through
BaseServer.handleRequest (where prepareImpl awaits it via
runInstrumentationHookIfAvailable), a cold-start request could begin
executing the userland route handler before instrumentation.ts#register()
resolved. The other two call sites (next-server.ts and web/adapter.ts)
already await; this aligns the third.

The function memoizes a single promise per process, so the added await
is a microtask no-op on every request after the first cold start.

Adds a with-async-node-app-route mirror of the existing
with-async-node-page case to lock in the invariant for app-route
handlers.
@mgm1313
mgm1313 force-pushed the mgm1313/fix-route-module-prepare-await-instrumentation branch from 2eca35a to 9d3cef9 Compare May 20, 2026 21:30
@mgm1313

mgm1313 commented May 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, @timneutkens. I looked into this a bit more and decided not to bump the sleep to 5s for now.

The existing next start request-based test can still pass without this fix, because that path already goes through BaseServer.prepareImpl(), which awaits instrumentation earlier. So increasing the timeout would make the test slower, but it still would not prove this specific RouteModule.prepare() await is needed I believe.

Instead I added a next start-only regression test that imports the built app-route module from .next/server/app/api/check/route.js and invokes its exported handler directly. That bypasses the BaseServer preparation path and exercises the route-module path this change fixes. Locally, this new test fails without the await (finished: false) and passes with it.

I used the direct compiled-handler pattern from cache-components.test.ts as precedent.

@timneutkens timneutkens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll take over getting this PR merged 🙏

@mgm1313

mgm1313 commented May 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for taking this over, @timneutkens 🙏

That makes sense. I went down the direct-handler route mostly because I was struggling to make the local next start test fail without the fix: that path seems to go through BaseServer.prepareImpl(), which already awaits instrumentation earlier, so it kept passing before and after the change. The direct import was just my attempt to isolate the RouteModule.prepare() path and prove the missing await mattered locally.

Appreciate you taking it from here.

@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Stats skipped

Commit: 2d29e2e
View workflow run

@github-actions

github-actions Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Failing test suites

Commit: 2d29e2e | About building and testing Next.js

pnpm test-deploy test/e2e/instrumentation-hook/instrumentation-hook.test.ts (job)

  • Instrumentation Hook > with-async-node-app-route > with-async-node-app-route should run the instrumentation hook before the app-route handler (DD)
Expand output

● Instrumentation Hook › with-async-node-app-route › with-async-node-app-route should run the instrumentation hook before the app-route handler

Failed to link project  Vercel CLI 54.6.1 (Node.js 20.9.0)
> NOTE: The Vercel CLI now collects telemetry regarding usage of the CLI.
> This information is used to shape the CLI roadmap and prioritize features.
> You can learn more, including how to opt-out if you'd not like to participate in this program, by visiting the following URL:
> https://vercel.com/docs/cli/about-telemetry
Error: No existing credentials found. Please run `vercel login` or pass "--token"
Learn More: https://err.sh/vercel/no-credentials-found (1)

  343 |
  344 |     if (linkRes.exitCode !== 0) {
> 345 |       throw new Error(
      |             ^
  346 |         `Failed to link project ${linkRes.stdout} ${linkRes.stderr} (${linkRes.exitCode})`
  347 |       )
  348 |     }

  at NextDeployInstance.setup (lib/next-modes/next-deploy.ts:345:13)
  at lib/e2e-utils/index.ts:289:7
  at Span.traceAsyncFn (../packages/next/src/trace/trace.ts:146:14)
  at createNext (lib/e2e-utils/index.ts:254:12)
  at Object.<anonymous> (lib/e2e-utils/index.ts:344:14)

pnpm test-deploy test/e2e/instrumentation-hook/instrumentation-hook.test.ts (job)

  • Instrumentation Hook > with-async-node-app-route > with-async-node-app-route should run the instrumentation hook before the app-route handler (DD)
Expand output

● Instrumentation Hook › with-async-node-app-route › with-async-node-app-route should run the instrumentation hook before the app-route handler

Failed to link project  Vercel CLI 54.6.1 (Node.js 20.9.0)
> NOTE: The Vercel CLI now collects telemetry regarding usage of the CLI.
> This information is used to shape the CLI roadmap and prioritize features.
> You can learn more, including how to opt-out if you'd not like to participate in this program, by visiting the following URL:
> https://vercel.com/docs/cli/about-telemetry
Error: No existing credentials found. Please run `vercel login` or pass "--token"
Learn More: https://err.sh/vercel/no-credentials-found (1)

  343 |
  344 |     if (linkRes.exitCode !== 0) {
> 345 |       throw new Error(
      |             ^
  346 |         `Failed to link project ${linkRes.stdout} ${linkRes.stderr} (${linkRes.exitCode})`
  347 |       )
  348 |     }

  at NextDeployInstance.setup (lib/next-modes/next-deploy.ts:345:13)
  at lib/e2e-utils/index.ts:289:7
  at Span.traceAsyncFn (../packages/next/src/trace/trace.ts:146:14)
  at createNext (lib/e2e-utils/index.ts:254:12)
  at Object.<anonymous> (lib/e2e-utils/index.ts:344:14)

@mischnic

mischnic commented Jun 1, 2026

Copy link
Copy Markdown
Member

Unfortunately, our tests currently need some secrets to run deploy tests, and those are not available on external PRs, so CI will always fail here.
I've recreated this PR with the commits here: #94306

timneutkens added a commit that referenced this pull request Jun 1, 2026
…94306)

Closes #93994
Unfortunately deploy tests can't pass on external PRs like #93994
currently due to missing secrets

----


The per-request call to ensureInstrumentationRegistered() inside
RouteModule.prepare was missing an await, so when an adapter dispatches
the compiled app-route template's handler without going through
BaseServer.handleRequest (where prepareImpl awaits it via
runInstrumentationHookIfAvailable), a cold-start request could begin
executing the userland route handler before
instrumentation.ts#register() resolved. The other two call sites
(next-server.ts and web/adapter.ts) already await; this aligns the
third.

This only caused a problem with adapters

---------

Co-authored-by: Maurits Misana <[email protected]>
Co-authored-by: Tim Neutkens <[email protected]>
@mgm1313
mgm1313 deleted the mgm1313/fix-route-module-prepare-await-instrumentation branch June 1, 2026 15:20
m-kawafuji pushed a commit to m-kawafuji/next.js that referenced this pull request Aug 8, 2026
…ercel#94306)

Closes vercel#93994
Unfortunately deploy tests can't pass on external PRs like vercel#93994
currently due to missing secrets

----


The per-request call to ensureInstrumentationRegistered() inside
RouteModule.prepare was missing an await, so when an adapter dispatches
the compiled app-route template's handler without going through
BaseServer.handleRequest (where prepareImpl awaits it via
runInstrumentationHookIfAvailable), a cold-start request could begin
executing the userland route handler before
instrumentation.ts#register() resolved. The other two call sites
(next-server.ts and web/adapter.ts) already await; this aligns the
third.

This only caused a problem with adapters

---------

Co-authored-by: Maurits Misana <[email protected]>
Co-authored-by: Tim Neutkens <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RouteModule.prepare doesn't await ensureInstrumentationRegistered

3 participants