From a23a5e269c35ebc60de50a9fdb271e77d0ad9bda Mon Sep 17 00:00:00 2001 From: s1gr1d <32902192+s1gr1d@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:35:49 +0100 Subject: [PATCH 1/6] ref(core): Split event processing into pipeline steps Split _processEvent into steps in the order of the client spec: roll the sample rate, run the filters (_applyFilters: event processors and the beforeSend callbacks), update the sessions (_updateSessions), and send. A sampled-out error goes through _countSampledOutError, which counts it in sessions if the filters keep it. No behavior change. The next change to which errors count in sessions can then override these steps instead of copying them. Refs #25605 --- docs/event-sending.md | 28 ++++--- packages/core/src/client.ts | 155 ++++++++++++++++++++++++------------ 2 files changed, 121 insertions(+), 62 deletions(-) diff --git a/docs/event-sending.md b/docs/event-sending.md index b72eda1d0746..44661e8f4379 100644 --- a/docs/event-sending.md +++ b/docs/event-sending.md @@ -11,12 +11,14 @@ This document gives an outline for how event sending works, and which which plac - `baseclient.eventFromException()` - `baseclient._captureEvent()` - `baseclient._processEvent()` - - `baseclient._prepareEvent()` - - `baseclient._applyClientOptions()` - - `baseclient._applyIntegrationsMetadata()` - - `scope.applyToEvent()` - - `baseclient._normalizeEvent()` - - `baseclient._updateSessionFromEvent()` + - `baseclient._applyFilters()` + - `baseclient._prepareEvent()` + - `baseclient._applyClientOptions()` + - `baseclient._applyIntegrationsMetadata()` + - `scope.applyToEvent()` + - `baseclient._normalizeEvent()` + - `beforeSend()` / `beforeSendTransaction()` + - `baseclient._updateSessions()` - `baseclient.sendEvent()` - `createEventEnvelope()` - `getSdkMetadataForEnvelopeHeader()` @@ -40,12 +42,14 @@ This document gives an outline for how event sending works, and which which plac - `baseclient.eventFromException()` - `baseclient._captureEvent()` - `baseclient._processEvent()` - - `baseclient._prepareEvent()` - - `baseclient._applyClientOptions()` - - `baseclient._applyIntegrationsMetadata()` - - `scope.applyToEvent()` - - `baseclient._normalizeEvent()` - - `baseclient._updateSessionFromEvent()` + - `baseclient._applyFilters()` + - `baseclient._prepareEvent()` + - `baseclient._applyClientOptions()` + - `baseclient._applyIntegrationsMetadata()` + - `scope.applyToEvent()` + - `baseclient._normalizeEvent()` + - `beforeSend()` / `beforeSendTransaction()` + - `baseclient._updateSessions()` - `baseclient.sendEvent()` - `createEventEnvelope()` - `getSdkMetadataForEnvelopeHeader()` diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 6b3b2e381b82..91ab7dbf912c 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -49,7 +49,7 @@ import { makePromiseBuffer, type PromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from import { safeMathRandom } from './utils/randomSafeContext'; import { safeCallback } from './utils/safeCallback'; import { reparentChildSpans, shouldIgnoreSpan } from './utils/should-ignore-span'; -import { rejectedSyncPromise } from './utils/syncpromise'; +import { resolvedSyncPromise } from './utils/syncpromise'; import { convertSpanJsonToTransactionEvent, convertTransactionEventToSpanJson } from './utils/transactionEvent'; import { maybeWarnAboutIgnoredTransactionOptions } from './utils/warnAboutIgnoredTransactionOptions'; import { resolveDataCollectionOptions } from './utils/data-collection/resolveDataCollectionOptions'; @@ -1297,6 +1297,52 @@ export abstract class Client { afterSetupIntegrations(this, integrations); } + /** + * Updates the sessions that an error counts towards. Runs after event processors and `beforeSend` kept the error, + * also when sampling drops it: sampling only saves quota, so the error must still count. + */ + protected _updateSessions(event: Event, currentScope: Scope, isolationScope: Scope): void { + const session = currentScope.getSession() || isolationScope.getSession(); + if (session) { + this._updateSessionFromEvent(session, event); + } + } + + /** + * Whether an error can still change a session that {@link Client._updateSessions} updates. + * + * Event processing can still make the error fatal (e.g. the scope level), so any error can change an `ok` session. + */ + protected _canErrorChangeSessions( + _event: Event, + _hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): boolean { + return (currentScope.getSession() || isolationScope.getSession())?.status === 'ok'; + } + + /** + * Counts a sampled-out error in sessions if the filters keep it, because sampling only saves quota. + * Records the outcome of the error. + */ + protected _countSampledOutError( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + if (!this._canErrorChangeSessions(event, hint, currentScope, isolationScope)) { + this.recordDroppedEvent('sample_rate', 'error'); + return resolvedSyncPromise(); + } + + return this._applyFilters(event, hint, currentScope, isolationScope).then(processedEvent => { + this._updateSessions(processedEvent, currentScope, isolationScope); + this.recordDroppedEvent('sample_rate', 'error'); + }); + } + /** Updates existing session based on the provided event */ protected _updateSessionFromEvent(session: Session, event: Event): void { // initially, set `unhandled` based on the event level and update from exceptions if there are any later on @@ -1471,34 +1517,64 @@ export abstract class Client { currentScope: Scope, isolationScope: Scope, ): PromiseLike { - const options = this.getOptions(); - const { sampleRate } = options; + const { sampleRate } = this.getOptions(); + + const processed: PromiseLike = rollSampleRate(event, sampleRate) + ? this._countSampledOutError(event, hint, currentScope, isolationScope).then(() => { + throw _makeSampledOutError(sampleRate); + }) + : this._applyFilters(event, hint, currentScope, isolationScope).then(processedEvent => { + if (isErrorEvent(event)) { + this._updateSessions(processedEvent, currentScope, isolationScope); + } + + this.sendEvent(processedEvent, hint); + return processedEvent; + }); + + return processed.then(null, reason => { + if (_isDoNotSendEventError(reason) || _isInternalError(reason)) { + throw reason; + } + + this.captureException(reason, { + mechanism: { + handled: false, + type: 'internal', + }, + data: { + __sentry__: true, + }, + originalException: reason, + }); + throw _makeInternalError( + `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, + ); + }); + } + /** + * Runs the event processors and the matching `beforeSend*` callback, and records an outcome when one of them drops + * the event. + * + * @returns A SyncPromise that resolves with the processed event, or rejects when the event is dropped. + */ + protected _applyFilters( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + const options = this.getOptions(); const isTransaction = isTransactionEvent(event); - const isError = isErrorEvent(event); - const eventType = event.type || 'error'; - const beforeSendLabel = `before send for type \`${eventType}\``; + const beforeSendLabel = `before send for type \`${event.type || 'error'}\``; + const dataCategory = getDataCategoryByType(event.type); let beforeSendDropReason: BeforeSendDropReason = 'before_send'; let ignoredSpanCount = 0; - - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate); - const isSampledOut = isError && typeof parsedSampleRate === 'number' && safeMathRandom() > parsedSampleRate; - const dataCategory = getDataCategoryByType(event.type); // Spans that event processors removed are already recorded in `prepareEvent`, so all later // span outcomes are relative to the span count of the prepared event. let preparedSpanCount = 0; - const session = currentScope.getSession() || isolationScope.getSession(); - // A sampled-out error only runs the pipeline to update the session. Without a session it could update, - // drop it right away so it doesn't hold a promise buffer slot while event processors run. - if (isSampledOut && session?.status !== 'ok') { - this.recordDroppedEvent('sample_rate', 'error'); - return rejectedSyncPromise(_makeSampledOutError(sampleRate)); - } - return this._prepareEvent(event, hint, currentScope, isolationScope) .then(prepared => { if (prepared === null) { @@ -1546,15 +1622,6 @@ export abstract class Client { throw _makeDoNotSendEventError(`${dropMessage}, will not send event.`); } - if (isError && session) { - this._updateSessionFromEvent(session, processedEvent); - } - - if (isSampledOut) { - this.recordDroppedEvent('sample_rate', 'error'); - throw _makeSampledOutError(sampleRate); - } - if (isTransaction) { const droppedSpanCount = preparedSpanCount - ignoredSpanCount - (processedEvent.spans?.length || 0); if (droppedSpanCount > 0) { @@ -1574,27 +1641,7 @@ export abstract class Client { }; } - this.sendEvent(processedEvent, hint); return processedEvent; - }) - .then(null, reason => { - if (_isDoNotSendEventError(reason) || _isInternalError(reason)) { - throw reason; - } - - this.captureException(reason, { - mechanism: { - handled: false, - type: 'internal', - }, - data: { - __sentry__: true, - }, - originalException: reason, - }); - throw _makeInternalError( - `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: ${reason}`, - ); }); } @@ -1783,6 +1830,14 @@ function processBeforeSend( return processedEvent; } +/** + * Rolls the dice for `sampleRate`. Only errors are sampled here, transactions are sampled when they start. + */ +function rollSampleRate(event: Event, sampleRate: ClientOptions['sampleRate']): boolean { + const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate); + return isErrorEvent(event) && typeof parsedSampleRate === 'number' && safeMathRandom() > parsedSampleRate; +} + function isErrorEvent(event: Event): event is ErrorEvent { return event.type === undefined; } From ab8816693ce86085c305191d724959a3176505be Mon Sep 17 00:00:00 2001 From: s1gr1d <32902192+s1gr1d@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:28:56 +0100 Subject: [PATCH 2/6] fix(core): Do not count dropped errors in request sessions Request sessions counted an error at capture time, before ignoreErrors, event processors and beforeSend ran. So errors that the user chose to drop still lowered the crash-free rate. Errors now count after beforeSend, as the client spec requires. Sampling and Dedupe only save quota, so an error that they drop still counts if the filters keep it. On the server, such an error runs the filters outside of the promise buffer, with its own limit, so it never pushes a real error out. Dedupe ignores sampled-out errors, so a repeated error is no longer dropped every time with a low sampleRate. Fixes #25605 --- .../node-suites/excludes.ts | 1 + .../filtered-errors-session-aggregate/test.ts | 33 ++ .../suites/sessions/instrument.mjs | 2 + .../instrument.mjs | 16 + .../sampled-errors-session-aggregate/test.ts | 33 ++ .../suites/sessions/server.mjs | 9 + packages/core/src/client.ts | 27 +- packages/core/src/integrations/dedupe.ts | 21 +- .../http/record-request-session.ts | 43 ++- packages/core/src/scope.ts | 2 + packages/core/src/server-runtime-client.ts | 183 ++++++++-- packages/core/src/utils/dedupeContext.ts | 34 ++ packages/core/src/utils/misc.ts | 14 +- packages/core/src/utils/requestSession.ts | 60 ++++ packages/core/test/lib/client.test.ts | 78 ++++- .../core/test/lib/integrations/dedupe.test.ts | 174 +++++++-- .../test/lib/server-runtime-client.test.ts | 329 +++++++++++++++++- 17 files changed, 988 insertions(+), 71 deletions(-) create mode 100644 dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts create mode 100644 dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs create mode 100644 dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts create mode 100644 packages/core/src/utils/dedupeContext.ts create mode 100644 packages/core/src/utils/requestSession.ts diff --git a/dev-packages/bun-integration-tests/node-suites/excludes.ts b/dev-packages/bun-integration-tests/node-suites/excludes.ts index e42f348bc04b..83a1868b9c3b 100644 --- a/dev-packages/bun-integration-tests/node-suites/excludes.ts +++ b/dev-packages/bun-integration-tests/node-suites/excludes.ts @@ -165,6 +165,7 @@ const NO_NATIVE_NODE_FETCH_INTEGRATION = [ // first request gets no spans after that. And an error that reaches the server does not mark // the request session as crashed. const HTTP_SERVER_SPANS_DIFFER = [ + 'suites/sessions/sampled-errors-session-aggregate/test.ts', 'suites/sessions/server-without-process-session/test.ts', 'suites/tracing/httpIntegration/test.ts', ]; diff --git a/dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts b/dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts new file mode 100644 index 000000000000..31afbac41a7f --- /dev/null +++ b/dev-packages/node-integration-tests/suites/sessions/filtered-errors-session-aggregate/test.ts @@ -0,0 +1,33 @@ +import { afterAll, expect, test } from 'vitest'; +import { join } from 'path'; +import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('does not count errors dropped by ignoreErrors or beforeSend', async () => { + const runner = createRunner(__dirname, '..', 'server.mjs') + .withInstrument(join(__dirname, '..', 'instrument.mjs')) + .ignore('span', 'event') + .unignore('sessions') + .expect({ + sessions: agg => { + // Sessions are bucketed by minute; tolerate splits across a minute boundary by summing. + const totals = agg.aggregates.reduce( + (acc, b) => ({ + exited: acc.exited + (b.exited ?? 0), + errored: acc.errored + (b.errored ?? 0), + crashed: acc.crashed + (b.crashed ?? 0), + }), + { exited: 0, errored: 0, crashed: 0 }, + ); + expect(totals).toEqual({ exited: 2, errored: 0, crashed: 0 }); + }, + }) + .start(); + + runner.makeRequest('get', '/test/error_ignored', { expectError: true }); + runner.makeRequest('get', '/test/error_dropped'); + await runner.completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/sessions/instrument.mjs b/dev-packages/node-integration-tests/suites/sessions/instrument.mjs index 943afdd99206..87928b307f09 100644 --- a/dev-packages/node-integration-tests/suites/sessions/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/sessions/instrument.mjs @@ -8,6 +8,8 @@ Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', release: '1.0', transport: loggingTransport, + ignoreErrors: ['Ignored!'], + beforeSend: event => (event.exception?.values?.[0]?.value === 'Dropped!' ? null : event), integrations: [ httpIntegration({ // Flush after 2 seconds (to avoid waiting for the default 60s) diff --git a/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs new file mode 100644 index 000000000000..4ab031797062 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs @@ -0,0 +1,16 @@ +import * as Sentry from '@sentry/node'; +import { loggingTransport } from '@sentry-internal/node-integration-tests'; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + release: '1.0', + transport: loggingTransport, + sampleRate: 0, + integrations: [ + Sentry.httpIntegration({ + // Flush after 2 seconds (to avoid waiting for the default 60s) + sessionFlushingDelayMS: 2_000, + }), + Sentry.expressIntegration(), + ], +}); diff --git a/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts new file mode 100644 index 000000000000..c20347f93ba6 --- /dev/null +++ b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/test.ts @@ -0,0 +1,33 @@ +import { afterAll, expect, test } from 'vitest'; +import { join } from 'path'; +import { cleanupChildProcesses, createRunner } from '../../../utils/runner'; + +afterAll(() => { + cleanupChildProcesses(); +}); + +test('counts errors dropped by sampleRate', async () => { + const runner = createRunner(__dirname, '..', 'server.mjs') + .withInstrument(join(__dirname, 'instrument.mjs')) + .ignore('span', 'event') + .unignore('sessions') + .expect({ + sessions: agg => { + // Sessions are bucketed by minute; tolerate splits across a minute boundary by summing. + const totals = agg.aggregates.reduce( + (acc, b) => ({ + exited: acc.exited + (b.exited ?? 0), + errored: acc.errored + (b.errored ?? 0), + crashed: acc.crashed + (b.crashed ?? 0), + }), + { exited: 0, errored: 0, crashed: 0 }, + ); + expect(totals).toEqual({ exited: 0, errored: 1, crashed: 1 }); + }, + }) + .start(); + + runner.makeRequest('get', '/test/error_handled'); + runner.makeRequest('get', '/test/error_unhandled', { expectError: true }); + await runner.completed(); +}); diff --git a/dev-packages/node-integration-tests/suites/sessions/server.mjs b/dev-packages/node-integration-tests/suites/sessions/server.mjs index f2f8eb5bc05e..00823d7d4fe2 100644 --- a/dev-packages/node-integration-tests/suites/sessions/server.mjs +++ b/dev-packages/node-integration-tests/suites/sessions/server.mjs @@ -32,4 +32,13 @@ app.get('/test/error_handled', (_req, res) => { res.send('Crash!'); }); +app.get('/test/error_ignored', () => { + throw new Error('Ignored!'); +}); + +app.get('/test/error_dropped', (_req, res) => { + Sentry.captureException(new Error('Dropped!')); + res.send('Dropped!'); +}); + startExpressServerAndSendPortToRunner(app); diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 91ab7dbf912c..761ea3a58147 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'; @@ -79,7 +80,7 @@ interface InternalError { [INTERNAL_ERROR_SYMBOL]: true; } -interface DoNotSendEventError { +export interface DoNotSendEventError { message: string; [DO_NOT_SEND_EVENT_SYMBOL]: true; } @@ -91,7 +92,8 @@ function _makeInternalError(message: string): InternalError { }; } -function _makeDoNotSendEventError(message: string): DoNotSendEventError { +/** @internal */ +export function _makeDoNotSendEventError(message: string): DoNotSendEventError { return { message, [DO_NOT_SEND_EVENT_SYMBOL]: true, @@ -268,6 +270,7 @@ export abstract class Client { .then(event => this._captureEvent(event, hintWithEventId, scope)) .then(res => res), 'error', + hintWithEventId, ); return hintWithEventId.event_id; @@ -337,6 +340,7 @@ export abstract class Client { this._process( () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope), dataCategory, + isExceptionEvent(event) ? hintWithEventId : undefined, ); return hintWithEventId.event_id; @@ -1299,7 +1303,7 @@ export abstract class Client { /** * Updates the sessions that an error counts towards. Runs after event processors and `beforeSend` kept the error, - * also when sampling drops it: sampling only saves quota, so the error must still count. + * also when sampling or Dedupe drop it: these only save quota, so the error must still count. */ protected _updateSessions(event: Event, currentScope: Scope, isolationScope: Scope): void { const session = currentScope.getSession() || isolationScope.getSession(); @@ -1322,6 +1326,11 @@ export abstract class Client { return (currentScope.getSession() || isolationScope.getSession())?.status === 'ok'; } + /** Called for an error that never reaches the event pipeline, because the promise buffer is full. */ + protected _onQueueOverflow(_hint: EventHint): void { + // Sessions are updated in the event pipeline only. + } + /** * Counts a sampled-out error in sessions if the filters keep it, because sampling only saves quota. * Records the outcome of the error. @@ -1337,6 +1346,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'); @@ -1648,7 +1659,7 @@ export abstract class Client { /** * Occupies the client with processing and event */ - protected _process(taskProducer: () => PromiseLike, dataCategory: DataCategory): void { + protected _process(taskProducer: () => PromiseLike, dataCategory: DataCategory, errorHint?: EventHint): void { this._numProcessing++; void this._promiseBuffer.add(taskProducer).then( @@ -1661,6 +1672,9 @@ export abstract class Client { if (reason === SENTRY_BUFFER_FULL_ERROR) { this.recordDroppedEvent('queue_overflow', dataCategory); + if (errorHint) { + this._onQueueOverflow(errorHint); + } } return reason; @@ -1845,3 +1859,8 @@ function isErrorEvent(event: Event): event is ErrorEvent { function isTransactionEvent(event: Event): event is TransactionEvent { return event.type === 'transaction'; } + +/** Whether the event is an error event with an exception. */ +export function isExceptionEvent(event: Event): boolean { + return isErrorEvent(event) && !!event.exception?.values?.length; +} diff --git a/packages/core/src/integrations/dedupe.ts b/packages/core/src/integrations/dedupe.ts index 357f6f52959a..aed15cb77ef2 100644 --- a/packages/core/src/integrations/dedupe.ts +++ b/packages/core/src/integrations/dedupe.ts @@ -1,22 +1,29 @@ import { DEBUG_BUILD } from '../debug-build'; import { defineIntegration } from '../integration'; +import type { Scope } from '../scope'; 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 { hasUnhandledException } from '../utils/misc'; import { getFramesFromEvent } from '../utils/stacktrace'; const INTEGRATION_NAME = 'Dedupe' as const; const _dedupeIntegration = (() => { let previousEvent: Event | undefined; + // Isolation scopes (e.g. requests) that already had a copy of the previous event. + let previousEventScopes = new WeakSet(); 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; } @@ -24,10 +31,20 @@ const _dedupeIntegration = (() => { try { if (_shouldDropEvent(currentEvent, previousEvent)) { DEBUG_BUILD && debug.warn('Event dropped due to being a duplicate of previously captured event.'); + // A later copy in the same isolation scope cannot change the session status, unless it is unhandled. + if ( + context?.mode === 'mark' && + (!previousEventScopes.has(context.isolationScope) || hasUnhandledException(currentEvent, hint)) + ) { + previousEventScopes.add(context.isolationScope); + context.isDuplicate = true; + return currentEvent; + } return null; } } catch {} // eslint-disable-line no-empty + previousEventScopes = new WeakSet(context ? [context.isolationScope] : []); return (previousEvent = currentEvent); }, }; diff --git a/packages/core/src/integrations/http/record-request-session.ts b/packages/core/src/integrations/http/record-request-session.ts index fa608118a5a2..4ef568abcf4f 100644 --- a/packages/core/src/integrations/http/record-request-session.ts +++ b/packages/core/src/integrations/http/record-request-session.ts @@ -65,11 +65,7 @@ export function startRequestSession( client.emit('startRequestSession'); let ended = false; - return () => { - if (ended) { - return; - } - ended = true; + const record = (sendNow: boolean): void => { const requestSession = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession; if (client && requestSession) { @@ -78,10 +74,19 @@ export function startRequestSession( const roundedDate = new Date(safeDateNow()); roundedDate.setSeconds(0, 0); const dateBucketKey = roundedDate.toISOString(); + const statusKey = ({ ok: 'exited', crashed: 'crashed', errored: 'errored' } as const)[requestSession.status]; + + if (sendNow) { + DEBUG_BUILD && debug.log('Sending request session that settled during a client flush'); + client.sendSession({ + aggregates: [{ started: dateBucketKey, exited: 0, errored: 0, crashed: 0, [statusKey]: 1 }], + }); + return; + } const existingClientAggregate = clientToRequestSessionAggregatesMap.get(client); const bucket = existingClientAggregate?.[dateBucketKey] || { exited: 0, crashed: 0, errored: 0 }; - bucket[({ ok: 'exited', crashed: 'crashed', errored: 'errored' } as const)[requestSession.status]]++; + bucket[statusKey]++; if (existingClientAggregate) { existingClientAggregate[dateBucketKey] = bucket; @@ -118,4 +123,30 @@ export function startRequestSession( } } }; + + return () => { + if (ended) { + return; + } + ended = true; + + // The event pipeline decides whether an error counts towards the session, and it can still run after the + // response ended (e.g. async event processors), so the status is final only once those errors settle. + const pendingErrors = requestIsolationScope.getScopeData().sdkProcessingMetadata.requestSession?.pendingErrors; + if (!pendingErrors?.size) { + record(false); + return; + } + + // A flush that starts while the errors settle waits for them, but its `flush` hook runs before this session + // is recorded. Such a session is sent at once, so that the flush includes it. + let isFlushing = false; + const unregisterFlushHook = client.on('flush', () => { + isFlushing = true; + }); + void Promise.allSettled(pendingErrors).then(() => { + unregisterFlushHook(); + record(isFlushing); + }); + }; } diff --git a/packages/core/src/scope.ts b/packages/core/src/scope.ts index 7130bc5eb0d2..bc30f24b2e21 100644 --- a/packages/core/src/scope.ts +++ b/packages/core/src/scope.ts @@ -57,6 +57,8 @@ export interface SdkProcessingMetadata { [key: string]: unknown; requestSession?: { status: 'ok' | 'errored' | 'crashed'; + /** Error events of the request that are still in the event pipeline. */ + pendingErrors?: Set>; }; normalizedRequest?: RequestEventData; dynamicSamplingContext?: Partial; diff --git a/packages/core/src/server-runtime-client.ts b/packages/core/src/server-runtime-client.ts index ff1376dbee5d..c91223b89c83 100644 --- a/packages/core/src/server-runtime-client.ts +++ b/packages/core/src/server-runtime-client.ts @@ -1,6 +1,6 @@ import { SERVER_ADDRESS } from '@sentry/conventions/attributes'; import { createCheckInEnvelope } from './checkin'; -import { Client } from './client'; +import { _makeDoNotSendEventError, Client, isExceptionEvent } from './client'; import { getIsolationScope } from './currentScopes'; import { DEBUG_BUILD } from './debug-build'; import { @@ -18,12 +18,21 @@ import type { SeverityLevel } from './types/severity'; import type { BaseTransportOptions, Transport } from './types/transport'; import { debug } from './utils/debug-logger'; import { eventFromMessage, eventFromUnknownInput } from './utils/eventbuilder'; -import { uuid4 } from './utils/misc'; +import { isMarkedDuplicate, setDedupeContext } from './utils/dedupeContext'; +import { hasUnhandledException, isAlreadyCaptured, uuid4 } from './utils/misc'; +import { + addPendingRequestSessionError, + crashRequestSessionIfErrored, + getRequestSession, + setRequestSessionErroredOrCrashed, +} from './utils/requestSession'; import { makePromiseBuffer } from './utils/promisebuffer'; -import { resolvedSyncPromise } from './utils/syncpromise'; +import { rejectedSyncPromise, resolvedSyncPromise } from './utils/syncpromise'; import { _getTraceInfoFromScope } from './utils/trace-info'; import { applyServerTunnelDefaults } from './utils/tunnelDefaults'; +const DUPLICATE_EVENT_ERROR = 'Event is a duplicate of the previously captured event, will not send event.'; + export interface ServerRuntimeClientOptions extends ClientOptions { platform?: string; runtime?: { name: string; version?: string }; @@ -40,6 +49,9 @@ export class ServerRuntimeClient< > extends Client { private _disposeCallbacks: (() => void)[] = []; + /** Number of errors that are never sent, but run through event processing to update sessions. */ + private _numCountingWithoutSlot = 0; + /** * Creates a new Edge SDK instance. * @param options Configuration options for this SDK. @@ -91,7 +103,9 @@ export class ServerRuntimeClient< * @inheritDoc */ public captureException(exception: unknown, hint?: EventHint, scope?: Scope): string { - setCurrentRequestSessionErroredOrCrashed(hint); + if (isAlreadyCaptured(exception)) { + onAlreadyCapturedError(hint); + } return super.captureException(exception, hint, scope); } @@ -99,15 +113,122 @@ export class ServerRuntimeClient< * @inheritDoc */ public captureEvent(event: Event, hint?: EventHint, scope?: Scope): string { - // If the event is of type Exception, then a request session should be captured - const isException = !event.type && event.exception?.values && event.exception.values.length > 0; - if (isException) { - setCurrentRequestSessionErroredOrCrashed(hint); + if (isExceptionEvent(event) && isAlreadyCaptured(hint?.originalException)) { + onAlreadyCapturedError(hint); } - return super.captureEvent(event, hint, scope); } + /** + * @inheritDoc + */ + protected override _processEvent( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + if (!isExceptionEvent(event)) { + return super._processEvent(event, hint, currentScope, isolationScope); + } + + const canCountDuplicate = + this._canCountWithoutSlot() && this._canErrorChangeSessions(event, hint, currentScope, isolationScope); + setDedupeContext( + hint, + canCountDuplicate ? { mode: 'mark', isolationScope, isDuplicate: false } : { mode: 'drop', isolationScope }, + ); + const processedEvent = super._processEvent(event, hint, currentScope, isolationScope); + addPendingRequestSessionError(isolationScope, processedEvent); + return processedEvent; + } + + /** + * Hands a duplicate that Dedupe marked over to {@link ServerRuntimeClient._countWithoutSlot}. + */ + protected override _applyFilters( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + const filtered = super._applyFilters(event, hint, currentScope, isolationScope); + const countDuplicate = (processedEvent: Event): void => { + this._updateSessions(processedEvent, currentScope, isolationScope); + this.recordDroppedEvent('event_processor', 'error'); + }; + + // The event processors before Dedupe are usually synchronous, so most duplicates are known here. + if (isMarkedDuplicate(hint)) { + this._countWithoutSlot(filtered.then(countDuplicate), isolationScope); + return rejectedSyncPromise(_makeDoNotSendEventError(DUPLICATE_EVENT_ERROR)); + } + + return filtered.then(processedEvent => { + // Dedupe ran after an asynchronous event processor. + if (isMarkedDuplicate(hint)) { + countDuplicate(processedEvent); + throw _makeDoNotSendEventError(DUPLICATE_EVENT_ERROR); + } + return processedEvent; + }); + } + + /** + * @inheritDoc + */ + protected override _countSampledOutError( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): PromiseLike { + if (this._canCountWithoutSlot()) { + this._countWithoutSlot(super._countSampledOutError(event, hint, currentScope, isolationScope), isolationScope); + } else { + this.recordDroppedEvent('sample_rate', 'error'); + } + return resolvedSyncPromise(); + } + + /** + * @inheritDoc + */ + protected override _canErrorChangeSessions( + event: Event, + hint: EventHint, + currentScope: Scope, + isolationScope: Scope, + ): boolean { + if (super._canErrorChangeSessions(event, hint, currentScope, isolationScope)) { + return true; + } + if (!isExceptionEvent(event)) { + return false; + } + + const requestSessionStatus = getRequestSession(isolationScope)?.status; + return requestSessionStatus === 'ok' || (requestSessionStatus === 'errored' && hasUnhandledException(event, hint)); + } + + /** + * @inheritDoc + */ + protected override _updateSessions(event: Event, currentScope: Scope, isolationScope: Scope): void { + super._updateSessions(event, currentScope, isolationScope); + if (isExceptionEvent(event)) { + setRequestSessionErroredOrCrashed(isolationScope, hasUnhandledException(event)); + } + } + + /** + * @inheritDoc + */ + protected override _onQueueOverflow(hint: EventHint): void { + // Without the event pipeline, filters cannot drop the error, so it counts. + setRequestSessionErroredOrCrashed(getIsolationScope(), hint.mechanism?.handled === false); + } + /** * Create a cron monitor check in and send it to Sentry. * @@ -242,6 +363,29 @@ export class ServerRuntimeClient< return super._prepareEvent(event, hint, currentScope, isolationScope); } + /** + * Whether an error that is never sent can still run event processing to update sessions. The limit keeps that + * work bounded in an error storm. + */ + private _canCountWithoutSlot(): boolean { + return this._numCountingWithoutSlot < (this._options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE); + } + + /** + * Tracks the session update of an error that is never sent. It runs outside of the promise buffer, so that it + * never takes a slot from an error that is sent. + */ + private _countWithoutSlot(counting: PromiseLike, isolationScope: Scope): void { + this._numProcessing++; + this._numCountingWithoutSlot++; + const settle = (): void => { + this._numProcessing--; + this._numCountingWithoutSlot--; + }; + counting.then(settle, settle); + addPendingRequestSessionError(isolationScope, counting); + } + /** * Process a server-side metric before it is captured. */ @@ -257,19 +401,12 @@ export class ServerRuntimeClient< } } -function setCurrentRequestSessionErroredOrCrashed(eventHint?: EventHint): void { - const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession; - if (requestSession) { - // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular - // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the - // original isolation scope that the http integration stored away. - const isHandledException = eventHint?.mechanism?.handled ?? true; - // A request session can go from "errored" -> "crashed" but not "crashed" -> "errored". - // Crashed (unhandled exception) is worse than errored (handled exception). - if (isHandledException && requestSession.status !== 'crashed') { - requestSession.status = 'errored'; - } else if (!isHandledException) { - requestSession.status = 'crashed'; - } +/** + * An unhandled error that was captured before, e.g. captured as handled, then rethrown and captured again by a + * framework error handler, crashes the request session if the first capture counted. + */ +function onAlreadyCapturedError(hint: EventHint | undefined): void { + if (hint?.mechanism?.handled === false) { + crashRequestSessionIfErrored(getIsolationScope()); } } diff --git a/packages/core/src/utils/dedupeContext.ts b/packages/core/src/utils/dedupeContext.ts new file mode 100644 index 000000000000..ead07f6fca5f --- /dev/null +++ b/packages/core/src/utils/dedupeContext.ts @@ -0,0 +1,34 @@ +import type { Scope } from '../scope'; +import type { EventHint } from '../types/event'; + +/** + * How the Dedupe integration treats an error event. The client sets it before event processors run. + * + * - `drop`: Dedupe drops a duplicate, like any other event processor. + * - `mark`: The duplicate can still change a session. If it is the first copy in its isolation scope (e.g. request), or + * if it is unhandled, Dedupe marks it and keeps it, so that it runs through all event processors and `beforeSend`. + * The client drops it after the session update, like a sampled-out error. + * - `ignore`: The error is never sent. Dedupe does not compare it and does not remember it. + */ +export type DedupeContext = + | { mode: 'ignore' } + | { mode: 'drop'; isolationScope: Scope } + | { mode: 'mark'; isolationScope: Scope; isDuplicate: boolean }; + +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); +} + +/** Whether the Dedupe integration marked the error event of this hint as a duplicate. */ +export function isMarkedDuplicate(hint: EventHint): boolean { + const context = dedupeContexts.get(hint); + return context?.mode === 'mark' && context.isDuplicate; +} diff --git a/packages/core/src/utils/misc.ts b/packages/core/src/utils/misc.ts index 454e4a9ab95d..55e092cdee58 100644 --- a/packages/core/src/utils/misc.ts +++ b/packages/core/src/utils/misc.ts @@ -1,4 +1,4 @@ -import type { Event } from '../types/event'; +import type { Event, EventHint } from '../types/event'; import type { Exception } from '../types/exception'; import type { Mechanism } from '../types/mechanism'; import type { StackFrame } from '../types/stackframe'; @@ -133,6 +133,18 @@ export function addExceptionMechanismToCapturedException(event: Event, newMechan applyExceptionMechanism(capturedException, newMechanism); } +/** + * Whether an event has an unhandled exception. Before event processing, the mechanism can be only in the hint. + * + * @hidden + */ +export function hasUnhandledException(event: Event, hint?: EventHint): boolean { + return ( + hint?.mechanism?.handled === false || + !!event.exception?.values?.some(exception => exception.mechanism?.handled === false) + ); +} + function applyExceptionMechanism(exception: Exception, newMechanism?: Partial): void { const defaultMechanism = { type: 'generic', handled: true }; const currentMechanism = exception.mechanism; diff --git a/packages/core/src/utils/requestSession.ts b/packages/core/src/utils/requestSession.ts new file mode 100644 index 000000000000..69a61d8c2c54 --- /dev/null +++ b/packages/core/src/utils/requestSession.ts @@ -0,0 +1,60 @@ +import type { Scope, SdkProcessingMetadata } from '../scope'; + +type RequestSession = NonNullable; + +export function getRequestSession(isolationScope: Scope): RequestSession | undefined { + return isolationScope.getScopeData().sdkProcessingMetadata.requestSession; +} + +/** Tracks an error of the request that is still in the event pipeline, so the session waits for it. */ +export function addPendingRequestSessionError(isolationScope: Scope, processing: PromiseLike): void { + const requestSession = getRequestSession(isolationScope); + if (!requestSession) { + return; + } + + const pendingErrors = (requestSession.pendingErrors ||= new Set()); + const settle = (): void => { + pendingErrors.delete(processing); + }; + pendingErrors.add(processing); + processing.then(settle, settle); +} + +/** Marks the request session as errored, or as crashed for an unhandled error. */ +export function setRequestSessionErroredOrCrashed(isolationScope: Scope, isUnhandled: boolean): void { + const requestSession = getRequestSession(isolationScope); + if (!requestSession) { + return; + } + + // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular + // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the + // original isolation scope that the http integration stored away. + // A request session can go from "errored" -> "crashed" but not "crashed" -> "errored". + // Crashed (unhandled exception) is worse than errored (handled exception). + if (isUnhandled) { + requestSession.status = 'crashed'; + } else if (requestSession.status !== 'crashed') { + requestSession.status = 'errored'; + } +} + +/** Crashes the request session if an error counted. That error can still be in the event pipeline. */ +export function crashRequestSessionIfErrored(isolationScope: Scope): void { + const requestSession = getRequestSession(isolationScope); + if (!requestSession) { + return; + } + + const crashIfErrored = (): void => { + if (requestSession.status === 'errored') { + requestSession.status = 'crashed'; + } + }; + if (!requestSession.pendingErrors?.size) { + crashIfErrored(); + return; + } + addPendingRequestSessionError(isolationScope, Promise.allSettled(requestSession.pendingErrors).then(crashIfErrored)); +} diff --git a/packages/core/test/lib/client.test.ts b/packages/core/test/lib/client.test.ts index 8d05b74cf9d8..ac7038720edf 100644 --- a/packages/core/test/lib/client.test.ts +++ b/packages/core/test/lib/client.test.ts @@ -563,17 +563,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'); }); @@ -3806,6 +3818,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..304d7fe25940 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,138 @@ 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()); + + 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(client._clearOutcomes()).toEqual([{ 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(); }); }); }); diff --git a/packages/core/test/lib/server-runtime-client.test.ts b/packages/core/test/lib/server-runtime-client.test.ts index 12ae4d625503..771a4275a309 100644 --- a/packages/core/test/lib/server-runtime-client.test.ts +++ b/packages/core/test/lib/server-runtime-client.test.ts @@ -1,9 +1,12 @@ -import { describe, expect, it, test, vi } from 'vitest'; -import { applySdkMetadata, createTransport, Scope } from '../../src'; +import { beforeEach, describe, expect, it, test, vi } from 'vitest'; +import { applySdkMetadata, createTransport, dedupeIntegration, getIsolationScope, Scope } from '../../src'; +import { startRequestSession } from '../../src/integrations/http/record-request-session'; +import { AsyncTestIntegration } from '../mocks/integration'; import { _INTERNAL_captureMetric, _INTERNAL_getMetricBuffer } from '../../src/metrics/internal'; import type { ServerRuntimeClientOptions } from '../../src/server-runtime-client'; import { ServerRuntimeClient } from '../../src/server-runtime-client'; -import type { Event, EventHint } from '../../src/types/event'; +import type { ErrorEvent, Event, EventHint } from '../../src/types/event'; +import { resetGlobals } from '../testutils'; const PUBLIC_DSN = 'https://username@domain/123'; @@ -16,6 +19,29 @@ function getDefaultClientOptions(options: Partial = }; } +/** Captures an error in the isolation scope of a request, as the HTTP integration does in Node. */ +function captureErrorInScope(client: ServerRuntimeClient, message: string, requestIsolationScope: Scope): void { + client.captureEvent({ + exception: { values: [{ type: 'Error', value: message }] }, + sdkProcessingMetadata: { capturedSpanIsolationScope: requestIsolationScope }, + }); +} + +/** Captures equal errors in a request with its own isolation scope. */ +function captureErrorInRequest(client: ServerRuntimeClient, message: string, route = '/', count = 1): void { + const requestIsolationScope = new Scope(); + requestIsolationScope.setTag('route', route); + const endRequestSession = startRequestSession(client, { requestIsolationScope }); + for (let i = 0; i < count; i++) { + captureErrorInScope(client, message, requestIsolationScope); + } + endRequestSession(); +} + +function delayed(event: ErrorEvent): Promise { + return new Promise(resolve => setTimeout(() => resolve(event), 10)); +} + describe('ServerRuntimeClient', () => { let client: ServerRuntimeClient; @@ -183,6 +209,303 @@ describe('ServerRuntimeClient', () => { }); }); + describe('request sessions', () => { + beforeEach(() => { + resetGlobals(); + }); + + it.each([ + ['errored for a handled exception', {}, undefined, { errored: 1 }], + ['crashed for an unhandled exception', {}, { mechanism: { type: 'test', handled: false } }, { crashed: 1 }], + ['exited for an exception that `beforeSend` drops', { beforeSend: () => null }, undefined, { exited: 1 }], + ['errored for an exception that `sampleRate` drops', { sampleRate: 0 }, undefined, { errored: 1 }], + [ + 'errored for an exception that is processed after the request ended', + { beforeSend: delayed }, + undefined, + { errored: 1 }, + ], + ] as const)('records the session as %s', async (_, options, hint, counts) => { + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, ...options })); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + const endRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + client.captureException(new Error('foo'), hint); + endRequestSession(); + await client.flush(); + + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 0, crashed: 0, ...counts }], + }); + }); + + it('records sampled-out errors without taking a buffer slot from errors that are sent', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + sampleRate: 0, + transportOptions: { bufferSize: 1 }, + beforeSend: delayed, + }), + ); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + const endRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('sampled out')); + client.getOptions().sampleRate = 1; + client.captureException(new Error('sampled in')); + endRequestSession(); + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledOnce(); + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 1, crashed: 0 }], + }); + }); + + it('limits how many errors that are never sent run event processing at the same time', async () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + sampleRate: 0, + beforeSend, + transportOptions: { bufferSize: 2 }, + integrations: [new AsyncTestIntegration()], + sendClientReports: true, + }), + ); + client.init(); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('first')); + client.captureException(new Error('second')); + client.captureException(new Error('third')); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledTimes(2); + expect(client['_clearOutcomes']()).toEqual([{ reason: 'sample_rate', category: 'error', quantity: 3 }]); + }); + + it.each([ + ['synchronous', [dedupeIntegration()]], + ['asynchronous', [new AsyncTestIntegration(), dedupeIntegration()]], + ])( + 'crashes the request session for an unhandled duplicate in the same request, with %s processors before Dedupe', + async (_, integrations) => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations, sendClientReports: true }), + ); + client.init(); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('duplicate')); + client.captureException(new Error('duplicate'), { mechanism: { type: 'generic', handled: false } }); + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledOnce(); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('crashed'); + expect(client['_clearOutcomes']()).toEqual([{ reason: 'event_processor', category: 'error', quantity: 1 }]); + }, + ); + + it('drops sampled-out errors before event processing once the request session crashed', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('crash'), { mechanism: { type: 'test', handled: false } }); + client.captureException(new Error('after crash')); + + expect(beforeSend).toHaveBeenCalledOnce(); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('crashed'); + }); + + it('drops sampled-out handled errors before event processing once the request session errored', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('handled')); + client.captureException(new Error('handled again')); + client.captureException(new Error('crash'), { mechanism: { type: 'test', handled: false } }); + + expect(beforeSend).toHaveBeenCalledTimes(2); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('crashed'); + }); + + it('records each request that fails with the same error as errored, also when Dedupe drops the error', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()] }), + ); + client.init(); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + + for (let i = 0; i < 2; i++) { + captureErrorInRequest(client, 'same error'); + } + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledOnce(); + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 2, crashed: 0 }], + }); + }); + + it('does not count a request whose duplicate error `beforeSend` drops', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + integrations: [dedupeIntegration()], + beforeSend: event => (event.tags?.route === '/health' ? null : event), + }), + ); + client.init(); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + + captureErrorInRequest(client, 'same error', '/users'); + captureErrorInRequest(client, 'same error', '/health'); + await client.flush(); + + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 1, errored: 1, crashed: 0 }], + }); + }); + + it('does not let duplicate errors from many requests push other errors out of the promise buffer', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + integrations: [dedupeIntegration(), new AsyncTestIntegration()], + transportOptions: { bufferSize: 2 }, + }), + ); + client.init(); + const sendEventSpy = vi.spyOn(client, 'sendEvent'); + + for (let i = 0; i < 10; i++) { + captureErrorInRequest(client, 'same error'); + } + captureErrorInRequest(client, 'other error'); + await client.flush(); + + expect(sendEventSpy).toHaveBeenCalledTimes(2); + }); + + it('calls `beforeSend` once for equal errors in one request', async () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()], beforeSend }), + ); + client.init(); + + captureErrorInRequest(client, 'same error', '/users', 3); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledOnce(); + }); + + it('calls `beforeSend` once per request for equal errors from requests that run at the same time', async () => { + const beforeSend = vi.fn(delayed); + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, integrations: [dedupeIntegration()], beforeSend }), + ); + client.init(); + const firstRequest = new Scope(); + const secondRequest = new Scope(); + startRequestSession(client, { requestIsolationScope: firstRequest }); + startRequestSession(client, { requestIsolationScope: secondRequest }); + + captureErrorInScope(client, 'same error', firstRequest); + captureErrorInScope(client, 'same error', secondRequest); + captureErrorInScope(client, 'same error', firstRequest); + captureErrorInScope(client, 'same error', secondRequest); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledTimes(2); + }); + + it('does not run event processing for sampled-out messages', () => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, sampleRate: 0, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureMessage('message'); + + expect(beforeSend).not.toHaveBeenCalled(); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('ok'); + }); + + it.each([ + ['errored for a handled exception', undefined, 'errored'], + ['crashed for an unhandled exception', { mechanism: { type: 'test', handled: false } }, 'crashed'], + ] as const)('records a request whose error overflows the buffer as %s', (_, hint, status) => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ dsn: PUBLIC_DSN, transportOptions: { bufferSize: 1 }, beforeSend: delayed }), + ); + captureErrorInScope(client, 'takes the only buffer slot', new Scope()); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureException(new Error('overflows'), hint); + + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe(status); + }); + + it.each([ + ['crashed when the first capture counted', delayed, 'crashed'], + ['ok when `beforeSend` dropped the first capture', () => null, 'ok'], + ] as const)('records a rethrown unhandled error as %s', async (_, beforeSend, status) => { + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, beforeSend })); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + const error = new Error('rethrown'); + + client.captureException(error); + client.captureException(error, { mechanism: { type: 'test', handled: false } }); + await client.flush(); + + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe(status); + }); + + it('sends a session that settles during a flush, also when another request opened an aggregate', async () => { + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + beforeSend: delayed, + }), + ); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + const endErroredRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + client.captureException(new Error('foo')); + endErroredRequestSession(); + + const flushed = client.flush(); + startRequestSession(client, { requestIsolationScope: new Scope() })(); + await flushed; + + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 0, errored: 1, crashed: 0 }], + }); + }); + + it('aggregates a session that settles after the request ended when no flush runs', async () => { + client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, beforeSend: delayed })); + const sendSessionSpy = vi.spyOn(client, 'sendSession'); + const endErroredRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + client.captureException(new Error('foo')); + endErroredRequestSession(); + await new Promise(resolve => setTimeout(resolve, 20)); + + startRequestSession(client, { requestIsolationScope: new Scope() })(); + await client.flush(); + + expect(sendSessionSpy).toHaveBeenCalledExactlyOnceWith({ + aggregates: [{ started: expect.any(String), exited: 1, errored: 1, crashed: 0 }], + }); + }); + }); + describe('captureMessage', () => { it('sends a message event with level info', () => { const options = getDefaultClientOptions({ dsn: PUBLIC_DSN }); From 887c4c01728ce2f43b04186e9c73cfd1a810f69e Mon Sep 17 00:00:00 2001 From: s1gr1d <32902192+s1gr1d@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:27:44 +0100 Subject: [PATCH 3/6] docs(core): Explain why browsers count sampled-out errors in the buffer Only ServerRuntimeClient moves never-sent errors out of the promise buffer. In the browser a burst with async event processors can still overflow it, but one user rarely fills it, so the browser keeps the develop behavior to save bundle size. --- packages/core/src/client.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 761ea3a58147..2770353052c2 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -1348,6 +1348,8 @@ export abstract class Client { // The error is never sent, so it must not make a later copy of it a duplicate. setDedupeContext(hint, { mode: 'ignore' }); + // Runs in the promise buffer, so a burst with async processors can still overflow it. `ServerRuntimeClient` avoids + // this; in the browser it is rare (one user, mostly sync processors), so we keep the bundle size small instead. return this._applyFilters(event, hint, currentScope, isolationScope).then(processedEvent => { this._updateSessions(processedEvent, currentScope, isolationScope); this.recordDroppedEvent('sample_rate', 'error'); From c9f905bdaaca10d829c3045b10e41ee1e7a82a91 Mon Sep 17 00:00:00 2001 From: s1gr1d <32902192+s1gr1d@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:34:54 +0100 Subject: [PATCH 4/6] docs(core): Explain non-obvious parts of the request session counting Say why the browser keeps sampled-out errors in the promise buffer, why only exception events get the overflow hint, what the side lane limit trades off, why a marked duplicate rejects at once, and why the side lane increments _numProcessing. --- packages/core/src/client.ts | 8 ++++++-- packages/core/src/server-runtime-client.ts | 7 +++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index 2770353052c2..dbe3d7850f39 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -340,6 +340,7 @@ export abstract class Client { this._process( () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope), dataCategory, + // Only exception events count in request sessions, so `_onQueueOverflow` gets the hint only for them. isExceptionEvent(event) ? hintWithEventId : undefined, ); @@ -1348,8 +1349,11 @@ export abstract class Client { // The error is never sent, so it must not make a later copy of it a duplicate. setDedupeContext(hint, { mode: 'ignore' }); - // Runs in the promise buffer, so a burst with async processors can still overflow it. `ServerRuntimeClient` avoids - // this; in the browser it is rare (one user, mostly sync processors), so we keep the bundle size small instead. + // The `_applyFilters` call below holds a promise buffer slot until it settles. With an async event processor or + // `beforeSend`, many sampled-out errors at the same time can fill the buffer. The client then drops errors that it + // would otherwise send, with `queue_overflow`. `ServerRuntimeClient` overrides this method to run the filters + // outside the buffer, because a server gets errors from many requests at the same time. The base client does not, + // to save browser bundle size. One browser user rarely causes that many errors at the same time. 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/server-runtime-client.ts b/packages/core/src/server-runtime-client.ts index c91223b89c83..3f965dd1bec8 100644 --- a/packages/core/src/server-runtime-client.ts +++ b/packages/core/src/server-runtime-client.ts @@ -160,6 +160,8 @@ export class ServerRuntimeClient< // The event processors before Dedupe are usually synchronous, so most duplicates are known here. if (isMarkedDuplicate(hint)) { + // Reject at once to free the promise buffer slot. `filtered` keeps running and counts the duplicate outside + // the buffer. this._countWithoutSlot(filtered.then(countDuplicate), isolationScope); return rejectedSyncPromise(_makeDoNotSendEventError(DUPLICATE_EVENT_ERROR)); } @@ -364,8 +366,8 @@ export class ServerRuntimeClient< } /** - * Whether an error that is never sent can still run event processing to update sessions. The limit keeps that - * work bounded in an error storm. + * Whether an error that is never sent can still run event processing to update sessions. Above the limit, the error + * does not update the session. So an error storm can lose a session count, but it never loses an error that is sent. */ private _canCountWithoutSlot(): boolean { return this._numCountingWithoutSlot < (this._options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE); @@ -376,6 +378,7 @@ export class ServerRuntimeClient< * never takes a slot from an error that is sent. */ private _countWithoutSlot(counting: PromiseLike, isolationScope: Scope): void { + // `flush()` waits until `_numProcessing` is 0, so it also waits for this session update. this._numProcessing++; this._numCountingWithoutSlot++; const settle = (): void => { From 4f062d34882f719cd9c027ec43dc0aff5be9a49d Mon Sep 17 00:00:00 2001 From: s1gr1d <32902192+s1gr1d@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:35:49 +0100 Subject: [PATCH 5/6] fix(core): Do not count captureMessage events in request sessions With attachStacktrace, eventFromMessage adds exception values to a message event, so the request session counted it as an error. The sessions spec says that captureMessage events must not count. eventFromMessage now flags these events, and ServerRuntimeClient skips them. --- packages/core/src/scope.ts | 5 ++++ packages/core/src/server-runtime-client.ts | 14 ++++++++--- packages/core/src/utils/eventbuilder.ts | 3 +++ .../test/lib/server-runtime-client.test.ts | 23 +++++++++++++++++++ .../core/test/lib/utils/eventbuilder.test.ts | 1 + 5 files changed, 43 insertions(+), 3 deletions(-) diff --git a/packages/core/src/scope.ts b/packages/core/src/scope.ts index 44ce0e4090ad..58b6c2f52630 100644 --- a/packages/core/src/scope.ts +++ b/packages/core/src/scope.ts @@ -74,6 +74,11 @@ export interface SdkProcessingMetadata { * defaults to `true`, so Replay does not treat them as errors in buffer mode. */ hasDefaultSyntheticStacktrace?: boolean; + /** + * Set on a `captureMessage` event that has exception values because of `attachStacktrace`. The exception values + * hold only the stack trace, so the event must not count as an error in request sessions. + */ + isMessageWithStacktrace?: boolean; } /** diff --git a/packages/core/src/server-runtime-client.ts b/packages/core/src/server-runtime-client.ts index 34fca0442c21..b09b6fba463e 100644 --- a/packages/core/src/server-runtime-client.ts +++ b/packages/core/src/server-runtime-client.ts @@ -129,7 +129,7 @@ export class ServerRuntimeClient< currentScope: Scope, isolationScope: Scope, ): PromiseLike { - if (!isExceptionEvent(event)) { + if (!isRequestSessionError(event)) { return super._processEvent(event, hint, currentScope, isolationScope); } @@ -206,7 +206,7 @@ export class ServerRuntimeClient< if (super._canErrorChangeSessions(event, hint, currentScope, isolationScope)) { return true; } - if (!isExceptionEvent(event)) { + if (!isRequestSessionError(event)) { return false; } @@ -219,7 +219,7 @@ export class ServerRuntimeClient< */ protected override _updateSessions(event: Event, currentScope: Scope, isolationScope: Scope): void { super._updateSessions(event, currentScope, isolationScope); - if (isExceptionEvent(event)) { + if (isRequestSessionError(event)) { setRequestSessionErroredOrCrashed(isolationScope, hasUnhandledException(event)); } } @@ -405,6 +405,14 @@ export class ServerRuntimeClient< } } +/** + * Whether the event counts as an error in request sessions. The sessions spec says that a `captureMessage` event + * must never count, so this excludes a message that has exception values because of `attachStacktrace`. + */ +function isRequestSessionError(event: Event): boolean { + return isExceptionEvent(event) && !event.sdkProcessingMetadata?.isMessageWithStacktrace; +} + /** * An unhandled error that was captured before, e.g. captured as handled, then rethrown and captured again by a * framework error handler, crashes the request session if the first capture counted. diff --git a/packages/core/src/utils/eventbuilder.ts b/packages/core/src/utils/eventbuilder.ts index 2e8445ed5878..1a57bf994e14 100644 --- a/packages/core/src/utils/eventbuilder.ts +++ b/packages/core/src/utils/eventbuilder.ts @@ -239,6 +239,9 @@ export function eventFromMessage( ], }; addExceptionMechanism(event, { synthetic: true }); + // With exception values, the message looks like an error. `ServerRuntimeClient` reads this flag to keep the + // message out of request sessions. + event.sdkProcessingMetadata = { isMessageWithStacktrace: true }; } } diff --git a/packages/core/test/lib/server-runtime-client.test.ts b/packages/core/test/lib/server-runtime-client.test.ts index d4e0722a200c..43ee0e3eb1d2 100644 --- a/packages/core/test/lib/server-runtime-client.test.ts +++ b/packages/core/test/lib/server-runtime-client.test.ts @@ -458,6 +458,29 @@ describe('ServerRuntimeClient', () => { expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('ok'); }); + it.each([ + ['a sent message', 1], + ['a sampled-out message', 0], + ])('does not count %s that has a synthetic stack trace', async (_, sampleRate) => { + const beforeSend = vi.fn((event: ErrorEvent) => event); + client = new ServerRuntimeClient( + getDefaultClientOptions({ + dsn: PUBLIC_DSN, + sampleRate, + beforeSend, + attachStacktrace: true, + stackParser: () => [{ filename: 'file.js', function: 'fn' }], + }), + ); + startRequestSession(client, { requestIsolationScope: getIsolationScope() }); + + client.captureMessage('message', 'error', { syntheticException: new Error('message') }); + await client.flush(); + + expect(beforeSend).toHaveBeenCalledTimes(sampleRate); + expect(getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession?.status).toBe('ok'); + }); + it.each([ ['errored for a handled exception', undefined, 'errored'], ['crashed for an unhandled exception', { mechanism: { type: 'test', handled: false } }, 'crashed'], diff --git a/packages/core/test/lib/utils/eventbuilder.test.ts b/packages/core/test/lib/utils/eventbuilder.test.ts index 5a2fcc003419..daddf2f6342b 100644 --- a/packages/core/test/lib/utils/eventbuilder.test.ts +++ b/packages/core/test/lib/utils/eventbuilder.test.ts @@ -213,6 +213,7 @@ describe('eventFromMessage', () => { }, level: 'info', message: 'Test Message', + sdkProcessingMetadata: { isMessageWithStacktrace: true }, }); }); From e82ee586cc8c4bbca13b13433f637b643fdd72f3 Mon Sep 17 00:00:00 2001 From: s1gr1d <32902192+s1gr1d@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:39:37 +0100 Subject: [PATCH 6/6] test(core): Use fake timers and run the sampled-errors suite on Deno Replace a fixed 20 ms sleep with fake timers that advance exactly the delay of the async beforeSend. Use denoHttpIntegration in the sampled-errors session suite when httpIntegration does not exist, as the shared sessions suite does. --- .../sessions/sampled-errors-session-aggregate/instrument.mjs | 5 ++++- packages/core/test/lib/server-runtime-client.test.ts | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs index 4ab031797062..58656d36616b 100644 --- a/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs +++ b/dev-packages/node-integration-tests/suites/sessions/sampled-errors-session-aggregate/instrument.mjs @@ -1,13 +1,16 @@ import * as Sentry from '@sentry/node'; import { loggingTransport } from '@sentry-internal/node-integration-tests'; +// `@sentry/deno` has the same options in `denoHttpIntegration`. +const httpIntegration = Sentry.httpIntegration ?? Sentry.denoHttpIntegration; + Sentry.init({ dsn: 'https://public@dsn.ingest.sentry.io/1337', release: '1.0', transport: loggingTransport, sampleRate: 0, integrations: [ - Sentry.httpIntegration({ + httpIntegration({ // Flush after 2 seconds (to avoid waiting for the default 60s) sessionFlushingDelayMS: 2_000, }), diff --git a/packages/core/test/lib/server-runtime-client.test.ts b/packages/core/test/lib/server-runtime-client.test.ts index 43ee0e3eb1d2..30528dbaeed8 100644 --- a/packages/core/test/lib/server-runtime-client.test.ts +++ b/packages/core/test/lib/server-runtime-client.test.ts @@ -533,12 +533,14 @@ describe('ServerRuntimeClient', () => { }); it('aggregates a session that settles after the request ended when no flush runs', async () => { + vi.useFakeTimers(); client = new ServerRuntimeClient(getDefaultClientOptions({ dsn: PUBLIC_DSN, beforeSend: delayed })); const sendSessionSpy = vi.spyOn(client, 'sendSession'); const endErroredRequestSession = startRequestSession(client, { requestIsolationScope: getIsolationScope() }); client.captureException(new Error('foo')); endErroredRequestSession(); - await new Promise(resolve => setTimeout(resolve, 20)); + await vi.advanceTimersByTimeAsync(10); + vi.useRealTimers(); startRequestSession(client, { requestIsolationScope: new Scope() })(); await client.flush();