diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro index 6f1650f..180211e 100644 --- a/android/consumer-rules.pro +++ b/android/consumer-rules.pro @@ -1,4 +1,4 @@ -# Guarded by the minified Expo release e2e (Task 28): recheck these rules on every otel-java bump. +# Guarded by the minified Expo release e2e: recheck these rules on every otel-java bump. # otel-java references optional, compile-only classes it never loads at runtime here (no autoconfigure, no incubator, # annotations only); R8 in a minifying app fails on them as missing. -dontwarn com.google.auto.value.** diff --git a/android/src/main/java/com/callstack/otel/core/OtelCore.kt b/android/src/main/java/com/callstack/otel/core/OtelCore.kt index b04ae7e..99173d4 100644 --- a/android/src/main/java/com/callstack/otel/core/OtelCore.kt +++ b/android/src/main/java/com/callstack/otel/core/OtelCore.kt @@ -52,7 +52,7 @@ class OtelCore(config: CoreConfig, testMode: Boolean = false, distroVersion: Str OtlpHttpSpanExporter.builder().setEndpoint(config.exportUrl) .apply { config.exportHeaders.forEach { (k, v) -> addHeader(k, v) } }.build() }, - // test mode: no timed export within a device test, so only flush and background export send (Task 27) + // test mode: no timed export within a device test, so only flush and background export send ).apply { if (testMode) setScheduleDelay(120, TimeUnit.SECONDS) }.build() /** The native TracerProvider; JS spans join its batch processor. */ diff --git a/docs/superpowers/plans/2026-11-21-rn-otel-v0.md b/docs/superpowers/plans/2026-11-21-rn-otel-v0.md deleted file mode 100644 index afa6f2f..0000000 --- a/docs/superpowers/plans/2026-11-21-rn-otel-v0.md +++ /dev/null @@ -1,611 +0,0 @@ -# React Native OpenTelemetry v0 Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**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 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. - -**Spec:** `docs/superpowers/specs/2026-11-10-rn-otel-design.md` (visual summary: https://claude.ai/artifact/UWTqogG1HpfZuQX2NHPQ12). Section references below (§n) point into the spec. Revised after the council review of 2026-11-21. - -## 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 ≥ 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`; 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: 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). -- Expected files: `verify/expected/.shape.json` (hand-written, one per scenario) and `verify/expected/..otlp.json` (drafted with `--update`), platform ∈ `js | android | ios | web`, OTLP/JSON with hex IDs. `verify/` is behind `CODEOWNERS`. Any new or changed expected file needs the author's review before the task is done. - > Superseded during review: one `verify/expected/.otlp.json` per scenario for every platform; no shape files. iOS's known opentelemetry-swift gaps (time rounding, unwritten flags/traceState/schemaUrl) are accepted in the compare step only. -- Fixture JSON encodes `NaN`, `Infinity`, `-Infinity`, `-0` as `{"$num": ""}`. -- `e2e` pinned to `0.24.0`; CI sets `E2E_TELEMETRY_DISABLED=1`. - -## 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**: 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. - ---- - -## Lanes and order - -| Phase | Lane | Tasks | Depends on | Worktree branch | -|---|---|---|---|---| -| 0 | Contracts + tracer bullet (serial) | 1–9 | — | `v0/contracts` | -| 1 | L1 Context | 10–13 | Phase 0 | `v0/l1-context` | -| 1 | L2 JS SDK | 14 | Phase 0; L1 Tasks 10–11 | `v0/l2-sdk` | -| 1 | L3 Kotlin core | 15–17 | Phase 0 | `v0/l3-kotlin` | -| 1 | L4 Swift core | 18–20 | Phase 0 | `v0/l4-swift` | -| 1 | L5 Web | 21–23 | Phase 0; L1 Tasks 10–11 (21), Task 13 (23) | `v0/l5-web` | -| 2 | Android adapter | 24 | L1, L2, L3 | `v0/p2-android` | -| 2 | iOS adapter | 25 | L1, L2, L4 | `v0/p2-ios` | -| 2 | Integration (both platforms, one lane) | 26–30 | 24 and 25 | `v0/p2-integration` | -| 2 | Release | 31–32 | 30 | `v0/release` | - -- **Phase 0 must be merged and the Task 9 review done before any Phase 1 lane starts.** -- CI is not a separate lane: Task 6 gates every PR from Phase 0 on, and each task that adds an e2e target adds its CI job in the same commit (Tasks 7, 23, 28). -- Merge-conflict rules: every dependency of Phases 0–1 is added in Task 1; `verify/run.ts` discovers stages from `verify/stages/*.ts`, so lanes add files instead of editing it; scenarios register through `verify/scenarios/index.ts`, generated by a glob in `scenario.ts`. - -## File structure - -``` -src/ - index.ts public API: startReactNativeSdk - sdk/start.ts mobile startReactNativeSdk (attach or fallback init), clock offset - sdk/start.web.ts web startReactNativeSdk (startBrowserSdk) - sdk/config.ts SdkConfig type, endpoint normalization - sdk/noop.ts no-op handle - 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 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) -nitro.json, nitrogen/generated/ -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 -ios/Core/ pure Swift core -ios/Adapter/ Nitro adapter, RNOtel public API -ReactNativeOpenTelemetry.podspec -verify/ - harness/collector.ts fake collector (server + control API) - harness/otlpJson.ts protobuf -> OTLP/JSON - harness/normalize.ts merge + sort, never rewrite - harness/compare.ts structured diff, expected(), update mode - harness/shape.ts shapeOf + compare to .shape.json - 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 - expected/*.shape.json, expected/*.otlp.json - 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` - VERIFY.md -example/ bare RN app (native-first init), recreated at latest RN -example-expo/ Expo prebuild app (JS-fallback init) -.githooks/pre-commit -.github/workflows/{ci,scheduled,release}.yml -CODEOWNERS -``` - ---- - -## Phase 0 — Contracts and tracer bullet - -### Task 1: Clean skeleton, packaging, static stage, pre-commit hook - -**Files:** -- Delete: `src/*`, `android/src/main/java/com/opentelemetry/*`, `ios/*`, `OpenTelemetry.podspec`, `example/` (all of it, including `example/collector/`; the fake collector replaces it) -- Modify: `package.json`, `tsconfig.json`, `.github/workflows/ci.yml` (temporarily: static only) -- Create: `src/index.ts` (empty export), `verify/run.ts`, `verify/stages/static.ts`, `verify/static/packContents.ts`, `.githooks/pre-commit`, `jest.config.js`, `CODEOWNERS` - -**Interfaces:** -- 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"`, `"./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`. - -- [ ] **Step 1: Write the failing test** `verify/static/packContents.test.ts`: `packContents` returns `['nitrogen/']` for a list lacking any `nitrogen/` path, `[]` for a complete list. -- [ ] **Step 2: Run** `bunx jest verify/static` → FAIL. -- [ ] **Step 3: Implement**; static stage runs `tsc --noEmit`, `oxlint`, `packContents` on `npm pack --dry-run --json`, `jest --selectProjects harness`. -- [ ] **Step 4: Run** `bun run prepare` → `lib/` built; `bun verify` → static green. -- [ ] **Step 5: Commit** `chore: reset to v0 skeleton with packaging and static stage`. - -### Task 2: Nitro spec - -**Files:** -- Create: `src/native/Otel.nitro.ts`, `src/native/otel.ts`, `nitro.json`, `nitrogen/generated/**` (generated) -- Modify: `package.json` (script `codegen`), `verify/stages/static.ts` (`nitrogen && git diff --exit-code nitrogen/`) - -**Interfaces:** -- Produces (exact, `src/native/Otel.nitro.ts`): -```ts -export type HrTime = [seconds: number, nanos: number]; -export interface SeamSpanContext { traceId: string; spanId: string; traceFlags: number; traceState?: string } -export type AttrValue = string | number | boolean | string[] | number[] | boolean[]; -export interface SeamAttribute { key: string; value: AttrValue } -export interface SeamEvent { name: string; time: HrTime; attributes: SeamAttribute[] } -export interface SeamLink { context: SeamSpanContext; attributes: SeamAttribute[] } -export interface SeamScope { name: string; version?: string; schemaUrl?: string; attributes: SeamAttribute[] } -export interface SeamSpan { - context: SeamSpanContext; parentSpanId?: string; name: string; kind: number; - start: HrTime; end: HrTime; attributes: SeamAttribute[]; events: SeamEvent[]; - links: SeamLink[]; status: { code: number; message?: string }; scope: SeamScope; -} -export interface SeamConfig { - serviceName: string; serviceVersion?: string; resourceAttributes: SeamAttribute[]; - exportUrl: string; exportHeaders: SeamAttribute[]; -} -export interface SeamInitResult { alreadyInitialized: boolean; testMode: boolean; error?: string } -export interface Otel extends HybridObject<{ ios: 'swift'; android: 'kotlin' }> { - initialize(config?: SeamConfig): SeamInitResult; - handOff(spans: SeamSpan[]): void; - flush(timeoutMs: number): Promise; -} -``` - `testMode` tells JS the native build was compiled in test mode, so JS uses `0a` sequential IDs without any public switch. If nitrogen rejects the array members of the `AttrValue` variant, replace `AttrValue` with a tagged struct `{ type: 'string'|'double'|'bool'|'stringArray'|'doubleArray'|'boolArray'; s?: string; d?: number; b?: boolean; sa?: string[]; da?: number[]; ba?: boolean[] }` and record that change in spec §4.3. -- `src/native/otel.ts`: `getOtel(): Otel | undefined` (returns `undefined` when the HybridObject isn't registered: web, Jest, Expo Go). - -- [ ] **Step 1: Implement** the spec and `nitro.json` (`cxxNamespace: ["callstack","otel"]`, `ios.iosModuleName: "ReactNativeOpenTelemetry"`, `android.androidNamespace: ["callstack","otel"]`, `android.androidCxxLibName: "ReactNativeOpenTelemetry"`, autolinking `Otel` → Swift `HybridOtel`, Kotlin `HybridOtel`); run `bun run codegen`. -- [ ] **Step 2: Run** `bun run static` → PASS; edit a field without regenerating → static FAIL naming `nitrogen/generated/...`; revert. -- [ ] **Step 3: Commit** `feat: Nitro seam spec`. - -### Task 3: Fake collector - -**Files:** -- Create: `verify/harness/collector.ts`, `verify/harness/otlpJson.ts`, `verify/harness/normalize.ts`, `verify/harness/proto/` (opentelemetry-proto `.proto` files at its latest release tag, recorded in `verify/harness/proto/VERSION`), `verify/harness/__tests__/{otlpJson,normalize,collector}.test.ts` - -**Interfaces:** -- Produces: - - `startCollector(opts?: { port?: number; artifactsDir?: string }): Promise`; default port `4318`, artifacts dir `verify/artifacts`. - - `Collector`: `url: string`; `begin(scenario: string, platform: string): void`; `end(): Promise` (normalized, also written to `verify/artifacts/..otlp.json`, raw bodies to `verify/artifacts/raw/./.{pb,json}`, request headers to `.../headers.json`); `refuse(status: number, count: number): void`; `close(): Promise`. - - HTTP: `POST /v1/traces` (protobuf `application/x-protobuf` or `application/json`), CORS `*` for any origin and `OPTIONS`; control endpoints `POST /_verify/begin {scenario, platform}`, `POST /_verify/end` → normalized JSON, `POST /_verify/refuse {status, count}`. - - `toOtlpJson(req: ExportTraceServiceRequest): OtlpJson` — hex `traceId`/`spanId`/`parentSpanId`, int64 as decimal strings, enums as numbers, empty/default fields omitted (proto3 JSON). - - `normalize(requests: OtlpJson[]): OtlpJson` — merge `resourceSpans` with equal resource, `scopeSpans` with equal scope; sort spans by `spanId`, attributes by `key`, events by `timeUnixNano` then `name`, links by `spanId`. Values are never changed. - -- [ ] **Step 1: Write failing tests**: - - `toOtlpJson converts ids to hex`: a protobuf request with 16 bytes `0a00…01` traceId → `"0a000000000000000000000000000001"`; `startTimeUnixNano` `1767225600000000000` → string `"1767225600000000000"`. - - `normalize merges two requests with the same resource into one resourceSpans` and `sorts spans by spanId and attributes by key`; `normalize never changes a value` (deep-equal of every span's fields modulo order). - - `collector refuses then accepts`: after `refuse(503, 1)`, first POST gets 503, second 200, `end()` contains only the second request's spans. - - `collector answers CORS preflight`: `OPTIONS /v1/traces` → 204 with `access-control-allow-origin: *`. -- [ ] **Step 2: Run** `bunx jest verify/harness` → FAIL. -- [ ] **Step 3: Implement** with Node `http` and `protobufjs` loading the vendored protos. -- [ ] **Step 4: Run** `bunx jest verify/harness` → PASS. -- [ ] **Step 5: Commit** `feat(verify): fake OTLP collector with normalizer`. - -### Task 4: Compare, update mode, shape check - -**Files:** -- Create: `verify/harness/compare.ts`, `verify/harness/shape.ts`, `verify/harness/fixtureJson.ts`, `verify/harness/__tests__/{compare,shape,fixtureJson}.test.ts` - -**Interfaces:** -- Produces: - - `expectedPath(scenario: string, platform: Platform): string`; `type Platform = 'js'|'android'|'ios'|'web'`. - - `compareToExpected(scenario, platform, actual: OtlpJson): { ok: boolean; report: string }` — first checks `shapeOf(actual)` against `verify/expected/.shape.json` (a shape mismatch fails even in update mode), then the exact file. When `VERIFY_UPDATE=1` and the shape matches, writes `actual` to the expected path (pretty, 2-space) and returns ok with report `updated `. - - `diffOtlp(expected, actual): Diff[]`; `Diff = { spanId?: string; spanName?: string; path: string; expected: unknown; actual: unknown }`; spans matched by `spanId`. - - `formatReport(scenario, platform, diffs): string` — exact format: - ``` - ✗ [] span "" - expected got - expected: verify/expected/..otlp.json - actual: verify/artifacts/..otlp.json - scenario: verify/scenarios/.ts - ``` - - `shapeOf(otlp): Shape` — per trace (traces numbered in order of first span), spans as `{ name, kind, parent: name|null, status, links: name[], attributes: Record }`, sorted by name; resource and scope attribute keys included. `compareShape(scenario, actual): Diff[]`. - - `encodeFixture(value)` / `decodeFixture(json)`: `NaN`, `Infinity`, `-Infinity`, `-0` ↔ `{"$num": "NaN" | "Infinity" | "-Infinity" | "-0"}`. - - `pending(scenario: string)` marks a scenario `test.todo` in every runner. - -- [ ] **Step 1: Write failing tests**: `diffOtlp reports missing parentSpanId`; `formatReport matches the spec's failure text` (snapshot for `nest-after-await`/`android`); `update mode writes the file and passes`; `update mode refuses when the shape differs`; `shapeOf ignores ids and timestamps`; `fixture round trip keeps NaN, Infinity and -0` (`Object.is(decoded, -0)`). -- [ ] **Step 2: Run** `bunx jest verify/harness` → FAIL. -- [ ] **Step 3: Implement.** -- [ ] **Step 4: Run** → PASS. -- [ ] **Step 5: Commit** `feat(verify): exact compare, shape check, fixture encoding`. - -### Task 5: Scenario API, test IDs, Jest scenario runner - -**Files:** -- Create: `verify/harness/scenario.ts`, `src/internal/testMode.ts`, `verify/stages/fast-js.ts`, `verify/jest/scenarios.test.ts`, `verify/jest/jest.scenarios.config.js`, `verify/scenarios/smoke-js.ts`, `verify/expected/smoke-js.{shape,js.otlp}.json` -- Modify: `jest.config.js` (projects) - -**Interfaces:** -- Produces: - - `scenario(name: string, run: (ctx: ScenarioCtx) => Promise, opts?: { runners?: ('jest'|'e2e')[]; pending?: boolean }): Scenario`; `allScenarios(): Scenario[]` from `verify/scenarios/index.ts` (regenerated from the folder by `bun verify`; also imported by the example apps). - - `ScenarioCtx = { tracer: Tracer; at(us: number): HrTime; native?: TestNative }`; `at(n)` = base `1767225600000000000` ns + `n` µs as `HrTime`. - - `src/internal/testMode.ts` (not exported from the package): `isTestModeBuild(): boolean` (`typeof process !== 'undefined' && process.env?.OTEL_TEST_MODE === '1'`); `sequentialIds(prefix: '0a'|'0b'): IdGenerator & { reset(): void }`: trace ids `` + zero-padded counter to 32 hex, span ids to 16 hex, counters independent. - - Jest scenario runner: for each scenario with runner `jest`, builds a `BasicTracerProvider` with `idGenerator: sequentialIds('0a')`, `resource: resourceFromAttributes({ 'service.name': 'verify' })` (not merged with the default resource, so no `telemetry.sdk.*`), `SimpleSpanProcessor(OTLPTraceExporter({ url: collector.url + '/v1/traces' }))`, runs it between `collector.begin(name,'js')` and `end()`, then `compareToExpected`. The project uses `babel-jest` with `@react-native/babel-preset` so `async` is downleveled like in RN. -- [ ] **Step 1: Write failing tests**: `sequentialIds('0a') gives 0a000000000000000000000000000001 then …02`; `at(3) is [1767225600, 3000]`; scenario `smoke-js` (one root span `smoke` from `at(0)` to `at(1)`) against hand-written `smoke-js.shape.json` and `smoke-js.js.otlp.json`. -- [ ] **Step 2: Run** `bun verify` → FAIL. -- [ ] **Step 3: Implement.** -- [ ] **Step 4: Run** `bun verify` → PASS, report lists `smoke-js [js] ✓`. -- [ ] **Step 5: Commit** `feat(verify): scenario API, sequential ids, Jest scenario runner`. - -### Task 6: CI for static and fast stages, PR budget - -**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`). 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`. - -### Task 7: Tracer bullet — example app, native stubs, first device e2e - -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`) - -**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. -- 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. -- [ ] **Step 3: Run** `bun verify --e2e` on Android emulator and iOS simulator → both tests green on both platforms. -- [ ] **Step 4: Capability check** (record results in `verify/VERIFY.md`): with agent-device, trigger a JS reload, a fast refresh (dev build), send the app to background and back, read logs. Anything unsupported is a blocker for Task 27; raise it now. -- [ ] **Step 5: Commit** `feat(example): tracer bullet through the Nitro seam on both platforms`. - -### 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) - -**Interfaces:** -- `toSeamSpan(span: ReadableSpan): SeamSpan` — copies `HrTime` as-is; attributes in insertion order; `parentSpanId` from `span.parentSpanContext?.spanId`; scope from `span.instrumentationScope` (scope attributes included); status code/message; drops `undefined` attribute values. -- `class NativeHandOffProcessor implements SpanProcessor { constructor(native: Otel) }` — `onEnd`: skips unsampled spans, else `native.handOff([toSeamSpan(span)])`; `forceFlush()`/`shutdown()` → `native.flush(5000)`. No buffer (spec §4.3). -- Fixture format (consumed by Tasks 15, 18): -```json -{ "config": { "serviceName": "verify", "serviceVersion": "0.0.0", "resourceAttributes": [], - "exportUrl": "", "exportHeaders": [] }, - "spans": [ /* SeamSpan objects, in hand-off order, encoded with encodeFixture */ ] } -``` -- `fixtures.test.ts`: runs each fixture scenario through a `BasicTracerProvider` with `NativeHandOffProcessor` over a **recording fake** `Otel`; asserts the recorded payloads deep-equal the decoded fixture `spans`. With `VERIFY_UPDATE=1` it writes the fixture. -- `rich-span` covers every attribute type (string, int, double, bool, each array type), non-ASCII text (`"zażółć 🚀"`), two events with attributes, one link with attributes, status `ERROR` with message, scope with version, `schemaUrl` and one scope attribute. -- `odd-attributes` sets `NaN`, `Infinity`, `-0`, `2**53 + 2`, `[]` and records whatever `sdk-trace` lets through. -- [ ] **Step 1:** Write the scenarios, their shape files and unit tests `unsampled spans are never handed off`, `handOff receives a one-element array`; run → FAIL. -- [ ] **Step 2: Implement.** -- [ ] **Step 3: Run** `VERIFY_UPDATE=1 bun verify` → fixtures generated; `bun verify` → fixtures match. -- [ ] **Step 4: Commit** `feat(handoff): seam conversion, hand-off processor, generated fixtures`. - -### Task 9: Scenario bodies and shapes (author review gate) - -**Files:** -- 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]; `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] -- Exact `.otlp.json` files are **not** hand-written here: each owning task drafts them with `VERIFY_UPDATE=1` (shape must already match) and the author reviews them in that task. -- [ ] **Step 1:** Write each scenario body from §6.1/§6.2 and its shape file. -- [ ] **Step 2: Author review.** Stop; ask the author to review every scenario, every shape file and the generated fixtures from Task 8. Apply requested changes. -- [ ] **Step 3: Run** `bun verify` → harness green; unimplemented scenarios report as pending, not failing. -- [ ] **Step 4: Commit** `test(verify): scenarios and shapes for v0`. - ---- - -## Phase 1 — L1 Context - -### Task 10: Context manager, runtime patch, interval policy - -**Files:** -- Create: `src/context/RNContextManager.ts`, `src/context/patch.ts`, `src/setup.ts` -- Modify: the 11 L1 scenarios owned by Task 10 (un-pend), Jest scenario runner imports `src/setup.ts` first - -**Interfaces:** -- `class RNContextManager extends StackContextManager { swap(ctx: Context): Context }`. -- `installContextPatch(cm: RNContextManager): void` — idempotent via `globalThis[Symbol.for('com.callstack.otel.patched')]`; wraps `Promise.prototype.then`, `setTimeout`, `setImmediate`, `queueMicrotask`, `requestAnimationFrame` (when present); `setInterval` runs every tick in `ROOT_CONTEXT`. -- Algorithm (spec §6.1): capture at registration; **if the captured context is `ROOT_CONTEXT`, call the original unwrapped**; otherwise a fixed-arity wrapper: -```ts -const wrap = (ctx, fn) => function (v) { const prev = cm.swap(ctx); try { return fn.call(this, v); } finally { cm.swap(prev); } }; -``` - Timer wrappers forward extra arguments with the same fast path. -- `src/setup.ts` creates the singleton, installs the patch, calls `context.setGlobalContextManager(cm)`; exports `contextManager`. -- [ ] **Step 1:** Un-pend; `bun verify` → FAIL on each. -- [ ] **Step 2:** Unit tests: `installContextPatch twice wraps once`; `then registered at ROOT is not wrapped` (callback identity reaches the original `then`). -- [ ] **Step 3: Implement.** -- [ ] **Step 4:** `VERIFY_UPDATE=1 bun verify` drafts the `.js` files (shapes must match: `captured-then` is a lost parent, `interval-new-root` ticks are roots, `batching-shared-queue` records the documented wrong parent); `bun verify` green. **Author review** of the new files. -- [ ] **Step 5: Commit** `feat(context): runtime patch with ROOT fast path and interval roots`. - -### Task 11: Startup probe and degraded flag - -**Files:** -- 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:** 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 - -**Files:** -- Create: `metro/index.js`, `metro/__tests__/withOtel.test.js` - -**Interfaces:** -- `withOtel(config: MetroConfig): MetroConfig` — wraps `serializer.getModulesRunBeforeMainModule` so its result is the original list plus `require.resolve('react-native-open-telemetry/setup')` (→ `lib/module/setup.js`, built by `prepare`), **after** RN's `InitializeCore` and before any app module; keeps every other field. -- [ ] **Step 1: Write failing tests**: `adds setup after InitializeCore`; `keeps a user's existing entries`; `is idempotent when applied twice`. -- [ ] **Step 2–4:** FAIL → implement → PASS. -- [ ] **Step 5: Commit** `feat(metro): withOtel installs the context patch first`. - -### Task 13: L1 on device - -**Files:** -- Modify: `example/metro.config.js` (`withOtel`), `verify/e2e/scenarios.e2e.ts`, scenarios `interaction-manager`, `event-emitter-listener` - -- `scenarios.e2e.ts`: one `test(name)` per L1 scenario: `app.open()`, `collector.begin`, tap `scenario-`, wait for `scenario-done`, `compareToExpected(name, 'js')`. -- `interaction-manager`: a span active when `InteractionManager.runAfterInteractions` is called is the parent of the span started in the callback. `event-emitter-listener`: a span started in a `DeviceEventEmitter` listener has the emitter's caller as parent when emitted synchronously from JS. Draft their `.js` files from the device run, author review. -- [ ] **Step 1:** Run `bun verify --e2e` → L1 scenarios FAIL until `withOtel` is applied. -- [ ] **Step 2:** Apply `withOtel` in the example. -- [ ] **Step 3: Run** → every L1 scenario matches its `.js` file on both platforms. A Hermes-only difference is a finding: fix the patch, never the expected file, unless the author agrees. -- [ ] **Step 4: Commit** `test(example): context guarantees on Hermes`. - ---- - -## Phase 1 — L2 JS SDK - -### Task 14: `startReactNativeSdk` (mobile) - -**Files:** -- Create: `src/sdk/start.ts`, `src/sdk/config.ts`, `src/sdk/noop.ts`, test `src/sdk/__tests__/start.test.ts` -- Modify: `src/index.ts` - -**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[] }`. -- 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. - - Provider: `idGenerator: sequentialIds('0a')` when `result.testMode` (native compiled in test mode), else default; resource **empty** (native owns it); sampler `ParentBased(AlwaysOn)`; user `spanProcessors` first, then `NativeHandOffProcessor`. - - The registered global provider is the returned `tracerProvider`; its `getTracer` adds `scopeAttributes()` when degraded. - - Time source: offset `Date.now() - performance.now()` computed at start and on `AppState` `active`; falls back to `Date.now()` when `performance` is missing. - - `shutdown()` shuts down the JS provider only. Second call → returns the first handle, warns once. -- [ ] **Step 1: Write failing tests** (fake `Otel`): `attaches when native is initialized`; `initializes native when it is not` (exact `SeamConfig`); `no native module returns a no-op handle and logs once`; `init error returns a no-op handle and logs once`; `never throws on missing config`; `second call returns the first handle with one warning` (Review Focus 4); `user span processors still see spans`; `test-mode native gives 0a ids`; `global provider is the returned provider`; `clock offset follows Date.now`. -- [ ] **Step 2–4:** FAIL → implement → `bun verify` PASS. -- [ ] **Step 5: Commit** `feat(sdk): startReactNativeSdk attach and fallback init`. - ---- - -## Phase 1 — L3 Kotlin core - -### 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` - -**Interfaces:** -- Core (no Android/Nitro imports): Kotlin data classes mirroring the seam (`SeamSpan`, `SeamAttribute`, …, `HrTime(seconds: Double, nanos: Double)`); `JsSpanData(span: SeamSpan, resource: Resource) : SpanData` computing attributes, IDs and times lazily (first access happens on the export thread); `fun attributesOf(list: List): Attributes` with the integer rule (`Double` whole and within `Long` range → `long`, else `double`; arrays all-whole → long array); `class OtelCore(config: CoreConfig, testMode: Boolean = false)` with `handOff(spans: List)` (enqueue only), `flush(timeoutMs): Boolean`, `resource: Resource`. In test mode: IDs `0b…`, resource from config only (no `telemetry.*`). -- Fixture reader decodes `{"$num": ...}`. -- Test: for every fixture: `begin(name, "android")`, `OtelCore(config, testMode = true).handOff(spans)`, `flush`, `end`; Node compares against `.android.otlp.json` (shape first). -- [ ] **Step 1:** `FixtureExportTest` and `AttributesTest` (`1.0 → long 1`, `1.5 → double`, `9.007199254740994E15 → long`, `NaN → double NaN`, `-0.0 → double`); run → FAIL. -- [ ] **Step 2: Implement.** -- [ ] **Step 3:** `VERIFY_UPDATE=1 bun verify` drafts `*.android.otlp.json` (shape must match); `bun verify` green. -- [ ] **Step 4: Author review** of the new `android` files. -- [ ] **Step 5: Commit** `feat(android-core): seam spans exported through otel-java`. - -### Task 16: Core config and `export-headers` - -**Files:** -- Create: `android/src/core/kotlin/com/callstack/otel/core/{CoreConfig.kt,Endpoint.kt}`, tests -- Modify: scenario `export-headers` - -**Interfaces:** -- `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`. - -### Task 17: Parenting helper - -**Files:** -- Create: `android/src/core/kotlin/com/callstack/otel/core/Parenting.kt`, test - -**Interfaces:** -- `fun contextFrom(traceparent: String): Context` (W3C parse; invalid → `Context.root()`); `fun traceparentOf(span: Span): String`; `fun contextFrom(sc: SeamSpanContext): Context` (non-remote parent). -- [ ] **Step 1: Write failing tests**: round trip; child started with `setParent(contextFrom(tp))` has parent span id from `tp` and `isRemote == false`; `contextFrom("garbage")` → child is a root, no exception (Review Focus 5). -- [ ] **Step 2–4:** FAIL → implement → PASS. -- [ ] **Step 5: Commit** `feat(android-core): explicit parenting helper`. - -## Phase 1 — L4 Swift core - -### 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` - -**Interfaces:** Mirror Task 15: `OtelCore(config:testMode:)`, `handOff(_ spans:)` (enqueue only; `SpanData` built on the export queue), `flush(timeoutMs:) -> Bool`, `attributes(of:)` with the same integer rule; times converted from `HrTime` to `Date`. -- [ ] **Step 1: Prove time exactness first:** `TimeRoundTripTests`: `at(0)…at(10_000)` and `at(1_000_000_000)` converted to `Date` and exported come back as the same whole-µs nanosecond strings. If not exact, stop: record the floor in `VERIFY.md` and agree the fix with the author (e.g. round to µs on export) before writing golden files. -- [ ] **Step 2:** `FixtureExportTests` over every fixture (`begin(name, "ios")`) + `AttributesTests` with the same cases as Task 15; run → FAIL. -- [ ] **Step 3: Implement.** -- [ ] **Step 4:** `VERIFY_UPDATE=1 bun verify` drafts `*.ios.otlp.json` (shape must match); **author review**. -- [ ] **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: 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`. - -## Phase 1 — L5 Web - -### Task 21: `startReactNativeSdk` on web - -**Files:** -- Create: `src/sdk/start.web.ts`, test - -**Interfaces:** -- 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: Async lowering on Expo web - -**Files:** -- Modify: `example-expo/babel.config.js`, `example-expo/metro.config.js`, `example-expo/package.json` (react-dom, react-native-web, @expo/metro-runtime) - -**Interfaces:** -- `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-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**. -- [ ] **Step 3: Run** `bun verify --e2e` → web target green; CI job green. -- [ ] **Step 4: Commit** `test(web): e2e target for all JS scenarios`. - ---- - -## Phase 2 — Integration - -### Task 24: Android adapter and native-first init (bare app) - -**Files:** -- Create: `android/src/main/java/com/callstack/otel/{RNOtel.kt,RNOtelConfig.kt}` -- Modify: `android/build.gradle` (add `src/core/kotlin` to `sourceSets.main`), `android/src/main/java/com/callstack/otel/HybridOtel.kt` (stub → real), `example/android/.../MainApplication.kt`, `example/src/ScenariosScreen.tsx` (export via `startReactNativeSdk`, not JS-direct), `verify/e2e/harness.ts` (`android-bare` compares to `android` files) - -**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/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`. -- [ ] **Step 4: Commit** `feat(android): Nitro adapter and native-first init`. - -### Task 25: iOS adapter and native-first init (bare app) -Mirror Task 24: `ios/Adapter/{HybridOtel.swift,RNOtel.swift,RNOtelConfig.swift}` (stub → real); `RNOtel.start { c in … }` in `AppDelegate`; test mode from `#if OTEL_TEST_MODE`; background flush in `didEnterBackground` wrapped in `beginBackgroundTask`/`endBackgroundTask` with an expiration handler; `ios-bare` compares to `ios` files. Builds with static frameworks (`USE_FRAMEWORKS=static`) as well as the default. Commit `feat(ios): Nitro adapter and native-first init`. - -### Task 26: Cross-boundary parenting (both platforms) - -**Files:** -- Create: `example/android/.../TestNative.kt`, `example/ios/TestNative.swift`, `example/src/specs/TestNative.nitro.ts` (example-only HybridObject) -- Modify: scenarios `cross-js-to-native`, `cross-native-to-js` - -**Interfaces:** -- `TestNative.doWork(traceparent: string, start: HrTime, end: HrTime): string` — starts `native.work` with `RNOtel.contextFrom(traceparent)` as parent, explicit timestamps, ends it, returns `RNOtel.traceparentOf(span)`. `ScenarioCtx.native` is this object. -- Scenarios: JS span `A` → `doWork` → native `B` (child of A, id `0b…`) → JS `js.after_native` under `trace.wrapSpanContext(B)`. -- [ ] **Step 1:** Un-pend; run → FAIL. -- [ ] **Step 2: Implement** on both platforms. -- [ ] **Step 3:** Draft `android`/`ios` files (shape must match); **author review**. -- [ ] **Step 4: Run** `bun verify --e2e` → green on both. -- [ ] **Step 5: Commit** `test: cross-boundary parenting both directions`. - -### Task 27: Failure scenarios (both platforms) - -**Files:** -- Modify: scenarios `collector-down`, `native-init-failure`, `flush-after-reload`, `background-flush`, `fast-refresh-idempotent`; `verify/e2e/scenarios.e2e.ts`; `.github/workflows/ci.yml` (a dev build per platform for reload and fast-refresh scenarios, and a build with an invalid export URL for `native-init-failure`) - -- Behaviour pinned per scenario: - - `collector-down`: `refuse(503, 3)`; `scenario-done` within 2 s; after the refusals, the spans arrive and match the expected file. - - `native-init-failure`: build flag points `exportUrl` at `not a url`; exactly one error log line from the SDK; app keeps running; no spans exported; `forceFlush()` on the no-op handle resolves. - - `flush-after-reload`: run scenario, JS reload, `forceFlush()` → resolves within 5 s; spans arrive once. - - `background-flush` (Review Focus 3): run scenario, background the app immediately → spans arrive without `forceFlush()`; no ANR on Android. - - `fast-refresh-idempotent`: fast refresh twice, run `nest-after-await` → output identical to its expected file. -- [ ] **Step 1:** Un-pend; run → FAIL. -- [ ] **Step 2: Implement** the missing behaviour. -- [ ] **Step 3:** Review any new expected files. -- [ ] **Step 4: Run** `bun verify --e2e` → green on both platforms. -- [ ] **Step 5: Commit** `test: failure scenarios on device`. - -### Task 28: Expo app with JS-fallback init - -**Files:** -- Create: `example-expo/` (latest Expo SDK, `expo prebuild` CNG, no native init), reusing `ScenariosScreen` and `verify/scenarios`; e2e targets `android-expo` (`bundleId: 'opentelemetry.example.expo'`), `ios-expo`; an example-only local config plugin that writes `otelTestMode=true` to `gradle.properties` (the iOS flag comes from `OTEL_TEST_MODE=1` at `pod install`) -- Modify: `verify/e2e/e2e.config.ts`, `.github/workflows/ci.yml` (jobs `e2e-android-expo`, `e2e-ios-expo`) - -- Calls `startReactNativeSdk({ serviceName: 'verify', serviceVersion: '0.0.0', exportConfig: { url } })`; native reports `testMode` from its build flag; no test fields in the config. -- [ ] **Step 1:** Add targets; run → FAIL. -- [ ] **Step 2: Implement** the app. -- [ ] **Step 3: Run** `bun verify --e2e` → `android-expo` and `ios-expo` match the **same** `android`/`ios` files as the bare app (proves both init paths are equivalent). -- [ ] **Step 4: Commit** `feat(example-expo): JS-fallback init verified against the same files`. - -### Task 29: Smoke and performance guardrail - -**Files:** -- Create: `verify/e2e/smoke.e2e.ts`, `verify/e2e/perf.e2e.ts`, scenario `perf-budget` - -- `smoke-device` on every mobile target: production pipeline (test mode off): spans named `smoke` arrive; assert count and names only. -- `perf-budget` on `android-bare` only: (a) 1,000× `startSpan → setAttribute×10 → end()` through the real hand-off, timing p50/p95 µs per span; (b) 10,000 awaits with the patch on vs off (patch disabled by an example build flag). Fails only if hand-off p50 ≥ 100 µs or the patch ratio ≥ 3×. Writes `verify/artifacts/perf.json`. -- [ ] **Step 1–4:** add tests → FAIL → implement → PASS. -- [ ] **Step 5: Commit** `test: device smoke and performance guardrail`. - -### Task 30: OTLP compliance job - -**Files:** Create `verify/compliance/collector.yaml`, `verify/compliance/replay.ts`; modify `.github/workflows/ci.yml` (job `compliance`, needs all e2e jobs, ubuntu). -- Runs `otel/opentelemetry-collector:` with an OTLP HTTP receiver and `debug` exporter; `replay.ts` POSTs every raw request from the e2e artifacts and every `verify/expected/*.otlp.json`; fails on non-2xx or any `error` line in the collector log. -- [ ] Steps: run on a PR → green; corrupt one expected file's `traceId` length locally → compliance fails; restore. Commit `ci: official collector compliance`. - ---- - -## Release lane - -### Task 31: Scheduled runs - -**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. - > 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`. - ---- - -## Done when - -- `bun verify` and `bun verify --e2e` are green locally; CI green on all jobs; every platform's output matches its scenario's shape file; the official Collector accepts every request and expected file. -- Every scenario named in Task 9 is implemented (none pending) and its expected files were reviewed by the author. -- Spec §8 item 7 holds on iOS and Android: one trace with a JS root, a child after `await`, a native child parented from JS, a JS span parented by native; plus a concurrent trace sharing nothing. On web (no native side): the JS root, the child after `await`, and the concurrent trace sharing nothing. -- `perf-budget` passes and `verify/artifacts/perf.json` from CI is linked in `VERIFY.md`. 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 4b6ab59..006d4d7 100644 --- a/docs/superpowers/specs/2026-11-10-rn-otel-design.md +++ b/docs/superpowers/specs/2026-11-10-rn-otel-design.md @@ -192,7 +192,7 @@ class NativeHandOffProcessor implements SpanProcessor { - 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 + the seam structs and hands the core `ReadableSpan`s. *(R24: 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.)* @@ -574,8 +574,7 @@ Sequencing (from review; council review 2026-11-21 added step 0): 4. Expected-file goldens and parity check on both platforms. 5. Web. -Each step is defined by the list of scenario names that must pass (9.3); the implementation -plan carries those lists. +Each step is defined by the list of scenario names that must pass (9.3). ## 9. Verification (decided) diff --git a/example-expo/plugins/withOtelExample.js b/example-expo/plugins/withOtelExample.js index 1b6d83b..ce24218 100644 --- a/example-expo/plugins/withOtelExample.js +++ b/example-expo/plugins/withOtelExample.js @@ -11,7 +11,7 @@ tasks.matching { it.name.startsWith("createBundle") }.configureEach { `; /** - * Example-only (Task 28): what the bare example's native projects carry by hand, applied at `expo prebuild`. The Core + * Example-only: what the bare example's native projects carry by hand, applied at `expo prebuild`. The Core * pod (R24) comes from the package's own plugin (`react-native-open-telemetry` in app.json), as in a real Expo app. */ module.exports = config => { diff --git a/example/modules/test-native/TestNative.podspec b/example/modules/test-native/TestNative.podspec index 6196ac3..b31c842 100644 --- a/example/modules/test-native/TestNative.podspec +++ b/example/modules/test-native/TestNative.podspec @@ -1,4 +1,4 @@ -# Example-only Nitro module (Task 26, R25): app native code using the public RNOtel API. +# Example-only Nitro module (R25): app native code using the public RNOtel API. Pod::Spec.new do |s| s.name = "TestNative" s.version = "0.0.0" diff --git a/example/modules/test-native/android/build.gradle b/example/modules/test-native/android/build.gradle index a6e4adb..b1d72b6 100644 --- a/example/modules/test-native/android/build.gradle +++ b/example/modules/test-native/android/build.gradle @@ -1,4 +1,4 @@ -// Example-only Nitro module (Task 26, R25). Versions follow the app (rootProject.ext), as autolinked libraries do. +// Example-only Nitro module (R25). Versions follow the app (rootProject.ext), as autolinked libraries do. apply plugin: "com.android.library" apply plugin: "org.jetbrains.kotlin.android" apply from: "../nitrogen/generated/android/TestNative+autolinking.gradle" diff --git a/example/modules/test-native/package.json b/example/modules/test-native/package.json index a0af9ce..a50cf7a 100644 --- a/example/modules/test-native/package.json +++ b/example/modules/test-native/package.json @@ -2,7 +2,7 @@ "name": "react-native-test-native", "version": "0.0.0", "private": true, - "description": "Example-only HybridObject: app native code using the public RNOtel helpers (Task 26)", + "description": "Example-only HybridObject: app native code using the public RNOtel helpers", "scripts": { "codegen": "../../../node_modules/.bin/nitrogen" } diff --git a/example/modules/test-native/src/TestNative.nitro.ts b/example/modules/test-native/src/TestNative.nitro.ts index 4d54fb9..6b996d0 100644 --- a/example/modules/test-native/src/TestNative.nitro.ts +++ b/example/modules/test-native/src/TestNative.nitro.ts @@ -1,9 +1,9 @@ import type {HybridObject} from 'react-native-nitro-modules'; -/** Example-only (Task 26): app native code that parents its spans with the public `RNOtel` helpers. */ +/** Example-only: app native code that parents its spans with the public `RNOtel` helpers. */ export interface TestNative extends HybridObject<{ios: 'swift'; android: 'kotlin'}> { /** Starts and ends `native.work` under `traceparent` ('' = a root) at `start`/`end` ([s, ns]), returns its traceparent. */ doWork(traceparent: string, start: number[], end: number[]): string; - /** Reloads the JS app natively, as OTA updaters do; `DevSettings.reload()` is a no-op in release (Task 27). */ + /** Reloads the JS app natively, as OTA updaters do; `DevSettings.reload()` is a no-op in release. */ reload(): void; } diff --git a/example/src/ScenariosScreen.tsx b/example/src/ScenariosScreen.tsx index 8537080..2a3c6dd 100644 --- a/example/src/ScenariosScreen.tsx +++ b/example/src/ScenariosScreen.tsx @@ -8,11 +8,11 @@ import {at} from '../../verify/harness/scenario'; import {allScenarios} from '../../verify/scenarios'; import type {TestNative} from '../modules/test-native/src/TestNative.nitro'; -// Failure scenarios (Task 27) whose e2e test decides when, or whether, anything flushes. +// Failure scenarios whose e2e test decides when, or whether, anything flushes. const NO_FLUSH = new Set(['collector-down', 'flush-after-reload', 'background-flush']); const TEST_MODE = process.env.OTEL_TEST_MODE === '1'; -// fast-refresh-idempotent (Task 27): the patched functions as first seen; `??=` keeps them across re-evaluations of +// fast-refresh-idempotent: the patched functions as first seen; `??=` keeps them across re-evaluations of // this module, so a refresh that stacked the patch shows `changed`. The e2e edit counts in `__otelRefreshes`. const g = globalThis as any; g.__otelFirstPatch ??= {then: Promise.prototype.then, setTimeout: g.setTimeout}; @@ -51,7 +51,7 @@ export function ScenariosScreen() { ).finally(() => setRunning(null)); }, [running]); - // test-mode only (Task 27): each resolved forceFlush shows `flush-done-`, so a wait never matches a stale one + // test-mode only: each resolved forceFlush shows `flush-done-`, so a wait never matches a stale one const [flushes, setFlushes] = useState(0); const flush = () => startReactNativeSdk().forceFlush().then(() => setFlushes(n => n + 1)); diff --git a/ios/Core/OtelCore.swift b/ios/Core/OtelCore.swift index aaa6f36..4d389ec 100644 --- a/ios/Core/OtelCore.swift +++ b/ios/Core/OtelCore.swift @@ -61,7 +61,7 @@ package final class OtelCore { OtlpHttpTraceExporter(endpoint: $0, envVarHeaders: config.exportHeaders.map { ($0.key, $0.value) }) } } - // test mode: no timed export within a device test, so only flush and background export send (Task 27) + // test mode: no timed export within a device test, so only flush and background export send bsp = BatchSpanProcessor(spanExporter: exporter, scheduleDelay: testMode ? 120 : 5) // 5 s: upstream's default let b = TracerProviderBuilder().with(resource: resource).add(spanProcessor: bsp) tracerProvider = (testMode ? b.with(idGenerator: SequentialIds()) : b).build() diff --git a/verify/VERIFY.md b/verify/VERIFY.md index f85e221..50d9fbb 100644 --- a/verify/VERIFY.md +++ b/verify/VERIFY.md @@ -58,25 +58,25 @@ exports through `startReactNativeSdk` and the Kotlin or Swift core. One file for 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` +**Fixtures by target kind.** `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 +**TestNative (R25).** `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 +C++ interop and the app is not (`'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 => '<package dir>'`. 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). +(CI) and `USE_FRAMEWORKS=static` (checked locally, 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), +**`performance.timeOrigin` on Hermes (X17).** 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). @@ -87,7 +87,7 @@ 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) +## Expo app `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 @@ -117,7 +117,7 @@ unproven until their first CI run. - **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) +## Web 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 @@ -146,7 +146,7 @@ HybridObjects: no native `testMode` line, scenarios get no `native`). (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) +## Failure scenarios 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: @@ -191,7 +191,7 @@ Each has its own e2e file (R10); the ScenariosScreen does not `forceFlush()` aft If watchman reports recrawls, restart Metro: a dead watch never delivers the edit. -## Android cold start with `RNOtel.start` (Task 24, 2026-11-24) +## Android cold start with `RNOtel.start` (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): @@ -203,31 +203,29 @@ emulator (API 36, arm64), release test-mode build. `TotalTime` (ms): 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) +## Device capability check (2026-11-23) -What Task 27 (reload, fast refresh, background flush) needs from agent-device. +What the failure scenarios (reload, fast refresh, background flush) need from agent-device. iOS: iPhone 18 Pro simulator, iOS 27.0, Xcode 27.1, agent-device 0.21.36 (T3 device panel), RN 0.88.1 Debug build + Metro. | Capability | iOS simulator | Android emulator (Pixel_9) | | --- | --- | --- | -| 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 <udid> 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) | +| JS reload | ✓ `agent-device metro reload` (Metro re-bundled; screen state reset). Release: native reload via TestNative | ✓ release: native reload via TestNative, e2e `flush-after-reload`. `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` | +| 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` | +| 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 <udid> log show --predicate 'process == "OpenTelemetryExample" …'` | ✓ via the e2e harness: `adb logcat -d -s RNOtel:I` (tracer-bullet test green; the test was later retired, 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. Task 27 filled it in through e2e tests. +(`@e2e-dev/mobile`, agent-device 0.21.39) drives it fine. The Android column was filled in through e2e tests. ## Scenarios One file per guarantee in `verify/scenarios/`, named after it, with one exact `verify/expected/<name>.otlp.json` that every platform compares against. It is drafted with `VERIFY_UPDATE=1` (or `VERIFY_E2E_DRAFT=1` for e2e-only scenarios, -from Android or web) and reviewed by the author. `pending` scenarios report as `todo`; the owning task flips `pending` off. +from Android or web) and reviewed by the author. `pending` scenarios report as `todo`; un-pend a scenario once it passes. Every file uses the JS runner's resource, `service.name` only. 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 files. diff --git a/verify/e2e/e2e.config.ts b/verify/e2e/e2e.config.ts index 7bf10e7..148104f 100644 --- a/verify/e2e/e2e.config.ts +++ b/verify/e2e/e2e.config.ts @@ -4,7 +4,7 @@ import {web} from '@e2e-dev/web'; const bundleId = 'opentelemetry.example'; const example = '../../example'; -// Expo prebuild app (JS-fallback init, Task 28): same scenarios, same android/ios expected files +// Expo prebuild app (JS-fallback init): same scenarios, same expected files const expo = '../../example-expo'; export default { @@ -49,7 +49,7 @@ export default { appPath: process.env.E2E_IOS_EXPO_APP ?? `${expo}/ios/build/Build/Products/Release-iphonesimulator/OpenTelemetryExpo.app`, }, }, - // The Expo app's Metro web export (react-native-web), exporting with the web SDK (Task 23). + // The Expo app's Metro web export (react-native-web), exporting with the web SDK. // The runner exports it in test mode (lib/ first: `bun run prepare`) and serves it with `expo serve`. { name: 'web', @@ -66,7 +66,7 @@ export default { }, }, }, - // Dev builds (Debug + Metro), local only: fast-refresh-idempotent (Task 27). See VERIFY.md. + // Dev builds (Debug + Metro), local only: fast-refresh-idempotent. See VERIFY.md. ...(process.env.E2E_DEV === '1' ? [ { diff --git a/verify/e2e/harness.ts b/verify/e2e/harness.ts index 50c8991..e11cf15 100644 --- a/verify/e2e/harness.ts +++ b/verify/e2e/harness.ts @@ -86,7 +86,7 @@ export function anyTarget(title: string, body: (f: Fixtures) => Promise<void>) { ); } -/** Steps the failure scenarios (Task 27) add around the tap-and-compare. */ +/** Steps the failure scenarios add around the tap-and-compare. */ export type ScenarioSteps = { /** Replaces the cold start, e.g. to relaunch with launch arguments. */ launch?: () => Promise<void>; @@ -121,8 +121,8 @@ export async function expectScenario( } finally { actual = await collector.end(); } - // every app exports through the native core (bare: native-first init, Expo: JS-fallback init), so android-* compare - // to `android` files and ios-* to `ios` (R13): one set of files proves both init paths equivalent (Task 28). + // every app exports through the native core (bare: native-first init, Expo: JS-fallback init), so one expected + // file per scenario proves both init paths equivalent (R13). // VERIFY_E2E_DRAFT=1 writes a missing expected file and still fails (review it, then rerun) const r = compareToExpected(name, platformOf(target), actual, {draft: process.env.VERIFY_E2E_DRAFT === '1'}); if (!r.ok) throw new Error('\n' + r.report); diff --git a/verify/scenarios/background-flush.ts b/verify/scenarios/background-flush.ts index 3cda83f..c52646d 100644 --- a/verify/scenarios/background-flush.ts +++ b/verify/scenarios/background-flush.ts @@ -1,7 +1,7 @@ import {scenario} from '../harness/scenario'; /** - * Background flush (§9.4, Task 27): run this and background the app immediately. The span arrives without + * Background flush (§9.4): run this and background the app immediately. The span arrives without * `forceFlush()`, exactly once; no ANR on Android. */ export default scenario( diff --git a/verify/scenarios/captured-then.ts b/verify/scenarios/captured-then.ts index 3b0731e..74aa18e 100644 --- a/verify/scenarios/captured-then.ts +++ b/verify/scenarios/captured-then.ts @@ -3,7 +3,7 @@ import {scenario} from '../harness/scenario'; /** * Documented exception (§6.1 install order): code holding the `then` captured before the patch ran * loses the parent and starts a new root; the patched `then` keeps it. - * The pre-patch `then` is read from the patch marker (Task 10 stores the originals there). + * The pre-patch `then` is read from the patch marker (the patch stores the originals there). */ export default scenario( 'captured-then', diff --git a/verify/scenarios/collector-down.ts b/verify/scenarios/collector-down.ts index 331092c..34e54a4 100644 --- a/verify/scenarios/collector-down.ts +++ b/verify/scenarios/collector-down.ts @@ -1,7 +1,7 @@ import {scenario} from '../harness/scenario'; /** - * Collector down (§9.4 failure scenarios, Task 27): the e2e test makes the collector `refuse(503, 3)`. + * Collector down (§9.4 failure scenarios): the e2e test makes the collector `refuse(503, 3)`. * The app does not block or crash (`scenario-done` within 2 s) and, once the collector accepts again, * the span arrives exactly once. */ diff --git a/verify/scenarios/cross-js-to-native.ts b/verify/scenarios/cross-js-to-native.ts index b55d431..ddaba99 100644 --- a/verify/scenarios/cross-js-to-native.ts +++ b/verify/scenarios/cross-js-to-native.ts @@ -1,7 +1,7 @@ import {scenario} from '../harness/scenario'; /** - * A native span started from JS is a child of the active JS span (Task 26). + * A native span started from JS is a child of the active JS span. * Steps: JS span `js.parent` active → `ctx.native.doWork(traceparent, start, end)` starts and ends native * `native.work` with `contextFrom(traceparent)` as parent. Proof: one trace, `native.work` (a `0b…` id) * has `js.parent` as parent. diff --git a/verify/scenarios/cross-native-to-js.ts b/verify/scenarios/cross-native-to-js.ts index 0463b4a..2861045 100644 --- a/verify/scenarios/cross-native-to-js.ts +++ b/verify/scenarios/cross-native-to-js.ts @@ -2,7 +2,7 @@ import {context, trace} from '@opentelemetry/api'; import {scenario} from '../harness/scenario'; /** - * A JS span started under a native span's context is its child (Task 26). + * A JS span started under a native span's context is its child. * Steps: at ROOT, `ctx.native.doWork('', …)` starts and ends root `native.work` and returns its traceparent → * JS starts `js.after_native` under `trace.wrapSpanContext(<that context>)` (non-remote, spec §4.3). * Proof: one trace, `js.after_native` has `native.work` as parent. diff --git a/verify/scenarios/fast-refresh-idempotent.ts b/verify/scenarios/fast-refresh-idempotent.ts index 57d4e95..8e4d433 100644 --- a/verify/scenarios/fast-refresh-idempotent.ts +++ b/verify/scenarios/fast-refresh-idempotent.ts @@ -2,7 +2,7 @@ import {scenario} from '../harness/scenario'; import nestAfterAwait from './nest-after-await'; /** - * Fast refresh does not stack the context patch (§6.1.3, Task 27). Stacked wrappers would still give the same + * Fast refresh does not stack the context patch (§6.1.3). Stacked wrappers would still give the same * parents, so the output alone cannot fail; the proof is: * (a) `Promise.prototype.then` and `setTimeout` are the same functions before and after two fast refreshes * (identity read via the `Symbol.for('com.callstack.otel.patched')` marker), and diff --git a/verify/scenarios/flush-after-reload.ts b/verify/scenarios/flush-after-reload.ts index d5d2d34..0ff7f09 100644 --- a/verify/scenarios/flush-after-reload.ts +++ b/verify/scenarios/flush-after-reload.ts @@ -1,7 +1,7 @@ import {scenario} from '../harness/scenario'; /** - * `flush()` across a JS reload (§9.4, Task 27): run this, reload JS, call `forceFlush()`. It resolves within + * `flush()` across a JS reload (§9.4): run this, reload JS, call `forceFlush()`. It resolves within * 5 s without blocking the main thread, and the span arrives exactly once. */ export default scenario( diff --git a/verify/scenarios/native-init-failure.ts b/verify/scenarios/native-init-failure.ts index 93365e0..ddef766 100644 --- a/verify/scenarios/native-init-failure.ts +++ b/verify/scenarios/native-init-failure.ts @@ -1,7 +1,7 @@ import {scenario} from '../harness/scenario'; /** - * Native init failure (§4, §9.4, Task 27): a build whose `exportUrl` is `not a url`. The SDK logs exactly one + * Native init failure (§4, §9.4): a build whose `exportUrl` is `not a url`. The SDK logs exactly one * error, the app keeps running on a no-op SDK, `forceFlush()` resolves, and no span is exported. */ export default scenario(