:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(engineering-analytics): track the revert share of merged pull requests (#120181)
Georges-Antoine Assi860185d7a244
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 5a5ba8919507..1d243be43729 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -10427,17 +10427,17 @@ snapshots:scenes-app-engineering-analytics-pull-request--section-load-errors--light:hash: v1.k794b7964.6666cde9262743b7824ee9a39abb36a0d5285419252424ea5fe8b21d8e3c412c.SMA91aAvY1AeNAGRUyxxwMjJd5yiRkLrLmKbzSH_IOcscenes-app-engineering-analytics-repo-overview--repo-overview--dark:- hash: v1.k794b7964.1891b27c427eeacc778c17aae2a415e4cde048540f95d79be52a4031e8ad5f58.zvBjyvMrnN15yUfqWfiC8MaI72OThY0dXnKCunATzgs+ hash: v1.k794b7964.87be1d41fd12e12ad1acd81ffaaa5893ec06f42e41e9f2901b916c3761f1661c._2khTyS28hvNBlShZzSSXpSYhkCsHpJstqox5OLihnwscenes-app-engineering-analytics-repo-overview--repo-overview--light:- hash: v1.k794b7964.fc84c401be718826fc1ffafb2978e6d9a9a757ff719a693c48ca658e89444e54.S5_fgia9xnwRe3shj_RdfaA9Gd-UZG_7FpQ50KuSbzw+ hash: v1.k794b7964.671d82298164c1f890c1782854cf946a69c484d9be7f5af29e3c177f6e69f33c.a4wQxYP6rm3yJRsKn8MuLbgPtqAAz1Uc8IQmVThfxq8scenes-app-engineering-analytics-repo-overview--repo-overview-with-several-repositories--dark:- hash: v1.k794b7964.a69d28c8183bdf87f260ada495110b72c587f00c66969154879ea353d3b16179.30e70egR2_ldxgEYgJejAai4nO9obPXMdSnaLMzTRFo+ hash: v1.k794b7964.cb6a4d3c506732f5087f29c24883d3e1bdfef4f459110993973568ce1776ec08.LBoGA1tXCJRaIxDg02vLQxER_x4Ql8NiOqm0Qm90uh8scenes-app-engineering-analytics-repo-overview--repo-overview-with-several-repositories--light:- hash: v1.k794b7964.8ff34e1ffc6b5400f8f82094342c784032db60aeb30f3fa33a856ad6b9b14752.qa7dL0EfUjAqKl9NrHwi9i99dhTA5oZ_DkiR3lRFBzQ+ hash: v1.k794b7964.d98cb4a59e3b8b31dc49bffac04b35a1e5922c30c39313ded28dc2e95fa90cb5.jRY8SDWX3yRlE0-WK1G7PY8f5ODM0eUGM1woXueAEm4scenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--dark:- hash: v1.k794b7964.1891b27c427eeacc778c17aae2a415e4cde048540f95d79be52a4031e8ad5f58.wLPhR03AW0mLDd-VoCK2IKCP2LztfvjIGoTiK4I4yiA+ hash: v1.k794b7964.87be1d41fd12e12ad1acd81ffaaa5893ec06f42e41e9f2901b916c3761f1661c.Y1f8W2F9qHcXN4C82rj8-l88ane9Vz2Sos647vpjENAscenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--light:- hash: v1.k794b7964.fc84c401be718826fc1ffafb2978e6d9a9a757ff719a693c48ca658e89444e54.aTnGv7rF-txJenzrAmrPW2BnDIr2e3GpGxsu5A_7tTA+ hash: v1.k794b7964.671d82298164c1f890c1782854cf946a69c484d9be7f5af29e3c177f6e69f33c.ad1Fk85U9HCftoorirZAipAF6F3I65Wos9-PDi0zUakscenes-app-engineering-analytics-run-activity-chart--default--dark:hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJEscenes-app-engineering-analytics-run-activity-chart--default--light:diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 70c4e68f09dd..b0f219a8a3cc 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -95,6 +95,7 @@ The endpoint catalog is `presentation/views.py`; the agent-facing descriptions l- Test evidence is counted per CI run, never per span or run attempt (one run fans a test across matrix legs, and every attempt re-tests the same commit), and both span-derived reads group the same `run_evidence()` so the grain and the meaning of flaky cannot drift. A test is `confirmed_flake` only on same-commit recovery proof: a re-run attempt going green, or an in-job retry. Unproven failures rank as `suspected_regression` by blast radius.- A CI setup break is not per-test evidence. `run_evidence()` drops every trial of a run attempt whose errored tests span 3 or more jobs or 3 or more owning teams, and of a job attempt with 100 or more distinct failed or errored tests, so their failures are no test's failure and their passes are no test's recovery. The spans name the attempt, and GitHub's synced `workflow_jobs` rows confirm it: a run attempt must report 3 or more failed jobs there, a job attempt at least one. CI stamps every span attribute the rule reads, so no evidence is dropped on the spans alone, and an unsynced jobs table drops nothing.- Reads over optional data (e.g. `team_members`) degrade honestly (`has_membership_data: false`), never 500.+- A reverting pull request is recognized by its title, defined once in `logic/reverts.py`: GitHub's `Revert "<title>"` or a conventional-commit `revert: ...` / `revert(scope): ...` title. GitHub records no link from a revert to the change it undid, so `repo_overview` reports `reverting_pr_count` and `revert_share` against every merged pull request in the window, counted when the revert merges. The share is the guardrail to read before a review requirement is loosened.- A pull request's lifetime cost on the list reads is cached for 5 minutes per pull request, because it needs a full jobs scan however few pull requests a page shows. CI status stays live. The cache key carries a hash of the cost query, so a change to the query, its prices or the resolved tables starts a fresh cache. A cached value is served only when the reader's HogQL catalog grants every table that query reads.### Exposed warehouse viewsdiff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex d846b3da5578..972fbc6b483d 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1384,6 +1384,22 @@ class ReadyToMergeBucket:p50_seconds: float | None+@dataclass(frozen=True)+class RevertShareBucket:+ """One time bucket of reverts among the repo's merges: PRs merged in the bucket whose title+ names a revert (``logic/reverts.py``), over every PR merged in it, all authors and bots+ included. Keyed on the revert's own merge time, not on the change it undid. Empty buckets are+ zero-filled with 0 merges and a None share, so a quiet stretch is never shown as 0% reverted.+ """++ # Bucket start, aligned to the granularity (top of hour / midnight / Monday). Keyed on merge time.+ bucket_start: datetime+ merged_pr_count: int+ reverting_pr_count: int+ # None when nothing merged in the bucket.+ revert_share: float | None++class DeliveryStage(LabeledStrEnum):"""A pre-merge leg of a PR's path to production, named for the timestamps that bound it.@@ -1444,6 +1460,13 @@ class RepoOverview:# so cost-per-merge ratios use the same denominator as the cost series' bucket-local merges.merged_pr_count: intmerged_pr_count_prev: int+ # Merged PRs whose title names a revert (logic/reverts.py), counted when the revert merges, not+ # when the change it undid did. Same population as merged_pr_count.+ reverting_pr_count: int+ reverting_pr_count_prev: int+ # reverting_pr_count / merged_pr_count. None when nothing merged.+ revert_share: float | None+ revert_share_prev: float | None# Coarse by design: merged_at - created_at (draft + ready time fused), median over PRs merged in the window.median_open_to_merge_seconds: float | Nonemedian_open_to_merge_seconds_prev: float | None@@ -1533,6 +1556,11 @@ class RepoOverview:ready_to_merge_series: list[ReadyToMergeBucket]# Bucket width of `ready_to_merge_series`, chosen to fit the window: 'hour', 'day', or 'week'.ready_to_merge_series_granularity: str+ # Revert trend: reverting merges over all merges per bucket (all authors, bots included), oldest+ # first, zero-filled, bucketed by `revert_share_series_granularity`. Empty buckets carry a None share.+ revert_share_series: list[RevertShareBucket]+ # Bucket width of `revert_share_series`, chosen to fit the window: 'hour', 'day', or 'week'.+ revert_share_series_granularity: str# Bots and drafts excluded, unlike the headline counts above.delivery_pipeline: DeliveryPipelinediff --git a/products/engineering_analytics/backend/logic/queries/repo_overview.py b/products/engineering_analytics/backend/logic/queries/repo_overview.pyindex 09b4a4870a8a..45df500aa260 100644--- a/products/engineering_analytics/backend/logic/queries/repo_overview.py+++ b/products/engineering_analytics/backend/logic/queries/repo_overview.py@@ -26,6 +26,7 @@ from products.engineering_analytics.backend.facade.contracts import (PassRateBucket,ReadyToMergeBucket,RepoOverview,+ RevertShareBucket,TimeToGreenBucket,)from products.engineering_analytics.backend.logic.queries._buckets import (@@ -83,7 +84,9 @@ _PR_SELECT = f"""__READY_MEDIAN_CUR__ AS ready_median_cur,__READY_MEDIAN_PREV__ AS ready_median_prev,countIf(__CUR_MERGED__) AS merged_cur,- countIf(__PREV_MERGED__) AS merged_prev+ countIf(__PREV_MERGED__) AS merged_prev,+ countIf(__CUR_MERGED__ AND is_revert) AS reverting_cur,+ countIf(__PREV_MERGED__ AND is_revert) AS reverting_prevFROM __PR_SOURCE__ AS pr__READY_JOIN__WHERE merged_at IS NOT NULL AND merged_at >= {{prev_from}}@@ -246,6 +249,60 @@ def query_ready_to_merge_series(]+def _share(part: int, whole: int) -> float | None:+ return part / whole if whole else None+++# Reverts over all merges per bucket, the same all-authors population as the headline merge counts.+_REVERT_SHARE_SERIES_SELECT = """+ SELECT+ __BUCKET_FN__ AS bucket_start,+ count() AS merged,+ countIf(is_revert) AS reverting+ FROM __PR_SOURCE__ AS pr+ WHERE merged_at IS NOT NULL AND merged_at >= {date_from} __DATE_TO_MERGED__+ GROUP BY bucket_start+ LIMIT 40000+"""+++def query_revert_share_series(+ *,+ curated: CuratedGitHubSource,+ date_from: datetime,+ date_to: datetime | None,+ granularity: Granularity,+) -> list[RevertShareBucket]:+ """Reverting merges over all merges per bucket across the window, oldest first and zero-filled.+ A bucket where nothing merged carries 0 merges and a None share."""+ placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from)}+ date_to_clause = "AND merged_at <= {date_to}" if date_to is not None else ""+ if date_to is not None:+ placeholders["date_to"] = ast.Constant(value=date_to)+ sql = (+ _REVERT_SHARE_SERIES_SELECT.replace("__PR_SOURCE__", curated.pr_source())+ .replace("__DATE_TO_MERGED__", date_to_clause)+ .replace("__BUCKET_FN__", bucket_expr(granularity, "merged_at"))+ )+ response = curated.run(sql, query_type="engineering_analytics.revert_share_series", placeholders=placeholders)+ counts_by_bucket = {+ normalize_bucket(bucket_start, granularity): (int(merged or 0), int(reverting or 0))+ for bucket_start, merged, reverting in response.results or []+ }+ buckets: list[RevertShareBucket] = []+ for bucket in window_buckets(date_from, date_to, granularity):+ merged, reverting = counts_by_bucket.get(bucket, (0, 0))+ buckets.append(+ RevertShareBucket(+ bucket_start=bucket,+ merged_pr_count=merged,+ reverting_pr_count=reverting,+ revert_share=_share(reverting, merged),+ )+ )+ return buckets++def query_open_to_merge_series(*,curated: CuratedGitHubSource,@@ -286,6 +343,7 @@ class RepoSeries:success_rate: list[PassRateBucket]open_to_merge: list[OpenToMergeBucket]ready_to_merge: list[ReadyToMergeBucket]+ revert_share: list[RevertShareBucket]def query_repo_series(@@ -313,6 +371,9 @@ def query_repo_series(ready_to_merge=query_ready_to_merge_series(curated=curated, date_from=date_from, date_to=date_to, granularity=granularity),+ revert_share=query_revert_share_series(+ curated=curated, date_from=date_from, date_to=date_to, granularity=granularity+ ),)@@ -326,6 +387,7 @@ def empty_repo_series(*, date_from: datetime, date_to: datetime | None) -> RepoSsuccess_rate=[],open_to_merge=[],ready_to_merge=[],+ revert_share=[],)@@ -390,6 +452,8 @@ class _MergeHeadlines:median_ready_to_merge_seconds_prev: float | Nonemerged_count: intmerged_count_prev: int+ reverting_count: int+ reverting_count_prev: intdef _query_merge_headlines(@@ -416,8 +480,8 @@ def _query_merge_headlines(.replace("__PR_SOURCE__", curated.pr_source()))response = curated.run(sql, query_type="engineering_analytics.repo_overview_prs", placeholders=placeholders)- median_cur, median_prev, ready_cur, ready_prev, merged_cur, merged_prev = (- response.results[0] if response.results else (None, None, None, None, 0, 0)+ median_cur, median_prev, ready_cur, ready_prev, merged_cur, merged_prev, reverting_cur, reverting_prev = (+ response.results[0] if response.results else (None, None, None, None, 0, 0, 0, 0))return _MergeHeadlines(median_open_to_merge_seconds=opt_float(median_cur),@@ -426,6 +490,8 @@ def _query_merge_headlines(median_ready_to_merge_seconds_prev=opt_float(ready_prev),merged_count=int(merged_cur or 0),merged_count_prev=int(merged_prev or 0),+ reverting_count=int(reverting_cur or 0),+ reverting_count_prev=int(reverting_prev or 0),)@@ -530,6 +596,10 @@ def query_repo_overview(rerun_cycles_prev=runs.rerun_cycles_prev,merged_pr_count=merges.merged_count,merged_pr_count_prev=merges.merged_count_prev,+ reverting_pr_count=merges.reverting_count,+ reverting_pr_count_prev=merges.reverting_count_prev,+ revert_share=_share(merges.reverting_count, merges.merged_count),+ revert_share_prev=_share(merges.reverting_count_prev, merges.merged_count_prev),median_open_to_merge_seconds=merges.median_open_to_merge_seconds,median_open_to_merge_seconds_prev=merges.median_open_to_merge_seconds_prev,median_ready_to_merge_seconds=merges.median_ready_to_merge_seconds,@@ -579,5 +649,7 @@ def query_repo_overview(open_to_merge_series_granularity=series.granularity,ready_to_merge_series=series.ready_to_merge,ready_to_merge_series_granularity=series.granularity,+ revert_share_series=series.revert_share,+ revert_share_series_granularity=series.granularity,delivery_pipeline=pipeline,)diff --git a/products/engineering_analytics/backend/logic/reverts.py b/products/engineering_analytics/backend/logic/reverts.pynew file mode 100644index 000000000000..88b261cbf1f8--- /dev/null+++ b/products/engineering_analytics/backend/logic/reverts.py@@ -0,0 +1,22 @@+"""Reverts: telling a pull request that undoes another apart from ordinary work, defined once.++GitHub records no link between a revert and the change it undoes, so the only signal in the+warehouse is the title. Two shapes name a revert:++- GitHub's revert button: ``Revert "<original title>"``.+- A conventional-commit title: ``revert: <subject>`` or ``revert(<scope>): <subject>``, with an+ optional breaking-change ``!`` before the colon, the form a repository that lints pull request+ titles produces.++Both patterns are anchored at the start of the title, so a title that merely mentions a revert+does not count. The pattern stays backslash-free so it survives embedding in a HogQL string+literal unescaped.+"""++_REVERT_TITLE_PATTERN = '(?i)^revert( "|([(][^()]*[)])?!?: )'+++def revert_title_expr(title_column: str) -> str:+ """HogQL: whether ``title_column`` names a revert. ``ifNull`` keeps a NULL title from poisoning+ a ``countIf`` the way a NULL inside ``match`` would."""+ return f"match(ifNull({title_column}, ''), '{_REVERT_TITLE_PATTERN}')"diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.pyindex 4eb71191280a..564dfe0c4e1e 100644--- a/products/engineering_analytics/backend/logic/views/pull_requests.py+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py@@ -33,6 +33,7 @@ avoids referencing a same-SELECT alias as another expression's input."""from products.engineering_analytics.backend.logic.merge_queue import merge_queue_branch_expr+from products.engineering_analytics.backend.logic.reverts import revert_title_expr# Bots whose handle does not carry GitHub's automatic ``[bot]`` suffix. Kept# deliberately small; per-team configuration is deferred.@@ -60,6 +61,7 @@ def build_query(table_name: str) -> str:author_handle,author_avatar_url,(author_handle LIKE '%[bot]' OR author_handle IN ({_bot_handle_in_list()})) AS is_bot,+ {revert_title_expr("title")} AS is_revert,arrayElement(repo_parts, 1) AS repo_owner,arrayElement(repo_parts, 2) AS repo_name,arrayMap(label -> JSONExtractString(label, 'name'), JSONExtractArrayRaw(labels_json)) AS labels,diff --git a/products/engineering_analytics/backend/presentation/serializers/workflows.py b/products/engineering_analytics/backend/presentation/serializers/workflows.pyindex 99acf56d26d2..68730b944632 100644--- a/products/engineering_analytics/backend/presentation/serializers/workflows.py+++ b/products/engineering_analytics/backend/presentation/serializers/workflows.py@@ -24,6 +24,7 @@ from products.engineering_analytics.backend.facade.contracts import (PassRateBucket,ReadyToMergeBucket,RepoOverview,+ RevertShareBucket,RunFailureLogs,TimeToGreenBucket,WorkflowHealthBucket,@@ -633,6 +634,26 @@ class ReadyToMergeBucketSerializer(DataclassSerializer):}+class RevertShareBucketSerializer(DataclassSerializer):+ class Meta:+ dataclass = RevertShareBucket+ extra_kwargs = {+ "bucket_start": {+ "help_text": "Bucket start, aligned to revert_share_series_granularity (top of hour, midnight, or Monday). "+ "Keyed on the revert's own merge time."+ },+ "merged_pr_count": {"help_text": "PRs merged in this bucket, all authors and bots included."},+ "reverting_pr_count": {+ "help_text": "Of those, PRs whose title names a revert: GitHub's 'Revert \"...\"' or a "+ "conventional-commit 'revert: ...' / 'revert(scope): ...' title."+ },+ "revert_share": {+ "help_text": "reverting_pr_count divided by merged_pr_count. Null when nothing merged in the bucket.",+ "allow_null": True,+ },+ }++class DeliveryStageTimingSerializer(DataclassSerializer):class Meta:dataclass = DeliveryStageTiming@@ -712,6 +733,12 @@ class RepoOverviewSerializer(DataclassSerializer):"null; the whole series is empty when the issue-events table isn't synced or include_series=false, ""so fall back to open_to_merge_series.",)+ revert_share_series = RevertShareBucketSerializer(+ many=True,+ help_text="Reverting merges over all merges (all authors, bots included) per bucket across the window, "+ "oldest first, zero-filled, bucketed by revert_share_series_granularity. Empty buckets carry a null "+ "share; the whole series is empty when include_series=false.",+ )class Meta:dataclass = RepoOverview@@ -737,6 +764,23 @@ class RepoOverviewSerializer(DataclassSerializer):"so dividing them by this count spreads all CI spend over the merges."},"merged_pr_count_prev": {"help_text": "Merged-PR count over the previous window."},+ "reverting_pr_count": {+ "help_text": "PRs merged in the window whose title names a revert: GitHub's 'Revert \"...\"' or a "+ "conventional-commit 'revert: ...' / 'revert(scope): ...' title. Counts the revert when it merges, "+ "not the change it undid, which may have merged in an earlier window. Same population as "+ "merged_pr_count."+ },+ "reverting_pr_count_prev": {"help_text": "Reverting-PR count over the previous window."},+ "revert_share": {+ "help_text": "reverting_pr_count divided by merged_pr_count: the share of merges that undid an "+ "earlier merge. The guardrail to watch when review requirements are loosened. Null when nothing "+ "merged.",+ "allow_null": True,+ },+ "revert_share_prev": {+ "help_text": "The same share over the previous window. Null when nothing merged.",+ "allow_null": True,+ },"median_open_to_merge_seconds": {"help_text": "Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. ""Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.",@@ -926,6 +970,9 @@ class RepoOverviewSerializer(DataclassSerializer):"ready_to_merge_series_granularity": {"help_text": "Bucket width of the ready_to_merge_series trend: 'hour', 'day', or 'week'."},+ "revert_share_series_granularity": {+ "help_text": "Bucket width of the revert_share_series trend: 'hour', 'day', or 'week'."+ },}diff --git a/products/engineering_analytics/backend/presentation/views/workflows.py b/products/engineering_analytics/backend/presentation/views/workflows.pyindex 2b6755889aa0..583feecff60e 100644--- a/products/engineering_analytics/backend/presentation/views/workflows.py+++ b/products/engineering_analytics/backend/presentation/views/workflows.py@@ -506,7 +506,8 @@ class WorkflowActionsMixin(EngineeringAnalyticsViewSetBase):},description=("Repo-level headline aggregates over a window (default -30d): run count, conclusive-run success rate, re-run "- "cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; "+ "cycles, merged-PR count (bots included), reverting-PR count and revert share (merges whose title names "+ "a revert, over all merges), median PR open-to-merge (bots and drafts excluded; ""coarse: draft and ready time fused), median time-to-green, billable minutes + estimated cost ""(with the merge-queue slice of billable minutes broken out), and merge-queue landing stats ""(queue-landed merges, first-gate-to-merge median and p90, gate attempts, failed-gate share): "diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.pyindex b1cbcdacb03b..485ebcbc36c4 100644--- a/products/engineering_analytics/backend/tests/_github_fixtures.py+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py@@ -249,11 +249,12 @@ def _pr_row(full_name: str = "PostHog/posthog",default_branch: str = "",labels: tuple[str, ...] = (),+ title: str | None = None,) -> dict[str, Any]:return {"id": 1000 + number,"number": number,- "title": f"PR {number}",+ "title": title if title is not None else f"PR {number}","state": state,"draft": draft,"created_at": created_at,diff --git a/products/engineering_analytics/backend/tests/test_logic_workflows.py b/products/engineering_analytics/backend/tests/test_logic_workflows.pyindex 913642650977..1f03c12ec425 100644--- a/products/engineering_analytics/backend/tests/test_logic_workflows.py+++ b/products/engineering_analytics/backend/tests/test_logic_workflows.py@@ -326,6 +326,41 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):_pr_row(81, "dependabot[bot]", "closed", 0, _ago(4), merged_at=_ago(3), head_sha="sha81"),# merged before the window (and before its prev twin): in neither count_pr_row(82, "alice", "closed", 0, _ago(120), merged_at=_ago(90), head_sha="sha82"),+ # the two revert title shapes, merged in window: both count as reverting merges. Each+ # opens 8 days before it merges, like PR 80, so the open-to-merge median stays put.+ _pr_row(+ 83,+ "alice",+ "closed",+ 0,+ _ago(10),+ merged_at=_ago(2),+ head_sha="sha83",+ title='Revert "PR 80 (#80)"',+ ),+ _pr_row(+ 84,+ "bob",+ "closed",+ 0,+ _ago(10),+ merged_at=_ago(2),+ head_sha="sha84",+ title="revert(ci)!: drop the gate",+ ),+ # mentions a revert without being one: an unanchored match would count it+ _pr_row(+ 85,+ "bob",+ "closed",+ 0,+ _ago(10),+ merged_at=_ago(2),+ head_sha="sha85",+ title="fix: Revert-safe cache",+ ),+ # a revert merged in the previous window, so the prev twin carries a share too+ _pr_row(86, "bob", "closed", 0, _ago(50), merged_at=_ago(45), head_sha="sha86", title="revert: PR 70"),],)self._create_table(@@ -359,8 +394,12 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):with mock.patch.object(Database, "create_for", wraps=Database.create_for) as build_catalog:overview = api.get_repo_overview(team=self.team, include_series=False)assert build_catalog.call_count == 1 # one catalog for every query of the request- assert overview.merged_pr_count == 2 # 80 and 81; 82 merged long before the window- assert overview.merged_pr_count_prev == 0+ assert overview.merged_pr_count == 5 # 80, 81, 83, 84, 85; 82 merged long before the window+ assert overview.merged_pr_count_prev == 1 # 86+ assert overview.reverting_pr_count == 2 # 83 and 84; 85 only mentions a revert+ assert overview.revert_share == pytest.approx(2 / 5)+ assert overview.reverting_pr_count_prev == 1+ assert overview.revert_share_prev == pytest.approx(1.0)assert overview.median_open_to_merge_seconds == pytest.approx(8 * 86400) # bot PR 81 excludedassert overview.run_count == 11assert overview.success_rate == pytest.approx(4 / 7) # 4 successes of 7 conclusive runs@@ -368,7 +407,7 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):assert overview.billable_minutes == pytest.approx(7.0) # two 120s jobs and one 180s Depot CI attempt# 4 min x $0.004 x 2 (4-core) on GitHub Actions, plus 3 min x $0.004 on the default Depot CI sandboxassert overview.estimated_cost_usd == pytest.approx(0.044)- assert overview.cost_per_merge_usd == pytest.approx(0.022) # the window's cost over its 2 merges+ assert overview.cost_per_merge_usd == pytest.approx(0.044 / 5) # the window's cost over its 5 mergesassert overview.merge_queue_billable_minutes == pytest.approx(2.0) # only the trunk-merge/** jobassert overview.merge_queue_billable_minutes_prev is None # no prev-window jobs, like billable_minutes_prevassert overview.depot_ci_billable_minutes == pytest.approx(3.0) # only the Depot CI attempt@@ -379,9 +418,10 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):assert overview.success_rate_series == []assert overview.open_to_merge_series == []assert overview.ready_to_merge_series == []+ assert overview.revert_share_series == []assert overview.cost_series_granularity == "day" # the grain the series would have used# No gate runs synced: the gate legs read unobserved, never zero.- assert overview.delivery_pipeline.merged_pr_count == 1+ assert overview.delivery_pipeline.merged_pr_count == 4 # the human merges: 80, 83, 84, 85assert all(leg.median_seconds is None for leg in overview.delivery_pipeline.stages)with_series = api.get_repo_overview(team=self.team)@@ -390,6 +430,17 @@ class TestWorkflowEndpointsWarehouse(_EndpointsWarehouseMixin, BaseTest):bucket.success_rate for bucket in with_series.success_rate_series if bucket.success_rate is not None]assert observed_pass_rates == [pytest.approx(4 / 7)]+ # Oldest first: the bot's merge day (0 of 1), then the day 80 and the reverts landed (2 of 4).+ observed_revert_buckets = [+ (bucket.merged_pr_count, bucket.reverting_pr_count, bucket.revert_share)+ for bucket in with_series.revert_share_series+ if bucket.merged_pr_count > 0+ ]+ assert observed_revert_buckets == [(1, 0, 0.0), (4, 2, 0.5)]+ # A day with no merges is a gap, never a false 0% share.+ assert all(+ bucket.revert_share is None for bucket in with_series.revert_share_series if bucket.merged_pr_count == 0+ )def test_time_to_green_measures_push_rounds_not_runs(self) -> None:# A per-run median would read this fixture as ~5 min. The round definition asks a differentdiff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.pyindex 676910a44d23..701e89336f75 100644--- a/products/engineering_analytics/backend/tests/test_presentation.py+++ b/products/engineering_analytics/backend/tests/test_presentation.py@@ -136,6 +136,10 @@ def _repo_overview() -> contracts.RepoOverview:rerun_cycles_prev=1,merged_pr_count=42,merged_pr_count_prev=40,+ reverting_pr_count=2,+ reverting_pr_count_prev=1,+ revert_share=2 / 42,+ revert_share_prev=1 / 40,median_open_to_merge_seconds=3600.0,median_open_to_merge_seconds_prev=4000.0,median_ready_to_merge_seconds=3000.0,@@ -185,6 +189,8 @@ def _repo_overview() -> contracts.RepoOverview:open_to_merge_series_granularity="day",ready_to_merge_series=[],ready_to_merge_series_granularity="day",+ revert_share_series=[],+ revert_share_series_granularity="day",delivery_pipeline=contracts.DeliveryPipeline(merged_pr_count=38,stages=[@@ -410,6 +416,8 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):data = response.json()assert data["merged_pr_count"] == 42assert data["merged_pr_count_prev"] == 40+ assert data["reverting_pr_count"] == 2+ assert data["revert_share"] == 2 / 42assert data["merge_queue_billable_minutes"] == 30.0 # the digest's queue row reads this keyassert data["depot_ci_billable_minutes"] == 20.0 # the digest's Depot CI row reads this keyassert data["merge_queue_merged_pr_count"] == 38diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.tsindex 4e1afece0056..f5f2b7873918 100644--- a/products/engineering_analytics/frontend/generated/api.schemas.ts+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts@@ -1935,6 +1935,20 @@ export interface ReadyToMergeBucketApi {p50_seconds: number | null}+export interface RevertShareBucketApi {+ /** Bucket start, aligned to revert_share_series_granularity (top of hour, midnight, or Monday). Keyed on the revert's own merge time. */+ bucket_start: string+ /** PRs merged in this bucket, all authors and bots included. */+ merged_pr_count: number+ /** Of those, PRs whose title names a revert: GitHub's 'Revert "..."' or a conventional-commit 'revert: ...' / 'revert(scope): ...' title. */+ reverting_pr_count: number+ /**+ * reverting_pr_count divided by merged_pr_count. Null when nothing merged in the bucket.+ * @nullable+ */+ revert_share: number | null+}+export interface RepoOverviewApi {/** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced or include_series=false. */cost_series: CostPerMergeBucketApi[]@@ -1948,6 +1962,8 @@ export interface RepoOverviewApi {delivery_pipeline: DeliveryPipelineApi/** Median cycle time (p50 per-PR ready_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by ready_to_merge_series_granularity. Empty buckets carry null; the whole series is empty when the issue-events table isn't synced or include_series=false, so fall back to open_to_merge_series. */ready_to_merge_series: ReadyToMergeBucketApi[]+ /** Reverting merges over all merges (all authors, bots included) per bucket across the window, oldest first, zero-filled, bucketed by revert_share_series_granularity. Empty buckets carry a null share; the whole series is empty when include_series=false. */+ revert_share_series: RevertShareBucketApi[]/** Workflow runs started in the window, all branches and workflows. */run_count: number/** Same count over the equal-length window immediately before date_from: the delta baseline. */@@ -1970,6 +1986,20 @@ export interface RepoOverviewApi {merged_pr_count: number/** Merged-PR count over the previous window. */merged_pr_count_prev: number+ /** PRs merged in the window whose title names a revert: GitHub's 'Revert "..."' or a conventional-commit 'revert: ...' / 'revert(scope): ...' title. Counts the revert when it merges, not the change it undid, which may have merged in an earlier window. Same population as merged_pr_count. */+ reverting_pr_count: number+ /** Reverting-PR count over the previous window. */+ reverting_pr_count_prev: number+ /**+ * reverting_pr_count divided by merged_pr_count: the share of merges that undid an earlier merge. The guardrail to watch when review requirements are loosened. Null when nothing merged.+ * @nullable+ */+ revert_share: number | null+ /**+ * The same share over the previous window. Null when nothing merged.+ * @nullable+ */+ revert_share_prev: number | null/*** Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.* @nullable@@ -2160,6 +2190,8 @@ export interface RepoOverviewApi {open_to_merge_series_granularity: string/** Bucket width of the ready_to_merge_series trend: 'hour', 'day', or 'week'. */ready_to_merge_series_granularity: string+ /** Bucket width of the revert_share_series trend: 'hour', 'day', or 'week'. */+ revert_share_series_granularity: string}export interface WorkflowRunActivityPointApi {diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.tsindex 0a728f7b3267..01a7129314fa 100644--- a/products/engineering_analytics/frontend/generated/api.ts+++ b/products/engineering_analytics/frontend/generated/api.ts@@ -957,7 +957,7 @@ export const getEngineeringAnalyticsRepoOverviewUrl = (}/**- * Repo-level headline aggregates over a window (default -30d): run count, conclusive-run success rate, re-run cycles, merged-PR count (bots included), median PR open-to-merge (bots and drafts excluded; coarse: draft and ready time fused), median time-to-green, billable minutes + estimated cost (with the merge-queue slice of billable minutes broken out), and merge-queue landing stats (queue-landed merges, first-gate-to-merge median and p90, gate attempts, failed-gate share): each with its equal-length previous-window twin so a caller can render honest deltas. Also carries the detected default branch and its completed-run history series (skippable via include_series=false). Cost figures are null until the job-level source is synced.+ * Repo-level headline aggregates over a window (default -30d): run count, conclusive-run success rate, re-run cycles, merged-PR count (bots included), reverting-PR count and revert share (merges whose title names a revert, over all merges), median PR open-to-merge (bots and drafts excluded; coarse: draft and ready time fused), median time-to-green, billable minutes + estimated cost (with the merge-queue slice of billable minutes broken out), and merge-queue landing stats (queue-landed merges, first-gate-to-merge median and p90, gate attempts, failed-gate share): each with its equal-length previous-window twin so a caller can render honest deltas. Also carries the detected default branch and its completed-run history series (skippable via include_series=false). Cost figures are null until the job-level source is synced.*/export const engineeringAnalyticsRepoOverview = async (projectId: string,diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsxindex aa8e7af44d0a..0a3c0530fbd0 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.stories.tsx@@ -29,6 +29,10 @@ const OVERVIEW: RepoOverviewApi = {rerun_cycles_prev: 30,merged_pr_count: 56,merged_pr_count_prev: 49,+ reverting_pr_count: 3,+ reverting_pr_count_prev: 1,+ revert_share: 3 / 56,+ revert_share_prev: 1 / 49,median_open_to_merge_seconds: 14 * 3600,median_open_to_merge_seconds_prev: 19 * 3600,median_ready_to_merge_seconds: 9 * 3600,@@ -79,6 +83,8 @@ const OVERVIEW: RepoOverviewApi = {open_to_merge_series_granularity: 'day',ready_to_merge_series: [],ready_to_merge_series_granularity: 'day',+ revert_share_series: [],+ revert_share_series_granularity: 'day',delivery_pipeline: {merged_pr_count: 52,stages: [diff --git a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsxindex 22bdb7191139..1e6124e71366 100644--- a/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx+++ b/products/engineering_analytics/frontend/scenes/RepoOverviewScene.tsx@@ -138,6 +138,19 @@ export function RepoOverviewScene(): JSX.Element {}tooltip="Estimated CI cost of every run in the window, divided by the pull requests merged in it. Includes runs on the default branch and on pull requests that never merged. Per-workflow spend is in Workflows below."/>++ <WindowComparisonCard+ title="Reverts among merged PRs"+ value={overview?.revert_share}+ previousValue={overview?.revert_share_prev}+ formatValue={(value) => percent(value, 1)}+ goodWhenDown+ deltaUnit="pt"+ deltaPrecision={1}+ loading={overviewPending}+ tooltip="Pull requests merged in the window whose title says they revert another change, as a share of all merged pull requests. Counts the revert when it merges, not the change it undid. Bots included."+ emptyText="Nothing merged in the window."+ /></div></div></Section>diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 55efb514397b..23072a79705b 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -96754,6 +96754,20 @@ export namespace Schemas {p50_seconds: number | null;}+ export interface RevertShareBucket {+ /** Bucket start, aligned to revert_share_series_granularity (top of hour, midnight, or Monday). Keyed on the revert's own merge time. */+ bucket_start: string;+ /** PRs merged in this bucket, all authors and bots included. */+ merged_pr_count: number;+ /** Of those, PRs whose title names a revert: GitHub's 'Revert "..."' or a conventional-commit 'revert: ...' / 'revert(scope): ...' title. */+ reverting_pr_count: number;+ /**+ * reverting_pr_count divided by merged_pr_count. Null when nothing merged in the bucket.+ * @nullable+ */+ revert_share: number | null;+ }+export interface RepoOverview {/** CI cost per merged PR across the window, oldest first, zero-filled, bucketed by cost_series_granularity. Empty when the job-level source isn't synced or include_series=false. */cost_series: CostPerMergeBucket[];@@ -96767,6 +96781,8 @@ export namespace Schemas {delivery_pipeline: DeliveryPipeline;/** Median cycle time (p50 per-PR ready_to_merge_seconds, bots/drafts excluded) per bucket across the window, oldest first, bucketed by ready_to_merge_series_granularity. Empty buckets carry null; the whole series is empty when the issue-events table isn't synced or include_series=false, so fall back to open_to_merge_series. */ready_to_merge_series: ReadyToMergeBucket[];+ /** Reverting merges over all merges (all authors, bots included) per bucket across the window, oldest first, zero-filled, bucketed by revert_share_series_granularity. Empty buckets carry a null share; the whole series is empty when include_series=false. */+ revert_share_series: RevertShareBucket[];/** Workflow runs started in the window, all branches and workflows. */run_count: number;/** Same count over the equal-length window immediately before date_from: the delta baseline. */@@ -96789,6 +96805,20 @@ export namespace Schemas {merged_pr_count: number;/** Merged-PR count over the previous window. */merged_pr_count_prev: number;+ /** PRs merged in the window whose title names a revert: GitHub's 'Revert "..."' or a conventional-commit 'revert: ...' / 'revert(scope): ...' title. Counts the revert when it merges, not the change it undid, which may have merged in an earlier window. Same population as merged_pr_count. */+ reverting_pr_count: number;+ /** Reverting-PR count over the previous window. */+ reverting_pr_count_prev: number;+ /**+ * reverting_pr_count divided by merged_pr_count: the share of merges that undid an earlier merge. The guardrail to watch when review requirements are loosened. Null when nothing merged.+ * @nullable+ */+ revert_share: number | null;+ /**+ * The same share over the previous window. Null when nothing merged.+ * @nullable+ */+ revert_share_prev: number | null;/*** Median merged_at - created_at over PRs merged in the window, bots and drafts excluded. Coarse by design: draft and ready-for-review time are fused. Null when nothing merged.* @nullable@@ -96979,6 +97009,8 @@ export namespace Schemas {open_to_merge_series_granularity: string;/** Bucket width of the ready_to_merge_series trend: 'hour', 'day', or 'week'. */ready_to_merge_series_granularity: string;+ /** Bucket width of the revert_share_series trend: 'hour', 'day', or 'week'. */+ revert_share_series_granularity: string;}export interface RepoRoutingRule {