diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 4967bacbf596..7923159e6293 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -36,6 +36,7 @@ import type { StartSpanOptions } from './types/startSpanOptions'; import type { Transport, TransportMakeRequestResponse } from './types/transport'; import type { ResolvedDataCollection } from './types/datacollection'; import { createClientReportEnvelope } from './utils/clientreport'; +import { setDedupeContext } from './utils/dedupeContext'; import { consoleSandbox, debug } from './utils/debug-logger'; import { dsnToString, makeDsn } from './utils/dsn'; import { addItemToEnvelope, createAttachmentEnvelopeItem, getDataCategoryByType } from './utils/envelope'; @@ -1347,6 +1348,8 @@ export abstract class Client { return resolvedSyncPromise(); } + // The error is never sent, so it must not make a later copy of it a duplicate. + setDedupeContext(hint, { mode: 'ignore' }); return this._applyFilters(event, hint, currentScope, isolationScope).then(processedEvent => { this._updateSessions(processedEvent, currentScope, isolationScope); this.recordDroppedEvent('sample_rate', 'error'); diff --git a/packages/core/src/integrations/dedupe.ts b/packages/core/src/integrations/dedupe.ts index 357f6f52959a..38f40af697aa 100644 --- a/packages/core/src/integrations/dedupe.ts +++ b/packages/core/src/integrations/dedupe.ts @@ -4,6 +4,7 @@ import type { Event } from '../types/event'; import type { Exception } from '../types/exception'; import type { IntegrationFn } from '../types/integration'; import { debug } from '../utils/debug-logger'; +import { getDedupeContext } from '../utils/dedupeContext'; import { getFramesFromEvent } from '../utils/stacktrace'; const INTEGRATION_NAME = 'Dedupe' as const; @@ -13,10 +14,12 @@ const _dedupeIntegration = (() => { return { name: INTEGRATION_NAME, - processEvent(currentEvent) { + processEvent(currentEvent, hint) { + const context = getDedupeContext(hint); // We want to ignore any non-error type events, e.g. transactions or replays // These should never be deduped, and also not be compared against as _previousEvent. - if (currentEvent.type) { + // Errors that are never sent (e.g. sampled out) must not make a later error a duplicate. + if (currentEvent.type || context?.mode === 'ignore') { return currentEvent; } diff --git a/packages/core/src/utils/dedupeContext.ts b/packages/core/src/utils/dedupeContext.ts new file mode 100644 index 000000000000..d01081bc989d --- /dev/null +++ b/packages/core/src/utils/dedupeContext.ts @@ -0,0 +1,20 @@ +import type { EventHint } from '../types/event'; + +/** + * How the Dedupe integration treats an error event. The client sets it before event processors run. + * + * - `ignore`: The error is never sent. Dedupe does not compare it and does not remember it. + */ +export type DedupeContext = { mode: 'ignore' }; + +const dedupeContexts = new WeakMap(); + +/** Sets how the Dedupe integration treats the error event of this hint. */ +export function setDedupeContext(hint: EventHint, context: DedupeContext): void { + dedupeContexts.set(hint, context); +} + +/** Gets how the Dedupe integration treats the error event of this hint. */ +export function getDedupeContext(hint: EventHint): DedupeContext | undefined { + return dedupeContexts.get(hint); +} diff --git a/packages/core/test/lib/client.test.ts b/packages/core/test/lib/client.test.ts index 1fc028089b03..9a6d582f984e 100644 --- a/packages/core/test/lib/client.test.ts +++ b/packages/core/test/lib/client.test.ts @@ -574,17 +574,29 @@ describe('Client', () => { expect(TestClient.instance!.event).toBeUndefined(); }); - test('(known limitation) replaces lastEventId with a sampled-out error ID when a session exists', () => { - // After a successfully sent error, a subsequent sampled-out error replaces lastEventId() even though that new ID has no corresponding event in Sentry. - // With a session, the `setLastEventId` call in `_prepareEvent` executes before the `sampleRate` check + test('does not set lastEventId when a sampled-out error cannot change the session', () => { const client = new TestClient(getDefaultTestClientOptions({ dsn: PUBLIC_DSN })); - getCurrentScope().setSession(makeSession()); + setCurrentClient(client); + getCurrentScope().setSession(makeSession({ status: 'crashed' })); client.captureException(new Error('sent exception'), { event_id: 'sent-event-id' }); client.getOptions().sampleRate = 0; client.captureException(new Error('sampled-out exception'), { event_id: 'sampled-out-event-id' }); expect(TestClient.instance!.event?.event_id).toBe('sent-event-id'); + expect(lastEventId()).toBe('sent-event-id'); + }); + + test('(known limitation) sets lastEventId to a sampled-out error ID when the error can change the session', () => { + // With a session that the error can change, the `setLastEventId` call in `_prepareEvent` executes before the + // error is dropped, even though that ID has no corresponding event in Sentry. + const client = new TestClient(getDefaultTestClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0 })); + setCurrentClient(client); + getCurrentScope().setSession(makeSession()); + + client.captureException(new Error('sampled-out exception'), { event_id: 'sampled-out-event-id' }); + + expect(TestClient.instance!.event).toBeUndefined(); expect(lastEventId()).toBe('sampled-out-event-id'); }); @@ -3863,6 +3875,64 @@ describe('Client', () => { }); }); + describe('errors that are never sent', () => { + test('drops sampled-out errors before event processing when they cannot change the session', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + const client = new TestClient(getDefaultTestClientOptions({ dsn: PUBLIC_DSN, beforeSend, sampleRate: 0 })); + setCurrentClient(client); + const session = makeSession({ status: 'crashed' }); + getCurrentScope().setSession(session); + + client.captureException(new Error('sampled out')); + + expect(beforeSend).not.toHaveBeenCalled(); + expect(session.errors).toBe(0); + expect(client._clearOutcomes()).toEqual([{ reason: 'sample_rate', category: 'error', quantity: 1 }]); + }); + + test('counts a sampled-out message that the scope makes fatal in a session that already has an error', () => { + const client = new TestClient(getDefaultTestClientOptions({ dsn: PUBLIC_DSN })); + setCurrentClient(client); + const session = makeSession(); + getCurrentScope().setSession(session); + + client.captureException(new Error('sent')); + client.getOptions().sampleRate = 0; + getCurrentScope().setLevel('fatal'); + client.captureMessage('sampled out'); + + expect(session.status).toBe('crashed'); + expect(session.errors).toBe(1); + }); + + test('records a sampled-out error that an event processor drops as dropped by the event processor', () => { + const client = new TestClient(getDefaultTestClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0 })); + setCurrentClient(client); + const session = makeSession(); + getCurrentScope().setSession(session); + client.addEventProcessor(() => null); + + client.captureException(new Error('sampled out')); + + expect(session.errors).toBe(0); + expect(client._clearOutcomes()).toEqual([{ reason: 'event_processor', category: 'error', quantity: 1 }]); + }); + + test('records a sampled-out error that `beforeSend` drops as dropped by `beforeSend`', () => { + const client = new TestClient( + getDefaultTestClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend: () => null }), + ); + setCurrentClient(client); + const session = makeSession(); + getCurrentScope().setSession(session); + + client.captureException(new Error('sampled out')); + + expect(session.errors).toBe(0); + expect(client._clearOutcomes()).toEqual([{ reason: 'before_send', category: 'error', quantity: 1 }]); + }); + }); + describe('recordDroppedEvent()/_clearOutcomes()', () => { test('records and returns outcomes', () => { const options = getDefaultTestClientOptions({ dsn: PUBLIC_DSN }); diff --git a/packages/core/test/lib/integrations/dedupe.test.ts b/packages/core/test/lib/integrations/dedupe.test.ts index 5220d9d045ff..0913850661d0 100644 --- a/packages/core/test/lib/integrations/dedupe.test.ts +++ b/packages/core/test/lib/integrations/dedupe.test.ts @@ -1,9 +1,22 @@ -import { describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + captureException, + getCurrentScope, + linkedErrorsIntegration, + makeSession, + setCurrentClient, + withScope, +} from '../../../src'; import { _shouldDropEvent, dedupeIntegration } from '../../../src/integrations/dedupe'; import type { Event as SentryEvent } from '../../../src/types/event'; import type { Exception } from '../../../src/types/exception'; import type { StackFrame } from '../../../src/types/stackframe'; import type { Stacktrace } from '../../../src/types/stacktrace'; +import { getDefaultTestClientOptions, TestClient, type TestClientOptions } from '../../mocks/client'; +import { AsyncTestIntegration } from '../../mocks/integration'; +import { resetGlobals } from '../../testutils'; + +const PUBLIC_DSN = 'https://username@domain/123'; type EventWithException = SentryEvent & { exception: { @@ -178,33 +191,149 @@ describe('Dedupe', () => { }); }); - describe('processEvent', () => { - it('ignores consecutive errors', () => { - const integration = dedupeIntegration(); - - expect(integration.processEvent?.(clone(exceptionEvent), {}, {} as any)).not.toBeNull(); - expect(integration.processEvent?.(clone(exceptionEvent), {}, {} as any)).toBeNull(); - expect(integration.processEvent?.(clone(exceptionEvent), {}, {} as any)).toBeNull(); - }); - - it('ignores transactions between errors', () => { - const integration = dedupeIntegration(); - - expect(integration.processEvent?.(clone(exceptionEvent), {}, {} as any)).not.toBeNull(); - expect( - integration.processEvent?.( - { - event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', - message: 'someMessage', - transaction: 'wat', - type: 'transaction', - }, - {}, - {} as any, - ), - ).not.toBeNull(); - expect(integration.processEvent?.(clone(exceptionEvent), {}, {} as any)).toBeNull(); - expect(integration.processEvent?.(clone(exceptionEvent), {}, {} as any)).toBeNull(); + describe('integration', () => { + beforeEach(() => { + TestClient.instance = undefined; + TestClient.sendEventCalled = undefined; + resetGlobals(); + }); + + function initClient(options: Partial = {}): TestClient { + const client = new TestClient( + getDefaultTestClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()], ...options }), + ); + setCurrentClient(client); + client.init(); + return client; + } + + it('drops consecutive duplicate errors', () => { + const sendEventCalled = vi.fn(); + TestClient.sendEventCalled = sendEventCalled; + const client = initClient(); + + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate')); + + expect(sendEventCalled).toHaveBeenCalledOnce(); + expect(client._clearOutcomes()).toEqual([{ reason: 'event_processor', category: 'error', quantity: 2 }]); + }); + + it('compares an event only with the previous event', () => { + const sendEventCalled = vi.fn(); + TestClient.sendEventCalled = sendEventCalled; + const client = initClient(); + + for (const value of ['a', 'a', 'b', 'b', 'a']) { + client.captureException(new Error(value)); + } + client.captureMessage('message'); + client.captureMessage('message'); + + expect(sendEventCalled).toHaveBeenCalledTimes(4); + expect(client._clearOutcomes()).toEqual([{ reason: 'event_processor', category: 'error', quantity: 3 }]); + }); + + it('compares errors with the fingerprint from the scope', () => { + const sendEventCalled = vi.fn(); + TestClient.sendEventCalled = sendEventCalled; + const client = initClient(); + + for (const fingerprint of ['a', 'b']) { + withScope(scope => { + scope.setFingerprint([fingerprint]); + client.captureException(new Error('same error'), undefined, scope); + }); + } + + expect(sendEventCalled).toHaveBeenCalledTimes(2); + }); + + it('compares errors with their linked errors', () => { + const sendEventCalled = vi.fn(); + TestClient.sendEventCalled = sendEventCalled; + initClient({ integrations: [linkedErrorsIntegration(), dedupeIntegration()] }); + + for (const cause of ['a', 'a', 'b']) { + captureException(Object.assign(new Error('same error'), { cause: new Error(cause) })); + } + + expect(sendEventCalled).toHaveBeenCalledTimes(2); + }); + + it('does not let duplicate errors push other errors out of the promise buffer', async () => { + const sendEventCalled = vi.fn(); + TestClient.sendEventCalled = sendEventCalled; + const client = initClient({ + integrations: [dedupeIntegration(), new AsyncTestIntegration()], + transportOptions: { bufferSize: 2 }, + }); + getCurrentScope().setSession(makeSession()); + const sendEnvelopeSpy = vi.spyOn(client, 'sendEnvelope'); + + for (let i = 0; i < 10; i++) { + client.captureException(new Error('duplicate')); + } + client.captureException(new Error('other error')); + await client.flush(); + + expect(sendEventCalled).toHaveBeenCalledTimes(2); + expect(sendEnvelopeSpy).toHaveBeenCalledWith([ + expect.any(Object), + [ + [ + { type: 'client_report' }, + expect.objectContaining({ + discarded_events: [{ reason: 'event_processor', category: 'error', quantity: 9 }], + }), + ], + ], + ]); + }); + + it('does not count a duplicate error that a later event processor drops', () => { + const client = initClient(); + const session = makeSession(); + getCurrentScope().setSession(session); + client.addEventProcessor(() => null); + + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate')); + + expect(session.errors).toBe(0); + expect(client._clearOutcomes()).toEqual([{ reason: 'event_processor', category: 'error', quantity: 2 }]); + }); + + it('drops a handled duplicate error from the same isolation scope without calling `beforeSend` again', () => { + const beforeSend = vi.fn(() => null); + const client = initClient({ beforeSend }); + const session = makeSession(); + getCurrentScope().setSession(session); + + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate')); + + expect(beforeSend).toHaveBeenCalledOnce(); + expect(session.errors).toBe(0); + expect(client._clearOutcomes()).toEqual([ + { reason: 'before_send', category: 'error', quantity: 1 }, + { reason: 'event_processor', category: 'error', quantity: 2 }, + ]); + }); + + it('does not drop a sampled-in error that duplicates a sampled-out error', () => { + const sendEventCalled = vi.fn(); + TestClient.sendEventCalled = sendEventCalled; + const client = initClient({ sampleRate: 0 }); + getCurrentScope().setSession(makeSession()); + + client.captureException(new Error('duplicate')); + client.getOptions().sampleRate = 1; + client.captureException(new Error('duplicate')); + + expect(sendEventCalled).toHaveBeenCalledOnce(); }); }); });