diff --git a/.changeset/config.json b/.changeset/config.json
index 66c1704..2be13d4 100644
--- a/.changeset/config.json
+++ b/.changeset/config.json
@@ -1,10 +1,10 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
"changelog": "@changesets/cli/changelog",
- "commit": true,
+ "commit": false,
"fixed": [],
"linked": [],
- "access": "restricted",
+ "access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
diff --git a/.changeset/v0-tracing-rewrite.md b/.changeset/v0-tracing-rewrite.md
new file mode 100644
index 0000000..4123664
--- /dev/null
+++ b/.changeset/v0-tracing-rewrite.md
@@ -0,0 +1,8 @@
+---
+"react-native-open-telemetry": minor
+---
+
+v0: a rewrite around one trace across JS and native. Native-first init (`RNOtel.start` on Android and iOS) with a JS
+fallback (`startReactNativeSdk`), a context patch that carries the active span through `await`, promises and timers,
+and a `withOtel` helper for Metro. Removed (breaking): metrics, fetch instrumentation, session tagging and
+the `openTelemetrySDK` init.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c234bc4..38e4a2e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,20 +40,15 @@ jobs:
java-version: '17'
- run: bun install --frozen-lockfile
- run: bun run prepare
- - run: bun verify # every non-e2e stage (R17)
+ - run: bun verify
- uses: actions/upload-artifact@v4
if: always()
with:
name: verify-artifacts-static-fast
path: verify/artifacts/
if-no-files-found: ignore
- include-hidden-files: true # verify/e2e/.e2e is a dot dir
+ include-hidden-files: true
- # Release builds with the JS bundle embedded (no Metro), test mode on; the bare jobs also build test mode off for
- # smoke-device (per PR on bare only, X11 interim; Expo smoke goes to the nightly). perf-budget runs on android-bare.
- # Every Task 27 failure scenario runs here except fast-refresh-idempotent: it needs dev builds + Metro, so it is
- # local only (verify/VERIFY.md), no per-PR jobs; a nightly can add it.
- # Native outputs are cached on native inputs only, so a JS-only change re-bundles but reuses the native build.
e2e-android-bare:
runs-on: ubuntu-latest
timeout-minutes: 45
@@ -69,7 +64,7 @@ jobs:
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: example
- - run: bun run prepare # the example bundles the package through exports -> lib/ (R4)
+ - run: bun run prepare
- name: Enable KVM
run: |
echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
@@ -89,19 +84,10 @@ jobs:
example/node_modules/react-native-nitro-modules/android/build
example/node_modules/react-native-nitro-modules/android/.cxx
key: android-native-${{ hashFiles('android/**', 'nitrogen/**', 'patches/**', 'example/android/**', 'example/modules/**', 'bun.lock', 'example/bun.lock') }}
- # smoke-device (R20, X11): the production pipeline needs a test-mode-off build. Built first, so the test-mode
- # build is what the native outputs cache keeps; the switch recompiles only Kotlin and the bundle.
- - name: Build release APK (smoke, test mode off)
- working-directory: example/android
- run: |
- ./gradlew :app:assembleRelease -PreactNativeArchitectures=x86_64 ||
- ./gradlew :app:assembleRelease -PreactNativeArchitectures=x86_64
- cp app/build/outputs/apk/release/app-release.apk '${{ runner.temp }}/smoke.apk'
- name: Build release APK (test mode)
working-directory: example/android
env:
OTEL_TEST_MODE: '1'
- # one retry: plugin and NDK downloads fail transiently on hosted runners
run: |
./gradlew :app:assembleRelease -PotelTestMode=true -PreactNativeArchitectures=x86_64 ||
./gradlew :app:assembleRelease -PotelTestMode=true -PreactNativeArchitectures=x86_64
@@ -125,7 +111,7 @@ jobs:
disable-animations: false
script: echo "AVD snapshot created"
- name: e2e (android-bare)
- timeout-minutes: 25 # a hung device run fails here, not at the job limit
+ timeout-minutes: 25
uses: reactivecircus/android-emulator-runner@v2
env:
E2E_TARGET: android-bare
@@ -138,18 +124,16 @@ jobs:
disable-animations: true
script: |
adb shell settings put global hide_error_dialogs 1
- # one line (the runner runs each line in its own shell and stops at the first failure): smoke runs even
- # when the main e2e failed, and the step exits with the first non-zero code
- bun verify --e2e e2e; a=$?; E2E_SMOKE=1 E2E_ANDROID_APP='${{ runner.temp }}/smoke.apk' bun verify --e2e e2e; b=$?; exit $(( a ? a : b ))
+ bun verify --e2e e2e
- uses: actions/upload-artifact@v4
- if: always() # e2e retries once; keep traces of retried and failed attempts
+ if: always()
with:
name: verify-artifacts-e2e-android-bare
path: |
verify/artifacts/
verify/e2e/.e2e/
if-no-files-found: ignore
- include-hidden-files: true # verify/e2e/.e2e is a dot dir
+ include-hidden-files: true
e2e-ios-bare:
runs-on: xcode-27
@@ -165,7 +149,7 @@ jobs:
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: example
- - run: bun run prepare # the example bundles the package through exports -> lib/ (R4)
+ - run: bun run prepare
- name: Cache Swift packages
uses: actions/cache@v4
with:
@@ -178,19 +162,6 @@ jobs:
example/ios/Pods
example/ios/build/Build
key: ios-native-${{ hashFiles('ios/**', 'nitrogen/**', 'ReactNativeOpenTelemetry.podspec', 'ReactNativeOpenTelemetryCore.podspec', 'example/ios/Podfile', 'example/ios/Podfile.lock', 'example/ios/OpenTelemetryExample/**', 'example/ios/OpenTelemetryExample.xcodeproj/**', 'example/modules/**', 'bun.lock', 'example/bun.lock') }}
- # smoke-device (R20, X11): a test-mode-off build, first, so the cache keeps the test-mode one; the switch
- # recompiles only the core pod, the adapter and the app.
- - name: pod install (smoke, test mode off)
- working-directory: example/ios
- run: pod install
- - name: Build release app (smoke, test mode off)
- id: ios-smoke-build
- working-directory: example/ios
- run: |
- xcodebuild -workspace OpenTelemetryExample.xcworkspace -scheme OpenTelemetryExample \
- -configuration Release -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' \
- -derivedDataPath build ARCHS=arm64 build
- cp -R build/Build/Products/Release-iphonesimulator/OpenTelemetryExample.app '${{ runner.temp }}/'
- name: pod install (test mode)
working-directory: example/ios
env:
@@ -210,23 +181,14 @@ jobs:
xcrun simctl boot "$udid"
xcrun simctl bootstatus "$udid" -b
- name: e2e (ios-bare)
- timeout-minutes: 30 # a hung device run fails here, not at the job limit
+ timeout-minutes: 30
env:
E2E_TARGET: ios-bare
- AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS: '600000' # the first daemon start on a cold runner outlasts the 120 s default
- run: bun verify --e2e e2e
- - name: e2e smoke (ios-bare, test mode off)
- timeout-minutes: 10 # a hung device run fails here, not at the job limit
- # also after a failed main e2e (that step already fails the job)
- if: ${{ !cancelled() && steps.ios-smoke-build.outcome == 'success' }}
- env:
- E2E_TARGET: ios-bare
- E2E_SMOKE: '1'
AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS: '600000'
- run: E2E_IOS_APP='${{ runner.temp }}/OpenTelemetryExample.app' bun verify --e2e e2e
+ run: bun verify --e2e e2e
- name: Diagnose the simulator log
if: failure()
- timeout-minutes: 4 # `log show` scans the whole store: ~1 min per call on a runner
+ timeout-minutes: 4
run: |
echo "--- RNOtel lines"; xcrun simctl spawn booted log show --last 10m --info --style compact --predicate 'eventMessage CONTAINS "RNOtel"' | tail -20
echo "--- app process lines"; xcrun simctl spawn booted log show --last 10m --info --style compact --predicate 'process == "OpenTelemetryExample"' | tail -20
@@ -239,18 +201,15 @@ jobs:
if-no-files-found: ignore
include-hidden-files: true
- uses: actions/upload-artifact@v4
- if: always() # e2e retries once; keep traces of retried and failed attempts
+ if: always()
with:
name: verify-artifacts-e2e-ios-bare
path: |
verify/artifacts/
verify/e2e/.e2e/
if-no-files-found: ignore
- include-hidden-files: true # verify/e2e/.e2e is a dot dir
+ include-hidden-files: true
- # The Expo app (Task 28): JS-fallback init, CNG (`expo prebuild` every run; android/ and ios/ are not committed),
- # same scenarios and the same android/ios expected files as the bare app. Test mode: OTEL_TEST_MODE=1 at prebuild
- # (the local config plugin writes otelTestMode=true to gradle.properties) and at pod install.
e2e-android-expo:
runs-on: ubuntu-latest
timeout-minutes: 45
@@ -266,7 +225,7 @@ jobs:
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: example-expo
- - run: bun run prepare # the app bundles the package through exports -> lib/ (R4)
+ - run: bun run prepare
- name: expo prebuild (test mode)
working-directory: example-expo
env:
@@ -280,7 +239,7 @@ jobs:
- uses: gradle/actions/setup-gradle@v4
- name: Enable the Gradle build cache (setup-gradle persists it)
run: printf '\norg.gradle.caching=true\n' >> example-expo/android/gradle.properties
- - name: Cache native build outputs # after prebuild, which regenerates android/
+ - name: Cache native build outputs
uses: actions/cache@v4
with:
path: |
@@ -295,7 +254,6 @@ jobs:
working-directory: example-expo/android
env:
OTEL_TEST_MODE: '1'
- # one retry: plugin and NDK downloads fail transiently on hosted runners
run: |
./gradlew :app:assembleRelease -PreactNativeArchitectures=x86_64 ||
./gradlew :app:assembleRelease -PreactNativeArchitectures=x86_64
@@ -319,7 +277,7 @@ jobs:
disable-animations: false
script: echo "AVD snapshot created"
- name: e2e (android-expo)
- timeout-minutes: 25 # a hung device run fails here, not at the job limit
+ timeout-minutes: 25
uses: reactivecircus/android-emulator-runner@v2
env:
E2E_TARGET: android-expo
@@ -334,14 +292,14 @@ jobs:
adb shell settings put global hide_error_dialogs 1
bun verify --e2e e2e
- uses: actions/upload-artifact@v4
- if: always() # e2e retries once; keep traces of retried and failed attempts
+ if: always()
with:
name: verify-artifacts-e2e-android-expo
path: |
verify/artifacts/
verify/e2e/.e2e/
if-no-files-found: ignore
- include-hidden-files: true # verify/e2e/.e2e is a dot dir
+ include-hidden-files: true
e2e-ios-expo:
runs-on: xcode-27
@@ -357,11 +315,11 @@ jobs:
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: example-expo
- - run: bun run prepare # the app bundles the package through exports -> lib/ (R4)
+ - run: bun run prepare
- name: expo prebuild
working-directory: example-expo
run: bunx expo prebuild --clean --no-install --platform ios
- - name: Cache native build outputs # after prebuild, which regenerates ios/
+ - name: Cache native build outputs
uses: actions/cache@v4
with:
path: |
@@ -388,10 +346,10 @@ jobs:
xcrun simctl boot "$udid"
xcrun simctl bootstatus "$udid" -b
- name: e2e (ios-expo)
- timeout-minutes: 30 # a hung device run fails here, not at the job limit
+ timeout-minutes: 30
env:
E2E_TARGET: ios-expo
- AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS: '600000' # the first daemon start on a cold runner outlasts the 120 s default
+ AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS: '600000'
run: bun verify --e2e e2e
- uses: actions/upload-artifact@v4
if: failure()
@@ -401,17 +359,15 @@ jobs:
if-no-files-found: ignore
include-hidden-files: true
- uses: actions/upload-artifact@v4
- if: always() # e2e retries once; keep traces of retried and failed attempts
+ if: always()
with:
name: verify-artifacts-e2e-ios-expo
path: |
verify/artifacts/
verify/e2e/.e2e/
if-no-files-found: ignore
- include-hidden-files: true # verify/e2e/.e2e is a dot dir
+ include-hidden-files: true
- # The Expo app's Metro web export (react-native-web) and the web SDK, headless Chromium.
- # The runner exports the app in test mode and serves it (e2e.config.ts `command`).
e2e-web:
runs-on: ubuntu-latest
timeout-minutes: 15
@@ -423,7 +379,7 @@ jobs:
- run: bun install --frozen-lockfile
- run: bun install --frozen-lockfile
working-directory: example-expo
- - run: bun run prepare # the web app resolves the package through exports -> lib/ (browser condition)
+ - run: bun run prepare
- run: bunx e2e-web install chromium --with-deps
- run: bun verify --e2e e2e
env:
@@ -436,10 +392,10 @@ jobs:
verify/artifacts/
verify/e2e/.e2e/
if-no-files-found: ignore
- include-hidden-files: true # verify/e2e/.e2e is a dot dir
+ include-hidden-files: true
budget:
- needs: [static-fast, e2e-android-bare, e2e-ios-bare, e2e-android-expo, e2e-ios-expo, e2e-web] # every other job; extend when jobs are added
+ needs: [static-fast, e2e-android-bare, e2e-ios-bare, e2e-android-expo, e2e-ios-expo, e2e-web]
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
diff --git a/.gitignore b/.gitignore
index 84d2f30..3c7d885 100644
--- a/.gitignore
+++ b/.gitignore
@@ -89,3 +89,5 @@ android/generated
.superpowers/
verify/artifacts/
verify/e2e/.e2e/
+
+ios/RNOtel/PackageVersion.swift
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 32303fa..5573533 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -77,9 +77,14 @@ We follow the [conventional commits specification](https://www.conventionalcommi
We use [TypeScript](https://www.typescriptlang.org/) for type checking and [OXLint](https://oxc.rs/docs/guide/usage/linter.html) for linting and formatting the code.
-### Publishing to npm π§
+### Publishing to npm
-We use [changesets](https://github.com/changesets/changesets) for managing versions, though this is a manual process for now in the experimental phase.
+We use [changesets](https://github.com/changesets/changesets). Releases are manual:
+
+1. Add a changeset (`bunx changeset`) in your PR.
+2. To release, check that CI is green on `main`, then run `bun run version` on `main`
+ (bumps `package.json` and writes `CHANGELOG.md`), review and commit it.
+3. `bun run publish` (`changeset publish`) builds through `prepare` and publishes to npm.
### Scripts
diff --git a/README.md b/README.md
index 12c0062..86c8c5d 100644
--- a/README.md
+++ b/README.md
@@ -9,96 +9,171 @@ Best in class observability brought to React Native.
* **Telemetry without lock-in**. Send to **any OTLP compliant backend** including [vendors](https://opentelemetry.io/ecosystem/vendors/)
* [**Tracing** API](https://opentelemetry.io/docs/specs/otel/trace/api/)
-* [**Metrics** API](https://opentelemetry.io/docs/specs/otel/metrics/api/)
-* **Web**, **Android** (experimental) support with **iOS** coming soon
-* Automatic **fetch instrumentation**
-* Automatic **session tagging**
+* **One trace across JS and Native**, exported together
+* Context carried through `await`, promises and timers
+* **Web**, **Android** and **iOS** support
## Platform support
| Platform | Support |
| --- | --- |
| **web** | βοΈ Stable |
-| **android** | βοΈ Stable JS with experimental Native ποΈ |
-| **ios** | βοΈ Stable JS with planned Native π |
+| **android** | βοΈ Stable JS and Native |
+| **ios** | βοΈ Stable JS and Native |
+
+Requires React Native **0.88+** (New Architecture, Hermes), Xcode **27+** and Android minSdk **26**.
## Installation
```sh
-npm install react-native-open-telemetry
+npm install react-native-open-telemetry react-native-nitro-modules
+```
+
+**iOS** β add the core pod to your app target in `ios/Podfile`, then run `pod install`:
+
+```ruby
+pod 'ReactNativeOpenTelemetryCore', :path => '../node_modules/react-native-open-telemetry'
+```
+
+**Expo** β use the config plugin instead, it adds that line for you:
+
+```json
+{ "expo": { "plugins": ["react-native-open-telemetry"] } }
+```
+
+**Metro** β wrap the merged config, so context tracking starts before any of your code:
+
+```js
+const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config'); // Expo: expo/metro-config
+const {withOtel} = require('react-native-open-telemetry/metro');
+
+module.exports = withOtel(mergeConfig(getDefaultConfig(__dirname), {}));
+```
+
+On **Expo web**, also lower `async` in `babel.config.js`, otherwise spans lose their parent after `await`:
+
+```js
+module.exports = api => {
+ const web = api.caller(c => c?.platform === 'web');
+ return {
+ presets: ['babel-preset-expo'],
+ plugins: web ? ['@babel/plugin-transform-async-generator-functions', '@babel/plugin-transform-async-to-generator'] : [],
+ };
+};
```
## Usage
-### 1. Start the JS SDK
+### 1. Start the native SDK (recommended)
+
+Start in native code, before React Native, so you can trace from the very start of the app. It never throws: on bad config it logs an error and telemetry stays off.
+
+See OpenTelemetry's [Java](https://opentelemetry.io/docs/languages/java/api/#tracerprovider) and [Swift](https://opentelemetry.io/docs/languages/swift/) documentation for more information on available APIs.
+
+**Android**
+
+```kt
+import com.callstack.otel.RNOtel
+
+class MainApplication : Application(), ReactApplication {
+ override fun onCreate() {
+ super.onCreate()
-See OpenTelemetry's JS documentation on [Traces](https://opentelemetry.io/docs/languages/js/instrumentation/#acquiring-a-tracer) and [Metrics](https://opentelemetry.io/docs/languages/js/instrumentation/#acquiring-a-meter) for more information on available APIs.
+ // Start the SDK, before loadReactNative(this)
+ RNOtel.start(this) {
+ serviceName = "my-app"
+ serviceVersion = "1.0.0"
+ resourceAttributes = mapOf("deployment.environment.name" to "production")
+ export {
+ url = "https://my-collector.com:4318/v1/traces"
+ headers = mapOf("x-api-key" to KEY)
+ }
+ }
+
+ // Use available APIs
+ val span = RNOtel.tracer("native-scope-name").spanBuilder("native-work").startSpan()
+ span.end()
+ }
+}
+```
+
+**iOS**
+
+```swift
+import ReactNativeOpenTelemetryCore
+
+// AppDelegate, application(_:didFinishLaunchingWithOptions:), before React Native starts
+RNOtel.start { c in
+ c.serviceName = "my-app"
+ c.serviceVersion = "1.0.0"
+ c.export = .init(url: "https://my-collector.com:4318/v1/traces", headers: ["x-api-key": KEY])
+}
+```
+
+### 2. Start the JS SDK
+
+Call it in `index.js`, before the app is registered. When native already started, it attaches to it and `exportConfig` is ignored. Otherwise (web, or an Expo app without native code) it starts everything itself.
+
+See OpenTelemetry's JS documentation on [Traces](https://opentelemetry.io/docs/languages/js/instrumentation/#acquiring-a-tracer) for more information on available APIs.
```js
-import { openTelemetrySDK } from 'react-native-open-telemetry';
+import { trace } from '@opentelemetry/api';
+import { startReactNativeSdk } from 'react-native-open-telemetry';
// Start the SDK
-const sdk = openTelemetrySDK({
- debug: true,
- url: "https://my-collector.com:4317",
- name: "my-app",
- version: "1.0.0-alpha",
- environment: "development",
+startReactNativeSdk({
+ serviceName: 'my-app',
+ serviceVersion: '1.0.0',
+ resourceAttributes: { 'deployment.environment.name': 'production' },
+ exportConfig: { url: 'https://my-collector.com:4318/v1/traces', headers: { 'x-api-key': KEY } },
});
// Use available APIs
-const meter = sdk.metrics.getMeter("my-js-meter", "1.0");
-
-const promoCounter = meter.createCounter("my-promo-counter", {
- description: "A counter metric for my promo section"
-});
+const tracer = trace.getTracer('my-js-tracer', '1.0');
function App() {
- function onPress() {
- promoCounter.add(1);
+ async function onPress() {
+ await tracer.startActiveSpan('promo-press', async span => {
+ await fetchPromo(); // spans started in here keep their parent
+ span.end();
+ });
}
return
}
```
-### 2. Start the native SDK (optional) π§
+`url` is the OTLP/HTTP traces endpoint, used as given (no path is appended).
-> [!IMPORTANT]
-> This section is considered **highly experimental**.
-> There's currently no support for bidirectional JS/Native communication and the `native` feature flag only marks an API that will become available.
+### 3. Connect JS and Native spans (optional)
-**Android**
+Pass a W3C `traceparent` across your own native module. Parent the native span with `RNOtel.contextFrom(traceparent)`, or return `RNOtel.traceparentOf(span)` to JS to continue from native.
-See OpenTelemetry's Android documentation on [Traces](https://opentelemetry.io/docs/languages/java/api/#tracerprovider) and [Metrics](https://opentelemetry.io/docs/languages/java/api/#meterprovider) for more information on available APIs.
+```ts
+const { traceId, spanId, traceFlags } = span.spanContext();
+MyNative.doWork(`00-${traceId}-${spanId}-${traceFlags.toString(16).padStart(2, '0')}`);
+```
```kt
-import com.opentelemetry.OpenTelemetry
-
-class MainApplication : Application(), ReactApplication {
- override fun onCreate() {
- super.onCreate()
+RNOtel.tracer("my.module").spanBuilder("native.work").setParent(RNOtel.contextFrom(traceparent)).startSpan()
+```
- // Start the SDK
- OpenTelemetry.init(this) {
- debug = true
- url = "https://my-collector.com:4317"
- name = "my-app"
- version = "1.0.0"
- environment = "production"
- }
+## Try it locally
- // ..
+Run the official OpenTelemetry Collector with Jaeger:
- // Use available APIs
- val sdk = OpenTelemetry.get()
- val meter = sdk.getMeter("native-scope-name")
- val counter = meter.counterBuilder("native-counter").build()
- counter.add(14)
- }
-}
+```sh
+docker compose -f example/collector/docker-compose.yaml up
```
+Point `url` at `http://localhost:4318/v1/traces` (`10.0.2.2` on the Android emulator) and open Jaeger at http://localhost:16686.
+
+## Known limitations
+
+* Work batched through a shared queue (React's scheduler, debounce/throttle helpers) can get the wrong parent. Bind it yourself with `context.with(...)`.
+* `setInterval` ticks start a new trace.
+* **iOS** doesn't export span/link `flags`, `traceState` and the scope `schemaUrl`, and times are rounded to ~240 ns. Both come from [opentelemetry-swift](https://github.com/open-telemetry/opentelemetry-swift).
+
## Contributing
See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
diff --git a/ReactNativeOpenTelemetryCore.podspec b/ReactNativeOpenTelemetryCore.podspec
index f206f85..b39983e 100644
--- a/ReactNativeOpenTelemetryCore.podspec
+++ b/ReactNativeOpenTelemetryCore.podspec
@@ -2,9 +2,9 @@ require "json"
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
-# Pure Swift (R24): the core and the public `RNOtel` API, no Nitro and no C++ interop, so an app's Swift
-# `AppDelegate` can `import ReactNativeOpenTelemetryCore`. The Nitro adapter pod (ReactNativeOpenTelemetry) depends on it.
-# Autolinking links one podspec per package: apps add `pod 'ReactNativeOpenTelemetryCore', :path => ''`.
+File.write(File.join(__dir__, "ios/RNOtel/PackageVersion.swift"),
+ "let packageVersion = \"#{package["version"]}\"\n")
+
Pod::Spec.new do |s|
s.name = "ReactNativeOpenTelemetryCore"
s.version = package["version"]
@@ -19,19 +19,16 @@ Pod::Spec.new do |s|
s.source_files = ["ios/Core/**/*.swift", "ios/RNOtel/**/*.swift"]
- # `package` declarations are shared with the adapter pod through one Swift package name.
- # Test mode is a build flag, never API: `OTEL_TEST_MODE=1 pod install`.
s.pod_target_xcconfig = {
'OTHER_SWIFT_FLAGS' => '$(inherited) -package-name ReactNativeOpenTelemetry',
}.merge(ENV['OTEL_TEST_MODE'] == '1' ? { 'SWIFT_ACTIVE_COMPILATION_CONDITIONS' => '$(inherited) OTEL_TEST_MODE' } : {})
- # opentelemetry-swift 2.6 moved OpenTelemetryApi/OpenTelemetrySdk into opentelemetry-swift-core.
spm_dependency(s,
url: 'https://github.com/open-telemetry/opentelemetry-swift',
- requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' },
+ requirement: { kind: 'exactVersion', version: '2.6.0' },
products: ['OpenTelemetryProtocolExporterHTTP'])
spm_dependency(s,
url: 'https://github.com/open-telemetry/opentelemetry-swift-core',
- requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' },
+ requirement: { kind: 'exactVersion', version: '2.6.0' },
products: ['OpenTelemetrySdk'])
end
diff --git a/bun.lock b/bun.lock
index 7203dcc..1560deb 100644
--- a/bun.lock
+++ b/bun.lock
@@ -4,12 +4,12 @@
"": {
"name": "react-native-open-telemetry",
"dependencies": {
- "@opentelemetry/api": "~1.10.0",
- "@opentelemetry/core": "~3.1.1",
+ "@opentelemetry/api": "1.10.0",
+ "@opentelemetry/core": "3.1.1",
"@opentelemetry/exporter-trace-otlp-proto": "0.301.2",
- "@opentelemetry/resources": "~3.1.1",
- "@opentelemetry/sdk-trace": "~3.1.1",
- "@opentelemetry/semantic-conventions": "^1.45.0",
+ "@opentelemetry/resources": "3.1.1",
+ "@opentelemetry/sdk-trace": "3.1.1",
+ "@opentelemetry/semantic-conventions": "1.45.0",
},
"devDependencies": {
"@changesets/cli": "^2.28.1",
@@ -30,7 +30,7 @@
"typescript": "^5.8.3",
},
"peerDependencies": {
- "react-native": ">=0.79",
+ "react-native": ">=0.88",
"react-native-nitro-modules": "~0.37.0",
},
},
diff --git a/docs/superpowers/plans/2026-11-21-rn-otel-v0.md b/docs/superpowers/plans/2026-11-21-rn-otel-v0.md
index 3ae5e51..4d77bde 100644
--- a/docs/superpowers/plans/2026-11-21-rn-otel-v0.md
+++ b/docs/superpowers/plans/2026-11-21-rn-otel-v0.md
@@ -4,7 +4,7 @@
**Goal:** Ship the v0 vertical slice of `react-native-open-telemetry`: SDK set up on iOS, Android and web, JS spans exported through the native pipeline with correct nesting, all proven by an exact-output verification pipeline.
-**Architecture:** JS spans live in stock `@opentelemetry/sdk-trace`; on end, one sync Nitro call hands each span (as a one-element array) to a pure Kotlin/Swift core that converts it off the JS thread to otel-java / opentelemetry-swift `SpanData` and exports OTLP. Context propagates through a runtime patch of `Promise.prototype.then` and timers. Web uses the upstream browser SDK with the same context manager. Every guarantee is a named scenario whose exporter output is compared exactly to a reviewed OTLP/JSON file and to a reviewed shape file.
+**Architecture:** JS spans live in stock `@opentelemetry/sdk-trace`; on end, one sync Nitro call hands each span (as a one-element array) to a Kotlin/Swift core that converts it off the JS thread to otel-java / opentelemetry-swift `SpanData` and exports OTLP. Context propagates through a runtime patch of `Promise.prototype.then` and timers. Web uses the upstream browser SDK with the same context manager. Every guarantee is a named scenario whose exporter output is compared exactly to a reviewed OTLP/JSON file and to a reviewed shape file.
**Tech Stack:** TypeScript, `@opentelemetry/api` 1.10, OTel JS 3.1.x (`sdk-trace`), `@opentelemetry/browser-sdk`, Nitro Modules 0.37.x, Kotlin + otel-java, Swift + opentelemetry-swift 2.6, Jest + `@react-native/babel-preset`, JUnit, XCTest, `e2e` 0.24.0 (agent-device / Playwright), Bun for scripts, GitHub Actions.
@@ -12,18 +12,18 @@
## Global Constraints
-- RN New Architecture only, Hermes. Minimum RN **0.79** (OTel JS 3.x needs Metro β₯ 0.81.3); Nitro needs RN β₯ 0.75; Xcode β₯ 16.4; NDK β₯ 27.
+- RN New Architecture only, Hermes. Minimum RN **0.79** (OTel JS 3.x needs Metro β₯ 0.81.3); Nitro needs RN β₯ 0.75; Xcode β₯ 27.0 (opentelemetry-swift 2.6 dependencies need Swift 6.4); NDK β₯ 27.
- `@opentelemetry/api` 1.10; OTel JS stable 3.1.x / experimental 0.301.x; use `@opentelemetry/sdk-trace`, never `sdk-trace-base` / `sdk-trace-web`. Runtime code imports only the stable `@opentelemetry/semantic-conventions` entry; incubating keys are inlined.
- Native SDKs: otel-java (stable) directly, **not** opentelemetry-android; opentelemetry-swift 2.6 via SwiftPM (`spm_dependency` in the podspec).
- `react-native-nitro-modules` 0.37.x is a **peer** dependency with a pinned range.
- The Nitro spec uses only OTel-neutral shapes: no `io.opentelemetry.*`, no Swift OTel types, no callbacks or event emitters (`tsc` enforces the first two).
-- Package `react-native-open-telemetry`; subpaths `/metro`, `/vite`; entry function `startReactNativeSdk` on mobile and web, returning `{ tracerProvider, forceFlush, shutdown }`. No other public JS API in v0.
+- Package `react-native-open-telemetry`; subpath `/metro`; entry function `startReactNativeSdk` on mobile and web, returning `{ tracerProvider, forceFlush, shutdown }`. No other public JS API in v0.
- The SDK never throws into the app: bad config, init failure or a missing native module β one `console.error` and a no-op handle.
- Times cross the seam as `HrTime` `[seconds, nanos]`. Numbers become OTLP `intValue` iff `Number.isInteger(v)` (same rule on JS, Kotlin, Swift).
- Custom names only under `com.callstack.*`; nothing under `otel.*`; semantic conventions first; `schemaUrl` set on tracers. SDK identity: `telemetry.distro.name` / `telemetry.distro.version`.
- Default sampler `ParentBased(AlwaysOn)` on both sides, honoring `traceFlags`.
- One resource, owned by native on mobile; JS adds no `telemetry.sdk.*`. The degraded flag is a scope attribute of the JS tracers.
-- Endpoint: base URL; `/v1/traces` appended unless already present; same rule on Android, iOS and web.
+- Endpoint: the OTLP/HTTP traces URL, used as given; same rule on Android, iOS and web.
- JS-thread work in `handOff` is marshalling and enqueueing only. Background flush never blocks the main thread (Android async; iOS inside a background task).
- Android native init runs only in the main process.
- Test mode is a **build flag**, never public API: JS `process.env.OTEL_TEST_MODE === '1'` inlined at bundle time; Android Gradle property `otelTestMode=true`; iOS `OTEL_TEST_MODE=1` at `pod install` (adds a Swift compilation condition). When on: JS IDs `0aβ¦`, native IDs `0bβ¦`, resource built from config only (no `telemetry.*`). Scenarios use explicit whole-Β΅s timestamps from base **1767225600000000000 ns** (2026-01-01T00:00:00Z).
@@ -34,7 +34,7 @@
## Review Focus
1. **Odd attribute values from JS** (`NaN`, `Infinity`, `-0`, integers above 2^53, empty arrays, mixed arrays after upstream sanitizing): the seam never crashes; values reach OTLP as upstream JS would encode them. Pinned by fixture `odd-attributes` (Tasks 8, 15, 18).
-2. **Endpoint written in different forms** (`http://host:4318`, trailing `/`, already ending in `/v1/traces`): spans go to exactly one `/v1/traces` URL, on Android, iOS and web. Pinned in Tasks 16, 19, 21.
+2. **Endpoint**: spans go to `url` exactly as given, on Android, iOS and web; no path is appended. Pinned in Tasks 16, 19, 21.
3. **App backgrounded right after work**: handed-off spans are exported without `flush()`; no main-thread block. Pinned by `background-flush` (Task 27).
4. **`startReactNativeSdk` called twice** (fast refresh re-runs `index.js`) or with config while native already initialized: second call returns the first handle with one warning; native config wins with one warning. Pinned in Task 14.
5. **Malformed `traceparent` passed to the native helper**: the span starts as a root, nothing throws. Pinned in Tasks 17 and 20.
@@ -72,22 +72,18 @@ src/
context/RNContextManager.ts extends StackContextManager, adds swap()
context/patch.ts then/timer wrappers, ROOT fast path, setInterval in ROOT, idempotency marker
context/probe.ts await probe, degraded scope attribute
- setup.ts module injected first by the Metro/Vite helpers
+ setup.ts module injected first by the Metro helper
handoff/toSeamSpan.ts ReadableSpan -> SeamSpan
handoff/NativeHandOffProcessor.ts
internal/testMode.ts OTEL_TEST_MODE flag, sequentialIds(prefix)
native/Otel.nitro.ts Nitro spec (seam types)
native/otel.ts HybridObject accessor
metro/index.js withOtel(metroConfig) (subpath /metro)
-vite/index.ts withOtel(viteConfig) (subpath /vite)
nitro.json, nitrogen/generated/
-android/src/core/kotlin/com/callstack/otel/core/ pure Kotlin core
+android/src/main/java/com/callstack/otel/core/ Kotlin core (reads Nitro's seam structs)
android/src/main/java/com/callstack/otel/ Nitro adapter, RNOtel public API
-android/core-jvm/ JVM-only Gradle project over src/core (tests)
ios/Core/ pure Swift core
ios/Adapter/ Nitro adapter, RNOtel public API
-ios/CoreTests/ XCTest over ios/Core
-Package.swift SwiftPM for ios/Core + tests
ReactNativeOpenTelemetry.podspec
verify/
harness/collector.ts fake collector (server + control API)
@@ -95,14 +91,12 @@ verify/
harness/normalize.ts merge + sort, never rewrite
harness/compare.ts structured diff, expected(), update mode
harness/shape.ts shapeOf + compare to .shape.json
- harness/fixtureJson.ts {"$num": ...} encode/decode
harness/scenario.ts scenario(), at(), registry
harness/proto/ vendored opentelemetry-proto at a pinned tag
stages/*.ts one file per `bun verify` stage (auto-discovered)
scenarios/*.ts one per guarantee
- fixtures/*.handoff.json seam contract: SeamSpan payloads (generated, reviewed)
expected/*.shape.json, expected/*.otlp.json
- jest/ Jest projects (scenarios, fixtures, degraded)
+ jest/ Jest projects (scenarios, hand-off processor)
e2e/e2e.config.ts, e2e/*.e2e.ts, e2e/harness.ts
compliance/ official Collector replay
run.ts `bun verify`
@@ -129,7 +123,7 @@ CODEOWNERS
- Produces: `bun verify` (runs every `verify/stages/*.ts` in name order; each exports `{ name, order, e2e?: boolean, run(ctx) }`; flags `--e2e`, `--update`); `bun run static`; Jest root config with projects under `verify/jest/`.
- `package.json`:
- keeps `"prepare": "bob build"` and appends `&& (git config core.hooksPath .githooks || true)`;
- - `exports`: `"."`, `"./metro"`, `"./vite"`, `"./setup"`, `"./package.json"`; `files`: `lib`, `src`, `nitrogen`, `android` (minus build dirs), `ios`, `Package.swift`, `ReactNativeOpenTelemetry.podspec`, `nitro.json`, `metro`, `vite`;
+ - `exports`: `"."`, `"./metro"`, `"./setup"`, `"./package.json"`; `files`: `lib`, `src`, `nitrogen`, `android` (minus build dirs), `ios`, `ReactNativeOpenTelemetry.podspec`, `nitro.json`, `metro`;
- drops all old deps; adds **every Phase 0β1 dependency now**: `@opentelemetry/api@1.10.x`, `@opentelemetry/sdk-trace@3.1.x`, `@opentelemetry/core@3.1.x`, `@opentelemetry/resources@3.1.x`, `@opentelemetry/semantic-conventions`, `@opentelemetry/browser-sdk` (exact, pre-1.0), dev: `@opentelemetry/exporter-trace-otlp-http@0.301.x`, `jest`, `babel-jest`, `@react-native/babel-preset`, `protobufjs`, `e2e@0.24.0`, `nitrogen@~0.37.0`; peer `react-native-nitro-modules@~0.37.0`.
- `packContents(list: string[]): string[]` returns required paths missing from `npm pack --dry-run --json` output.
- `.githooks/pre-commit` runs `bun run static`. `CODEOWNERS`: `/verify/ @adhorodyski`.
@@ -252,7 +246,7 @@ export interface Otel extends HybridObject<{ ios: 'swift'; android: 'kotlin' }>
**Files:** Modify `.github/workflows/ci.yml`.
- One workflow for everything (later tasks add e2e jobs to it). `concurrency: { group: ci-${{ github.ref }}, cancel-in-progress: true }`.
-- Jobs: `static-fast` on `ubuntu-latest` (Bun, Java 17, `bun verify`); `fast-swift` on `macos-15` with a pinned Xcode (`swift test` via `bun verify`, a no-op until Task 18). Every job sets `timeout-minutes`. Upload `verify/artifacts/` on failure.
+- Jobs: `static-fast` on `ubuntu-latest` (Bun, Java 17, `bun verify`). Every job sets `timeout-minutes`. Upload `verify/artifacts/` on failure.
- PR budget: final job `budget` with `needs:` on every other job and `if: always()`; compares the run's `created_at` (from `github.event` / `gh api`) to now and fails when over `PR_BUDGET_MINUTES` (repo variable; until set, it only prints the duration).
- [ ] Steps: open a PR β jobs green; break `smoke-js` β PR red with the structured diff in the log; restore. Commit `ci: static and fast jobs with PR budget`.
@@ -262,14 +256,13 @@ The riskiest integration is proven here, before lanes fan out.
**Files:**
- Create: `example/` with `@react-native-community/cli init` at the latest stable RN (bundle id `opentelemetry.example`, app name `OpenTelemetryExample`), `example/src/ScenariosScreen.tsx`, `android/src/main/java/com/callstack/otel/HybridOtel.kt` (stub), `ios/Adapter/HybridOtel.swift` (stub), `ReactNativeOpenTelemetry.podspec`, `verify/e2e/{e2e.config.ts,harness.ts,scenarios.e2e.ts,tracer-bullet.e2e.ts}`, `verify/stages/e2e.ts`
-- Modify: `android/build.gradle` (otel-java BOM + `opentelemetry-sdk` + `opentelemetry-exporter-otlp`; force-align OkHttp with RN's), `example/metro.config.js` (`watchFolders` includes `verify/` and the repo root), `.github/workflows/ci.yml` (jobs `e2e-android-bare`, `e2e-ios-bare`), `verify/stages/static.ts` (bundle-size check)
+- Modify: `android/build.gradle` (otel-java BOM + `opentelemetry-sdk` + `opentelemetry-exporter-otlp`; force-align OkHttp with RN's), `example/metro.config.js` (`watchFolders` includes `verify/` and the repo root), `.github/workflows/ci.yml` (jobs `e2e-android-bare`, `e2e-ios-bare`)
**Interfaces:**
- Stubs link the real native dependencies: `HybridOtel.initialize` returns `{ alreadyInitialized: false, testMode: }`; `handOff(spans)` logs one line `RNOtel handOff spans= attrs= events= links=` and does nothing else; `flush` resolves.
- Podspec: `source_files` `ios/Core/**/*.swift`, `ios/Adapter/**/*.swift`, `nitrogen/generated/ios/**`; `spm_dependency(s, url: 'https://github.com/open-telemetry/opentelemetry-swift', requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' }, products: ['OpenTelemetrySdk', 'OpenTelemetryProtocolExporterHTTP'])`; when `ENV['OTEL_TEST_MODE'] == '1'` add `SWIFT_ACTIVE_COMPILATION_CONDITIONS => 'OTEL_TEST_MODE'`. Android reads Gradle property `otelTestMode` into `BuildConfig.OTEL_TEST_MODE` of the library.
- Scenarios screen: one button per scenario, `testID="scenario-"`; on press runs the scenario with the same provider setup as the Jest runner (Phase 1: **JS-direct export** to the collector), calls `forceFlush()`, then renders `testID="scenario-done"`. A hidden button `testID="tracer-bullet-handoff"` calls `getOtel()!.handOff(decodeFixture(rich-span fixture).spans)`. Collector host: `10.0.2.2` on Android, `localhost` elsewhere. Example Babel config inlines `OTEL_TEST_MODE`; e2e builds set it to `1` (and `otelTestMode=true`, `OTEL_TEST_MODE=1 pod install`). Android network config allows cleartext to `10.0.2.2`; iOS `NSAllowsLocalNetworking`.
- `verify/e2e/e2e.config.ts` targets `android-bare` (`mobile({ platform: 'android' })`, `bundleId: 'opentelemetry.example'`) and `ios-bare` (`mobile({ platform: 'ios' })`). `harness.ts`: worker fixture starting the collector once; `platformOf(targetName)` = prefix before `-`; `expectScenario(name, target)`. Until Tasks 24/25 the device runs compare to the **`.js`** expected files.
-- Bundle-size check: `react-native bundle` of the example in release mode; the SDK's share (modules under the package and `@opentelemetry/*`) must stay within 10% of `verify/static/bundle-baseline.json`.
- CI e2e jobs: Release builds with the JS bundle embedded (no Metro); cache native build outputs keyed on `android/`, `ios/`, `nitrogen/`, `example/{android,ios}` and lockfiles, reusing the binary when only JS changed; Android on `ubuntu-latest` with KVM and a cached AVD snapshot; iOS on `macos-15` with a pinned Xcode; `retries: 1` with artifacts uploaded on retry.
- [ ] **Step 1:** Write `tracer-bullet.e2e.ts`: tap `tracer-bullet-handoff`, read device logs, expect `RNOtel handOff spans=1 attrs=β¦` with the counts of the `rich-span` fixture; and `scenarios.e2e.ts` running `smoke-js` against `smoke-js.js.otlp.json`. Run `bun verify --e2e` β FAIL (no app).
- [ ] **Step 2: Implement** app, stubs, podspec, Gradle, config, harness, CI jobs.
@@ -279,6 +272,9 @@ The riskiest integration is proven here, before lanes fan out.
### Task 8: Seam conversion and generated fixtures
+> Superseded during review: the host-side native replay (hand-off fixtures, `android/core-jvm`, `Package.swift` + `ios/CoreTests`, the fast-jvm and fast-swift stages) was removed. The device e2e compares every scenario against the same `*.android` / `*.ios` files.
+
+
**Files:**
- Create: `src/handoff/toSeamSpan.ts`, `src/handoff/NativeHandOffProcessor.ts`, `verify/jest/fixtures.test.ts`, scenarios `verify/scenarios/{handoff-basic,rich-span,odd-attributes}.ts` with `.shape.json`, `verify/fixtures/{handoff-basic,rich-span,odd-attributes,nest-after-await}.handoff.json` (generated)
@@ -305,7 +301,7 @@ The riskiest integration is proven here, before lanes fan out.
- Create: `verify/scenarios/*.ts` and `verify/expected/*.shape.json` for every scenario below (bodies `pending` where a lane fills them), `verify/VERIFY.md`, `CLAUDE.md` pointer line.
- Scenario names (the guarantee IDs), owning task in brackets:
- - L1: `nest-after-await`, `nest-timers-microtasks`, `nest-promise-all-race`, `concurrent-interleaved`, `root-no-leak`, `captured-then`, `async-generator`, `error-in-callback`, `never-settling-promise`, `interval-new-root`, `batching-shared-queue` [10]; `degraded-probe` [11]; `interaction-manager`, `event-emitter-listener` (runner `e2e` only) [13]
+ - L1: `nest-after-await`, `nest-timers-microtasks`, `nest-promise-all-race`, `concurrent-interleaved`, `root-no-leak`, `captured-then`, `async-generator`, `error-in-callback`, `never-settling-promise`, `interval-new-root`, `batching-shared-queue` [10]; `interaction-manager`, `event-emitter-listener` (runner `e2e` only) [13]
- Seam: `handoff-basic`, `rich-span`, `odd-attributes` [8, 15, 18]
- L3/L4: `export-headers` [16, 19]
- Phase 2: `cross-js-to-native`, `cross-native-to-js` [26]; `collector-down`, `native-init-failure`, `flush-after-reload`, `background-flush`, `fast-refresh-idempotent` [27]; `smoke-device`, `perf-budget` [29]
@@ -343,15 +339,12 @@ const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return
### Task 11: Startup probe and degraded flag
**Files:**
-- Create: `src/context/probe.ts`, `verify/jest/jest.degraded.config.js` (Babel config that keeps native `async`)
-- Modify: scenario `degraded-probe`
+- Create: `src/context/probe.ts`, `src/context/__tests__/probe.test.ts`
**Interfaces:**
- `probeAsyncContext(): Promise`; `DEGRADED_ATTR = 'com.callstack.context.degraded'`. When the probe fails: `console.error` once naming the cause (native `await` not downleveled), and tracers obtained from the SDK carry scope attribute `DEGRADED_ATTR: true` (Task 14 wires the provider; here export `scopeAttributes(): Attributes`).
-- [ ] **Step 1:** Un-pend; Jest project `degraded` runs only `degraded-probe` with async preserved; `bun verify` β FAIL.
-- [ ] **Step 2:** Unit test `probe resolves true when then is patched and false when async is native`.
-- [ ] **Step 3: Implement.**
-- [ ] **Step 4:** Draft and review `degraded-probe.js.otlp.json` (scope has `com.callstack.context.degraded: true`; spans after `await` are roots, never wrongly parented).
+- [ ] **Step 1:** Unit test `probe resolves true when then is patched and false when async is native` (a native-`async` step built with `new Function`, so Babel cannot lower it) β FAIL.
+- [ ] **Step 2: Implement** β PASS.
- [ ] **Step 5: Commit** `feat(context): startup probe and degraded scope attribute`.
### Task 12: Metro helper
@@ -389,7 +382,7 @@ const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return
**Interfaces:**
- Consumes: `getOtel`, `NativeHandOffProcessor`, `contextManager` from `setup.ts`, `probeAsyncContext`/`scopeAttributes`, `isTestModeBuild`, `sequentialIds`.
-- Produces: `startReactNativeSdk(config?: SdkConfig): SdkHandle`; `SdkHandle = { tracerProvider: TracerProvider; forceFlush(): Promise; shutdown(): Promise }`; `SdkConfig = { serviceName?: string; serviceVersion?: string; resourceAttributes?: Attributes; exportConfig?: { url: string; headers?: Record }; spanProcessors?: SpanProcessor[] }`; `tracesUrl(url: string): string` in `config.ts` (shared with web).
+- Produces: `startReactNativeSdk(config?: SdkConfig): SdkHandle`; `SdkHandle = { tracerProvider: TracerProvider; forceFlush(): Promise; shutdown(): Promise }`; `SdkConfig = { serviceName?: string; serviceVersion?: string; resourceAttributes?: Attributes; exportConfig?: { url: string; headers?: Record }; spanProcessors?: SpanProcessor[] }`.
- Behaviour:
- `getOtel()` undefined (Expo Go, misconfigured build) β `console.error` once, return no-op handle.
- `result = native.initialize(config ? toSeamConfig(config) : undefined)`. `alreadyInitialized` β attach; warn once if `exportConfig` was passed. `error` β `console.error(error)` once, return no-op handle.
@@ -407,6 +400,9 @@ const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return
### Task 15: JVM project, seam span β SpanData, export
+> Superseded during review: the host-side native replay (hand-off fixtures, `android/core-jvm`, `Package.swift` + `ios/CoreTests`, the fast-jvm and fast-swift stages) was removed. The device e2e compares every scenario against the same `*.android` / `*.ios` files.
+
+
**Files:**
- Create: `android/core-jvm/{settings.gradle.kts,build.gradle.kts}` (`sourceSets.main.kotlin.srcDir("../src/core/kotlin")`, tests in `android/core-jvm/src/test/kotlin`), `android/src/core/kotlin/com/callstack/otel/core/{SeamModel.kt,JsSpanData.kt,Attributes.kt,OtelCore.kt,FixtureJson.kt}`, `android/core-jvm/src/test/kotlin/FixtureExportTest.kt`, `verify/stages/fast-jvm.ts`
@@ -427,8 +423,8 @@ const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return
- Modify: scenario `export-headers`
**Interfaces:**
-- `data class CoreConfig(serviceName, serviceVersion?, resourceAttributes: Attributes, exportUrl: String, exportHeaders: Map)`; `fun tracesUrl(exportUrl: String): String` β trims trailing `/`, appends `/v1/traces` unless already present; `OtelCore.initialize` idempotent (second call returns `alreadyInitialized`); invalid URL β error result, never an exception; resource adds `telemetry.distro.name = "react-native-open-telemetry"` and `telemetry.distro.version` outside test mode; sampler `ParentBased(AlwaysOn)`; `BatchSpanProcessor` with OTLP/HTTP protobuf exporter.
-- [ ] **Step 1: Write failing tests**: `tracesUrl` for `http://h:4318`, `http://h:4318/`, `http://h:4318/v1/traces` β all `http://h:4318/v1/traces` (Review Focus 2); `initialize twice keeps the first config`; `invalid url returns an error`; `export-headers`: collector `headers.json` contains `x-api-key: test`.
+- `data class CoreConfig(serviceName, serviceVersion?, resourceAttributes: Attributes, exportUrl: String, exportHeaders: Map)`; `exportUrl` is the traces endpoint, used as given; `OtelCore.initialize` idempotent (second call returns `alreadyInitialized`); invalid URL β error result, never an exception; resource adds `telemetry.distro.name = "react-native-open-telemetry"` and `telemetry.distro.version` outside test mode; sampler `ParentBased(AlwaysOn)`; `BatchSpanProcessor` with OTLP/HTTP protobuf exporter.
+- [ ] **Step 1: Write failing tests**: `initialize twice keeps the first config`; `invalid url returns an error`; `export-headers`: collector `headers.json` contains `x-api-key: test`.
- [ ] **Step 2β4:** FAIL β implement β PASS.
- [ ] **Step 5: Commit** `feat(android-core): config, endpoint and headers`.
@@ -447,6 +443,9 @@ const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return
### Task 18: SwiftPM package, seam span β SpanData, export
+> Superseded during review: the host-side native replay (hand-off fixtures, `android/core-jvm`, `Package.swift` + `ios/CoreTests`, the fast-jvm and fast-swift stages) was removed. The device e2e compares every scenario against the same `*.android` / `*.ios` files.
+
+
**Files:**
- Create: `Package.swift` (target `OtelCore` at `ios/Core`, test target `OtelCoreTests` at `ios/CoreTests`, dependency opentelemetry-swift `2.6.x`), `ios/Core/{SeamModel.swift,SpanDataBuilder.swift,Attributes.swift,OtelCore.swift,FixtureJson.swift}`, `ios/CoreTests/FixtureExportTests.swift`, `verify/stages/fast-swift.ts`
@@ -458,7 +457,7 @@ const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return
- [ ] **Step 5: Commit** `feat(ios-core): seam spans exported through opentelemetry-swift`.
### Task 19: Swift core config and `export-headers`
-Mirror Task 16 in `ios/Core/{CoreConfig.swift,Endpoint.swift}`; test mode via `#if OTEL_TEST_MODE` in the adapter only, the core takes `testMode: Bool`; same tests including `tracesUrl` (Review Focus 2), invalid URL β error, distro attributes, `export-headers`. Commit `feat(ios-core): config, endpoint and headers`.
+Mirror Task 16 in `ios/Core/{CoreConfig.swift,Endpoint.swift}`; test mode via `#if OTEL_TEST_MODE` in the adapter only, the core takes `testMode: Bool`; same tests: invalid URL β error, distro attributes, `export-headers`. Commit `feat(ios-core): config, endpoint and headers`.
### Task 20: Swift parenting helper
Mirror Task 17 in `ios/Core/Parenting.swift`: `contextFrom(traceparent:)`, `traceparent(of:)`, same tests including malformed input (Review Focus 5). Commit `feat(ios-core): explicit parenting helper`.
@@ -471,26 +470,26 @@ Mirror Task 17 in `ios/Core/Parenting.swift`: `contextFrom(traceparent:)`, `trac
- Create: `src/sdk/start.web.ts`, test
**Interfaces:**
-- Same signature and handle as Task 14. Calls `startBrowserSdk` with `serviceName`, `serviceVersion`, `resourceAttributes`, `exportConfig: { url: tracesUrl(url), headers }` (check in browser-sdk source whether it appends the signal path; pass whatever makes the request hit exactly one `/v1/traces`), `spanProcessors`; then re-registers our `contextManager` so it wins over any manager the browser SDK installs. Missing `exportConfig` β `console.error` once and no-op handle. Test mode (`isTestModeBuild()`): `0a` IDs.
-- [ ] **Step 1: Write failing tests** (jsdom): `our context manager is the global one after start`; `url forms all export to one /v1/traces` (Review Focus 2); `missing exportConfig returns a no-op handle`; `second call returns the first handle with one warning`.
+- Same signature and handle as Task 14. Calls `startBrowserSdk` with `serviceName`, `serviceVersion`, `resourceAttributes`, `exportConfig: { url, headers }` (the request hits `url` as given), `spanProcessors`; then re-registers our `contextManager` so it wins over any manager the browser SDK installs. Missing `exportConfig` β `console.error` once and no-op handle. Test mode (`isTestModeBuild()`): `0a` IDs.
+- [ ] **Step 1: Write failing tests** (jsdom): `our context manager is the global one after start`; `exports to the url as given, with the headers` (Review Focus 2); `missing exportConfig returns a no-op handle`; `second call returns the first handle with one warning`.
- [ ] **Step 2β4:** FAIL β implement β PASS.
- [ ] **Step 5: Commit** `feat(web): startReactNativeSdk over the browser SDK`.
-### Task 22: Vite helper
+### Task 22: Async lowering on Expo web
**Files:**
-- Create: `vite/index.ts`, test
+- Modify: `example-expo/babel.config.js`, `example-expo/metro.config.js`, `example-expo/package.json` (react-dom, react-native-web, @expo/metro-runtime)
**Interfaces:**
-- `withOtel(config: UserConfig): UserConfig` β sets `esbuild.supported['async-await'] = false`, `optimizeDeps.esbuildOptions.supported['async-await'] = false`, and injects `react-native-open-telemetry/setup` before the app entry via a tiny plugin (`transformIndexHtml`). webpack is deferred (spec Β§7).
-- [ ] **Step 1: Write failing tests**: output contains the flags and plugin; existing user values kept; idempotent.
-- [ ] **Step 2β4:** FAIL β implement β PASS.
-- [ ] **Step 5: Commit** `feat(web): Vite helper`.
+- `babel-preset-expo` keeps native `async` on web; for the web platform the app adds `@babel/plugin-transform-async-to-generator` and `@babel/plugin-transform-async-generator-functions` (spec Β§7). The Metro resolver maps `react-native-nitro-modules` to a stub on web (no HybridObjects).
+- [ ] **Step 1:** `expo export -p web` without the plugins: the bundle has native `async` (the probe fails).
+- [ ] **Step 2:** Add the plugins; the exported bundle has no native `async`.
+- [ ] **Step 3: Commit** `feat(web): Expo web export with async lowered`.
### Task 23: Web e2e target
**Files:**
-- Modify: `example/web/*` (Vite app using `withOtel`, same scenarios screen through react-native-web, `define` sets `process.env.OTEL_TEST_MODE`), `verify/e2e/e2e.config.ts` (target `web`, `web({ browser: 'chromium' })`, `app.url` from the Vite preview server via the config's `command`), `.github/workflows/ci.yml` (job `e2e-web`)
+- Modify: `example-expo/package.json` (`web:e2e`: `expo export -p web` in test mode, then `expo serve`), `verify/e2e/e2e.config.ts` (target `web`, `web({ browser: 'chromium' })`, `app.url` from `expo serve` via the config's `command`), `.github/workflows/ci.yml` (job `e2e-web`)
- Create: `verify/expected/*.web.otlp.json` (drafted with `VERIFY_UPDATE=1`, shape must match, author review)
- [ ] **Step 1:** Add `web` target; `bun verify --e2e` β FAIL (no expected files).
- [ ] **Step 2:** Draft web expected files; **author review**.
@@ -510,7 +509,7 @@ Mirror Task 17 in `ios/Core/Parenting.swift`: `contextFrom(traceparent:)`, `trac
**Interfaces:**
- `RNOtel.start(context: Context, block: RNOtelConfig.() -> Unit)` β no-op outside the main process (compares `Application.getProcessName()` to package name); exporter constructed lazily on the export executor, not in `onCreate`; `RNOtel.tracer(name: String, version: String? = null): Tracer`; `RNOtel.contextFrom(traceparent)`, `RNOtel.traceparentOf(span)`. Test mode comes from the library's `BuildConfig.OTEL_TEST_MODE`; no testing API.
- `HybridOtel` maps seam β core 1:1; `handOff` copies the structs and enqueues, no conversion on the JS thread; `flush` resolves on a background thread; background flush on `ProcessLifecycleOwner` `ON_STOP`, asynchronous (never `join()` on the main thread).
-- Example `MainApplication.onCreate`: `RNOtel.start(this) { serviceName = "verify"; serviceVersion = "0.0.0"; export { url = "http://10.0.2.2:4318" } }`.
+- Example `MainApplication.onCreate`: `RNOtel.start(this) { serviceName = "verify"; serviceVersion = "0.0.0"; export { url = "http://10.0.2.2:4318/v1/traces" } }`.
- [ ] **Step 1:** Point `android-bare` at `android` files; `bun verify --e2e` β FAIL.
- [ ] **Step 2: Implement.**
- [ ] **Step 3: Run** β every JS scenario on `android-bare` equals the files the Kotlin core produced in Task 15. Measure cold start before/after `RNOtel.start` once (`adb shell am start -W`), record in `VERIFY.md`.
@@ -587,14 +586,18 @@ Mirror Task 24: `ios/Adapter/{HybridOtel.swift,RNOtel.swift,RNOtelConfig.swift}`
**Files:** Create `.github/workflows/scheduled.yml`.
- Nightly: e2e on RN **0.79** and latest (regenerate `example` per version in CI); fast loop + e2e with `@opentelemetry/*`, otel-java and opentelemetry-swift bumped to latest; `npm pack` β install the tarball into a fresh bare app and a fresh Expo app β run `smoke-device`. Marks the commit with a `nightly` status check on success.
+ > Superseded during review: no scheduled or post-merge matrix. The minimum React Native is 0.88, the version every PR tests.
- [ ] Steps: `workflow_dispatch` dry run green. Commit `ci: nightly matrix`.
### Task 32: Release flow, migration and docs
**Files:** Create `.github/workflows/release.yml`, `MIGRATION.md`, a major changeset; modify `README.md`.
- Release: changesets publishes to dist-tag `next` only from `main` commits whose CI is green; a manual `promote` job moves the version to `latest` only if that commit has a green `nightly` status.
-- `MIGRATION.md`: from the published 0.x (session tracking, metrics, fetch instrumentation and the old init API are removed in v0; what replaces each, or that it returns in v1).
-- `README.md`: install (bare and Expo), native-first init, JS fallback, `withOtel` for Metro and Vite, endpoint rule, the context guarantees and their documented exceptions (Β§6.2), link to `VERIFY.md`.
+ > Superseded during review: no release workflow; releases stay manual with changesets as on `main`.
+- `MIGRATION.md`: from the published 0.x.
+ > Superseded during review: no migration guide while the package is pre-v1; the README covers v0 as is.
+- `README.md`: install (bare and Expo), native-first init, JS fallback, `withOtel` for Metro, async lowering on Expo web, endpoint rule, the context guarantees and their documented exceptions (Β§6.2), link to `VERIFY.md`.
+ > Superseded during review: the README keeps its original structure and voice, extended only where v0 changed it.
- [ ] Steps: dry-run the release workflow; confirm a red commit can't publish to `next`. Commit `chore: release flow, migration guide and README for v0`.
---
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 d68557e..f5a825a 100644
--- a/docs/superpowers/specs/2026-11-10-rn-otel-design.md
+++ b/docs/superpowers/specs/2026-11-10-rn-otel-design.md
@@ -63,20 +63,19 @@ nesting**, to a collector β on iOS, Android and web.
## 3. Constraints and context
- RN New Architecture, Hermes. Research was done against RN 0.84β0.88 / Hermes V1.
- Minimum supported RN version: builder's choice, but upstream OTel JS 3.x requires
- Metro β₯ 0.81.3 (RN β₯ 0.79) for `package.json` `imports` resolution, and Nitro requires
- RN β₯ 0.75.
+ Minimum supported RN version: **0.88**, the version every PR tests (decided). No older
+ React Native is tested.
- Upstream versions at time of writing: `@opentelemetry/api` 1.10, OTel JS stable 3.1.x /
experimental 0.301.x (`@opentelemetry/sdk-trace` replaced `sdk-trace-base`/`-web` in 3.0),
`@opentelemetry/browser-sdk` (lives in `open-telemetry/opentelemetry-browser`, pre-1.0),
otel-java (stable), opentelemetry-swift 2.6.
-- Nitro Modules 0.37.x (pre-1.0). Requires Xcode β₯ 16.4, NDK β₯ 27. Pin the supported range
+- Nitro Modules 0.37.x (pre-1.0). Requires Xcode β₯ 27.0 (the opentelemetry-swift 2.6 dependencies need Swift 6.4), NDK β₯ 27. Pin the supported range
and document it; `react-native-nitro-modules` is a peer dependency the app installs.
- Bare RN and Expo must both work. Expo config plugins only run in `expo prebuild`, so
nothing essential may depend on a plugin.
- opentelemetry-swift appears to be distributed via SwiftPM only (no podspec at repo
root β reported by a reviewer, builder to confirm). The pod must pull it via
- `spm_dependency` (RN β₯ 0.75) or vendor it; verify with Xcode 16.4, static frameworks and
+ `spm_dependency` (RN β₯ 0.75) or vendor it; verify with Xcode 27.0, static frameworks and
Nitro's Swift/C++ interop.
## 4. Architecture (decided)
@@ -101,8 +100,8 @@ flowchart TB
subgraph web["Web"]
direction TB
- jsw["JS: startBrowserSdk (upstream browser-sdk) + same ContextManager"]
- wexp["OTLP/HTTP fetch exporter (upstream)"]
+ jsw["JS: sdk-trace TracerProvider (7) + same ContextManager"]
+ wexp["OTLP/HTTP proto fetch exporter (upstream)"]
jsw --> wexp
end
@@ -114,8 +113,8 @@ flowchart TB
| Ours vs upstream | |
|---|---|
-| upstream, reused as-is | `@opentelemetry/api`, `sdk-trace`, browser-sdk, otel-java, opentelemetry-swift, exporters |
-| ours | ContextManager patch, hand-off processor, Nitro adapters, pure native core, bundler helpers |
+| upstream, reused as-is | `@opentelemetry/api`, `sdk-trace`, otel-java, opentelemetry-swift, exporters |
+| ours | ContextManager patch, hand-off processor, Nitro adapters, pure native core, Metro helper |
### 4.1 Where spans live (decided: "option C")
- **JS spans live in the stock JS SDK** (`@opentelemetry/sdk-trace` `TracerProvider`) on both
@@ -184,18 +183,19 @@ class NativeHandOffProcessor implements SpanProcessor {
```
### 4.2 Native core and the seam
-- A **pure Kotlin** module and a **pure Swift** module hold all native logic (span
- hand-off β `SpanData`, SDK setup, export config, the native parenting helper). They do
- not import React Native or Nitro. Nitro HybridObjects are thin adapters over them.
- **(Claude's call, required by the verification design.)**
-- Layout that works with autolinking (Claude's call, from review): shared sources, two
- build entry points.
- - Android: core sources in e.g. `android/src/core/kotlin`, compiled into the library by the
- normal `android/` project; a standalone JVM-only Gradle project points its `srcDir` at
- the same folder so `gradle test` runs without AGP. Core depends on `opentelemetry-sdk`
- and the OTLP exporter only.
- - iOS: core sources in e.g. `ios/Core/*.swift`, listed in the podspec `source_files`; a
- root `Package.swift` uses the same path for `swift test` on macOS.
+- A native core per platform holds all native logic (span hand-off β `SpanData`, SDK
+ setup, export config, the native parenting helper); the Nitro HybridObject is a thin
+ adapter over it.
+ - Android: the core (`android/src/main/java/com/callstack/otel/core`) reads Nitro's
+ generated seam structs directly; no hand-kept copy of the seam types. Core depends on
+ `opentelemetry-sdk` and the OTLP exporter.
+ - iOS: the core (`ios/Core/*.swift`) takes opentelemetry-swift types only. Nitro's
+ generated Swift structs are typealiases of C++ structs, so code using them needs C++
+ interop, and the core must not (below): the Nitro adapter pod builds `SpanData` from
+ the seam structs and hands the core `ReadableSpan`s. *(R24, Task 25: the app's non-interop Swift `AppDelegate` cannot import a Nitro C++-interop module, so iOS ships
+ two pods: pure-Swift `ReactNativeOpenTelemetryCore` (`ios/Core` + `RNOtel`) and the Nitro adapter pod that
+ depends on it. Autolinking links one podspec per package, so apps add `pod 'ReactNativeOpenTelemetryCore',
+ :path => '../node_modules/react-native-open-telemetry'` to their Podfile.)*
- **v0 uses otel-java directly, not opentelemetry-android** (Claude's call): otel-java is
stable; opentelemetry-android is alpha, adds desugaring/AGP constraints, and v0 needs none
of its instrumentation. Add it with v1 lifecycle work. Watch OkHttp version alignment
@@ -305,12 +305,11 @@ OTel data model.
itself with the semantic-convention distro attributes `telemetry.distro.name` /
`telemetry.distro.version` (`telemetry.sdk.*` stays otel-java / opentelemetry-swift's).
Carry `schemaUrl` for resource and scope.
-- **Clock (Claude's call, simplified in council review):** both sides use wall-clock epoch
- time. JS computes one offset, `Date.now() - performance.now()`, at start and again on
- `AppState` β active (Hermes' monotonic clock doesn't advance during device suspend), and
- uses it as the JS SDK's time source. Error between JS and native siblings is under 1 ms;
- scenarios use explicit timestamps, so test output is unaffected. Guard missing
- `performance` (fall back to `Date.now()`).
+- **Clock (Claude's call, simplified in council review and again in v0 implementation):** both
+ sides use wall-clock epoch time. JS keeps upstream `sdk-trace` timing: each span starts at
+ `Date.now()` and measures its duration with `performance.now()`; there is no extra JS offset
+ (sdk-trace 3.1 has no time-source hook). Error between JS and native siblings is under 1 ms;
+ scenarios use explicit timestamps, so test output is unaffected.
- **Before native is ready / failures (Claude's call):** no pre-init buffer. `initialize`
runs synchronously inside `startReactNativeSdk` before the JS provider is registered, so
no span can end before native is ready; spans started earlier come from the API's no-op
@@ -318,7 +317,7 @@ OTel data model.
loudly (`console.error`), and `startReactNativeSdk` returns a working no-op handle. The
SDK never throws into the app.
- **Multiple runtimes (Claude's call):** one native singleton; `initialize` is safe under
- concurrent calls; each JS runtime has its own hand-off and clock anchor. Per-runtime
+ concurrent calls; each JS runtime has its own hand-off. Per-runtime
attributes are out of scope for v0.
### 4.4 Configuration (decided: "option A", with JS fallback)
@@ -337,9 +336,8 @@ OTel data model.
- 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 base URL; `/v1/traces` is appended unless the URL already ends with it (so vendor
- URLs that already name the traces path still work). Web normalizes before calling
- `startBrowserSdk`.
+ OTLP/HTTP traces endpoint (e.g. `https://collector:4318/v1/traces`), used as given. No path
+ is appended.
- **Web**: the same call takes exporter options, mirroring `startBrowserSdk`'s option names
(`serviceName`, `serviceVersion`, `resourceAttributes`, `exportConfig: { url, headers }`,
`instrumentations`, β¦).
@@ -355,7 +353,7 @@ 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"; headers = mapOf("x-api-key" to KEY) }
+ export { url = "https://collector.example.com:4318/v1/traces"; headers = mapOf("x-api-key" to KEY) }
resourceAttributes = mapOf("deployment.environment.name" to "prod")
}
```
@@ -364,7 +362,7 @@ 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", headers: ["x-api-key": KEY])
+ c.export = .init(url: "https://collector.example.com:4318/v1/traces", headers: ["x-api-key": KEY])
}
```
@@ -374,7 +372,7 @@ 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', headers: { 'x-api-key': KEY } },
+ exportConfig: { url: 'https://collector.example.com:4318/v1/traces', headers: { 'x-api-key': KEY } },
spanProcessors: [/* stock sdk-trace SpanProcessors, unchanged */],
});
```
@@ -394,7 +392,7 @@ module.exports = withOtel(getDefaultConfig(__dirname));
(OTel naming guidance: reverse-domain prefix; `otel.*` is reserved). **Prefix is
Claude's call.**
-Package name: `react-native-open-telemetry` (subpaths `/metro`, `/vite`). Entry function:
+Package name: `react-native-open-telemetry` (subpath `/metro`). Entry function:
`startReactNativeSdk`, on web too. **(decided)**
## 5. Trace model (decided; most of it lands with v1 instrumentations)
@@ -516,25 +514,33 @@ ships TC39 AsyncContext (Stage 2).
## 7. Web (decided)
Same `@opentelemetry/api` surface and the same ContextManager; spans live in the JS SDK and
-export directly via upstream `@opentelemetry/browser-sdk` (`startBrowserSdk`) and its OTLP
-fetch exporter. Builder to check whether `browser-sdk` installs its own context manager and
-make ours win.
-
+export directly from JS. **Changed in v0 implementation (R7, pending author review):** web
+builds its own `sdk-trace` `TracerProvider` + `BatchSpanProcessor` + upstream
+`@opentelemetry/exporter-trace-otlp-proto` (fetch), not `startBrowserSdk`. Why:
+browser-sdk 0.9.1 takes no `idGenerator` (no `0a` test-mode IDs, so no exact web goldens),
+adds `telemetry.sdk.*` to the resource (against 4.3), also starts a Logs SDK, exports JSON
+(loses NaN), and returns no `tracerProvider`/`forceFlush` for our handle. The resource is
+`service.*` + `resourceAttributes` + `telemetry.distro.*` (outside test mode). `start`
+re-registers our context manager if another one took the global slot. The package's
+`exports` `browser` condition points Metro web (Expo web) at `index.web.js`.
+
+Web is bundled with Metro (Expo web), with the same `withOtel` from `/metro` as mobile.
Browsers run `await` natively, which bypasses the patched `then`. **Decided:** web apps
compile `async` down in their bundler β the same mechanism RN uses by default, and what
-Angular requires for zone.js. We ship one-line bundler helpers mirroring the Metro helper:
-- Vite: `withOtel(viteConfig)` sets esbuild `supported: { 'async-await': false }` for the
- app and for pre-bundled dependencies.
-- webpack / Babel: deferred until a webpack user asks (Expo web uses Metro, covered by
- `withOtel` from `/metro`); the manual fix is `@babel/plugin-transform-async-to-generator`.
-Without the helper, the probe reports degraded (lost parents after `await`, never wrong).
-Prior art: Angular CLI does exactly this for zone.js (Β§14 P4).
+Angular requires for zone.js (Β§14 P4). `babel-preset-expo` keeps native `async` on web, so the
+app adds `@babel/plugin-transform-async-to-generator` and
+`@babel/plugin-transform-async-generator-functions` for the web platform in `babel.config.js`
+(README). Without them, the probe reports degraded (lost parents after `await`, never wrong).
-```ts
-// vite.config.ts (illustrative)
-import { withOtel } from 'react-native-open-telemetry/vite';
-export default withOtel(defineConfig({ plugins: [react()] }));
-// sets esbuild.supported['async-await'] = false for build and optimizeDeps
+```js
+// babel.config.js (Expo app, illustrative)
+module.exports = api => {
+ const web = api.caller(c => c?.platform === 'web');
+ return {
+ presets: ['babel-preset-expo'],
+ plugins: web ? ['@babel/plugin-transform-async-generator-functions', '@babel/plugin-transform-async-to-generator'] : [],
+ };
+};
```
## 8. v0 scope and sequencing (decided scope; sequencing is Claude's call)
@@ -547,7 +553,7 @@ Scope:
policy (6.2).
4. Cross-boundary parenting, both directions, with the native helper.
5. The seam (4.3).
-6. Web: upstream browser SDK, same ContextManager, bundler helpers.
+6. Web: upstream browser SDK, same ContextManager, Metro (Expo web).
7. Proof (section 9): on iOS and Android, the example app produces one trace with a JS
root, a child after `await`, a native child parented from JS, a JS span parented by
native; plus a second concurrent trace that shares nothing with the first. On web (no
@@ -593,8 +599,9 @@ tests: they don't care about internals, so internals can be rewritten freely.
time; native: Gradle property `otelTestMode` / `OTEL_TEST_MODE=1` at `pod install`. Same
flag for the bare and Expo apps; no test fields in the public API or the seam config:
- **explicit timestamps**: v0 scenarios create all spans themselves, so they pass
- `startTime` / `end(t)` explicitly (JS and native), in whole microseconds (exactly
- representable on iOS). Clock stubs (Java `setClock`/`TestClock` in test source sets
+ `startTime` / `end(t)` explicitly (JS and native), in whole microseconds. iOS cannot
+ represent them exactly: opentelemetry-swift exports `Date`, a ~238β256 ns grid, so the `ios`
+ files record the quantized values (R22, measured floor in verify/VERIFY.md). Clock stubs (Java `setClock`/`TestClock` in test source sets
only; Swift `with(clock:)`) are only a fallback for implicit reads.
- sequential test ID generators, namespaced per side (JS `0aβ¦01`, native `0bβ¦01`) via
upstream hooks: JS `sdk-trace` `idGenerator`, Java `setIdGenerator`, Swift
@@ -610,9 +617,9 @@ tests: they don't care about internals, so internals can be rewritten freely.
output is reduced to a shape and must equal it, so all platforms agree with each other by
construction. Shapes are written first; exact per-platform files are then drafted with
`--update` and reviewed (council review: hand-writing 30+ exact OTLP trees puts the bugs
- in the expected files).
-- One non-deterministic smoke scenario per device (production pipeline, no test mode) checks
- the real path still exports.
+ in the expected files). Known v0 gap, accepted: opentelemetry-swift 2.6's OTLP encoder never
+ writes span/link `flags`, span/link `traceState` or the scope `schemaUrl`, so the `ios` files
+ lack them (shapes don't cover them; no encoder reimplementation, see verify/VERIFY.md).
A scenario and its expected file, roughly:
@@ -660,9 +667,7 @@ The same scenarios run in every layer, fastest first.
| Layer | Runner | Covers | When |
|---|---|---|---|
| JS (Node) | **Jest** + `babel-jest` + `@react-native/babel-preset` | context patch, hand-off (fake Nitro module) | every iteration |
-| Kotlin core | JUnit via `gradle test` (plain JVM) | native hand-off β OTLP | every iteration |
-| Swift core | XCTest via `swift test` (macOS) | native hand-off β OTLP | every iteration |
-| E2E: iOS, Android, web | **[`e2e`](https://www.npmjs.com/package/e2e)** (agent-device for mobile, Playwright for web) | everything for real: Nitro glue, both init paths, threading, reload, failure paths, browser SDK, bundler helpers (matrix in 9.4) | **every PR** once the seam exists (decided) |
+| E2E: iOS, Android, web | **[`e2e`](https://www.npmjs.com/package/e2e)** (agent-device for mobile, Playwright for web) | everything for real: Nitro glue, both init paths, threading, reload, failure paths, browser SDK, Metro helper (matrix in 9.4) | **every PR** once the seam exists (decided) |
- **Why Jest:** it compiles scenarios the way RN does (`await` β `.then`). Bun's test runner
and Vitest keep native `await`, which bypasses the context patch and makes results wrong
@@ -689,27 +694,22 @@ The same scenarios run in every layer, fastest first.
```mermaid
flowchart LR
sc["Scenarios (verify/scenarios)"] --> js["JS: Jest (Node)"]
- js -- "writes handOff payloads" --> fx[("Shared payload fixtures")]
- fx --> kt["Kotlin core gradle test"]
- fx --> sw["Swift core swift test"]
sc --> e2e["e2e: iOS / Android / web (every PR)"]
js --> fc
- kt --> fc
- sw --> fc
e2e --> fc
fc[("Fake collector OTLP β OTLP/JSON")] --> cmp{"exact compare + parity shape"}
exp[("verify/expected (CODEOWNERS)")] --> cmp
cmp --> out["structured diff + verify/artifacts"]
```
-- **Shared payload fixture** (Claude's call): JS generates the exact `handOff` payloads for
- the scenarios; the Kotlin and Swift tests consume the same fixture files. This is the
- contract test for the seam (int vs double, optional vs null, attribute arrays, HrTime).
+- **Native cores are proven on devices:** the Kotlin and Swift cores have no host-side test
+ runs. The device e2e runs every scenario through the real seam and native core and compares
+ against the same `*.android` / `*.ios` expected files.
- **Fake collector**: a small Node OTLP/HTTP receiver decoding protobuf with the official
`opentelemetry-proto` definitions and producing OTLP/JSON (GitHub macOS runners can't run
Docker, so no Collector image).
- **No separate Hermes layer:** E2E runs on real Hermes; Jest on Node is the fast loop. The
- future native-`await` case is covered by a Jest project that keeps native `async`; an
+ future native-`await` case is covered by the probe's unit test; an
`unstable_preserveAsync` device build is added once a Hermes release ships it.
- E2E needs `10.0.2.2` on Android, cleartext config and iOS ATS local-networking
allowance, scoped to the example app only.
@@ -719,16 +719,8 @@ flowchart LR
work, ROOT leak check, captured `then`, async generators, batching (documented
exception), `setInterval` (new root), thrown errors in callbacks, never-settling promise
(no context leak into later work), cross-boundary both ways, one rich span (every
- attribute type, events, links, status) to catch seam drift, degraded probe (Jest with
- native `async`), `perf-budget` (below).
-- **Fixture encoding:** fixtures are JSON, which can't hold `NaN`, `Infinity` or `-0`; these
- are written as `{"$num": "NaN" | "Infinity" | "-Infinity" | "-0"}` and decoded by the
- Kotlin and Swift test readers.
-- **Performance guardrail (council review):** one e2e scenario, `perf-budget`, on the
- Android target only: 1,000 spans with 10 attributes each through the real hand-off, and
- 10,000 awaits with the patch on vs off (test build flag). It fails only on loose budgets
- (hand-off p50 < 100 Β΅s per span, patch ratio < 3Γ) so emulator noise doesn't flake;
- numbers go to `verify/artifacts/perf.json`.
+ attribute type, events, links, status) to catch seam drift.
+ The degraded probe is a unit test: a native-`async` step built with `new Function` defeats the patch.
### 9.3 Working loop
1. One command: `bun verify` starts the fake collector, runs the layers, compares every
@@ -751,17 +743,14 @@ Everything below is automated; nothing needs a person except reviewing expected
```mermaid
flowchart LR
- s1["1 Β· Static every push"] --> s2["2 Β· Fast loop every iteration"] --> s3["3 Β· E2E matrix every PR"] --> s4["4 Β· OTLP compliance every PR"]
- s5["5 Β· Scheduled nightly + before release"]
+ s1["1 Β· Static every push"] --> s2["2 Β· Fast loop every iteration"] --> s3["3 Β· E2E matrix every PR"]
```
| Stage | Runs | Checks |
|---|---|---|
-| **1. Static** (seconds) | pre-commit hook, and every push | `tsc`; `oxlint`; Nitro codegen is current (`nitrogen && git diff --exit-code nitrogen/`); `npm pack` contents include `lib/`, `nitrogen/`, `android/`, `ios/`, `Package.swift`, the podspec and helper subpaths; bundle size: the SDK's share of a Metro bundle of the example stays within 10% of a committed baseline; unit tests of the fake collector's normalizer (it sorts and merges, so a bug there would hide or invent diffs everywhere) |
-| **2. Fast loop** (seconds) | every iteration, local and CI | Jest (Node), `gradle test`, `swift test`, all through the fake collector against expected files; the handful of unit tests (int vs double, `HrTime`, endpoint) |
-| **3. E2E matrix** (minutes) | every PR | `e2e` on five targets: **bare app** (native-first init) on iOS and Android, **Expo prebuild app** (JS-fallback init) on iOS and Android, **web**. All golden scenarios, the failure scenarios below, and one smoke scenario per target without test mode. Parity check across all five outputs. `perf-budget` on Android. |
-| **4. OTLP compliance** | every PR, Linux runner with Docker | The fake collector keeps every raw request it received. They are replayed, together with every expected file, to the **official OTel Collector** image (pinned) with an OTLP receiver; the job fails on any rejected request or decode error in its logs. Proves both our output and our spec files are real OTLP. |
-| **5. Scheduled** | nightly, and before every release | E2E on the **minimum and latest supported RN**; the fast loop and E2E against the **latest upstream** `@opentelemetry/*`, otel-java and opentelemetry-swift (catches upstream changes before a version bump); the **packed tarball** (`npm pack`) installed into a fresh bare app and a fresh Expo app, running the smoke scenario (catches missing files and broken autolinking). |
+| **1. Static** (seconds) | pre-commit hook, and every push | `tsc`; `oxlint`; Nitro codegen is current (`nitrogen && git diff --exit-code nitrogen/`); `npm pack` contents include `lib/`, `nitrogen/`, `android/`, `ios/`, the podspecs and the `metro/` helper; unit tests of the fake collector's normalizer (it sorts and merges, so a bug there would hide or invent diffs everywhere) |
+| **2. Fast loop** (seconds) | every iteration, local and CI | Jest (Node) through the fake collector against expected files; the handful of unit tests (int vs double, `HrTime`, endpoint) |
+| **3. E2E matrix** (minutes) | every PR | `e2e` on five targets: **bare app** (native-first init) on iOS and Android, **Expo prebuild app** (JS-fallback init) on iOS and Android, **web** (the Expo app's Metro web export). All golden scenarios and the failure scenarios below; parity check across all five outputs. |
Two apps cover both init paths: the bare example inits natively in
`MainApplication`/`AppDelegate`; the Expo app has no native init and relies on the JS
@@ -774,9 +763,8 @@ one final `needs:` job that checks total wall-clock time. When a PR run exceeds
(cache native builds, shard targets, trim slow scenarios), never dropping a target: the full
matrix on every PR is decided.
-**Releases:** only from commits on `main` whose full PR pipeline and stage 5 passed. Publish
-to the `next` dist-tag first; promote to `latest` after the next nightly is green on that
-commit.
+**Releases:** manual with changesets (`bun run version`, then `bun run publish`), from `main`
+once its PR pipeline is green. No release workflow.
**Failure scenarios** (E2E; the fake collector can refuse requests on demand):
- collector down: the app doesn't block or crash; spans arrive once it is back.
@@ -787,8 +775,8 @@ commit.
- fast refresh doesn't stack the context patch (same output before and after).
### 9.5 Not covered in v0
-- **Performance** beyond the `perf-budget` guardrail (low-end device numbers, Kotlin vs C++
- adapter): the v1 spike (section 11).
+- **Performance** (hand-off cost, patch overhead, low-end devices, Kotlin vs C++ adapter):
+ not measured in CI; the v1 spike (section 11).
- **Memory retention** (a never-settling promise keeping its span alive): output tests
can't see it; add a `WeakRef` + `--expose-gc` check if it becomes a concern.
- **Multiple JS runtimes**: one native singleton is designed for, not tested.
@@ -872,7 +860,7 @@ Left out until needed:
8. Default sampling `ParentBased(AlwaysOn)` on both sides, honoring `traceFlags` (4.3).
9. One native-owned resource; JS adds no `telemetry.sdk.*`; SDK identity via
`telemetry.distro.*` (4.3).
-10. Clock: one `Date.now() - performance.now()` offset, recomputed on foreground (4.3).
+10. Clock: upstream sdk-trace timing (start at `Date.now()`, `performance.now()` durations) (4.3).
11. No pre-init buffer; init failure β one error and a no-op handle, never a throw;
multi-runtime handling (4.3, 4.4).
12. Context manager extends upstream `StackContextManager`; Metro `withOtel` helper for
@@ -880,11 +868,10 @@ Left out until needed:
13. Trace-model rules: links for multi-cause renders, marked heuristic attribution (5).
14. Sequencing, with the real-RN-app context milestone first (8).
15. Test mode as a build flag; explicit whole-Β΅s timestamps in scenarios; attribute/event
- sorting; parity shape; one non-deterministic smoke scenario per device (9.1).
-16. Shared payload fixture as the seam contract test (9.2).
-17. One endpoint meaning on every platform (base URL, `/v1/traces` appended unless
- present); returned handle `{ tracerProvider, forceFlush, shutdown }` (4.4).
-18. `perf-budget` guardrail and bundle-size check (9.2, 9.4).
+ sorting; parity shape (9.1).
+16. Native cores proven by device e2e against the same expected files (9.2).
+17. One endpoint meaning on every platform (the traces endpoint, used as given); returned handle `{ tracerProvider, forceFlush, shutdown }` (4.4).
+18. No performance or compliance jobs in CI: the upstream OTLP exporters own the wire format; `example/collector/` runs the official Collector by hand (9.4).
## 14. Prior art and proof
@@ -897,7 +884,7 @@ direct precedent was found; treat those as the highest-risk parts.
| P1 | Context runtime patch: wrap `Promise.prototype.then` + timers, capture at schedule, restore at run (6.1) | zone.js (Angular) patches `then` and replaces `Promise`; async-listener (Node, pre-`async_hooks`, basis of `continuation-local-storage`) wraps `then` and timers | [zone.js `patchThen`](https://github.com/angular/angular/blob/efbab16e56734d7121d9dd29c2761dec6e787807/packages/zone.js/lib/common/promise.ts#L585-L611) Β· [async-listener `wrap(Promise.prototype, 'then')`](https://github.com/othiym23/async-listener/blob/01a02ee123db3d4a98e0cc5dda6f8ef82c55f81e/index.js#L468) Β· [async-listener timers](https://github.com/othiym23/async-listener/blob/01a02ee123db3d4a98e0cc5dda6f8ef82c55f81e/index.js#L215-L224) |
| P2 | ContextManager extends upstream sync manager (6.1) | OTel JS `StackContextManager` | [StackContextManager.ts](https://github.com/open-telemetry/opentelemetry-js/blob/ee0bd33cac8bb245a3d83fc2b8ba0b07534b8efd/packages/sdk-trace/src/StackContextManager.ts#L20) |
| P3 | Startup probe that detects whether the patch can work (6.1) | async-listener checks at load whether `Promise` is native and whether its patch takes effect | [async-listener native-Promise check](https://github.com/othiym23/async-listener/blob/01a02ee123db3d4a98e0cc5dda6f8ef82c55f81e/index.js#L347-L361) |
-| P4 | Web: require bundlers to downlevel `async`, via a `withOtel(viteConfig)` helper (7) | Angular CLI disables native async/await in esbuild so zone.js can track it | [Angular CLI `getFeatureSupport`](https://github.com/angular/angular-cli/blob/c5d6f9f04d3a971b453b9189d8a344f8ca5e0fe2/packages/angular/build/src/tools/esbuild/utils.ts#L190-L199) |
+| P4 | Web: require the bundler to downlevel `async` (Babel plugins on Expo web) (7) | Angular CLI disables native async/await in esbuild so zone.js can track it | [Angular CLI `getFeatureSupport`](https://github.com/angular/angular-cli/blob/c5d6f9f04d3a971b453b9189d8a344f8ca5e0fe2/packages/angular/build/src/tools/esbuild/utils.ts#L190-L199) |
| P5 | Metro helper installs the patch before app modules (6.1) | RN's own Metro config runs `InitializeCore` before the main module the same way; Sentry ships a `withSentryConfig` Metro wrapper | [RN `getModulesRunBeforeMainModule`](https://github.com/facebook/react-native/blob/6b9afd8a836604df111fad1d2fbcbce773bd0eaf/packages/metro-config/src/index.flow.js#L44) Β· [Sentry `withSentryConfig`](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/tools/metroconfig.ts#L133) |
| P6 | Spans created in JS, handed to native which owns transport (4.1) | Sentry RN: JS SDK builds envelopes, native SDK sends them (offline cache, retry) | [Sentry native transport](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/transports/native.ts#L38) Β· [`sendEnvelope`](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/wrapper.ts#L225) Β· this repo's earlier Kotlin `SpanData` conversion (commit `fe4d4b8`, removed `exportTraces`) |
| P7 | Native-first init with JS fallback (4.4) | Sentry RN: native-first `RNSentrySDK.start`, JS `initNativeSdk` otherwise; Embrace checks `isStarted()` and starts from JS if needed | [Sentry `RNSentrySDK.m`](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/ios/RNSentrySDK.m) Β· [Sentry `initNativeSdk`](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/wrapper.ts#L289) Β· [Embrace `isStarted`](https://github.com/embrace-io/embrace-react-native-sdk/blob/db0e9a6e3677f61f822f9bd98a95c9ce95ee4f64/packages/core/src/index.ts#L29) |
@@ -907,7 +894,7 @@ direct precedent was found; treat those as the highest-risk parts.
| P11 | Links instead of parents for batched/multi-cause work; interval ticks as new roots (5, 6.2) | OTel spec: links represent batched operations; React notes it can't attribute batched updates without AsyncContext | [Spec: Links between spans](https://github.com/open-telemetry/opentelemetry-specification/blob/a03fa4e26b3982da42aa0010aaebcd9f694cb037/specification/overview.md#L207-L214) Β· [React `ReactFiberAsyncAction.js`](https://github.com/facebook/react/blob/fe719f77ba3e4b5fb3ebe13787bfbd0ed911da19/packages/react-reconciler/src/ReactFiberAsyncAction.js#L42) |
| P12 | *(removed: the staleness rule was cut in council review, see 6.2)* | | |
| P13 | *(removed: the pre-init buffer was cut in council review, see 4.3)* | | |
-| P14 | Clock offset `Date.now() - performance.now()`, recomputed on foreground (4.3) | OTel JS derives span times from `performance.timeOrigin` + `performance.now()`; Sentry RN guards an unreliable `performance.timeOrigin` | [Sentry `timeOrigin` guard](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/sdk.tsx#L76-L80) |
+| P14 | *(Superseded by R8: upstream timing kept, no offset.)* Clock offset `Date.now() - performance.now()`, recomputed on foreground (4.3) | OTel JS derives span times from `performance.timeOrigin` + `performance.now()`; Sentry RN guards an unreliable `performance.timeOrigin` | [Sentry `timeOrigin` guard](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/sdk.tsx#L76-L80) |
| P15 | Custom names under a reverse-domain prefix, never `otel.*` (4.5) | OTel naming guidance | [naming.md: app developers](https://github.com/open-telemetry/semantic-conventions/blob/2d91ead21027a8a58fbb7488b12d80238e7c0ac5/docs/general/naming.md#L183-L187) Β· [`otel.*` reserved](https://github.com/open-telemetry/semantic-conventions/blob/2d91ead21027a8a58fbb7488b12d80238e7c0ac5/docs/general/naming.md#L217-L227) |
| P16 | Option names mirror `startBrowserSdk`; invalid config returns a no-op SDK instead of throwing (4.4) | OTel Browser SIG browser SDK | [browser-sdk README](https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/sdk) |
| P17 | Exact expected-output files (goldens) for traces (9.1) | OTel Collector tests compare traces against golden files | [collector-contrib `pkg/golden`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/c64840337cf400792cb684037ed998428b268197/pkg/golden) Β· [`ptracetest` compare options](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/c64840337cf400792cb684037ed998428b268197/pkg/pdatatest/ptracetest/options.go#L102-L149) |
@@ -916,5 +903,4 @@ direct precedent was found; treat those as the highest-risk parts.
| P20 | Protected expected files (9.3) | GitHub `CODEOWNERS` | [About code owners](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) |
| P21 | *(removed: the mutant meta-check was cut from v0, see 9.3)* | | |
| P22 | Hermetic fake collector decoding the official protos (9.2) | Official OTLP protobuf definitions | [opentelemetry-proto](https://github.com/open-telemetry/opentelemetry-proto) |
-| P23 | Pure Kotlin/Swift core + thin Nitro adapters; shared-sources layout (4.2) | **Ours**: no direct precedent found in the RN OTel SDKs reviewed | β |
-| P24 | Shared JS-generated payload fixtures as the seam contract test (9.2) | Consumer-driven contract testing (general practice) | [Pact: consumer-driven contracts](https://docs.pact.io/) |
+| P23 | Native core + thin Nitro adapter; on iOS a Nitro-free core pod (4.2) | **Ours**: no direct precedent found in the RN OTel SDKs reviewed | β |
diff --git a/example/android/app/src/main/java/opentelemetry/example/OtelInit.kt b/example/android/app/src/main/java/opentelemetry/example/OtelInit.kt
index 78d68bb..032fd17 100644
--- a/example/android/app/src/main/java/opentelemetry/example/OtelInit.kt
+++ b/example/android/app/src/main/java/opentelemetry/example/OtelInit.kt
@@ -4,27 +4,17 @@ import android.app.Application
import com.callstack.otel.RNOtel
import java.io.File
-/**
- * Native-first init, called from MainApplication.onCreate before React Native. Its own file so the nightly
- * (verify/nightly/app.sh) can add it unchanged to a freshly generated app at another RN version.
- * No serviceVersion: the test-mode resource is service.name only (R2).
- */
internal fun Application.startOtel() {
RNOtel.start(this) {
serviceName = "verify"
export {
- url = testExportUrl() ?: "http://10.0.2.2:4318/v1/traces" // the e2e collector on the host
- headers = mapOf("x-api-key" to "test") // asserted by verify/e2e/export-headers.e2e.ts
+ url = testExportUrl() ?: "http://10.0.2.2:4318/v1/traces"
+ headers = mapOf("x-api-key" to "test")
}
}
- // compile check: the otel API is part of RNOtel's public surface (a no-op tracer is cheap to build)
RNOtel.tracer("opentelemetry.example")
}
-/**
- * Test-mode builds only: verify/e2e/native-init-failure.e2e.ts overrides the URL. Application.onCreate cannot see
- * launch arguments (they reach the Activity), so the test writes this file with adb and removes it afterwards.
- */
private fun Application.testExportUrl(): String? =
if (!BuildConfig.OTEL_TEST_MODE) null
else File(getExternalFilesDir(null), "otel-export-url").takeIf { it.exists() }?.readText()?.trim()
diff --git a/example/collector/docker-compose.yaml b/example/collector/docker-compose.yaml
new file mode 100644
index 0000000..afc57b8
--- /dev/null
+++ b/example/collector/docker-compose.yaml
@@ -0,0 +1,15 @@
+services:
+ otel-collector:
+ image: otel/opentelemetry-collector:0.165.0
+ command: ["--config=/etc/otel-collector-config.yaml"]
+ volumes:
+ - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
+ ports:
+ - "4318:4318"
+ depends_on:
+ - jaeger
+
+ jaeger:
+ image: jaegertracing/jaeger:2.23.0
+ ports:
+ - "16686:16686"
diff --git a/example/collector/otel-collector-config.yaml b/example/collector/otel-collector-config.yaml
new file mode 100644
index 0000000..129fb0f
--- /dev/null
+++ b/example/collector/otel-collector-config.yaml
@@ -0,0 +1,28 @@
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+ cors:
+ allowed_origins:
+ - http://localhost:*
+ allowed_headers:
+ - "*"
+
+processors:
+ batch:
+
+exporters:
+ debug:
+ verbosity: detailed
+ otlp:
+ endpoint: jaeger:4317
+ tls:
+ insecure: true
+
+service:
+ pipelines:
+ traces:
+ receivers: [otlp]
+ processors: [batch]
+ exporters: [debug, otlp]
diff --git a/example/ios/OpenTelemetryExample/AppDelegate.swift b/example/ios/OpenTelemetryExample/AppDelegate.swift
index 21d9b04..5fe2d14 100644
--- a/example/ios/OpenTelemetryExample/AppDelegate.swift
+++ b/example/ios/OpenTelemetryExample/AppDelegate.swift
@@ -12,19 +12,14 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
}
}
-// otel-init: verify/nightly/app.sh appends this line and everything below it to a freshly generated AppDelegate.swift.
-/// Native-first init, before React Native. No serviceVersion: the test-mode resource is service.name only (R2).
func startOtel() {
RNOtel.start { c in
c.serviceName = "verify"
- // the e2e collector on the host; asserted by verify/e2e/export-headers.e2e.ts
c.export = .init(url: testExportUrl() ?? "http://localhost:4318/v1/traces", headers: ["x-api-key": "test"])
}
- // compile check: the otel API is part of RNOtel's public surface (a no-op tracer is cheap to build)
_ = RNOtel.tracer("opentelemetry.example")
}
-/// Test-mode builds only: verify/e2e/native-init-failure.e2e.ts launches with `--otel-export-url=`.
private func testExportUrl() -> String? {
#if OTEL_TEST_MODE
let prefix = "--otel-export-url="
diff --git a/ios/RNOtel/RNOtel.swift b/ios/RNOtel/RNOtel.swift
index aed3221..598669b 100644
--- a/ios/RNOtel/RNOtel.swift
+++ b/ios/RNOtel/RNOtel.swift
@@ -2,10 +2,6 @@ import Foundation
import OpenTelemetryApi
import UIKit
-/// `package.json` version, reported as `telemetry.distro.version`; the static stage checks it matches.
-let packageVersion = "0.2.0"
-
-/// Public native API (spec Β§4.3/Β§4.4). Test mode comes from the build (`OTEL_TEST_MODE=1 pod install`), never from here.
public enum RNOtel {
#if OTEL_TEST_MODE
static let testMode = true
@@ -13,35 +9,26 @@ public enum RNOtel {
static let testMode = false
#endif
- /// Native-first init from `AppDelegate`, before React Native. Never throws; an error is logged once.
public static func start(_ configure: (RNOtelConfig) -> Void) {
let c = RNOtelConfig()
configure(c)
let r = initialize(c.toCore())
- // alreadyInitialized: a repeat call; a sticky failure was logged by the first one
if let err = r.error, !r.alreadyInitialized { NSLog("RNOtel init failed; telemetry is off: %@", err) }
}
private static var observer: NSObjectProtocol?
private static let lock = NSLock()
- /// One path for native-first and JS-fallback init. The exporter is built on first export, off the main thread.
package static func initialize(_ config: CoreConfig?) -> InitResult {
let r = OtelCore.initialize(config, testMode: testMode, distroVersion: packageVersion)
if let core = OtelCore.instance { lock.withLock { if observer == nil { observer = flushOnBackground(core) } } }
return r
}
- /// Exports what is queued when the app is about to go to the background, inside a background task so iOS lets it
- /// finish. The flush blocks a global queue, never the main thread.
- /// Starts on `willResignActive`, not `didEnterBackground`: once backgrounded, a loaded system can starve the app for
- /// 15 s and more despite the background task (seen on CI simulators: the export stalls until the app is reopened).
- /// It also fires for transient interruptions (Control Center, a call); an extra flush there is harmless.
private static func flushOnBackground(_ core: OtelCore) -> NSObjectProtocol {
NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { _ in
let app = UIApplication.shared
var task = UIBackgroundTaskIdentifier.invalid
- // begin/end/expiration all run on the main thread, so `task` needs no lock
let end = { if task != .invalid { app.endBackgroundTask(task); task = .invalid } }
task = app.beginBackgroundTask(withName: "RNOtel flush", expirationHandler: end)
DispatchQueue.global(qos: .utility).async {
@@ -51,13 +38,11 @@ public enum RNOtel {
}
}
- /// A tracer on the native provider; a no-op tracer before (or without) a successful init.
public static func tracer(_ name: String, version: String? = nil) -> any Tracer {
guard let p = OtelCore.instance?.tracerProvider else { return DefaultTracer.instance }
return p.get(instrumentationName: name, instrumentationVersion: version)
}
- /// W3C traceparent -> explicit, non-remote parent `SpanContext` for `setParent(_:)`; invalid input -> nil (a root).
public static func contextFrom(traceparent: String) -> SpanContext? { ReactNativeOpenTelemetryCore.contextFrom(traceparent: traceparent) }
public static func traceparentOf(_ span: any Span) -> String { traceparent(of: span.context) }
diff --git a/package.json b/package.json
index 2b9274c..0e749b7 100644
--- a/package.json
+++ b/package.json
@@ -76,11 +76,11 @@
"publish": "bunx changeset publish"
},
"dependencies": {
- "@opentelemetry/api": "~1.10.0",
- "@opentelemetry/sdk-trace": "~3.1.1",
- "@opentelemetry/core": "~3.1.1",
- "@opentelemetry/resources": "~3.1.1",
- "@opentelemetry/semantic-conventions": "^1.45.0",
+ "@opentelemetry/api": "1.10.0",
+ "@opentelemetry/sdk-trace": "3.1.1",
+ "@opentelemetry/core": "3.1.1",
+ "@opentelemetry/resources": "3.1.1",
+ "@opentelemetry/semantic-conventions": "1.45.0",
"@opentelemetry/exporter-trace-otlp-proto": "0.301.2"
},
"devDependencies": {
@@ -102,7 +102,7 @@
"typescript": "^5.8.3"
},
"peerDependencies": {
- "react-native": ">=0.79",
+ "react-native": ">=0.88",
"react-native-nitro-modules": "~0.37.0"
},
"react-native-builder-bob": {
diff --git a/verify/VERIFY.md b/verify/VERIFY.md
index a115592..19b3c94 100644
--- a/verify/VERIFY.md
+++ b/verify/VERIFY.md
@@ -3,17 +3,208 @@
`bun verify [stageβ¦] [--e2e] [--update]` runs the stages in `verify/stages/`. `--e2e` adds the device stage
(`e2e`), which needs release builds of `example/` in test mode:
+The example bundles the package through `exports` β `lib/` (R4), so build `lib/` first: the release builds embed
+the JS bundle, and the e2e stage cannot rebuild it.
+
```sh
+bun run prepare # lib/
# Android (emulator booted)
cd example/android && OTEL_TEST_MODE=1 ./gradlew :app:assembleRelease -PotelTestMode=true
# iOS
cd example/ios && OTEL_TEST_MODE=1 pod install && OTEL_TEST_MODE=1 xcodebuild -workspace OpenTelemetryExample.xcworkspace \
-scheme OpenTelemetryExample -configuration Release -sdk iphonesimulator -derivedDataPath build build
-E2E_TARGET=android-bare bun verify --e2e e2e # or ios-bare; omit E2E_TARGET for both
+E2E_TARGET=android-bare bun verify --e2e e2e # or ios-bare, android-expo, ios-expo, web; omit E2E_TARGET for all five
+```
+
+Web (`web` target) needs `lib/`, `bun install` in `example-expo/` and a Playwright Chromium
+(`bunx e2e-web install chromium`); the runner exports and serves the Expo app for web itself (below).
+
+The Expo app (`example-expo/`, `android-expo` / `ios-expo`) is CNG: `android/` and `ios/` are generated, not committed.
+
+```sh
+cd example-expo && bun install && OTEL_TEST_MODE=1 bunx expo prebuild --clean --no-install
+cd android && OTEL_TEST_MODE=1 ./gradlew :app:assembleRelease # otelTestMode=true comes from the prebuild
+cd ../ios && OTEL_TEST_MODE=1 pod install && OTEL_TEST_MODE=1 xcodebuild -workspace OpenTelemetryExpo.xcworkspace \
+ -scheme OpenTelemetryExpo -configuration Release -sdk iphonesimulator -derivedDataPath build build
```
+The Kotlin and Swift cores have no host-side test runs: the `e2e` stage runs every scenario on Android and iOS
+through the real seam and native core and compares against `.android.otlp.json` / `.ios.otlp.json`.
+
+**iOS time floor (R22).** opentelemetry-swift 2.6 keeps times as `Date` and exports
+`UInt64(timeIntervalSince1970 * 1e9)`, so whole-Β΅s seam times come back on a ~238β256 ns grid, truncated
+(measured once over `at(0β¦10_000)` and `at(1_000_000_000)`: max |error| 240 ns, 314 of 10 002 exact).
+`*.ios.otlp.json` record these quantized values as emitted (deterministic); shapes ignore times.
+
+**iOS vs Android/JS goldens.** Apart from times, the `ios` files differ only by what the opentelemetry-swift 2.6 OTLP
+encoder (`SpanAdapter`) never writes: span `flags` (257), span `traceState`, link `flags`, link `traceState`, and the
+scope `schemaUrl` on `ScopeSpans`. The core passes them all into `SpanData`; the exporter drops them. Accepted for v0
+(no encoder reimplementation); `rich-span` exercises span flags, link flags/traceState and the scope `schemaUrl`.
+
+**iOS `TRACEPARENT` (upstream caveat).** opentelemetry-swift reads a `TRACEPARENT` environment variable at provider
+construction and makes it the parent of every root span, even with `setNoParent()`. Apps only see it when launched with
+it (Xcode scheme, `SIMCTL_CHILD_TRACEPARENT`).
+
+`verify/e2e/scenarios.e2e.ts` runs one test per scenario with runner `e2e`, not `pending`, on each target it lists,
+except the scenarios with their own e2e file. Each test cold-starts the app (R5). e2e is compare-only;
+On web, `forceFlush` latency follows the OTLP exporter's own retries (about 10 s worst case), not a native flush timeout; `collector-down` allows 10 s there.
+
+`VERIFY_E2E_DRAFT=1` writes a **missing** `..otlp.json` from the device run and still fails the test
+("drafted β¦, review it"); existing files are never overwritten. Draft runs have no retries, so a drafting run always ends red.
+Each target compares to its platform's files (`android-*` β `android`, `ios-*` β `ios`, `web` β `web`): the bare app inits native
+first (`RNOtel.start` in `MainApplication` / `AppDelegate`), the Expo app inits from JS (below), and ScenariosScreen
+exports through `startReactNativeSdk` and the Kotlin or Swift core. One set of files for both apps is the proof that
+the two init paths are equivalent. A scenario that only one app can run names targets (`android-bare`) instead of
+platforms in `targets`.
+
+**Fixtures by target kind (Task 23).** `harness.ts` has two chains: `test` (device targets: its auto `installed`
+fixture and `target` name `device`, so every `test(β¦)` passes `{platforms: MOBILE}`) and `webTest` (a fresh browser
+context per test; `target` is the platform, `web`). `anyTarget(title, body)` registers one body on both; e2e titles must
+be unique, so the web copy is `web βΊ `.
+
+**TestNative (R25, Task 26).** `cross-*` scenarios call `ctx.native`, the example-only Nitro HybridObject in
+`example/modules/test-native/` (own `nitro.json`, podspec, `build.gradle`; autolinked through
+`example/react-native.config.js`). It uses only the public `RNOtel` helpers. After editing its spec, regenerate with
+`bun run codegen` in that directory (the patched root nitrogen) and commit `nitrogen/generated`.
+
+**iOS pods (R24).** An app's Swift `AppDelegate` cannot `import ReactNativeOpenTelemetry`: the Nitro pod is built with
+C++ interop and the app is not (Task 25 Step 0: `'functional' file not found` while building `NitroModules`). So
+iOS ships two pods: `ReactNativeOpenTelemetryCore` (pure Swift: `ios/Core` + the public `RNOtel` in `ios/RNOtel`) and
+the Nitro adapter `ReactNativeOpenTelemetry` (`ios/Adapter`), which depends on it and reaches the core's `package`
+declarations through one `-package-name`. Autolinking links only the adapter, so the app's Podfile adds
+`pod 'ReactNativeOpenTelemetryCore', :path => ''`. Both linkages build: the default static libraries
+(CI) and `USE_FRAMEWORKS=static` (checked locally in Task 25, not a CI job: e2e `ios-bare` 18/18 on that build).
+
+**`performance.timeOrigin` on Hermes (X17, Task 13).** Defined on both platforms (RN 0.88.1 release, Hermes),
+checked with a one-off `console.log` of `timeOrigin`, `performance.now()` and `Date.now()` at app start:
+Android `timeOrigin + now()` = `Date.now()` within 1 ms; **iOS simulator `timeOrigin + now()` was ~23.9 h behind
+`Date.now()`** (the monotonic clock under `now()` stopped while the host slept; `timeOrigin` stayed at simulator boot).
+sdk-trace 3.1 is unaffected: each span recomputes `_performanceOffset = Date.now() - (now() + timeOrigin)` at start,
+so explicit times, default times and `addEvent(name, perfNumber)` stay correct. Known limit: anything that turns
+`performance.now()` values into wall-clock with `timeOrigin` alone (e.g. `@opentelemetry/core` `hrTime()` without
+an argument) can be off by that skew on iOS.
+
The fake collector listens on port 4318; the app reaches it at `10.0.2.2` (Android emulator) or `localhost` (iOS simulator).
+## Expo app (Task 28)
+
+`example-expo/`: **Expo SDK 58** (`expo` 58.0.26), **React Native 0.88.1**, React 19.3.0, `react-native-nitro-modules`
+0.37.2, all pinned exactly. SDK 58 is the newest Expo SDK (npm `latest`, 2026-11-24) and bundles the same RN as the bare
+app. Built locally with Xcode 27.1; the CI jobs `e2e-android-expo` / `e2e-ios-expo` (`xcode-27`, Xcode 27.0) are
+unproven until their first CI run.
+
+- **Init: JS fallback.** No native init. `index.js` calls `startReactNativeSdk({serviceName: 'verify', exportConfig:
+ {url, headers: {'x-api-key': 'test'}}})` (no `serviceVersion`, R2) before registering the bare example's
+ `ScenariosScreen`, whose later `startReactNativeSdk()` calls get that first handle. Native reports `testMode` from its
+ build flag; the config has no test fields.
+- **Metro:** `withOtel(mergeConfig(getDefaultConfig(__dirname), β¦))` with Expo's `getDefaultConfig`; same single-copy
+ resolver setup as the bare app (blocks the root's and `example/`'s React Native copies). Babel: `babel-preset-expo`
+ plus the bare example's `OTEL_TEST_MODE` inline plugin.
+- **Autolinking:** Expo autolinking reads `example-expo/react-native.config.js`, which points at the repo root and at
+ the bare example's TestNative, so the `cross-*` scenarios run on Expo too.
+- **Config plugins** (`app.json`): the package's own `react-native-open-telemetry` (`app.plugin.js`) adds
+ `pod 'ReactNativeOpenTelemetryCore', :path => '../..'` to the Podfile (R24), as in any Expo app. Expo resolves it by
+ package name: `example-expo`'s `postinstall` links `node_modules/react-native-open-telemetry` to the repo root (bun
+ cannot install the root as a `file:` dependency: it looks for the root's `patches/` relative to the app). Then the
+ example-only `example-expo/plugins/withOtelExample.js` sets `usesCleartextTraffic` (the collector is plain HTTP), adds
+ the bundle task inputs, and with `OTEL_TEST_MODE=1` at prebuild writes `otelTestMode=true` to `gradle.properties`.
+ iOS takes test mode at `OTEL_TEST_MODE=1 pod install`.
+- **R8:** Expo release builds minify (`android.enableMinifyInReleaseBuilds=true`). The library now ships
+ `android/consumer-rules.pro`: `-dontwarn` for otel-java's optional compile-only classes, and a keep rule for
+ `io.opentelemetry.sdk.resources.**`, which otel-java's `ResourceMarshaler` reaches by reflection
+ (`EntityUtil.getEntities`). Without it every export threw `Error calling getEntities on Resource` and nothing arrived.
+- **Not on Expo:** `native-init-failure` (`targets: ['android-bare', 'ios-bare']`): the bad URL goes to the bare app's
+ native init, and the Expo app has none. `fast-refresh-idempotent` runs on the bare dev builds only, locally.
+
+## Web (Task 23)
+
+The `web` target is the Expo app's Metro web export (`example-expo`, `expo export -p web`): its `ScenariosScreen`
+through react-native-web 0.21.4 (react-dom 19.3.0). `index.js` inits first with
+`startReactNativeSdk({serviceName: 'verify', exportConfig: {url: 'http://localhost:4318/v1/traces', headers: {'x-api-key':
+'test'}}})`, so every scenario runs through the **web SDK** (own `TracerProvider`, `BatchSpanProcessor`, OTLP/proto
+exporter, R7), not a harness provider. Metro resolves the package through its `exports` (`browser` β
+`lib/module/index.web.js`); on web, `metro.config.js` maps `react-native-nitro-modules` to `nitro-stub.web.ts` (no
+HybridObjects: no native `testMode` line, scenarios get no `native`).
+
+- **Test mode:** `isTestModeBuild()` reads plain `process.env.OTEL_TEST_MODE` inside a `try` (a browser has no
+ `process`). That one form is what the Babel plugin (`example/inlineTestMode.js`, on every platform) and Jest's real
+ `process` both see. The e2e config builds with `OTEL_TEST_MODE=1`.
+- **Runner:** the `web` target (`web({browser: 'chromium'})`) starts `bun run web:e2e` in `example-expo/`
+ (`expo export -p web` + `expo serve` on `localhost:4173`); its log is `verify/e2e/.e2e/logs/web.log`. `app.restart()`
+ opens a new page, the cold start (R5). The collector answers CORS (`OPTIONS` 204, `allow-headers: *`).
+- **Probe:** `babel-preset-expo` keeps native `async` on web; `example-expo/babel.config.js` adds the two async
+ plugins for the web platform, so the bundle has no native `async`/`for await`; no `com.callstack.context.degraded`
+ scope attribute in any web file.
+- **Files:** every `*.web.otlp.json` is byte-identical to the scenario's `.js` file (`collector-down`, `handoff-basic`,
+ `odd-attributes` and `export-headers`, which have no `.js`, equal their `.android` file). The proto exporter and the web resource (`service.name` only in test mode)
+ change nothing visible.
+- **collector-down:** the OTel JS exporter retries a 503 inside the export (backoff 1 s Γ1.5, Β±20 %), so the first
+ `flush` resolves after the three refusals (~4.7 s; up to 5.7 s): the web flush timeout is 10 s.
+- **nest-timers-microtasks:** browsers have no `setImmediate`; there the `immediate` step is one more `setTimeout(0)`,
+ so all runners keep one shape.
+- **Not on web:** `cross-*` (TestNative is native), `native-init-failure` (bare native init), `flush-after-reload`
+ (the native reload; a page reload drops the JS context, a different guarantee), `background-flush` (app
+ background; the browser `pagehide` flush is not covered), `fast-refresh-idempotent`, `native test mode reaches initialize`.
+
+## Failure scenarios (Task 27)
+
+Each has its own e2e file (R10); the ScenariosScreen does not `forceFlush()` after `collector-down`,
+`flush-after-reload` and `background-flush`, so the test decides what exports. Test-mode-only screen controls:
+`flush` (a JS `forceFlush()`, shows `flush-done-`), `reload` (`TestNative.reload()`) and `patch-identity`.
+
+- **Test mode has no timed export.** Test-mode native cores set the batch processor's schedule delay to 120 s
+ (default 5 s), so within a device test only a flush or the background hook sends anything. Without it,
+ `background-flush` and `flush-after-reload` would pass on the timer alone.
+- `collector-down`: `refuse(503, 3)` after `begin`, `scenario-done` within 2 s, then three `flush` taps (each
+ resolves while the collector refuses); the span arrives once. Android: otel-java retries a 503 inside the export.
+ **iOS (X6):** opentelemetry-swift 2.6's `OtlpHttpTraceExporter` does not retry; with its default
+ `requeueOnFailure: true` it keeps a failed batch in memory and resends it on the next `export` or `flush` (our core
+ flush calls both). So on iOS the span arrives on the first flush after the collector is back, not by itself; its
+ batch processor never exports an empty queue. No exception needed, no hand-rolled retry.
+- `native-init-failure`: the example's native init gets `exportUrl = "not a url"`, in test-mode builds only (R26).
+ iOS: launch argument `--otel-export-url=not a url` (AppDelegate, `#if OTEL_TEST_MODE`; the Podfile adds the
+ condition to the app target). Android: `Application.onCreate` cannot see launch arguments (they reach the
+ Activity), so the test writes `/sdcard/Android/data/opentelemetry.example/files/otel-export-url` (mode 644, removed
+ afterwards and before each install's warm-up launch) and `OtelInit.kt` (called from `MainApplication`) reads it. Asserted: exactly one log line with `telemetry is off` (native `RNOtel`
+ plus JS `[react-native-open-telemetry]` lines), `scenario-done` (the no-op `forceFlush()` resolved), and the empty
+ expected file. JS no longer repeats a native-first failure that native already reported (`alreadyInitialized`).
+- `flush-after-reload`: `reload`, then `flush` must resolve within 5 s, the span arrives once.
+ **Step 0:** `DevSettings.reload()` is a no-op in release builds (JS side, `__DEV__` only), on both platforms. The
+ example's TestNative `reload()` calls `ReactHost.reload` / `RCTTriggerReloadCommandListeners`, the native reload
+ that OTA updaters use, so this runs on the release builds, per PR, with no extra build.
+- `background-flush`: `device.home()` right after `scenario-done`; something must arrive within 15 s. Android: no
+ `am_anr` for the app in the events log. Checked: without `home()` nothing arrives within 15 s on either platform.
+- `fast-refresh-idempotent` (dev builds + Metro: local only): each of two
+ edits of `lib/module/setup.js` appends `globalThis.__otelRefreshes += 1`; Metro hot-updates it, it re-runs
+ `installContextPatch`, and `patch-identity` must read `same refreshes=` (`then`/`setTimeout` are still the
+ functions first seen; a full reload would reset the count). Then `nest-after-await` must match its own expected
+ file. The test edits `lib/`, so run `bun run prepare` first; a killed run leaves the extra line in
+ `lib/module/setup.js`, which `bun run prepare` clears. Run it:
+
+ ```sh
+ cd example/android && OTEL_TEST_MODE=1 ./gradlew :app:assembleDebug -PotelTestMode=true
+ cd example/ios && OTEL_TEST_MODE=1 xcodebuild -workspace OpenTelemetryExample.xcworkspace -scheme OpenTelemetryExample \
+ -configuration Debug -sdk iphonesimulator -derivedDataPath build build
+ cd example && OTEL_TEST_MODE=1 bunx react-native start # keep running; Android also: adb reverse tcp:8081 tcp:8081
+ E2E_DEV=1 bunx e2e run --config verify/e2e/e2e.config.ts --target android-dev,ios-dev fast-refresh-idempotent
+ ```
+
+ If watchman reports recrawls, restart Metro: a dead watch never delivers the edit.
+
+## Android cold start with `RNOtel.start` (Task 24, 2026-11-24)
+
+`adb shell am start -W -n opentelemetry.example/.MainActivity` after `am force-stop`, 6 launches each, Pixel_9
+emulator (API 36, arm64), release test-mode build. `TotalTime` (ms):
+
+| Build | runs | min | median |
+| --- | --- | --- | --- |
+| before (no `RNOtel.start`, JS-direct) | 178, 194, 401, 327, 228, 180 | 178 | 211 |
+| after (`RNOtel.start` in `MainApplication.onCreate`) | 265, 206, 234, 293, 316, 191 | 191 | 250 |
+
+Emulator noise (Β±100 ms between runs) is larger than the difference; `RNOtel.start` builds the resource, the
+batch processor and the provider, but no exporter or OkHttp client (built on the first export, on the BSP thread).
+Task 29 measures properly on a device.
+
## Device capability check (Task 7, 2026-11-23)
What Task 27 (reload, fast refresh, background flush) needs from agent-device.
@@ -21,16 +212,16 @@ iOS: iPhone 18 Pro simulator, iOS 27.0, Xcode 27.1, agent-device 0.21.36 (T3 dev
| Capability | iOS simulator | Android emulator (Pixel_9) |
| --- | --- | --- |
-| JS reload | β `agent-device metro reload` (Metro re-bundled; screen state reset) | not checked: blocked, see below |
-| Fast refresh (dev build) | β editing `ScenariosScreen.tsx` text showed on device with React state kept | not checked |
-| Background and back | β `agent-device home`, then `open opentelemetry.example`: UIKit logged the background task end and `UIApplicationWillEnterForegroundNotification`; state kept. `appstate` still says `runningForeground` after `home` (known iOS quirk, documented by e2e), so check lifecycle in the log, not `appstate` | not checked |
-| Read logs | β `agent-device logs start/stop` captures the app's unified log, `NSLog` lines included (`RNOtel handOff β¦`). The e2e harness reads with `xcrun simctl spawn log show --predicate 'process == "OpenTelemetryExample" β¦'` | β via the e2e harness: `adb logcat -d -s RNOtel:I` (tracer-bullet test green) |
+| JS reload | β `agent-device metro reload` (Metro re-bundled; screen state reset). Release: native reload via TestNative (Task 27) | β release: native reload via TestNative, e2e `flush-after-reload` (Task 27). `DevSettings.reload()` is a no-op in release |
+| Fast refresh (dev build) | β editing `ScenariosScreen.tsx` text showed on device with React state kept | β e2e `fast-refresh-idempotent` on `android-dev` (Task 27) |
+| Background and back | β `agent-device home`, then `open opentelemetry.example`: UIKit logged the background task end and `UIApplicationWillEnterForegroundNotification`; state kept. `appstate` still says `runningForeground` after `home` (known iOS quirk, documented by e2e), so check lifecycle in the log, not `appstate` | β `device.home()` in e2e `background-flush` (Task 27) |
+| Read logs | β `agent-device logs start/stop` captures the app's unified log, `NSLog` lines included (`RNOtel handOff β¦`). The e2e harness reads with `xcrun simctl spawn log show --predicate 'process == "OpenTelemetryExample" β¦'` | β via the e2e harness: `adb logcat -d -s RNOtel:I` (tracer-bullet test green; the test was retired in Task 24, R14) |
**Blocker (Android, interactive only):** the T3 device panel could not open `Pixel_9`:
`Failed to allocate an emulator port for Pixel_9 β¦ avdmanager: β¦ Unable to locate a Java Runtime.`
The T3 host process has no `JAVA_HOME`, so `avdmanager list avd` fails. The emulator itself boots and the e2e runner
(`@e2e-dev/mobile`, agent-device 0.21.39) drives it fine. Reload / fast refresh / background on Android still need a
-check before Task 27; fix the T3 host's Java (or run the check through an e2e test) and fill in the column.
+check before Task 27; fix the T3 host's Java (or run the check through an e2e test) and fill in the column. Task 27 filled it in through e2e tests.
## Scenarios
@@ -38,50 +229,45 @@ One file per guarantee in `verify/scenarios/`, named after it, with a hand-writt
(the cross-platform parity contract). Exact `..otlp.json` files are drafted by the owning task with
`VERIFY_UPDATE=1` and reviewed by the author. `pending` scenarios report as `todo`; the owning task flips `pending` off.
-Shapes use the JS runner's resource, `["service.name"]`. Native-first and device runs add resource keys
-(`service.version`, and `telemetry.*` outside test mode): Tasks 24/25 (and 29 for `smoke-device`) revise those
-shape files with the author.
+Shapes use the JS runner's resource, `["service.name"]`. Native test mode builds the resource from config only and
+the example inits with no `serviceVersion` (R2), so native-first device runs match the same shapes.
e2e targets are android, ios and web unless the Runners column names them.
| Scenario | Guarantee | Task | Runners | Status |
| --- | --- | --- | --- | --- |
-| `smoke-js` | the JS pipeline exports a span | 7 | jest | passing |
-| `nest-after-await` | a span after `await` is a child of the span active before it | 10 | jest, e2e | pending |
-| `nest-timers-microtasks` | `setTimeout`/`setImmediate`/`queueMicrotask` callbacks keep their scheduling context, also after the parent ended | 10 | jest, e2e | pending |
-| `nest-promise-all-race` | `Promise.all`/`race` branches and the code after them keep the parent | 10 | jest, e2e | pending |
-| `concurrent-interleaved` | interleaved async jobs keep their own parents; work after the join is a root | 10 | jest, e2e | pending |
-| `root-no-leak` | after a span's work ends, later work (fast path included) starts new roots | 10 | jest, e2e | pending |
-| `captured-then` | exception: a `then` captured before the patch loses the parent | 10 | jest, e2e | pending |
-| `async-generator` | async generator bodies and `for await` keep the parent | 10 | jest, e2e | pending |
-| `error-in-callback` | a throwing callback still restores context | 10 | jest, e2e | pending |
-| `never-settling-promise` | a never-settling promise does not leak its span into later work | 10 | jest, e2e | pending |
-| `interval-new-root` | exception: each `setInterval` tick is a new root | 10 | jest, e2e | pending |
-| `batching-shared-queue` | exception: a shared queue runs work as its first enqueuer (pinned wrong parent) | 10 | jest, e2e | pending |
-| `degraded-probe` | native `await` β degraded scope attribute, spans after `await` are roots | 11 | jest-degraded | pending |
-| `interaction-manager` | `runAfterInteractions` callback is a child of the caller's span | 13 | e2e | pending |
-| `nest-raf` | a `requestAnimationFrame` callback keeps its scheduling context | 13 | e2e | pending |
-| `event-emitter-listener` | a synchronous `DeviceEventEmitter` listener is a child of the emitter's span | 13 | e2e (android, ios) | pending |
-| `handoff-basic` | a span crosses the seam intact | 8, 15, 18 | jest, e2e | passing (js) |
-| `rich-span` | every attribute type, events, links, status, scope survive the seam | 8, 15, 18 | jest, e2e | passing (js) |
-| `odd-attributes` | NaN, Β±Infinity, -0, big ints, empty arrays survive the seam | 8, 15, 18 | jest, e2e | passing (js) |
-| `export-headers` | configured export headers are sent on every request | 16, 19 | e2e | pending |
-| `cross-js-to-native` | a native span started from JS is a child of the JS span | 26 | e2e (android, ios) | pending |
-| `cross-native-to-js` | a JS span started under a native span's context is its child | 26 | e2e (android, ios) | pending |
-| `collector-down` | app never blocks; spans arrive exactly once when the collector is back | 27 | e2e | pending |
-| `native-init-failure` | one error log, no-op SDK, nothing exported | 27 | e2e (android, ios) | pending |
-| `flush-after-reload` | `forceFlush()` resolves across a JS reload; spans arrive once | 27 | e2e (android, ios) | pending |
-| `background-flush` | spans are exported on background without `forceFlush()` | 27 | e2e (android, ios) | pending |
-| `fast-refresh-idempotent` | fast refresh does not stack the patch: `then`/`setTimeout` keep their identity across refreshes | 27 | e2e | pending |
-| `smoke-device` | production pipeline (no test mode) exports `smoke` spans | 29 | e2e (android, ios) | pending |
-| `perf-budget` | hand-off p50 < 100 Β΅s/span, patch ratio < 3Γ (`artifacts/perf.json`, no shape) | 29 | e2e (android) | pending |
+| `nest-after-await` | a span after `await` is a child of the span active before it | 10 | jest, e2e | passing |
+| `nest-timers-microtasks` | `setTimeout`/`setImmediate`/`queueMicrotask` callbacks keep their scheduling context, also after the parent ended | 10 | jest, e2e | passing |
+| `nest-promise-all-race` | `Promise.all`/`race` branches and the code after them keep the parent | 10 | jest, e2e | passing |
+| `concurrent-interleaved` | interleaved async jobs keep their own parents; work after the join is a root | 10 | jest, e2e | passing |
+| `root-no-leak` | after a span's work ends, later work (fast path included) starts new roots | 10 | jest, e2e | passing |
+| `captured-then` | exception: a `then` captured before the patch loses the parent | 10 | jest, e2e | passing |
+| `async-generator` | async generator bodies and `for await` keep the parent | 10 | jest, e2e | passing |
+| `error-in-callback` | a throwing callback still restores context | 10 | jest, e2e | passing |
+| `never-settling-promise` | a never-settling promise does not leak its span into later work | 10 | jest, e2e | passing |
+| `interval-new-root` | exception: each `setInterval` tick is a new root | 10 | jest, e2e | passing |
+| `batching-shared-queue` | exception: a shared queue runs work as its first enqueuer (pinned wrong parent) | 10 | jest, e2e | passing |
+| `interaction-manager` | `runAfterInteractions` callback is a child of the caller's span | 13 | e2e | pending: RN 0.88 removed `InteractionManager` |
+| `nest-raf` | a `requestAnimationFrame` callback keeps its scheduling context | 13 | e2e | passing |
+| `event-emitter-listener` | a synchronous `DeviceEventEmitter` listener is a child of the emitter's span | 13 | e2e (android, ios) | passing |
+| `handoff-basic` | a span crosses the seam intact | 8, 15, 18 | e2e | passing |
+| `rich-span` | every attribute type, events, links, status, scope survive the seam | 8, 15, 18 | jest, e2e | passing |
+| `odd-attributes` | NaN, Β±Infinity, -0, big ints, empty arrays survive the seam | 8, 15, 18 | e2e | passing |
+| `export-headers` | configured export headers are sent on every request | 16, 19, 23, 24, 25 | e2e | passing |
+| `cross-js-to-native` | a native span started from JS is a child of the JS span | 26 | e2e (android, ios) | passing |
+| `cross-native-to-js` | a JS span started under a native span's context is its child | 26 | e2e (android, ios) | passing |
+| `collector-down` | app never blocks; spans arrive exactly once when the collector is back | 23, 27 | e2e | passing |
+| `native-init-failure` | one error log, no-op SDK, nothing exported | 27 | e2e (android-bare, ios-bare) | passing |
+| `flush-after-reload` | `forceFlush()` resolves across a JS reload; spans arrive once | 27 | e2e (android, ios) | passing |
+| `background-flush` | spans are exported on background without `forceFlush()` | 27 | e2e (android, ios) | passing |
+| `fast-refresh-idempotent` | fast refresh does not stack the patch: `then`/`setTimeout` keep their identity across refreshes | 27 | e2e (android-dev, ios-dev; local only) | passing (local) |
### Adding a scenario
1. `verify/scenarios/.ts`: `export default scenario('', async ({tracer, at}) => {β¦}, opts)`.
Explicit `at(Β΅s)` start/end times on every span; parents through `context.active()` (`startActiveSpan`), not
- explicit parent contexts. `opts.runners` defaults to `['jest', 'e2e']` (`'jest-degraded'` is the native-`async` project), `opts.targets` to
- `['android', 'ios', 'web']` (the e2e harness skips other targets); `pending: true` until it passes.
+ explicit parent contexts. `opts.runners` defaults to `['jest', 'e2e']`, `opts.targets` to
+ `['android', 'ios', 'web']` (platforms or target names like `android-bare`; the e2e harness skips other targets); `pending: true` until it passes.
2. Hand-write `verify/expected/.shape.json` in exactly `shapeOf()`'s format (traces ordered by first
span start, spans sorted by name, `kind` 1 = INTERNAL) and get it reviewed.
3. `bun verify` regenerates `verify/scenarios/index.ts`. Un-pend, draft the exact files with `VERIFY_UPDATE=1 bun verify`
diff --git a/verify/e2e/perf.e2e.ts b/verify/e2e/perf.e2e.ts
deleted file mode 100644
index ae37561..0000000
--- a/verify/e2e/perf.e2e.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import {execFileSync} from 'node:child_process';
-import fs from 'node:fs';
-import path from 'node:path';
-import {expect} from 'e2e';
-import {MOBILE, test} from './harness';
-
-const BUDGET = {handoffP50Us: 100, patchRatio: 3};
-/** Report only: the gates use the unrounded values. */
-const round = (x: number) => Math.round(x * 100) / 100;
-const median = (xs: number[]) => {
- const s = [...xs].sort((a, b) => a - b);
- const m = s.length >> 1;
- return s.length % 2 ? s[m]! : (s[m - 1]! + s[m]!) / 2;
-};
-const OUT = path.join(import.meta.dirname, '..', 'artifacts', 'perf.json');
-
-/** OTLP/JSON attribute value -> number or number[] (NaN when missing, which fails both budgets). */
-const num = (v: any): number => Number(v?.doubleValue ?? v?.intValue ?? NaN);
-
-// Performance guardrail (Β§9.2, R27): perf-budget sends its numbers as the attributes of one `perf-result` span;
-// this test writes them to verify/artifacts/perf.json and fails only on the loose budgets. No shape file, no compare.
-// android-bare only, by target name (android-expo runs the same JS through another init path, not another hand-off).
-test('perf-budget', {platforms: MOBILE}, async ({app, screen, collector, device, target}) => {
- test.skip(target !== 'android-bare', 'perf-budget runs on android-bare only');
- await app.restart();
- collector.begin('perf-budget', 'android');
- let out;
- try {
- await screen.getByTestId('scenario-perf-budget').tap();
- await expect(screen.getByTestId('scenario-done')).toBeVisible({timeout: 120_000});
- } finally {
- out = await collector.end();
- }
- const span = (out.resourceSpans ?? [])
- .flatMap(r => r.scopeSpans.flatMap((s: any) => s.spans))
- .find(s => s.name === 'perf-result');
- if (!span) throw new Error('no perf-result span arrived');
- const attrs = new Map(span.attributes.map((a: any) => [a.key.replace(/^com\.callstack\.perf\./, ''), a.value]));
- const n = (k: string) => num(attrs.get(k));
- const ns = (k: string): number[] => (attrs.get(k)?.arrayValue?.values ?? []).map(num);
- const prop = (p: string) =>
- execFileSync('adb', ['-s', device.unstable_raw.deviceId, 'shell', 'getprop', p], {encoding: 'utf8'}).trim();
-
- const p50Us = n('handoff.p50_us');
- const onMs = ns('await.on_ms');
- const offMs = ns('await.off_ms');
- const ratio = onMs.length && offMs.length ? median(onMs) / median(offMs) : NaN;
- const report = {
- scenario: 'perf-budget',
- target,
- build: 'release, test mode on (test-mode ids and resource; the same JS -> Nitro hand-off seam as production)',
- measuredAt: new Date().toISOString(),
- device: {
- model: prop('ro.product.model'),
- emulator: prop('ro.kernel.qemu') === '1' || prop('ro.boot.qemu') === '1',
- abi: prop('ro.product.cpu.abi'),
- androidRelease: prop('ro.build.version.release'),
- apiLevel: Number(prop('ro.build.version.sdk')),
- },
- handoff: {
- what: 'per span, in the test-mode build: tracer.startSpan -> setAttribute x10 -> end(), through NativeHandOffProcessor.onEnd -> Nitro handOff (synchronous on the JS thread, the production seam); performance.now() around each span',
- spans: n('handoff.spans'),
- warmupSpans: n('handoff.warmup'),
- p50Us: round(p50Us),
- p95Us: round(n('handoff.p95_us')),
- endOnlyP50Us: round(n('handoff.end_p50_us')), // end() alone: onEnd, isSampled, toSeamSpan, handOff
- budgetP50Us: BUDGET.handoffP50Us,
- },
- patch: {
- what: 'in the test-mode build: alternating rounds (on, off, on, off, β¦) of N sequential `await null` inside an active span (the wrapped path); off = Promise.prototype.then restored from the patch marker for the leg (R27); ratio = median(on) / median(off)',
- awaitsPerLeg: n('await.count'),
- rounds: n('await.rounds'),
- onMs: onMs.map(round),
- offMs: offMs.map(round),
- medianOnMs: round(median(onMs)),
- medianOffMs: round(median(offMs)),
- ratio: round(ratio),
- budgetRatio: BUDGET.patchRatio,
- },
- };
- fs.mkdirSync(path.dirname(OUT), {recursive: true});
- fs.writeFileSync(OUT, JSON.stringify(report, null, 2) + '\n');
- console.log(`perf.json: ${JSON.stringify(report)}`);
- expect(p50Us).toBeLessThan(BUDGET.handoffP50Us);
- expect(ratio).toBeLessThan(BUDGET.patchRatio);
-});
diff --git a/verify/e2e/scenarios.e2e.ts b/verify/e2e/scenarios.e2e.ts
index 9811f1d..a6d6c9a 100644
--- a/verify/e2e/scenarios.e2e.ts
+++ b/verify/e2e/scenarios.e2e.ts
@@ -7,8 +7,6 @@ const OWN_FILE = new Set([
'flush-after-reload',
'background-flush',
'fast-refresh-idempotent',
- 'smoke-device',
- 'perf-budget',
'export-headers',
]);
diff --git a/verify/e2e/smoke.e2e.ts b/verify/e2e/smoke.e2e.ts
deleted file mode 100644
index fbc00c6..0000000
--- a/verify/e2e/smoke.e2e.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import {expect} from 'e2e';
-import {MOBILE, test} from './harness';
-
-// Device smoke (Β§9.4, R20): the production pipeline, test mode off (native and JS), exports the `smoke` span.
-// Count and names only: ids, times and the real resource (telemetry.*) are not deterministic, so no expected file.
-// Needs a test-mode-off build: E2E_SMOKE=1 runs only this file (verify/stages/e2e.ts); VERIFY.md has the builds.
-test('smoke-device', {platforms: MOBILE}, async ({app, screen, collector, target}) => {
- test.skip(process.env.E2E_SMOKE !== '1', 'needs a test-mode-off build (E2E_SMOKE=1)');
- await app.restart();
- // a test-mode build (native flag, or a stale bundle with the JS flag inlined) would not prove the production path
- await expect(screen.getByTestId('native-test-mode')).toHaveText('native testMode=false', {timeout: 30_000});
- await expect(screen.getByTestId('flush')).not.toBeVisible();
- collector.begin('smoke-device', target);
- let out;
- try {
- await screen.getByTestId('scenario-smoke-device').tap();
- await expect(screen.getByTestId('scenario-done')).toBeVisible({timeout: 30_000});
- } finally {
- out = await collector.end();
- }
- const names = (out.resourceSpans ?? []).flatMap(r => r.scopeSpans.flatMap((s: any) => s.spans.map((x: any) => x.name)));
- expect(names).toEqual(['smoke']);
-});
diff --git a/verify/scenarios/index.ts b/verify/scenarios/index.ts
index 59e7362..009cc7b 100644
--- a/verify/scenarios/index.ts
+++ b/verify/scenarios/index.ts
@@ -23,9 +23,7 @@ import nestRaf from './nest-raf';
import nestTimersMicrotasks from './nest-timers-microtasks';
import neverSettlingPromise from './never-settling-promise';
import oddAttributes from './odd-attributes';
-import perfBudget from './perf-budget';
import richSpan from './rich-span';
import rootNoLeak from './root-no-leak';
-import smokeDevice from './smoke-device';
-export const allScenarios = (): Scenario[] => [asyncGenerator, backgroundFlush, batchingSharedQueue, capturedThen, collectorDown, concurrentInterleaved, crossJsToNative, crossNativeToJs, errorInCallback, eventEmitterListener, exportHeaders, fastRefreshIdempotent, flushAfterReload, handoffBasic, interactionManager, intervalNewRoot, nativeInitFailure, nestAfterAwait, nestPromiseAllRace, nestRaf, nestTimersMicrotasks, neverSettlingPromise, oddAttributes, perfBudget, richSpan, rootNoLeak, smokeDevice];
+export const allScenarios = (): Scenario[] => [asyncGenerator, backgroundFlush, batchingSharedQueue, capturedThen, collectorDown, concurrentInterleaved, crossJsToNative, crossNativeToJs, errorInCallback, eventEmitterListener, exportHeaders, fastRefreshIdempotent, flushAfterReload, handoffBasic, interactionManager, intervalNewRoot, nativeInitFailure, nestAfterAwait, nestPromiseAllRace, nestRaf, nestTimersMicrotasks, neverSettlingPromise, oddAttributes, richSpan, rootNoLeak];
diff --git a/verify/scenarios/perf-budget.ts b/verify/scenarios/perf-budget.ts
deleted file mode 100644
index ab22477..0000000
--- a/verify/scenarios/perf-budget.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import {context, trace} from '@opentelemetry/api';
-import {scenario} from '../harness/scenario';
-
-const SPANS = 1_000;
-const WARMUP = 100;
-const AWAITS = 20_000;
-const ROUNDS = 5;
-const P = 'com.callstack.perf.';
-
-const pct = (xs: number[], p: number) => [...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor(xs.length * p))]!;
-const us = (ms: number) => ms * 1000; // unrounded: perf.e2e.ts gates on these and rounds only for the report
-
-async function awaits(n: number) {
- const t0 = performance.now();
- for (let i = 0; i < n; i++) await null;
- return performance.now() - t0;
-}
-
-/**
- * Performance guardrail (Β§9.2, Task 29), `android-bare` only: (a) 1,000 spans Γ 10 attributes through the real
- * hand-off, p50/p95 Β΅s per span; (b) 5 alternating rounds of 20,000 awaits inside an active span, patch on vs off (R27: `then`
- * restored from the patch marker for the off leg). The numbers leave as the attributes of one `perf-result` span;
- * verify/e2e/perf.e2e.ts writes `verify/artifacts/perf.json` and applies the budgets. No shape file.
- */
-export default scenario(
- 'perf-budget',
- async ({tracer}) => {
- const total: number[] = [];
- const end: number[] = [];
- for (let i = 0; i < WARMUP + SPANS; i++) {
- const t0 = performance.now();
- const span = tracer.startSpan('perf');
- for (let a = 0; a < 10; a++) span.setAttribute(`a${a}`, i);
- const t1 = performance.now();
- span.end();
- const t2 = performance.now();
- if (i < WARMUP) continue;
- total.push(t2 - t0);
- end.push(t2 - t1);
- }
-
- const marker = (globalThis as any)[Symbol.for('com.callstack.otel.patched')];
- if (!marker) throw new Error('perf-budget: the context patch is not installed');
- const patched = Promise.prototype.then;
- // inside an active span: the wrapped path (at ROOT the patch calls the original `then` directly). Each leg
- // enters the span's context itself, since the off leg loses it after its first await.
- const span = tracer.startSpan('perf.awaits');
- const inSpan = (n: number) => context.with(trace.setSpan(context.active(), span), () => awaits(n));
- await inSpan(1_000); // warm-up
- // alternating legs (on, off, on, off, β¦): perf.e2e.ts gates on median(on) / median(off), so one GC pause or a
- // warm-up drift in either leg does not decide the ratio
- const onMs: number[] = [];
- const offMs: number[] = [];
- for (let r = 0; r < ROUNDS; r++) {
- onMs.push(await inSpan(AWAITS));
- Promise.prototype.then = marker.then;
- try {
- offMs.push(await inSpan(AWAITS));
- } finally {
- Promise.prototype.then = patched;
- }
- }
- span.end();
-
- tracer
- .startSpan('perf-result', {
- attributes: {
- [`${P}handoff.spans`]: SPANS,
- [`${P}handoff.warmup`]: WARMUP,
- [`${P}handoff.p50_us`]: us(pct(total, 0.5)),
- [`${P}handoff.p95_us`]: us(pct(total, 0.95)),
- [`${P}handoff.end_p50_us`]: us(pct(end, 0.5)),
- [`${P}await.count`]: AWAITS,
- [`${P}await.rounds`]: ROUNDS,
- [`${P}await.on_ms`]: onMs,
- [`${P}await.off_ms`]: offMs,
- },
- })
- .end();
- },
- {runners: ['e2e'], targets: ['android-bare']},
-);
diff --git a/verify/scenarios/smoke-device.ts b/verify/scenarios/smoke-device.ts
deleted file mode 100644
index 096deb6..0000000
--- a/verify/scenarios/smoke-device.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import {scenario} from '../harness/scenario';
-
-/**
- * Device smoke (Β§9.1, Task 29): production pipeline, test mode off, on every mobile target. Spans named
- * `smoke` arrive; only count and names are asserted (ids, times and the real resource are not deterministic).
- */
-export default scenario(
- 'smoke-device',
- async ({tracer}) => {
- tracer.startSpan('smoke').end();
- },
- {runners: ['e2e'], targets: ['android', 'ios']},
-);
diff --git a/verify/stages/e2e.ts b/verify/stages/e2e.ts
index d582008..e7bfed6 100644
--- a/verify/stages/e2e.ts
+++ b/verify/stages/e2e.ts
@@ -6,16 +6,11 @@ const stage: Stage = {
order: 90,
e2e: true,
run() {
- // E2E_TARGET=android-bare|ios-bare|android-expo|ios-expo runs one target (CI runs one per job)
const target = process.env.E2E_TARGET ? ['--target', process.env.E2E_TARGET] : [];
- // E2E_SMOKE=1: a test-mode-off build is installed, so only smoke.e2e.ts can pass (VERIFY.md)
- const files = process.env.E2E_SMOKE === '1' ? ['smoke'] : [];
- // Device runs compare to the reviewed expected files: never --update them from a device.
const update = process.env.VERIFY_UPDATE;
delete process.env.VERIFY_UPDATE;
try {
- // stdio inherited, not ctx.sh's captured stdout: a long device run shows progress live, and a killed step keeps it
- const cmd = ['bunx', 'e2e', 'run', '--config', 'verify/e2e/e2e.config.ts', ...target, ...files];
+ const cmd = ['bunx', 'e2e', 'run', '--config', 'verify/e2e/e2e.config.ts', ...target];
const p = spawnSync(cmd[0]!, cmd.slice(1), {stdio: 'inherit'});
if (p.status !== 0) throw new Error(`${cmd.join(' ')} exited ${p.status ?? p.signal}`);
} finally {
diff --git a/verify/stages/static.ts b/verify/stages/static.ts
index cd308b3..31afa19 100644
--- a/verify/stages/static.ts
+++ b/verify/stages/static.ts
@@ -1,6 +1,4 @@
import type {Stage} from '../run';
-import fs from 'node:fs';
-import path from 'node:path';
import {packContents, REQUIRED} from '../static/packContents';
const stage: Stage = {
@@ -10,9 +8,8 @@ const stage: Stage = {
run({sh}) {
sh(['bunx', 'tsc', '--noEmit']);
sh(['bun', 'run', 'codegen']);
- sh(['bun', 'run', '--cwd', 'example/modules/test-native', 'codegen']); // the example's TestNative module (Task 26)
+ sh(['bun', 'run', '--cwd', 'example/modules/test-native', 'codegen']);
const generated = ['nitrogen/', 'example/modules/test-native/nitrogen/'];
- // git diff ignores untracked files, so list them too.
sh(['git', 'diff', '--exit-code', ...generated]);
if (sh(['git', 'ls-files', '--others', '--exclude-standard', ...generated]).trim()) {
throw new Error('nitrogen/generated is out of date: run `bun run codegen` and commit');
@@ -22,11 +19,6 @@ const stage: Stage = {
const list: string[] = JSON.parse(out)[0].files.map((f: {path: string}) => f.path);
const missing = packContents(list, REQUIRED);
if (missing.length) throw new Error(`npm pack is missing: ${missing.join(', ')}`);
- // iOS has no build-time access to package.json (Android reads it in Gradle): the Swift constant must match.
- const root = path.join(import.meta.dirname, '..', '..');
- const {version} = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
- if (!fs.readFileSync(path.join(root, 'ios', 'RNOtel', 'RNOtel.swift'), 'utf8').includes(`let packageVersion = "${version}"`))
- throw new Error(`ios/RNOtel/RNOtel.swift: set packageVersion to "${version}" (package.json)`);
sh(['bunx', 'jest', '--selectProjects', 'harness']);
},
};