Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -1347,6 +1348,8 @@ export abstract class Client<O extends ClientOptions = ClientOptions> {
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');
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/integrations/dedupe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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') {

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.

[m] packages/core/src/integrations/dedupe.ts:22: A sampled-out duplicate now counts in sessions, but the same duplicate sampled in does not

With mode: 'ignore', Dedupe skips the sampled-out error entirely, so it no longer drops it when it duplicates the previous sent error. The error then reaches beforeSend and _updateSessions. The same duplicate, sampled in, is still dropped by Dedupe and does not count. So session health now depends on the sample roll, which goes against the goal in _updateSessions ("sampling only saves quota, so the error must still count" as if it were sent).

Trigger: Error('dup') is sent, a new session starts (or the second copy is unhandled), then the same error is captured again. I checked with a scratch test (Dedupe, beforeSend, a fresh ok session before the second capture):

second capture session.errors beforeSend calls outcome
sampled in (HEAD and base) 0 1 event_processor
sampled out, base 0 1 event_processor
sampled out, this PR 1 2 sample_rate

A fix that keeps both goals: for a sampled-out error, Dedupe still compares it with previousEvent (and drops it if it is a duplicate) but does not store it as previousEvent. The ignore doc in dedupeContext.ts ("does not compare it and does not remember it") would change with it.

return currentEvent;
}

Expand Down
20 changes: 20 additions & 0 deletions packages/core/src/utils/dedupeContext.ts
Original file line number Diff line number Diff line change
@@ -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<EventHint, DedupeContext>();

/** 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);
}
78 changes: 74 additions & 4 deletions packages/core/test/lib/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});

Expand Down Expand Up @@ -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 });
Expand Down
185 changes: 157 additions & 28 deletions packages/core/test/lib/integrations/dedupe.test.ts
Original file line number Diff line number Diff line change
@@ -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: {
Expand Down Expand Up @@ -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', () => {

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.

[m] packages/core/test/lib/integrations/dedupe.test.ts:194: The "transactions between errors" case was dropped in the port

The old processEvent test ignores transactions between errors was removed, and the new integration suite has no case with a typed event (transaction, replay) between two equal errors. That case covers the currentEvent.type half of the condition this PR changed on dedupe.ts:22. I removed currentEvent.type || from that line and all 22 tests in this file still pass. I also searched dev-packages/node-integration-tests/suites/integrations/dedupe/ and found no transaction case there either.

A port that fits the new suite: capture Error('duplicate'), then client.captureEvent({ type: 'transaction', transaction: 'wat', ... }), then the same error again, and expect sendEventCalled once for the errors.

beforeEach(() => {
TestClient.instance = undefined;
TestClient.sendEventCalled = undefined;
resetGlobals();
});

function initClient(options: Partial<TestClientOptions> = {}): 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();
});
});
});
Loading