🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): recover and group stale Next.js chunk load failures (#17441)
cursor[bot]2a018f0b15ca
diff --git a/web/instrumentation-client.ts b/web/instrumentation-client.tsindex 93a5ac4caf..e5ff6bcf28 100644--- a/web/instrumentation-client.ts+++ b/web/instrumentation-client.ts@@ -6,7 +6,9 @@ import {isNoisyHttpClientPollEvent,isPosthogRecorderInternalEvent,isReactDevtoolsInternalEvent,+ isStaleChunkLoadErrorEvent,isStaleChunkParseErrorEvent,+ STALE_CHUNK_LOAD_FINGERPRINT,STALE_CHUNK_PARSE_FINGERPRINT,} from "@/src/utils/sentryFilters";import { applyCachedV4BetaEnabledSentryTag } from "@/src/utils/sentryV4BetaTag";@@ -82,6 +84,14 @@ Sentry.init({event.fingerprint = [STALE_CHUNK_PARSE_FINGERPRINT];}+ // Stale-deploy / CDN chunk LOAD failures (script.onerror, dynamic+ // import()): collapse into ONE issue instead of one per content-hashed+ // filename. Grouped, not dropped — same posture as parse errors. See+ // isStaleChunkLoadErrorEvent.+ if (isStaleChunkLoadErrorEvent(event)) {+ event.fingerprint = [STALE_CHUNK_LOAD_FINGERPRINT];+ }+return event;},diff --git a/web/src/components/CrashModal/CrashModal.tsx b/web/src/components/CrashModal/CrashModal.tsxindex 5b488b45e3..9c57bc5e45 100644--- a/web/src/components/CrashModal/CrashModal.tsx+++ b/web/src/components/CrashModal/CrashModal.tsx@@ -49,10 +49,17 @@ export const CrashModal = ({</div>) : null}- {showReturnHome ? (- <Button asChild className="mt-6">- <Link href="/">Return home</Link>- </Button>+ {!statusCode || showReturnHome ? (+ <div className="mt-6 flex flex-wrap gap-3">+ {!statusCode ? (+ <Button onClick={() => window.location.reload()}>Reload</Button>+ ) : null}+ {showReturnHome ? (+ <Button asChild variant={!statusCode ? "secondary" : "default"}>+ <Link href="/">Return home</Link>+ </Button>+ ) : null}+ </div>) : null}</div></div>diff --git a/web/src/features/version-update/reloadOnStaleChunk.clienttest.ts b/web/src/features/version-update/reloadOnStaleChunk.clienttest.tsnew file mode 100644index 0000000000..9fa9f15a98--- /dev/null+++ b/web/src/features/version-update/reloadOnStaleChunk.clienttest.ts@@ -0,0 +1,85 @@+// @vitest-environment jsdom++import {+ handleStaleChunkScriptError,+ isStaleNextScriptElement,+ STALE_CHUNK_RELOAD_SESSION_KEY,+} from "@/src/features/version-update/reloadOnStaleChunk";++const NEXT_CHUNK =+ "https://us.cloud.langfuse.com/_next/static/chunks/31w9e6884-o68.js";++function scriptErrorEvent(src: string): Event {+ const script = document.createElement("script");+ script.src = src;+ const event = new Event("error");+ Object.defineProperty(event, "target", { value: script });+ return event;+}++describe("isStaleNextScriptElement", () => {+ it("matches a Next.js static chunk script", () => {+ const script = document.createElement("script");+ script.src = NEXT_CHUNK;+ expect(isStaleNextScriptElement(script)).toBe(true);+ });++ it("rejects a third-party script", () => {+ const script = document.createElement("script");+ script.src = "https://cdn.example.com/vendor.js";+ expect(isStaleNextScriptElement(script)).toBe(false);+ });++ it("rejects a stylesheet or missing target", () => {+ const link = document.createElement("link");+ link.href = "https://us.cloud.langfuse.com/_next/static/chunks/app.css";+ expect(isStaleNextScriptElement(link)).toBe(false);+ expect(isStaleNextScriptElement(null)).toBe(false);+ });+});++describe("handleStaleChunkScriptError", () => {+ const reload = vi.fn();+ const mismatch = () => true;++ beforeEach(() => {+ reload.mockReset();+ sessionStorage.clear();+ Object.defineProperty(window, "location", {+ configurable: true,+ value: { reload },+ });+ });++ afterEach(() => {+ sessionStorage.clear();+ });++ it("reloads once when a Next chunk fails after a version mismatch", () => {+ handleStaleChunkScriptError(scriptErrorEvent(NEXT_CHUNK), mismatch);+ expect(reload).toHaveBeenCalledTimes(1);+ expect(sessionStorage.getItem(STALE_CHUNK_RELOAD_SESSION_KEY)).toBe("1");+ });++ it("does not reload a second time in the same session", () => {+ const event = scriptErrorEvent(NEXT_CHUNK);+ handleStaleChunkScriptError(event, mismatch);+ handleStaleChunkScriptError(event, mismatch);+ expect(reload).toHaveBeenCalledTimes(1);+ });++ it("does not reload without an observed version mismatch", () => {+ handleStaleChunkScriptError(scriptErrorEvent(NEXT_CHUNK), () => false);+ expect(reload).not.toHaveBeenCalled();+ expect(sessionStorage.getItem(STALE_CHUNK_RELOAD_SESSION_KEY)).toBeNull();+ });++ it("does not reload a third-party script failure", () => {+ handleStaleChunkScriptError(+ scriptErrorEvent("https://cdn.example.com/vendor.js"),+ mismatch,+ );+ expect(reload).not.toHaveBeenCalled();+ expect(sessionStorage.getItem(STALE_CHUNK_RELOAD_SESSION_KEY)).toBeNull();+ });+});diff --git a/web/src/features/version-update/reloadOnStaleChunk.ts b/web/src/features/version-update/reloadOnStaleChunk.tsnew file mode 100644index 0000000000..5230cc7d34--- /dev/null+++ b/web/src/features/version-update/reloadOnStaleChunk.ts@@ -0,0 +1,50 @@+/**+ * One-shot hard reload when a Next.js static chunk script fails to load on a+ * tab that has already observed a newer build.+ *+ * Long-lived tabs keep a superseded bundle after a deploy; the next+ * code-split navigation 404s a content-hashed `/_next/static/` script and+ * Next.js then `console.error`s `Error rendering page:`. The version-update+ * banner is the prompt for a still-working tab; this listener recovers a tab+ * that already crashed. Reload is gated on+ * {@link versionUpdateStore.hasObservedVersionMismatch} so a transient CDN+ * blip or lazy-chunk hiccup on a current-build tab is not force-reloaded.+ * Never loops: sessionStorage records the attempt, and a storage failure+ * skips the reload rather than retrying.+ */++import { versionUpdateStore } from "./versionUpdateStore";++export const STALE_CHUNK_RELOAD_SESSION_KEY = "langfuse:stale-chunk-reloaded";++const NEXT_STATIC_PATH = "/_next/static/";++let installed = false;++export function isStaleNextScriptElement(target: EventTarget | null): boolean {+ return (+ target instanceof HTMLScriptElement && target.src.includes(NEXT_STATIC_PATH)+ );+}++export function handleStaleChunkScriptError(+ event: Event,+ hasObservedVersionMismatch: () => boolean = () =>+ versionUpdateStore.hasObservedVersionMismatch(),+): void {+ if (!isStaleNextScriptElement(event.target)) return;+ if (!hasObservedVersionMismatch()) return;+ try {+ if (sessionStorage.getItem(STALE_CHUNK_RELOAD_SESSION_KEY)) return;+ sessionStorage.setItem(STALE_CHUNK_RELOAD_SESSION_KEY, "1");+ } catch {+ return;+ }+ window.location.reload();+}++export function installStaleChunkReloadListener(): void {+ if (typeof window === "undefined" || installed) return;+ installed = true;+ window.addEventListener("error", handleStaleChunkScriptError, true);+}diff --git a/web/src/features/version-update/versionUpdateStore.clienttest.ts b/web/src/features/version-update/versionUpdateStore.clienttest.tsindex 9216083c47..5b698270a2 100644--- a/web/src/features/version-update/versionUpdateStore.clienttest.ts+++ b/web/src/features/version-update/versionUpdateStore.clienttest.ts@@ -51,11 +51,26 @@ describe("versionUpdateStore", () => {expect(store.getSnapshot()).toBe(false);store.reportObservedBuildId("deployed");expect(store.getSnapshot()).toBe(true);+ expect(store.hasObservedVersionMismatch()).toBe(true);// Unknown running build (self-hosted without a build id) proves nothing.const unknown = createVersionUpdateStore(() => undefined, mechanics);unknown.reportObservedBuildId("deployed");expect(unknown.getSnapshot()).toBe(false);+ expect(unknown.hasObservedVersionMismatch()).toBe(false);+ });++ it("hasObservedVersionMismatch is independent of banner 48 h / debounce gates", () => {+ const store = createVersionUpdateStore(() => "running", {+ debounceMs: 0,+ minStalenessMs: VERSION_UPDATE_MIN_STALENESS_MS,+ getStorage: noStorage,+ now: () => 0,+ });+ expect(store.hasObservedVersionMismatch()).toBe(false);+ store.reportObservedBuildId("deployed");+ expect(store.getSnapshot()).toBe(false);+ expect(store.hasObservedVersionMismatch()).toBe(true);});it("is sticky and flap-free while rolling-deploy pods serve mixed responses", () => {diff --git a/web/src/features/version-update/versionUpdateStore.ts b/web/src/features/version-update/versionUpdateStore.tsindex 87c50d23a1..29b510f05d 100644--- a/web/src/features/version-update/versionUpdateStore.ts+++ b/web/src/features/version-update/versionUpdateStore.ts@@ -47,6 +47,12 @@ export type VersionUpdateStore = {getServerSnapshot: () => boolean;/** Feed a build id from a server response; safe on every response, any value. */reportObservedBuildId: (observedBuildId: string | null | undefined) => void;+ /**+ * True once this tab has seen a build id that differs from the running+ * bundle. Independent of the banner's 48 h / debounce / dismiss gates —+ * those withhold a *prompt*, not the fact of supersession.+ */+ hasObservedVersionMismatch: () => boolean;/** Hide until a never-seen build id arrives; persists the 24 h suppression. */dismiss: () => void;/**@@ -231,6 +237,9 @@ export function createVersionUpdateStore(// Responses are the clock ticks that mature staleness / expire windows.emitChange();},+ hasObservedVersionMismatch() {+ return updateAvailable;+ },dismiss() {dismissed = true;writeTimestamp(diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex 1a5181ef21..8dc1a3bff4 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -49,6 +49,8 @@ import "streamdown/styles.css";// See: https://github.com/facebook/react/issues/11538// See also: https://issues.chromium.org/issues/41407169if (typeof window !== "undefined") {+ installStaleChunkReloadListener();+const originalRemoveChild = Element.prototype.removeChild;const originalInsertBefore = Element.prototype.insertBefore;@@ -88,6 +90,7 @@ import { ThemeProvider } from "@/src/features/theming/ThemeProvider";import { MarkdownRenderCharacterLimitProvider } from "@/src/hooks/useMarkdownRenderCharacterLimit";import { SupportDrawerProvider } from "@/src/features/support-chat/SupportDrawerProvider";import { V4MigrationPanelProvider } from "@/src/features/v4-migration/V4MigrationPanelProvider";+import { installStaleChunkReloadListener } from "@/src/features/version-update/reloadOnStaleChunk";import { InAppAiAgentProvider } from "@/src/features/in-app-agent/components/InAppAiAgentProvider";import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";import { ScoreCacheProvider } from "@/src/features/scores/contexts/ScoreCacheContext";diff --git a/web/src/utils/sentryFilters.clienttest.ts b/web/src/utils/sentryFilters.clienttest.tsindex 85989932a0..267b58caef 100644--- a/web/src/utils/sentryFilters.clienttest.ts+++ b/web/src/utils/sentryFilters.clienttest.ts@@ -7,6 +7,7 @@ import {isNoisyHttpClientPollEvent,isPosthogRecorderInternalEvent,isReactDevtoolsInternalEvent,+ isStaleChunkLoadErrorEvent,isStaleChunkParseErrorEvent,} from "@/src/utils/sentryFilters";@@ -1152,7 +1153,7 @@ describe("isDenylistedNoiseEvent", () => {it("keeps a first-party chunk dynamic-import failure (stale deploy / CDN)", () => {// Same Chrome message as LANGFUSE-5ZS, but the URL is ours. This is a// real client failure (stale tab after deploy, truncated download) and- // must still reach Sentry.+ // must still reach Sentry (grouped, not dropped).expect(isDenylistedNoiseEvent(exceptionEvent(@@ -1679,6 +1680,115 @@ describe("isReactDevtoolsInternalEvent", () => {});});+/**+ * Next.js route-loader `script.onerror`: capture_console from+ * `Error rendering page: ` + `Failed to load script: <hashed chunk URL>`.+ */+function chunkLoadErrorEvent(+ value = "Failed to load script: https://us.cloud.langfuse.com/_next/static/chunks/31w9e6884-o68.js",+): ErrorEvent {+ return {+ exception: {+ values: [+ {+ type: "Error",+ value,+ mechanism: { type: "auto.core.capture_console", handled: true },+ stacktrace: {+ frames: [+ {+ filename: "node_modules/next/src/client/route-loader.ts",+ function: "script.onerror",+ },+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+}++describe("isStaleChunkLoadErrorEvent", () => {+ describe("matches first-party chunk LOAD failures (grouped, not dropped)", () => {+ it("matches Next.js route-loader script.onerror (hashed chunk URL)", () => {+ expect(isStaleChunkLoadErrorEvent(chunkLoadErrorEvent())).toBe(true);+ });++ it("matches regardless of the (per-deploy hashed) chunk filename", () => {+ expect(+ isStaleChunkLoadErrorEvent(+ chunkLoadErrorEvent(+ "Failed to load script: https://static-hipaa.langfuse.com/_next/static/chunks/abc123-xyz.js",+ ),+ ),+ ).toBe(true);+ });++ it("matches a first-party dynamic import() chunk failure", () => {+ expect(+ isStaleChunkLoadErrorEvent(+ exceptionEvent(+ "Failed to fetch dynamically imported module: https://us.cloud.langfuse.com/_next/static/chunks/app.js",+ "TypeError",+ ),+ ),+ ).toBe(true);+ expect(+ isStaleChunkLoadErrorEvent(+ messageEvent(+ "Failed to fetch dynamically imported module: http://localhost:3000/_next/static/chunks/app.js",+ ),+ ),+ ).toBe(true);+ });++ it("is grouped by beforeSend, NOT dropped by the denylist", () => {+ expect(isDenylistedNoiseEvent(chunkLoadErrorEvent())).toBe(false);+ });+ });++ describe("NEVER matches unrelated load failures", () => {+ it("keeps a third-party script.onerror (no Next chunk path)", () => {+ expect(+ isStaleChunkLoadErrorEvent(+ chunkLoadErrorEvent(+ "Failed to load script: https://cdn.example.com/vendor.js",+ ),+ ),+ ).toBe(false);+ });++ it("keeps UI copy that quotes Failed to load without a chunk URL", () => {+ expect(+ isStaleChunkLoadErrorEvent(+ exceptionEvent("Failed to load evaluators: upstream timed out"),+ ),+ ).toBe(false);+ });++ it("keeps worker importScripts failures (separate family)", () => {+ expect(+ isStaleChunkLoadErrorEvent(+ exceptionEvent(+ "[ELK layout] worker failed to load: Uncaught NetworkError: Failed to execute 'importScripts' on 'WorkerGlobalScope': The script at 'https://us.cloud.langfuse.com/_next/static/chunks/27ywx138-jmac.js' failed to load.",+ ),+ ),+ ).toBe(false);+ });++ it("keeps a browser-extension dynamic import() failure", () => {+ expect(+ isStaleChunkLoadErrorEvent(+ exceptionEvent(+ "Failed to fetch dynamically imported module: chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/chunk.js",+ "TypeError",+ ),+ ),+ ).toBe(false);+ });+ });+});+/*** Build the exact WIRE shape the SDK hands `beforeSend` for a chunk PARSE* failure (LANGFUSE-5WH/5WG/5WD/5S7): global `onerror` mechanism,diff --git a/web/src/utils/sentryFilters.ts b/web/src/utils/sentryFilters.tsindex c55195dc73..0ee221e8be 100644--- a/web/src/utils/sentryFilters.ts+++ b/web/src/utils/sentryFilters.ts@@ -480,7 +480,8 @@ export function isReactDevtoolsInternalEvent(event: ErrorEvent): boolean {* surfaces as a spike on one issue.* - first-party `Failed to fetch dynamically imported module` of a* `/_next/static/chunks/` URL — same Chrome wording as the extension- * family, but our chunks (stale tab / CDN); kept.+ * family, but our chunks (stale tab / CDN); kept and GROUPED via+ * {@link isStaleChunkLoadErrorEvent}.* - an UNCAUGHT `window.__NEXT_DATA__` getter-only TypeError (global* `onerror`) — Next.js Pages Router failed to boot; kept as a diagnostic.* Only the console-captured sibling is dropped (LANGFUSE-61R).@@ -734,6 +735,16 @@ function isGlobalHandlerUnsupportedMediaResourceEvent(*/export const STALE_CHUNK_PARSE_FINGERPRINT = "stale-chunk-parse-error";+/**+ * Fingerprint used to collapse first-party chunk LOAD failures into ONE Sentry+ * issue (see {@link isStaleChunkLoadErrorEvent}). Separate from the parse+ * fingerprint: a 404/network miss is not the same signal as an unparsable body.+ */+export const STALE_CHUNK_LOAD_FINGERPRINT = "stale-chunk-load-error";++const NEXT_STATIC_CHUNK_PATH = "/_next/static/";+const FAILED_TO_LOAD_SCRIPT_MARKER = "Failed to load script:";+/*** True for a browser-level parse failure of a Next.js chunk: the global* `onerror` handler caught a `SyntaxError` whose entire stack is ONE anonymous@@ -779,6 +790,31 @@ export function isStaleChunkParseErrorEvent(event: ErrorEvent): boolean {);}+/**+ * True for a first-party Next.js chunk that failed to LOAD (not parse):+ * Pages Router `route-loader` `script.onerror` (`Failed to load script:+ * <hashed /_next/static/… URL>`) or Chrome's dynamic+ * `import()` of the same path. Chunk filenames are content-hashed, so Sentry+ * minted a new issue per chunk per deploy. The one-shot reload in+ * `reloadOnStaleChunk` is the user-facing recovery; these events are GROUPED+ * under {@link STALE_CHUNK_LOAD_FINGERPRINT} in `beforeSend`, NOT dropped —+ * a CDN/deploy that 404s a chunk for everyone still spikes on one issue.+ *+ * Cannot catch:+ * - a third-party `Failed to load script:` (no `/_next/static/` path);+ * - UI copy such as `Failed to load evaluators:` (no chunk URL);+ * - worker `importScripts` failures (different message family);+ * - browser-extension `import()` (extension protocol, already denylisted).+ */+export function isStaleChunkLoadErrorEvent(event: ErrorEvent): boolean {+ const text = eventText(event);+ if (!text.includes(NEXT_STATIC_CHUNK_PATH)) return false;+ return (+ text.includes(FAILED_TO_LOAD_SCRIPT_MARKER) ||+ text.includes(DYNAMIC_IMPORT_FAILURE_MARKER)+ );+}+/*** PostHog's lazily-loaded session-replay recorder script. Older posthog-js* served `/static/posthog-recorder.js?v=<version>`; 1.417+ serves