Skip to content

feat(o11y): add setAttributes and removeAttributes - #865

Open
abelonogov-ld wants to merge 1 commit into
mainfrom
andrey/global-attributes-web
Open

abelonogov-ld wants to merge 1 commit into
mainfrom
andrey/global-attributes-web

Conversation

@abelonogov-ld

@abelonogov-ld abelonogov-ld commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds LDObserve.setAttributes(attributes) / LDObserve.removeAttributes(keys) to the browser SDK (@launchdarkly/o11y, surfaced through @launchdarkly/observability and @launchdarkly/session-replay). This addresses the customer request for app-wide attributes (e.g. UTM parameters) on all telemetry, and matches the RN (#856), Android (#860), iOS (launchdarkly/swift-launchdarkly-observability#290), Flutter (#858), MAUI (#863), Java (#861) and Python (#859) PRs.

  • One in-memory attribute map for the page lifetime, merged by key (immutable snapshot rebuilt only on change). It lives on globalThis under a Symbol.for key so the observability and session-replay bundles, which each bundle their own copy of o11y, share it.
  • Applied to every span via CustomBatchSpanProcessor.onStart (manual, fetch/XHR, error, flag evaluation, track, document load, user interaction), to logs (the launchdarkly.js.log span and its log event), and to every metric data point. Spans take the values current when they start.
  • Precedence: per-call / explicitly set attributes > LD context keys > globals > resource. Globals only fill missing keys.
  • highlight.session_id, session.id and highlight.record are ignored (logged in debug mode), as are invalid attribute values. setAttributes({ k: undefined }) is ignored; use removeAttributes to remove.
  • Calls write straight to the store instead of the pre-init call buffer, so they apply before init or start() with manualStart, including to automatic spans emitted during init. Nothing is persisted; values survive session changes.

README documents the API and how it differs from addSessionProperties.

How did you test this change?

  • New globalAttributes.test.ts (14 tests): merge/remove, reserved keys, invalid values, snapshot immutability, calls before init and with manualStart, the processor path used by automatic spans (values captured at start, later attributes win), manual spans, errors, logs and metrics.
  • Full o11y suite (597 tests), yarn turbo run build test typegen lint for o11y, observability, highlight.run and session-replay, Prettier check, and yarn enforce-size (172.6 kB / 256 kB) pass.

Are there any deployment considerations?

Additive; no behavior change unless the new API is used. Global attributes are added to metric data points, so they increase metric cardinality.


Note

Overview
Adds LDObserve.setAttributes / removeAttributes so apps can attach page-scoped metadata (e.g. tenant, campaign) to all subsequent spans, logs, and metrics, including auto-instrumented telemetry.

A new globalAttributes store merges keys in memory for the page lifetime, shared across observability and session-replay bundles via globalThis. setAttributes / removeAttributes bypass the pre-init call buffer so values apply before init or manualStart. Globals only fill missing keys; explicit span/log/metric attributes and LD context keys win. Reserved keys (highlight.session_id, session.id, highlight.record) and invalid OTel values are dropped.

Wiring: CustomBatchSpanProcessor.onStart applies globals to every span at start; ObserveSDK and the replay Highlight client spread getGlobalAttributes() onto log events and metric data points. README and Observe API types document behavior vs addSessionProperties.

Tests: new globalAttributes.test.ts covers merge/remove, precedence, pre-init usage, and telemetry paths.

Reviewed by Cursor Bugbot for commit bb4b6d7. Bugbot is set up for automated code reviews on this repo. Configure here.

Co-authored-by: Cursor <cursoragent@cursor.com>
vadim-korolik added a commit that referenced this pull request Nov 4, 2026
…ibutes (#877)

<!-- TERMAG_PR_BODY_BEGIN -->
## Demo

A vitest/jsdom harness runs the real `ObserveSDK` with the real span
processor, document-load/location-change/fetch instrumentations and a
real OTel metrics pipeline, all exporting to memory. The page loads at
`/?utm_campaign=spring&utm_source=email&other=x` with
`document.referrer` set to
`https://www.google.com/search?q=me%40mail.com&token=abc#top`. It then
does:

1. two SPA navigations (`/products`, `/checkout`)
2. a fetch, a log, an error and a metric
3. an SPA landing on `/promo?utm_campaign=fall`
4. another log and metric

The demo has three runs: default config with a cross-origin referrer,
default config with a same-origin referrer, and both options off.

-
[Transcript](https://app.termag.ldinfra.net/termag/files/team-o11y/artifacts/sf9-utm-capture/transcript.txt):
exported span, log-event and metric attributes for each run
- [vitest
run](https://app.termag.ldinfra.net/termag/files/team-o11y/artifacts/sf9-utm-capture/vitest-run.txt)
· [harness
source](https://app.termag.ldinfra.net/termag/files/team-o11y/artifacts/sf9-utm-capture/demo.captureQueryParams.test.ts)

Default config, cross-origin referrer (excerpt):

```
documentLoad        {"landing.referrer":"https://www.google.com/search","utm_campaign":"spring","utm_source":"email", ...}
page_view           {"url.full":".../checkout","landing.referrer":"https://www.google.com/search","utm_campaign":"spring","utm_source":"email"}
HTTP GET            {"http.url":"https://api.example.com/cart","landing.referrer":"https://www.google.com/search","utm_campaign":"spring","utm_source":"email"}
page_view           {"url.full":".../promo?utm_campaign=fall","landing.referrer":"https://www.google.com/search","utm_campaign":"fall"}
  log event "promo opened" {"landing.referrer":"https://www.google.com/search","utm_campaign":"fall"}
checkout.views      value=1 {"landing.referrer":"https://www.google.com/search","utm_campaign":"spring","utm_source":"email"}
promo.views         value=1 {"landing.referrer":"https://www.google.com/search","utm_campaign":"fall"}
```

`other` is never captured, and the referrer's query string and fragment
are stripped. On the `/promo` landing, `utm_source` is removed and
`utm_campaign` becomes `fall` (last touch). A same-origin referrer sets
no `landing.referrer`. With both options `false`, none of these
attributes appear.

## What

Two options on the Observe plugin (`ObserveOptions`, exposed through
`@launchdarkly/observability`).

### `captureQueryParams?: string[] | false`

**On by default** with `['utm_source', 'utm_medium', 'utm_campaign',
'utm_term', 'utm_content']`.
- `false` or `[]` turns it off, and a custom list replaces the default.
A trailing `*` matches a prefix (`'utm_*'`).
- At init, the SDK reads `location.search` and sets each listed
parameter that is present as a global attribute named after the
parameter. It uses the #855 `setAttributes` store, so the reserved-key
rules are the same. Empty values are skipped, and for a repeated
parameter the first value wins.
- **Last touch:** when an SPA navigation (`pushState`, `replaceState` or
`popstate`) lands on a URL with any listed parameter, the captured
values are replaced by that URL's values, and previously captured keys
missing from it are removed. A navigation without listed parameters
keeps the current values. The page_view span of the new landing already
carries the new values. Spans that were already started keep their
values, because attributes are stamped at span start.
- **Precedence:** capture only replaces or removes keys whose current
value came from capture. A key the app set with `setAttributes` (before
init or after) is never touched. `removeAttributes` removes a captured
value, and a later landing with that parameter captures it again.
- It works with `manualStart`: the values are present while tracing is
set up (the document load span) and on telemetry buffered before
`start()`. Navigation is tracked from SDK construction.
- The SDK registers its own `PathListener` when constructed, before the
page_view instrumentation's, so last-touch works even when page views
are disabled.

### `captureReferrer?: boolean`

**Default `true`.**
- At init, a non-empty, cross-origin `document.referrer` is set as
`landing.referrer`. Only the origin and path are kept: the query string,
fragment and credentials are stripped.
- A same-origin, empty or unparseable referrer sets nothing.
- The value is not updated on SPA navigation, and `setAttributes` can
override it.
- `landing.` is not a reserved namespace, so the requested name is used
as-is.

### Unchanged

- Everything is kept in memory for the current page load. Nothing is
written to storage or cookies.
- Metrics carry the captured attributes.
- **Privacy:** only listed keys are captured, the default list is
UTM-only, and the referrer is reduced to origin and path. This is stated
in the TSDoc and the README.
- README (`@launchdarkly/observability`): documents both options, last
touch, and a recipe for keeping UTMs across a full page load or an auth
redirect (sessionStorage + `LDObserve.setAttributes` on loads whose URL
has none).
- Not exposed on `@launchdarkly/session-replay` (its `RecordOptions`
doesn't apply global attributes) or on `H.init` (which doesn't construct
`ObserveSDK`).

## Overlap

- #865 (an alternative `setAttributes`, superseded by #855): this PR
builds on #855, which is on `main`. #865 would conflict with
`sdk/observe.ts` if it were revived.
- #729 (sanitize page URLs in telemetry): no file overlap, because #729
edits the old `sdk/highlight-run/` paths. Related: the upstream
`documentLoad` span's raw `http.url` and the page_view `url.full` still
carry the full query string (`other=x` in the demo). That is existing
behaviour and unchanged here; it's what #729 is about.

## Tests

`src/sdk/observe.captureQueryParams.test.ts` has 35 tests.

Capture:
- the default list captured without configuration
- `false` and `[]` disabling capture
- a custom list replacing the default
- the `utm_*` prefix pattern
- unlisted params ignored
- a page load without UTMs capturing nothing
- reserved keys ignored
- `removeAttributes`
- explicit and pre-init `setAttributes` winning
- nothing written to storage or cookies
- values on document load, page views, fetch, log, error and metric
- disabled: no values on telemetry
- `manualStart`

Last touch:
- replace and remove on a new landing
- keep on navigations without listed params
- `replaceState`
- explicit `setAttributes` keys (before or after init) never replaced or
removed
- re-capture after `removeAttributes`
- no tracking when disabled
- the new landing's page_view carries the new values while a span
started before it keeps the old ones

Referrer:
- cross-origin, stripped of query, fragment and credentials
- same-origin
- empty
- unparseable
- `false`
- independent of `captureQueryParams`, not updated on navigation
- `setAttributes` override

Mutation checks: 10 tests fail without the init capture, 6 without last
touch, and 4 without the referrer stripping.

- `yarn workspace @launchdarkly/o11y test`: 46 files, 661 tests passed
- `tsc --noEmit` (`typegen:check`): clean
- `turbo lint` (o11y, observability, session-replay): passed
- `yarn enforce-size`: 173.4 kB brotli (limit 256 kB)
- `prettier --check` on the changed files: clean

Asked by `vkorolik` through `termag ask`; follow up with `termag ask …
--thread cmw1cfqqr4hswpm7w0jzydp0f`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- TERMAG_PR_BODY_END -->

<!-- termag: box=i-00c6025680f887b59 project=repo
ask=cmw1cfqqr4hswpm7w0jzydp0f -->
<sub>Opened from termag</sub>

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> Adds **automatic campaign and landing metadata** to observability
global attributes via two new `ObserveOptions`: **`captureQueryParams`**
(on by default with standard UTM keys, optional prefix patterns like
`utm_*`, disable with `false`/`[]`) and **`captureReferrer`** (default
`true`, sets sanitized cross-origin **`landing.referrer`**).
> 
> Captured query values flow through the existing **`setAttributes`**
store onto spans, logs, errors, and metrics for the page load,
**persisting after SPA navigations** that drop the query string.
**Last-touch** updates captured keys when a navigation lands on a URL
with any listed parameter (replacing/removing prior captured keys);
navigations without listed params leave values unchanged.
**`setAttributes` / pre-init buffered attributes win** over capture;
**`removeAttributes`** can drop captured keys for re-capture later.
> 
> **`PathListener`** is refactored to install a **single shared
`history` wrap** on `window` (reference-counted subscribers, safe
teardown when another wrap sits on top) so multiple SDK instances or
bundles emit **one `locationchange` per navigation**. **`ObserveSDK`**
wires landing capture at construct time, re-attaches the navigation
listener on **`start()`**, and detaches on **`stop()`**.
> 
> New helpers in **`queryParams.ts`**, expanded TSDoc, README sections
(including a sessionStorage recipe for redirects), and broad vitest
coverage for parsing, referrer stripping, telemetry stamping, and
multi-instance behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
40791b8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
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