Skip to content

feat: support cross-linking synthetics & apm - #1162

Open
shahzad31 wants to merge 8 commits into
mainfrom
apm-integration
Open

shahzad31 wants to merge 8 commits into
mainfrom
apm-integration

Conversation

@shahzad31

@shahzad31 shahzad31 commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

📋 Summary

Adds cross-linking between Synthetics journey executions and the APM data of the applications they exercise. 🔗 Revives and rebases #595 (originally by @vigneshshanmugam) onto current main, now that the Heartbeat side (elastic/beats#51083) has merged.

For browser journeys, a new APM plugin intercepts requests to the URLs you configure and adds a W3C baggage header that carries the synthetics context, so the traced app's agent can attach it to its APM documents:

  • 🧳 synthetics.trace.id: the per-execution id (equals monitor.check_group)
  • synthetics.monitor.id
  • synthetics.monitor.type
  • synthetics.monitor.location

Our members are appended to any baggage the page already sends. traceparent and tracestate are never touched, so a page that is already instrumented (EDOT RUM, an OTel SDK) stays the owner of its trace and its sampling decision.

The monitor context and trace id come from the ELASTIC_SYNTHETICS_* environment variables injected by Heartbeat (elastic/beats#51083), falling back to the journey's own monitor config when run standalone.

// synthetics.config.ts (local and CI runs)
export default {
  apm: {
    traceUrls: ['**/api/**'], // only these requests get the header
  },
};
# Heartbeat never reads synthetics.config.ts, so monitors it runs take the same
# list as a flag (through synthetics_args). The flag wins over the config file.
npx @elastic/synthetics --apm-trace-urls 'https://app.example.com/**' ...

List only the origins of the apps you trace. Enabling request interception turns off the browser HTTP cache for the journey, and cross-origin requests that carry baggage trigger a CORS preflight the server has to allow.

⚙️ How the cross-link works end to end

  1. Heartbeat spawns the runner with ELASTIC_SYNTHETICS_{TRACE_ID,MONITOR_ID,MONITOR_TYPE,MONITOR_LOCATION} (TRACE_ID == monitor.check_group).
  2. The APM plugin adds baggage to requests matching the trace URLs.
  3. The traced app's APM/OTel agent lifts the baggage onto its transactions/spans.
  4. 🔑 Join key: traces-apm.*.synthetics.trace.id == synthetics.monitor.check_group.

🚚 How the trace URLs reach the runner

Where the monitor runs How to set it
Local or CI run apm.traceUrls in synthetics.config.ts, or --apm-trace-urls
UI or API monitors, Fleet policies synthetics_args: ['--apm-trace-urls', '<url>']
Pushed project monitors ⏳ Not yet. The bundle only contains the journey code and Kibana's project monitor API has no field for it. push warns when apm is set in the config. Tracked in elastic/kibana#304060, with an optional typed Heartbeat setting in elastic/beats#54564.

🛠️ Implementation notes

  • The plugin is browser-only (it routes driver.context), registered through PluginManager for browser drivers only, so API journeys skip it. Re-applied on top of the multi step API runner refactor (feat: multi step api runner #997).
  • Baggage members are joined with , and values are percent-encoded, per the W3C Baggage spec. (An earlier ;-joined form collapsed to the first key on spec-compliant parsers, caught during E2E.)
  • The route handler is bound once so stop() can actually unroute it.
  • The apm block is validated when the config is read, so a bad value fails with a clear message instead of a TypeError when the journey starts.

🚫 Not included

🤖 Agent support (important)

The synthetics.* context only lands on APM docs if the traced app's agent captures W3C baggage:

Agent Captures baggage?
OpenTelemetry SDKs / EDOT ✅ verified end to end with a baggage span processor. The browser SDK is not verified.
Elastic classic Java / .NET / Python / Go ✅ (baggage spec implemented)
Elastic classic RUM (JS) ❌ dropped
Elastic classic Node.js ❌ dropped

For agents that lift baggage, the resulting label naming differs by agent (e.g. OTel/APM Server stores labels.synthetics_trace_id; classic agents prefix with baggage.). The Kibana-side join query must account for this.

✅ Test plan

  • Unit tests for baggage generation and merging, header propagation (including keeping the page's own baggage, traceparent and tracestate), config validation, and the CLI flag end to end with Heartbeat-style env vars (__tests__/plugins/apm.test.ts, __tests__/options.test.ts, __tests__/cli.test.ts)
  • 🧪 Live E2E: OTel-instrumented app (baggage span processor → APM Server → ES) exercised by a browser journey. All four synthetics.* fields land on the APM transaction and synthetics.trace.id matches the injected trace id.
  • 💓 Live E2E with real Heartbeat: built Heartbeat from [Heartbeat] Pass synthetics monitor context for APM cross-linking beats#51083, ran a browser monitor that spawned this runner, and confirmed in a single ES cluster that the synthetics-browser-* docs' monitor.check_group equals the APM docs' labels.synthetics_trace_id (and monitor.location flows from run_from).

Relates to elastic/beats#51083
Closes #265
Supersedes #595

Adds an APM plugin that propagates W3C baggage and tracestate headers on
configured trace URLs so browser journey executions can be cross-linked
with the traced application's APM data.

The monitor context (id, type, location) and per-execution trace id are
read from the ELASTIC_SYNTHETICS_* env vars injected by Heartbeat
(elastic/beats#51083), falling back to the journey's monitor config.

Re-applied on top of the multi step api runner refactor (#997): the APM
plugin is browser-only and is registered via PluginManager only for
browser drivers.

Relates to #595

Co-authored-by: Cursor <cursoragent@cursor.com>
shahzad31 and others added 5 commits July 20, 2026 22:10
Importing from the `../core` barrel created a load-time cycle
(runner.ts -> plugins -> apm -> core -> globals -> runner) that left the
`runner` binding undefined, breaking journey registration. Import
directly from `../core/globals`, which does not pull in the plugins
barrel.

Co-authored-by: Cursor <cursoragent@cursor.com>
The baggage header joined members with ';', but per the W3C Baggage spec
members are separated by ',' (';' delimits per-member properties). Spec
compliant parsers (e.g. OpenTelemetry's W3CBaggagePropagator) therefore
read the whole string as a single member and drop everything after the
first key, so only synthetics.trace.id survived cross-linking.

Join members with ',' and percent-encode values. Verified end-to-end
against an OTel-instrumented app (baggage span processor -> APM Server ->
Elasticsearch): all of synthetics.monitor.id/type/location and
synthetics.trace.id now land as labels on the APM transaction.

Co-authored-by: Cursor <cursoragent@cursor.com>
Bind the route handler once so unroute matches the registered function,
and only set the baggage header when there is synthetics context to share.
@shahzad31
shahzad31 requested a review from a team as a code owner November 6, 2026 08:41
…alidate apm config

- merge our baggage members and es tracestate entry into the headers the
  page already sends instead of replacing them
- round sample rates between 0 and 0.0001 up to 0.0001 per the agent
  sampling spec (was 0.001)
- validate the apm config block with clear errors and only apply it for
  the run command
- document ApmOptions caveats and cover the wiring with tests
lucaslopezf
lucaslopezf previously approved these changes Nov 7, 2026

@lucaslopezf lucaslopezf 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.

lgtm

Comment thread src/options.ts Outdated
}

options.screenshots = cliArgs.screenshots ?? 'on';
options.apm = normalizeApmOptions(config.apm);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

from CC:

apm never reaches Heartbeat-run monitors, where the baggage data exists**

  • Why: options.apm is set only from config.apm in run mode. That has three consequences:

    • Project monitor bundles contain only the bundled journey code (src/push/bundler.ts:71, which runs archive.append(code, …)), not synthetics.config.ts.
    • push mode explicitly drops apm, as the test options.test.ts › is not applied when pushing monitors shows.
    • Inline runs skip reading the config (src/options.ts:68-71).

    There is no CLI flag either. Meanwhile, generateBaggageHeader depends on ELASTIC_SYNTHETICS_TRACE_ID, _MONITOR_TYPE and _LOCATION, which only Heartbeat sets. So the feature works locally, where the baggage holds only synthetics.monitor.id=<journey id>. It is inert in production, where the cross-link would matter. That misses the PR's stated goal ("support cross-linking synthetics & apm").

  • Example: A user adds apm: { traceUrls: ['**/api/**'] } to synthetics.config.ts and runs npx @elastic/synthetics push. The private location runs the monitor and its /api requests carry no baggage or tracestate. Nothing warns the user.

  • Fix: Pick a delivery channel and test it:

    • a CLI flag such as --apm-trace-urls / --apm-sample-rate, which Heartbeat/Kibana can pass through synthetics_args, or
    • pushing apm as part of the monitor config so Heartbeat can forward it.

    At minimum, document the feature as local-only and warn during push when config.apm is set. Confirm with the Heartbeat/Kibana owners (see questions 1–2).

Comment thread src/plugins/apm.ts Outdated
if (baggage) {
headers[BAGGAGE_HEADER] = mergeBaggage(existing[BAGGAGE_HEADER], baggage);
}
route.continue({ headers });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Should we add the await?

Comment thread src/plugins/apm.ts Outdated
const existing = request.headers();
// Merge into whatever the page already sends so the traced app keeps its
// own baggage and other vendors keep their tracestate entries
const headers = {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

should we add traceparent?

- add --apm-trace-urls so monitors run by Heartbeat, which never read
  synthetics.config.ts, can enable the baggage propagation through
  synthetics_args. The flag takes precedence over apm.traceUrls
- warn on push when apm is set in the config, since project monitors do
  not carry it to the location that runs them
- stop injecting tracestate and drop apm.sampleRate: tracestate without a
  traceparent is ignored per the W3C trace context spec, and overriding
  the es entry of a page that already sends traceparent (EDOT RUM, OTel)
  would corrupt that trace's sampling rate
- await route.continue in the handler
- note in the ApmOptions docs that request interception disables the
  browser HTTP cache
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.

[Proposal] Crosslinking Synthetics with APM

2 participants