From e1711a1a66ff3511cfb021bca44767953d84e0e3 Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Wed, 28 Oct 2026 15:41:24 +0100 Subject: [PATCH 01/22] =?UTF-8?q?=E2=9C=A8=20[DEBUG-6444]=20Capture=20Exce?= =?UTF-8?q?ption=20Replay=20snapshots=20for=20RUM=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add Exception Replay to the Browser Debugger SDK. Code built with the Live Debugger build plugin's `exceptionReplay` option calls `$dd_catch` for every exception that leaves an instrumented function. The SDK captures the arguments and `this` of the three innermost frames, keeps them with the error, and only sends them as snapshots when RUM reports the error. A new RUM plugin, `datadogDebugger.exceptionReplayPlugin()`, adds `error.debug_info_captured` and `_dd.exception_replay` to the RUM error event to link it to its snapshots. Captures redact sensitive names using the tracers' list, are limited to 10 new exceptions per second and one report per error type and function per hour, and count toward the global snapshot limit. Environment: Datadog workspace Co-Authored-By: Claude Sonnet 5.5 --- packages/browser-debugger/README.md | 24 ++ packages/browser-debugger/package.json | 3 + packages/browser-debugger/src/domain/api.ts | 84 ++++- .../src/domain/capture.spec.ts | 85 +++++ .../browser-debugger/src/domain/capture.ts | 46 ++- .../src/domain/exceptionReplay.spec.ts | 353 ++++++++++++++++++ .../src/domain/exceptionReplay.ts | 314 ++++++++++++++++ .../src/domain/exceptionReplayPlugin.spec.ts | 100 +++++ .../src/domain/exceptionReplayPlugin.ts | 76 ++++ .../src/domain/redaction.spec.ts | 25 ++ .../browser-debugger/src/domain/redaction.ts | 30 ++ .../browser-debugger/src/domain/stacktrace.ts | 9 +- .../browser-debugger/src/entries/main.spec.ts | 31 +- packages/browser-debugger/src/entries/main.ts | 28 ++ .../browser-rum-core/src/rumEvent.types.ts | 28 ++ test/e2e/scenario/debugger.scenario.ts | 84 ++++- yarn.lock | 1 + 17 files changed, 1301 insertions(+), 20 deletions(-) create mode 100644 packages/browser-debugger/src/domain/exceptionReplay.spec.ts create mode 100644 packages/browser-debugger/src/domain/exceptionReplay.ts create mode 100644 packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts create mode 100644 packages/browser-debugger/src/domain/exceptionReplayPlugin.ts create mode 100644 packages/browser-debugger/src/domain/redaction.spec.ts create mode 100644 packages/browser-debugger/src/domain/redaction.ts diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index 05850e62aa..8c478e319f 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -47,6 +47,29 @@ If you set `version` for version-specific probe targeting, use an immutable depl When the [RUM Browser SDK][4] is loaded on the page, the first hit of each probe creates a RUM custom action named `probe: ()`. For probes evaluated at function entry, the action lasts until the instrumented function returns or throws. For probes evaluated at function exit, the action is a point in time at the function exit. The action's context includes the probe, the ID of the snapshot sent for that hit, and the outcome (`return` or `throw`, with the error type). Only hits that pass sampling and the probe condition count. To disable this, set `trackProbeHitsAsRumActions: false` in `init()`. +## Exception Replay + +Exception Replay captures the arguments and `this` of the instrumented functions an error passes through, and shows them on the error's stack frames in Error Tracking, without adding probes. It requires the [RUM Browser SDK][4]: + +1. Build your application with the Live Debugger build plugin's [`exceptionReplay`][8] option. +2. Register the Exception Replay plugin when initializing the RUM Browser SDK: + + ```js + import { datadogRum } from '@datadog/browser-rum' + import { datadogDebugger } from '@datadog/browser-debugger' + + datadogRum.init({ + // ... + plugins: [datadogDebugger.exceptionReplayPlugin()], + }) + ``` + +3. Initialize the Live Debugger SDK as shown in [Usage](#usage). + +The SDK captures the three innermost instrumented frames of an exception as it's thrown, and only sends them as snapshots when RUM reports the error. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. + +Exception Replay snapshots count toward the `maxSnapshotsPerSecondGlobally` limit. + ## Troubleshooting Need help? Contact [Datadog Support][3]. @@ -60,3 +83,4 @@ Need help? Contact [Datadog Support][3]. [5]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger [6]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger#source-maps [7]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger#limitations-during-preview +[8]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger#livedebuggerexceptionreplay diff --git a/packages/browser-debugger/package.json b/packages/browser-debugger/package.json index e6353452ed..8c6d873bd0 100644 --- a/packages/browser-debugger/package.json +++ b/packages/browser-debugger/package.json @@ -18,6 +18,9 @@ "build:bundle": "node ../../scripts/build/build-package.ts --bundle datadog-debugger.js", "prepack": "yarn build" }, + "devDependencies": { + "@datadog/browser-rum-core": "workspace:*" + }, "dependencies": { "@datadog/browser-core": "workspace:*", "@datadog/js-core": "workspace:*" diff --git a/packages/browser-debugger/src/domain/api.ts b/packages/browser-debugger/src/domain/api.ts index d382c5cb21..73be8d1114 100644 --- a/packages/browser-debugger/src/domain/api.ts +++ b/packages/browser-debugger/src/domain/api.ts @@ -6,7 +6,7 @@ import { monitorError } from '@datadog/js-core/monitor' import { buildDebugIdByUrl, buildTag, mergeArrays } from '@datadog/browser-core' import type { BrowserWindow, DebuggerInitConfiguration } from '../entries/main' import { capture, captureFields } from './capture' -import type { CaptureContext } from './capture' +import type { CaptureContext, CaptureOptions } from './capture' import type { InitializedProbe } from './probes' import { checkConditionErrorBudget, @@ -23,6 +23,7 @@ import { evaluateProbeMessage } from './template' import { evaluateProbeCondition, isConditionEvaluationError } from './condition' import { display } from './display' import { formatThrowable } from './error' +import type { Throwable } from './error' import { evaluateCaptureExpressions } from './captureExpressions' import { addExitProbeRumAction, startProbeRumAction, stopProbeRumAction } from './rumAction' @@ -434,11 +435,79 @@ function queueDebuggerSnapshot(result: ActiveEntry): void { recordProbeEventSent(probe) } +/** + * A snapshot that no probe produced: Exception Replay captures one for each instrumented frame an + * exception leaves (see `exceptionReplay.ts`). + */ +export interface ExceptionSnapshot { + id: string + exceptionId: string + timestamp: number + message: string + location: { type: string; method: string } + stack: StackFrame[] + arguments: Record + throwable: Throwable +} + +/** + * Queue an Exception Replay snapshot for delivery via the debugger's own transport. + * + * @returns Whether the snapshot was queued, which requires `DD_DEBUGGER.init()` to have been called + */ +export function queueExceptionSnapshot(snapshot: ExceptionSnapshot): boolean { + if (!debuggerBatch || !debuggerConfig) { + return false + } + + const version = globalObj.DD_DEBUGGER!.version + const debugIds = buildDebugIdByUrl(collectStackFrameUrls(snapshot.throwable.stacktrace, snapshot.stack)) + + debuggerBatch.add({ + message: snapshot.message, + service: debuggerConfig.service, + ddtags: getDebuggerDDtags(version), + _dd: (debugIds ? { debug_ids: debugIds } : undefined) as ContextValue, + logger: { + name: snapshot.location.type, + method: snapshot.location.method, + version, + thread_name: threadName, + }, + debugger: { + snapshot: { + id: snapshot.id, + // Marks the snapshot as an Exception Replay snapshot in the Datadog UI + exceptionId: snapshot.exceptionId, + timestamp: snapshot.timestamp, + probe: { + // No probe produced the snapshot, so like the tracers' Exception Replay, give it a probe + // ID of its own + id: generateUUID(), + version: 0, + location: snapshot.location, + }, + stack: snapshot.stack, + language: 'javascript', + captures: { + return: { arguments: snapshot.arguments, throwable: snapshot.throwable }, + } as ContextValue, + }, + }, + }) + return true +} + function buildSnapshotDebugIds(result: ActiveEntry) { + return buildDebugIdByUrl(collectStackFrameUrls(result.return?.throwable?.stacktrace, result.stack)) +} + +function collectStackFrameUrls(...stacks: Array): string[] { const urls: string[] = [] - appendStackFrameUrls(urls, result.return?.throwable?.stacktrace) - appendStackFrameUrls(urls, result.stack) - return buildDebugIdByUrl(urls) + for (const stack of stacks) { + appendStackFrameUrls(urls, stack) + } + return urls } function appendStackFrameUrls(urls: string[], stack: StackFrame[] | undefined): void { @@ -451,10 +520,13 @@ function appendStackFrameUrls(urls: string[], stack: StackFrame[] | undefined): } } -function captureArguments( +/** + * Capture a function's arguments, along with its receiver as `this` unless it's the global object. + */ +export function captureArguments( args: Record, self: any, - captureOptions: InitializedProbe['capture'], + captureOptions: CaptureOptions, captureCtx: CaptureContext ): Record { const fields = captureFields(args, captureOptions, captureCtx) diff --git a/packages/browser-debugger/src/domain/capture.spec.ts b/packages/browser-debugger/src/domain/capture.spec.ts index 8ff598a20a..3ff09deb94 100644 --- a/packages/browser-debugger/src/domain/capture.spec.ts +++ b/packages/browser-debugger/src/domain/capture.spec.ts @@ -793,3 +793,88 @@ describe('capture timeout', () => { expect(result.field2).toEqual({ type: 'Object', notCapturedReason: 'timeout' }) }) }) + +describe('capture redaction', () => { + const defaultOpts = {} + + function redactingContext(): CaptureContext { + return { deadline: Infinity, timedOut: false, redact: true } + } + + it('should redact the values of fields named after sensitive identifiers', () => { + const result = captureFields( + { password: 'hunter2', apiKey: 'abc', 'X-Csrf-Token': 'def', session: { id: 1 }, username: 'alice' }, + defaultOpts, + redactingContext() + ) + + expect(result).toEqual({ + password: { type: 'string', notCapturedReason: 'redactedIdent' }, + apiKey: { type: 'string', notCapturedReason: 'redactedIdent' }, + 'X-Csrf-Token': { type: 'string', notCapturedReason: 'redactedIdent' }, + session: { type: 'Object', notCapturedReason: 'redactedIdent' }, + username: { type: 'string', value: 'alice' }, + }) + }) + + it('should redact nested fields', () => { + const result = capture({ user: { name: 'alice', token: 'abc' } }, defaultOpts, redactingContext()) + + expect(result.fields!.user.fields).toEqual({ + name: { type: 'string', value: 'alice' }, + token: { type: 'string', notCapturedReason: 'redactedIdent' }, + }) + }) + + it('should redact the values of map entries with sensitive string keys', () => { + const result = capture( + new Map([ + ['Authorization', 'Bearer abc'], + [1, 'one'], + ]), + defaultOpts, + redactingContext() + ) + + expect(result.entries).toEqual([ + [ + { type: 'string', value: 'Authorization' }, + { type: 'string', notCapturedReason: 'redactedIdent' }, + ], + [ + { type: 'number', value: '1' }, + { type: 'string', value: 'one' }, + ], + ]) + }) + + it('should not read a redacted field twice', () => { + const getter = jasmine.createSpy('getter').and.returnValue('hunter2') + const obj = {} + Object.defineProperty(obj, 'password', { get: getter, enumerable: true }) + + captureFields(obj, defaultOpts, redactingContext()) + + expect(getter).toHaveBeenCalledTimes(1) + }) + + it('should report a redacted field whose getter throws', () => { + const obj = {} + Object.defineProperty(obj, 'password', { + get: () => { + throw new Error('boom') + }, + enumerable: true, + }) + + expect(captureFields(obj, defaultOpts, redactingContext())).toEqual({ + password: { notCapturedReason: 'redactedIdent' }, + }) + }) + + it('should not redact unless the context asks for it', () => { + const result = captureFields({ password: 'hunter2' }, defaultOpts, { deadline: Infinity, timedOut: false }) + + expect(result).toEqual({ password: { type: 'string', value: 'hunter2' } }) + }) +}) diff --git a/packages/browser-debugger/src/domain/capture.ts b/packages/browser-debugger/src/domain/capture.ts index 6197dc1125..87ccac185d 100644 --- a/packages/browser-debugger/src/domain/capture.ts +++ b/packages/browser-debugger/src/domain/capture.ts @@ -1,4 +1,5 @@ import { getConstructorName, isError } from '@datadog/browser-core' +import { isRedactedIdentifier } from './redaction' export interface CaptureOptions { maxReferenceDepth?: number @@ -26,6 +27,11 @@ export interface CapturedValue { export interface CaptureContext { deadline: number timedOut: boolean + /** + * Whether to redact the values of properties and map entries named after a sensitive identifier + * (see {@link isRedactedIdentifier}). + */ + redact?: boolean } // Prefer replaceAll to replace because it's ~20% faster in this hot code path. @@ -321,16 +327,10 @@ function captureObjectPropertiesFields( const keyName = typeof key === 'symbol' ? key.description || key.toString() : keyStr.includes('.') ? replaceDots(keyStr) : keyStr - fields[keyName] = captureProperty( - obj, - key, - depth, - maxReferenceDepth, - maxCollectionSize, - maxFieldCount, - maxLength, - ctx - ) + fields[keyName] = + ctx.redact && typeof key === 'string' && isRedactedIdentifier(key) + ? captureRedactedProperty(obj, key) + : captureProperty(obj, key, depth, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx) } return fields @@ -424,7 +424,9 @@ function captureMap( } entries.push([ captureValue(key, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), - captureValue(value, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), + ctx.redact && typeof key === 'string' && isRedactedIdentifier(key) + ? captureRedactedValue(value) + : captureValue(value, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), ]) count++ } @@ -547,6 +549,28 @@ function captureProperty( } } +function captureRedactedProperty(obj: any, property: string): CapturedValue { + try { + return captureRedactedValue(obj[property]) + } catch { + return { notCapturedReason: 'redactedIdent' } + } +} + +function captureRedactedValue(value: unknown): CapturedValue { + let type: string + if (value === null) { + type = 'null' + } else if (typeof value === 'object') { + type = getConstructorName(value) ?? 'Object' + } else if (typeof value === 'function') { + type = 'Function' + } else { + type = typeof value + } + return { type, notCapturedReason: 'redactedIdent' } +} + function captureOptionalProperty( obj: any, property: string | symbol, diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts new file mode 100644 index 0000000000..2791803f1e --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -0,0 +1,353 @@ +import { computeStackTrace } from '@datadog/browser-core' +import { mockClock, registerCleanupTask } from '@datadog/browser-core/test' +import type { BrowserWindow } from '../entries/main' +import { initDebuggerTransport, resetDebuggerTransport } from './api' +import { + collectExceptionReplay, + onCatch, + registerExceptionReplayPlugin, + resetExceptionReplay, + startExceptionReplay, +} from './exceptionReplay' +import { clearProbes } from './probes' + +const browserWindow = window as BrowserWindow + +interface SentSnapshot { + id: string + exceptionId: string + probe: { location: { type: string; method: string } } + captures: { return: { arguments: Record; throwable: { message: string } } } +} + +describe('exceptionReplay', () => { + let mockBatchAdd: jasmine.Spy + + function initTransport(overrides: Record = {}) { + resetDebuggerTransport() + initDebuggerTransport( + { service: 'test-service', env: 'test-env', ...overrides } as any, + { add: mockBatchAdd } as any + ) + } + + // The functions below stand in for instrumented code: the build plugin calls `$dd_catch` from the + // catch block it wraps around each function body, then rethrows. + + function throwingFunction(value: number, secret?: string) { + try { + throw new Error(`boom ${value}`) + } catch (e) { + onCatch('src/throwing.ts;throwingFunction', e, undefined, { value, secret }) + throw e + } + } + + function callingFunction(a: number, b: number) { + try { + return throwingFunction(a + b) + } catch (e) { + onCatch('src/calling.ts;callingFunction', e, undefined, { a, b }) + throw e + } + } + + function outerFunction() { + try { + return callingFunction(1, 2) + } catch (e) { + onCatch('src/outer.ts;outerFunction', e, undefined, {}) + throw e + } + } + + function outermostFunction() { + try { + return outerFunction() + } catch (e) { + onCatch('src/outermost.ts;outermostFunction', e, undefined, {}) + throw e + } + } + + function catchError(fn: () => unknown): unknown { + let error: unknown + try { + fn() + } catch (e) { + error = e + } + expect(error).toBeDefined() + return error + } + + function stackIndexOf(error: unknown, functionName: string): number { + return computeStackTrace(error).stack.findIndex((frame) => frame.func?.includes(functionName)) + } + + function sentSnapshots(): SentSnapshot[] { + return mockBatchAdd.calls + .allArgs() + .map(([payload]) => (payload as { debugger: { snapshot: SentSnapshot } }).debugger.snapshot) + } + + beforeEach(() => { + clearProbes() + mockBatchAdd = jasmine.createSpy('batchAdd') + initTransport() + ;(window as any).DD_DEBUGGER = { version: '0.0.1' } + registerExceptionReplayPlugin() + startExceptionReplay() + + registerCleanupTask(() => { + delete (window as any).DD_DEBUGGER + resetExceptionReplay() + resetDebuggerTransport() + clearProbes() + }) + }) + + describe('catch hook installation', () => { + beforeEach(() => { + resetExceptionReplay() + }) + + it('should install the catch hook once the plugin is registered and the debugger is started', () => { + registerExceptionReplayPlugin() + expect(browserWindow.$dd_catch).toBeUndefined() + + startExceptionReplay() + expect(browserWindow.$dd_catch).toBe(onCatch) + }) + + it('should install the catch hook when the debugger starts before the plugin is registered', () => { + startExceptionReplay() + expect(browserWindow.$dd_catch).toBeUndefined() + + registerExceptionReplayPlugin() + expect(browserWindow.$dd_catch).toBe(onCatch) + }) + }) + + it('should send a snapshot for each captured frame, and link them to the reported error', () => { + const error = catchError(() => callingFunction(1, 2)) + + const attributes = collectExceptionReplay(error)! + + expect(attributes.frames.map(({ index }) => index)).toEqual([ + stackIndexOf(error, 'throwingFunction'), + stackIndexOf(error, 'callingFunction'), + ]) + const snapshots = sentSnapshots() + expect(snapshots.map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) + expect(snapshots.map(({ exceptionId }) => exceptionId)).toEqual([attributes.exceptionId, attributes.exceptionId]) + }) + + it('should capture the arguments of each frame', () => { + const error = catchError(() => callingFunction(1, 2)) + + collectExceptionReplay(error) + + const [throwingSnapshot, callingSnapshot] = sentSnapshots() + expect(throwingSnapshot.probe.location).toEqual({ type: 'src/throwing.ts', method: 'throwingFunction' }) + expect(throwingSnapshot.captures.return.arguments.value).toEqual({ type: 'number', value: '3' }) + expect(throwingSnapshot.captures.return.throwable.message).toBe('boom 3') + expect(callingSnapshot.probe.location).toEqual({ type: 'src/calling.ts', method: 'callingFunction' }) + expect(callingSnapshot.captures.return.arguments).toEqual( + jasmine.objectContaining({ a: { type: 'number', value: '1' }, b: { type: 'number', value: '2' } }) + ) + }) + + it('should send snapshots in the same envelope as probe snapshots', () => { + const error = catchError(() => throwingFunction(1)) + + collectExceptionReplay(error) + + const payload = mockBatchAdd.calls.mostRecent().args[0] + expect(payload).toEqual( + jasmine.objectContaining({ + message: 'Error: boom 1', + service: 'test-service', + ddtags: jasmine.stringContaining('env:test-env'), + logger: jasmine.objectContaining({ name: 'src/throwing.ts', method: 'throwingFunction', version: '0.0.1' }), + }) + ) + expect(payload.debugger.snapshot).toEqual( + jasmine.objectContaining({ + language: 'javascript', + probe: { id: jasmine.any(String), version: 0, location: jasmine.any(Object) }, + stack: jasmine.arrayContaining([ + jasmine.objectContaining({ function: jasmine.stringContaining('throwingFunction') }), + ]), + }) + ) + }) + + it('should redact sensitive arguments', () => { + const error = catchError(() => throwingFunction(1, 'hunter2')) + + collectExceptionReplay(error) + + expect(sentSnapshots()[0].captures.return.arguments.secret).toEqual({ + type: 'string', + notCapturedReason: 'redactedIdent', + }) + }) + + it('should only capture the three innermost frames', () => { + const error = catchError(outermostFunction) + + const attributes = collectExceptionReplay(error)! + + expect(attributes.frames.map(({ index }) => index)).toEqual([ + stackIndexOf(error, 'throwingFunction'), + stackIndexOf(error, 'callingFunction'), + stackIndexOf(error, 'outerFunction'), + ]) + }) + + it('should capture async functions', async () => { + async function asyncThrowingFunction() { + try { + await Promise.resolve() + throw new Error('async boom') + } catch (e) { + onCatch('src/async.ts;asyncThrowingFunction', e, undefined, {}) + throw e + } + } + + const error = await asyncThrowingFunction().then( + () => undefined, + (e: unknown) => e + ) + + const attributes = collectExceptionReplay(error)! + + expect(attributes.frames[0].index).toBe(stackIndexOf(error, 'asyncThrowingFunction')) + }) + + it('should not send snapshots for exceptions that are not reported', () => { + catchError(() => callingFunction(1, 2)) + + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + + it('should reuse the same snapshots when an error is reported twice', () => { + const error = catchError(() => callingFunction(1, 2)) + + const attributes = collectExceptionReplay(error) + const callCount = mockBatchAdd.calls.count() + + expect(collectExceptionReplay(error)).toBe(attributes) + expect(mockBatchAdd.calls.count()).toBe(callCount) + }) + + it('should stop capturing frames once the exception is reported', () => { + let error: unknown + function reportingFunction() { + try { + throwingFunction(1) + } catch (e) { + error = e + collectExceptionReplay(e) + onCatch('src/reporting.ts;reportingFunction', e, undefined, {}) + } + } + + reportingFunction() + + expect(collectExceptionReplay(error)!.frames.length).toBe(1) + expect(mockBatchAdd).toHaveBeenCalledTimes(1) + }) + + it('should return undefined for errors without captured frames', () => { + expect(collectExceptionReplay(new Error('not thrown through instrumented code'))).toBeUndefined() + expect(collectExceptionReplay(undefined)).toBeUndefined() + }) + + it('should ignore thrown values that are not objects', () => { + expect(() => onCatch('src/throwing.ts;throwingFunction', 'boom', undefined, {})).not.toThrow() + + expect(collectExceptionReplay('boom')).toBeUndefined() + }) + + it('should skip frames that are not in the error stack', () => { + const preparedError = new Error('created before being thrown') + function rethrowingFunction() { + try { + throw preparedError + } catch (e) { + onCatch('src/rethrowing.ts;rethrowingFunction', e, undefined, {}) + throw e + } + } + + const error = catchError(rethrowingFunction) + + expect(collectExceptionReplay(error)).toBeUndefined() + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + + it('should not report snapshots when the debugger transport is not initialized', () => { + const error = catchError(() => throwingFunction(1)) + resetDebuggerTransport() + + expect(collectExceptionReplay(error)).toBeUndefined() + }) + + it('should respect the global snapshot budget', () => { + initTransport({ maxSnapshotsPerSecondGlobally: 1 }) + const error = catchError(() => callingFunction(1, 2)) + + const attributes = collectExceptionReplay(error)! + + expect(attributes.frames.length).toBe(1) + expect(mockBatchAdd).toHaveBeenCalledTimes(1) + }) + + it('should not capture an exception with the same fingerprint for an hour after reporting it', () => { + const clock = mockClock() + + collectExceptionReplay(catchError(() => throwingFunction(1))) + expect(collectExceptionReplay(catchError(() => throwingFunction(2)))).toBeUndefined() + + clock.tick(60 * 60 * 1000 + 1) + expect(collectExceptionReplay(catchError(() => throwingFunction(3)))).toBeDefined() + }) + + it('should only report one of the exceptions with the same fingerprint captured before either is reported', () => { + const first = catchError(() => throwingFunction(1)) + const second = catchError(() => throwingFunction(2)) + + expect(collectExceptionReplay(first)).toBeDefined() + expect(collectExceptionReplay(second)).toBeUndefined() + expect(mockBatchAdd).toHaveBeenCalledTimes(1) + }) + + it('should keep capturing an exception that was never reported', () => { + catchError(() => throwingFunction(1)) + + expect(collectExceptionReplay(catchError(() => throwingFunction(2)))).toBeDefined() + }) + + it('should limit the number of exceptions captured per second', () => { + const clock = mockClock() + function typeErrorFunction() { + try { + throw new TypeError('boom') + } catch (e) { + onCatch('src/type-error.ts;typeErrorFunction', e, undefined, {}) + throw e + } + } + const errors = Array.from({ length: 11 }, (_, i) => catchError(() => throwingFunction(i))) + + expect(collectExceptionReplay(errors[10])).toBeUndefined() + expect(collectExceptionReplay(errors[9])).toBeDefined() + expect(collectExceptionReplay(catchError(typeErrorFunction))).toBeUndefined() + + clock.tick(1001) + expect(collectExceptionReplay(catchError(typeErrorFunction))).toBeDefined() + }) +}) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts new file mode 100644 index 0000000000..b19e63ccdb --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -0,0 +1,314 @@ +import { globalObject, generateUUID } from '@datadog/js-core/util' +import { timeStampNow } from '@datadog/js-core/time' +import { monitorError } from '@datadog/js-core/monitor' +import { computeStackTrace, isError } from '@datadog/browser-core' +import type { StackTrace } from '@datadog/browser-core' +import type { BrowserWindow } from '../entries/main' +import { captureArguments, queueExceptionSnapshot } from './api' +import type { CaptureContext } from './capture' +import { formatThrowable, formatUnknownError, safeReadErrorProperty } from './error' +import { checkGlobalSnapshotBudget } from './probes' +import { mapStackFrames } from './stacktrace' + +// Like the Java tracer, only capture the innermost frames, which are closest to the cause. +const MAX_FRAMES_PER_EXCEPTION = 3 + +// Exceptions are captured as they're thrown, before it's known whether they will be reported, so +// cap the work for code that throws and catches a lot of exceptions. +const MAX_EXCEPTIONS_CAPTURED_PER_SECOND = 10 + +// Like the tracers, report snapshots for a given exception fingerprint at most once an hour. +const FINGERPRINT_COOLDOWN_MS = 60 * 60 * 1000 +const MAX_FINGERPRINTS = 1000 + +const SNAPSHOT_TIMEOUT_MS = 10 + +/** + * Links the snapshots of a reported exception to its RUM error event. + */ +export interface ExceptionReplayAttributes { + exceptionId: string + /** + * Frames with a snapshot, innermost first. `index` is the frame's position in the error's stack, + * as parsed by `computeStackTrace`, which is how RUM formats the error event's `error.stack`. + */ + frames: Array<{ index: number; snapshotId: string }> +} + +interface CapturedFrame { + functionId: string + timestamp: number + arguments: Record + // Created in `onCatch`, so its stack starts with `onCatch`, followed by the instrumented function + callStack: Error +} + +interface CapturedException { + fingerprint: string + frames: CapturedFrame[] + // Set when the exception is first reported, so reporting it again reuses the same snapshots + attributes?: ExceptionReplayAttributes | null +} + +let capturedExceptions = new WeakMap() +let lastReportByFingerprint = new Map() +let captureWindowStart = -Infinity +let capturesInWindow = 0 +let pluginRegistered = false +let debuggerStarted = false + +/** + * Called when the Exception Replay plugin is registered on the RUM Browser SDK. + */ +export function registerExceptionReplayPlugin(): void { + pluginRegistered = true + installCatchHook() +} + +/** + * Called when the Live Debugger SDK is initialized, which provides the transport for snapshots. + */ +export function startExceptionReplay(): void { + debuggerStarted = true + installCatchHook() +} + +export function resetExceptionReplay(): void { + capturedExceptions = new WeakMap() + lastReportByFingerprint = new Map() + captureWindowStart = -Infinity + capturesInWindow = 0 + pluginRegistered = false + debuggerStarted = false + delete (globalObject as BrowserWindow).$dd_catch +} + +// Instrumented code only calls `$dd_catch` once it's defined, so Exception Replay costs nothing +// until both the plugin and the transport are there. +function installCatchHook(): void { + if (pluginRegistered && debuggerStarted) { + ;(globalObject as BrowserWindow).$dd_catch = onCatch + } +} + +/** + * Called by instrumented code built with Exception Replay enabled, for every exception that leaves + * an instrumented function, whether or not a probe is active. An exception reaches the innermost + * function first. + * + * Captures the arguments of the function's frame, and keeps them with the exception until RUM + * reports it (see {@link collectExceptionReplay}). The captures of exceptions that are never + * reported are garbage collected with them. + * + * Never throws: it runs in the instrumented function's catch block, before the exception is + * rethrown. + * + * @param functionId - ID of the instrumented function + * @param error - The thrown value + * @param self - The 'this' context + * @param args - Function arguments + */ +export function onCatch(functionId: string, error: unknown, self: unknown, args: Record = {}): void { + try { + // Captures are kept with the thrown value, which must be an object for that + if (!isObject(error)) { + return + } + + let exception = capturedExceptions.get(error) + if (exception === undefined) { + exception = startCapture(functionId, error) + capturedExceptions.set(error, exception) + } + + if (!exception || exception.attributes !== undefined || exception.frames.length >= MAX_FRAMES_PER_EXCEPTION) { + return + } + + const captureCtx: CaptureContext = { + deadline: performance.now() + SNAPSHOT_TIMEOUT_MS, + timedOut: false, + // Unlike probes, Exception Replay captures data nobody asked for, so redact sensitive names + redact: true, + } + exception.frames.push({ + functionId, + timestamp: timeStampNow(), + arguments: captureArguments(args, self, {}, captureCtx), + callStack: new Error(), + }) + } catch (e) { + monitorError(e) + } +} + +function startCapture(functionId: string, error: object): CapturedException | false { + const now = performance.now() + // The innermost instrumented function is the first one to see the exception + const errorType = isError(error) ? safeReadErrorProperty(error, 'name') : undefined + const fingerprint = `${errorType ?? ''};${functionId}` + + if (isCoolingDown(fingerprint, now)) { + return false + } + + if (now - captureWindowStart > 1000) { + captureWindowStart = now + capturesInWindow = 0 + } + if (capturesInWindow >= MAX_EXCEPTIONS_CAPTURED_PER_SECOND) { + return false + } + capturesInWindow++ + + return { fingerprint, frames: [] } +} + +/** + * Called when RUM reports an error. Sends the snapshots captured for the exception, and returns the + * attributes linking them to the RUM error event, or undefined if it has none. + */ +export function collectExceptionReplay(error: unknown): ExceptionReplayAttributes | undefined { + try { + if (!isObject(error)) { + return + } + + const exception = capturedExceptions.get(error) + if (!exception) { + return + } + + if (exception.attributes === undefined) { + exception.attributes = sendSnapshots(error, exception) + } + return exception.attributes ?? undefined + } catch (e) { + monitorError(e) + } +} + +function sendSnapshots(error: object, exception: CapturedException): ExceptionReplayAttributes | null { + const capturedFrames = exception.frames + // Release the captures: the exception can't capture more frames once it's reported + exception.frames = [] + + // Another exception with the same fingerprint may have been reported since this one was captured + if (isCoolingDown(exception.fingerprint, performance.now())) { + return null + } + + const errorFrames = computeStackTrace(error).stack + const exceptionId = generateUUID() + const message = formatUnknownError(error) + const throwable = formatThrowable(error) + const frames: ExceptionReplayAttributes['frames'] = [] + + let fromIndex = 0 + for (const frame of capturedFrames) { + const callFrames = computeStackTrace(frame.callStack).stack + const index = findFrameIndex(errorFrames, callFrames, fromIndex) + if (index === undefined) { + continue + } + + if (!checkGlobalSnapshotBudget(performance.now(), true)) { + break + } + + const snapshotId = generateUUID() + const separatorIndex = frame.functionId.lastIndexOf(';') + const queued = queueExceptionSnapshot({ + id: snapshotId, + exceptionId, + timestamp: frame.timestamp, + message, + location: { + type: frame.functionId.slice(0, separatorIndex), + method: frame.functionId.slice(separatorIndex + 1), + }, + stack: mapStackFrames(callFrames, 1), + arguments: frame.arguments, + throwable, + }) + if (!queued) { + break + } + + frames.push({ index, snapshotId }) + fromIndex = index + 1 + } + + if (frames.length === 0) { + return null + } + + recordReport(exception.fingerprint) + return { exceptionId, frames } +} + +function isCoolingDown(fingerprint: string, now: number): boolean { + const lastReport = lastReportByFingerprint.get(fingerprint) + return lastReport !== undefined && now - lastReport < FINGERPRINT_COOLDOWN_MS +} + +function recordReport(fingerprint: string): void { + // Re-insert the fingerprint so the map stays ordered by report time, oldest first + lastReportByFingerprint.delete(fingerprint) + lastReportByFingerprint.set(fingerprint, performance.now()) + if (lastReportByFingerprint.size > MAX_FINGERPRINTS) { + lastReportByFingerprint.delete(lastReportByFingerprint.keys().next().value!) + } +} + +/** + * Find the index, in the error's stack, of the instrumented function that captured `callFrames`. + * + * `callFrames` is the stack captured in `onCatch`: `onCatch` itself, then the instrumented + * function, then its callers. The callers are still paused at the call sites they were at when the + * exception was thrown, so they're the frames that follow the function in the error's stack. The + * function's own frame differs, as it has moved to its catch block, so only its URL is compared. + * + * Both stacks can be truncated (V8 keeps 10 frames by default), so only the callers present in both + * are compared. + */ +function findFrameIndex( + errorFrames: StackTrace['stack'], + callFrames: StackTrace['stack'], + fromIndex: number +): number | undefined { + const functionFrame = callFrames[1] + if (!functionFrame?.url) { + return + } + + const callers = callFrames.slice(2) + for (let index = fromIndex; index < errorFrames.length; index++) { + if (errorFrames[index].url !== functionFrame.url) { + continue + } + + const comparedCount = Math.min(callers.length, errorFrames.length - index - 1) + // A function with callers needs at least one of them in the error's stack to confirm the match. + // A function without callers is at the bottom of both stacks. + if (callers.length > 0 ? comparedCount === 0 : index !== errorFrames.length - 1) { + continue + } + + let matches = true + for (let i = 0; i < comparedCount && matches; i++) { + matches = isSameLocation(callers[i], errorFrames[index + 1 + i]) + } + if (matches) { + return index + } + } +} + +function isSameLocation(a: StackTrace['stack'][number], b: StackTrace['stack'][number]): boolean { + return a.url === b.url && a.line === b.line && a.column === b.column +} + +function isObject(value: unknown): value is object { + return (typeof value === 'object' && value !== null) || typeof value === 'function' +} diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts new file mode 100644 index 0000000000..1332a22ac0 --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -0,0 +1,100 @@ +import { SKIPPED } from '@datadog/js-core/assembly' +import { registerCleanupTask } from '@datadog/browser-core/test' +import type { RumPlugin, RumPluginOnInitOptions } from '@datadog/browser-rum-core' +import type { BrowserWindow } from '../entries/main' +import { initDebuggerTransport, resetDebuggerTransport } from './api' +import { onCatch, resetExceptionReplay, startExceptionReplay } from './exceptionReplay' +import { exceptionReplayPlugin } from './exceptionReplayPlugin' +import { clearProbes } from './probes' + +type AssembleHook = Parameters[0] + +describe('exceptionReplayPlugin', () => { + let assembleHook: AssembleHook + + function initPlugin() { + const registerAssembleEventHook = jasmine.createSpy('registerAssembleEventHook') + exceptionReplayPlugin().onInit({ registerAssembleEventHook }) + assembleHook = registerAssembleEventHook.calls.mostRecent().args[0] + } + + function assemble(eventType: string, error: unknown) { + return assembleHook({ eventType, domainContext: { error } } as unknown as Parameters[0]) + } + + function throwingFunction() { + try { + throw new Error('boom') + } catch (e) { + onCatch('src/throwing.ts;throwingFunction', e, undefined, {}) + throw e + } + } + + function catchError(fn: () => unknown): unknown { + let error: unknown + try { + fn() + } catch (e) { + error = e + } + return error + } + + beforeEach(() => { + clearProbes() + initDebuggerTransport({ service: 'test-service' } as any, { add: jasmine.createSpy('batchAdd') } as any) + ;(window as any).DD_DEBUGGER = { version: '0.0.1' } + startExceptionReplay() + + registerCleanupTask(() => { + delete (window as any).DD_DEBUGGER + resetExceptionReplay() + resetDebuggerTransport() + clearProbes() + }) + }) + + it('should be compatible with the RUM Browser SDK plugin type', () => { + const plugin: RumPlugin = exceptionReplayPlugin() + + expect(plugin.name).toBe('exception-replay') + }) + + it('should install the catch hook when initialized', () => { + expect((window as BrowserWindow).$dd_catch).toBeUndefined() + + initPlugin() + + expect((window as BrowserWindow).$dd_catch).toBe(onCatch) + }) + + it('should link the snapshots of a reported error to its RUM event', () => { + initPlugin() + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toEqual({ + type: 'error', + error: { debug_info_captured: 'true' }, + _dd: { + exception_replay: { + exception_id: jasmine.any(String), + frames: [{ index: 0, snapshot_id: jasmine.any(String) }], + }, + }, + }) + }) + + it('should skip errors without snapshots', () => { + initPlugin() + + expect(assemble('error', new Error('not thrown through instrumented code'))).toBe(SKIPPED) + }) + + it('should skip other event types', () => { + initPlugin() + const error = catchError(throwingFunction) + + expect(assemble('action', error)).toBe(SKIPPED) + }) +}) diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts new file mode 100644 index 0000000000..df6b962eb3 --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -0,0 +1,76 @@ +import { SKIPPED } from '@datadog/js-core/assembly' +import { collectExceptionReplay, registerExceptionReplayPlugin } from './exceptionReplay' + +// The plugin is typed structurally, rather than with the RUM Browser SDK's `RumPlugin` type, so that +// the Live Debugger SDK doesn't depend on the RUM Browser SDK. + +interface AssembleEventHookParams { + eventType: string + domainContext: object +} + +// eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- `type` is needed for implicit index signature compatibility with RUM event types +type ExceptionReplayEventAttributes = { + type: 'error' + error: { debug_info_captured: 'true' } + _dd: { + exception_replay: { + exception_id: string + frames: Array<{ index: number; snapshot_id: string }> + } + } +} + +type AssembleEventHook = (params: AssembleEventHookParams) => ExceptionReplayEventAttributes | SKIPPED + +/** + * Exception Replay plugin for the RUM Browser SDK. Compatible with the RUM Browser SDK's `RumPlugin`. + */ +export interface ExceptionReplayPlugin { + name: string + onInit(options: { registerAssembleEventHook: (callback: AssembleEventHook) => unknown }): void +} + +/** + * Create the Exception Replay plugin for the RUM Browser SDK. + * + * When an application built with the Live Debugger build plugin's `exceptionReplay` option throws, + * the Live Debugger SDK captures the arguments of the instrumented functions the exception passes + * through. When RUM reports the error, this plugin sends those captures as snapshots and links them + * to the RUM error event, so Error Tracking can show them on the error's stack frames. + * + * Exception Replay only starts once the plugin is registered and `DD_DEBUGGER.init()` is called. + */ +export function exceptionReplayPlugin(): ExceptionReplayPlugin { + return { + name: 'exception-replay', + onInit({ registerAssembleEventHook }) { + registerExceptionReplayPlugin() + + registerAssembleEventHook(({ eventType, domainContext }) => { + if (eventType !== 'error') { + return SKIPPED + } + + const attributes = collectExceptionReplay('error' in domainContext ? domainContext.error : undefined) + if (!attributes) { + return SKIPPED + } + + return { + type: 'error', + error: { + // Error Tracking reads this flag as a string, as backend tracers set it on spans + debug_info_captured: 'true', + }, + _dd: { + exception_replay: { + exception_id: attributes.exceptionId, + frames: attributes.frames.map(({ index, snapshotId }) => ({ index, snapshot_id: snapshotId })), + }, + }, + } + }) + }, + } +} diff --git a/packages/browser-debugger/src/domain/redaction.spec.ts b/packages/browser-debugger/src/domain/redaction.spec.ts new file mode 100644 index 0000000000..ab32c3d77e --- /dev/null +++ b/packages/browser-debugger/src/domain/redaction.spec.ts @@ -0,0 +1,25 @@ +import { isRedactedIdentifier } from './redaction' + +describe('isRedactedIdentifier', () => { + it('should match sensitive identifiers', () => { + expect(isRedactedIdentifier('password')).toBeTrue() + expect(isRedactedIdentifier('token')).toBeTrue() + expect(isRedactedIdentifier('ssn')).toBeTrue() + }) + + it('should ignore case and separators', () => { + expect(isRedactedIdentifier('apiKey')).toBeTrue() + expect(isRedactedIdentifier('api_key')).toBeTrue() + expect(isRedactedIdentifier('X-Api-Key')).toBeTrue() + expect(isRedactedIdentifier('$password')).toBeTrue() + expect(isRedactedIdentifier('@session.id')).toBeTrue() + expect(isRedactedIdentifier(' Authorization ')).toBeTrue() + }) + + it('should not match other identifiers', () => { + expect(isRedactedIdentifier('username')).toBeFalse() + expect(isRedactedIdentifier('passwordHint')).toBeFalse() + expect(isRedactedIdentifier('tokens')).toBeFalse() + expect(isRedactedIdentifier('')).toBeFalse() + }) +}) diff --git a/packages/browser-debugger/src/domain/redaction.ts b/packages/browser-debugger/src/domain/redaction.ts new file mode 100644 index 0000000000..39902936fc --- /dev/null +++ b/packages/browser-debugger/src/domain/redaction.ts @@ -0,0 +1,30 @@ +// Identifiers whose values are never captured, normalized by `normalizeIdentifier`. This is the +// list the Datadog tracers redact in Dynamic Instrumentation and Exception Replay snapshots. +const REDACTED_IDENTIFIERS = new Set( + ( + '2fa accesstoken aiohttpsession apikey apisecret apisignature appkey applicationkey auth authorization ' + + 'authtoken ccnumber certificatepin cipher clientid clientsecret connectionstring connectsid cookie ' + + 'credentials creditcard csrf csrftoken cvv databaseurl dburl encryptionkey encryptionkeyid geolocation ' + + 'gpgkey ipaddress jti jwt licensekey masterkey mysqlpwd nonce oauth oauthtoken otp passhash passwd ' + + 'password passwordb pemfile pgpkey phpsessid pin pincode pkcs8 privatekey publickey pwd recaptchakey ' + + 'refreshtoken routingnumber salt secret secretkey secrettoken securityanswer securitycode ' + + 'securityquestion serviceaccountcredentials session sessionid sessionkey setcookie signature ' + + 'signaturekey sshkey ssn symfony token transactionid twiliotoken usersession voterid xapikey xauthtoken ' + + 'xcsrftoken xforwardedfor xrealip xsrf xsrftoken' + ).split(' ') +) + +const IDENTIFIER_SEPARATORS = /[-_@$.]/g + +/** + * Whether the value of a variable, argument, property or map entry with this name must be redacted + * from snapshots. Matching ignores case and the `-`, `_`, `@`, `$` and `.` separators, so + * `api_key`, `apiKey` and `X-Api-Key` all match `apikey`. + */ +export function isRedactedIdentifier(name: string): boolean { + return REDACTED_IDENTIFIERS.has(normalizeIdentifier(name)) +} + +function normalizeIdentifier(name: string): string { + return name.trim().toLowerCase().replace(IDENTIFIER_SEPARATORS, '') +} diff --git a/packages/browser-debugger/src/domain/stacktrace.ts b/packages/browser-debugger/src/domain/stacktrace.ts index b582a6632e..1bc3064c38 100644 --- a/packages/browser-debugger/src/domain/stacktrace.ts +++ b/packages/browser-debugger/src/domain/stacktrace.ts @@ -47,7 +47,14 @@ function mapStackFrame(frame: StackTrace['stack'][number]): StackFrame | undefin } } -function mapStackFrames(stack: StackTrace['stack'], skipFrames = 0): StackFrame[] { +/** + * Map frames parsed by `computeStackTrace` to snapshot stack frames, dropping frames without a location + * + * @param stack - Frames parsed by `computeStackTrace` + * @param skipFrames - Number of frames to skip from the top of the stack (default: 0) + * @returns Array of stack frames + */ +export function mapStackFrames(stack: StackTrace['stack'], skipFrames = 0): StackFrame[] { return stack.reduce((result, frame, index) => { if (index < skipFrames) { return result diff --git a/packages/browser-debugger/src/entries/main.spec.ts b/packages/browser-debugger/src/entries/main.spec.ts index 5a21ea36c9..36db1628bf 100644 --- a/packages/browser-debugger/src/entries/main.spec.ts +++ b/packages/browser-debugger/src/entries/main.spec.ts @@ -3,6 +3,7 @@ import { registerCleanupTask, replaceMockableWithSpy } from '@datadog/browser-co import { initDebuggerTransport } from '../domain/api' import { startDeliveryApiPolling } from '../domain/deliveryApi' import { display } from '../domain/display' +import { registerExceptionReplayPlugin, resetExceptionReplay, startExceptionReplay } from '../domain/exceptionReplay' import { startDebuggerBatch } from '../transport/startDebuggerBatch' import type { BrowserWindow, DebuggerBuildMetadata, DebuggerInitConfiguration } from './main' import { datadogDebugger } from './main' @@ -33,17 +34,45 @@ describe('datadogDebugger', () => { delete browserWindow.$dd_return delete browserWindow.$dd_throw delete browserWindow.$dd_probes + resetExceptionReplay() }) }) - it('should only expose init, version, and onReady', () => { + it('should only expose init, exceptionReplayPlugin, version, and onReady', () => { expect(datadogDebugger).toEqual({ init: jasmine.any(Function), + exceptionReplayPlugin: jasmine.any(Function), version: jasmine.any(String), onReady: jasmine.any(Function), }) }) + it('should start Exception Replay on init', () => { + mockInitDependencies() + const startExceptionReplaySpy = replaceMockableWithSpy(startExceptionReplay) + + datadogDebugger.init(INIT_CONFIGURATION) + + expect(startExceptionReplaySpy).toHaveBeenCalled() + }) + + it('should install the Exception Replay catch hook on init once the plugin is registered', () => { + mockInitDependencies() + registerExceptionReplayPlugin() + + datadogDebugger.init(INIT_CONFIGURATION) + + expect(browserWindow.$dd_catch).toBeDefined() + }) + + it('should not install the Exception Replay catch hook on init without the plugin', () => { + mockInitDependencies() + + datadogDebugger.init(INIT_CONFIGURATION) + + expect(browserWindow.$dd_catch).toBeUndefined() + }) + it('should default the init version from build-plugin metadata', async () => { browserWindow.__DD_LIVE_DEBUGGER_BUILD__ = { version: 'build-version' } const { initTransportSpy, startDeliveryApiPollingSpy } = mockInitDependencies() diff --git a/packages/browser-debugger/src/entries/main.ts b/packages/browser-debugger/src/entries/main.ts index 77e796838a..d82437817d 100644 --- a/packages/browser-debugger/src/entries/main.ts +++ b/packages/browser-debugger/src/entries/main.ts @@ -13,9 +13,15 @@ import type { Site } from '@datadog/js-core/transport' import { initDebuggerTransport, onEntry, onReturn, onThrow } from '../domain/api' import { startDeliveryApiPolling } from '../domain/deliveryApi' import { display } from '../domain/display' +import type { onCatch } from '../domain/exceptionReplay' +import { startExceptionReplay } from '../domain/exceptionReplay' +import { exceptionReplayPlugin } from '../domain/exceptionReplayPlugin' +import type { ExceptionReplayPlugin } from '../domain/exceptionReplayPlugin' import { getProbes } from '../domain/probes' import { startDebuggerBatch } from '../transport/startDebuggerBatch' +export type { ExceptionReplayPlugin } + export interface DebuggerBuildMetadata { version?: string service?: string @@ -173,6 +179,25 @@ export interface DatadogDebugger extends PublicApi { * ``` */ init: (initConfiguration: DebuggerInitConfiguration) => void + + /** + * Create the Exception Replay plugin for the RUM Browser SDK. Register it with + * `DD_RUM.init({ plugins: [...] })` to capture the arguments of the instrumented functions an + * error passes through, and show them on the error's stack frames in Error Tracking. + * + * Requires an application built with the Live Debugger build plugin's `exceptionReplay` option. + * Exception Replay starts once the plugin is registered and `init()` is called. + * + * @category Exception Replay + * @example + * ```ts + * datadogRum.init({ + * // ... + * plugins: [datadogDebugger.exceptionReplayPlugin()], + * }) + * ``` + */ + exceptionReplayPlugin: () => ExceptionReplayPlugin } export interface BrowserWindow { @@ -182,6 +207,7 @@ export interface BrowserWindow { $dd_return?: typeof onReturn $dd_throw?: typeof onThrow $dd_probes?: typeof getProbes + $dd_catch?: typeof onCatch } function getBuildMetadataString(key: keyof DebuggerBuildMetadata): string | undefined { @@ -232,6 +258,7 @@ function makeDebuggerPublicApi(): DatadogDebugger { debuggerGlobal.$dd_return = onReturn debuggerGlobal.$dd_throw = onThrow debuggerGlobal.$dd_probes = getProbes + mockable(startExceptionReplay)() mockable(startDeliveryApiPolling)({ service: resolvedConfiguration.service, @@ -245,6 +272,7 @@ function makeDebuggerPublicApi(): DatadogDebugger { maxUnreachableDuration: resolvedConfiguration.maxUnreachableDuration, }) }, + exceptionReplayPlugin, }) } diff --git a/packages/browser-rum-core/src/rumEvent.types.ts b/packages/browser-rum-core/src/rumEvent.types.ts index 91f869f8ec..3fcf9de2dd 100644 --- a/packages/browser-rum-core/src/rumEvent.types.ts +++ b/packages/browser-rum-core/src/rumEvent.types.ts @@ -496,6 +496,10 @@ export type RumErrorEvent = CommonProperties & * Time since application start when error happened (in milliseconds) */ readonly time_since_app_start?: number + /** + * Whether Exception Replay captured snapshots for this error. A string rather than a boolean, to match the `error.debug_info_captured` span tag that Error Tracking reads for backend errors + */ + readonly debug_info_captured?: 'true' [k: string]: unknown } /** @@ -546,6 +550,30 @@ export type RumErrorEvent = CommonProperties & id: string [k: string]: unknown }[] + /** + * Exception Replay snapshots captured for the stack frames of the error + */ + exception_replay?: { + /** + * UUID of the captured exception, also set as `exceptionId` on each of its snapshots + */ + exception_id: string + /** + * Stack frames of the error that have a snapshot, from the innermost frame outwards + */ + frames: { + /** + * Index of the frame in `error.stack`, starting at 0 for the innermost frame + */ + index: number + /** + * UUID of the Live Debugger snapshot captured for the frame + */ + snapshot_id: string + [k: string]: unknown + }[] + [k: string]: unknown + } [k: string]: unknown } [k: string]: unknown diff --git a/test/e2e/scenario/debugger.scenario.ts b/test/e2e/scenario/debugger.scenario.ts index 1c8963f0a6..05b62e39dd 100644 --- a/test/e2e/scenario/debugger.scenario.ts +++ b/test/e2e/scenario/debugger.scenario.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unsafe-call, camelcase */ import { test, expect } from '@playwright/test' import type { Page } from '@playwright/test' -import { createTest, microfrontendSetup } from '../lib/framework' +import { createTest, html, microfrontendSetup } from '../lib/framework' const DEBUGGER_POLL_INTERVAL = 1_000 const PROBE_WAIT_TIMEOUT = 30_000 @@ -648,4 +648,86 @@ test.describe('debugger', () => { outcome: 'return', }) }) + + createTest('link Exception Replay snapshots to the RUM error event') + .withRum() + .withRumInit((configuration) => { + // The debugger is loaded after RUM, so wait for it to create the plugin + const initRum = () => { + window.DD_RUM!.init({ ...configuration, plugins: [(window as any).DD_DEBUGGER.exceptionReplayPlugin()] }) + } + if ((window as any).DD_DEBUGGER) { + ;(window as any).DD_DEBUGGER.onReady(initRum) + } else { + document.addEventListener('DOMContentLoaded', initRum) + } + }) + .withDebugger() + // Instrumented code is loaded from a script, so its stack frames have a URL. Code evaluated by + // Playwright has none, so Exception Replay can't locate its frames. + .withBody(html` + + `) + .run(async ({ intakeRegistry, flushEvents, page }) => { + await page.evaluate(() => { + try { + ;(window as any).callingFunction(1) + } catch (error) { + window.DD_RUM!.addError(error) + } + }) + + await flushEvents() + + expect(intakeRegistry.rumErrorEvents).toHaveLength(1) + const errorEvent = intakeRegistry.rumErrorEvents[0] + expect((errorEvent.error as any).debug_info_captured).toBe('true') + const exceptionReplay = (errorEvent._dd as any).exception_replay + const stackFrames = errorEvent.error.stack!.split('\n').slice(1) + expect( + exceptionReplay.frames.map(({ index }: { index: number }) => stackFrames[index].trim().split(' ')[1]) + ).toEqual(['throwingFunction', 'callingFunction']) + + const snapshots = intakeRegistry.debuggerEvents.map( + (event) => + (event.debugger as any).snapshot as { + id: string + exceptionId: string + probe: { location: unknown } + captures: { return: { arguments: Record } } + } + ) + expect(snapshots.map(({ id }) => id)).toEqual( + exceptionReplay.frames.map(({ snapshot_id }: { snapshot_id: string }) => snapshot_id) + ) + expect(snapshots.map(({ exceptionId }) => exceptionId)).toEqual([ + exceptionReplay.exception_id, + exceptionReplay.exception_id, + ]) + expect(snapshots[0].probe.location).toEqual({ type: 'src/throwing.ts', method: 'throwingFunction' }) + expect(snapshots[0].captures.return.arguments.count).toEqual({ type: 'number', value: '2' }) + expect(snapshots[0].captures.return.arguments.token).toEqual({ + type: 'string', + notCapturedReason: 'redactedIdent', + }) + expect(snapshots[1].captures.return.arguments.count).toEqual({ type: 'number', value: '1' }) + }) }) diff --git a/yarn.lock b/yarn.lock index 733e2c9810..f6a61a9702 100644 --- a/yarn.lock +++ b/yarn.lock @@ -484,6 +484,7 @@ __metadata: resolution: "@datadog/browser-debugger@workspace:packages/browser-debugger" dependencies: "@datadog/browser-core": "workspace:*" + "@datadog/browser-rum-core": "workspace:*" "@datadog/js-core": "workspace:*" languageName: unknown linkType: soft From 63598721f0fcc550c23e11d0951a2c33bef0cf8a Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Thu, 29 Oct 2026 10:19:47 +0100 Subject: [PATCH 02/22] =?UTF-8?q?=E2=9C=A8=20[DEBUG-6444]=20Only=20send=20?= =?UTF-8?q?Exception=20Replay=20snapshots=20for=20errors=20RUM=20sends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exception Replay sent an error's snapshots while RUM assembled the error event, before `beforeSend` and the event rate limits ran. An error that either of them dropped still sent its snapshots, with no error event to link them to. Add an `eventCollected` hook to RUM, triggered once an event has passed `beforeSend` and the rate limits, and expose it to plugins as `registerEventCollectedHook`. The Exception Replay plugin still adds its attributes while the event is assembled, but holds the snapshots until the hook fires. The one-hour fingerprint limit also starts then. Also stop capturing in sessions RUM doesn't track, since their errors are never reported, and fix the async function spec on Safari 14, which leaves the function's name out of the stack after an `await`. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-debugger/README.md | 2 +- packages/browser-debugger/src/domain/api.ts | 17 ++- .../src/domain/exceptionReplay.spec.ts | 105 +++++++++++++----- .../src/domain/exceptionReplay.ts | 63 ++++++++--- .../src/domain/exceptionReplayPlugin.spec.ts | 51 ++++++++- .../src/domain/exceptionReplayPlugin.ts | 40 +++++-- .../browser-debugger/src/entries/main.spec.ts | 2 +- .../src/boot/preStartRum.spec.ts | 2 + .../browser-rum-core/src/boot/preStartRum.ts | 1 + .../src/domain/assembly.spec.ts | 40 +++++++ .../browser-rum-core/src/domain/assembly.ts | 1 + packages/browser-rum-core/src/domain/hooks.ts | 12 +- .../browser-rum-core/src/domain/plugins.ts | 8 +- test/e2e/scenario/debugger.scenario.ts | 82 ++++++++++---- 14 files changed, 338 insertions(+), 88 deletions(-) diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index 8c478e319f..cc14efd7f3 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -66,7 +66,7 @@ Exception Replay captures the arguments and `this` of the instrumented functions 3. Initialize the Live Debugger SDK as shown in [Usage](#usage). -The SDK captures the three innermost instrumented frames of an exception as it's thrown, and only sends them as snapshots when RUM reports the error. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. +The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. Exception Replay snapshots count toward the `maxSnapshotsPerSecondGlobally` limit. diff --git a/packages/browser-debugger/src/domain/api.ts b/packages/browser-debugger/src/domain/api.ts index 73be8d1114..383328887e 100644 --- a/packages/browser-debugger/src/domain/api.ts +++ b/packages/browser-debugger/src/domain/api.ts @@ -451,13 +451,19 @@ export interface ExceptionSnapshot { } /** - * Queue an Exception Replay snapshot for delivery via the debugger's own transport. - * - * @returns Whether the snapshot was queued, which requires `DD_DEBUGGER.init()` to have been called + * Whether snapshots can be sent, which requires `DD_DEBUGGER.init()` to have been called. + */ +export function isDebuggerTransportInitialized(): boolean { + return debuggerBatch !== undefined && debuggerConfig !== undefined +} + +/** + * Queue an Exception Replay snapshot for delivery via the debugger's own transport. Does nothing + * until `DD_DEBUGGER.init()` has been called. */ -export function queueExceptionSnapshot(snapshot: ExceptionSnapshot): boolean { +export function queueExceptionSnapshot(snapshot: ExceptionSnapshot): void { if (!debuggerBatch || !debuggerConfig) { - return false + return } const version = globalObj.DD_DEBUGGER!.version @@ -495,7 +501,6 @@ export function queueExceptionSnapshot(snapshot: ExceptionSnapshot): boolean { }, }, }) - return true } function buildSnapshotDebugIds(result: ActiveEntry) { diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 2791803f1e..1f9e9fb5c0 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -7,6 +7,7 @@ import { onCatch, registerExceptionReplayPlugin, resetExceptionReplay, + sendExceptionReplay, startExceptionReplay, } from './exceptionReplay' import { clearProbes } from './probes' @@ -81,6 +82,13 @@ describe('exceptionReplay', () => { return error } + // Like RUM: assemble the error event, then collect it + function reportError(error: unknown) { + const attributes = collectExceptionReplay(error) + sendExceptionReplay(error) + return attributes + } + function stackIndexOf(error: unknown, functionName: string): number { return computeStackTrace(error).stack.findIndex((frame) => frame.func?.includes(functionName)) } @@ -96,7 +104,7 @@ describe('exceptionReplay', () => { mockBatchAdd = jasmine.createSpy('batchAdd') initTransport() ;(window as any).DD_DEBUGGER = { version: '0.0.1' } - registerExceptionReplayPlugin() + registerExceptionReplayPlugin(() => true) startExceptionReplay() registerCleanupTask(() => { @@ -113,7 +121,7 @@ describe('exceptionReplay', () => { }) it('should install the catch hook once the plugin is registered and the debugger is started', () => { - registerExceptionReplayPlugin() + registerExceptionReplayPlugin(() => true) expect(browserWindow.$dd_catch).toBeUndefined() startExceptionReplay() @@ -124,7 +132,7 @@ describe('exceptionReplay', () => { startExceptionReplay() expect(browserWindow.$dd_catch).toBeUndefined() - registerExceptionReplayPlugin() + registerExceptionReplayPlugin(() => true) expect(browserWindow.$dd_catch).toBe(onCatch) }) }) @@ -132,7 +140,7 @@ describe('exceptionReplay', () => { it('should send a snapshot for each captured frame, and link them to the reported error', () => { const error = catchError(() => callingFunction(1, 2)) - const attributes = collectExceptionReplay(error)! + const attributes = reportError(error)! expect(attributes.frames.map(({ index }) => index)).toEqual([ stackIndexOf(error, 'throwingFunction'), @@ -146,7 +154,7 @@ describe('exceptionReplay', () => { it('should capture the arguments of each frame', () => { const error = catchError(() => callingFunction(1, 2)) - collectExceptionReplay(error) + reportError(error) const [throwingSnapshot, callingSnapshot] = sentSnapshots() expect(throwingSnapshot.probe.location).toEqual({ type: 'src/throwing.ts', method: 'throwingFunction' }) @@ -161,7 +169,7 @@ describe('exceptionReplay', () => { it('should send snapshots in the same envelope as probe snapshots', () => { const error = catchError(() => throwingFunction(1)) - collectExceptionReplay(error) + reportError(error) const payload = mockBatchAdd.calls.mostRecent().args[0] expect(payload).toEqual( @@ -186,7 +194,7 @@ describe('exceptionReplay', () => { it('should redact sensitive arguments', () => { const error = catchError(() => throwingFunction(1, 'hunter2')) - collectExceptionReplay(error) + reportError(error) expect(sentSnapshots()[0].captures.return.arguments.secret).toEqual({ type: 'string', @@ -197,7 +205,7 @@ describe('exceptionReplay', () => { it('should only capture the three innermost frames', () => { const error = catchError(outermostFunction) - const attributes = collectExceptionReplay(error)! + const attributes = reportError(error)! expect(attributes.frames.map(({ index }) => index)).toEqual([ stackIndexOf(error, 'throwingFunction'), @@ -222,9 +230,11 @@ describe('exceptionReplay', () => { (e: unknown) => e ) - const attributes = collectExceptionReplay(error)! + const attributes = reportError(error)! - expect(attributes.frames[0].index).toBe(stackIndexOf(error, 'asyncThrowingFunction')) + // The error is created in `asyncThrowingFunction`, so its frame is the innermost one. Some + // browsers, like Safari 14, leave the function's name out of the stack after an `await`. + expect(attributes.frames[0].index).toBe(0) }) it('should not send snapshots for exceptions that are not reported', () => { @@ -233,13 +243,48 @@ describe('exceptionReplay', () => { expect(mockBatchAdd).not.toHaveBeenCalled() }) + it('should only send snapshots once RUM collects the error event', () => { + const error = catchError(() => callingFunction(1, 2)) + + const attributes = collectExceptionReplay(error)! + expect(mockBatchAdd).not.toHaveBeenCalled() + + sendExceptionReplay(error) + expect(sentSnapshots().map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) + }) + + it('should not send snapshots for an error event that RUM drops', () => { + const dropped = catchError(() => throwingFunction(1)) + expect(collectExceptionReplay(dropped)).toBeDefined() + + expect(mockBatchAdd).not.toHaveBeenCalled() + // The fingerprint wasn't reported, so it isn't cooling down + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + }) + + it('should send the snapshots of an error once RUM collects it, after dropping it once', () => { + const error = catchError(() => throwingFunction(1)) + const attributes = collectExceptionReplay(error)! + + expect(reportError(error)).toBe(attributes) + expect(sentSnapshots().map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) + }) + + it('should not capture exceptions in sessions that RUM does not track', () => { + resetExceptionReplay() + registerExceptionReplayPlugin(() => false) + startExceptionReplay() + + expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() + }) + it('should reuse the same snapshots when an error is reported twice', () => { const error = catchError(() => callingFunction(1, 2)) - const attributes = collectExceptionReplay(error) + const attributes = reportError(error) const callCount = mockBatchAdd.calls.count() - expect(collectExceptionReplay(error)).toBe(attributes) + expect(reportError(error)).toBe(attributes) expect(mockBatchAdd.calls.count()).toBe(callCount) }) @@ -250,26 +295,26 @@ describe('exceptionReplay', () => { throwingFunction(1) } catch (e) { error = e - collectExceptionReplay(e) + reportError(e) onCatch('src/reporting.ts;reportingFunction', e, undefined, {}) } } reportingFunction() - expect(collectExceptionReplay(error)!.frames.length).toBe(1) + expect(reportError(error)!.frames.length).toBe(1) expect(mockBatchAdd).toHaveBeenCalledTimes(1) }) it('should return undefined for errors without captured frames', () => { - expect(collectExceptionReplay(new Error('not thrown through instrumented code'))).toBeUndefined() - expect(collectExceptionReplay(undefined)).toBeUndefined() + expect(reportError(new Error('not thrown through instrumented code'))).toBeUndefined() + expect(reportError(undefined)).toBeUndefined() }) it('should ignore thrown values that are not objects', () => { expect(() => onCatch('src/throwing.ts;throwingFunction', 'boom', undefined, {})).not.toThrow() - expect(collectExceptionReplay('boom')).toBeUndefined() + expect(reportError('boom')).toBeUndefined() }) it('should skip frames that are not in the error stack', () => { @@ -285,7 +330,7 @@ describe('exceptionReplay', () => { const error = catchError(rethrowingFunction) - expect(collectExceptionReplay(error)).toBeUndefined() + expect(reportError(error)).toBeUndefined() expect(mockBatchAdd).not.toHaveBeenCalled() }) @@ -293,14 +338,14 @@ describe('exceptionReplay', () => { const error = catchError(() => throwingFunction(1)) resetDebuggerTransport() - expect(collectExceptionReplay(error)).toBeUndefined() + expect(reportError(error)).toBeUndefined() }) it('should respect the global snapshot budget', () => { initTransport({ maxSnapshotsPerSecondGlobally: 1 }) const error = catchError(() => callingFunction(1, 2)) - const attributes = collectExceptionReplay(error)! + const attributes = reportError(error)! expect(attributes.frames.length).toBe(1) expect(mockBatchAdd).toHaveBeenCalledTimes(1) @@ -309,26 +354,26 @@ describe('exceptionReplay', () => { it('should not capture an exception with the same fingerprint for an hour after reporting it', () => { const clock = mockClock() - collectExceptionReplay(catchError(() => throwingFunction(1))) - expect(collectExceptionReplay(catchError(() => throwingFunction(2)))).toBeUndefined() + reportError(catchError(() => throwingFunction(1))) + expect(reportError(catchError(() => throwingFunction(2)))).toBeUndefined() clock.tick(60 * 60 * 1000 + 1) - expect(collectExceptionReplay(catchError(() => throwingFunction(3)))).toBeDefined() + expect(reportError(catchError(() => throwingFunction(3)))).toBeDefined() }) it('should only report one of the exceptions with the same fingerprint captured before either is reported', () => { const first = catchError(() => throwingFunction(1)) const second = catchError(() => throwingFunction(2)) - expect(collectExceptionReplay(first)).toBeDefined() - expect(collectExceptionReplay(second)).toBeUndefined() + expect(reportError(first)).toBeDefined() + expect(reportError(second)).toBeUndefined() expect(mockBatchAdd).toHaveBeenCalledTimes(1) }) it('should keep capturing an exception that was never reported', () => { catchError(() => throwingFunction(1)) - expect(collectExceptionReplay(catchError(() => throwingFunction(2)))).toBeDefined() + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() }) it('should limit the number of exceptions captured per second', () => { @@ -343,11 +388,11 @@ describe('exceptionReplay', () => { } const errors = Array.from({ length: 11 }, (_, i) => catchError(() => throwingFunction(i))) - expect(collectExceptionReplay(errors[10])).toBeUndefined() - expect(collectExceptionReplay(errors[9])).toBeDefined() - expect(collectExceptionReplay(catchError(typeErrorFunction))).toBeUndefined() + expect(reportError(errors[10])).toBeUndefined() + expect(reportError(errors[9])).toBeDefined() + expect(reportError(catchError(typeErrorFunction))).toBeUndefined() clock.tick(1001) - expect(collectExceptionReplay(catchError(typeErrorFunction))).toBeDefined() + expect(reportError(catchError(typeErrorFunction))).toBeDefined() }) }) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index b19e63ccdb..61dc52a9fb 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -4,7 +4,8 @@ import { monitorError } from '@datadog/js-core/monitor' import { computeStackTrace, isError } from '@datadog/browser-core' import type { StackTrace } from '@datadog/browser-core' import type { BrowserWindow } from '../entries/main' -import { captureArguments, queueExceptionSnapshot } from './api' +import { captureArguments, isDebuggerTransportInitialized, queueExceptionSnapshot } from './api' +import type { ExceptionSnapshot } from './api' import type { CaptureContext } from './capture' import { formatThrowable, formatUnknownError, safeReadErrorProperty } from './error' import { checkGlobalSnapshotBudget } from './probes' @@ -48,6 +49,8 @@ interface CapturedException { frames: CapturedFrame[] // Set when the exception is first reported, so reporting it again reuses the same snapshots attributes?: ExceptionReplayAttributes | null + // Snapshots of a reported exception, until RUM collects its error event + pendingSnapshots?: ExceptionSnapshot[] } let capturedExceptions = new WeakMap() @@ -56,12 +59,16 @@ let captureWindowStart = -Infinity let capturesInWindow = 0 let pluginRegistered = false let debuggerStarted = false +let isSessionTracked: () => boolean = () => true /** * Called when the Exception Replay plugin is registered on the RUM Browser SDK. + * + * @param isTracked - Whether RUM tracks the current session */ -export function registerExceptionReplayPlugin(): void { +export function registerExceptionReplayPlugin(isTracked: () => boolean): void { pluginRegistered = true + isSessionTracked = isTracked installCatchHook() } @@ -80,6 +87,7 @@ export function resetExceptionReplay(): void { capturesInWindow = 0 pluginRegistered = false debuggerStarted = false + isSessionTracked = () => true delete (globalObject as BrowserWindow).$dd_catch } @@ -152,6 +160,11 @@ function startCapture(functionId: string, error: object): CapturedException | fa return false } + // RUM doesn't report the errors of the sessions it doesn't track + if (!isSessionTracked()) { + return false + } + if (now - captureWindowStart > 1000) { captureWindowStart = now capturesInWindow = 0 @@ -165,8 +178,9 @@ function startCapture(functionId: string, error: object): CapturedException | fa } /** - * Called when RUM reports an error. Sends the snapshots captured for the exception, and returns the - * attributes linking them to the RUM error event, or undefined if it has none. + * Called when RUM assembles an error event. Prepares the snapshots captured for the exception, and + * returns the attributes linking them to the event, or undefined if it has none. The snapshots are + * only sent once RUM collects the event (see {@link sendExceptionReplay}). */ export function collectExceptionReplay(error: unknown): ExceptionReplayAttributes | undefined { try { @@ -180,7 +194,7 @@ export function collectExceptionReplay(error: unknown): ExceptionReplayAttribute } if (exception.attributes === undefined) { - exception.attributes = sendSnapshots(error, exception) + exception.attributes = prepareSnapshots(error, exception) } return exception.attributes ?? undefined } catch (e) { @@ -188,13 +202,39 @@ export function collectExceptionReplay(error: unknown): ExceptionReplayAttribute } } -function sendSnapshots(error: object, exception: CapturedException): ExceptionReplayAttributes | null { +/** + * Called when RUM collects an error event, once `beforeSend` and the event rate limits have let it + * through. Sends the snapshots prepared for the exception, so errors that RUM drops send none. + */ +export function sendExceptionReplay(error: unknown): void { + try { + if (!isObject(error)) { + return + } + + const exception = capturedExceptions.get(error) + if (!exception || !exception.pendingSnapshots) { + return + } + + const snapshots = exception.pendingSnapshots + exception.pendingSnapshots = undefined + for (const snapshot of snapshots) { + queueExceptionSnapshot(snapshot) + } + recordReport(exception.fingerprint) + } catch (e) { + monitorError(e) + } +} + +function prepareSnapshots(error: object, exception: CapturedException): ExceptionReplayAttributes | null { const capturedFrames = exception.frames // Release the captures: the exception can't capture more frames once it's reported exception.frames = [] // Another exception with the same fingerprint may have been reported since this one was captured - if (isCoolingDown(exception.fingerprint, performance.now())) { + if (isCoolingDown(exception.fingerprint, performance.now()) || !isDebuggerTransportInitialized()) { return null } @@ -203,6 +243,7 @@ function sendSnapshots(error: object, exception: CapturedException): ExceptionRe const message = formatUnknownError(error) const throwable = formatThrowable(error) const frames: ExceptionReplayAttributes['frames'] = [] + const snapshots: ExceptionSnapshot[] = [] let fromIndex = 0 for (const frame of capturedFrames) { @@ -218,7 +259,7 @@ function sendSnapshots(error: object, exception: CapturedException): ExceptionRe const snapshotId = generateUUID() const separatorIndex = frame.functionId.lastIndexOf(';') - const queued = queueExceptionSnapshot({ + snapshots.push({ id: snapshotId, exceptionId, timestamp: frame.timestamp, @@ -231,10 +272,6 @@ function sendSnapshots(error: object, exception: CapturedException): ExceptionRe arguments: frame.arguments, throwable, }) - if (!queued) { - break - } - frames.push({ index, snapshotId }) fromIndex = index + 1 } @@ -243,7 +280,7 @@ function sendSnapshots(error: object, exception: CapturedException): ExceptionRe return null } - recordReport(exception.fingerprint) + exception.pendingSnapshots = snapshots return { exceptionId, frames } } diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts index 1332a22ac0..7eb9b72771 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -3,25 +3,39 @@ import { registerCleanupTask } from '@datadog/browser-core/test' import type { RumPlugin, RumPluginOnInitOptions } from '@datadog/browser-rum-core' import type { BrowserWindow } from '../entries/main' import { initDebuggerTransport, resetDebuggerTransport } from './api' +import { display } from './display' import { onCatch, resetExceptionReplay, startExceptionReplay } from './exceptionReplay' import { exceptionReplayPlugin } from './exceptionReplayPlugin' import { clearProbes } from './probes' type AssembleHook = Parameters[0] +type EventCollectedHook = Parameters[0] describe('exceptionReplayPlugin', () => { let assembleHook: AssembleHook + let eventCollectedHook: EventCollectedHook + let batchAdd: jasmine.Spy - function initPlugin() { + function initPlugin({ isSessionTracked = true } = {}) { const registerAssembleEventHook = jasmine.createSpy('registerAssembleEventHook') - exceptionReplayPlugin().onInit({ registerAssembleEventHook }) + const registerEventCollectedHook = jasmine.createSpy('registerEventCollectedHook') + exceptionReplayPlugin().onInit({ + publicApi: { getInternalContext: () => (isSessionTracked ? {} : undefined) }, + registerAssembleEventHook, + registerEventCollectedHook, + }) assembleHook = registerAssembleEventHook.calls.mostRecent().args[0] + eventCollectedHook = registerEventCollectedHook.calls.mostRecent().args[0] } function assemble(eventType: string, error: unknown) { return assembleHook({ eventType, domainContext: { error } } as unknown as Parameters[0]) } + function collect(eventType: string, error: unknown) { + eventCollectedHook({ eventType, domainContext: { error } } as unknown as Parameters[0]) + } + function throwingFunction() { try { throw new Error('boom') @@ -43,7 +57,8 @@ describe('exceptionReplayPlugin', () => { beforeEach(() => { clearProbes() - initDebuggerTransport({ service: 'test-service' } as any, { add: jasmine.createSpy('batchAdd') } as any) + batchAdd = jasmine.createSpy('batchAdd') + initDebuggerTransport({ service: 'test-service' } as any, { add: batchAdd } as any) ;(window as any).DD_DEBUGGER = { version: '0.0.1' } startExceptionReplay() @@ -85,6 +100,36 @@ describe('exceptionReplayPlugin', () => { }) }) + it('should send the snapshots once RUM collects the error event', () => { + initPlugin() + const error = catchError(throwingFunction) + assemble('error', error) + expect(batchAdd).not.toHaveBeenCalled() + + collect('error', error) + + expect(batchAdd).toHaveBeenCalledTimes(1) + }) + + it('should not capture errors in sessions that RUM does not track', () => { + initPlugin({ isSessionTracked: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toBe(SKIPPED) + }) + + it('should not start with a RUM Browser SDK that lacks the event collected hook', () => { + const displaySpy = spyOn(display, 'warn') + + exceptionReplayPlugin().onInit({ + publicApi: { getInternalContext: () => ({}) }, + registerAssembleEventHook: jasmine.createSpy('registerAssembleEventHook'), + }) + + expect(displaySpy).toHaveBeenCalled() + expect((window as BrowserWindow).$dd_catch).toBeUndefined() + }) + it('should skip errors without snapshots', () => { initPlugin() diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts index df6b962eb3..cd36c38e90 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -1,10 +1,11 @@ import { SKIPPED } from '@datadog/js-core/assembly' -import { collectExceptionReplay, registerExceptionReplayPlugin } from './exceptionReplay' +import { display } from './display' +import { collectExceptionReplay, registerExceptionReplayPlugin, sendExceptionReplay } from './exceptionReplay' // The plugin is typed structurally, rather than with the RUM Browser SDK's `RumPlugin` type, so that // the Live Debugger SDK doesn't depend on the RUM Browser SDK. -interface AssembleEventHookParams { +interface EventHookParams { eventType: string domainContext: object } @@ -21,14 +22,22 @@ type ExceptionReplayEventAttributes = { } } -type AssembleEventHook = (params: AssembleEventHookParams) => ExceptionReplayEventAttributes | SKIPPED +type AssembleEventHook = (params: EventHookParams) => ExceptionReplayEventAttributes | SKIPPED +type EventCollectedHook = (params: EventHookParams) => void + +interface ExceptionReplayPluginOnInitOptions { + publicApi: { getInternalContext: () => object | undefined } + registerAssembleEventHook: (callback: AssembleEventHook) => unknown + // Missing from RUM Browser SDK versions older than this plugin + registerEventCollectedHook?: (callback: EventCollectedHook) => unknown +} /** * Exception Replay plugin for the RUM Browser SDK. Compatible with the RUM Browser SDK's `RumPlugin`. */ export interface ExceptionReplayPlugin { name: string - onInit(options: { registerAssembleEventHook: (callback: AssembleEventHook) => unknown }): void + onInit(options: ExceptionReplayPluginOnInitOptions): void } /** @@ -36,16 +45,23 @@ export interface ExceptionReplayPlugin { * * When an application built with the Live Debugger build plugin's `exceptionReplay` option throws, * the Live Debugger SDK captures the arguments of the instrumented functions the exception passes - * through. When RUM reports the error, this plugin sends those captures as snapshots and links them - * to the RUM error event, so Error Tracking can show them on the error's stack frames. + * through. When RUM reports the error, this plugin links those captures to the RUM error event, and + * sends them as snapshots once the event passes `beforeSend` and the event rate limits, so Error + * Tracking can show them on the error's stack frames. * - * Exception Replay only starts once the plugin is registered and `DD_DEBUGGER.init()` is called. + * Exception Replay only starts once the plugin is registered and `DD_DEBUGGER.init()` is called. It + * doesn't capture anything in sessions that RUM doesn't track. */ export function exceptionReplayPlugin(): ExceptionReplayPlugin { return { name: 'exception-replay', - onInit({ registerAssembleEventHook }) { - registerExceptionReplayPlugin() + onInit({ publicApi, registerAssembleEventHook, registerEventCollectedHook }) { + if (!registerEventCollectedHook) { + display.warn('Exception Replay requires a version of the RUM Browser SDK that matches the Live Debugger SDK.') + return + } + + registerExceptionReplayPlugin(() => publicApi.getInternalContext() !== undefined) registerAssembleEventHook(({ eventType, domainContext }) => { if (eventType !== 'error') { @@ -71,6 +87,12 @@ export function exceptionReplayPlugin(): ExceptionReplayPlugin { }, } }) + + registerEventCollectedHook(({ eventType, domainContext }) => { + if (eventType === 'error' && 'error' in domainContext) { + sendExceptionReplay(domainContext.error) + } + }) }, } } diff --git a/packages/browser-debugger/src/entries/main.spec.ts b/packages/browser-debugger/src/entries/main.spec.ts index 36db1628bf..9057a8f412 100644 --- a/packages/browser-debugger/src/entries/main.spec.ts +++ b/packages/browser-debugger/src/entries/main.spec.ts @@ -58,7 +58,7 @@ describe('datadogDebugger', () => { it('should install the Exception Replay catch hook on init once the plugin is registered', () => { mockInitDependencies() - registerExceptionReplayPlugin() + registerExceptionReplayPlugin(() => true) datadogDebugger.init(INIT_CONFIGURATION) diff --git a/packages/browser-rum-core/src/boot/preStartRum.spec.ts b/packages/browser-rum-core/src/boot/preStartRum.spec.ts index a5d3e013ce..0b3ccc07d2 100644 --- a/packages/browser-rum-core/src/boot/preStartRum.spec.ts +++ b/packages/browser-rum-core/src/boot/preStartRum.spec.ts @@ -626,6 +626,8 @@ describe('preStartRum', () => { jasmine.objectContaining({ initConfiguration, publicApi: PUBLIC_API, + registerAssembleEventHook: jasmine.any(Function), + registerEventCollectedHook: jasmine.any(Function), }) ) }) diff --git a/packages/browser-rum-core/src/boot/preStartRum.ts b/packages/browser-rum-core/src/boot/preStartRum.ts index 1109dd373b..6aa777bf41 100644 --- a/packages/browser-rum-core/src/boot/preStartRum.ts +++ b/packages/browser-rum-core/src/boot/preStartRum.ts @@ -368,6 +368,7 @@ export function createPreStartStrategy( initConfiguration, publicApi, registerAssembleEventHook: hooks.assembleEvent.register, + registerEventCollectedHook: hooks.eventCollected.register, } const shouldContinue = callPluginsOnInit(initConfiguration.plugins, onInitOptions) diff --git a/packages/browser-rum-core/src/domain/assembly.spec.ts b/packages/browser-rum-core/src/domain/assembly.spec.ts index f50667be8f..f954057b50 100644 --- a/packages/browser-rum-core/src/domain/assembly.spec.ts +++ b/packages/browser-rum-core/src/domain/assembly.spec.ts @@ -791,6 +791,46 @@ describe('rum assembly', () => { }) }) + describe('eventCollected hook', () => { + it('is triggered with the collected event and its domain context', () => { + const { lifeCycle, hooks, serverRumEvents } = setupAssemblyTestWithDefaults() + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(eventCollectedSpy) + const domainContext = { error: new Error('boom') } as RumEventDomainContext + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR), domainContext }) + + expect(eventCollectedSpy).toHaveBeenCalledOnceWith({ + eventType: RumEventType.ERROR, + event: serverRumEvents[0], + domainContext, + }) + }) + + it('is not triggered for events dismissed by beforeSend', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults({ + partialConfiguration: { beforeSend: () => false }, + }) + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(eventCollectedSpy) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(eventCollectedSpy).not.toHaveBeenCalled() + }) + + it('is not triggered for events over the rate limit', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults({ eventRateLimit: 1 }) + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(eventCollectedSpy) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(eventCollectedSpy).toHaveBeenCalledTimes(1) + }) + }) + describe('event generation condition', () => { it('when tracked, it should generate event', () => { const { lifeCycle, serverRumEvents } = setupAssemblyTestWithDefaults() diff --git a/packages/browser-rum-core/src/domain/assembly.ts b/packages/browser-rum-core/src/domain/assembly.ts index df2ec75793..f1cad698e4 100644 --- a/packages/browser-rum-core/src/domain/assembly.ts +++ b/packages/browser-rum-core/src/domain/assembly.ts @@ -103,6 +103,7 @@ export function startRumAssembly( delete serverRumEvent.context } lifeCycle.notify(LifeCycleEventType.RUM_EVENT_COLLECTED, serverRumEvent) + hooks.eventCollected.trigger({ eventType: serverRumEvent.type, event: serverRumEvent, domainContext }) } } ) diff --git a/packages/browser-rum-core/src/domain/hooks.ts b/packages/browser-rum-core/src/domain/hooks.ts index aa218a9f6e..cc623c44bc 100644 --- a/packages/browser-rum-core/src/domain/hooks.ts +++ b/packages/browser-rum-core/src/domain/hooks.ts @@ -4,7 +4,7 @@ import { createHook } from '@datadog/js-core/assembly' import type { Hook } from '@datadog/js-core/assembly' import type { RecursivePartial } from '@datadog/js-core/util' import type { RumEvent } from '../rumEvent.types' -import type { RawRumEvent } from '../rawRumEvent.types' +import type { AssembledRumEvent, RawRumEvent } from '../rawRumEvent.types' import type { RumEventDomainContext } from '../domainContext.types' // Define a partial RUM event type. @@ -29,10 +29,19 @@ export interface AssembleHookParams { export type AssembleHook = Hook export type AssembleTelemetryHook = Hook<{ startTime: RelativeTime }, DefaultTelemetryEventAttributes> +export interface EventCollectedHookParams { + readonly eventType: RumEvent['type'] + event: Readonly + domainContext: DeepReadonly> +} + +export type EventCollectedHook = Hook + export interface Hooks { assembleEventDefaults: AssembleHook assembleTelemetry: AssembleTelemetryHook assembleEvent: AssembleHook + eventCollected: EventCollectedHook } export function createHooks(): Hooks { @@ -40,5 +49,6 @@ export function createHooks(): Hooks { assembleEventDefaults: createHook(), assembleTelemetry: createHook(), assembleEvent: createHook(), + eventCollected: createHook(), } } diff --git a/packages/browser-rum-core/src/domain/plugins.ts b/packages/browser-rum-core/src/domain/plugins.ts index 171c7ea1d2..aeaa29bda4 100644 --- a/packages/browser-rum-core/src/domain/plugins.ts +++ b/packages/browser-rum-core/src/domain/plugins.ts @@ -2,7 +2,7 @@ import { isThenable } from '@datadog/browser-core' import type { RumPublicApi } from '../boot/rumPublicApi' import type { StartRumResult } from '../boot/startRum' import type { RumInitConfiguration } from './configuration' -import type { AssembleHook } from './hooks' +import type { AssembleHook, EventCollectedHook } from './hooks' /** * onInit plugin API options. @@ -18,6 +18,12 @@ export interface RumPluginOnInitOptions { * assembled, including events buffered during the pre-start phase. */ registerAssembleEventHook: AssembleHook['register'] + /** + * Register a callback invoked when a RUM event is collected, once `beforeSend` and the event rate + * limits have let it through, right before it is sent. Plugins can use it to send data related to + * an event only if the event itself is sent. + */ + registerEventCollectedHook: EventCollectedHook['register'] } /** diff --git a/test/e2e/scenario/debugger.scenario.ts b/test/e2e/scenario/debugger.scenario.ts index 05b62e39dd..5074f3aaca 100644 --- a/test/e2e/scenario/debugger.scenario.ts +++ b/test/e2e/scenario/debugger.scenario.ts @@ -168,6 +168,30 @@ async function injectThrowingFunction(page: Page) { await waitForProbe(page, 'TestModule;throwingFunction') } +// Instrumented code is loaded from a script, so its stack frames have a URL. Code evaluated by +// Playwright has none, so Exception Replay can't locate its frames. +const EXCEPTION_REPLAY_BODY = html` + +` + test.describe('debugger', () => { createTest('send debugger snapshot when instrumented function is called') .withDebugger() @@ -663,29 +687,7 @@ test.describe('debugger', () => { } }) .withDebugger() - // Instrumented code is loaded from a script, so its stack frames have a URL. Code evaluated by - // Playwright has none, so Exception Replay can't locate its frames. - .withBody(html` - - `) + .withBody(EXCEPTION_REPLAY_BODY) .run(async ({ intakeRegistry, flushEvents, page }) => { await page.evaluate(() => { try { @@ -730,4 +732,38 @@ test.describe('debugger', () => { }) expect(snapshots[1].captures.return.arguments.count).toEqual({ type: 'number', value: '1' }) }) + + createTest('do not send Exception Replay snapshots for errors dismissed by beforeSend') + .withRum() + .withRumInit((configuration) => { + // The debugger is loaded after RUM, so wait for it to create the plugin + const initRum = () => { + window.DD_RUM!.init({ + ...configuration, + plugins: [(window as any).DD_DEBUGGER.exceptionReplayPlugin()], + beforeSend: (event) => event.type !== 'error', + }) + } + if ((window as any).DD_DEBUGGER) { + ;(window as any).DD_DEBUGGER.onReady(initRum) + } else { + document.addEventListener('DOMContentLoaded', initRum) + } + }) + .withDebugger() + .withBody(EXCEPTION_REPLAY_BODY) + .run(async ({ intakeRegistry, flushEvents, page }) => { + await page.evaluate(() => { + try { + ;(window as any).callingFunction(1) + } catch (error) { + window.DD_RUM!.addError(error) + } + }) + + await flushEvents() + + expect(intakeRegistry.rumErrorEvents).toHaveLength(0) + expect(intakeRegistry.debuggerEvents).toHaveLength(0) + }) }) From 08f81da7fd8de59db49d453c5bc13edb3a3f4f6f Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Thu, 29 Oct 2026 11:39:22 +0100 Subject: [PATCH 03/22] =?UTF-8?q?=F0=9F=91=B7=20[DEBUG-6444]=20Fix=20the?= =?UTF-8?q?=20browser-rum-core=20declaration=20build?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The declaration build failed with "Type instantiation is excessively deep" where the `eventCollected` hook is triggered. Checking that the domain context fits `DeepReadonly` recursed through the DOM types it holds. `yarn typecheck` didn't catch it, as it uses another configuration. The hook's domain context is now a plain `RumEventDomainContext`. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-rum-core/src/domain/hooks.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/browser-rum-core/src/domain/hooks.ts b/packages/browser-rum-core/src/domain/hooks.ts index cc623c44bc..6864e0389c 100644 --- a/packages/browser-rum-core/src/domain/hooks.ts +++ b/packages/browser-rum-core/src/domain/hooks.ts @@ -29,10 +29,12 @@ export interface AssembleHookParams { export type AssembleHook = Hook export type AssembleTelemetryHook = Hook<{ startTime: RelativeTime }, DefaultTelemetryEventAttributes> +// Unlike AssembleHookParams, the domain context isn't DeepReadonly: checking that it fits recurses +// through the DOM types it holds, which the declaration build rejects as excessively deep. export interface EventCollectedHookParams { readonly eventType: RumEvent['type'] - event: Readonly - domainContext: DeepReadonly> + readonly event: Readonly + readonly domainContext: RumEventDomainContext } export type EventCollectedHook = Hook From db0df197233a136d1795316597a02d5f35f1992f Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Thu, 29 Oct 2026 12:07:30 +0100 Subject: [PATCH 04/22] =?UTF-8?q?=F0=9F=91=B7=20[DEBUG-6444]=20Point=20@da?= =?UTF-8?q?tadog/rum-events-format=20at=20the=20Exception=20Replay=20schem?= =?UTF-8?q?a=20PR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit check-schemas regenerates the types from the pinned schema, which didn't have the Exception Replay fields yet. Pin the head commit of DataDog/rum-events-format#458 until it merges, then bump to its merge commit. The regenerated types also pick up #454 (Add Unreal as source), which is already on rum-events-format master. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 03bd932871..c8c3149a60 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "woke": "scripts/cli woke" }, "devDependencies": { - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5", + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=070d92554ad397af100972184177404adbb36a7f", "@eslint/js": "10.0.1", "@microsoft/api-extractor": "7.60.1", "@oxc-project/runtime": "0.152.0", diff --git a/yarn.lock b/yarn.lock index f6a61a9702..40a838853d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -750,10 +750,10 @@ __metadata: languageName: unknown linkType: soft -"@datadog/rum-events-format@DataDog/rum-events-format#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5": +"@datadog/rum-events-format@DataDog/rum-events-format#commit=070d92554ad397af100972184177404adbb36a7f": version: 0.0.0 - resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5" - checksum: 10c0/3426d4a433ed7055d1ba8421e3cef6f5e6576d9c354c4613314cdda894cc28b32718f5f86a2801efa32057f2f3612772d72571d9226acbf79dd52e17d2c8d0ae + resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=070d92554ad397af100972184177404adbb36a7f" + checksum: 10c0/8dd4bca8b783e2b75518f8dcc1080c497848f745294a51944357efdfcbc6a6a31bf4d53721103f994bd7f789660435f113e44fcc2ddefe5522ac945314756eb0 languageName: node linkType: hard @@ -6333,7 +6333,7 @@ __metadata: version: 0.0.0-use.local resolution: "browser-sdk@workspace:." dependencies: - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5" + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=070d92554ad397af100972184177404adbb36a7f" "@eslint/js": "npm:10.0.1" "@microsoft/api-extractor": "npm:7.60.1" "@oxc-project/runtime": "npm:0.152.0" From f81b56e01e0e68a9bbc86be5704bf2ddd828733f Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Sat, 31 Oct 2026 14:44:25 +0100 Subject: [PATCH 05/22] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20[DEBUG-6444]=20Give?= =?UTF-8?q?=20Exception=20Replay=20its=20own=20capture=20time=20budget?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exception Replay captures on the main thread as exceptions are thrown, and the 10 ms per-frame deadline alone allowed up to 300 ms per second (10 exceptions with 3 frames each). The deadline also can't interrupt a single slow step, such as reading the property names of an object with 100k keys. - Cap capturing at 25 ms per second on average. Each frame's deadline is also capped by the remaining budget. Time spent beyond the budget is carried over, so capturing pauses until it's made up. - Stop counting Exception Replay snapshots against the probes' maxSnapshotsPerSecondGlobally, so neither feature can starve the other. Exception Replay is already limited by its own caps. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-debugger/README.md | 2 +- .../src/domain/exceptionReplay.spec.ts | 53 ++++++++++++++++--- .../src/domain/exceptionReplay.ts | 41 +++++++++++--- 3 files changed, 82 insertions(+), 14 deletions(-) diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index cc14efd7f3..c19201c0b6 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -68,7 +68,7 @@ Exception Replay captures the arguments and `this` of the instrumented functions The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. -Exception Replay snapshots count toward the `maxSnapshotsPerSecondGlobally` limit. +To limit the time spent on the main thread, Exception Replay captures at most 10 exceptions per second, and spends at most 25 ms per second on average capturing them. When a capture takes longer, capturing pauses until the time is made up. These limits are separate from `maxSnapshotsPerSecondGlobally`, which only applies to probes. ## Troubleshooting diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 1f9e9fb5c0..2e6cef3949 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -1,5 +1,6 @@ import { computeStackTrace } from '@datadog/browser-core' import { mockClock, registerCleanupTask } from '@datadog/browser-core/test' +import type { Clock } from '@datadog/browser-core/test' import type { BrowserWindow } from '../entries/main' import { initDebuggerTransport, resetDebuggerTransport } from './api' import { @@ -10,7 +11,7 @@ import { sendExceptionReplay, startExceptionReplay, } from './exceptionReplay' -import { clearProbes } from './probes' +import { checkGlobalSnapshotBudget, clearProbes } from './probes' const browserWindow = window as BrowserWindow @@ -71,6 +72,22 @@ describe('exceptionReplay', () => { } } + // Reading its argument advances the clock, like a capture that takes `ms` and can't be interrupted + function slowFunction(clock: Clock, ms: number) { + const args = { + get value() { + clock.tick(ms) + return 1 + }, + } + try { + throw new Error('slow') + } catch (e) { + onCatch('src/slow.ts;slowFunction', e, undefined, args) + throw e + } + } + function catchError(fn: () => unknown): unknown { let error: unknown try { @@ -341,14 +358,12 @@ describe('exceptionReplay', () => { expect(reportError(error)).toBeUndefined() }) - it('should respect the global snapshot budget', () => { + it('should neither use nor be limited by the snapshot budget of probes', () => { initTransport({ maxSnapshotsPerSecondGlobally: 1 }) const error = catchError(() => callingFunction(1, 2)) - const attributes = reportError(error)! - - expect(attributes.frames.length).toBe(1) - expect(mockBatchAdd).toHaveBeenCalledTimes(1) + expect(reportError(error)!.frames.length).toBe(2) + expect(checkGlobalSnapshotBudget(performance.now(), true)).toBeTrue() }) it('should not capture an exception with the same fingerprint for an hour after reporting it', () => { @@ -395,4 +410,30 @@ describe('exceptionReplay', () => { clock.tick(1001) expect(reportError(catchError(typeErrorFunction))).toBeDefined() }) + + it('should stop capturing the frames of an exception once the capture time budget is used up', () => { + const clock = mockClock() + function callingSlowFunction() { + try { + return slowFunction(clock, 30) + } catch (e) { + onCatch('src/calling-slow.ts;callingSlowFunction', e, undefined, {}) + throw e + } + } + + expect(reportError(catchError(callingSlowFunction))!.frames.length).toBe(1) + }) + + it('should pause capturing until the time spent beyond the capture time budget is made up', () => { + const clock = mockClock() + // 75 ms puts the 25 ms budget 50 ms in debt, which takes 2 s to make up + expect(reportError(catchError(() => slowFunction(clock, 75)))).toBeDefined() + + clock.tick(1500) + expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() + + clock.tick(600) + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + }) }) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 61dc52a9fb..9fa6808cd9 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -8,16 +8,21 @@ import { captureArguments, isDebuggerTransportInitialized, queueExceptionSnapsho import type { ExceptionSnapshot } from './api' import type { CaptureContext } from './capture' import { formatThrowable, formatUnknownError, safeReadErrorProperty } from './error' -import { checkGlobalSnapshotBudget } from './probes' import { mapStackFrames } from './stacktrace' // Like the Java tracer, only capture the innermost frames, which are closest to the cause. const MAX_FRAMES_PER_EXCEPTION = 3 // Exceptions are captured as they're thrown, before it's known whether they will be reported, so -// cap the work for code that throws and catches a lot of exceptions. +// cap the work for code that throws and catches a lot of exceptions. These limits are separate from +// the probes' snapshot budget, so neither feature can use up the other's. const MAX_EXCEPTIONS_CAPTURED_PER_SECOND = 10 +// Capturing blocks the main thread, so also cap the time it takes. The deadline can't interrupt +// everything, such as reading the property names of a huge object, so time spent beyond the budget +// is carried over, and capturing pauses until the budget recovers. +const CAPTURE_BUDGET_MS_PER_SECOND = 25 + // Like the tracers, report snapshots for a given exception fingerprint at most once an hour. const FINGERPRINT_COOLDOWN_MS = 60 * 60 * 1000 const MAX_FINGERPRINTS = 1000 @@ -57,6 +62,8 @@ let capturedExceptions = new WeakMap() let lastReportByFingerprint = new Map() let captureWindowStart = -Infinity let capturesInWindow = 0 +let captureBudgetMs = CAPTURE_BUDGET_MS_PER_SECOND +let captureBudgetUpdatedAt = -Infinity let pluginRegistered = false let debuggerStarted = false let isSessionTracked: () => boolean = () => true @@ -85,6 +92,8 @@ export function resetExceptionReplay(): void { lastReportByFingerprint = new Map() captureWindowStart = -Infinity capturesInWindow = 0 + captureBudgetMs = CAPTURE_BUDGET_MS_PER_SECOND + captureBudgetUpdatedAt = -Infinity pluginRegistered = false debuggerStarted = false isSessionTracked = () => true @@ -133,8 +142,14 @@ export function onCatch(functionId: string, error: unknown, self: unknown, args: return } + const start = performance.now() + const budgetMs = refillCaptureBudget(start) + if (budgetMs <= 0) { + return + } + const captureCtx: CaptureContext = { - deadline: performance.now() + SNAPSHOT_TIMEOUT_MS, + deadline: start + Math.min(SNAPSHOT_TIMEOUT_MS, budgetMs), timedOut: false, // Unlike probes, Exception Replay captures data nobody asked for, so redact sensitive names redact: true, @@ -145,6 +160,8 @@ export function onCatch(functionId: string, error: unknown, self: unknown, args: arguments: captureArguments(args, self, {}, captureCtx), callStack: new Error(), }) + // Charge the time actually spent, which can go past the deadline + captureBudgetMs -= performance.now() - start } catch (e) { monitorError(e) } @@ -165,6 +182,10 @@ function startCapture(functionId: string, error: object): CapturedException | fa return false } + if (refillCaptureBudget(now) <= 0) { + return false + } + if (now - captureWindowStart > 1000) { captureWindowStart = now capturesInWindow = 0 @@ -177,6 +198,16 @@ function startCapture(functionId: string, error: object): CapturedException | fa return { fingerprint, frames: [] } } +// Adds the budget earned since the last update, up to one second's worth, and returns the budget +function refillCaptureBudget(now: number): number { + captureBudgetMs = Math.min( + CAPTURE_BUDGET_MS_PER_SECOND, + captureBudgetMs + ((now - captureBudgetUpdatedAt) * CAPTURE_BUDGET_MS_PER_SECOND) / 1000 + ) + captureBudgetUpdatedAt = now + return captureBudgetMs +} + /** * Called when RUM assembles an error event. Prepares the snapshots captured for the exception, and * returns the attributes linking them to the event, or undefined if it has none. The snapshots are @@ -253,10 +284,6 @@ function prepareSnapshots(error: object, exception: CapturedException): Exceptio continue } - if (!checkGlobalSnapshotBudget(performance.now(), true)) { - break - } - const snapshotId = generateUUID() const separatorIndex = frame.functionId.lastIndexOf(';') snapshots.push({ From 107496758a5ceaac224440ca7d1ce4de66d10ac3 Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Tue, 3 Nov 2026 12:35:25 +0100 Subject: [PATCH 06/22] =?UTF-8?q?=F0=9F=91=8C=20[DEBUG-6444]=20Address=20t?= =?UTF-8?q?he=20automated=20review=20of=20Exception=20Replay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Redact properties and map entries with sensitive symbol keys, which are captured under their description. - Capture errors thrown before RUM starts, whose session isn't known yet. Only skip sessions that RUM doesn't track once it has started. - Don't send the snapshots of an error that RUM dropped once another error with the same fingerprint has been reported. - Trigger the `eventCollected` hook before the event is dispatched, as documented. - Charge the capture time budget even when capturing throws. - Compare only the line of async caller frames, which are located at the `await` instead of the call, so outer async frames aren't dropped. - Match a frame without callers only to a frame of the same function, so its snapshot can't land on an unrelated frame of the same script. - Document that a `beforeSend` removing or reordering frames in `error.stack` can misplace snapshots. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-debugger/README.md | 2 +- .../src/domain/capture.spec.ts | 15 +++ .../browser-debugger/src/domain/capture.ts | 14 ++- .../src/domain/exceptionReplay.spec.ts | 102 ++++++++++++++++++ .../src/domain/exceptionReplay.ts | 75 ++++++++++--- .../src/domain/exceptionReplayPlugin.spec.ts | 15 ++- .../src/domain/exceptionReplayPlugin.ts | 10 +- .../src/domain/assembly.spec.ts | 16 +++ .../browser-rum-core/src/domain/assembly.ts | 2 +- 9 files changed, 229 insertions(+), 22 deletions(-) diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index c19201c0b6..cfc9641275 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -66,7 +66,7 @@ Exception Replay captures the arguments and `this` of the instrumented functions 3. Initialize the Live Debugger SDK as shown in [Usage](#usage). -The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. +The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track. Snapshots are linked to frames by their position in `error.stack`, so a `beforeSend` that removes or reorders frames there can show them on the wrong frames. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. To limit the time spent on the main thread, Exception Replay captures at most 10 exceptions per second, and spends at most 25 ms per second on average capturing them. When a capture takes longer, capturing pauses until the time is made up. These limits are separate from `maxSnapshotsPerSecondGlobally`, which only applies to probes. diff --git a/packages/browser-debugger/src/domain/capture.spec.ts b/packages/browser-debugger/src/domain/capture.spec.ts index 3ff09deb94..05a6c4ee17 100644 --- a/packages/browser-debugger/src/domain/capture.spec.ts +++ b/packages/browser-debugger/src/domain/capture.spec.ts @@ -848,6 +848,21 @@ describe('capture redaction', () => { ]) }) + it('should redact the values of fields and map entries with sensitive symbol keys', () => { + const passwordKey = Symbol('password') + const tokenKey = Symbol('token') + + expect( + captureFields({ [passwordKey]: 'hunter2', [Symbol('name')]: 'alice' }, defaultOpts, redactingContext()) + ).toEqual({ + password: { type: 'string', notCapturedReason: 'redactedIdent' }, + name: { type: 'string', value: 'alice' }, + }) + expect(capture(new Map([[tokenKey, 'abc']]), defaultOpts, redactingContext()).entries).toEqual([ + [jasmine.objectContaining({ type: 'symbol' }), { type: 'string', notCapturedReason: 'redactedIdent' }], + ]) + }) + it('should not read a redacted field twice', () => { const getter = jasmine.createSpy('getter').and.returnValue('hunter2') const obj = {} diff --git a/packages/browser-debugger/src/domain/capture.ts b/packages/browser-debugger/src/domain/capture.ts index 87ccac185d..fc122fba0c 100644 --- a/packages/browser-debugger/src/domain/capture.ts +++ b/packages/browser-debugger/src/domain/capture.ts @@ -328,7 +328,7 @@ function captureObjectPropertiesFields( typeof key === 'symbol' ? key.description || key.toString() : keyStr.includes('.') ? replaceDots(keyStr) : keyStr fields[keyName] = - ctx.redact && typeof key === 'string' && isRedactedIdentifier(key) + ctx.redact && isRedactedKey(key) ? captureRedactedProperty(obj, key) : captureProperty(obj, key, depth, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx) } @@ -424,7 +424,7 @@ function captureMap( } entries.push([ captureValue(key, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), - ctx.redact && typeof key === 'string' && isRedactedIdentifier(key) + ctx.redact && isRedactedKey(key) ? captureRedactedValue(value) : captureValue(value, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), ]) @@ -549,7 +549,15 @@ function captureProperty( } } -function captureRedactedProperty(obj: any, property: string): CapturedValue { +// Symbol keys are captured under their description, so they're redacted by it too +function isRedactedKey(key: unknown): boolean { + if (typeof key === 'symbol') { + return key.description !== undefined && isRedactedIdentifier(key.description) + } + return typeof key === 'string' && isRedactedIdentifier(key) +} + +function captureRedactedProperty(obj: any, property: string | symbol): CapturedValue { try { return captureRedactedValue(obj[property]) } catch { diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 2e6cef3949..ee5e95f86c 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -254,6 +254,72 @@ describe('exceptionReplay', () => { expect(attributes.frames[0].index).toBe(0) }) + it('should capture an async function awaiting a callee that throws before its first await', async () => { + async function asyncCallee(value: number) { + try { + if (value > 0) { + throw new Error('boom') + } + await Promise.resolve() + } catch (e) { + onCatch('src/async.ts;asyncCallee', e, undefined, { value }) + throw e + } + } + async function asyncCaller() { + try { + await asyncCallee(1) + } catch (e) { + onCatch('src/async.ts;asyncCaller', e, undefined, {}) + throw e + } + } + let error: unknown + async function awaitingFunction() { + try { + await asyncCaller() + } catch (e) { + error = e + } + } + + await awaitingFunction() + const attributes = reportError(error)! + + // Once `asyncCaller` resumes, `awaitingFunction` is an async frame located at the `await`, while + // the error's stack has it at the call + expect(attributes.frames.map(({ index }) => index)).toEqual([ + stackIndexOf(error, 'asyncCallee'), + stackIndexOf(error, 'asyncCaller'), + ]) + }) + + it('should not link a function without callers to an unrelated frame of the same script', async () => { + function rejectLater() { + return new Promise((_, reject) => { + setTimeout(function timerCallback() { + reject(new Error('boom')) + }) + }) + } + async function awaitingFunction() { + try { + await rejectLater() + } catch (e) { + onCatch('src/async.ts;awaitingFunction', e, undefined, {}) + throw e + } + } + + // Not awaited, so `awaitingFunction` has no callers once it resumes + const error = await new Promise((resolve) => { + awaitingFunction().catch(resolve) + }) + + // The error's only frame is `timerCallback`, from the same script as `awaitingFunction` + expect(reportError(error)).toBeUndefined() + }) + it('should not send snapshots for exceptions that are not reported', () => { catchError(() => callingFunction(1, 2)) @@ -287,6 +353,16 @@ describe('exceptionReplay', () => { expect(sentSnapshots().map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) }) + it('should not send the snapshots of a dropped error once another error with its fingerprint is reported', () => { + const dropped = catchError(() => throwingFunction(1)) + expect(collectExceptionReplay(dropped)).toBeDefined() + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + mockBatchAdd.calls.reset() + + expect(reportError(dropped)).toBeUndefined() + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + it('should not capture exceptions in sessions that RUM does not track', () => { resetExceptionReplay() registerExceptionReplayPlugin(() => false) @@ -425,6 +501,32 @@ describe('exceptionReplay', () => { expect(reportError(catchError(callingSlowFunction))!.frames.length).toBe(1) }) + it('should charge the capture time budget when capturing throws', () => { + const clock = mockClock() + const args = new Proxy( + {}, + { + ownKeys() { + clock.tick(75) + throw new Error('ownKeys') + }, + } + ) + function throwingWhileCapturing() { + try { + throw new Error('boom') + } catch (e) { + onCatch('src/proxy.ts;throwingWhileCapturing', e, undefined, args) + throw e + } + } + + catchError(throwingWhileCapturing) + clock.tick(1500) + + expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() + }) + it('should pause capturing until the time spent beyond the capture time budget is made up', () => { const clock = mockClock() // 75 ms puts the 25 ms budget 50 ms in debt, which takes 2 s to make up diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 9fa6808cd9..7da5714b48 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -154,14 +154,17 @@ export function onCatch(functionId: string, error: unknown, self: unknown, args: // Unlike probes, Exception Replay captures data nobody asked for, so redact sensitive names redact: true, } - exception.frames.push({ - functionId, - timestamp: timeStampNow(), - arguments: captureArguments(args, self, {}, captureCtx), - callStack: new Error(), - }) - // Charge the time actually spent, which can go past the deadline - captureBudgetMs -= performance.now() - start + try { + exception.frames.push({ + functionId, + timestamp: timeStampNow(), + arguments: captureArguments(args, self, {}, captureCtx), + callStack: new Error(), + }) + } finally { + // Charge the time actually spent, which can go past the deadline, even if capturing threw + captureBudgetMs -= performance.now() - start + } } catch (e) { monitorError(e) } @@ -224,6 +227,13 @@ export function collectExceptionReplay(error: unknown): ExceptionReplayAttribute return } + // The error was assembled before but RUM dropped it, and another exception with the same + // fingerprint has been reported since + if (exception.pendingSnapshots && isCoolingDown(exception.fingerprint, performance.now())) { + exception.pendingSnapshots = undefined + exception.attributes = null + } + if (exception.attributes === undefined) { exception.attributes = prepareSnapshots(error, exception) } @@ -334,8 +344,11 @@ function recordReport(fingerprint: string): void { * function's own frame differs, as it has moved to its catch block, so only its URL is compared. * * Both stacks can be truncated (V8 keeps 10 frames by default), so only the callers present in both - * are compared. + * are compared. A function without callers has nothing to compare, so its frame in the error's stack + * must also look like the same function. */ +type StackFrame = StackTrace['stack'][number] + function findFrameIndex( errorFrames: StackTrace['stack'], callFrames: StackTrace['stack'], @@ -353,9 +366,13 @@ function findFrameIndex( } const comparedCount = Math.min(callers.length, errorFrames.length - index - 1) - // A function with callers needs at least one of them in the error's stack to confirm the match. - // A function without callers is at the bottom of both stacks. - if (callers.length > 0 ? comparedCount === 0 : index !== errorFrames.length - 1) { + if (callers.length > 0) { + // A function with callers needs at least one of them in the error's stack to confirm the match + if (comparedCount === 0) { + continue + } + } else if (index !== errorFrames.length - 1 || !isSameFunction(errorFrames[index], functionFrame)) { + // A function without callers is at the bottom of both stacks continue } @@ -369,8 +386,38 @@ function findFrameIndex( } } -function isSameLocation(a: StackTrace['stack'][number], b: StackTrace['stack'][number]): boolean { - return a.url === b.url && a.line === b.line && a.column === b.column +// After an `await`, the stack shows a caller as an async frame located at the `await` instead of the +// call, as in `async main` (Chrome) or `async*main` (Firefox), so only its line can be compared. +const ASYNC_FRAME_PREFIX = /^async[ *]/ + +function isSameLocation(a: StackFrame, b: StackFrame): boolean { + return a.url === b.url && a.line === b.line && (a.column === b.column || isAsyncFrame(a) || isAsyncFrame(b)) +} + +function isAsyncFrame(frame: StackFrame): boolean { + return frame.func !== undefined && ASYNC_FRAME_PREFIX.test(frame.func) +} + +// Compares function names when both frames have one. Otherwise, the frame from the error's stack must +// come first: it's where the function threw or called a callee, before reaching its catch block. +function isSameFunction(errorFrame: StackFrame, functionFrame: StackFrame): boolean { + const errorFunction = getFunctionName(errorFrame) + const functionName = getFunctionName(functionFrame) + if (errorFunction !== undefined && functionName !== undefined) { + return errorFunction === functionName + } + return ( + errorFrame.line !== undefined && + functionFrame.line !== undefined && + (errorFrame.line < functionFrame.line || + (errorFrame.line === functionFrame.line && (errorFrame.column ?? 0) < (functionFrame.column ?? 0))) + ) +} + +function getFunctionName(frame: StackFrame): string | undefined { + const name = frame.func?.replace(ASYNC_FRAME_PREFIX, '') + // `computeStackTrace` names unknown functions `?` + return name && name !== '?' ? name : undefined } function isObject(value: unknown): value is object { diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts index 7eb9b72771..20b893a3d0 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -16,14 +16,18 @@ describe('exceptionReplayPlugin', () => { let eventCollectedHook: EventCollectedHook let batchAdd: jasmine.Spy - function initPlugin({ isSessionTracked = true } = {}) { + function initPlugin({ isSessionTracked = true, rumStarted = true } = {}) { const registerAssembleEventHook = jasmine.createSpy('registerAssembleEventHook') const registerEventCollectedHook = jasmine.createSpy('registerEventCollectedHook') - exceptionReplayPlugin().onInit({ + const plugin = exceptionReplayPlugin() + plugin.onInit({ publicApi: { getInternalContext: () => (isSessionTracked ? {} : undefined) }, registerAssembleEventHook, registerEventCollectedHook, }) + if (rumStarted) { + plugin.onRumStart() + } assembleHook = registerAssembleEventHook.calls.mostRecent().args[0] eventCollectedHook = registerEventCollectedHook.calls.mostRecent().args[0] } @@ -118,6 +122,13 @@ describe('exceptionReplayPlugin', () => { expect(assemble('error', error)).toBe(SKIPPED) }) + it('should capture errors thrown before RUM starts, as their session is not known yet', () => { + initPlugin({ isSessionTracked: false, rumStarted: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).not.toBe(SKIPPED) + }) + it('should not start with a RUM Browser SDK that lacks the event collected hook', () => { const displaySpy = spyOn(display, 'warn') diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts index cd36c38e90..c89b2e0deb 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -38,6 +38,7 @@ interface ExceptionReplayPluginOnInitOptions { export interface ExceptionReplayPlugin { name: string onInit(options: ExceptionReplayPluginOnInitOptions): void + onRumStart(): void } /** @@ -53,6 +54,8 @@ export interface ExceptionReplayPlugin { * doesn't capture anything in sessions that RUM doesn't track. */ export function exceptionReplayPlugin(): ExceptionReplayPlugin { + let rumStarted = false + return { name: 'exception-replay', onInit({ publicApi, registerAssembleEventHook, registerEventCollectedHook }) { @@ -61,7 +64,9 @@ export function exceptionReplayPlugin(): ExceptionReplayPlugin { return } - registerExceptionReplayPlugin(() => publicApi.getInternalContext() !== undefined) + // Until RUM starts, its session isn't known yet, and RUM reports the errors it buffered once + // it starts, so they're captured + registerExceptionReplayPlugin(() => !rumStarted || publicApi.getInternalContext() !== undefined) registerAssembleEventHook(({ eventType, domainContext }) => { if (eventType !== 'error') { @@ -94,5 +99,8 @@ export function exceptionReplayPlugin(): ExceptionReplayPlugin { } }) }, + onRumStart() { + rumStarted = true + }, } } diff --git a/packages/browser-rum-core/src/domain/assembly.spec.ts b/packages/browser-rum-core/src/domain/assembly.spec.ts index f954057b50..1302c87e85 100644 --- a/packages/browser-rum-core/src/domain/assembly.spec.ts +++ b/packages/browser-rum-core/src/domain/assembly.spec.ts @@ -807,6 +807,22 @@ describe('rum assembly', () => { }) }) + it('is triggered before the event is dispatched', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults() + const calls: string[] = [] + hooks.eventCollected.register(() => { + calls.push('eventCollected') + }) + const subscription = lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, () => { + calls.push('RUM_EVENT_COLLECTED') + }) + registerCleanupTask(() => subscription.unsubscribe()) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(calls).toEqual(['eventCollected', 'RUM_EVENT_COLLECTED']) + }) + it('is not triggered for events dismissed by beforeSend', () => { const { lifeCycle, hooks } = setupAssemblyTestWithDefaults({ partialConfiguration: { beforeSend: () => false }, diff --git a/packages/browser-rum-core/src/domain/assembly.ts b/packages/browser-rum-core/src/domain/assembly.ts index f1cad698e4..d263033bcf 100644 --- a/packages/browser-rum-core/src/domain/assembly.ts +++ b/packages/browser-rum-core/src/domain/assembly.ts @@ -102,8 +102,8 @@ export function startRumAssembly( if (isEmptyObject(serverRumEvent.context!)) { delete serverRumEvent.context } - lifeCycle.notify(LifeCycleEventType.RUM_EVENT_COLLECTED, serverRumEvent) hooks.eventCollected.trigger({ eventType: serverRumEvent.type, event: serverRumEvent, domainContext }) + lifeCycle.notify(LifeCycleEventType.RUM_EVENT_COLLECTED, serverRumEvent) } } ) From 12e9670640de6c929c732636641309df52ba5367 Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Tue, 3 Nov 2026 13:02:43 +0100 Subject: [PATCH 07/22] =?UTF-8?q?=E2=9C=85=20[DEBUG-6444]=20Fix=20the=20as?= =?UTF-8?q?ync=20Exception=20Replay=20spec=20in=20browsers=20without=20asy?= =?UTF-8?q?nc=20stack=20traces?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The older Chrome, Edge, Firefox and Safari versions on BrowserStack don't record async stack traces, so once `asyncCaller` resumes, its stack shows no caller and its frame can't be confirmed. The SDK then leaves it without a snapshot, as intended. Only expect its snapshot when the browser records async stack traces. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplay.spec.ts | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index ee5e95f86c..fde33e82e8 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -106,6 +106,19 @@ describe('exceptionReplay', () => { return attributes } + // Whether the stack of a resumed async function includes the function awaiting it + async function hasAsyncStackTraces(): Promise { + async function resumedFunction() { + await Promise.resolve() + return computeStackTrace(new Error()).stack + } + async function awaitingCaller() { + return await resumedFunction() + } + const frames = await awaitingCaller() + return frames.some((frame) => frame.func?.includes('awaitingCaller')) + } + function stackIndexOf(error: unknown, functionName: string): number { return computeStackTrace(error).stack.findIndex((frame) => frame.func?.includes(functionName)) } @@ -287,11 +300,12 @@ describe('exceptionReplay', () => { const attributes = reportError(error)! // Once `asyncCaller` resumes, `awaitingFunction` is an async frame located at the `await`, while - // the error's stack has it at the call - expect(attributes.frames.map(({ index }) => index)).toEqual([ - stackIndexOf(error, 'asyncCallee'), - stackIndexOf(error, 'asyncCaller'), - ]) + // the error's stack has it at the call. Browsers without async stack traces show no caller for + // `asyncCaller`, so its frame can't be confirmed and gets no snapshot. + const capturedFunctions = (await hasAsyncStackTraces()) ? ['asyncCallee', 'asyncCaller'] : ['asyncCallee'] + expect(attributes.frames.map(({ index }) => index)).toEqual( + capturedFunctions.map((functionName) => stackIndexOf(error, functionName)) + ) }) it('should not link a function without callers to an unrelated frame of the same script', async () => { From 14024b88c77571544ebee1a223d9f797e4429d46 Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Tue, 3 Nov 2026 13:21:39 +0100 Subject: [PATCH 08/22] =?UTF-8?q?=F0=9F=91=8C=20[DEBUG-6444]=20Address=20t?= =?UTF-8?q?he=20second=20automated=20review=20of=20Exception=20Replay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Don't capture before RUM starts while tracking consent isn't granted. - Only capture `Error` instances: RUM doesn't report the stack of other thrown values, so their snapshots would link to frames that aren't there. - Keep function identity when comparing async caller frames by line, so two functions on the same line of a minified bundle don't match. - Report redacted objects as `Object` or `Array`, without reading their constructor name, which the redacted object controls. - Document that RUM and the Live Debugger SDK must send to the same site and organization. - Make the async callee spec hold in browsers that don't show async callers on the line of their `await` (Chrome 80, Edge) or don't name async functions (Safari 14): check frame positions, and only require the caller's snapshot where the browser shows the caller there. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-debugger/README.md | 4 +- .../src/domain/capture.spec.ts | 6 +++ .../browser-debugger/src/domain/capture.ts | 3 +- .../src/domain/exceptionReplay.spec.ts | 37 +++++++++++++------ .../src/domain/exceptionReplay.ts | 20 +++++++--- .../src/domain/exceptionReplayPlugin.spec.ts | 15 +++++++- .../src/domain/exceptionReplayPlugin.ts | 11 ++++-- 7 files changed, 70 insertions(+), 26 deletions(-) diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index cfc9641275..280d8f55ee 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -64,9 +64,9 @@ Exception Replay captures the arguments and `this` of the instrumented functions }) ``` -3. Initialize the Live Debugger SDK as shown in [Usage](#usage). +3. Initialize the Live Debugger SDK as shown in [Usage](#usage). It must send to the same Datadog site and organization as the RUM Browser SDK, or Error Tracking can't find the snapshots of RUM errors. -The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track. Snapshots are linked to frames by their position in `error.stack`, so a `beforeSend` that removes or reorders frames there can show them on the wrong frames. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. +The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track, or before tracking consent is granted. Snapshots are linked to frames by their position in `error.stack`, so a `beforeSend` that removes or reorders frames there can show them on the wrong frames. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. To limit the time spent on the main thread, Exception Replay captures at most 10 exceptions per second, and spends at most 25 ms per second on average capturing them. When a capture takes longer, capturing pauses until the time is made up. These limits are separate from `maxSnapshotsPerSecondGlobally`, which only applies to probes. diff --git a/packages/browser-debugger/src/domain/capture.spec.ts b/packages/browser-debugger/src/domain/capture.spec.ts index 05a6c4ee17..969cabd147 100644 --- a/packages/browser-debugger/src/domain/capture.spec.ts +++ b/packages/browser-debugger/src/domain/capture.spec.ts @@ -863,6 +863,12 @@ describe('capture redaction', () => { ]) }) + it('should not use the constructor name of a redacted object', () => { + expect(captureFields({ password: { constructor: { name: 'hunter2' } } }, defaultOpts, redactingContext())).toEqual({ + password: { type: 'Object', notCapturedReason: 'redactedIdent' }, + }) + }) + it('should not read a redacted field twice', () => { const getter = jasmine.createSpy('getter').and.returnValue('hunter2') const obj = {} diff --git a/packages/browser-debugger/src/domain/capture.ts b/packages/browser-debugger/src/domain/capture.ts index fc122fba0c..aab285ab64 100644 --- a/packages/browser-debugger/src/domain/capture.ts +++ b/packages/browser-debugger/src/domain/capture.ts @@ -570,7 +570,8 @@ function captureRedactedValue(value: unknown): CapturedValue { if (value === null) { type = 'null' } else if (typeof value === 'object') { - type = getConstructorName(value) ?? 'Object' + // Not the constructor name, which a redacted object controls, as in `{ constructor: { name } }` + type = Array.isArray(value) ? 'Array' : 'Object' } else if (typeof value === 'function') { type = 'Function' } else { diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index fde33e82e8..7674173c82 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -106,17 +106,18 @@ describe('exceptionReplay', () => { return attributes } - // Whether the stack of a resumed async function includes the function awaiting it - async function hasAsyncStackTraces(): Promise { + // Whether, once an async function resumes, its stack shows the function awaiting it on the line + // of its `await` + async function hasAsyncCallersOnAwaitLine(): Promise { async function resumedFunction() { await Promise.resolve() return computeStackTrace(new Error()).stack } async function awaitingCaller() { - return await resumedFunction() + return [computeStackTrace(new Error()).stack[0].line, await resumedFunction()] as const } - const frames = await awaitingCaller() - return frames.some((frame) => frame.func?.includes('awaitingCaller')) + const [awaitLine, resumedFrames] = await awaitingCaller() + return resumedFrames.some((frame) => frame.func?.includes('awaitingCaller') && frame.line === awaitLine) } function stackIndexOf(error: unknown, functionName: string): number { @@ -299,13 +300,16 @@ describe('exceptionReplay', () => { await awaitingFunction() const attributes = reportError(error)! - // Once `asyncCaller` resumes, `awaitingFunction` is an async frame located at the `await`, while - // the error's stack has it at the call. Browsers without async stack traces show no caller for - // `asyncCaller`, so its frame can't be confirmed and gets no snapshot. - const capturedFunctions = (await hasAsyncStackTraces()) ? ['asyncCallee', 'asyncCaller'] : ['asyncCallee'] - expect(attributes.frames.map(({ index }) => index)).toEqual( - capturedFunctions.map((functionName) => stackIndexOf(error, functionName)) - ) + const indexes = attributes.frames.map(({ index }) => index) + // `asyncCallee` throws before its first `await`, so its frame is the innermost one. Once + // `asyncCaller` resumes, its stack shows `awaitingFunction` as an async frame located at the + // `await`, while the error's stack has it at the call. Browsers that don't show it on that line, + // or don't show it at all, leave `asyncCaller` without a snapshot, but never put it elsewhere. + if (await hasAsyncCallersOnAwaitLine()) { + expect(indexes).toEqual([0, 1]) + } else { + expect([[0], [0, 1]]).toContain(indexes) + } }) it('should not link a function without callers to an unrelated frame of the same script', async () => { @@ -418,6 +422,15 @@ describe('exceptionReplay', () => { expect(reportError(undefined)).toBeUndefined() }) + it('should not capture thrown objects that are not errors', () => { + // RUM doesn't report the stack of an object that isn't an `Error`, even if it has one + const thrown = { message: 'boom', stack: new Error('boom').stack } + + onCatch('src/throwing.ts;throwingFunction', thrown, undefined, {}) + + expect(reportError(thrown)).toBeUndefined() + }) + it('should ignore thrown values that are not objects', () => { expect(() => onCatch('src/throwing.ts;throwingFunction', 'boom', undefined, {})).not.toThrow() diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 7da5714b48..e316e962be 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -127,8 +127,8 @@ function installCatchHook(): void { */ export function onCatch(functionId: string, error: unknown, self: unknown, args: Record = {}): void { try { - // Captures are kept with the thrown value, which must be an object for that - if (!isObject(error)) { + // RUM only reports the stack of errors, which their snapshots are linked to + if (!isError(error)) { return } @@ -170,11 +170,10 @@ export function onCatch(functionId: string, error: unknown, self: unknown, args: } } -function startCapture(functionId: string, error: object): CapturedException | false { +function startCapture(functionId: string, error: Error): CapturedException | false { const now = performance.now() // The innermost instrumented function is the first one to see the exception - const errorType = isError(error) ? safeReadErrorProperty(error, 'name') : undefined - const fingerprint = `${errorType ?? ''};${functionId}` + const fingerprint = `${safeReadErrorProperty(error, 'name') ?? ''};${functionId}` if (isCoolingDown(fingerprint, now)) { return false @@ -391,7 +390,16 @@ function findFrameIndex( const ASYNC_FRAME_PREFIX = /^async[ *]/ function isSameLocation(a: StackFrame, b: StackFrame): boolean { - return a.url === b.url && a.line === b.line && (a.column === b.column || isAsyncFrame(a) || isAsyncFrame(b)) + if (a.url !== b.url || a.line !== b.line) { + return false + } + if (a.column === b.column) { + return true + } + // Without the column, the line could hold several functions, as in a minified bundle + const aName = getFunctionName(a) + const bName = getFunctionName(b) + return (isAsyncFrame(a) || isAsyncFrame(b)) && (aName === undefined || bName === undefined || aName === bName) } function isAsyncFrame(frame: StackFrame): boolean { diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts index 20b893a3d0..b7540b5b78 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -16,11 +16,16 @@ describe('exceptionReplayPlugin', () => { let eventCollectedHook: EventCollectedHook let batchAdd: jasmine.Spy - function initPlugin({ isSessionTracked = true, rumStarted = true } = {}) { + function initPlugin({ + isSessionTracked = true, + rumStarted = true, + trackingConsent, + }: { isSessionTracked?: boolean; rumStarted?: boolean; trackingConsent?: string } = {}) { const registerAssembleEventHook = jasmine.createSpy('registerAssembleEventHook') const registerEventCollectedHook = jasmine.createSpy('registerEventCollectedHook') const plugin = exceptionReplayPlugin() plugin.onInit({ + initConfiguration: { trackingConsent }, publicApi: { getInternalContext: () => (isSessionTracked ? {} : undefined) }, registerAssembleEventHook, registerEventCollectedHook, @@ -129,10 +134,18 @@ describe('exceptionReplayPlugin', () => { expect(assemble('error', error)).not.toBe(SKIPPED) }) + it('should not capture errors thrown before RUM starts while tracking consent is not granted', () => { + initPlugin({ rumStarted: false, trackingConsent: 'not-granted' }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toBe(SKIPPED) + }) + it('should not start with a RUM Browser SDK that lacks the event collected hook', () => { const displaySpy = spyOn(display, 'warn') exceptionReplayPlugin().onInit({ + initConfiguration: {}, publicApi: { getInternalContext: () => ({}) }, registerAssembleEventHook: jasmine.createSpy('registerAssembleEventHook'), }) diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts index c89b2e0deb..fe24021b87 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -26,6 +26,7 @@ type AssembleEventHook = (params: EventHookParams) => ExceptionReplayEventAttrib type EventCollectedHook = (params: EventHookParams) => void interface ExceptionReplayPluginOnInitOptions { + initConfiguration: { trackingConsent?: string } publicApi: { getInternalContext: () => object | undefined } registerAssembleEventHook: (callback: AssembleEventHook) => unknown // Missing from RUM Browser SDK versions older than this plugin @@ -51,22 +52,24 @@ export interface ExceptionReplayPlugin { * Tracking can show them on the error's stack frames. * * Exception Replay only starts once the plugin is registered and `DD_DEBUGGER.init()` is called. It - * doesn't capture anything in sessions that RUM doesn't track. + * doesn't capture anything in sessions that RUM doesn't track, or before tracking consent is granted. */ export function exceptionReplayPlugin(): ExceptionReplayPlugin { let rumStarted = false return { name: 'exception-replay', - onInit({ publicApi, registerAssembleEventHook, registerEventCollectedHook }) { + onInit({ initConfiguration, publicApi, registerAssembleEventHook, registerEventCollectedHook }) { if (!registerEventCollectedHook) { display.warn('Exception Replay requires a version of the RUM Browser SDK that matches the Live Debugger SDK.') return } // Until RUM starts, its session isn't known yet, and RUM reports the errors it buffered once - // it starts, so they're captured - registerExceptionReplayPlugin(() => !rumStarted || publicApi.getInternalContext() !== undefined) + // it starts, so they're captured, unless RUM is waiting for tracking consent + registerExceptionReplayPlugin(() => + rumStarted ? publicApi.getInternalContext() !== undefined : initConfiguration.trackingConsent !== 'not-granted' + ) registerAssembleEventHook(({ eventType, domainContext }) => { if (eventType !== 'error') { From d74d6a0e89d65cb8c33be8526543e4cd6431157b Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Tue, 3 Nov 2026 12:42:19 +0000 Subject: [PATCH 09/22] =?UTF-8?q?=E2=9C=A8=20[DEBUG-6444]=20Add=20Exceptio?= =?UTF-8?q?n=20Replay=20to=20RUM=20from=20DD=5FDEBUGGER.init()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Customers no longer pass a plugin to DD_RUM.init(), so the Live Debugger SDK doesn't have to load before RUM is initialized. DD_DEBUGGER.init() adds the Exception Replay plugin with DD_RUM.addPlugin() once the RUM Browser SDK has loaded, including with the async loading snippet. It warns if that version of RUM can't add plugins after init. - Remove exceptionReplayPlugin() from the public API. - Update the README, and the e2e tests, which no longer have to start RUM from DD_DEBUGGER.onReady(). Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-debugger/README.md | 15 +--- .../src/domain/exceptionReplayPlugin.spec.ts | 68 ++++++++++++++++++- .../src/domain/exceptionReplayPlugin.ts | 35 +++++++++- .../browser-debugger/src/entries/main.spec.ts | 8 ++- packages/browser-debugger/src/entries/main.ts | 26 +------ test/e2e/scenario/debugger.scenario.ts | 25 +------ 6 files changed, 109 insertions(+), 68 deletions(-) diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index 280d8f55ee..b0db07f0b2 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -49,21 +49,10 @@ When the [RUM Browser SDK][4] is loaded on the page, the first hit of each probe ## Exception Replay -Exception Replay captures the arguments and `this` of the instrumented functions an error passes through, and shows them on the error's stack frames in Error Tracking, without adding probes. It requires the [RUM Browser SDK][4]: +Exception Replay captures the arguments and `this` of the instrumented functions an error passes through, and shows them on the error's stack frames in Error Tracking, without adding probes. It requires the [RUM Browser SDK][4], at the same version as the Live Debugger SDK: 1. Build your application with the Live Debugger build plugin's [`exceptionReplay`][8] option. -2. Register the Exception Replay plugin when initializing the RUM Browser SDK: - - ```js - import { datadogRum } from '@datadog/browser-rum' - import { datadogDebugger } from '@datadog/browser-debugger' - - datadogRum.init({ - // ... - plugins: [datadogDebugger.exceptionReplayPlugin()], - }) - ``` - +2. Load the RUM Browser SDK, or its async loading snippet, before you call `DD_DEBUGGER.init()`. With npm, importing `@datadog/browser-rum` is enough. You don't need to change your RUM configuration: `DD_DEBUGGER.init()` adds Exception Replay to the RUM Browser SDK, whether or not RUM is already initialized. 3. Initialize the Live Debugger SDK as shown in [Usage](#usage). It must send to the same Datadog site and organization as the RUM Browser SDK, or Error Tracking can't find the snapshots of RUM errors. The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track, or before tracking consent is granted. Snapshots are linked to frames by their position in `error.stack`, so a `beforeSend` that removes or reorders frames there can show them on the wrong frames. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts index b7540b5b78..71ae8617eb 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -1,11 +1,12 @@ import { SKIPPED } from '@datadog/js-core/assembly' import { registerCleanupTask } from '@datadog/browser-core/test' -import type { RumPlugin, RumPluginOnInitOptions } from '@datadog/browser-rum-core' +import type { RumPlugin, RumPluginOnInitOptions, RumPublicApi } from '@datadog/browser-rum-core' import type { BrowserWindow } from '../entries/main' import { initDebuggerTransport, resetDebuggerTransport } from './api' import { display } from './display' import { onCatch, resetExceptionReplay, startExceptionReplay } from './exceptionReplay' -import { exceptionReplayPlugin } from './exceptionReplayPlugin' +import type { RumGlobal } from './exceptionReplayPlugin' +import { addExceptionReplayPluginToRum, exceptionReplayPlugin } from './exceptionReplayPlugin' import { clearProbes } from './probes' type AssembleHook = Parameters[0] @@ -167,3 +168,66 @@ describe('exceptionReplayPlugin', () => { expect(assemble('action', error)).toBe(SKIPPED) }) }) + +describe('addExceptionReplayPluginToRum', () => { + const rumWindow = window as { DD_RUM?: RumGlobal } + + beforeEach(() => { + const originalRum = rumWindow.DD_RUM + delete rumWindow.DD_RUM + + registerCleanupTask(() => { + rumWindow.DD_RUM = originalRum + }) + }) + + it('should be compatible with the RUM Browser SDK public API', () => { + // Fails to compile if the RUM Browser SDK's public API stops matching what the plugin uses + const isCompatible: RumPublicApi extends Required ? true : false = true + + expect(isCompatible).toBeTrue() + }) + + it('should add the plugin to RUM', () => { + const addPlugin = jasmine.createSpy('addPlugin') + rumWindow.DD_RUM = { onReady: (callback) => callback(), addPlugin } + + addExceptionReplayPluginToRum() + + expect(addPlugin).toHaveBeenCalledOnceWith(jasmine.objectContaining({ name: 'exception-replay' })) + }) + + it('should wait for RUM to load when it uses the async loading snippet', () => { + const queuedCallbacks: Array<() => void> = [] + rumWindow.DD_RUM = { + onReady: (callback) => { + queuedCallbacks.push(callback) + }, + } + addExceptionReplayPluginToRum() + + // Like the RUM Browser SDK when it loads: replace the snippet, then run its queued callbacks + const addPlugin = jasmine.createSpy('addPlugin') + rumWindow.DD_RUM = { onReady: (callback) => callback(), addPlugin } + queuedCallbacks.forEach((callback) => callback()) + + expect(addPlugin).toHaveBeenCalledTimes(1) + }) + + it('should warn when the RUM Browser SDK is too old to add plugins after init', () => { + const displaySpy = spyOn(display, 'warn') + rumWindow.DD_RUM = { onReady: (callback) => callback() } + + addExceptionReplayPluginToRum() + + expect(displaySpy).toHaveBeenCalled() + }) + + it('should do nothing without the RUM Browser SDK', () => { + const displaySpy = spyOn(display, 'warn') + + addExceptionReplayPluginToRum() + + expect(displaySpy).not.toHaveBeenCalled() + }) +}) diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts index fe24021b87..8a94ae5b7c 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -1,4 +1,5 @@ import { SKIPPED } from '@datadog/js-core/assembly' +import { globalObject } from '@datadog/js-core/util' import { display } from './display' import { collectExceptionReplay, registerExceptionReplayPlugin, sendExceptionReplay } from './exceptionReplay' @@ -42,6 +43,35 @@ export interface ExceptionReplayPlugin { onRumStart(): void } +export interface RumGlobal { + // The async loading snippet also defines it, and queues the callbacks until the SDK loads + onReady?: (callback: () => void) => void + // Missing from RUM Browser SDK versions older than this plugin + addPlugin?: (plugin: ExceptionReplayPlugin) => void +} + +interface BrowserWindow { + DD_RUM?: RumGlobal +} + +/** + * Add the Exception Replay plugin to the RUM Browser SDK on the page, once it has loaded. Called by + * `DD_DEBUGGER.init()`, so customers don't have to change their RUM configuration. + * + * Does nothing if the RUM Browser SDK isn't on the page, since the Live Debugger SDK also works + * without it. + */ +export function addExceptionReplayPluginToRum(): void { + ;(globalObject as BrowserWindow).DD_RUM?.onReady?.(() => { + const rum = (globalObject as BrowserWindow).DD_RUM + if (!rum?.addPlugin) { + display.warn('Exception Replay requires a version of the RUM Browser SDK that matches the Live Debugger SDK.') + return + } + rum.addPlugin(exceptionReplayPlugin()) + }) +} + /** * Create the Exception Replay plugin for the RUM Browser SDK. * @@ -51,8 +81,9 @@ export interface ExceptionReplayPlugin { * sends them as snapshots once the event passes `beforeSend` and the event rate limits, so Error * Tracking can show them on the error's stack frames. * - * Exception Replay only starts once the plugin is registered and `DD_DEBUGGER.init()` is called. It - * doesn't capture anything in sessions that RUM doesn't track, or before tracking consent is granted. + * Exception Replay only starts once RUM has called the plugin's `onInit` and `DD_DEBUGGER.init()` is + * called. It doesn't capture anything in sessions that RUM doesn't track, or before tracking consent + * is granted. */ export function exceptionReplayPlugin(): ExceptionReplayPlugin { let rumStarted = false diff --git a/packages/browser-debugger/src/entries/main.spec.ts b/packages/browser-debugger/src/entries/main.spec.ts index 9057a8f412..a3c45e870b 100644 --- a/packages/browser-debugger/src/entries/main.spec.ts +++ b/packages/browser-debugger/src/entries/main.spec.ts @@ -4,6 +4,7 @@ import { initDebuggerTransport } from '../domain/api' import { startDeliveryApiPolling } from '../domain/deliveryApi' import { display } from '../domain/display' import { registerExceptionReplayPlugin, resetExceptionReplay, startExceptionReplay } from '../domain/exceptionReplay' +import { addExceptionReplayPluginToRum } from '../domain/exceptionReplayPlugin' import { startDebuggerBatch } from '../transport/startDebuggerBatch' import type { BrowserWindow, DebuggerBuildMetadata, DebuggerInitConfiguration } from './main' import { datadogDebugger } from './main' @@ -38,22 +39,23 @@ describe('datadogDebugger', () => { }) }) - it('should only expose init, exceptionReplayPlugin, version, and onReady', () => { + it('should only expose init, version, and onReady', () => { expect(datadogDebugger).toEqual({ init: jasmine.any(Function), - exceptionReplayPlugin: jasmine.any(Function), version: jasmine.any(String), onReady: jasmine.any(Function), }) }) - it('should start Exception Replay on init', () => { + it('should start Exception Replay and add its plugin to RUM on init', () => { mockInitDependencies() const startExceptionReplaySpy = replaceMockableWithSpy(startExceptionReplay) + const addExceptionReplayPluginToRumSpy = replaceMockableWithSpy(addExceptionReplayPluginToRum) datadogDebugger.init(INIT_CONFIGURATION) expect(startExceptionReplaySpy).toHaveBeenCalled() + expect(addExceptionReplayPluginToRumSpy).toHaveBeenCalled() }) it('should install the Exception Replay catch hook on init once the plugin is registered', () => { diff --git a/packages/browser-debugger/src/entries/main.ts b/packages/browser-debugger/src/entries/main.ts index d82437817d..5122f88b1a 100644 --- a/packages/browser-debugger/src/entries/main.ts +++ b/packages/browser-debugger/src/entries/main.ts @@ -15,13 +15,10 @@ import { startDeliveryApiPolling } from '../domain/deliveryApi' import { display } from '../domain/display' import type { onCatch } from '../domain/exceptionReplay' import { startExceptionReplay } from '../domain/exceptionReplay' -import { exceptionReplayPlugin } from '../domain/exceptionReplayPlugin' -import type { ExceptionReplayPlugin } from '../domain/exceptionReplayPlugin' +import { addExceptionReplayPluginToRum } from '../domain/exceptionReplayPlugin' import { getProbes } from '../domain/probes' import { startDebuggerBatch } from '../transport/startDebuggerBatch' -export type { ExceptionReplayPlugin } - export interface DebuggerBuildMetadata { version?: string service?: string @@ -179,25 +176,6 @@ export interface DatadogDebugger extends PublicApi { * ``` */ init: (initConfiguration: DebuggerInitConfiguration) => void - - /** - * Create the Exception Replay plugin for the RUM Browser SDK. Register it with - * `DD_RUM.init({ plugins: [...] })` to capture the arguments of the instrumented functions an - * error passes through, and show them on the error's stack frames in Error Tracking. - * - * Requires an application built with the Live Debugger build plugin's `exceptionReplay` option. - * Exception Replay starts once the plugin is registered and `init()` is called. - * - * @category Exception Replay - * @example - * ```ts - * datadogRum.init({ - * // ... - * plugins: [datadogDebugger.exceptionReplayPlugin()], - * }) - * ``` - */ - exceptionReplayPlugin: () => ExceptionReplayPlugin } export interface BrowserWindow { @@ -259,6 +237,7 @@ function makeDebuggerPublicApi(): DatadogDebugger { debuggerGlobal.$dd_throw = onThrow debuggerGlobal.$dd_probes = getProbes mockable(startExceptionReplay)() + mockable(addExceptionReplayPluginToRum)() mockable(startDeliveryApiPolling)({ service: resolvedConfiguration.service, @@ -272,7 +251,6 @@ function makeDebuggerPublicApi(): DatadogDebugger { maxUnreachableDuration: resolvedConfiguration.maxUnreachableDuration, }) }, - exceptionReplayPlugin, }) } diff --git a/test/e2e/scenario/debugger.scenario.ts b/test/e2e/scenario/debugger.scenario.ts index 5074f3aaca..cdc670cb57 100644 --- a/test/e2e/scenario/debugger.scenario.ts +++ b/test/e2e/scenario/debugger.scenario.ts @@ -675,17 +675,6 @@ test.describe('debugger', () => { createTest('link Exception Replay snapshots to the RUM error event') .withRum() - .withRumInit((configuration) => { - // The debugger is loaded after RUM, so wait for it to create the plugin - const initRum = () => { - window.DD_RUM!.init({ ...configuration, plugins: [(window as any).DD_DEBUGGER.exceptionReplayPlugin()] }) - } - if ((window as any).DD_DEBUGGER) { - ;(window as any).DD_DEBUGGER.onReady(initRum) - } else { - document.addEventListener('DOMContentLoaded', initRum) - } - }) .withDebugger() .withBody(EXCEPTION_REPLAY_BODY) .run(async ({ intakeRegistry, flushEvents, page }) => { @@ -736,19 +725,7 @@ test.describe('debugger', () => { createTest('do not send Exception Replay snapshots for errors dismissed by beforeSend') .withRum() .withRumInit((configuration) => { - // The debugger is loaded after RUM, so wait for it to create the plugin - const initRum = () => { - window.DD_RUM!.init({ - ...configuration, - plugins: [(window as any).DD_DEBUGGER.exceptionReplayPlugin()], - beforeSend: (event) => event.type !== 'error', - }) - } - if ((window as any).DD_DEBUGGER) { - ;(window as any).DD_DEBUGGER.onReady(initRum) - } else { - document.addEventListener('DOMContentLoaded', initRum) - } + window.DD_RUM!.init({ ...configuration, beforeSend: (event) => event.type !== 'error' }) }) .withDebugger() .withBody(EXCEPTION_REPLAY_BODY) From 42ab5911ddbf86332158c1ac29708948e0edf5ce Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Tue, 3 Nov 2026 13:28:23 +0000 Subject: [PATCH 10/22] =?UTF-8?q?=F0=9F=94=92=20[DEBUG-6444]=20Honor=20tra?= =?UTF-8?q?cking=20consent=20set=20before=20init()=20in=20Exception=20Repl?= =?UTF-8?q?ay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before RUM started, Exception Replay only checked the trackingConsent init option. It missed consent denied with setTrackingConsent() before init(), which overrides that option, and so captured arguments while consent was denied. - RUM gives plugins isTrackingConsentGranted(), which reads the current consent, however it was set. - Exception Replay uses it until RUM starts, and stays off with a RUM version that lacks it. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplayPlugin.spec.ts | 23 +++++++++++++++---- .../src/domain/exceptionReplayPlugin.ts | 8 +++---- .../src/boot/preStartRum.spec.ts | 16 ++++++++++++- .../browser-rum-core/src/boot/preStartRum.ts | 1 + .../browser-rum-core/src/domain/plugins.ts | 5 ++++ 5 files changed, 43 insertions(+), 10 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts index 71ae8617eb..4cac5ba264 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -20,14 +20,14 @@ describe('exceptionReplayPlugin', () => { function initPlugin({ isSessionTracked = true, rumStarted = true, - trackingConsent, - }: { isSessionTracked?: boolean; rumStarted?: boolean; trackingConsent?: string } = {}) { + isTrackingConsentGranted = true, + }: { isSessionTracked?: boolean; rumStarted?: boolean; isTrackingConsentGranted?: boolean } = {}) { const registerAssembleEventHook = jasmine.createSpy('registerAssembleEventHook') const registerEventCollectedHook = jasmine.createSpy('registerEventCollectedHook') const plugin = exceptionReplayPlugin() plugin.onInit({ - initConfiguration: { trackingConsent }, publicApi: { getInternalContext: () => (isSessionTracked ? {} : undefined) }, + isTrackingConsentGranted: () => isTrackingConsentGranted, registerAssembleEventHook, registerEventCollectedHook, }) @@ -136,19 +136,32 @@ describe('exceptionReplayPlugin', () => { }) it('should not capture errors thrown before RUM starts while tracking consent is not granted', () => { - initPlugin({ rumStarted: false, trackingConsent: 'not-granted' }) + initPlugin({ rumStarted: false, isTrackingConsentGranted: false }) const error = catchError(throwingFunction) expect(assemble('error', error)).toBe(SKIPPED) }) + it('should not start with a RUM Browser SDK that does not tell whether tracking consent is granted', () => { + const displaySpy = spyOn(display, 'warn') + + exceptionReplayPlugin().onInit({ + publicApi: { getInternalContext: () => ({}) }, + registerAssembleEventHook: jasmine.createSpy('registerAssembleEventHook'), + registerEventCollectedHook: jasmine.createSpy('registerEventCollectedHook'), + }) + + expect(displaySpy).toHaveBeenCalled() + expect((window as BrowserWindow).$dd_catch).toBeUndefined() + }) + it('should not start with a RUM Browser SDK that lacks the event collected hook', () => { const displaySpy = spyOn(display, 'warn') exceptionReplayPlugin().onInit({ - initConfiguration: {}, publicApi: { getInternalContext: () => ({}) }, registerAssembleEventHook: jasmine.createSpy('registerAssembleEventHook'), + isTrackingConsentGranted: () => true, }) expect(displaySpy).toHaveBeenCalled() diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts index 8a94ae5b7c..b3bdae997c 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -27,11 +27,11 @@ type AssembleEventHook = (params: EventHookParams) => ExceptionReplayEventAttrib type EventCollectedHook = (params: EventHookParams) => void interface ExceptionReplayPluginOnInitOptions { - initConfiguration: { trackingConsent?: string } publicApi: { getInternalContext: () => object | undefined } registerAssembleEventHook: (callback: AssembleEventHook) => unknown // Missing from RUM Browser SDK versions older than this plugin registerEventCollectedHook?: (callback: EventCollectedHook) => unknown + isTrackingConsentGranted?: () => boolean } /** @@ -90,8 +90,8 @@ export function exceptionReplayPlugin(): ExceptionReplayPlugin { return { name: 'exception-replay', - onInit({ initConfiguration, publicApi, registerAssembleEventHook, registerEventCollectedHook }) { - if (!registerEventCollectedHook) { + onInit({ publicApi, registerAssembleEventHook, registerEventCollectedHook, isTrackingConsentGranted }) { + if (!registerEventCollectedHook || !isTrackingConsentGranted) { display.warn('Exception Replay requires a version of the RUM Browser SDK that matches the Live Debugger SDK.') return } @@ -99,7 +99,7 @@ export function exceptionReplayPlugin(): ExceptionReplayPlugin { // Until RUM starts, its session isn't known yet, and RUM reports the errors it buffered once // it starts, so they're captured, unless RUM is waiting for tracking consent registerExceptionReplayPlugin(() => - rumStarted ? publicApi.getInternalContext() !== undefined : initConfiguration.trackingConsent !== 'not-granted' + rumStarted ? publicApi.getInternalContext() !== undefined : isTrackingConsentGranted() ) registerAssembleEventHook(({ eventType, domainContext }) => { diff --git a/packages/browser-rum-core/src/boot/preStartRum.spec.ts b/packages/browser-rum-core/src/boot/preStartRum.spec.ts index 0b3ccc07d2..2617b54141 100644 --- a/packages/browser-rum-core/src/boot/preStartRum.spec.ts +++ b/packages/browser-rum-core/src/boot/preStartRum.spec.ts @@ -28,7 +28,7 @@ import { import type { RumInitConfiguration } from '../domain/configuration' import type { ViewOptions } from '../domain/view/trackViews' import { ActionType, VitalType } from '../rawRumEvent.types' -import type { RumPlugin } from '../domain/plugins' +import type { RumPlugin, RumPluginOnInitOptions } from '../domain/plugins' import type { AssembleHookParams } from '../domain/hooks' import type { ManualAction } from '../domain/action/trackManualActions' import type { RumPublicApi, RumPublicApiOptions, Strategy } from './rumPublicApi' @@ -616,6 +616,20 @@ describe('preStartRum', () => { }) describe('plugins', () => { + it('tells plugins whether tracking consent is granted, including when it was set before init()', () => { + const plugin = { name: 'a', onInit: jasmine.createSpy() } + const trackingConsentState = createTrackingConsentState() + const { strategy } = createPreStartStrategyWithDefaults({ trackingConsentState }) + + trackingConsentState.update(TrackingConsent.NOT_GRANTED) + strategy.init({ ...DEFAULT_INIT_CONFIGURATION, plugins: [plugin] }, PUBLIC_API) + const { isTrackingConsentGranted } = plugin.onInit.calls.mostRecent().args[0] as RumPluginOnInitOptions + expect(isTrackingConsentGranted()).toBeFalse() + + trackingConsentState.update(TrackingConsent.GRANTED) + expect(isTrackingConsentGranted()).toBeTrue() + }) + it('calls the onInit method on provided plugins', () => { const plugin = { name: 'a', onInit: jasmine.createSpy() } const { strategy } = createPreStartStrategyWithDefaults() diff --git a/packages/browser-rum-core/src/boot/preStartRum.ts b/packages/browser-rum-core/src/boot/preStartRum.ts index 6aa777bf41..ed55c1e714 100644 --- a/packages/browser-rum-core/src/boot/preStartRum.ts +++ b/packages/browser-rum-core/src/boot/preStartRum.ts @@ -369,6 +369,7 @@ export function createPreStartStrategy( publicApi, registerAssembleEventHook: hooks.assembleEvent.register, registerEventCollectedHook: hooks.eventCollected.register, + isTrackingConsentGranted: trackingConsentState.isGranted, } const shouldContinue = callPluginsOnInit(initConfiguration.plugins, onInitOptions) diff --git a/packages/browser-rum-core/src/domain/plugins.ts b/packages/browser-rum-core/src/domain/plugins.ts index aeaa29bda4..6a4a968b7f 100644 --- a/packages/browser-rum-core/src/domain/plugins.ts +++ b/packages/browser-rum-core/src/domain/plugins.ts @@ -24,6 +24,11 @@ export interface RumPluginOnInitOptions { * an event only if the event itself is sent. */ registerEventCollectedHook: EventCollectedHook['register'] + /** + * Whether tracking consent is granted, whether it was set with the `trackingConsent` init option + * or with `setTrackingConsent()`, including before init(). RUM doesn't start until it is. + */ + isTrackingConsentGranted: () => boolean } /** From 91457f9737a0207d8ab51abb7d1d0ef96e9622b7 Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Tue, 3 Nov 2026 14:46:12 +0100 Subject: [PATCH 11/22] =?UTF-8?q?=F0=9F=91=8C=20[DEBUG-6444]=20Don't=20lin?= =?UTF-8?q?k=20an=20unnamed=20function=20to=20a=20named=20frame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A function without callers was matched to a frame of the same script that came earlier in the file whenever one of the two had no function name. An anonymous function that caught an error created by a named function of the same script was then linked to that function's frame. A frame with a name and one without are now from different functions. Two unnamed functions of the same script can still be mistaken for each other. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplay.spec.ts | 24 +++++++++++++++++++ .../src/domain/exceptionReplay.ts | 8 ++++--- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 7674173c82..cf0adbad19 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -338,6 +338,30 @@ describe('exceptionReplay', () => { expect(reportError(error)).toBeUndefined() }) + it('should not link an unnamed function without callers to a named frame of the same script', async () => { + function rejectLater() { + return new Promise((_, reject) => { + setTimeout(function timerCallback() { + reject(new Error('boom')) + }) + }) + } + + // An anonymous function defined after `timerCallback`, with no callers once it resumes + const error = await new Promise((resolve) => { + ;(async () => { + try { + await rejectLater() + } catch (e) { + onCatch('src/async.ts;', e, undefined, {}) + throw e + } + })().catch(resolve) + }) + + expect(reportError(error)).toBeUndefined() + }) + it('should not send snapshots for exceptions that are not reported', () => { catchError(() => callingFunction(1, 2)) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index e316e962be..9196ec4db6 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -406,12 +406,14 @@ function isAsyncFrame(frame: StackFrame): boolean { return frame.func !== undefined && ASYNC_FRAME_PREFIX.test(frame.func) } -// Compares function names when both frames have one. Otherwise, the frame from the error's stack must -// come first: it's where the function threw or called a callee, before reaching its catch block. +// Compares function names, so a frame with a name and one without are from different functions. +// When neither has one, the frame from the error's stack must come first: it's where the function +// threw or called a callee, before reaching its catch block. Two unnamed functions of the same script +// can still be mistaken for each other. function isSameFunction(errorFrame: StackFrame, functionFrame: StackFrame): boolean { const errorFunction = getFunctionName(errorFrame) const functionName = getFunctionName(functionFrame) - if (errorFunction !== undefined && functionName !== undefined) { + if (errorFunction !== undefined || functionName !== undefined) { return errorFunction === functionName } return ( From 2a5333196873b085721ffbfea9780cef6c7d4ccf Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Wed, 4 Nov 2026 11:13:56 +0000 Subject: [PATCH 12/22] =?UTF-8?q?=E2=9C=85=20[DEBUG-6444]=20Probe=20async?= =?UTF-8?q?=20callers=20after=20a=20rejected=20await=20in=20the=20Exceptio?= =?UTF-8?q?n=20Replay=20spec?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The async callee spec failed on Chrome 80 and Edge 80 on BrowserStack. V8 8.0 only adds async frames to a stack when the function resumed from an `await` that fulfilled. V8 8.1 (Chrome 81) also handles an `await` that rejected. `asyncCaller` resumes from a rejected `await`, so on Chromium 80 its stack has no callers and it gets no snapshot. The probe resumed from a fulfilled `await`, so it still reported that the browser shows the caller. Resume the probe from a rejected `await`, like the scenario it guards. Environment: Datadog workspace Co-Authored-By: Claude Sonnet 5.5 --- .../src/domain/exceptionReplay.spec.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index cf0adbad19..d5a39fd894 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -106,12 +106,17 @@ describe('exceptionReplay', () => { return attributes } - // Whether, once an async function resumes, its stack shows the function awaiting it on the line - // of its `await` + // Whether, once an async function resumes from an `await` that rejects, its stack shows the + // function awaiting it on the line of its `await`. Chrome and Edge 80 (V8 8.0) only show it after + // an `await` that fulfills. async function hasAsyncCallersOnAwaitLine(): Promise { async function resumedFunction() { - await Promise.resolve() - return computeStackTrace(new Error()).stack + try { + await Promise.reject(new Error()) + return [] + } catch { + return computeStackTrace(new Error()).stack + } } async function awaitingCaller() { return [computeStackTrace(new Error()).stack[0].line, await resumedFunction()] as const From 0f9cbd3f3e2733e5dcb3655b4bf288ba82027a6a Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Wed, 4 Nov 2026 11:14:05 +0000 Subject: [PATCH 13/22] =?UTF-8?q?=F0=9F=91=8C=20[DEBUG-6444]=20Call=20ever?= =?UTF-8?q?y=20eventCollected=20callback,=20even=20after=20one=20returns?= =?UTF-8?q?=20DISCARDED?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The `eventCollected` hook reused the assemble hooks' `Hook` type. Its `register()` accepted callbacks that return `DISCARDED`, and `trigger()` stopped at the first one, while RUM still sent the event. A plugin registered after one that returned `DISCARDED` never saw the event. For Exception Replay, the error event would link to snapshots that were never sent. Give the hook its own type, backed by an `Observable`, that calls every callback and ignores what they return. Environment: Datadog workspace Co-Authored-By: Claude Sonnet 5.5 --- .../src/domain/assembly.spec.ts | 14 ++++++++++- packages/browser-rum-core/src/domain/hooks.ts | 23 +++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/packages/browser-rum-core/src/domain/assembly.spec.ts b/packages/browser-rum-core/src/domain/assembly.spec.ts index 1302c87e85..efd8732622 100644 --- a/packages/browser-rum-core/src/domain/assembly.spec.ts +++ b/packages/browser-rum-core/src/domain/assembly.spec.ts @@ -1,6 +1,6 @@ import { ONE_MINUTE, relativeToClocks } from '@datadog/js-core/time' import type { TimeStamp, ClocksState, RelativeTime } from '@datadog/js-core/time' -import { SKIPPED } from '@datadog/js-core/assembly' +import { DISCARDED, SKIPPED } from '@datadog/js-core/assembly' import type { SessionManager } from '@datadog/browser-core' import { display, startGlobalContext, startTabContext } from '@datadog/browser-core' import type { Clock } from '@datadog/browser-core/test' @@ -823,6 +823,18 @@ describe('rum assembly', () => { expect(calls).toEqual(['eventCollected', 'RUM_EVENT_COLLECTED']) }) + it('calls every callback, even after one returns DISCARDED', () => { + const { lifeCycle, hooks, serverRumEvents } = setupAssemblyTestWithDefaults() + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(() => DISCARDED) + hooks.eventCollected.register(eventCollectedSpy) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(eventCollectedSpy).toHaveBeenCalledTimes(1) + expect(serverRumEvents.length).toBe(1) + }) + it('is not triggered for events dismissed by beforeSend', () => { const { lifeCycle, hooks } = setupAssemblyTestWithDefaults({ partialConfiguration: { beforeSend: () => false }, diff --git a/packages/browser-rum-core/src/domain/hooks.ts b/packages/browser-rum-core/src/domain/hooks.ts index 6864e0389c..12657f9993 100644 --- a/packages/browser-rum-core/src/domain/hooks.ts +++ b/packages/browser-rum-core/src/domain/hooks.ts @@ -2,6 +2,7 @@ import type { Duration, RelativeTime } from '@datadog/js-core/time' import type { TelemetryEvent } from '@datadog/browser-core' import { createHook } from '@datadog/js-core/assembly' import type { Hook } from '@datadog/js-core/assembly' +import { Observable } from '@datadog/js-core/util' import type { RecursivePartial } from '@datadog/js-core/util' import type { RumEvent } from '../rumEvent.types' import type { AssembledRumEvent, RawRumEvent } from '../rawRumEvent.types' @@ -37,7 +38,12 @@ export interface EventCollectedHookParams { readonly domainContext: RumEventDomainContext } -export type EventCollectedHook = Hook +// Unlike the assemble hooks, callbacks can't discard the event, which is about to be sent, so every +// callback is called, whatever the others return. +export interface EventCollectedHook { + register(this: void, callback: (params: EventCollectedHookParams) => void): { unregister: () => void } + trigger(this: void, params: EventCollectedHookParams): void +} export interface Hooks { assembleEventDefaults: AssembleHook @@ -51,6 +57,19 @@ export function createHooks(): Hooks { assembleEventDefaults: createHook(), assembleTelemetry: createHook(), assembleEvent: createHook(), - eventCollected: createHook(), + eventCollected: createEventCollectedHook(), + } +} + +function createEventCollectedHook(): EventCollectedHook { + const observable = new Observable() + return { + register(callback) { + const { unsubscribe } = observable.subscribe(callback) + return { unregister: unsubscribe } + }, + trigger(params) { + observable.notify(params) + }, } } From 9780b46fa3c65c07ca5255471b122d89fbaabe67 Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 11:10:46 +0000 Subject: [PATCH 14/22] =?UTF-8?q?=F0=9F=90=9B=20[DEBUG-6444]=20Recognize?= =?UTF-8?q?=20anonymous=20async=20callers=20in=20Exception=20Replay=20fram?= =?UTF-8?q?e=20matching?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After an `await`, Chrome shows an anonymous async caller as `at async :line:col`, which `computeStackTrace` parses as a function named `async`. `ASYNC_FRAME_PREFIX` required a space or `*` after `async`, so that frame wasn't treated as an async frame, and its `await` column was compared against the call's column in the error's stack. The function it called then got no snapshot, as in an `async () => { await f() }` callback. Unit tests now run with Vitest, where the spec's own test callback is such an anonymous async caller, which surfaced this in the "awaiting a callee that throws before its first await" spec. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-debugger/src/domain/exceptionReplay.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 9196ec4db6..c90a3e2734 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -386,8 +386,9 @@ function findFrameIndex( } // After an `await`, the stack shows a caller as an async frame located at the `await` instead of the -// call, as in `async main` (Chrome) or `async*main` (Firefox), so only its line can be compared. -const ASYNC_FRAME_PREFIX = /^async[ *]/ +// call, as in `async main` (Chrome) or `async*main` (Firefox), so only its line can be compared. An +// anonymous caller is just `async` in Chrome. +const ASYNC_FRAME_PREFIX = /^async(?:[ *]|$)/ function isSameLocation(a: StackFrame, b: StackFrame): boolean { if (a.url !== b.url || a.line !== b.line) { From c2f61655b4203eedec8070d17a5265640a5b1736 Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 11:18:56 +0000 Subject: [PATCH 15/22] =?UTF-8?q?=F0=9F=94=92=20[DEBUG-6444]=20Recheck=20t?= =?UTF-8?q?racking=20before=20capturing=20each=20Exception=20Replay=20fram?= =?UTF-8?q?e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only the first frame of an exception checked whether RUM tracks the session. Frames captured later, as the exception propagated or was rethrown after tracking consent was withdrawn, were still captured. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplay.spec.ts | 19 +++++++++++++++++++ .../src/domain/exceptionReplay.ts | 5 +++++ 2 files changed, 24 insertions(+) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index d5a39fd894..8d2fcee479 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -418,6 +418,25 @@ describe('exceptionReplay', () => { expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() }) + it('should stop capturing frames once RUM stops tracking the session', () => { + let tracked = true + resetExceptionReplay() + registerExceptionReplayPlugin(() => tracked) + startExceptionReplay() + + function withdrawingFunction() { + try { + throwingFunction(1) + } catch (e) { + tracked = false + onCatch('src/withdrawing.ts;withdrawingFunction', e, undefined, {}) + throw e + } + } + + expect(reportError(catchError(withdrawingFunction))!.frames.length).toBe(1) + }) + it('should reuse the same snapshots when an error is reported twice', () => { const error = catchError(() => callingFunction(1, 2)) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index c90a3e2734..21cabff6fe 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -142,6 +142,11 @@ export function onCatch(functionId: string, error: unknown, self: unknown, args: return } + // Tracking can stop while the exception propagates, or before it's rethrown + if (!isSessionTracked()) { + return + } + const start = performance.now() const budgetMs = refillCaptureBudget(start) if (budgetMs <= 0) { From c9e06370deb940d7a9d23bc1a0818450f61cac3a Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 11:29:07 +0000 Subject: [PATCH 16/22] =?UTF-8?q?=F0=9F=94=92=20[DEBUG-6444]=20Keep=20chec?= =?UTF-8?q?king=20tracking=20consent=20after=20RUM=20starts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Once RUM started, Exception Replay only checked that RUM had a session. The event bridge's session stub stays tracked when tracking consent is withdrawn, so WebViews kept capturing. Consent is now checked too. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplayPlugin.spec.ts | 8 ++++++++ .../browser-debugger/src/domain/exceptionReplayPlugin.ts | 7 ++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts index 4cac5ba264..acf8fdf2b6 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -142,6 +142,14 @@ describe('exceptionReplayPlugin', () => { expect(assemble('error', error)).toBe(SKIPPED) }) + it('should not capture errors once tracking consent is withdrawn, even if the session is still tracked', () => { + // The event bridge's session stays tracked when consent is withdrawn + initPlugin({ isTrackingConsentGranted: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toBe(SKIPPED) + }) + it('should not start with a RUM Browser SDK that does not tell whether tracking consent is granted', () => { const displaySpy = spyOn(display, 'warn') diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts index b3bdae997c..8318786c70 100644 --- a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -97,9 +97,10 @@ export function exceptionReplayPlugin(): ExceptionReplayPlugin { } // Until RUM starts, its session isn't known yet, and RUM reports the errors it buffered once - // it starts, so they're captured, unless RUM is waiting for tracking consent - registerExceptionReplayPlugin(() => - rumStarted ? publicApi.getInternalContext() !== undefined : isTrackingConsentGranted() + // it starts, so they're captured, unless RUM is waiting for tracking consent. Consent is + // still checked once RUM starts: the event bridge's session outlives it. + registerExceptionReplayPlugin( + () => isTrackingConsentGranted() && (!rumStarted || publicApi.getInternalContext() !== undefined) ) registerAssembleEventHook(({ eventType, domainContext }) => { From 0f26b63745d7714377f4d3f6356d9b04039fc89e Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 11:29:08 +0000 Subject: [PATCH 17/22] =?UTF-8?q?=F0=9F=90=9B=20[DEBUG-6444]=20Compare=20f?= =?UTF-8?q?unction=20names=20when=20matching=20Exception=20Replay=20frames?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A function with callers was matched to an error stack frame by URL and callers only. Two functions called from the same call site have the same callers, so a snapshot could be linked to the frame of another function in the same script. Their names now have to match when both frames have one. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplay.spec.ts | 24 +++++++++++++++++++ .../src/domain/exceptionReplay.ts | 10 ++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 8d2fcee479..245cfde3ab 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -437,6 +437,30 @@ describe('exceptionReplay', () => { expect(reportError(catchError(withdrawingFunction))!.frames.length).toBe(1) }) + it('should not link a frame to another function called from the same call site', () => { + let created: Error | undefined + function createError() { + created = new Error('boom') + } + function rethrowError() { + try { + throw created! + } catch (e) { + onCatch('src/rethrow.ts;rethrowError', e, undefined, {}) + throw e + } + } + + const error = catchError(() => { + // Both functions have the same callers + for (const fn of [createError, rethrowError]) { + fn() + } + }) + + expect(reportError(error)).toBeUndefined() + }) + it('should reuse the same snapshots when an error is reported twice', () => { const error = catchError(() => callingFunction(1, 2)) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 21cabff6fe..78c6275e91 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -345,7 +345,8 @@ function recordReport(fingerprint: string): void { * `callFrames` is the stack captured in `onCatch`: `onCatch` itself, then the instrumented * function, then its callers. The callers are still paused at the call sites they were at when the * exception was thrown, so they're the frames that follow the function in the error's stack. The - * function's own frame differs, as it has moved to its catch block, so only its URL is compared. + * function's own frame differs, as it has moved to its catch block, so only its URL is compared, and + * its name when both frames have one: functions called from the same call site have the same callers. * * Both stacks can be truncated (V8 keeps 10 frames by default), so only the callers present in both * are compared. A function without callers has nothing to compare, so its frame in the error's stack @@ -363,9 +364,14 @@ function findFrameIndex( return } + const functionName = getFunctionName(functionFrame) const callers = callFrames.slice(2) for (let index = fromIndex; index < errorFrames.length; index++) { - if (errorFrames[index].url !== functionFrame.url) { + const errorFunctionName = getFunctionName(errorFrames[index]) + if ( + errorFrames[index].url !== functionFrame.url || + (errorFunctionName !== undefined && functionName !== undefined && errorFunctionName !== functionName) + ) { continue } From 5463124b1753c10c155f9c01bc4ff13399e39848 Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 11:37:02 +0000 Subject: [PATCH 18/22] =?UTF-8?q?=F0=9F=94=92=20[DEBUG-6444]=20Discard=20E?= =?UTF-8?q?xception=20Replay=20captures=20reported=20without=20tracking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The event bridge's session stays tracked when tracking consent is withdrawn, so RUM can still report an error captured before. Its snapshots, which the debugger transport sends over HTTP rather than through the bridge, were still linked and sent. When RUM assembles or collects the error event while tracking is off, the error's captures are now discarded, so they're never sent, even if the error is reported again once tracking resumes. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplay.spec.ts | 28 ++++++++++++++++++- .../src/domain/exceptionReplay.ts | 13 +++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 245cfde3ab..638ea58419 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -434,7 +434,33 @@ describe('exceptionReplay', () => { } } - expect(reportError(catchError(withdrawingFunction))!.frames.length).toBe(1) + const error = catchError(withdrawingFunction) + tracked = true + + expect(reportError(error)!.frames.length).toBe(1) + }) + + it('should discard the snapshots of errors reported once RUM stops tracking the session', () => { + let tracked = true + resetExceptionReplay() + registerExceptionReplayPlugin(() => tracked) + startExceptionReplay() + const assembledError = catchError(() => throwingFunction(1)) + const reassembledError = catchError(() => throwingFunction(2)) + const capturedError = catchError(() => throwingFunction(3)) + expect(collectExceptionReplay(assembledError)).toBeDefined() + expect(collectExceptionReplay(reassembledError)).toBeDefined() + + tracked = false + expect(collectExceptionReplay(reassembledError)).toBeUndefined() + expect(collectExceptionReplay(capturedError)).toBeUndefined() + sendExceptionReplay(assembledError) + + tracked = true + sendExceptionReplay(reassembledError) + expect(reportError(assembledError)).toBeUndefined() + expect(reportError(capturedError)).toBeUndefined() + expect(mockBatchAdd).not.toHaveBeenCalled() }) it('should not link a frame to another function called from the same call site', () => { diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 78c6275e91..11a8703607 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -231,6 +231,13 @@ export function collectExceptionReplay(error: unknown): ExceptionReplayAttribute return } + // Tracking can stop after the exception is captured, and the event bridge's session stays + // tracked, so RUM can still report the error. Its captures are then discarded. + if (!isSessionTracked()) { + capturedExceptions.set(error, false) + return + } + // The error was assembled before but RUM dropped it, and another exception with the same // fingerprint has been reported since if (exception.pendingSnapshots && isCoolingDown(exception.fingerprint, performance.now())) { @@ -262,6 +269,12 @@ export function sendExceptionReplay(error: unknown): void { return } + // Tracking can also stop once the event is assembled, as in `beforeSend` + if (!isSessionTracked()) { + capturedExceptions.set(error, false) + return + } + const snapshots = exception.pendingSnapshots exception.pendingSnapshots = undefined for (const snapshot of snapshots) { From 04c70a039443b1844d98ffcdb09a37d22c88a8e5 Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 12:00:04 +0000 Subject: [PATCH 19/22] =?UTF-8?q?=F0=9F=91=B7=20[DEBUG-6444]=20Pin=20@data?= =?UTF-8?q?dog/rum-events-format=20to=20the=20updated=20schema=20PR=20head?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DataDog/rum-events-format#458 now includes master, so the generated types match both its Exception Replay fields and the newer master fields main uses. The regenerated types are unchanged. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- yarn.lock | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index c8c3149a60..1d2cddd4cd 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "woke": "scripts/cli woke" }, "devDependencies": { - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=070d92554ad397af100972184177404adbb36a7f", + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4", "@eslint/js": "10.0.1", "@microsoft/api-extractor": "7.60.1", "@oxc-project/runtime": "0.152.0", diff --git a/yarn.lock b/yarn.lock index 40a838853d..d47e7de5b8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -750,10 +750,10 @@ __metadata: languageName: unknown linkType: soft -"@datadog/rum-events-format@DataDog/rum-events-format#commit=070d92554ad397af100972184177404adbb36a7f": +"@datadog/rum-events-format@DataDog/rum-events-format#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4": version: 0.0.0 - resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=070d92554ad397af100972184177404adbb36a7f" - checksum: 10c0/8dd4bca8b783e2b75518f8dcc1080c497848f745294a51944357efdfcbc6a6a31bf4d53721103f994bd7f789660435f113e44fcc2ddefe5522ac945314756eb0 + resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4" + checksum: 10c0/8e8ff2092f23e5389a403c3ff9b61f5ff3a348e9bd366ce62709421b53906b5b5292fac00798a743ed29e43301d9e528a63d87edebd139ca0fe12547bd1581ee languageName: node linkType: hard @@ -6333,7 +6333,7 @@ __metadata: version: 0.0.0-use.local resolution: "browser-sdk@workspace:." dependencies: - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=070d92554ad397af100972184177404adbb36a7f" + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4" "@eslint/js": "npm:10.0.1" "@microsoft/api-extractor": "npm:7.60.1" "@oxc-project/runtime": "npm:0.152.0" From 950b92da465686e5e5b97c4e5ce46e15a06231c1 Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 12:43:10 +0000 Subject: [PATCH 20/22] =?UTF-8?q?=F0=9F=90=9B=20[DEBUG-6444]=20Ignore=20ex?= =?UTF-8?q?ceptions=20thrown=20while=20capturing=20an=20Exception=20Replay?= =?UTF-8?q?=20frame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Capturing a frame reads its arguments and `this`, whose getters can run instrumented code. If that code threw, $dd_catch re-entered before the current frame was stored or its time charged, so nested captures could get past the three-frame limit and charge overlapping time to the capture budget. Such exceptions come from the capture itself, so $dd_catch now ignores them. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- .../src/domain/exceptionReplay.spec.ts | 37 +++++++++++++++++++ .../src/domain/exceptionReplay.ts | 9 +++++ 2 files changed, 46 insertions(+) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts index 638ea58419..07c3df3b42 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -520,6 +520,43 @@ describe('exceptionReplay', () => { expect(reportError(undefined)).toBeUndefined() }) + it('should ignore exceptions thrown by instrumented code that runs while capturing a frame', () => { + let nestedArgumentReads = 0 + function rethrowingFunction(error: unknown) { + try { + throw error + } catch (e) { + onCatch('src/rethrowing.ts;rethrowingFunction', e, undefined, { + get value() { + nestedArgumentReads++ + return 1 + }, + }) + throw e + } + } + function throwingFunctionWithGetter() { + const error = new Error('boom') + try { + throw error + } catch (e) { + // Capturing this argument runs instrumented code that throws the same error again + onCatch('src/getter.ts;throwingFunctionWithGetter', e, undefined, { + get value() { + catchError(() => rethrowingFunction(error)) + return 1 + }, + }) + throw e + } + } + + const error = catchError(throwingFunctionWithGetter) + + expect(nestedArgumentReads).toBe(0) + expect(reportError(error)!.frames.length).toBe(1) + }) + it('should not capture thrown objects that are not errors', () => { // RUM doesn't report the stack of an object that isn't an `Error`, even if it has one const thrown = { message: 'boom', stack: new Error('boom').stack } diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts index 11a8703607..362d9969df 100644 --- a/packages/browser-debugger/src/domain/exceptionReplay.ts +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -66,6 +66,7 @@ let captureBudgetMs = CAPTURE_BUDGET_MS_PER_SECOND let captureBudgetUpdatedAt = -Infinity let pluginRegistered = false let debuggerStarted = false +let catchInProgress = false let isSessionTracked: () => boolean = () => true /** @@ -126,6 +127,12 @@ function installCatchHook(): void { * @param args - Function arguments */ export function onCatch(functionId: string, error: unknown, self: unknown, args: Record = {}): void { + // Capturing reads application values, whose getters can run instrumented code that throws. Those + // exceptions come from the capture itself, so they're ignored. + if (catchInProgress) { + return + } + catchInProgress = true try { // RUM only reports the stack of errors, which their snapshots are linked to if (!isError(error)) { @@ -172,6 +179,8 @@ export function onCatch(functionId: string, error: unknown, self: unknown, args: } } catch (e) { monitorError(e) + } finally { + catchInProgress = false } } From 11c9298749c9b75a5b00945e9840af29d8c04ac2 Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 14:42:06 +0000 Subject: [PATCH 21/22] =?UTF-8?q?=F0=9F=91=B7=20[DEBUG-6444]=20Pin=20@data?= =?UTF-8?q?dog/rum-events-format=20to=20its=20Exception=20Replay=20merge?= =?UTF-8?q?=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DataDog/rum-events-format#458 is merged. The regenerated types are unchanged. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- package.json | 2 +- yarn.lock | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 1d2cddd4cd..8578f96af1 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "woke": "scripts/cli woke" }, "devDependencies": { - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4", + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=79c264a627e2ebba7182e5d088aad84124de23c8", "@eslint/js": "10.0.1", "@microsoft/api-extractor": "7.60.1", "@oxc-project/runtime": "0.152.0", diff --git a/yarn.lock b/yarn.lock index d47e7de5b8..3371963ec0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -750,9 +750,9 @@ __metadata: languageName: unknown linkType: soft -"@datadog/rum-events-format@DataDog/rum-events-format#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4": +"@datadog/rum-events-format@DataDog/rum-events-format#commit=79c264a627e2ebba7182e5d088aad84124de23c8": version: 0.0.0 - resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4" + resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=79c264a627e2ebba7182e5d088aad84124de23c8" checksum: 10c0/8e8ff2092f23e5389a403c3ff9b61f5ff3a348e9bd366ce62709421b53906b5b5292fac00798a743ed29e43301d9e528a63d87edebd139ca0fe12547bd1581ee languageName: node linkType: hard @@ -6333,7 +6333,7 @@ __metadata: version: 0.0.0-use.local resolution: "browser-sdk@workspace:." dependencies: - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=8fa83bc429d461bd9e8a28c1d10b71af2038dac4" + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=79c264a627e2ebba7182e5d088aad84124de23c8" "@eslint/js": "npm:10.0.1" "@microsoft/api-extractor": "npm:7.60.1" "@oxc-project/runtime": "npm:0.152.0" From 04feaab5d5595e6e9d89216d45f46ac23486e1cd Mon Sep 17 00:00:00 2001 From: "thomas.watson" Date: Thu, 19 Nov 2026 19:12:45 +0000 Subject: [PATCH 22/22] =?UTF-8?q?=F0=9F=91=8C=20[DEBUG-6444]=20Drop=20the?= =?UTF-8?q?=20unused=20event=20from=20the=20eventCollected=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Its only consumer, the Exception Replay plugin, reads the event type and domain context only. Environment: Datadog workspace Co-Authored-By: Claude Opus 5.5 --- packages/browser-rum-core/src/domain/assembly.spec.ts | 5 ++--- packages/browser-rum-core/src/domain/assembly.ts | 2 +- packages/browser-rum-core/src/domain/hooks.ts | 3 +-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/packages/browser-rum-core/src/domain/assembly.spec.ts b/packages/browser-rum-core/src/domain/assembly.spec.ts index efd8732622..db1ce8b96e 100644 --- a/packages/browser-rum-core/src/domain/assembly.spec.ts +++ b/packages/browser-rum-core/src/domain/assembly.spec.ts @@ -792,8 +792,8 @@ describe('rum assembly', () => { }) describe('eventCollected hook', () => { - it('is triggered with the collected event and its domain context', () => { - const { lifeCycle, hooks, serverRumEvents } = setupAssemblyTestWithDefaults() + it('is triggered with the event type and domain context', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults() const eventCollectedSpy = jasmine.createSpy('eventCollected') hooks.eventCollected.register(eventCollectedSpy) const domainContext = { error: new Error('boom') } as RumEventDomainContext @@ -802,7 +802,6 @@ describe('rum assembly', () => { expect(eventCollectedSpy).toHaveBeenCalledOnceWith({ eventType: RumEventType.ERROR, - event: serverRumEvents[0], domainContext, }) }) diff --git a/packages/browser-rum-core/src/domain/assembly.ts b/packages/browser-rum-core/src/domain/assembly.ts index d263033bcf..e12f75a620 100644 --- a/packages/browser-rum-core/src/domain/assembly.ts +++ b/packages/browser-rum-core/src/domain/assembly.ts @@ -102,7 +102,7 @@ export function startRumAssembly( if (isEmptyObject(serverRumEvent.context!)) { delete serverRumEvent.context } - hooks.eventCollected.trigger({ eventType: serverRumEvent.type, event: serverRumEvent, domainContext }) + hooks.eventCollected.trigger({ eventType: serverRumEvent.type, domainContext }) lifeCycle.notify(LifeCycleEventType.RUM_EVENT_COLLECTED, serverRumEvent) } } diff --git a/packages/browser-rum-core/src/domain/hooks.ts b/packages/browser-rum-core/src/domain/hooks.ts index 12657f9993..4abc896b4d 100644 --- a/packages/browser-rum-core/src/domain/hooks.ts +++ b/packages/browser-rum-core/src/domain/hooks.ts @@ -5,7 +5,7 @@ import type { Hook } from '@datadog/js-core/assembly' import { Observable } from '@datadog/js-core/util' import type { RecursivePartial } from '@datadog/js-core/util' import type { RumEvent } from '../rumEvent.types' -import type { AssembledRumEvent, RawRumEvent } from '../rawRumEvent.types' +import type { RawRumEvent } from '../rawRumEvent.types' import type { RumEventDomainContext } from '../domainContext.types' // Define a partial RUM event type. @@ -34,7 +34,6 @@ export type AssembleTelemetryHook = Hook<{ startTime: RelativeTime }, DefaultTel // through the DOM types it holds, which the declaration build rejects as excessively deep. export interface EventCollectedHookParams { readonly eventType: RumEvent['type'] - readonly event: Readonly readonly domainContext: RumEventDomainContext }