Skip to content

refactor(rum): Simplify profiling state and lifecycle handling - #5364

Merged
amortemousque merged 8 commits into
mainfrom
amortemousque/simplify-profiling-state
Dec 3, 2026
Merged

amortemousque merged 8 commits into
mainfrom
amortemousque/simplify-profiling-state

Conversation

@amortemousque

@amortemousque amortemousque commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Simplify profiling state and lifecycle handling

Changes

  • Remove internal stop reasons; keep quota diagnostics in the profiling context.
  • Centralize subscriptions and state checks, with cleanup and unload guards preventing unintended restarts.
  • Replace discard with the positive assemble option and extend lifecycle regression coverage.

Test instructions

Run the targeted unit tests:

yarn test:unit packages/browser-rum/src/domain/profiling/datadogProfiler.spec.ts packages/browser-rum/src/boot/profilerApi.spec.ts

Expected: 57 tests pass. Coverage includes visibility pause/resume, session expiry and renewal, quota denial, stale quota responses, and controller cleanup followed by an explicit restart.

Validation completed locally: 57 Chromium unit tests, source type-checking (tsconfig.default.json), lint on changed files, and formatting. The local dependency setup required invoking Vitest through yarn node with a temporary cache configuration. Full-repository type-checking is blocked by missing release-please dependencies in the release scripts. Manual/staging testing was not performed.

Checklist

  • Tested locally
  • Tested on staging
  • Added unit tests for this change.
  • Added e2e/integration tests for this change.
  • Updated documentation and/or relevant AGENTS.md file

@amortemousque
amortemousque requested a review from a team as a code owner December 1, 2026 13:55
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-03T15:56:11.487180Z 2c00f5c New commits
🔒 Security Review ✅ Completed 2026-12-03T15:57:32.523219Z 2c00f5c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Bundles Sizes Evolution

📦 Bundle Name Base Size Local Size 𝚫 𝚫% Status
Rum Salesforce 195.38 KiB 195.38 KiB 0 B 0.00% ✅
Rum 195.35 KiB 195.35 KiB 0 B 0.00% ✅
Rum Salesforce Profiler 7.93 KiB 7.81 KiB -117 B -1.44% ✅
Rum Profiler 7.93 KiB 7.81 KiB -117 B -1.44% ✅
Rum Salesforce Recorder 32.80 KiB 32.80 KiB 0 B 0.00% ✅
Rum Recorder 32.80 KiB 32.80 KiB 0 B 0.00% ✅
Logs 60.22 KiB 60.22 KiB 0 B 0.00% ✅
Rum Slim 150.75 KiB 150.75 KiB 0 B 0.00% ✅
Worker 24.23 KiB 24.23 KiB 0 B 0.00% ✅
Rum Shopify 226.90 KiB 226.90 KiB 0 B 0.00% ✅
Rum Shopify Profiler 7.93 KiB 7.81 KiB -117 B -1.44% ✅
Rum Shopify Recorder 4.85 KiB 4.85 KiB 0 B 0.00% ✅
Early Collection 309 B 309 B 0 B 0.00% ✅

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 74.07%
• Overall Coverage: 78.06% (-0.01%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: e1b11dd | Docs | View more details | Give us feedback!

@datadog-datadog-prod-us1 datadog-datadog-prod-us1 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The lifecycle changes yielded no reportable defects in static review. Runtime verification remains incomplete because the required Playwright Chromium executable is missing.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit 43a4438

@thomasbertet thomasbertet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice simplification overall — unsubscribing the lifeCycle listeners in stop() and avoiding duplicate window listeners on start() are good improvements, and the normal lifecycle (visibility pause/resume, session expiry/renewal, quota checks, and cleanup) behaves the same as before.

A few findings inline, most notably a behavioral change on startup failures followed by SESSION_RENEWED.

} as any)

setVisibilityState('visible')
window.dispatchEvent(createNewEvent('beforeunload'))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure why you added these new dispatched event ? Seems unrelated to the test 🤔

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the extra beforeunload dispatches from both existing tests in e1b11dd and restored the visibility test's original name. The paused-profiler unload behavior is covered by its dedicated regression test. All 46 profiling unit tests pass.

