From 4ac56ba0219ff4855d4489df5408603a219b83fd Mon Sep 17 00:00:00 2001 From: Adam Horodyski Date: Thu, 26 Nov 2026 22:30:37 +0100 Subject: [PATCH 1/2] spec: design metrics as two independent pipelines from one config JS metrics use stock sdk-metrics and export from JS on every platform; native metrics use the native SDK and RNOtel.meter. Both read exportConfig.metrics, and native hands JS its resource and merged metrics config through the initialize result. Nothing crosses the seam per measurement. Also replaces exportConfig.url with one URL per signal (traces, metrics) and shared plus per-signal headers. Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-10-rn-otel-design.md | 307 +++++++++++++++++- 1 file changed, 295 insertions(+), 12 deletions(-) diff --git a/docs/superpowers/specs/2026-11-10-rn-otel-design.md b/docs/superpowers/specs/2026-11-10-rn-otel-design.md index ecdfd39..f1d6612 100644 --- a/docs/superpowers/specs/2026-11-10-rn-otel-design.md +++ b/docs/superpowers/specs/2026-11-10-rn-otel-design.md @@ -39,7 +39,7 @@ nesting**, to a collector — on iOS, Android and web. - React-specific APIs (hooks, providers, `trace()` helpers, `'use trace'`). - Sessions, sampling config, disk buffering, runtime header updates, enable/consent switch. - Cross-platform data-shaping processors (`attributes`, `filter`, `redaction`). -- Logs and metrics signals. Old architecture (New Architecture only). +- Logs. Metrics are designed in §4.6 (proposed, built after v0). Old architecture (New Architecture only). **Anti-goals** (would make this a failure even if it technically works) - A span attached to the **wrong parent** through `await`, promise or timer flows. Losing a @@ -318,16 +318,34 @@ OTel data model. apps without a config plugin; it loses only pre-JS capture. Prior art: §12 P7. - When native init did happen, `startReactNativeSdk({...})` attaches; JS export config is ignored with one warning. -- Returns `{ tracerProvider, forceFlush(), shutdown() }`, the names OTel JS uses on every - provider and SDK. On mobile `shutdown` stops only the JS provider, never the native - singleton. The returned `tracerProvider` is the one registered globally. +- Returns `{ tracerProvider, meterProvider, forceFlush(), shutdown() }`, the names OTel JS + uses on every provider and SDK. On mobile `shutdown` stops only the JS provider, never the + native singleton. The returned providers are the ones registered globally. `forceFlush` + flushes both signals (on mobile the JS meter provider, then native `flush` for spans and + native metrics). *(`meterProvider`: proposed with metrics, §4.6.)* - Missing or invalid config logs one error and returns a no-op handle (as browser-sdk does with `invalidConfig`); it never throws. -- **Endpoint (`exportConfig.url` / native `url`)** means the same on every platform: the - OTLP/HTTP traces endpoint (e.g. `https://collector:4318/v1/traces`), used as given. No path - is appended. +- **Endpoints, one URL per signal (proposed with metrics, §4.6; replaces v0's single + `exportConfig.url`).** `exportConfig.traces.url` and `exportConfig.metrics.url` (natively + `export.traces.url` / `export.metrics.url`) are the OTLP/HTTP endpoints of their signal + (e.g. `https://collector:4318/v1/traces`, `…/v1/metrics`), used as given on every platform. + No path is appended; v0's rule, and what all three upstream HTTP exporters do with an + explicit URL (otel-java `setEndpoint` "include the full HTTP path"; JS `url`; + opentelemetry-swift `endpoint: URL`). + - **A signal is on when its URL is set.** Neither set is the existing "missing config" + case: one error, no-op handle. Traces only, metrics only and both are all valid. + - **Headers:** `exportConfig.headers` go to every signal; `traces.headers` / + `metrics.headers` are merged over them, the signal's value winning on the same key. The + same precedence as OTel's `OTEL_EXPORTER_OTLP_HEADERS` vs + `OTEL_EXPORTER_OTLP__HEADERS`. Why per signal at all: some backends need a header + on one signal only (e.g. a metrics dataset header); one shared map covers the common + case. + - **`metrics.temporalityPreference`**: `'cumulative'` (default) or `'delta'`, applied to JS and native metrics (§4.6.4). + The JS exporter's option name; the declarative config calls it `temporality_preference`. + - v0 is unreleased, so the old `exportConfig.url` is replaced, not aliased. - **Web**: the same call takes exporter options, mirroring `startBrowserSdk`'s option names - (`serviceName`, `serviceVersion`, `resourceAttributes`, `exportConfig: { url, headers }`, + (`serviceName`, `serviceVersion`, `resourceAttributes`, + `exportConfig: { headers, traces: { url, headers }, metrics: { url, headers, temporalityPreference } }`, `instrumentations`, …). - Option names mirror upstream (`startBrowserSdk`, declarative config schema) wherever upstream has a name. Rejected: OTel declarative config YAML (not supported by @@ -341,7 +359,11 @@ Usage, roughly (names are placeholders): // android: MainApplication.onCreate — preferred, native-first RNOtel.start(this) { serviceName = "shop"; serviceVersion = BuildConfig.VERSION_NAME - export { url = "https://collector.example.com:4318/v1/traces"; headers = mapOf("x-api-key" to KEY) } + export { + headers = mapOf("x-api-key" to KEY) + traces { url = "https://collector.example.com:4318/v1/traces" } + metrics { url = "https://collector.example.com:4318/v1/metrics"; temporalityPreference = Temporality.DELTA } + } resourceAttributes = mapOf("deployment.environment.name" to "prod") } ``` @@ -350,7 +372,9 @@ RNOtel.start(this) { // ios: AppDelegate — preferred, native-first RNOtel.start { c in c.serviceName = "shop"; c.serviceVersion = Bundle.main.version - c.export = .init(url: "https://collector.example.com:4318/v1/traces", headers: ["x-api-key": KEY]) + c.export = .init(headers: ["x-api-key": KEY], + traces: .init(url: "https://collector.example.com:4318/v1/traces"), + metrics: .init(url: "https://collector.example.com:4318/v1/metrics", temporalityPreference: .delta)) } ``` @@ -360,11 +384,21 @@ import { startReactNativeSdk } from 'react-native-open-telemetry'; startReactNativeSdk({ // only needed on web, or as the mobile fallback when no native init ran: serviceName: 'shop', - exportConfig: { url: 'https://collector.example.com:4318/v1/traces', headers: { 'x-api-key': KEY } }, + exportConfig: { + headers: { 'x-api-key': KEY }, + traces: { url: 'https://collector.example.com:4318/v1/traces' }, + metrics: { url: 'https://collector.example.com:4318/v1/metrics' }, + }, spanProcessors: [/* stock sdk-trace SpanProcessors, unchanged */], }); ``` +The seam config follows the same shape: `SeamConfig` loses `exportUrl`/`exportHeaders` and +gains `exportHeaders: SeamAttribute[]`, `traces?: SeamSignal`, `metrics?: SeamMetrics` +with `SeamSignal { url: string; headers: SeamAttribute[] }` and `SeamMetrics` the same plus +`delta: boolean` (Nitro needs named interfaces, 4.3). Header +merging happens in each native core (native-first init never passes through JS). + ```js // metro.config.js: installs the context patch before any app module const { withOtel } = require('react-native-open-telemetry/metro'); @@ -382,6 +416,209 @@ module.exports = withOtel(getDefaultConfig(__dirname)); Package name: `react-native-open-telemetry` (subpath `/metro`). Entry function: `startReactNativeSdk`, on web too. +### 4.6 Metrics (proposed, built after v0) + +Status: design only, nothing implemented. The published 0.2 had metrics (JS `sdk-metrics` +over OTLP/HTTP JSON; a separate otel-java `SdkMeterProvider` over gRPC on Android; nothing +on iOS). v0 removed them. This section brings them back with **two independent pipelines +from one config**, each built only from stock OTel types. Upstream versions checked: +otel-java 1.68.0, opentelemetry-swift 2.6.0 (core + exporters), `@opentelemetry/sdk-metrics` +3.1.1 with `@opentelemetry/exporter-metrics-otlp-proto` 0.301.2, spec at `4e01937`. + +Metrics are best effort next to spans (JS background flush, reloads: 4.6.4, 4.6.6). Spans and traces stay the priority. + +#### 4.6.1 Model: JS metrics in JS, native metrics in native +- **JS metrics live in the stock JS SDK on every platform.** `startReactNativeSdk` builds + `MeterProvider` + `PeriodicExportingMetricReader` + `OTLPMetricExporter` + (`exporter-metrics-otlp-proto`) on Android, iOS and web: the same code as web today builds + for spans. JS exports metrics itself; nothing crosses the seam per measurement. +- **Native metrics live in the native SDK.** The native core builds `SdkMeterProvider` + (otel-java) / `MeterProviderSdk` (opentelemetry-swift) + `PeriodicMetricReader` + + `OtlpHttpMetricExporter` next to the tracer provider, with the same resource. App native + code gets meters from `RNOtel.meter`. +- **One config.** Both pipelines read `exportConfig.metrics` (4.4). On mobile the config + usually lives in native init, so native hands JS what JS needs (4.6.3). +- **No shared instruments.** A JS instrument and a native instrument are never the same + instrument. To increment a native metric from JS, the app calls its own native module, + which records on its `RNOtel.meter` instrument (the same pattern as `doWork` in 4.3). +- **No idle traffic.** All three readers skip the export when there is nothing to send: + otel-java `PeriodicMetricReader` (`metricData.isEmpty()`, line 290), opentelemetry-swift + `PeriodicMetricReaderSdk` (`metricData.isEmpty`, line 91), JS + `PeriodicExportingMetricReader` (`scopeMetrics.length === 0`, line 197). An app that + records only in JS never sends a native metrics request, and the reverse. + +```mermaid +flowchart LR + subgraph mobile["Mobile"] + jsapp["JS: metrics.getMeter(...)"] --> jsmp["sdk-metrics MeterProvider
PeriodicExportingMetricReader"] --> jsexp["OTLPMetricExporter (proto, JS)"] + nat["app native code: RNOtel.meter(...)"] --> nmp["native MeterProvider
PeriodicMetricReader"] --> nexp["OtlpHttpMetricExporter"] + core["native core"] -. "initialize(): resource + metrics config" .-> jsmp + end + subgraph web["Web"] + jsw["JS: metrics.getMeter(...)"] --> wmp["sdk-metrics MeterProvider"] --> wexp["OTLPMetricExporter (proto)"] + end + jsexp --> col[("collector /v1/metrics")] + nexp --> col + wexp --> col +``` + +App code, the same file on every platform: + +```ts +// index.js: first line, before the app is imported (4.6.6) +startReactNativeSdk(); + +// src/cart.ts +const adds = metrics.getMeter('shop.cart').createCounter('cart.adds', { unit: '{item}' }); +adds.add(1, { screen: 'checkout' }); +``` + +```kotlin +// app native code +val taps = RNOtel.meter("shop.native").counterBuilder("native.taps").build() +taps.add(1) +``` + +#### 4.6.2 Single writer +The metrics data model (Stable): *"All metric data streams within OTLP MUST have one logical +writer"* +([data-model.md#single-writer](https://github.com/open-telemetry/opentelemetry-specification/blob/4e01937ed7d734e5f4feb8ffba89f1b6b960ab59/specification/metrics/data-model.md#single-writer)). +A stream is identified by resource, scope, metric name (+ kind, unit) and attributes. JS and +native share the resource, so each side must write its own scopes: +- **Rule (documented):** don't create an instrument with the same name in the same meter + scope from JS and from native. If an app does, the backend sees two writers of one stream. + We don't detect it. +- **Multiple JS runtimes** each build their own `MeterProvider`, so the same JS instrument in + two runtimes is two writers. Rare; documented, as per-runtime attributes are out of scope + (4.3). +- **A fleet** is many writers too: every install sends the same resource. 0.2 had the same + problem. See open question 1. + +#### 4.6.3 What crosses the seam +Nothing per measurement. Only `initialize`'s result grows, so a JS-only pipeline can export +with native's identity and config: + +```ts +// illustrative additions to Otel.nitro.ts +interface SeamResource { attributes: SeamAttribute[]; schemaUrl?: string } +interface SeamInitResult { + alreadyInitialized: boolean; testMode: boolean; error?: string; + resource: SeamResource; // native's resource, exactly as native exports it + metrics?: SeamMetrics; // 4.4's struct: url, headers (already merged), delta; absent = metrics off +} +``` + +- **Resource:** JS builds its `Resource` from these attributes and adds nothing, so JS and + native metrics, and all spans, carry one resource (4.3 "Resource identity"). Its + `telemetry.sdk.*` values are otel-java's or opentelemetry-swift's, as on JS spans. +- **Metrics config:** native merges the headers (4.4) and returns the result. JS passes `url` + and `headers` to `OTLPMetricExporter` and maps `delta` to + `temporalityPreference: AggregationTemporalityPreference.DELTA`. +- **The same path for both init routes.** With JS-fallback init, JS sends its config to + native and reads it back from the result; there is one code path, not two. +- **Trade-off: the metrics headers reach JS memory.** With native-first init they used to + stay native. The per-signal headers of 4.4 let an app give metrics a key of its own. + +#### 4.6.4 JS pipeline +| Setting | Choice | Why | +|---|---|---| +| Packages | `@opentelemetry/sdk-metrics` 3.1.1, `@opentelemetry/exporter-metrics-otlp-proto` 0.301.2, pinned exactly | Same release train as the pinned `sdk-trace` 3.1.1 and `exporter-trace-otlp-proto` 0.301.2. | +| Temporality | **cumulative** default; `delta` option | The spec default. `delta` is JS `DELTA`, otel-java and Swift `deltaPreferred()`: the same mapping on all three (up-down counters stay cumulative). | +| Export interval | **60 s**, not configurable yet | The JS default. Test mode: 120 s, so only `forceFlush` exports (9.6). | +| Background | mobile: an `AppState` `'background'` listener calls `meterProvider.forceFlush()` | Best effort: the JS thread and its `fetch` can be suspended on iOS before the request finishes. Accepted; spans keep the native background task. | +| Views, cardinality | stock `sdk-metrics` defaults, views not exposed | Upstream. Add a views option when someone asks. | +| Global | registered with `metrics.setGlobalMeterProvider` and returned as `handle.meterProvider` | As for the tracer provider. | + +- **Every JS instrument works**, including observables and `addBatchObservableCallback`: + callbacks run in JS at collection time; nothing calls JS from native. +- **Mobile and web are the same code.** Web reads the config from `startReactNativeSdk`; + mobile reads it from the `initialize` result. +- **Build check:** that `exporter-metrics-otlp-proto` resolves its browser entry under Metro + and Hermes and exports with `fetch` (RN has no `sendBeacon`). 0.2 shipped the JSON variant + in RN. + +#### 4.6.5 Native pipeline +Both cores build it next to the tracer provider when `metrics.url` is set: + +| Setting | Choice | Why | +|---|---|---| +| Exporter | `OtlpHttpMetricExporter`, URL as given, merged headers, built lazily | The same code path as the span exporter: otel-java's span and metric exporters wrap the same internal `HttpExporterBuilder` (retry on by default); Swift's wrap `OtlpHttpExporterBase` (no retry; `requeueOnFailure: true`). | +| Temporality | from config, as in 4.6.4 | One mapping on all three platforms. | +| Export interval | **60 s** | otel-java's default. Swift's `PeriodicMetricReaderBuilder` defaults to **1 s**, so iOS sets it. Test mode: 120 s. | +| Background flush | the existing hooks also call `meterProvider.forceFlush()` | Android: queued on the reader's worker, never joined on the main thread. iOS: blocks up to the export timeout, so it runs on the global queue inside the existing background task. | +| Exemplars | **off** (otel-java `ExemplarFilter.alwaysOff()`, Swift `AlwaysOffFilter()`) | Swift's default is `AlwaysOn` (an exemplar on every point). Off on both keeps them alike; v1 option in §10. | +| Cardinality, views | SDK defaults, not exposed | otel-java: 2,000 attribute sets, then an overflow series. Swift: a hard 2,000, then new sets are dropped. Documented. | + +opentelemetry-swift 2.6 has everything this needs: all sync and observable instruments with +long and double, scope version and `schemaUrl`, bucket advice, resource, temporality selector, +exemplar filter, and the OTLP/HTTP protobuf exporter. Its gaps, documented and not patched: +the 1 s default interval, the cardinality drop, `AlwaysOn` exemplars, a cumulative start time +taken from `Date()` instead of the builder clock, and no `ScopeMetrics.schemaUrl` in the +encoder (the same gap as for spans, §9.1). + +Native public API, next to `RNOtel.tracer`, same no-op rule: + +| | Android (`com.callstack.otel.RNOtel`) | iOS (`RNOtel`) | +|---|---|---| +| Meter on the native provider (no-op before init or without `metrics.url`) | `RNOtel.meter(name, version?)` → `io.opentelemetry.api.metrics.Meter` | `RNOtel.meter(name, version:)` → `any Meter` | + +Builder check: that `any Meter` (an associated-type protocol in opentelemetry-swift 2.6) is +usable from app Swift code without casts; otherwise return the concrete `MeterSdk` with a +`DefaultMeter` fallback. + +#### 4.6.6 Lifecycle and failures +- **Before `startReactNativeSdk`:** `metrics.getMeter()` returns the API's no-op meter and its + instruments stay no-op forever: `@opentelemetry/api` has no proxy meter provider (unlike + tracing's `ProxyTracerProvider`). The same on web; upstream behavior. Documented: + `startReactNativeSdk()` is the first line of `index.js`. +- **Native code before native init:** `RNOtel.meter` returns the no-op meter, as + `RNOtel.tracer` does. +- **No `metrics.url`, failed init or a missing native module:** neither side builds a meter + provider; `handle.meterProvider` is the API's no-op and no global is registered. Metrics + being off is not an error; init failure is still reported once (4.3). +- **JS reload:** the new runtime builds a new `MeterProvider`. Points recorded since the last + export are lost (up to 60 s), and JS cumulative series restart with a new start time, which + the data model treats as a reset. Native metrics are unaffected. +- **Crash or kill:** each side loses what it hasn't exported yet. The same as any OTel SDK. +- **`forceFlush()`** on the handle flushes the JS meter provider and calls native `flush`, + which now flushes the native meter provider too. `shutdown()` on mobile shuts down only the + JS providers. +- **Never throws:** JS export failures are `sdk-metrics`' own (`diag`); native ones the + native exporter's. + +#### 4.6.7 Rejected +- **Native as the only writer, JS a thin shim** (each `add`/`record` a synchronous Nitro call + into a native instrument, aggregation native). It kept native-only sending and survived + reloads, but cost a JSI call per measurement and two seam calls with a handle table. JS + observables couldn't work without native→JS callbacks, and mobile JS would behave unlike + web. It also had a silent identity trap: JS instruments default to DOUBLE and native + counters to long, so a "shared" counter split into two streams unless the types matched. +- **JS aggregates, native exports** (like span hand-off). The native exporters accept only + SDK data objects. otel-java has public `create` factories for `MetricData` and its points, + but in opentelemetry-swift 2.6 the initializers of `MetricData`, its point types and the + `create*` helpers are all `internal`. iOS would need a `Codable` decode that depends on the + internal key layout, or a custom HTTP POST of JS-encoded bytes. Neither is built from OTel + primitives. +- **Two SDKs as in 0.2** differed in transport (JSON vs gRPC), resource and config, and had + no iOS. This design keeps two pipelines but gives them one config, one resource and one + protocol. + +#### 4.6.8 Build order +Metrics are built separately, after v0, and don't block 0.3.0. Their only effect on v0's +surface is additive: new fields in `initialize`'s result and a new native API. The +per-signal `exportConfig` shape (4.4) is the one breaking change, so it should land in 0.3.0 +even if metrics come later. + +#### 4.6.9 Open questions (for the author) +1. Fleet identity (4.6.2): should native add `service.instance.id` (a random UUID v4 per + process start, the semantic conventions' suggestion when none is given) unless the app + sets one, or only document it and recommend `delta` for fleets? It changes the v0 + resource (spans too). Check the attribute's semconv stability first. +2. Expose the export interval now (`metrics.exportIntervalMillis`, the JS reader's name), or + wait for a request? Proposed: wait. +3. Keep `temporalityPreference`, or cumulative only until asked? Proposed: keep; it is one + enum, and mobile fleets often need delta. + ## 5. Trace model Recorded so v0 primitives don't preclude it: @@ -758,6 +995,49 @@ Left out until needed: | Release gate on real telemetry (a dogfood app reporting through the SDK) | a real app uses the SDK | | `unstable_preserveAsync` device build | a Hermes release ships commit `a9d054c8c9` | +### 9.6 Metrics verification (proposed with §4.6) +Verify **our** code (both pipelines' wiring, the config and resource handed to JS, the +background hooks), not upstream aggregation or OTLP encoding. + +- **Fake collector:** a `POST /v1/metrics` route next to `/v1/traces`, decoding with the + vendored `metrics/v1/metrics.proto` and `collector/metrics/v1/metrics_service.proto` (same + proto `VERSION` as today). Requests are kept per signal; `end()` writes + `verify/artifacts/..otlp.json` (traces, unchanged) and + `….metrics.otlp.json`. +- **Expected files:** `verify/expected/.metrics.otlp.json`, an + `ExportMetricsServiceRequest` in OTLP/JSON, one file per scenario for every platform (9.1). + **A scenario without a metrics file must export no metrics**, so every trace scenario also + asserts "no stray metrics", and `native-init-failure` covers metrics for free. +- **Normalizer:** merges requests by resource → scope → metric (JS and native send separate + requests); sorts metrics by name, data points by their sorted attribute set, and + attributes. **One documented rewrite:** data-point `startTimeUnixNano` and `timeUnixNano` + are removed. None of our code sets or computes a metric time, and a deterministic clock + isn't uniformly possible: `sdk-metrics` has no clock option, and opentelemetry-swift takes + the cumulative start time from `Date()`. +- **Determinism:** test mode sets both export intervals to 120 s, so a scenario exports once, + on `forceFlush()`. Each e2e test cold-starts the app; metric names are namespaced per + scenario (`verify..*`). +- **iOS exception:** `iosView` also skips `ScopeMetrics.schemaUrl` on native metrics (4.6.5). +- **Runners:** e2e only. Jest would only exercise stock `sdk-metrics`. +- **`TestNative`** gains `count(meter, name, value, attrs)` → + `RNOtel.meter(meter).counterBuilder(name).build().add(value, attrs)`, using only the public + helper. +- **Test apps** configure both URLs: the bare app in `RNOtel.start`, the Expo app and web in + `startReactNativeSdk`, so both init routes are proven for metrics. +- **`ScenarioCtx`** gains `meter` (`handle.meterProvider.getMeter('verify')`). + +| Scenario | Guarantee | Targets | +|---|---|---| +| `metrics-js` | counter, up-down counter, histogram with bucket advice, gauge and one observable gauge from JS; unit, description, scope version; exported under **native's resource** on mobile | android, ios, web | +| `metrics-native` | a counter from `TestNative.count` exports under the same resource, in its own scope | android, ios | +| `metrics-headers` | the metrics request carries the shared header and the metrics-only header, the trace request only the shared one | android, ios, web | +| `metrics-off` | no `metrics.url`: spans export, no metrics request from either side, no error | android, ios, web | +| `background-flush` (extended) | a native counter added before backgrounding is exported without `forceFlush()` | android, ios | + +Not covered: the JS `AppState` flush (best effort, iOS may suspend it), delta temporality (one +mapping line per platform; a second config means a second app), cardinality and views +(upstream), JS reload loss (documented behavior). + ## 10. v1 backlog - Spike: Nitro call cost on Android, Kotlin vs C++ HybridObject; context patch overhead on a low-end Android device (spike numbers are from an M-series Mac). @@ -778,7 +1058,10 @@ Left out until needed: - Opt-in "swap" Babel plugin for apps that can't downlevel async. - Links from interval ticks to the context that registered them; webpack helper. - Native in-memory exporter readable from JS for app teams' tests. -- Expo config plugin (optional, thin, for native-first init), errors/crashes, logs, metrics. +- Expo config plugin (optional, thin, for native-first init), errors/crashes, logs. +- Metrics: the design is §4.6 (proposed), with verification in §9.6. Follow-ups after it + ships: a views option; native exemplars; a configurable export interval and cardinality + limit; a more reliable JS background flush if best effort proves too lossy. - Native → JS callbacks (avoided in v0 because of Nitro reload hazards). ## 11. Research and evidence From acc9efc874c19a876ed3e001cd289d1d3fdbd40b Mon Sep 17 00:00:00 2001 From: Adam Horodyski Date: Mon, 30 Nov 2026 17:08:43 +0100 Subject: [PATCH 2/2] spec: metrics hand off from JS to native, as spans do JS aggregates with stock sdk-metrics and hands its points to native through exportMetrics; native exports JS and native metrics with one OtlpHttpMetricExporter under its own resource, URL and headers. JS no longer needs the resource or metrics config, so SeamInitResult is unchanged. Android builds MetricData from otel-java's public factories. iOS uses a fork of opentelemetry-swift-core 2.6.0 that makes the metric data constructors public (access levels only). Metrics are cumulative only; temporalityPreference is dropped until asked. Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-10-rn-otel-design.md | 268 +++++++++++------- 1 file changed, 161 insertions(+), 107 deletions(-) diff --git a/docs/superpowers/specs/2026-11-10-rn-otel-design.md b/docs/superpowers/specs/2026-11-10-rn-otel-design.md index f1d6612..1dfd03b 100644 --- a/docs/superpowers/specs/2026-11-10-rn-otel-design.md +++ b/docs/superpowers/specs/2026-11-10-rn-otel-design.md @@ -321,8 +321,9 @@ OTel data model. - Returns `{ tracerProvider, meterProvider, forceFlush(), shutdown() }`, the names OTel JS uses on every provider and SDK. On mobile `shutdown` stops only the JS provider, never the native singleton. The returned providers are the ones registered globally. `forceFlush` - flushes both signals (on mobile the JS meter provider, then native `flush` for spans and - native metrics). *(`meterProvider`: proposed with metrics, §4.6.)* + flushes both signals (on mobile the JS meter provider, which hands its metrics to native, + then native `flush` for spans and all metrics). *(`meterProvider`: proposed with metrics, + §4.6.)* - Missing or invalid config logs one error and returns a no-op handle (as browser-sdk does with `invalidConfig`); it never throws. - **Endpoints, one URL per signal (proposed with metrics, §4.6; replaces v0's single @@ -340,12 +341,11 @@ OTel data model. `OTEL_EXPORTER_OTLP__HEADERS`. Why per signal at all: some backends need a header on one signal only (e.g. a metrics dataset header); one shared map covers the common case. - - **`metrics.temporalityPreference`**: `'cumulative'` (default) or `'delta'`, applied to JS and native metrics (§4.6.4). - The JS exporter's option name; the declarative config calls it `temporality_preference`. + - **Metrics are cumulative.** No temporality option yet (§4.6.4). - v0 is unreleased, so the old `exportConfig.url` is replaced, not aliased. - **Web**: the same call takes exporter options, mirroring `startBrowserSdk`'s option names (`serviceName`, `serviceVersion`, `resourceAttributes`, - `exportConfig: { headers, traces: { url, headers }, metrics: { url, headers, temporalityPreference } }`, + `exportConfig: { headers, traces: { url, headers }, metrics: { url, headers } }`, `instrumentations`, …). - Option names mirror upstream (`startBrowserSdk`, declarative config schema) wherever upstream has a name. Rejected: OTel declarative config YAML (not supported by @@ -362,7 +362,7 @@ RNOtel.start(this) { export { headers = mapOf("x-api-key" to KEY) traces { url = "https://collector.example.com:4318/v1/traces" } - metrics { url = "https://collector.example.com:4318/v1/metrics"; temporalityPreference = Temporality.DELTA } + metrics { url = "https://collector.example.com:4318/v1/metrics" } } resourceAttributes = mapOf("deployment.environment.name" to "prod") } @@ -374,7 +374,7 @@ RNOtel.start { c in c.serviceName = "shop"; c.serviceVersion = Bundle.main.version c.export = .init(headers: ["x-api-key": KEY], traces: .init(url: "https://collector.example.com:4318/v1/traces"), - metrics: .init(url: "https://collector.example.com:4318/v1/metrics", temporalityPreference: .delta)) + metrics: .init(url: "https://collector.example.com:4318/v1/metrics")) } ``` @@ -394,10 +394,9 @@ startReactNativeSdk({ ``` The seam config follows the same shape: `SeamConfig` loses `exportUrl`/`exportHeaders` and -gains `exportHeaders: SeamAttribute[]`, `traces?: SeamSignal`, `metrics?: SeamMetrics` -with `SeamSignal { url: string; headers: SeamAttribute[] }` and `SeamMetrics` the same plus -`delta: boolean` (Nitro needs named interfaces, 4.3). Header -merging happens in each native core (native-first init never passes through JS). +gains `exportHeaders: SeamAttribute[]`, `traces?: SeamSignal`, `metrics?: SeamSignal` with +`SeamSignal { url: string; headers: SeamAttribute[] }` (Nitro needs named interfaces, 4.3). +Header merging happens in each native core (native-first init never passes through JS). ```js // metro.config.js: installs the context patch before any app module @@ -420,24 +419,27 @@ Package name: `react-native-open-telemetry` (subpath `/metro`). Entry function: Status: design only, nothing implemented. The published 0.2 had metrics (JS `sdk-metrics` over OTLP/HTTP JSON; a separate otel-java `SdkMeterProvider` over gRPC on Android; nothing -on iOS). v0 removed them. This section brings them back with **two independent pipelines -from one config**, each built only from stock OTel types. Upstream versions checked: -otel-java 1.68.0, opentelemetry-swift 2.6.0 (core + exporters), `@opentelemetry/sdk-metrics` -3.1.1 with `@opentelemetry/exporter-metrics-otlp-proto` 0.301.2, spec at `4e01937`. +on iOS). v0 removed them. This section brings them back **the way spans work: JS aggregates, +native exports**. Upstream versions checked: otel-java 1.68.0, opentelemetry-swift 2.6.0 +(core + exporters), `@opentelemetry/sdk-metrics` 3.1.1 with +`@opentelemetry/exporter-metrics-otlp-proto` 0.301.2 (web only), spec at `4e01937`. Metrics are best effort next to spans (JS background flush, reloads: 4.6.4, 4.6.6). Spans and traces stay the priority. -#### 4.6.1 Model: JS metrics in JS, native metrics in native -- **JS metrics live in the stock JS SDK on every platform.** `startReactNativeSdk` builds - `MeterProvider` + `PeriodicExportingMetricReader` + `OTLPMetricExporter` - (`exporter-metrics-otlp-proto`) on Android, iOS and web: the same code as web today builds - for spans. JS exports metrics itself; nothing crosses the seam per measurement. -- **Native metrics live in the native SDK.** The native core builds `SdkMeterProvider` - (otel-java) / `MeterProviderSdk` (opentelemetry-swift) + `PeriodicMetricReader` + - `OtlpHttpMetricExporter` next to the tracer provider, with the same resource. App native - code gets meters from `RNOtel.meter`. -- **One config.** Both pipelines read `exportConfig.metrics` (4.4). On mobile the config - usually lives in native init, so native hands JS what JS needs (4.6.3). +#### 4.6.1 Model: JS aggregates, native exports +- **JS metrics are aggregated by the stock JS SDK.** `startReactNativeSdk` builds + `MeterProvider` + `PeriodicExportingMetricReader`. On mobile the reader's exporter is ours, + `HandOffMetricExporter`: it maps `ResourceMetrics` to seam structs and calls + `exportMetrics` once per export (4.6.3). On web it is the stock `OTLPMetricExporter`. +- **Native metrics are aggregated by the native SDK.** The native core builds + `SdkMeterProvider` (otel-java) / `MeterProviderSdk` (opentelemetry-swift) + + `PeriodicMetricReader` next to the tracer provider. App native code gets meters from + `RNOtel.meter`. +- **Native exports both.** One `OtlpHttpMetricExporter` per core, with native's resource, URL + and merged headers, serves the native reader and the JS hand-off. Exactly as for spans, JS + never holds the resource, the URL or the headers. +- **One config, read only by native** (4.4). JS needs no metrics setting: there is no + temporality option (4.6.4), so `SeamInitResult` is unchanged. - **No shared instruments.** A JS instrument and a native instrument are never the same instrument. To increment a native metric from JS, the app calls its own native module, which records on its `RNOtel.meter` instrument (the same pattern as `doWork` in 4.3). @@ -445,20 +447,25 @@ Metrics are best effort next to spans (JS background flush, reloads: 4.6.4, 4.6. otel-java `PeriodicMetricReader` (`metricData.isEmpty()`, line 290), opentelemetry-swift `PeriodicMetricReaderSdk` (`metricData.isEmpty`, line 91), JS `PeriodicExportingMetricReader` (`scopeMetrics.length === 0`, line 197). An app that - records only in JS never sends a native metrics request, and the reverse. + records nothing in JS makes no `exportMetrics` call; one that records nothing natively + sends no native batch. +- **Two requests, not one.** JS and native batches export separately. otel-java could merge + them (`SdkMeterProviderBuilder.registerMetricProducer`), but opentelemetry-swift 2.6 has no + public way to add a producer, so both platforms keep two requests. ```mermaid flowchart LR subgraph mobile["Mobile"] - jsapp["JS: metrics.getMeter(...)"] --> jsmp["sdk-metrics MeterProvider
PeriodicExportingMetricReader"] --> jsexp["OTLPMetricExporter (proto, JS)"] - nat["app native code: RNOtel.meter(...)"] --> nmp["native MeterProvider
PeriodicMetricReader"] --> nexp["OtlpHttpMetricExporter"] - core["native core"] -. "initialize(): resource + metrics config" .-> jsmp + jsapp["JS: metrics.getMeter(...)"] --> jsmp["sdk-metrics MeterProvider
PeriodicExportingMetricReader"] --> hand["HandOffMetricExporter"] + hand -- "exportMetrics(SeamMetric[])" --> conv["native core: JS points → MetricData"] + nat["app native code: RNOtel.meter(...)"] --> nmp["native MeterProvider
PeriodicMetricReader"] + conv --> nexp["OtlpHttpMetricExporter
native resource, URL, headers"] + nmp --> nexp end subgraph web["Web"] jsw["JS: metrics.getMeter(...)"] --> wmp["sdk-metrics MeterProvider"] --> wexp["OTLPMetricExporter (proto)"] end - jsexp --> col[("collector /v1/metrics")] - nexp --> col + nexp --> col[("collector /v1/metrics")] wexp --> col ``` @@ -484,7 +491,7 @@ The metrics data model (Stable): *"All metric data streams within OTLP MUST have writer"* ([data-model.md#single-writer](https://github.com/open-telemetry/opentelemetry-specification/blob/4e01937ed7d734e5f4feb8ffba89f1b6b960ab59/specification/metrics/data-model.md#single-writer)). A stream is identified by resource, scope, metric name (+ kind, unit) and attributes. JS and -native share the resource, so each side must write its own scopes: +native metrics are exported under one resource, so each side must write its own scopes: - **Rule (documented):** don't create an instrument with the same name in the same meter scope from JS and from native. If an app does, the backend sees two writers of one stream. We don't detect it. @@ -495,66 +502,99 @@ native share the resource, so each side must write its own scopes: problem. See open question 1. #### 4.6.3 What crosses the seam -Nothing per measurement. Only `initialize`'s result grows, so a JS-only pipeline can export -with native's identity and config: +Nothing per measurement, and nothing at init. One call per JS export (every 60 s, or on +flush), the metrics counterpart of `handOff(spans)`: ```ts // illustrative additions to Otel.nitro.ts -interface SeamResource { attributes: SeamAttribute[]; schemaUrl?: string } -interface SeamInitResult { - alreadyInitialized: boolean; testMode: boolean; error?: string; - resource: SeamResource; // native's resource, exactly as native exports it - metrics?: SeamMetrics; // 4.4's struct: url, headers (already merged), delta; absent = metrics off +type SeamMetricKind = 'sum' | 'gauge' | 'histogram'; +interface SeamPoint { + start: HrTime; end: HrTime; attributes: SeamAttribute[]; + value?: number; // sum, gauge + count?: number; sum?: number; min?: number; max?: number; // histogram + boundaries?: number[]; counts?: number[]; +} +interface SeamMetric { + scope: SeamScope; name: string; description: string; unit: string; + kind: SeamMetricKind; isLong: boolean; isMonotonic: boolean; points: SeamPoint[]; +} +interface Otel { + // …v0 methods unchanged + exportMetrics(metrics: SeamMetric[]): void; } ``` -- **Resource:** JS builds its `Resource` from these attributes and adds nothing, so JS and - native metrics, and all spans, carry one resource (4.3 "Resource identity"). Its - `telemetry.sdk.*` values are otel-java's or opentelemetry-swift's, as on JS spans. -- **Metrics config:** native merges the headers (4.4) and returns the result. JS passes `url` - and `headers` to `OTLPMetricExporter` and maps `delta` to - `temporalityPreference: AggregationTemporalityPreference.DELTA`. -- **The same path for both init routes.** With JS-fallback init, JS sends its config to - native and reads it back from the result; there is one code path, not two. -- **Trade-off: the metrics headers reach JS memory.** With native-first init they used to - stay native. The per-signal headers of 4.4 let an app give metrics a key of its own. +- **Same contract as `handOff`:** synchronous, returns at once, never throws. The core + converts and exports on its own worker, never on the JS thread. Before native init, after + a failed init or without `metrics.url`, the core drops the batch. +- **`isLong`** comes from the instrument's `valueType` (`ValueType.INT`), so a JS integer + counter exports as `asInt`, as otel-java's would. +- **Only what `sdk-metrics` produces with default aggregation** crosses: sums, gauges, + explicit-bucket histograms. Exponential histograms need a view, and views aren't exposed + (4.6.4); the exporter skips other types. #### 4.6.4 JS pipeline | Setting | Choice | Why | |---|---|---| -| Packages | `@opentelemetry/sdk-metrics` 3.1.1, `@opentelemetry/exporter-metrics-otlp-proto` 0.301.2, pinned exactly | Same release train as the pinned `sdk-trace` 3.1.1 and `exporter-trace-otlp-proto` 0.301.2. | -| Temporality | **cumulative** default; `delta` option | The spec default. `delta` is JS `DELTA`, otel-java and Swift `deltaPreferred()`: the same mapping on all three (up-down counters stay cumulative). | +| Packages | `@opentelemetry/sdk-metrics` 3.1.1 on every platform; `@opentelemetry/exporter-metrics-otlp-proto` 0.301.2 on web only (`start.web.ts`), pinned exactly | Same release train as the pinned `sdk-trace` 3.1.1 and `exporter-trace-otlp-proto` 0.301.2. Mobile bundles no JS OTLP exporter. | +| Exporter | mobile: `HandOffMetricExporter` (a `PushMetricExporter`); web: `OTLPMetricExporter` | As for spans: `NativeHandOffProcessor` on mobile, the stock exporter on web. | +| Temporality | **cumulative**, no option | The spec default, and what every reader here picks without config. `sdk-metrics` picks temporality in JS at collection time (`TemporalMetricProcessor`, from the exporter's `selectAggregationTemporality`); an option would need a value from native in `SeamInitResult`. Add it when someone asks (§10). | | Export interval | **60 s**, not configurable yet | The JS default. Test mode: 120 s, so only `forceFlush` exports (9.6). | -| Background | mobile: an `AppState` `'background'` listener calls `meterProvider.forceFlush()` | Best effort: the JS thread and its `fetch` can be suspended on iOS before the request finishes. Accepted; spans keep the native background task. | +| Background | mobile: an `AppState` `'background'` listener calls `meterProvider.forceFlush()` | The hand-off is one synchronous call, and the export then runs natively inside the existing background task. Still best effort: iOS can suspend the JS thread before the listener runs. | | Views, cardinality | stock `sdk-metrics` defaults, views not exposed | Upstream. Add a views option when someone asks. | | Global | registered with `metrics.setGlobalMeterProvider` and returned as `handle.meterProvider` | As for the tracer provider. | - **Every JS instrument works**, including observables and `addBatchObservableCallback`: callbacks run in JS at collection time; nothing calls JS from native. -- **Mobile and web are the same code.** Web reads the config from `startReactNativeSdk`; - mobile reads it from the `initialize` result. -- **Build check:** that `exporter-metrics-otlp-proto` resolves its browser entry under Metro - and Hermes and exports with `fetch` (RN has no `sendBeacon`). 0.2 shipped the JSON variant - in RN. +- **Mobile and web share the meter provider code**; only the exporter differs, as for spans. #### 4.6.5 Native pipeline Both cores build it next to the tracer provider when `metrics.url` is set: | Setting | Choice | Why | |---|---|---| -| Exporter | `OtlpHttpMetricExporter`, URL as given, merged headers, built lazily | The same code path as the span exporter: otel-java's span and metric exporters wrap the same internal `HttpExporterBuilder` (retry on by default); Swift's wrap `OtlpHttpExporterBase` (no retry; `requeueOnFailure: true`). | -| Temporality | from config, as in 4.6.4 | One mapping on all three platforms. | +| Exporter | One `OtlpHttpMetricExporter`, URL as given, merged headers, built lazily, shared by the native reader and the JS hand-off | The same code path as the span exporter: otel-java's span and metric exporters wrap the same internal `HttpExporterBuilder` (retry on by default); Swift's wrap `OtlpHttpExporterBase` (no retry; `requeueOnFailure: true`; pending queue behind a lock, so sharing is safe). | +| Temporality | cumulative (the exporters' default) | As in 4.6.4. | | Export interval | **60 s** | otel-java's default. Swift's `PeriodicMetricReaderBuilder` defaults to **1 s**, so iOS sets it. Test mode: 120 s. | | Background flush | the existing hooks also call `meterProvider.forceFlush()` | Android: queued on the reader's worker, never joined on the main thread. iOS: blocks up to the export timeout, so it runs on the global queue inside the existing background task. | -| Exemplars | **off** (otel-java `ExemplarFilter.alwaysOff()`, Swift `AlwaysOffFilter()`) | Swift's default is `AlwaysOn` (an exemplar on every point). Off on both keeps them alike; v1 option in §10. | +| Exemplars | **off** (otel-java `ExemplarFilter.alwaysOff()`, Swift `AlwaysOffFilter()`) | Swift's default is `AlwaysOn` (an exemplar on every point). Off on both keeps them alike; JS points carry none either. v1 option in §10. | | Cardinality, views | SDK defaults, not exposed | otel-java: 2,000 attribute sets, then an overflow series. Swift: a hard 2,000, then new sets are dropped. Documented. | -opentelemetry-swift 2.6 has everything this needs: all sync and observable instruments with -long and double, scope version and `schemaUrl`, bucket advice, resource, temporality selector, -exemplar filter, and the OTLP/HTTP protobuf exporter. Its gaps, documented and not patched: -the 1 s default interval, the cardinality drop, `AlwaysOn` exemplars, a cumulative start time -taken from `Date()` instead of the builder clock, and no `ScopeMetrics.schemaUrl` in the -encoder (the same gap as for spans, §9.1). +**JS points → `MetricData`**, with the SDKs' own types only: +- **Android:** `JsMetricData` implements the public `MetricData` interface, as `JsSpanData` + implements `SpanData`. Points and data use otel-java's public factories: + `LongPointData.create`, `DoublePointData.create`, `HistogramPointData.create`, + `SumData.createLongSumData` / `createDoubleSumData`, `GaugeData.createLongGaugeData` / + `createDoubleGaugeData`, `HistogramData.create`. Build one `InstrumentationScopeInfo` per + scope: otel-java's encoder put each metric in its own `ScopeMetrics` when every metric had + its own scope instance. +- **iOS:** `LongPointData(…)`, `DoublePointData(…)`, `HistogramPointData(…)`, + `SumData(…)` / `GaugeData(…)` / `HistogramData(…)` and `MetricData.createLongSum(…)` etc. + These exist in opentelemetry-swift-core 2.6.0 but are `internal` (also on `main`), unlike + their otel-java counterparts and Swift's own public `SpanData` setters. **We ship a fork** + of opentelemetry-swift-core 2.6.0 that changes only access levels (14 lines in 4 files): + the six `MetricData.create*` factories, the `SumData` / `GaugeData` / `HistogramData` / + `SummaryData` / `ExponentialHistogramData` initializers, and the `LongPointData` / + `DoublePointData` / `HistogramPointData` initializers become `public`. The podspec's + `spm_dependency` points at the fork's tag. No upstream PR for now; dropping the fork later + is a URL change. +- **Proof** (2026-11-30, the pinned versions): `sdk-metrics` with a hand-off exporter produced + a counter, up-down counter, histogram with bucket advice, gauge and observable gauge in one + export; both cores converted them as above and the stock `OtlpHttpMetricExporter` returned + success; a fake collector decoded all five under the native resource with the native + headers. Against stock 2.6.0 the iOS code doesn't compile (`'createLongSum' is + inaccessible due to 'internal' protection level`). +- **Build check:** opentelemetry-swift depends on upstream opentelemetry-swift-core, and our + podspec on the fork; both resolve to the package identity `opentelemetry-swift-core`. + SwiftPM 6.4 takes the root's dependency with a warning ("will be escalated to an error in + future versions"). Verify in the bare and Expo apps under CocoaPods before building on it. + +opentelemetry-swift 2.6 has everything else this needs: all sync and observable instruments +with long and double, scope version and `schemaUrl`, bucket advice, resource, exemplar +filter, and the OTLP/HTTP protobuf exporter. Its gaps, documented and not patched: the 1 s +default interval, the cardinality drop, `AlwaysOn` exemplars, a cumulative start time taken +from `Date()` instead of the builder clock, and no `ScopeMetrics.schemaUrl` in the encoder +(the same gap as for spans, §9.1). Native public API, next to `RNOtel.tracer`, same no-op rule: @@ -573,51 +613,61 @@ usable from app Swift code without casts; otherwise return the concrete `MeterSd `startReactNativeSdk()` is the first line of `index.js`. - **Native code before native init:** `RNOtel.meter` returns the no-op meter, as `RNOtel.tracer` does. -- **No `metrics.url`, failed init or a missing native module:** neither side builds a meter - provider; `handle.meterProvider` is the API's no-op and no global is registered. Metrics - being off is not an error; init failure is still reported once (4.3). +- **Failed init or a missing native module:** no meter provider on either side; + `handle.meterProvider` is the API's no-op and no global is registered. Init failure is + reported once (4.3). +- **No `metrics.url`:** on web, JS builds no meter provider. On mobile JS doesn't know, so it + aggregates and hands off and native drops the batch, as it would for spans without an + exporter. The cost is the JS aggregation of instruments the app chose to record. Metrics + being off is not an error. - **JS reload:** the new runtime builds a new `MeterProvider`. Points recorded since the last export are lost (up to 60 s), and JS cumulative series restart with a new start time, which the data model treats as a reset. Native metrics are unaffected. - **Crash or kill:** each side loses what it hasn't exported yet. The same as any OTel SDK. -- **`forceFlush()`** on the handle flushes the JS meter provider and calls native `flush`, - which now flushes the native meter provider too. `shutdown()` on mobile shuts down only the - JS providers. -- **Never throws:** JS export failures are `sdk-metrics`' own (`diag`); native ones the - native exporter's. +- **`forceFlush()`** on the handle flushes the JS meter provider (one hand-off) and then + calls native `flush`, which now flushes the native meter provider and the metric exporter + too. `shutdown()` on mobile shuts down only the JS providers. +- **Never throws:** `exportMetrics` drops on any conversion error; export failures are the + native exporter's (and `sdk-metrics`' `diag` on web). #### 4.6.7 Rejected +- **JS exports metrics itself on mobile** (the first draft of this section: stock + `OTLPMetricExporter` in JS, two independent pipelines). JS needed native's resource and + merged metrics config in `SeamInitResult`, the metrics headers lived in JS memory, the + export ran on JS `fetch` that iOS can suspend in the background, and Metro/Hermes had to + bundle a second OTLP exporter. Spans never needed any of that, because native exports them. - **Native as the only writer, JS a thin shim** (each `add`/`record` a synchronous Nitro call - into a native instrument, aggregation native). It kept native-only sending and survived - reloads, but cost a JSI call per measurement and two seam calls with a handle table. JS - observables couldn't work without native→JS callbacks, and mobile JS would behave unlike - web. It also had a silent identity trap: JS instruments default to DOUBLE and native - counters to long, so a "shared" counter split into two streams unless the types matched. -- **JS aggregates, native exports** (like span hand-off). The native exporters accept only - SDK data objects. otel-java has public `create` factories for `MetricData` and its points, - but in opentelemetry-swift 2.6 the initializers of `MetricData`, its point types and the - `create*` helpers are all `internal`. iOS would need a `Codable` decode that depends on the - internal key layout, or a custom HTTP POST of JS-encoded bytes. Neither is built from OTel - primitives. + into a native instrument, aggregation native). It survived reloads, but cost a JSI call per + measurement and two seam calls with a handle table. JS observables couldn't work without + native→JS callbacks, and mobile JS would behave unlike web. It also had a silent identity + trap: JS instruments default to DOUBLE and native counters to long, so a "shared" counter + split into two streams unless the types matched. +- **iOS conversion through `MetricData`'s public `Codable` decoder** (works on stock 2.6.0, + proven the same day). It builds SDK objects from JSON keyed by undocumented `CodingKeys` + (`dataPoints`, `startEpochNanos`, …): a hack around the access levels instead of the SDK's + own constructors. +- **Raw OTLP bytes from JS, POSTed by native.** JS would still need the resource, and native + would bypass its own exporter. +- **A temporality option** (`temporalityPreference`). Needs a value from native in + `SeamInitResult`; cumulative only until asked (4.6.4). - **Two SDKs as in 0.2** differed in transport (JSON vs gRPC), resource and config, and had - no iOS. This design keeps two pipelines but gives them one config, one resource and one - protocol. + no iOS. #### 4.6.8 Build order -Metrics are built separately, after v0, and don't block 0.3.0. Their only effect on v0's -surface is additive: new fields in `initialize`'s result and a new native API. The -per-signal `exportConfig` shape (4.4) is the one breaking change, so it should land in 0.3.0 -even if metrics come later. +Metrics are built separately, after v0, and don't block 0.3.0. Their effect on v0's surface +is additive: one new seam method (`exportMetrics`), a native API (`RNOtel.meter`) and, on +iOS, the forked opentelemetry-swift-core. The per-signal `exportConfig` shape (4.4) is the +one breaking change, so it should land in 0.3.0 even if metrics come later. Start with the +SwiftPM identity build check (4.6.5). #### 4.6.9 Open questions (for the author) 1. Fleet identity (4.6.2): should native add `service.instance.id` (a random UUID v4 per process start, the semantic conventions' suggestion when none is given) unless the app - sets one, or only document it and recommend `delta` for fleets? It changes the v0 - resource (spans too). Check the attribute's semconv stability first. + sets one, or only document it? It changes the v0 resource (spans too). Check the + attribute's semconv stability first. Without it, a fleet's cumulative series from many + installs share one identity. 2. Expose the export interval now (`metrics.exportIntervalMillis`, the JS reader's name), or wait for a request? Proposed: wait. -3. Keep `temporalityPreference`, or cumulative only until asked? Proposed: keep; it is one - enum, and mobile fleets often need delta. ## 5. Trace model @@ -996,8 +1046,9 @@ Left out until needed: | `unstable_preserveAsync` device build | a Hermes release ships commit `a9d054c8c9` | ### 9.6 Metrics verification (proposed with §4.6) -Verify **our** code (both pipelines' wiring, the config and resource handed to JS, the -background hooks), not upstream aggregation or OTLP encoding. +Verify **our** code (the hand-off exporter, the JS points → `MetricData` conversion on both +cores, the iOS fork, the native pipeline's wiring, the background hooks), not upstream +aggregation or OTLP encoding. - **Fake collector:** a `POST /v1/metrics` route next to `/v1/traces`, decoding with the vendored `metrics/v1/metrics.proto` and `collector/metrics/v1/metrics_service.proto` (same @@ -1017,8 +1068,10 @@ background hooks), not upstream aggregation or OTLP encoding. - **Determinism:** test mode sets both export intervals to 120 s, so a scenario exports once, on `forceFlush()`. Each e2e test cold-starts the app; metric names are namespaced per scenario (`verify..*`). -- **iOS exception:** `iosView` also skips `ScopeMetrics.schemaUrl` on native metrics (4.6.5). -- **Runners:** e2e only. Jest would only exercise stock `sdk-metrics`. +- **iOS exception:** `iosView` also skips `ScopeMetrics.schemaUrl` on all metrics: native + exports JS metrics too, through the same encoder (4.6.5). +- **Runners:** e2e only. The conversion is native code, so only a device run exercises it; + every iOS e2e build also proves the forked opentelemetry-swift-core resolves. - **`TestNative`** gains `count(meter, name, value, attrs)` → `RNOtel.meter(meter).counterBuilder(name).build().add(value, attrs)`, using only the public helper. @@ -1028,14 +1081,13 @@ background hooks), not upstream aggregation or OTLP encoding. | Scenario | Guarantee | Targets | |---|---|---| -| `metrics-js` | counter, up-down counter, histogram with bucket advice, gauge and one observable gauge from JS; unit, description, scope version; exported under **native's resource** on mobile | android, ios, web | +| `metrics-js` | counter (`ValueType.INT`, exported `asInt`), up-down counter, histogram with bucket advice, gauge and one observable gauge from JS; unit, description, scope version, one `ScopeMetrics` per scope; on mobile handed off and exported by native under **native's resource** | android, ios, web | | `metrics-native` | a counter from `TestNative.count` exports under the same resource, in its own scope | android, ios | -| `metrics-headers` | the metrics request carries the shared header and the metrics-only header, the trace request only the shared one | android, ios, web | -| `metrics-off` | no `metrics.url`: spans export, no metrics request from either side, no error | android, ios, web | +| `metrics-headers` | the metrics requests (JS and native) carry the shared header and the metrics-only header, the trace request only the shared one | android, ios, web | +| `metrics-off` | no `metrics.url`: spans export; JS records and hands off, native drops it; no metrics request, no error | android, ios, web | | `background-flush` (extended) | a native counter added before backgrounding is exported without `forceFlush()` | android, ios | -Not covered: the JS `AppState` flush (best effort, iOS may suspend it), delta temporality (one -mapping line per platform; a second config means a second app), cardinality and views +Not covered: the JS `AppState` flush (best effort, iOS may suspend it), cardinality and views (upstream), JS reload loss (documented behavior). ## 10. v1 backlog @@ -1060,8 +1112,10 @@ mapping line per platform; a second config means a second app), cardinality and - Native in-memory exporter readable from JS for app teams' tests. - Expo config plugin (optional, thin, for native-first init), errors/crashes, logs. - Metrics: the design is §4.6 (proposed), with verification in §9.6. Follow-ups after it - ships: a views option; native exemplars; a configurable export interval and cardinality - limit; a more reliable JS background flush if best effort proves too lossy. + ships: a temporality option (one value from native in `SeamInitResult`, 4.6.4); a views + option; native exemplars; a configurable export interval and cardinality limit; a more + reliable JS background flush if best effort proves too lossy; dropping the + opentelemetry-swift-core fork if upstream makes the metric data constructors public. - Native → JS callbacks (avoided in v0 because of Nitro reload hazards). ## 11. Research and evidence