πͺ’ 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(sentry): stop three noise families from minting a fingerprint per occurrence (#15770)
Nikita Kabardin1b801e73b88b
diff --git a/web/instrumentation-client.ts b/web/instrumentation-client.tsindex 615c293d3d..227e3423c3 100644--- a/web/instrumentation-client.ts+++ b/web/instrumentation-client.ts@@ -2,7 +2,10 @@ import * as Sentry from "@sentry/nextjs";import {isDenylistedNoiseEvent,isNoisyHttpClientPollEvent,+ isPosthogRecorderInternalEvent,isReactDevtoolsInternalEvent,+ isStaleChunkParseErrorEvent,+ STALE_CHUNK_PARSE_FINGERPRINT,} from "@/src/utils/sentryFilters";const isEuOrUsRegionNonHipaa =@@ -45,6 +48,23 @@ Sentry.init({return null;}+ // Drop errors thrown wholly inside PostHog's session-replay recorder+ // script (rrweb DOM serialization failing on exotic page content). No app+ // frame is ever present in these stacks; anything touching our code is+ // kept. See isPosthogRecorderInternalEvent for the rationale.+ if (isPosthogRecorderInternalEvent(event)) {+ return null;+ }++ // Stale-deploy / truncated chunk parse errors: collapse into ONE issue+ // instead of one per content-hashed chunk filename. Deliberately grouped,+ // NOT dropped β a deploy that ships a genuinely unparsable chunk still+ // surfaces as a spike on the single grouped issue. See+ // isStaleChunkParseErrorEvent for the rationale.+ if (isStaleChunkParseErrorEvent(event)) {+ event.fingerprint = [STALE_CHUNK_PARSE_FINGERPRINT];+ }+return event;},diff --git a/web/src/utils/sentryFilters.clienttest.ts b/web/src/utils/sentryFilters.clienttest.tsindex 19553f164f..be8d8ba871 100644--- a/web/src/utils/sentryFilters.clienttest.ts+++ b/web/src/utils/sentryFilters.clienttest.ts@@ -3,7 +3,9 @@ import { type ErrorEvent } from "@sentry/nextjs";import {isDenylistedNoiseEvent,isNoisyHttpClientPollEvent,+ isPosthogRecorderInternalEvent,isReactDevtoolsInternalEvent,+ isStaleChunkParseErrorEvent,} from "@/src/utils/sentryFilters";/**@@ -351,6 +353,112 @@ describe("isDenylistedNoiseEvent", () => {});});+ describe("D. drops known-benign non-Error promise rejections (exact value denylist)", () => {+ // Real shape (LANGFUSE-5T9/5TA): SDK-synthesized `UnhandledRejection` type,+ // `onunhandledrejection` mechanism, NO stack β grouping falls back to the+ // stringified value, so every new value minted a new fingerprint.+ const nonErrorRejectionEvent = (rejectionValue: string): ErrorEvent =>+ ({+ exception: {+ values: [+ {+ type: "UnhandledRejection",+ value: `Non-Error promise rejection captured with value: ${rejectionValue}`,+ mechanism: {+ type: "auto.browser.global_handlers.onunhandledrejection",+ handled: false,+ },+ },+ ],+ },+ }) as ErrorEvent;++ it("drops the wallet/extension shim rejection (LANGFUSE-5T9)", () => {+ expect(+ isDenylistedNoiseEvent(+ nonErrorRejectionEvent("Not implemented on this platform"),+ ),+ ).toBe(true);+ });++ it("drops the empty `Promise.reject(undefined)` rejection (LANGFUSE-5TA)", () => {+ expect(isDenylistedNoiseEvent(nonErrorRejectionEvent("undefined"))).toBe(+ true,+ );+ });++ it("drops the Outlook SafeLinks scanner artifact (LANGFUSE-11Z, variable tail)", () => {+ expect(+ isDenylistedNoiseEvent(+ nonErrorRejectionEvent(+ "Object Not Found Matching Id:2, MethodName:update, ParamCount:4",+ ),+ ),+ ).toBe(true);+ });+ });++ describe("E. drops environmental storage-access SecurityError (console-captured only)", () => {+ // Real shape (LANGFUSE-5TC/5TD/5TE/5TF): our useLocalStorage catch logs the+ // DOMException via console.error β captureConsoleIntegration re-captures it+ // as an exception event (mechanism `auto.core.capture_console`) carrying+ // the browser-generated message.+ const consoleCapturedStorageDenial = (value: string): ErrorEvent =>+ ({+ exception: {+ values: [+ {+ type: "SecurityError",+ value,+ mechanism: { type: "auto.core.capture_console", handled: true },+ },+ ],+ },+ }) as ErrorEvent;++ it("drops the localStorage access denial (LANGFUSE-5TC/5TD/5TE/5TF)", () => {+ expect(+ isDenylistedNoiseEvent(+ consoleCapturedStorageDenial(+ "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",+ ),+ ),+ ).toBe(true);+ });++ it("drops the sessionStorage variant of the same browser artifact", () => {+ expect(+ isDenylistedNoiseEvent(+ consoleCapturedStorageDenial(+ "Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.",+ ),+ ),+ ).toBe(true);+ });++ it("KEEPS an UNCAUGHT storage SecurityError (page crash via global onerror)", () => {+ // A bare storage read during render that crashes the page arrives via the+ // global handler, not capture_console β that is a real diagnostic and+ // must survive.+ const event = {+ exception: {+ values: [+ {+ type: "SecurityError",+ value:+ "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",+ mechanism: {+ type: "auto.browser.global_handlers.onerror",+ handled: false,+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isDenylistedNoiseEvent(event)).toBe(false);+ });+ });+describe("A. transport failures also drop when they arrive as message events", () => {it("drops a message-event 'Failed to fetch'", () => {expect(isDenylistedNoiseEvent(messageEvent("Failed to fetch"))).toBe(@@ -524,6 +632,90 @@ describe("isDenylistedNoiseEvent", () => {).toBe(false);});+ it("keeps a non-Error rejection with an UNKNOWN value (could be app code)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "UnhandledRejection",+ value:+ "Non-Error promise rejection captured with value: Something went wrong loading traces",+ mechanism: {+ type: "auto.browser.global_handlers.onunhandledrejection",+ handled: false,+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isDenylistedNoiseEvent(event)).toBe(false);+ });++ it("keeps the object-shaped rejection variant (has carried real failures)", () => {+ // LANGFUSE-1BB: `code, message, stack` payloads β a serialized error.+ expect(+ isDenylistedNoiseEvent(+ exceptionEvent(+ "Object captured as promise rejection with keys: code, message, stack",+ "UnhandledRejection",+ ),+ ),+ ).toBe(false);+ });++ it("keeps a real unhandled rejection carrying an Error object", () => {+ // A rejected real Error keeps its own type β never `UnhandledRejection`.+ const event = {+ exception: {+ values: [+ {+ type: "TypeError",+ value: "Cannot read properties of undefined (reading 'map')",+ mechanism: {+ type: "auto.browser.global_handlers.onunhandledrejection",+ handled: false,+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isDenylistedNoiseEvent(event)).toBe(false);+ });++ it("keeps a benign-looking rejection value with extra text (exact match only)", () => {+ expect(+ isDenylistedNoiseEvent(+ exceptionEvent(+ "Non-Error promise rejection captured with value: undefined is not a function",+ "UnhandledRejection",+ ),+ ),+ ).toBe(false);+ });++ it("keeps a real SecurityError from app-adjacent logic (cross-origin frame access)", () => {+ expect(+ isDenylistedNoiseEvent(+ exceptionEvent(+ 'Blocked a frame with origin "https://cloud.langfuse.com" from accessing a cross-origin frame.',+ "SecurityError",+ ),+ ),+ ).toBe(false);+ });++ it("keeps the storage-denial message when the type is NOT SecurityError", () => {+ // Proves the type guard: an app error merely quoting the message survives.+ expect(+ isDenylistedNoiseEvent(+ exceptionEvent(+ "Failed to read the 'localStorage' property from 'Window': Access is denied for this document.",+ "Error",+ ),+ ),+ ).toBe(false);+ });+it("keeps an event with no exception values", () => {expect(isDenylistedNoiseEvent({ message: "some message" } as ErrorEvent),@@ -604,3 +796,404 @@ describe("isReactDevtoolsInternalEvent", () => {});});});++/**+ * Build the exact WIRE shape the SDK hands `beforeSend` for a chunk PARSE+ * failure (LANGFUSE-5WH/5WG/5WD/5S7): global `onerror` mechanism,+ * `SyntaxError`, and a single frame at the chunk URL whose function is the+ * SDK's UNKNOWN_FUNCTION placeholder `"?"` (server-side normalization later+ * strips that β the shape stored events show). Pass `fn: null` to build the+ * normalized shape with the `function` key genuinely absent (an explicit+ * `undefined` would be swallowed by the default parameter).+ */+function chunkParseErrorEvent(+ value: string,+ filename = "app:///_next/static/chunks/0_w4b6l3mpyep.js",+ fn: string | null = "?",+): ErrorEvent {+ return {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value,+ mechanism: {+ type: "auto.browser.global_handlers.onerror",+ handled: false,+ },+ stacktrace: {+ frames: [fn === null ? { filename } : { filename, function: fn }],+ },+ },+ ],+ },+ } as ErrorEvent;+}++describe("isStaleChunkParseErrorEvent", () => {+ describe("matches stale/truncated chunk parse failures (grouped, not dropped)", () => {+ it.each([+ ["Unexpected end of input"], // Chrome, LANGFUSE-5WH+ ['"" literal not terminated before end of script'], // Firefox, LANGFUSE-5WG+ ["missing } after property list"], // Firefox, LANGFUSE-5WD+ ["Invalid or unexpected token"], // Chrome, LANGFUSE-5S7+ ["expected expression, got end of script"], // Firefox, LANGFUSE-5WN+ ])("matches the real parse message %j", (value) => {+ expect(isStaleChunkParseErrorEvent(chunkParseErrorEvent(value))).toBe(+ true,+ );+ });++ it("matches regardless of the (per-deploy hashed) chunk filename", () => {+ expect(+ isStaleChunkParseErrorEvent(+ chunkParseErrorEvent(+ "Unexpected end of input",+ "app:///_next/static/chunks/3g9a8ojcqetek.js",+ ),+ ),+ ).toBe(true);+ });++ it("matches the normalized stored shape too (function key absent instead of '?')", () => {+ const event = chunkParseErrorEvent(+ "Unexpected end of input",+ "app:///_next/static/chunks/3g9a8ojcqetek.js",+ null,+ );+ // Guard the fixture itself: the frame must NOT carry a function key.+ expect(+ event.exception?.values?.[0]?.stacktrace?.frames?.[0],+ ).not.toHaveProperty("function");+ expect(isStaleChunkParseErrorEvent(event)).toBe(true);+ });++ it("is grouped by beforeSend, NOT dropped by the denylist", () => {+ expect(+ isDenylistedNoiseEvent(chunkParseErrorEvent("Unexpected end of input")),+ ).toBe(false);+ });+ });++ describe("NEVER matches a user-authored or app-code SyntaxError", () => {+ it("keeps the evals editor's user-code SyntaxError (LANGFUSE-5W3 shape)", () => {+ // Real shape: console.error capture with app + vendor formatter frames.+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Unexpected token (1:38)",+ mechanism: { type: "auto.core.capture_console", handled: true },+ stacktrace: {+ frames: [+ {+ filename:+ "web/src/features/evals/components/code-eval-template-form-body.tsx",+ function: "P",+ },+ {+ filename:+ "node_modules/.pnpm/[email protected]/node_modules/prettier/standalone.mjs",+ function: "Jn",+ },+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isStaleChunkParseErrorEvent(event)).toBe(false);+ });++ it("keeps the evals editor's user-code lint error (LANGFUSE-5W2 shape, type Error)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "Error",+ value:+ "Expected class, function definition or async function definition after decorator at byte range 477..481",+ mechanism: { type: "auto.core.capture_console", handled: true },+ stacktrace: {+ frames: [+ {+ filename:+ "web/src/features/evals/utils/code-eval-template-validation.ts",+ function: "aa",+ },+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isStaleChunkParseErrorEvent(event)).toBe(false);+ });++ it("keeps a runtime SyntaxError thrown by app code (JSON.parse β multi-frame)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Unexpected end of JSON input",+ mechanism: {+ type: "auto.browser.global_handlers.onerror",+ handled: false,+ },+ stacktrace: {+ frames: [+ {+ filename: "app:///_next/static/chunks/0r47ep231kqhy.js",+ function: "loadSavedFilters",+ },+ {+ filename: "app:///_next/static/chunks/0r47ep231kqhy.js",+ function: "JSON.parse",+ },+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isStaleChunkParseErrorEvent(event)).toBe(false);+ });++ it("keeps a single-frame SyntaxError with a NAMED function (runtime throw)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Unexpected end of JSON input",+ mechanism: {+ type: "auto.browser.global_handlers.onerror",+ handled: false,+ },+ stacktrace: {+ frames: [+ {+ filename: "app:///_next/static/chunks/0r47ep231kqhy.js",+ function: "parseStoredView",+ },+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isStaleChunkParseErrorEvent(event)).toBe(false);+ });++ it("keeps a parse error in a non-chunk script", () => {+ expect(+ isStaleChunkParseErrorEvent(+ chunkParseErrorEvent(+ "Unexpected end of input",+ "app:///some-other-script.js",+ ),+ ),+ ).toBe(false);+ });++ it("keeps a SyntaxError with no stacktrace and a non-SyntaxError parse-like event", () => {+ expect(+ isStaleChunkParseErrorEvent(+ exceptionEvent("Unexpected end of input", "SyntaxError"),+ ),+ ).toBe(false);+ expect(+ isStaleChunkParseErrorEvent(+ chunkParseErrorEvent("Unexpected end of input"),+ ),+ ).toBe(true); // sanity: same builder matches when shape is complete+ });+ });+});++/** Frame helper for recorder-stack fixtures. */+function frame(filename: string, fn?: string) {+ return { filename, function: fn };+}++describe("isPosthogRecorderInternalEvent", () => {+ // Wire shape: the recorder loads with a version query that survives into+ // frame filenames handed to beforeSend (stored events show it on abs_path).+ const RECORDER = "app:///static/posthog-recorder.js?v=1.390.2";++ describe("drops errors thrown wholly inside the PostHog session recorder", () => {+ it("drops the rrweb mutation-processing SyntaxError (LANGFUSE-5VX shape)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Invalid or unexpected token",+ mechanism: {+ type: "auto.browser.global_handlers.onerror",+ handled: false,+ },+ stacktrace: {+ frames: [+ frame(RECORDER, "Ut.processMutations"),+ frame(RECORDER, "Ut.emit"),+ frame(RECORDER, "Ws.onRRwebEmit"),+ frame("<anonymous>", "Array.forEach"),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(true);+ });++ it("drops the same shape without the version query (normalized stored filename)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Invalid or unexpected token",+ stacktrace: {+ frames: [+ frame(+ "app:///static/posthog-recorder.js",+ "Ut.processMutations",+ ),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(true);+ });++ it("drops the addEventListener-wrapped variant with a source-mapped Sentry SDK frame (LANGFUSE-5VY stored shape)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Invalid or unexpected token",+ mechanism: {+ type: "auto.browser.browserapierrors.addEventListener",+ handled: false,+ },+ stacktrace: {+ frames: [+ frame(+ "node_modules/.pnpm/@[email protected]/node_modules/@sentry/browser/src/helpers.ts",+ "r",+ ),+ frame(RECORDER, "l"),+ frame(RECORDER, "Se"),+ frame(RECORDER, "Ws.Hd"),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(true);+ });+ });++ describe("KEEPS any error that touches app code", () => {+ it("keeps a stack that mixes recorder frames with an app chunk frame", () => {+ const event = {+ exception: {+ values: [+ {+ type: "TypeError",+ value: "Cannot read properties of undefined (reading 'map')",+ stacktrace: {+ frames: [+ frame(RECORDER, "Ws.onRRwebEmit"),+ frame(+ "app:///_next/static/chunks/0r47ep231kqhy.js",+ "onMutation",+ ),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(false);+ });++ it("keeps the wrapped-listener variant when the SDK wrapper is bundled into an app chunk (prod wire shape β deliberate coverage gap)", () => {+ // In a prod bundle the Sentry wrap() frame is an app-chunk filename;+ // allowing chunk frames could mask real app listener errors, so this+ // shape stays kept even though it is recorder noise (LANGFUSE-5VY).+ const event = {+ exception: {+ values: [+ {+ type: "SyntaxError",+ value: "Invalid or unexpected token",+ stacktrace: {+ frames: [+ frame("app:///_next/static/chunks/2-jdgbtsa7jx3.js", "r"),+ frame(RECORDER, "l"),+ frame(RECORDER, "Ws.Hd"),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(false);+ });++ it("keeps an app-only stack (no recorder frame at all)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "TypeError",+ value: "boom",+ stacktrace: {+ frames: [+ frame("app:///_next/static/chunks/0r47ep231kqhy.js", "fn"),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(false);+ });++ it("keeps an all-opaque stack (<anonymous>/[native code] only β no recorder attribution)", () => {+ const event = {+ exception: {+ values: [+ {+ type: "TypeError",+ value: "boom",+ stacktrace: {+ frames: [+ frame("<anonymous>", "Array.forEach"),+ frame("[native code]"),+ ],+ },+ },+ ],+ },+ } as ErrorEvent;+ expect(isPosthogRecorderInternalEvent(event)).toBe(false);+ });++ it("keeps events with no stacktrace", () => {+ expect(+ isPosthogRecorderInternalEvent(exceptionEvent("boom", "TypeError")),+ ).toBe(false);+ expect(isPosthogRecorderInternalEvent(messageEvent("boom"))).toBe(false);+ });+ });+});diff --git a/web/src/utils/sentryFilters.ts b/web/src/utils/sentryFilters.tsindex f7df54be27..375c567319 100644--- a/web/src/utils/sentryFilters.ts+++ b/web/src/utils/sentryFilters.ts@@ -115,6 +115,44 @@ const NOISE_MESSAGE_PREFIXES: readonly string[] = ["_error.js called with falsy error",];+/**+ * The Sentry SDK synthesizes this exact prefix (global `onunhandledrejection`+ * handler) when a promise rejects with a non-`Error` value. These events carry+ * NO stack, so Sentry groups them by the stringified value β every new value+ * mints a new fingerprint.+ */+const NON_ERROR_REJECTION_PREFIX =+ "Non-Error promise rejection captured with value: ";++/**+ * Known-benign non-Error rejection values, each traced to a non-app source+ * from real events. ONLY these exact values (plus the prefixes below) are+ * dropped β an unknown value could be a real rejection from our code or a+ * bundled dependency and is KEPT, as is the object-shaped+ * `Object captured as promise rejection with keys: β¦` variant, which has+ * carried real failures (e.g. `code, message, stack` payloads).+ */+const BENIGN_NON_ERROR_REJECTION_VALUES: readonly string[] = [+ // Browser-extension shim (wallet/provider extensions no-op on unsupported+ // platforms and reject with this bare string). Observed with no stack and no+ // app frames (LANGFUSE-5T9).+ "Not implemented on this platform",+ // `Promise.reject()` / `reject(undefined)`: zero diagnostic content β no+ // stack, no message, no value. Nobody can act on it (LANGFUSE-5TA).+ "undefined",+];++/**+ * Prefix-matched benign rejection values whose tail varies per occurrence+ * (which is exactly what shatters grouping).+ */+const BENIGN_NON_ERROR_REJECTION_VALUE_PREFIXES: readonly string[] = [+ // Microsoft Outlook SafeLinks / email-scanner artifact: the crawler injects+ // scripts that reject with `Object Not Found Matching Id:<n>, MethodName:β¦`.+ // Industry-known scanner noise, never a browser session (LANGFUSE-11Z).+ "Object Not Found Matching Id:",+];+/*** A `TRPCClientError` re-wraps its cause's message. Depending on capture path* the Sentry `value` may be the bare cause message (`Failed to fetch`) or carry@@ -204,10 +242,12 @@ export function isReactDevtoolsInternalEvent(event: ErrorEvent): boolean {* occurred` β it aggregates real exceptions with no stack; hard-dropping it* could blind us if the underlying exceptions are not captured separately.* - `OAuthCallback` sign-in errors β could be a genuine auth-config break.- * - auth/permission (`UNAUTHORIZED`, not-a-member), query-timeout,- * chunk-load / stale-deploy `SyntaxError`, and Sentry perf detectors /- * third-party scripts β handled as UX or in Sentry project settings, not by a- * blind client-side drop.+ * - auth/permission (`UNAUTHORIZED`, not-a-member), query-timeout, and Sentry+ * perf detectors / third-party scripts β handled as UX or in Sentry project+ * settings, not by a blind client-side drop.+ * - the chunk-load / stale-deploy `SyntaxError` family β GROUPED (not dropped)+ * via {@link isStaleChunkParseErrorEvent} so a genuinely broken deploy still+ * surfaces as a spike on one issue.*/export function isDenylistedNoiseEvent(event: ErrorEvent): boolean {const exception = event.exception?.values?.[0];@@ -268,7 +308,172 @@ export function isDenylistedNoiseEvent(event: ErrorEvent): boolean {) {return true;}++ // Known-benign non-Error promise rejections. The `UnhandledRejection`+ // exception type is SDK-synthesized (a real `Error` rejection keeps its own+ // type, e.g. `TypeError`), and the value denylist is exact/prefix-anchored:+ // an unknown rejection value still flows to Sentry. See+ // BENIGN_NON_ERROR_REJECTION_VALUES for per-value provenance.+ if (+ exceptionType === "UnhandledRejection" &&+ exceptionValue.startsWith(NON_ERROR_REJECTION_PREFIX)+ ) {+ const rejectionValue = exceptionValue.slice(+ NON_ERROR_REJECTION_PREFIX.length,+ );+ if (+ BENIGN_NON_ERROR_REJECTION_VALUES.includes(rejectionValue) ||+ BENIGN_NON_ERROR_REJECTION_VALUE_PREFIXES.some((prefix) =>+ rejectionValue.startsWith(prefix),+ )+ ) {+ return true;+ }+ }++ // Environmental storage-access denial: browsers throw a `SecurityError`+ // DOMException on the `window.localStorage` property GETTER itself when+ // storage is blocked (third-party iframe, privacy mode). The message is+ // browser-generated β app logic cannot produce it. Stacks point at+ // per-deploy hashed chunks, so each occurrence minted a new fingerprint+ // (LANGFUSE-5TC/5TD/5TE/5TF).+ //+ // Guarded to the `capture_console` mechanism: only instances our own code+ // already CAUGHT and logged (e.g. the useLocalStorage / useSessionStorage+ // fallback paths) are dropped. An UNCAUGHT storage SecurityError β e.g. a+ // bare storage read during render crashing the page β arrives via the+ // global `onerror` handler and is KEPT, as are other `SecurityError`s+ // (e.g. cross-origin frame access).+ if (+ exceptionType === "SecurityError" &&+ exception?.mechanism?.type === "auto.core.capture_console" &&+ /^Failed to read the '(localStorage|sessionStorage)' property from 'Window':/.test(+ exceptionValue,+ )+ ) {+ return true;+ }}return false;}++/**+ * Fingerprint used to collapse all stale-chunk parse errors into ONE Sentry+ * issue (see {@link isStaleChunkParseErrorEvent}).+ */+export const STALE_CHUNK_PARSE_FINGERPRINT = "stale-chunk-parse-error";++/**+ * 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+ * frame at a `/_next/static/chunks/β¦` script β the shape a browser produces+ * when a script's CONTENT fails to parse (truncated download, or a stale+ * client fetching a chunk that no longer exists and receiving garbage after a+ * deploy). Chunk filenames are content-hashed, so Sentry minted a new+ * fingerprint per chunk per deploy (LANGFUSE-5WH/5WG/5WD/5S7 and the 1-event+ * long tail). The reload banner (#15279) is the mitigation for the cause.+ *+ * These events are GROUPED under {@link STALE_CHUNK_PARSE_FINGERPRINT} in+ * `beforeSend`, NOT dropped: if a deploy ever ships a genuinely unparsable+ * chunk to everyone, the single grouped issue spikes and stays visible.+ *+ * Cannot catch a user-authored or app-code `SyntaxError`:+ * - the evals code editor reports user-code syntax errors via+ * `console.error` (mechanism `auto.core.capture_console`) with app frames+ * (`web/src/features/evals/β¦`) β different mechanism, multi-frame stack;+ * - a runtime `SyntaxError` thrown by app code (e.g. `JSON.parse`) carries+ * its throwing function and callers β more than one frame / a named+ * function.+ */+export function isStaleChunkParseErrorEvent(event: ErrorEvent): boolean {+ const exception = event.exception?.values?.[0];+ if (exception?.type !== "SyntaxError") return false;+ if (exception.mechanism?.type !== "auto.browser.global_handlers.onerror") {+ return false;+ }++ const frames = exception.stacktrace?.frames;+ if (!frames || frames.length !== 1) return false;++ const frame = frames[0];+ // Parse errors carry no function name β the SDK synthesizes the frame with+ // its UNKNOWN_FUNCTION placeholder `"?"` on the wire (`beforeSend` runs+ // BEFORE server-side normalization turns that into `null`). A real function+ // name means runtime code threw.+ if (frame?.function && frame.function !== "?") return false;++ return (+ typeof frame?.filename === "string" &&+ frame.filename.includes("/_next/static/chunks/")+ );+}++/**+ * PostHog's lazily-loaded session-replay recorder script (served as+ * `/static/posthog-recorder.js?v=<posthog-js version>`).+ */+const POSTHOG_RECORDER_SCRIPT_SUFFIX = "/static/posthog-recorder.js";++/**+ * Frames that carry no attribution: browser-native/eval frames, and the Sentry+ * SDK's own wrapper frames (its `wrap()` helper sits at the outer edge of+ * every instrumented listener stack). The `@sentry` path shape only occurs in+ * dev / source-mapped stacks β in a prod bundle the wrapper lives in an app+ * chunk, which this predicate deliberately does NOT allow (see the coverage+ * gap note on {@link isPosthogRecorderInternalEvent}).+ */+function isOpaqueOrSdkFrame(filename: string): boolean {+ return (+ filename === "<anonymous>" ||+ filename === "[native code]" ||+ (filename.includes("node_modules") && filename.includes("@sentry"))+ );+}++/**+ * True for errors thrown wholly INSIDE PostHog's session-replay recorder:+ * every attributable stack frame lives in the recorder script (plus at most+ * browser-native and Sentry-SDK wrapper frames). rrweb's DOM serialization+ * throws on exotic page content (observed: `SyntaxError: Invalid or unexpected+ * token` from `processMutations` / `onRRwebEmit`, LANGFUSE-5VY/5VX), and each+ * throw site mints a new fingerprint per recorder version.+ *+ * Safe to drop: an error thrown by OUR code always carries at least one app+ * chunk frame (the throwing frame), which fails this check. Errors with no+ * app frame are the vendor recorder failing internally β not a Langfuse app+ * bug, and not actionable in Sentry (session replay is best-effort telemetry;+ * a broken recorder shows up as missing recordings in PostHog, not here).+ * Same posture as the browser-extension `denyUrls` entries, expressed as a+ * testable predicate because the crash frame is often `<anonymous>`, which+ * `denyUrls` skips inconsistently.+ *+ * Known coverage gap (deliberate): the `addEventListener`-wrapped variant+ * (LANGFUSE-5VY) carries the Sentry SDK's `wrap()` frame, which in a prod+ * bundle is an app-chunk filename indistinguishable from app code β those+ * events are KEPT. Allowing chunk frames here would risk masking real app+ * listener errors, so only the all-recorder shape (LANGFUSE-5VX) is dropped.+ */+export function isPosthogRecorderInternalEvent(event: ErrorEvent): boolean {+ const frames = event.exception?.values?.[0]?.stacktrace?.frames;+ if (!frames || frames.length === 0) return false;++ let sawRecorderFrame = false;+ for (const frame of frames) {+ const filename = frame?.filename;+ // A frame with no filename has no attribution β treat like <anonymous>.+ if (typeof filename !== "string" || filename.length === 0) continue;+ // The recorder loads with a version query (`?v=<posthog-js version>`) that+ // survives into wire-format frame filenames β strip query/fragment before+ // matching the path suffix.+ const path = filename.split(/[?#]/)[0];+ if (path.endsWith(POSTHOG_RECORDER_SCRIPT_SUFFIX)) {+ sawRecorderFrame = true;+ continue;+ }+ if (isOpaqueOrSdkFrame(filename)) continue;+ // Any other frame (app chunk, other vendor) β not recorder-internal.+ return false;+ }+ return sawRecorderFrame;+}