Comment on lines +63 to +67
addEventListener(window, DOM_EVENT.BEFORE_UNLOAD, () => {
if (instance.state !== 'stopped') {
startNextProfilerInstance()
}
}).stop,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (pre-existing behavior): instance.state !== 'stopped' also matches 'paused'. When paused, pauseProfilerInstance() has already stopped and assembled the running profiler, so there is nothing left to flush — yet beforeunload will spin up a brand-new Profiler instance on a hidden tab that is unloading.

Changing this guard to if (instance.state === 'running') would avoid creating a new profiler when already paused (unless starting one on beforeunload while hidden is intentional).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5961cae: the beforeunload guard now checks instance.state === 'running'. Added a regression test verifying that unloading while paused keeps the profiler paused, creates no new instance, and sends no additional profile. All 46 profiling unit tests pass.

Comment on lines +71 to +75
lifeCycle.subscribe(LifeCycleEventType.SESSION_RENEWED, () => {
if (instance.state === 'stopped' && isCurrentSessionSampled()) {
startProfiling()
}
}).unsubscribe

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behavioral change on startup failure: because cleanupTasks are registered before startProfiling(), if startNextProfilerInstance() fails (missing-document-policy-header, unexpected-exception) or throws (not-supported-by-browser), instance remains { state: 'stopped' } while SESSION_RENEWED stays subscribed.

Previously, stateReason remained 'initializing' (even after SESSION_EXPIRED), so SESSION_RENEWED never retried. Now every sampled SESSION_RENEWED calls startProfiling() again:

  • missing-document-policy-header: retries new Profiler(), logs the warning again, and fires another /api/v2/profiling/quota request even though Document-Policy cannot change for the document.
  • unexpected-exception: retries new Profiler() and sends another quota request on each renewal.
  • not-supported-by-browser: throws an uncaught Error inside the SESSION_RENEWED callback (for direct callers of createRumProfiler).

Consider only registering cleanupTasks once startup succeeds (or cleaning them up on startup failure), and adding unit tests covering startup failure + SESSION_RENEWED.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9285451: start() now registers the listeners only after startup succeeds, so an initial failure leaves no SESSION_RENEWED subscription to retry startup. Added a regression test covering constructor failure followed by session expiry and renewal, checking that neither the constructor nor the quota check runs again.

stopRunningProfiler(previousInstance, { discard: reason === 'quota_ko' })
}
if (previousInstance.state === 'running') {
stopRunningProfiler(previousInstance, { assemble: quotaReason === undefined })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deriving assemble from quotaReason === undefined couples the discard decision to telemetry metadata. With the current checkProfilingQuota, result.reason is always a string, so runtime behavior matches today — but if quota_ko ever arrives with reason: undefined (e.g. a mock or future change), assemble silently flips to true and sends the profile despite quota denial.

Passing an explicit option (e.g. stopProfiling({ assemble = true, quotaReason }: { assemble?: boolean; quotaReason?: QuotaReason } = {})) would keep the intent explicit.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 2c00f5c: stopProfiling now receives the full QuotaResult and uses quotaResult?.decision !== 'quota_ko' to control assembly. The reason is only used for profiling context metadata, so a missing reason cannot cause a denied profile to be sent. All 46 profiling unit tests pass.

@amortemousque
amortemousque merged commit c5c09b8 into main Dec 3, 2026
30 checks passed
@amortemousque
amortemousque deleted the amortemousque/simplify-profiling-state branch December 3, 2026 21:14
@dd-octo-sts dd-octo-sts Bot mentioned this pull request Dec 3, 2026
thomasbertet added a commit that referenced this pull request Dec 4, 2026
Reconcile the Web Worker Profiling extension seam with the profiling state
and lifecycle refactor from #5364:

- keep main's simplified start/stop lifecycle (cleanupTasks, QuotaResult,
  no stateReason)
- re-add the ProfilerExtension/ProfilerHost seam: mainThreadId shared with
  profileAssembly, attachExtension, onStart/onStop/onFlush hooks, and the
  stoppedByUser distinction for closePorts
- stopProfiling() semantics: quota_ko discards extensions, stopped-by-user
  closes their ports, session expiry keeps them open for renewal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants