Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(observability): filter known-benign client noise before Sentry capture (LFE-10976) (#15238)

Nikita Kabardin74222314d1cb
diff --git a/web/instrumentation-client.ts b/web/instrumentation-client.ts
index aa663e33c4..02563a6ec0 100644
--- a/web/instrumentation-client.ts
+++ b/web/instrumentation-client.ts
@@ -1,5 +1,8 @@
import * as Sentry from "@sentry/nextjs";
-import { isNoisyHttpClientPollEvent } from "@/src/utils/sentryFilters";
+import {
+ isDenylistedNoiseEvent,
+ isNoisyHttpClientPollEvent,
+} from "@/src/utils/sentryFilters";
const isEuOrUsRegionNonHipaa =
process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined
@@ -41,6 +44,17 @@ Sentry.init({
return null;
}
+ // Drop known-benign client-side noise: browser/transport failures (offline,
+ // flaky network, CORS, proxy/infra HTML error pages), transient
+ // framework/vendor poll logs (NextAuth CLIENT_FETCH_ERROR, PostHog notices),
+ // and expected browser artifacts (clipboard permission denials, intentional
+ // request cancellations). Each signature is narrow and cannot represent a
+ // real Langfuse app bug; real errors that merely quote a phrase still flow
+ // to Sentry. See isDenylistedNoiseEvent for the per-rule rationale.
+ if (isDenylistedNoiseEvent(event)) {
+ return null;
+ }
+
return event;
},
diff --git a/web/src/utils/sentryFilters.clienttest.ts b/web/src/utils/sentryFilters.clienttest.ts
index dc3cace13c..ce0032b509 100644
--- a/web/src/utils/sentryFilters.clienttest.ts
+++ b/web/src/utils/sentryFilters.clienttest.ts
@@ -1,6 +1,9 @@
import { type ErrorEvent } from "@sentry/nextjs";
-import { isNoisyHttpClientPollEvent } from "@/src/utils/sentryFilters";
+import {
+ isDenylistedNoiseEvent,
+ isNoisyHttpClientPollEvent,
+} from "@/src/utils/sentryFilters";
/**
* Build an event shaped exactly like the ones `httpClientIntegration` emits:
@@ -177,3 +180,357 @@ describe("isNoisyHttpClientPollEvent", () => {
});
});
});
+
+/**
+ * Build an event carrying a single exception value (type + value), the shape
+ * `captureConsoleIntegration` / global error handlers emit.
+ */
+function exceptionEvent(value: string, type = "Error"): ErrorEvent {
+ return {
+ exception: {
+ values: [{ type, value, mechanism: { type: "generic", handled: false } }],
+ },
+ } as ErrorEvent;
+}
+
+/**
+ * Build the shape `captureConsoleIntegration` produces for a string
+ * `console.error(...)` with `attachStacktrace` unset (the default): a MESSAGE
+ * event with `event.message` and NO `event.exception`. This is how the biggest
+ * console-origin families (NextAuth CLIENT_FETCH_ERROR, PostHog notices, the
+ * Next.js `_error.js` artifact) actually reach `beforeSend` in production.
+ */
+function messageEvent(message: string): ErrorEvent {
+ return { message } as ErrorEvent;
+}
+
+/** Same, but the text lives on `event.logentry.message` (defensive fallback). */
+function logentryEvent(message: string): ErrorEvent {
+ return { logentry: { message } } as ErrorEvent;
+}
+
+describe("isDenylistedNoiseEvent", () => {
+ describe("A. drops browser/transport failures (whole-message match)", () => {
+ it("drops Chrome 'Failed to fetch'", () => {
+ expect(isDenylistedNoiseEvent(exceptionEvent("Failed to fetch"))).toBe(
+ true,
+ );
+ });
+
+ it("drops Chrome 'Failed to fetch (hostname)' (trailing parenthetical)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("Failed to fetch (cloud.langfuse.com)"),
+ ),
+ ).toBe(true);
+ // also when wrapped by TRPCClientError
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "TRPCClientError: Failed to fetch (cloud.langfuse.com)",
+ ),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops Firefox 'NetworkError when attempting to fetch resource' (with trailing period)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("NetworkError when attempting to fetch resource."),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops Safari/WebKit 'Load failed'", () => {
+ expect(isDenylistedNoiseEvent(exceptionEvent("Load failed"))).toBe(true);
+ });
+
+ it("drops the transport failure when wrapped by TRPCClientError", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("TRPCClientError: Failed to fetch"),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops Response.json() on a non-JSON body", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "Failed to execute 'json' on 'Response': Unexpected end of JSON input",
+ ),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops an HTML error page parsed as JSON (json-parse signature + <html)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ `Unexpected token '<', "<html>\n<head>"... is not valid JSON`,
+ "SyntaxError",
+ ),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe("B. drops NextAuth session-poll CLIENT_FETCH_ERROR", () => {
+ // NextAuth logs a STRING via console.error, so this arrives as a MESSAGE
+ // event (no exception) β€” the shape captureConsoleIntegration produces.
+ it("drops the [next-auth][error][CLIENT_FETCH_ERROR] log (message event)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ messageEvent(
+ "[next-auth][error][CLIENT_FETCH_ERROR] https://cloud.langfuse.com/api/auth/session Failed to fetch",
+ ),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops it when the text lives on event.logentry.message", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ logentryEvent(
+ "[next-auth][error][CLIENT_FETCH_ERROR] https://cloud.langfuse.com/api/auth/session Load failed",
+ ),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe("C. drops expected browser-benign / vendor artifacts", () => {
+ it("drops a clipboard permission denial (NotAllowedError + writeText)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "Failed to execute 'writeText' on 'Clipboard': Write permission denied.",
+ "NotAllowedError",
+ ),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops an intentional request cancellation (AbortError)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("signal is aborted without reason", "AbortError"),
+ ),
+ ).toBe(true);
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("The operation was aborted.", "AbortError"),
+ ),
+ ).toBe(true);
+ });
+
+ // PostHog logs a string via console.error, so it arrives as a MESSAGE event
+ // (captureConsoleIntegration) β€” assert against that production shape.
+ it("drops a third-party [PostHog.js] notice (message event)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ messageEvent("[PostHog.js] was already loaded elsewhere."),
+ ),
+ ).toBe(true);
+ });
+
+ it("drops the @sentry/nextjs '_error.js called with falsy error (…)' artifact", () => {
+ // Real shape: captureException(`_error.js called with falsy error (${err})`)
+ // β†’ exception event whose value STARTS with the prefix.
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("_error.js called with falsy error (undefined)"),
+ ),
+ ).toBe(true);
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("_error.js called with falsy error (null)"),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ 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(
+ true,
+ );
+ });
+
+ it("drops a message-event HTML-parsed-as-JSON error", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ messageEvent(
+ `Unexpected token '<', "<html>\n<head>"... is not valid JSON`,
+ ),
+ ),
+ ).toBe(true);
+ });
+ });
+
+ // The heart of the safety contract: prove that real / similar-looking errors
+ // are NOT dropped. If any of these regress to `true`, a real bug would be
+ // hidden from Sentry.
+ describe("KEEPS real errors (never masks a genuine app error)", () => {
+ it("keeps a real tRPC error carrying the server's message", () => {
+ expect(
+ isDenylistedNoiseEvent(exceptionEvent("TRPCClientError: UNAUTHORIZED")),
+ ).toBe(false);
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "TRPCClientError: You are not a member of this organization",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps an app error that merely QUOTES a transport phrase", () => {
+ // Real messages seen in the codebase β€” must survive.
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "Failed to fetch created model",
+ "InvalidRequestError",
+ ),
+ ),
+ ).toBe(false);
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "Failed to fetch channels. Please check your Slack connection and try again.",
+ ),
+ ),
+ ).toBe(false);
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("Load failed for dataset export job 42"),
+ ),
+ ).toBe(false);
+ // Ends in a parenthetical, but the non-parenthetical part is longer than a
+ // bare transport phrase, so stripping the trailing `(…)` still leaves a
+ // non-matching whole message β€” must survive.
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("Failed to fetch traces (batch 3 of 5)"),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps a genuine SyntaxError with no <html (not an HTML-as-JSON artifact)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("Unexpected end of JSON input", "SyntaxError"),
+ ),
+ ).toBe(false);
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ `Unexpected token 'x', "xyz" is not valid JSON`,
+ "SyntaxError",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps the chunk-load / stale-deploy SyntaxError (handled separately, not dropped)", () => {
+ // Script parsing an HTML page: has `Unexpected token '<'` and `<html` but
+ // NOT the JSON-parse `is not valid JSON` suffix, so A5 must not catch it.
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "Unexpected token '<'\n<html><body>502 Bad Gateway</body></html>",
+ "SyntaxError",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps a real thrown TypeError", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "Cannot read properties of undefined (reading 'map')",
+ "TypeError",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps a non-clipboard NotAllowedError (autoplay/fullscreen)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "play() failed because the user didn't interact with the document first",
+ "NotAllowedError",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps the generic prod error-boundary string (LANGFUSE-1MY, deliberately not dropped)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent(
+ "A client-side exception has occurred while loading cloud.langfuse.com, see the browser console for more information.",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps an OAuthCallback sign-in error (deliberately not dropped)", () => {
+ expect(
+ isDenylistedNoiseEvent(exceptionEvent("OAuthCallback error", "Error")),
+ ).toBe(false);
+ });
+
+ it("keeps a different next-auth error (only CLIENT_FETCH_ERROR is dropped)", () => {
+ expect(
+ isDenylistedNoiseEvent(
+ messageEvent("[next-auth][error][SIGNIN_OAUTH_ERROR] boom"),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps a phrase-quoting app error delivered as a MESSAGE event", () => {
+ // Same safety contract on the message-event path: whole-message equality
+ // means a longer app message is not caught even without an exception.
+ expect(
+ isDenylistedNoiseEvent(messageEvent("Failed to fetch created model")),
+ ).toBe(false);
+ });
+
+ it("keeps the generic prod error-boundary string as a MESSAGE event (still excluded)", () => {
+ // captureConsoleIntegration delivers this 1MY string as a message event;
+ // it must survive on that path too, not just the exception path.
+ expect(
+ isDenylistedNoiseEvent(
+ messageEvent(
+ "A client-side exception has occurred while loading cloud.langfuse.com, see the browser console for more information.",
+ ),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps auth/permission and query-timeout errors (routed to UX, not dropped)", () => {
+ expect(isDenylistedNoiseEvent(exceptionEvent("UNAUTHORIZED"))).toBe(
+ false,
+ );
+ expect(
+ isDenylistedNoiseEvent(
+ exceptionEvent("Query could not be completed within the time limit"),
+ ),
+ ).toBe(false);
+ });
+
+ it("keeps an event with no exception values", () => {
+ expect(
+ isDenylistedNoiseEvent({ message: "some message" } as ErrorEvent),
+ ).toBe(false);
+ });
+
+ it("keeps an event with an empty exception value", () => {
+ expect(isDenylistedNoiseEvent(exceptionEvent(""))).toBe(false);
+ });
+ });
+});
diff --git a/web/src/utils/sentryFilters.ts b/web/src/utils/sentryFilters.ts
index 9dab08f7e7..33f3230e2d 100644
--- a/web/src/utils/sentryFilters.ts
+++ b/web/src/utils/sentryFilters.ts
@@ -67,3 +67,178 @@ export function isNoisyHttpClientPollEvent(event: ErrorEvent): boolean {
return HTTP_CLIENT_NOISE_PATHS.some((noisePath) => path.endsWith(noisePath));
}
+
+/**
+ * Browser/transport messages that mean the client could not complete a network
+ * request at the transport layer: offline, flaky wifi, a throttled/backgrounded
+ * tab, a CORS rejection, or a proxy/infra 5xx that returned an HTML page. Each
+ * is just one engine's name for "the fetch never completed" β€” none is Langfuse
+ * application logic.
+ *
+ * Matched as the WHOLE (normalized) exception message, never as a substring: a
+ * genuine failure does not surface as one of these bare strings. Real API
+ * failures surface server-side (request tracing / logs) and, on the client, as
+ * a *handled* error carrying the server's real message (e.g. `UNAUTHORIZED`).
+ * App code that merely quotes a phrase β€” e.g. `Failed to fetch created model`,
+ * `Failed to fetch channels. Please check your Slack connection` β€” is longer
+ * than the bare string and is therefore KEPT. See the negative fixtures in
+ * `sentryFilters.clienttest.ts`.
+ */
+const TRANSPORT_FAILURE_MESSAGES: readonly string[] = [
+ "Failed to fetch", // Chrome / Chromium fetch network failure
+ "NetworkError when attempting to fetch resource", // Firefox fetch network failure
+ "Load failed", // Safari / WebKit fetch network failure
+];
+
+/**
+ * Message prefixes emitted by non-Langfuse code (framework / vendor). These are
+ * unambiguous, vendor-namespaced strings that our own code cannot produce, so
+ * matching them by prefix cannot swallow a real app error.
+ */
+const NOISE_MESSAGE_PREFIXES: readonly string[] = [
+ // NextAuth's client `SessionProvider` logs this via `console.error` (picked up
+ // by `captureConsoleIntegration`) when its 5-min / on-focus session poll fails
+ // transiently β€” same transient root as the httpClient poll already filtered by
+ // `isNoisyHttpClientPollEvent`. The `[next-auth]` namespace can only come from
+ // the library, never from app code.
+ "[next-auth][error][CLIENT_FETCH_ERROR]",
+ // PostHog analytics SDK notices / client-side rate-limit logs. Third-party.
+ "[PostHog.js]",
+ // `Response.json()` on a non-JSON body (a 5xx / HTML proxy page returned where
+ // JSON was expected). This is the response not being ours-as-JSON, i.e. a
+ // transport/infra artifact, not app logic.
+ "Failed to execute 'json' on 'Response'",
+ // `@sentry/nextjs`'s own pages-router `_error` instrumentation calls
+ // `captureException(err || `_error.js called with falsy error (${err})`)`, so
+ // the fallback message always STARTS with this literal (`(undefined)`,
+ // `(null)`, ...). It is a framework artifact with no real error attached.
+ "_error.js called with falsy error",
+];
+
+/**
+ * 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
+ * the wrapper prefix (`TRPCClientError: Failed to fetch`). We strip ONLY this
+ * one known wrapper prefix and match the inner phrase, because the raw
+ * `TRPCClientError:` prefix also fronts real, must-keep errors.
+ */
+const TRPC_CLIENT_ERROR_PREFIX = "TRPCClientError: ";
+
+function coreMessage(value: string): string {
+ const withoutWrapper = value.startsWith(TRPC_CLIENT_ERROR_PREFIX)
+ ? value.slice(TRPC_CLIENT_ERROR_PREFIX.length)
+ : value;
+ // Strip engine-specific decorations so the whole-message comparison stays
+ // exact yet engine-agnostic:
+ // - a trailing ` (host)` parenthetical Chrome appends, e.g.
+ // `Failed to fetch (cloud.langfuse.com)` -> `Failed to fetch`;
+ // - a single trailing period Firefox appends to its transport message.
+ // Only a WHOLE trailing parenthetical/period is removed, so a real app error
+ // that merely quotes a phrase (`Failed to fetch created model`) is untouched
+ // and still fails the exact-equality match.
+ return withoutWrapper
+ .trim()
+ .replace(/\s*\([^()]*\)$/, "")
+ .replace(/\.$/, "")
+ .trim();
+}
+
+/**
+ * True for known-benign CLIENT-side noise that cannot be a real Langfuse app
+ * bug: browser-level network/transport failures, transient framework/vendor
+ * poll logs, and expected browser-permission / cancellation artifacts. Returning
+ * `true` drops the event in `beforeSend`.
+ *
+ * Design rule (safety first): only signatures that CANNOT represent a real app
+ * error are listed, each keyed on an unambiguous signature (whole-message match,
+ * vendor-namespaced prefix, or exception `type` + a required message guard) so a
+ * real error that merely quotes a phrase still flows to Sentry. When in doubt, a
+ * signature is left out. Real outages behind these client amplifications remain
+ * observable server-side (request tracing / logs).
+ *
+ * Event shape: message-signature rules are checked against the exception value
+ * AND the message-event fields (`event.message` / `event.logentry.message`),
+ * because console-origin noise (NextAuth `CLIENT_FETCH_ERROR`, PostHog notices,
+ * the Next.js `_error.js` artifact) is captured by `captureConsoleIntegration`
+ * as a MESSAGE event with NO `event.exception` (no stacktrace is attached by
+ * default). The `type`-guarded rules stay exception-only β€” message events carry
+ * no exception `type`, and those artifacts always arrive as thrown exceptions.
+ *
+ * DELIBERATELY NOT dropped here (needs separate, verified handling β€” do not add
+ * without confirming the real error is still captured elsewhere):
+ * - the generic prod error-boundary string `A client-side exception has
+ * 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.
+ */
+export function isDenylistedNoiseEvent(event: ErrorEvent): boolean {
+ const exception = event.exception?.values?.[0];
+ const exceptionType = exception?.type;
+ const exceptionValue = exception?.value;
+ const hasExceptionValue =
+ typeof exceptionValue === "string" && exceptionValue.length > 0;
+
+ // The message-signature rules run against the exception value when present,
+ // otherwise the message-event text (console-origin noise has no exception).
+ const messageText =
+ (hasExceptionValue ? exceptionValue : undefined) ??
+ event.message ??
+ event.logentry?.message;
+
+ if (typeof messageText === "string" && messageText.length > 0) {
+ const core = coreMessage(messageText);
+
+ // --- A. Transport / connectivity (whole-message match after unwrapping) ---
+ if (TRANSPORT_FAILURE_MESSAGES.includes(core)) return true;
+
+ // --- A + B + C. Unambiguous framework/vendor/transport prefixes (incl.
+ // NextAuth, PostHog, non-JSON Response.json(), and the Next.js `_error.js`
+ // falsy-error artifact). Anchored with startsWith, never a loose includes. ---
+ if (NOISE_MESSAGE_PREFIXES.some((prefix) => core.startsWith(prefix))) {
+ return true;
+ }
+
+ // --- A. Server returned an HTML error page where JSON was expected. ---
+ // Requires the JSON-parse signature (`is not valid JSON`) AND an HTML body
+ // marker, so it stays a "parsed an HTML error page as JSON" transport
+ // artifact and does NOT overlap the chunk-load / stale-deploy `SyntaxError`
+ // family (script parsing an HTML page), which is handled separately.
+ if (
+ messageText.includes("Unexpected token '<'") &&
+ messageText.includes("<html") &&
+ messageText.includes("is not valid JSON")
+ ) {
+ return true;
+ }
+ }
+
+ // --- C. `type`-guarded rules β€” exception events only (message events carry
+ // no exception `type`; these artifacts always arrive as thrown exceptions). ---
+ if (typeof exceptionValue === "string") {
+ // Expected clipboard permission denial (we already fall back). The generic
+ // `NotAllowedError` type (autoplay, fullscreen, ...) REQUIRES a clipboard
+ // marker alongside it.
+ if (
+ exceptionType === "NotAllowedError" &&
+ (exceptionValue.includes("Clipboard") ||
+ exceptionValue.includes("writeText"))
+ ) {
+ return true;
+ }
+
+ // Intentional request cancellation (nav away / superseded query).
+ if (
+ exceptionType === "AbortError" &&
+ (exceptionValue.includes("signal is aborted") ||
+ exceptionValue.includes("The operation was aborted"))
+ ) {
+ return true;
+ }
+ }
+
+ return false;
+}