From bc27efce46af71c5750863f9b9efc73556c6611b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:34:24 +0000 Subject: [PATCH 1/2] ci(android): Collect transactions as evidence in the verify-pr test workflow Co-Authored-By: Antonis Lilis --- .github/verify-pr-spike/spike.py | 38 ++++-- .github/workflows/verify-pr-spike.yml | 170 +++++++++++++++++++------- 2 files changed, 152 insertions(+), 56 deletions(-) diff --git a/.github/verify-pr-spike/spike.py b/.github/verify-pr-spike/spike.py index f320d37202..2a8d90e847 100644 --- a/.github/verify-pr-spike/spike.py +++ b/.github/verify-pr-spike/spike.py @@ -6,9 +6,9 @@ reverse-applied) and with it, rebuilding `packages/core` in between so each APK 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. +checks. After each flow it reads the ids of the error events and of the +transactions the app sent from the device log; 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. @@ -65,6 +65,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 +240,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 +288,8 @@ 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) + 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,19 +307,30 @@ 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"]: - failures.append(f"no 'Event beforeSend:' event id in the device log for {side}") + # Evidence is an error event or a transaction; a side with neither fails. + record = results["runs"][side] + if not record["event_ids"] and not record["transaction_ids"]: + failures.append( + f"no 'Event beforeSend:' or 'Transaction beforeSend:' event id in the device log for {side}" + ) save(results) if failures: sys.exit("; ".join(failures)) def cmd_outputs(_args): - """Writes each side's event ids as a job output, a comma-separated list.""" + """Writes each side's error and transaction ids as job outputs, comma-separated lists.""" runs = load()["runs"] with open(os.environ["GITHUB_OUTPUT"], "a") as fh: for side in SIDES: + 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}_event_ids={','.join(runs[side]['event_ids'])}\n") + 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..1a60d33498 100644 --- a/.github/workflows/verify-pr-spike.yml +++ b/.github/workflows/verify-pr-spike.yml @@ -9,8 +9,9 @@ run-name: "${{ inputs.pr != '' && inputs.fetch_run_id == '' && inputs.probe_metr # with it, rebuilding packages/core before each side so each APK bundles its own # 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. +# checkout. It hands the fetch job only the ids of each side's error events and +# transactions, read from the sample's `'Event beforeSend:', ''` and +# `'Transaction beforeSend:', ''` device log lines. A side with neither fails. # # 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 +19,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` and the transactions given in `fetch_without_transaction_ids` +# and `fetch_with_transaction_ids`, expecting the run ids of that earlier run. +# `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 @@ -66,6 +68,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 +105,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 @@ -287,7 +299,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 +309,35 @@ 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 }} + 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 and 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" and, when it has + transaction ids, its transactions under "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 +362,17 @@ 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 + # 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. @@ -483,28 +510,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,30 +541,86 @@ jobs: return summary - def read_event(event_id, run_id, token): + 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, summarize_event): url = PROJECT_URL + JSON_ENDPOINT.replace("", event_id) _, raw = fetch(url, token) url = PROJECT_URL + DETAIL_ENDPOINT.replace("", event_id) detail_status, detail = fetch(url, token, REFUSALS) if detail is None: print(f"{url}: HTTP {detail_status}, falling back to {JSON_ENDPOINT}", flush=True) - return summarize(event_id, run_id, raw, detail_status, detail) + return summarize_event(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 event_ids(side, kind, value, limit): + """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}: a {kind} id is not 32 lowercase hex characters") return ids + def side_ids(side, source): + """A side's error and transaction ids. A side needs at least one of either.""" + prefix = f"{source}_{side.upper()}" + errors = event_ids(side, "event", os.environ[f"{prefix}_IDS"], MAX_EVENTS) + transactions = event_ids(side, "transaction", os.environ[f"{prefix}_TRANSACTION_IDS"], MAX_TRANSACTIONS) + if not errors and not transactions: + raise ValueError(f"{side}: no event ids and no transaction ids") + return errors, transactions + + def sides(): - """Each side's expected run id and event ids, checked before any request.""" + """Each side's expected run id, error ids and transaction ids, checked before any request.""" fetch_run_id = os.environ["FETCH_RUN_ID"] if fetch_run_id: if not DIGITS.fullmatch(fetch_run_id): @@ -557,8 +629,8 @@ jobs: 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"])) + # Built in this job; only the ids come from the build job or the inputs. + side: (f"gh{run}-{side}", *side_ids(side, source)) for side in SIDES } @@ -620,14 +692,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] + events = [read_event(event_id, run_id, token, summarize) for event_id in ids] + transactions = [ + read_event(event_id, run_id, token, summarize_transaction) for event_id in transaction_ids + ] 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 transaction ids, so an error-only side's file stays as it was. + if transaction_ids: + result["transactions"] = transactions text = json.dumps(result, indent=2) + "\n" (OUT / f"{side}.json").write_text(text) print(f"{side}.json:\n{text}", flush=True) From f8307253f153b359f4ccad85fa2ead19b312122e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:49:08 +0000 Subject: [PATCH 2/2] ci(android): Make transaction evidence opt-in and tolerate missing transactions Co-Authored-By: Antonis Lilis --- .github/verify-pr-spike/spike.py | 29 ++-- .github/workflows/verify-pr-spike.yml | 199 ++++++++++++++++++-------- 2 files changed, 161 insertions(+), 67 deletions(-) diff --git a/.github/verify-pr-spike/spike.py b/.github/verify-pr-spike/spike.py index 2a8d90e847..aea7e25988 100644 --- a/.github/verify-pr-spike/spike.py +++ b/.github/verify-pr-spike/spike.py @@ -6,9 +6,10 @@ reverse-applied) and with it, rebuilding `packages/core` in between so each APK 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 and of the -transactions the app sent from the device log; the `outputs` step hands them to -the fetch job, one comma-separated list per side and kind. +checks. After each flow it reads the ids of the error events the app sent from +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). @@ -289,7 +292,8 @@ def run_side(side, results): record["logcat_run_id_lines"] = logcat.count(run_id) record["logcat_envelopes_sent"] = logcat.count("Envelope sent successfully") record["event_ids"] = logged_ids(BEFORE_SEND_EVENT_ID, logcat) - record["transaction_ids"] = logged_ids(BEFORE_SEND_TRANSACTION_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. @@ -307,29 +311,32 @@ def cmd_run(_args): for side in SIDES: if run_side(side, results) != 0: failures.append(f"the Maestro flow failed for {side}") - # Evidence is an error event or a transaction; a side with neither fails. + # With transactions, each side needs one and error events are optional. record = results["runs"][side] - if not record["event_ids"] and not record["transaction_ids"]: - failures.append( - f"no 'Event beforeSend:' or 'Transaction beforeSend:' event id in the device log for {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: sys.exit("; ".join(failures)) def cmd_outputs(_args): - """Writes each side's error and transaction ids as job outputs, comma-separated lists.""" + """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}_event_ids={','.join(runs[side]['event_ids'])}\n") fh.write(f"{side}_transaction_ids={','.join(transaction_ids[:MAX_TRANSACTIONS])}\n") diff --git a/.github/workflows/verify-pr-spike.yml b/.github/workflows/verify-pr-spike.yml index 1a60d33498..d5d4205292 100644 --- a/.github/workflows/verify-pr-spike.yml +++ b/.github/workflows/verify-pr-spike.yml @@ -9,9 +9,11 @@ run-name: "${{ inputs.pr != '' && inputs.fetch_run_id == '' && inputs.probe_metr # with it, rebuilding packages/core before each side so each APK bundles its own # 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 and -# transactions, read from the sample's `'Event beforeSend:', ''` and -# `'Transaction beforeSend:', ''` device log lines. A side with neither fails. +# 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, 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 @@ -20,9 +22,9 @@ run-name: "${{ inputs.pr != '' && inputs.fetch_run_id == '' && inputs.probe_metr # # Fetch-only mode: with `fetch_run_id` set, the build job is skipped and the # fetch job reads the error events given in `fetch_without_ids` and -# `fetch_with_ids` and the transactions given in `fetch_without_transaction_ids` -# and `fetch_with_transaction_ids`, expecting the run ids of that earlier run. -# `ref`, `pr`, `base_sha` and `flow` are not needed then. +# `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 @@ -56,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 @@ -114,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: @@ -316,6 +324,7 @@ jobs: 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. @@ -331,13 +340,14 @@ jobs: """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 - error and 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" and, when it has - transaction ids, its transactions under "transactions". Prints only URLs, status - codes and the 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 @@ -366,6 +376,9 @@ jobs: 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", @@ -399,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) @@ -589,48 +617,107 @@ jobs: return add_tags_and_errors(summary, source, event_id, run_id, tags, raw, detail) - def read_event(event_id, run_id, token, summarize_event): + def read_event(event_id, run_id, token): url = PROJECT_URL + JSON_ENDPOINT.replace("", event_id) _, raw = fetch(url, token) url = PROJECT_URL + DETAIL_ENDPOINT.replace("", event_id) detail_status, detail = fetch(url, token, REFUSALS) if detail is None: print(f"{url}: HTTP {detail_status}, falling back to {JSON_ENDPOINT}", flush=True) - return summarize_event(event_id, run_id, raw, detail_status, detail) + return summarize(event_id, run_id, raw, detail_status, detail) - def event_ids(side, kind, value, limit): + 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 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}: a {kind} 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): - """A side's error and transaction ids. A side needs at least one of either.""" + 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, "event", os.environ[f"{prefix}_IDS"], MAX_EVENTS) - transactions = event_ids(side, "transaction", os.environ[f"{prefix}_TRANSACTION_IDS"], MAX_TRANSACTIONS) - if not errors and not transactions: - raise ValueError(f"{side}: no event ids and no transaction ids") + 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, error ids and transaction 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 { + 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)) + side: (f"gh{run}-{side}", *side_ids(side, source, with_transactions)) for side in SIDES } @@ -684,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", "") @@ -694,18 +781,18 @@ jobs: failures = [] for side, (run_id, ids, transaction_ids) in checked.items(): try: - events = [read_event(event_id, run_id, token, summarize) for event_id in ids] - transactions = [ - read_event(event_id, run_id, token, summarize_transaction) for event_id in transaction_ids - ] + 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 transaction ids, so an error-only side's file stays as it was. - if transaction_ids: + # 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)