diff --git a/.github/verify-pr-spike/spike.py b/.github/verify-pr-spike/spike.py index f320d37202..aea7e25988 100644 --- a/.github/verify-pr-spike/spike.py +++ b/.github/verify-pr-spike/spike.py @@ -7,8 +7,9 @@ bundles its own JavaScript, then runs the flow in $VERIFY_FLOW on each build with the run ids the workflow passes in. Records timings, disk usage and bundle checks. After each flow it reads the ids of the error events the app sent from -the device log; the `outputs` step hands them to the fetch job, one -comma-separated list per side. +the device log, and with $VERIFY_TRANSACTIONS set to `true` the ids of its +transactions too; the `outputs` step hands them to the fetch job, one +comma-separated list per side and kind. Each subcommand is one workflow step. Results go to $RUNNER_TEMP/verify-pr-spike, which the workflow uploads. @@ -37,6 +38,8 @@ RESULTS = OUT / "results.json" PATCH = OUT / f"pr{os.environ['VERIFY_PR']}.patch" SIDES = ("without", "with") +# The workflow's `transactions` input: collect transaction ids as evidence. +TRANSACTIONS = os.environ["VERIFY_TRANSACTIONS"] == "true" CORE = "packages/core" CORE_SRC = f"{CORE}/src/" # Same exclusions as the skill's patch (SKILL.md step 2). @@ -65,6 +68,12 @@ # The sample's beforeSend log line (samples/react-native/src/App.tsx), one per # error event the JavaScript SDK sends. BEFORE_SEND_EVENT_ID = re.compile(r"'Event beforeSend:', '([0-9a-f]{32})'") +# The sample's beforeSendTransaction log line, one per transaction the +# JavaScript SDK sends. +BEFORE_SEND_TRANSACTION_ID = re.compile(r"'Transaction beforeSend:', '([0-9a-f]{32})'") +# Transaction ids passed to the fetch job per side, the first ones sent; the +# fetch job's MAX_TRANSACTIONS. results.json keeps them all. +MAX_TRANSACTIONS = 10 def load(): @@ -234,9 +243,9 @@ def adb(*args, **kwargs): return run(["adb", *args], **kwargs) -def before_send_event_ids(logcat): - """Event ids from the beforeSend log lines, in order, without duplicates.""" - return list(dict.fromkeys(BEFORE_SEND_EVENT_ID.findall(logcat))) +def logged_ids(pattern, logcat): + """Event ids from one kind of beforeSend log line, in order, without duplicates.""" + return list(dict.fromkeys(pattern.findall(logcat))) def run_side(side, results): @@ -282,7 +291,9 @@ def run_side(side, results): (run_dir / f"{run_id}.logcat").write_text(logcat, encoding="utf-8") record["logcat_run_id_lines"] = logcat.count(run_id) record["logcat_envelopes_sent"] = logcat.count("Envelope sent successfully") - record["event_ids"] = before_send_event_ids(logcat) + record["event_ids"] = logged_ids(BEFORE_SEND_EVENT_ID, logcat) + if TRANSACTIONS: + record["transaction_ids"] = logged_ids(BEFORE_SEND_TRANSACTION_ID, logcat) with (run_dir / "screencap.png").open("wb") as png: adb("exec-out", "screencap", "-p", stdout=png) # An all-black screenshot compresses to a few KB; a real one is much larger. @@ -300,7 +311,12 @@ def cmd_run(_args): for side in SIDES: if run_side(side, results) != 0: failures.append(f"the Maestro flow failed for {side}") - if not results["runs"][side]["event_ids"]: + # With transactions, each side needs one and error events are optional. + record = results["runs"][side] + if TRANSACTIONS: + if not record["transaction_ids"]: + failures.append(f"no 'Transaction beforeSend:' event id in the device log for {side}") + elif not record["event_ids"]: failures.append(f"no 'Event beforeSend:' event id in the device log for {side}") save(results) if failures: @@ -308,11 +324,20 @@ def cmd_run(_args): def cmd_outputs(_args): - """Writes each side's event ids as a job output, a comma-separated list.""" + """Writes each side's error ids, and transaction ids if collected, as job outputs, comma-separated lists.""" runs = load()["runs"] with open(os.environ["GITHUB_OUTPUT"], "a") as fh: for side in SIDES: fh.write(f"{side}_event_ids={','.join(runs[side]['event_ids'])}\n") + if not TRANSACTIONS: + continue + transaction_ids = runs[side]["transaction_ids"] + if len(transaction_ids) > MAX_TRANSACTIONS: + print( + f"{side}: {len(transaction_ids)} transaction ids, passing the first " + f"{MAX_TRANSACTIONS}; results.json has them all" + ) + fh.write(f"{side}_transaction_ids={','.join(transaction_ids[:MAX_TRANSACTIONS])}\n") def cmd_summary(_args): diff --git a/.github/workflows/verify-pr-spike.yml b/.github/workflows/verify-pr-spike.yml index 8f20f07974..d5d4205292 100644 --- a/.github/workflows/verify-pr-spike.yml +++ b/.github/workflows/verify-pr-spike.yml @@ -10,7 +10,10 @@ run-name: "${{ inputs.pr != '' && inputs.fetch_run_id == '' && inputs.probe_metr # JavaScript, and runs the `flow` from the ref branch on each. It holds no # secrets. Its step logic is in .github/verify-pr-spike/spike.py, from the main # checkout. It hands the fetch job only the ids of each side's error events, -# read from the sample's `'Event beforeSend:', ''` device log lines. +# read from the sample's `'Event beforeSend:', ''` device log lines, and a +# side without one fails. With `transactions` set, it also hands over the ids of +# each side's transactions, from the `'Transaction beforeSend:', ''` lines; +# then each side needs a transaction and error events are optional. # # The fetch job checks out nothing and runs no repository code: its logic is # inline below. It is the only job that gets SENTRY_AUTH_TOKEN. It checks each @@ -18,9 +21,10 @@ run-name: "${{ inputs.pr != '' && inputs.fetch_run_id == '' && inputs.probe_metr # itself from github.run_id, and refuses any event whose verify.run_id differs. # # Fetch-only mode: with `fetch_run_id` set, the build job is skipped and the -# fetch job reads the events given in `fetch_without_ids` and `fetch_with_ids`, -# expecting the run ids of that earlier run. `ref`, `pr`, `base_sha` and `flow` -# are not needed then. +# fetch job reads the error events given in `fetch_without_ids` and +# `fetch_with_ids`, expecting the run ids of that earlier run. Transaction ids in +# `fetch_without_transaction_ids` or `fetch_with_transaction_ids` turn on +# `transactions`. `ref`, `pr`, `base_sha` and `flow` are not needed then. # # Probe mode: with `probe_metric` set, the build job is skipped and the fetch # job makes one request for that metric's rows of the last 24 hours, to find @@ -54,6 +58,11 @@ on: description: Maestro flow on `ref` to run, matching .agents/skills/verify-pr/flows/.yml required: false type: string + transactions: + description: Also collect each side's transactions, for span evidence. Each side then needs one, and error events are optional + required: false + type: boolean + default: false fetch_run_id: description: Fetch-only mode. Id of an earlier run of this workflow, digits only; skips the build job required: false @@ -66,6 +75,14 @@ on: description: Fetch-only mode. Comma-separated ids (32 hex characters) of the "with" side's events, at most 5 required: false type: string + fetch_without_transaction_ids: + description: Fetch-only mode. Comma-separated ids (32 hex characters) of the "without" side's transactions, at most 10 + required: false + type: string + fetch_with_transaction_ids: + description: Fetch-only mode. Comma-separated ids (32 hex characters) of the "with" side's transactions, at most 10 + required: false + type: string probe_metric: description: Probe mode. A metric name, such as react_native.long_task.duration; skips the build job required: false @@ -95,6 +112,8 @@ jobs: outputs: without_event_ids: ${{ steps.event_ids.outputs.without_event_ids }} with_event_ids: ${{ steps.event_ids.outputs.with_event_ids }} + without_transaction_ids: ${{ steps.event_ids.outputs.without_transaction_ids }} + with_transaction_ids: ${{ steps.event_ids.outputs.with_transaction_ids }} env: # The script and the local action come from main, the code under test from ref. SPIKE: ${{ github.workspace }}/main/.github/verify-pr-spike/spike.py @@ -102,6 +121,7 @@ jobs: VERIFY_PR: ${{ inputs.pr }} VERIFY_FLOW: ${{ inputs.flow }} BASE_SHA: ${{ inputs.base_sha }} + VERIFY_TRANSACTIONS: ${{ inputs.transactions }} RUN_ID_WITHOUT: gh${{ github.run_id }}-without RUN_ID_WITH: gh${{ github.run_id }}-with steps: @@ -287,7 +307,7 @@ jobs: retention-days: 14 fetch: - name: Fetch the error events from Sentry + name: Fetch the events from Sentry needs: build # In fetch-only and probe mode the build job is skipped; otherwise it must pass. if: ${{ !cancelled() && (inputs.fetch_run_id != '' || inputs.probe_metric != '' || needs.build.result == 'success') }} @@ -297,29 +317,37 @@ jobs: contents: read steps: # No checkout: everything this job runs is in this file. - - name: Find and fetch each side's error events + - name: Find and fetch each side's error events and transactions shell: python env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} WORKFLOW_RUN_ID: ${{ github.run_id }} BUILD_WITHOUT_IDS: ${{ needs.build.outputs.without_event_ids }} BUILD_WITH_IDS: ${{ needs.build.outputs.with_event_ids }} + TRANSACTIONS: ${{ inputs.transactions }} + BUILD_WITHOUT_TRANSACTION_IDS: ${{ needs.build.outputs.without_transaction_ids }} + BUILD_WITH_TRANSACTION_IDS: ${{ needs.build.outputs.with_transaction_ids }} # Fetch-only mode. Checked below before any request. FETCH_RUN_ID: ${{ inputs.fetch_run_id }} FETCH_WITHOUT_IDS: ${{ inputs.fetch_without_ids }} FETCH_WITH_IDS: ${{ inputs.fetch_with_ids }} + FETCH_WITHOUT_TRANSACTION_IDS: ${{ inputs.fetch_without_transaction_ids }} + FETCH_WITH_TRANSACTION_IDS: ${{ inputs.fetch_with_transaction_ids }} # Probe mode. Checked below before the request. PROBE_METRIC: ${{ inputs.probe_metric }} FETCH_OUT: ${{ runner.temp }}/verify-pr-spike-events run: | - """Reads each side's error events by id and keeps only the fields the check needs. + """Reads each side's error events and transactions by id and keeps only the fields the check needs. Same auth as dev-packages/e2e-tests/maestro/utils/sentryApi.js. Takes each side's - event ids from the build job, or from the inputs in fetch-only mode, and checks - them before any request. Reads each event from two endpoints: /json/ (the raw - event, which drops null-valued tags) and the event detail endpoint (which keeps - them). Prints only URLs, status codes and the small files it writes: never the - token, the request headers or a response body. + error ids, and with `transactions` its transaction ids, from the build job, or + from the inputs in fetch-only mode, and checks them before any request. Reads each + event from two endpoints: /json/ (the raw event, which drops null-valued tags) and + the event detail endpoint (which keeps them). Writes a side's error events under + "events"; with `transactions`, its transactions under "transactions" and the ones + not available by the side's deadline under "missing_transactions". Prints only + URLs, status codes and the files it writes: never the token, the request headers + or a response body. """ import json @@ -344,8 +372,20 @@ jobs: DEADLINE_SECONDS = 180 RETRY_SECONDS = 5 REQUEST_TIMEOUT_SECONDS = 30 - # Event ids accepted per side. + # Error event ids accepted per side. MAX_EVENTS = 5 + # Transaction ids accepted per side; spike.py's MAX_TRANSACTIONS. + MAX_TRANSACTIONS = 10 + # One deadline for all requests for a side's transactions. One not available + # by then is recorded as missing, so the job's timeout bounds them. + TRANSACTION_DEADLINE_SECONDS = 180 + # Each span's fields under comparison, as Sentry stored them. + SPAN_FIELDS = ( + "op", "description", "status", "data", + "start_timestamp", "timestamp", "span_id", "parent_span_id", + ) + # The transaction's own span, from contexts.trace. + TRACE_FIELDS = ("op", "status", "span_id", "data") # Statuses no retry can change. A 404 is retried: the event may not be stored yet. FINAL_STATUSES = (400, 401, 403) # The token may be refused on the detail endpoint; /json/ has accepted it so far. @@ -372,40 +412,55 @@ jobs: OPENER = urllib.request.build_opener(NoRedirect) - def fetch(url, token, refusals=()): - """(status, JSON) for a URL, retried until it exists or the deadline passes. + def request_once(url, token, deadline, refusals=()): + """One request: ("ok", JSON), ("refused", status code), or ("retry", last result). - A status in `refusals` is returned with no JSON instead of failing. + Raises on a status no retry can change. """ request = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) - deadline = time.monotonic() + DEADLINE_SECONDS + try: + remaining = max(1, deadline - time.monotonic()) + timeout = min(REQUEST_TIMEOUT_SECONDS, remaining) + with OPENER.open(request, timeout=timeout) as response: + return "ok", json.loads(response.read()) + except urllib.error.HTTPError as error: + status = f"HTTP {error.code}" + error.close() + if error.code in refusals: + return "refused", error.code + # sentryApi.js gives up on 403 only; 400, 401 and redirects cannot + # succeed on a retry either. + if error.code in FINAL_STATUSES or 300 <= error.code < 400: + raise RuntimeError(f"{url}: {status}, not retrying") from None + return "retry", status + except OSError as error: + return "retry", type(error).__name__ + + + def fetch(url, token, refusals=(), deadline=None): + """(status, JSON) for a URL, retried until it exists or the deadline passes. + + A status in `refusals` is returned with no JSON instead of failing. The deadline + is DEADLINE_SECONDS from now unless given. + """ + start = time.monotonic() + if deadline is None: + deadline = start + DEADLINE_SECONDS attempt = 0 while True: attempt += 1 - try: - remaining = max(1, deadline - time.monotonic()) - timeout = min(REQUEST_TIMEOUT_SECONDS, remaining) - with OPENER.open(request, timeout=timeout) as response: - body = json.loads(response.read()) + kind, value = request_once(url, token, deadline, refusals) + if kind == "ok": print(f"{url}: HTTP 200 on attempt {attempt}", flush=True) - return 200, body - except urllib.error.HTTPError as error: - status = f"HTTP {error.code}" - error.close() - if error.code in refusals: - return error.code, None - # sentryApi.js gives up on 403 only; 400, 401 and redirects cannot - # succeed on a retry either. - if error.code in FINAL_STATUSES or 300 <= error.code < 400: - raise RuntimeError(f"{url}: {status}, not retrying") from None - except OSError as error: - status = type(error).__name__ + return 200, value + if kind == "refused": + return value, None if time.monotonic() + RETRY_SECONDS > deadline: raise RuntimeError( f"{url}: not available after {attempt} attempts in " - f"{DEADLINE_SECONDS} s, last result {status}" + f"{round(deadline - start)} s, last result {value}" ) - print(f"{url}: {status} on attempt {attempt}, retrying", flush=True) + print(f"{url}: {value} on attempt {attempt}, retrying", flush=True) time.sleep(RETRY_SECONDS) @@ -483,28 +538,17 @@ jobs: raise RuntimeError(f"{event_id}: refused, verify.run_id from {endpoint} is not {run_id}") - def summarize(event_id, run_id, raw, detail_status, detail): - """The fields under comparison, after checking both responses are this run's.""" + def checked_raw_tags(event_id, run_id, raw): + """/json/ tags, after checking the response is this event's and this run's.""" if raw.get("event_id") != event_id: raise RuntimeError(f"{event_id}: the {JSON_ENDPOINT} response is for another event") tags = raw_tags(raw) check_run_id(tags, event_id, run_id, JSON_ENDPOINT) - exceptions = (raw.get("exception") or {}).get("values") or [] - summary = { - "event_id": event_id, - "detail_status": detail_status, - "platform": raw.get("platform"), - # Sentry lists chained exceptions innermost first; the last is the - # one the issue is titled after. - "exception_type": exceptions[-1].get("type") if exceptions else None, - "exceptions": exception_frames(exceptions), - } - source = { - "event_id": JSON_ENDPOINT, - "platform": JSON_ENDPOINT, - "exception_type": JSON_ENDPOINT, - "exceptions": JSON_ENDPOINT, - } + return tags + + + def add_tags_and_errors(summary, source, event_id, run_id, tags, raw, detail): + """The kept tags and processing errors: from the detail endpoint, else /json/.""" if detail is not None: if detail.get("eventID") != event_id: raise RuntimeError(f"{event_id}: the {DETAIL_ENDPOINT} response is for another event") @@ -525,6 +569,54 @@ jobs: return summary + def summarize(event_id, run_id, raw, detail_status, detail): + """An error event's fields under comparison, after checking both responses are this run's.""" + tags = checked_raw_tags(event_id, run_id, raw) + exceptions = (raw.get("exception") or {}).get("values") or [] + summary = { + "event_id": event_id, + "detail_status": detail_status, + "platform": raw.get("platform"), + # Sentry lists chained exceptions innermost first; the last is the + # one the issue is titled after. + "exception_type": exceptions[-1].get("type") if exceptions else None, + "exceptions": exception_frames(exceptions), + } + source = { + "event_id": JSON_ENDPOINT, + "platform": JSON_ENDPOINT, + "exception_type": JSON_ENDPOINT, + "exceptions": JSON_ENDPOINT, + } + return add_tags_and_errors(summary, source, event_id, run_id, tags, raw, detail) + + + def summarize_transaction(event_id, run_id, raw, detail_status, detail): + """A transaction's fields under comparison, after checking both responses are this run's. + + The name, its own span from contexts.trace, and every child span, all from /json/ + as Sentry stored them, in stored order. + """ + tags = checked_raw_tags(event_id, run_id, raw) + if raw.get("type") != "transaction": + raise RuntimeError(f"{event_id}: refused, the {JSON_ENDPOINT} response is not a transaction") + trace = (raw.get("contexts") or {}).get("trace") or {} + summary = { + "event_id": event_id, + "detail_status": detail_status, + "transaction": raw.get("transaction"), + "trace": {field: trace.get(field) for field in TRACE_FIELDS}, + "spans": [{field: span.get(field) for field in SPAN_FIELDS} for span in raw.get("spans") or []], + } + source = { + "event_id": JSON_ENDPOINT, + "transaction": JSON_ENDPOINT, + "trace": JSON_ENDPOINT, + "spans": JSON_ENDPOINT, + } + return add_tags_and_errors(summary, source, event_id, run_id, tags, raw, detail) + + def read_event(event_id, run_id, token): url = PROJECT_URL + JSON_ENDPOINT.replace("", event_id) _, raw = fetch(url, token) @@ -535,30 +627,97 @@ jobs: return summarize(event_id, run_id, raw, detail_status, detail) - def event_ids(side, value): - """A side's event ids from a comma-separated list. Never prints the value.""" + def read_transactions(ids, run_id, token): + """A side's transactions, and the ones not available by its deadline. + + Polls /json/ of the ids not read yet in rounds, under one deadline for the side. + The detail endpoint shares it, and /json/ stands in when it can't be read. + Fails only when none could be read. + """ + deadline = time.monotonic() + TRANSACTION_DEADLINE_SECONDS + raws = {} + last = {event_id: None for event_id in ids} + attempt = 0 + while True: + attempt += 1 + for event_id in [event_id for event_id in ids if event_id not in raws]: + url = PROJECT_URL + JSON_ENDPOINT.replace("", event_id) + kind, value = request_once(url, token, deadline) + if kind == "ok": + print(f"{url}: HTTP 200 on attempt {attempt}", flush=True) + raws[event_id] = value + else: + print(f"{url}: {value} on attempt {attempt}", flush=True) + last[event_id] = value + if len(raws) == len(ids) or time.monotonic() + RETRY_SECONDS > deadline: + break + time.sleep(RETRY_SECONDS) + if not raws: + raise RuntimeError(f"none of the {len(ids)} transactions available in {TRANSACTION_DEADLINE_SECONDS} s") + transactions = [] + for event_id in ids: + if event_id not in raws: + continue + url = PROJECT_URL + DETAIL_ENDPOINT.replace("", event_id) + try: + detail_status, detail = fetch(url, token, REFUSALS, max(deadline, time.monotonic() + 1)) + if detail is None: + print(f"{url}: HTTP {detail_status}, falling back to {JSON_ENDPOINT}", flush=True) + except RuntimeError as error: + print(f"{error}, falling back to {JSON_ENDPOINT}", flush=True) + detail_status, detail = "unavailable", None + transactions.append(summarize_transaction(event_id, run_id, raws[event_id], detail_status, detail)) + missing = [{"event_id": event_id, "last_result": last[event_id]} for event_id in ids if event_id not in raws] + return transactions, missing + + + def event_ids(side, value, limit=MAX_EVENTS, kind="event", article="an"): + """A side's ids of one kind from a comma-separated list, maybe none. Never prints the value.""" ids = [event_id.strip() for event_id in value.split(",")] if value else [] - if not ids: - raise ValueError(f"{side}: no event ids") - if len(ids) > MAX_EVENTS: - raise ValueError(f"{side}: {len(ids)} event ids, at most {MAX_EVENTS}") + if len(ids) > limit: + raise ValueError(f"{side}: {len(ids)} {kind} ids, at most {limit}") if not all(EVENT_ID.fullmatch(event_id) for event_id in ids): - raise ValueError(f"{side}: an event id is not 32 lowercase hex characters") + raise ValueError(f"{side}: {article} {kind} id is not 32 lowercase hex characters") return ids + def side_ids(side, source, with_transactions): + """A side's error ids, and its transaction ids with `transactions`. + + Without `transactions` a side needs an error id, and with it a transaction id. + """ + prefix = f"{source}_{side.upper()}" + errors = event_ids(side, os.environ[f"{prefix}_IDS"]) + if not with_transactions: + if not errors: + raise ValueError(f"{side}: no event ids") + return errors, [] + transactions = event_ids( + side, os.environ[f"{prefix}_TRANSACTION_IDS"], MAX_TRANSACTIONS, "transaction", "a" + ) + if not transactions: + raise ValueError(f"{side}: no transaction ids") + return errors, transactions + + def sides(): - """Each side's expected run id and event ids, checked before any request.""" + """Whether `transactions` is on, and each side's expected run id, error ids and + transaction ids, checked before any request.""" fetch_run_id = os.environ["FETCH_RUN_ID"] + with_transactions = os.environ["TRANSACTIONS"] == "true" if fetch_run_id: if not DIGITS.fullmatch(fetch_run_id): raise ValueError("fetch_run_id is not digits") run, source = fetch_run_id, "FETCH" + # In fetch-only mode, transaction ids are enough to turn it on. + with_transactions = with_transactions or any( + os.environ[f"FETCH_{side.upper()}_TRANSACTION_IDS"] for side in SIDES + ) else: run, source = os.environ["WORKFLOW_RUN_ID"], "BUILD" - return { - # Built in this job; only the event ids come from the build job or the inputs. - side: (f"gh{run}-{side}", event_ids(side, os.environ[f"{source}_{side.upper()}_IDS"])) + return with_transactions, { + # Built in this job; only the ids come from the build job or the inputs. + side: (f"gh{run}-{side}", *side_ids(side, source, with_transactions)) for side in SIDES } @@ -612,7 +771,7 @@ jobs: probe(metric_name, token) return try: - checked = sides() + with_transactions, checked = sides() except ValueError as error: sys.exit(f"invalid event ids or run id: {error}") token = os.environ.get("SENTRY_AUTH_TOKEN", "") @@ -620,14 +779,20 @@ jobs: sys.exit("SENTRY_AUTH_TOKEN is empty") OUT.mkdir(parents=True, exist_ok=True) failures = [] - for side, (run_id, ids) in checked.items(): + for side, (run_id, ids, transaction_ids) in checked.items(): try: events = [read_event(event_id, run_id, token) for event_id in ids] + if with_transactions: + transactions, missing = read_transactions(transaction_ids, run_id, token) except (RuntimeError, ValueError, AttributeError, TypeError) as error: # None of these messages carries a response body. failures.append(f"{side}: {type(error).__name__}: {error}") continue result = {"run_id": run_id, "events": events} + # Only with `transactions`, so an error run's file stays as it was. + if with_transactions: + result["transactions"] = transactions + result["missing_transactions"] = missing text = json.dumps(result, indent=2) + "\n" (OUT / f"{side}.json").write_text(text) print(f"{side}.json:\n{text}", flush=True)