Skip to content

: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.

feat(engineering-analytics): compare an author's merge time with their team (#102159)

Julian Bezaef23fd23edf
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index 1682c9cb731f..ae8861d85679 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -32,6 +32,7 @@ from products.engineering_analytics.backend.facade.contracts import (
CISignalsConfig,
CITestRunner,
CurrentBranchHealth,
+ DeliveryComparison,
DeliverySummary,
DoraOverview,
FlakyTestList,
@@ -299,6 +300,35 @@ def get_delivery_summary(
)
+def get_delivery_comparison(
+ *,
+ team: Team,
+ author: str | None,
+ pr_number: int | None = None,
+ date_from: str | None = None,
+ date_to: str | None = None,
+ source_id: str | None = None,
+ repo: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> DeliveryComparison:
+ """An author's ready-to-merge medians next to their team's and the repository's. ``pr_number`` names a
+ pull request by the author, and a team that this pull request asked to review wins the team choice."""
+ author = (author or "").strip()
+ if not author:
+ raise ValueError("author is required")
+ repo = (repo or "").strip() or None
+ # Pull request numbers restart in every repository, so a number alone names no pull request.
+ if pr_number is not None and repo is None:
+ raise ValueError("repo is required with pr_number")
+ return logic.build_delivery_comparison(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
+ author=author,
+ focus_pr=pr_number,
+ date_from=date_from,
+ date_to=date_to,
+ )
+
+
def get_pull_request_timelines(
*,
team: Team,
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index 7e6631f6415a..0e531b4a6791 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -19,6 +19,7 @@ from products.engineering_analytics.backend.logic.ci_signals_config import (
update_ci_signals_config as update_ci_signals_config,
)
from products.engineering_analytics.backend.logic.delivery import (
+ build_delivery_comparison as build_delivery_comparison,
build_delivery_summary as build_delivery_summary,
build_pull_request_timelines as build_pull_request_timelines,
)
diff --git a/products/engineering_analytics/backend/logic/delivery.py b/products/engineering_analytics/backend/logic/delivery.py
index de18428a0e8e..9b9066eb5dc2 100644
--- a/products/engineering_analytics/backend/logic/delivery.py
+++ b/products/engineering_analytics/backend/logic/delivery.py
@@ -1,11 +1,13 @@
-"""Delivery orchestration: a scope's delivery summary and its pull request timelines.
+"""Delivery orchestration: a scope's delivery summary, its pull request timelines, and an author's
+comparison with their team.
-Both reads take one scope (see ``delivery_scope``) and compare it with the repository. The author
-page is the first caller; a team page reads the same summary with a GitHub team, and a pull request
-page reads one timeline.
+The summary and the timelines take one scope (see ``delivery_scope``) and compare it with the
+repository. The author page is the first caller; a team page reads the same summary with a GitHub
+team, and a pull request page reads one timeline and the comparison.
"""
from products.engineering_analytics.backend.facade.contracts import (
+ DeliveryComparison,
DeliveryScopeKind,
DeliverySummary,
PullRequestTimelines,
@@ -13,6 +15,7 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.logic._shared import _DEFAULT_WINDOW, _parse_window
from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries.delivery_comparison import query_delivery_comparison
from products.engineering_analytics.backend.logic.queries.delivery_summary import query_delivery_summary
from products.engineering_analytics.backend.logic.queries.pull_request_timelines import query_pull_request_timelines
@@ -43,3 +46,17 @@ def build_pull_request_timelines(
window_to = None if single_pr else date_to
parsed_from, parsed_to = _parse_window(curated.team, window_from, window_to, default=_DEFAULT_WINDOW)
return query_pull_request_timelines(curated=curated, scope=scope, date_from=parsed_from, date_to=parsed_to)
+
+
+def build_delivery_comparison(
+ *,
+ curated: CuratedGitHubSource,
+ author: str,
+ focus_pr: int | None = None,
+ date_from: str | None = None,
+ date_to: str | None = None,
+) -> DeliveryComparison:
+ parsed_from, parsed_to = _parse_window(curated.team, date_from, date_to, default=_DEFAULT_WINDOW)
+ return query_delivery_comparison(
+ curated=curated, author=author, focus_pr=focus_pr, date_from=parsed_from, date_to=parsed_to
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/delivery_comparison.py b/products/engineering_analytics/backend/logic/queries/delivery_comparison.py
new file mode 100644
index 000000000000..c0abc0e32cad
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/delivery_comparison.py
@@ -0,0 +1,212 @@
+"""Curated query: an author's ready-to-merge medians next to their team's and the repository's.
+
+The merged pull requests come from the delivery summary's own read, so all three populations share one
+definition with the summary figures. The team population is the team's members' pull requests, which is
+what a github_team delivery scope reads too.
+"""
+
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import (
+ UNOWNED_TEAM,
+ DeliveryComparison,
+ DeliveryScopeKind,
+ ReadyToMergeMedians,
+ TeamReadyToMergeMedians,
+)
+from products.engineering_analytics.backend.logic.comparison_teams import TeamChoice, choose_comparison_teams
+from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ UNPAGED_SCAN_LIMIT,
+ run_started_floor_constant,
+)
+from products.engineering_analytics.backend.logic.queries.census_counts import query_census_counts
+from products.engineering_analytics.backend.logic.queries.delivery_summary import (
+ CI_LOOKBACK,
+ MergedPRFacts,
+ pull_request_ready_to_merge,
+ query_ready_to_merge_facts,
+ ready_to_merge_medians,
+)
+
+# The census runs daily, so a few days always find its latest run.
+_CENSUS_LOOKBACK = timedelta(days=3)
+# Below this many other authors who contribute a value, the median is one or two pull requests wearing a
+# team's label (SPEC §2). A noise floor, not a privacy floor: the population holds one value per merged pull
+# request, and each of those times already shows on its own pull request page.
+MIN_OTHER_TEAM_AUTHORS = 2
+
+# Every team the author is in, with all of its members.
+_AUTHOR_TEAMS_SELECT = f"""
+ SELECT team_slug, groupUniqArray(member_handle) AS members
+ FROM __MEMBERS_SOURCE__ AS m
+ WHERE team_slug IN (
+ SELECT team_slug FROM __MEMBERS_SOURCE__ AS mine WHERE mine.member_handle = {{author}}
+ )
+ GROUP BY team_slug
+ LIMIT {UNPAGED_SCAN_LIMIT}
+"""
+
+# Per team: the author's pull requests that asked it to review in the window.
+_WINDOW_REQUESTS_SELECT = f"""
+ SELECT team_slug, uniq(pr_number) AS prs
+ FROM __REQUESTS_SOURCE__ AS rr
+ WHERE team_slug IN {{teams}} AND requested_at >= {{date_from}} __REQUESTED_TO__
+ AND pr_number IN (SELECT number FROM __PR_SOURCE__ AS pr WHERE pr.author_handle = {{author}})
+ GROUP BY team_slug
+ LIMIT {UNPAGED_SCAN_LIMIT}
+"""
+
+# The teams the pull request in focus asked to review, when the author wrote it. A long-lived pull request
+# asked them before the window, so this read has no scan floor.
+_FOCUS_REQUESTS_SELECT = f"""
+ SELECT DISTINCT team_slug
+ FROM __REQUESTS_SOURCE__ AS rr
+ WHERE team_slug IN {{teams}} AND pr_number = {{focus_pr}}
+ AND pr_number IN (
+ SELECT number FROM __PR_SOURCE__ AS pr WHERE pr.number = {{focus_pr}} AND pr.author_handle = {{author}}
+ )
+ LIMIT {UNPAGED_SCAN_LIMIT}
+"""
+
+
+def _query_author_teams(curated: CuratedGitHubSource, *, author: str) -> dict[str, set[str]]:
+ members_source = curated.members_source()
+ if members_source is None:
+ return {}
+ response = curated.run(
+ _AUTHOR_TEAMS_SELECT.replace("__MEMBERS_SOURCE__", members_source),
+ query_type="engineering_analytics.delivery_comparison_teams",
+ placeholders={"author": ast.Constant(value=author)},
+ )
+ return {team: set(members) for team, members in response.results or [] if team}
+
+
+def _query_code_teams(curated: CuratedGitHubSource) -> set[str]:
+ now = datetime.now(tz=UTC)
+ census_from = now - _CENSUS_LOOKBACK
+ code_teams = set(query_census_counts(curated=curated, date_from=census_from, scan_from=census_from, date_to=now))
+ code_teams.discard(UNOWNED_TEAM)
+ return code_teams
+
+
+def _choose_teams(
+ curated: CuratedGitHubSource,
+ *,
+ author: str,
+ author_teams: set[str],
+ focus_pr: int | None,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> TeamChoice:
+ code_teams = _query_code_teams(curated) if author_teams else set()
+ window_source = curated.team_review_requests_source(created_floor=True)
+ if not author_teams or window_source is None:
+ return choose_comparison_teams(
+ author_teams=author_teams, code_teams=code_teams, requested_prs={}, focus_requested=set()
+ )
+ teams = ast.Constant(value=sorted(author_teams))
+ placeholders: dict[str, ast.Expr] = {
+ "author": ast.Constant(value=author),
+ "teams": teams,
+ "date_from": ast.Constant(value=date_from),
+ "event_created_floor": run_started_floor_constant(date_from - CI_LOOKBACK),
+ }
+ requested_to = ""
+ if date_to is not None:
+ placeholders["date_to"] = ast.Constant(value=date_to)
+ requested_to = "AND requested_at <= {date_to}"
+ window = curated.run(
+ _WINDOW_REQUESTS_SELECT.replace("__REQUESTS_SOURCE__", window_source)
+ .replace("__PR_SOURCE__", curated.pr_source())
+ .replace("__REQUESTED_TO__", requested_to),
+ query_type="engineering_analytics.delivery_comparison_requests",
+ placeholders=placeholders,
+ )
+ focus_requested: set[str] = set()
+ focus_source = curated.team_review_requests_source()
+ if focus_pr is not None and focus_source is not None:
+ focus = curated.run(
+ _FOCUS_REQUESTS_SELECT.replace("__REQUESTS_SOURCE__", focus_source).replace(
+ "__PR_SOURCE__", curated.pr_source()
+ ),
+ query_type="engineering_analytics.delivery_comparison_focus_requests",
+ placeholders={
+ "teams": teams,
+ "focus_pr": ast.Constant(value=focus_pr),
+ "author": ast.Constant(value=author),
+ },
+ )
+ focus_requested = {team for (team,) in focus.results or []}
+ return choose_comparison_teams(
+ author_teams=author_teams,
+ code_teams=code_teams,
+ requested_prs={team: int(prs) for team, prs in window.results or []},
+ focus_requested=focus_requested,
+ )
+
+
+def _team_medians(facts: list[MergedPRFacts], *, members: set[str], author: str) -> ReadyToMergeMedians | None:
+ team_facts = [fact for fact in facts if fact.author in members]
+
+ def enough_others(contributing: list[MergedPRFacts]) -> bool:
+ return len({fact.author for fact in contributing} - {author}) >= MIN_OTHER_TEAM_AUTHORS
+
+ # A pull request without an observed ready time adds nothing to the median, so it does not count.
+ if not enough_others([fact for fact in team_facts if fact.ready_to_merge_seconds is not None]):
+ return None
+ medians = ready_to_merge_medians(team_facts)
+ if enough_others([fact for fact in team_facts if fact.ready_at is not None and fact.first_approval_at is not None]):
+ return medians
+ return replace(
+ medians,
+ ready_to_first_approval_seconds=None,
+ first_approval_to_merge_seconds=None,
+ before_first_approval_share=None,
+ )
+
+
+def query_delivery_comparison(
+ *,
+ curated: CuratedGitHubSource,
+ author: str,
+ focus_pr: int | None,
+ date_from: datetime,
+ date_to: datetime | None,
+) -> DeliveryComparison:
+ author_teams = _query_author_teams(curated, author=author)
+ choice = _choose_teams(
+ curated,
+ author=author,
+ author_teams=set(author_teams),
+ focus_pr=focus_pr,
+ date_from=date_from,
+ date_to=date_to,
+ )
+
+ scope = DeliveryScope(kind=DeliveryScopeKind.AUTHOR, author=author)
+ facts = query_ready_to_merge_facts(curated, scope=scope, date_from=date_from, date_to=date_to)
+ focus_fact = next((fact for fact in facts if fact.in_scope and fact.number == focus_pr), None)
+ # The pull request in focus is what the baselines are compared with, so it stays out of them.
+ baseline = [fact for fact in facts if fact is not focus_fact]
+ return DeliveryComparison(
+ author=author,
+ has_membership_data=curated.members_source() is not None,
+ review_data_available=curated.reviews_source() is not None,
+ ready_data_available=curated.ready_to_merge_sql().observable,
+ team_basis=choice.basis,
+ author_medians=ready_to_merge_medians([fact for fact in baseline if fact.in_scope]),
+ teams=[
+ TeamReadyToMergeMedians(
+ github_team=team,
+ medians=_team_medians(baseline, members=author_teams[team], author=author),
+ )
+ for team in choice.teams
+ ],
+ repo_medians=ready_to_merge_medians(baseline),
+ pull_request=pull_request_ready_to_merge(focus_fact) if focus_fact else None,
+ )
diff --git a/products/engineering_analytics/backend/presentation/serializers/delivery.py b/products/engineering_analytics/backend/presentation/serializers/delivery.py
index 44ea6a769866..39756b7a4c70 100644
--- a/products/engineering_analytics/backend/presentation/serializers/delivery.py
+++ b/products/engineering_analytics/backend/presentation/serializers/delivery.py
@@ -1,17 +1,22 @@
-"""Payloads for the delivery reads: a scope's delivery summary and its pull request timelines."""
+"""Payloads for the delivery reads: a scope's delivery summary, its pull request timelines, and an author's
+comparison with their team."""
from rest_framework_dataclasses.serializers import DataclassSerializer
from products.engineering_analytics.backend.facade.contracts import (
+ DeliveryComparison,
DeliveryLeadTime,
DeliverySummary,
DurationDistribution,
PRTimeline,
PRTimelinePush,
PRTimelineSegment,
+ PullRequestReadyToMerge,
PullRequestTimelines,
+ ReadyToMergeMedians,
ScopeRepoDistribution,
ScopeRepoFigure,
+ TeamReadyToMergeMedians,
)
from products.engineering_analytics.backend.presentation.serializers._shared import RepoRefSerializer
@@ -267,3 +272,111 @@ class PullRequestTimelinesSerializer(DataclassSerializer):
"truncated": {"help_text": "True when more PRs matched than the limit."},
"limit": {"help_text": "The maximum number of PRs returned."},
}
+
+
+class ReadyToMergeMediansSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = ReadyToMergeMedians
+ extra_kwargs = {
+ "merged_pr_count": {"help_text": "Pull requests merged in the window, bots and drafts excluded."},
+ "ready_to_merge_seconds": {
+ "help_text": "Median seconds from the last ready_for_review to merge. Null when nothing was measured.",
+ "allow_null": True,
+ },
+ "p90_ready_to_merge_seconds": {
+ "help_text": "90th percentile of the ready-to-merge seconds.",
+ "allow_null": True,
+ },
+ "ready_to_first_approval_seconds": {
+ "help_text": "Median seconds from ready to the first approval, over the pull requests with an "
+ "approval. Null when nothing was measured.",
+ "allow_null": True,
+ },
+ "first_approval_to_merge_seconds": {
+ "help_text": "Median seconds from the first approval to merge. The two approval medians do not add "
+ "up to the ready-to-merge median.",
+ "allow_null": True,
+ },
+ "before_first_approval_share": {
+ "help_text": "Share (0 to 1) of all ready-to-merge hours spent before the first approval, summed "
+ "over the pull requests, so long pull requests weigh more.",
+ "allow_null": True,
+ },
+ }
+
+
+class PullRequestReadyToMergeSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PullRequestReadyToMerge
+ extra_kwargs = {
+ "number": {"help_text": "The pull request number."},
+ "ready_to_merge_seconds": {
+ "help_text": "Seconds from the last ready_for_review to merge. Null when not observed.",
+ "allow_null": True,
+ },
+ "ready_to_first_approval_seconds": {
+ "help_text": "Seconds from ready to the first approval. Null without an approval or review data.",
+ "allow_null": True,
+ },
+ "first_approval_to_merge_seconds": {
+ "help_text": "Seconds from the first approval to merge. Null without an approval or review data.",
+ "allow_null": True,
+ },
+ "before_first_approval_share": {
+ "help_text": "Share (0 to 1) of the ready-to-merge time spent before the first approval.",
+ "allow_null": True,
+ },
+ }
+
+
+class TeamReadyToMergeMediansSerializer(DataclassSerializer):
+ medians = ReadyToMergeMediansSerializer(
+ allow_null=True,
+ help_text="Over the pull requests by the team's members, the same population as a github_team scope, "
+ "without the pr_number pull request. Null when fewer than three other authors contribute a ready time, "
+ "because the author could read a teammate's value back from the median. The approval medians are null "
+ "on the same terms for approvals.",
+ )
+
+ class Meta:
+ dataclass = TeamReadyToMergeMedians
+ extra_kwargs = {"github_team": {"help_text": "The GitHub team slug."}}
+
+
+class DeliveryComparisonSerializer(DataclassSerializer):
+ author_medians = ReadyToMergeMediansSerializer(
+ help_text="Over the author's pull requests, without the pr_number pull request."
+ )
+ teams = TeamReadyToMergeMediansSerializer(
+ many=True, help_text="The author's teams that team_basis picked, sorted by slug. Empty for no_team."
+ )
+ repo_medians = ReadyToMergeMediansSerializer(
+ help_text="Over every non-bot pull request in the repository, the author's included and the pr_number "
+ "pull request left out."
+ )
+ pull_request = PullRequestReadyToMergeSerializer(
+ allow_null=True,
+ help_text="The pr_number pull request measured the same way, when it merged in the window. Null otherwise.",
+ )
+
+ class Meta:
+ dataclass = DeliveryComparison
+ extra_kwargs = {
+ "author": {"help_text": "The GitHub login the comparison is for."},
+ "has_membership_data": {
+ "help_text": "True when the team membership table is synced. Without it, team_basis is no_team."
+ },
+ "review_data_available": {
+ "help_text": "False when reviews aren't synced: the approval medians are then null."
+ },
+ "ready_data_available": {
+ "help_text": "False when issue events aren't synced: the ready-to-merge medians are then null."
+ },
+ "team_basis": {
+ "help_text": "How the teams were picked from the author's teams that own code: pull_request (the "
+ "pr_number asked the team to review); review_requests (the team the author's pull "
+ "requests asked to review most often in the window, with ties kept); only_team (the author is in "
+ "one team); all_teams (no review request points at one team); no_team (no team, or no membership "
+ "data)."
+ },
+ }
diff --git a/products/engineering_analytics/backend/presentation/views/delivery.py b/products/engineering_analytics/backend/presentation/views/delivery.py
index 02d187263fc3..f6f6c342d35b 100644
--- a/products/engineering_analytics/backend/presentation/views/delivery.py
+++ b/products/engineering_analytics/backend/presentation/views/delivery.py
@@ -1,4 +1,5 @@
-"""Delivery reads: a scope's delivery summary and its pull request timelines."""
+"""Delivery reads: a scope's delivery summary, its pull request timelines, and an author's comparison with
+their team."""
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
@@ -8,6 +9,7 @@ from rest_framework.response import Response
from products.engineering_analytics.backend.facade import api
from products.engineering_analytics.backend.presentation.serializers.delivery import (
+ DeliveryComparisonSerializer,
DeliverySummarySerializer,
PullRequestTimelinesSerializer,
)
@@ -55,8 +57,26 @@ _REPO = OpenApiParameter(
)
+_COMPARISON_AUTHOR = OpenApiParameter(
+ name="author",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="GitHub login of the author to compare with their team and the repository.",
+)
+
+_FOCUS_PR_NUMBER = OpenApiParameter(
+ name="pr_number",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="A pull request by the author. Needs repo. A team of the author's that this pull request asked to "
+ "review is the team to compare with, and the pull request stays out of the medians.",
+)
+
+
class DeliveryActionsMixin(EngineeringAnalyticsViewSetBase):
- READ_ACTIONS = ["delivery_summary", "pull_request_timelines"]
+ READ_ACTIONS = ["delivery_summary", "delivery_comparison", "pull_request_timelines"]
@extend_schema(
operation_id="engineering_analytics_delivery_summary",
@@ -89,6 +109,38 @@ class DeliveryActionsMixin(EngineeringAnalyticsViewSetBase):
return _bad_request(exc, fallback="Invalid scope, date, or source_id")
return Response(DeliverySummarySerializer(instance=summary).data)
+ @extend_schema(
+ operation_id="engineering_analytics_delivery_comparison",
+ parameters=[_COMPARISON_AUTHOR, _FOCUS_PR_NUMBER, _DATE_FROM, _DATE_TO, _SOURCE_ID, _REPO],
+ responses={
+ 200: DeliveryComparisonSerializer,
+ 400: OpenApiResponse(description="Missing author, or invalid pr_number, date or source_id."),
+ },
+ description=(
+ "One author's median ready to merged time, split at the first approval, next to the same medians for "
+ "the author's own team and for the whole repository, over pull requests merged in the window "
+ "(date_from default -30d). The team is picked from the author's GitHub teams that own code: a team "
+ "that pr_number asked to review, else the team the author's pull requests asked to review most often, "
+ "else every team. Bots and drafts are excluded."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def delivery_comparison(self, request: Request, **kwargs) -> Response:
+ try:
+ comparison = api.get_delivery_comparison(
+ team=self.team,
+ author=request.query_params.get("author") or None,
+ pr_number=_optional_int_param(request, "pr_number"),
+ date_from=request.query_params.get("date_from") or None,
+ date_to=request.query_params.get("date_to") or None,
+ source_id=request.query_params.get("source_id") or None,
+ repo=request.query_params.get("repo") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Invalid author, pull request, date, or source_id")
+ return Response(DeliveryComparisonSerializer(instance=comparison).data)
+
@extend_schema(
operation_id="engineering_analytics_pull_request_timelines",
parameters=[_AUTHOR, _GITHUB_TEAM, _PR_NUMBER, _REPO, _DATE_FROM, _DATE_TO, _SOURCE_ID],
diff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.py
index 5abdc676e6c1..a4b0925609d9 100644
--- a/products/engineering_analytics/backend/tests/test_delivery.py
+++ b/products/engineering_analytics/backend/tests/test_delivery.py
@@ -1,6 +1,6 @@
from datetime import UTC, datetime, timedelta
-from posthog.test.base import APIBaseTest
+from posthog.test.base import APIBaseTest, _create_event, flush_persons_and_events
from django.test import SimpleTestCase
@@ -13,6 +13,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PRTimelineSegmentKind as Kind,
ScopeRepoFigure,
)
+from products.engineering_analytics.backend.logic.census import CENSUS_EVENT
from products.engineering_analytics.backend.logic.comparison_teams import choose_comparison_teams
from products.engineering_analytics.backend.logic.delivery_scope import DeliveryScope
from products.engineering_analytics.backend.logic.pr_timeline import (
@@ -24,6 +25,7 @@ from products.engineering_analytics.backend.logic.pr_timeline import (
RunAttempt,
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries.delivery_comparison import query_delivery_comparison
from products.engineering_analytics.backend.logic.queries.delivery_summary import (
CI_LOOKBACK,
DeliverySummaryAggregator,
@@ -46,6 +48,7 @@ from products.engineering_analytics.backend.tests._github_fixtures import (
_pr_row,
_run_row,
_status_row,
+ create_github_source,
)
from products.engineering_analytics.backend.tests._logic_helpers import (
_ago,
@@ -584,6 +587,135 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
assert old_open is None or old_open.started_at == date_from - CI_LOOKBACK
+_ISSUE_EVENTS_WITHOUT_TEAM_REQUESTS = {
+ column: types for column, types in ISSUE_EVENTS_COLUMNS.items() if column != "requested_team"
+}
+
+
+def _team_request_row(event_id: int, pr_number: int, team_slug: str, created_at: str) -> dict:
+ return {
+ **_issue_event_row(event_id, "review_requested", pr_number, created_at, login="assigner[bot]"),
+ "requested_team": f'{{"slug": "{team_slug}"}}',
+ }
+
+
+class TestDeliveryComparisonOnWarehouse(_WarehouseMixin):
+ def _seed(self, *, with_team_requests: bool) -> None:
+ # The census is keyed by repository, so the source has to name one.
+ self._github_source = create_github_source(self.team, repository="PostHog/posthog")
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(21, "alice", "closed", 0, _ago(3), merged_at=_ago(1)),
+ _pr_row(27, "alice", "closed", 0, _ago(3), merged_at=_ago(2)),
+ _pr_row(23, "alice", "closed", 0, _ago(2), merged_at=_ago(1)),
+ _pr_row(22, "bob", "closed", 0, _ago(4), merged_at=_ago(1)),
+ _pr_row(28, "carol", "closed", 0, _ago(4), merged_at=_ago(2)),
+ _pr_row(29, "dave", "closed", 0, _ago(4), merged_at=_ago(2)),
+ # Opened before the issue events start, so their ready times are unknown.
+ _pr_row(30, "erin", "closed", 0, _ago(12), merged_at=_ago(2)),
+ _pr_row(31, "gina", "closed", 0, _ago(12), merged_at=_ago(2)),
+ _pr_row(32, "hank", "closed", 0, _ago(12), merged_at=_ago(2)),
+ ],
+ )
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
+ # Alice is in two teams that own code and in an approver group that owns none. The two teams sit on
+ # either side of MIN_OTHER_TEAM_AUTHORS: team-replay has exactly as many other authors with a ready
+ # time as the floor asks for, team-ingestion one fewer, so its median stays hidden.
+ self._create_table(
+ "github_team_members",
+ TEAM_MEMBERS_COLUMNS,
+ [
+ _member_row(1, "alice", "team-replay"),
+ _member_row(2, "alice", "team-ingestion"),
+ _member_row(3, "alice", "client-libraries-approvers"),
+ _member_row(4, "bob", "team-replay"),
+ _member_row(5, "carol", "team-ingestion"),
+ _member_row(6, "dave", "team-replay"),
+ _member_row(7, "erin", "team-replay"),
+ _member_row(8, "gina", "team-ingestion"),
+ _member_row(9, "hank", "team-ingestion"),
+ ],
+ )
+ if with_team_requests:
+ # Other authors' pull requests ask team-ingestion more often, and must not count for alice.
+ self._create_table(
+ "github_issue_events",
+ ISSUE_EVENTS_COLUMNS,
+ [
+ _issue_event_row(9, "labeled", 21, _ago(10)),
+ _team_request_row(1, 21, "team-replay", _ago(2)),
+ _team_request_row(2, 27, "team-replay", _ago(3)),
+ _team_request_row(3, 23, "team-ingestion", _ago(1)),
+ _team_request_row(4, 22, "team-ingestion", _ago(3)),
+ _team_request_row(5, 28, "team-ingestion", _ago(3)),
+ ],
+ )
+ else:
+ self._create_table(
+ "github_issue_events",
+ _ISSUE_EVENTS_WITHOUT_TEAM_REQUESTS,
+ [_issue_event_row(1, "labeled", 21, _ago(10)), _issue_event_row(2, "labeled", 21, _ago(0))],
+ )
+ for owner_team in ("team-replay", "team-ingestion"):
+ _create_event(
+ event=CENSUS_EVENT,
+ team=self.team,
+ distinct_id="census",
+ properties={"repository": "PostHog/posthog", "owner_team": owner_team, "test_file_count": 10},
+ timestamp=datetime.now(tz=UTC) - timedelta(days=1),
+ )
+ flush_persons_and_events()
+
+ @parameterized.expand(
+ [
+ ("the_most_requested_team", True, None, Basis.REVIEW_REQUESTS, {"team-replay": 6}, (3, 9), None),
+ ("the_team_the_focus_pr_asked", True, 23, Basis.PULL_REQUEST, {"team-ingestion": None}, (2, 8), 86400),
+ (
+ "every_code_team_without_requests",
+ False,
+ None,
+ Basis.ALL_TEAMS,
+ {"team-ingestion": None, "team-replay": 6},
+ (3, 9),
+ None,
+ ),
+ ]
+ )
+ def test_compares_the_author_with_their_team(
+ self,
+ _name: str,
+ with_team_requests: bool,
+ focus_pr: int | None,
+ basis: Basis,
+ team_merged_counts: dict[str, int | None],
+ author_and_repo_counts: tuple[int, int],
+ focus_ready_seconds: int | None,
+ ) -> None:
+ self._seed(with_team_requests=with_team_requests)
+ curated = CuratedGitHubSource.for_team(self.team)
+
+ comparison = query_delivery_comparison(
+ curated=curated,
+ author="alice",
+ focus_pr=focus_pr,
+ date_from=datetime.now(tz=UTC) - timedelta(days=7),
+ date_to=None,
+ )
+
+ assert comparison.team_basis == basis
+ assert {
+ team.github_team: team.medians.merged_pr_count if team.medians else None for team in comparison.teams
+ } == team_merged_counts
+ assert (
+ comparison.author_medians.merged_pr_count,
+ comparison.repo_medians.merged_pr_count,
+ ) == author_and_repo_counts
+ focus = comparison.pull_request
+ assert (focus.ready_to_merge_seconds if focus else None) == focus_ready_seconds
+
+
class TestDeliveryDeployWindow(_WarehouseMixin):
def _seed(self) -> None:
# Two merges inside the window, each heading its own production deploy: one deploy lands
@@ -657,12 +789,14 @@ class TestDeliveryDeployWindow(_WarehouseMixin):
class TestDeliveryEndpoints(APIBaseTest):
@parameterized.expand(
[
- ("delivery_summary", "exactly one of author, github_team"),
- ("pull_request_timelines", "exactly one of author, github_team"),
+ ("delivery_summary", "", "exactly one of author, github_team"),
+ ("pull_request_timelines", "", "exactly one of author, github_team"),
+ ("delivery_comparison", "", "author is required"),
+ ("delivery_comparison", "?author=alice&pr_number=21", "repo is required with pr_number"),
]
)
- def test_rejects_a_missing_scope(self, action: str, message: str) -> None:
- response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/{action}/")
+ def test_rejects_a_missing_scope(self, action: str, query: str, message: str) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/engineering_analytics/{action}/{query}")
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert message in response.json()["detail"]
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index b6ff964e9e80..f00b73b3bbec 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -201,6 +201,112 @@ export interface CurrentBranchHealthApi {
failing_workflow_names: string[]
}
+export interface ReadyToMergeMediansApi {
+ /** Pull requests merged in the window, bots and drafts excluded. */
+ merged_pr_count: number
+ /**
+ * Median seconds from the last ready_for_review to merge. Null when nothing was measured.
+ * @nullable
+ */
+ ready_to_merge_seconds: number | null
+ /**
+ * 90th percentile of the ready-to-merge seconds.
+ * @nullable
+ */
+ p90_ready_to_merge_seconds: number | null
+ /**
+ * Median seconds from ready to the first approval, over the pull requests with an approval. Null when nothing was measured.
+ * @nullable
+ */
+ ready_to_first_approval_seconds: number | null
+ /**
+ * Median seconds from the first approval to merge. The two approval medians do not add up to the ready-to-merge median.
+ * @nullable
+ */
+ first_approval_to_merge_seconds: number | null
+ /**
+ * Share (0 to 1) of all ready-to-merge hours spent before the first approval, summed over the pull requests, so long pull requests weigh more.
+ * @nullable
+ */
+ before_first_approval_share: number | null
+}
+
+export interface TeamReadyToMergeMediansApi {
+ /** Over the pull requests by the team's members, the same population as a github_team scope, without the pr_number pull request. Null when fewer than three other authors contribute a ready time, because the author could read a teammate's value back from the median. The approval medians are null on the same terms for approvals. */
+ medians: ReadyToMergeMediansApi | null
+ /** The GitHub team slug. */
+ github_team: string
+}
+
+export interface PullRequestReadyToMergeApi {
+ /** The pull request number. */
+ number: number
+ /**
+ * Seconds from the last ready_for_review to merge. Null when not observed.
+ * @nullable
+ */
+ ready_to_merge_seconds: number | null
+ /**
+ * Seconds from ready to the first approval. Null without an approval or review data.
+ * @nullable
+ */
+ ready_to_first_approval_seconds: number | null
+ /**
+ * Seconds from the first approval to merge. Null without an approval or review data.
+ * @nullable
+ */
+ first_approval_to_merge_seconds: number | null
+ /**
+ * Share (0 to 1) of the ready-to-merge time spent before the first approval.
+ * @nullable
+ */
+ before_first_approval_share: number | null
+}
+
+/**
+ * * `pull_request` - PULL_REQUEST
+ * * `review_requests` - REVIEW_REQUESTS
+ * * `only_team` - ONLY_TEAM
+ * * `all_teams` - ALL_TEAMS
+ * * `no_team` - NO_TEAM
+ */
+export type TeamBasisEnumApi = (typeof TeamBasisEnumApi)[keyof typeof TeamBasisEnumApi]
+
+export const TeamBasisEnumApi = {
+ PullRequest: 'pull_request',
+ ReviewRequests: 'review_requests',
+ OnlyTeam: 'only_team',
+ AllTeams: 'all_teams',
+ NoTeam: 'no_team',
+} as const
+
+export interface DeliveryComparisonApi {
+ /** Over the author's pull requests, without the pr_number pull request. */
+ author_medians: ReadyToMergeMediansApi
+ /** The author's teams that team_basis picked, sorted by slug. Empty for no_team. */
+ teams: TeamReadyToMergeMediansApi[]
+ /** Over every non-bot pull request in the repository, the author's included and the pr_number pull request left out. */
+ repo_medians: ReadyToMergeMediansApi
+ /** The pr_number pull request measured the same way, when it merged in the window. Null otherwise. */
+ pull_request: PullRequestReadyToMergeApi | null
+ /** The GitHub login the comparison is for. */
+ author: string
+ /** True when the team membership table is synced. Without it, team_basis is no_team. */
+ has_membership_data: boolean
+ /** False when reviews aren't synced: the approval medians are then null. */
+ review_data_available: boolean
+ /** False when issue events aren't synced: the ready-to-merge medians are then null. */
+ ready_data_available: boolean
+ /** How the teams were picked from the author's teams that own code: pull_request (the pr_number asked the team to review); review_requests (the team the author's pull requests asked to review most often in the window, with ties kept); only_team (the author is in one team); all_teams (no review request points at one team); no_team (no team, or no membership data).
+ *
+ * * `pull_request` - PULL_REQUEST
+ * * `review_requests` - REVIEW_REQUESTS
+ * * `only_team` - ONLY_TEAM
+ * * `all_teams` - ALL_TEAMS
+ * * `no_team` - NO_TEAM */
+ team_basis: TeamBasisEnumApi
+}
+
export interface ScopeRepoFigureApi {
/**
* The figure over the pull requests in scope. Null when the scope has nothing to measure.
@@ -2032,6 +2138,33 @@ export type EngineeringAnalyticsCurrentBranchHealthParams = {
source_id?: string
}
+export type EngineeringAnalyticsDeliveryComparisonParams = {
+ /**
+ * GitHub login of the author to compare with their team and the repository.
+ */
+ author: string
+ /**
+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
+ */
+ date_from?: string
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string
+ /**
+ * A pull request by the author. Needs repo. A team of the author's that this pull request asked to review is the team to compare with, and the pull request stays out of the medians.
+ */
+ pr_number?: number
+ /**
+ * 'owner/name' repository. Required with pr_number; otherwise it picks the repository when the selected source syncs several.
+ */
+ repo?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+}
+
export type EngineeringAnalyticsDeliverySummaryParams = {
/**
* GitHub login: scope the read to this author's pull requests. Pass exactly one scope.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index cb052076636c..13582bf0072d 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -16,6 +16,7 @@ import type {
CISignalsConfigApi,
CISignalsConfigUpdateApi,
CurrentBranchHealthApi,
+ DeliveryComparisonApi,
DeliverySummaryApi,
DoraOverviewApi,
EngineeringAnalyticsAuthorWorkflowCostsParams,
@@ -23,6 +24,7 @@ import type {
EngineeringAnalyticsCiCardsParams,
EngineeringAnalyticsCiFailureLogsParams,
EngineeringAnalyticsCurrentBranchHealthParams,
+ EngineeringAnalyticsDeliveryComparisonParams,
EngineeringAnalyticsDeliverySummaryParams,
EngineeringAnalyticsDoraParams,
EngineeringAnalyticsFlakyTestsParams,
@@ -272,6 +274,39 @@ export const engineeringAnalyticsCurrentBranchHealth = async (
})
}
+export const getEngineeringAnalyticsDeliveryComparisonUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsDeliveryComparisonParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/engineering_analytics/delivery_comparison/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/delivery_comparison/`
+}
+
+/**
+ * One author's median ready to merged time, split at the first approval, next to the same medians for the author's own team and for the whole repository, over pull requests merged in the window (date_from default -30d). The team is picked from the author's GitHub teams that own code: a team that pr_number asked to review, else the team the author's pull requests asked to review most often, else every team. Bots and drafts are excluded.
+ */
+export const engineeringAnalyticsDeliveryComparison = async (
+ projectId: string,
+ params: EngineeringAnalyticsDeliveryComparisonParams,
+ options?: RequestInit
+): Promise<DeliveryComparisonApi> => {
+ return apiMutator<DeliveryComparisonApi>(getEngineeringAnalyticsDeliveryComparisonUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsDeliverySummaryUrl = (
projectId: string,
params?: EngineeringAnalyticsDeliverySummaryParams
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index d086727e9f34..0a8532385f21 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -71,6 +71,9 @@ tools:
engineering-analytics-current-branch-health:
operation: engineering_analytics_current_branch_health
enabled: false
+ engineering-analytics-delivery-comparison:
+ operation: engineering_analytics_delivery_comparison
+ enabled: false
engineering-analytics-delivery-summary:
operation: engineering_analytics_delivery_summary
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 379d552fc9be..ff31e5346555 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -29559,6 +29559,113 @@ export namespace Schemas {
error: string | null;
}
+ export interface ReadyToMergeMedians {
+ /** Pull requests merged in the window, bots and drafts excluded. */
+ merged_pr_count: number;
+ /**
+ * Median seconds from the last ready_for_review to merge. Null when nothing was measured.
+ * @nullable
+ */
+ ready_to_merge_seconds: number | null;
+ /**
+ * 90th percentile of the ready-to-merge seconds.
+ * @nullable
+ */
+ p90_ready_to_merge_seconds: number | null;
+ /**
+ * Median seconds from ready to the first approval, over the pull requests with an approval. Null when nothing was measured.
+ * @nullable
+ */
+ ready_to_first_approval_seconds: number | null;
+ /**
+ * Median seconds from the first approval to merge. The two approval medians do not add up to the ready-to-merge median.
+ * @nullable
+ */
+ first_approval_to_merge_seconds: number | null;
+ /**
+ * Share (0 to 1) of all ready-to-merge hours spent before the first approval, summed over the pull requests, so long pull requests weigh more.
+ * @nullable
+ */
+ before_first_approval_share: number | null;
+ }
+
+ export interface TeamReadyToMergeMedians {
+ /** Over the pull requests by the team's members, the same population as a github_team scope, without the pr_number pull request. Null when fewer than three other authors contribute a ready time, because the author could read a teammate's value back from the median. The approval medians are null on the same terms for approvals. */
+ medians: ReadyToMergeMedians | null;
+ /** The GitHub team slug. */
+ github_team: string;
+ }
+
+ export interface PullRequestReadyToMerge {
+ /** The pull request number. */
+ number: number;
+ /**
+ * Seconds from the last ready_for_review to merge. Null when not observed.
+ * @nullable
+ */
+ ready_to_merge_seconds: number | null;
+ /**
+ * Seconds from ready to the first approval. Null without an approval or review data.
+ * @nullable
+ */
+ ready_to_first_approval_seconds: number | null;
+ /**
+ * Seconds from the first approval to merge. Null without an approval or review data.
+ * @nullable
+ */
+ first_approval_to_merge_seconds: number | null;
+ /**
+ * Share (0 to 1) of the ready-to-merge time spent before the first approval.
+ * @nullable
+ */
+ before_first_approval_share: number | null;
+ }
+
+ /**
+ * * `pull_request` - PULL_REQUEST
+ * * `review_requests` - REVIEW_REQUESTS
+ * * `only_team` - ONLY_TEAM
+ * * `all_teams` - ALL_TEAMS
+ * * `no_team` - NO_TEAM
+ */
+ export type TeamBasisEnum = typeof TeamBasisEnum[keyof typeof TeamBasisEnum];
+
+
+ export const TeamBasisEnum = {
+ PullRequest: 'pull_request',
+ ReviewRequests: 'review_requests',
+ OnlyTeam: 'only_team',
+ AllTeams: 'all_teams',
+ NoTeam: 'no_team',
+ } as const;
+
+ export interface DeliveryComparison {
+ /** Over the author's pull requests, without the pr_number pull request. */
+ author_medians: ReadyToMergeMedians;
+ /** The author's teams that team_basis picked, sorted by slug. Empty for no_team. */
+ teams: TeamReadyToMergeMedians[];
+ /** Over every non-bot pull request in the repository, the author's included and the pr_number pull request left out. */
+ repo_medians: ReadyToMergeMedians;
+ /** The pr_number pull request measured the same way, when it merged in the window. Null otherwise. */
+ pull_request: PullRequestReadyToMerge | null;
+ /** The GitHub login the comparison is for. */
+ author: string;
+ /** True when the team membership table is synced. Without it, team_basis is no_team. */
+ has_membership_data: boolean;
+ /** False when reviews aren't synced: the approval medians are then null. */
+ review_data_available: boolean;
+ /** False when issue events aren't synced: the ready-to-merge medians are then null. */
+ ready_data_available: boolean;
+ /** How the teams were picked from the author's teams that own code: pull_request (the pr_number asked the team to review); review_requests (the team the author's pull requests asked to review most often in the window, with ties kept); only_team (the author is in one team); all_teams (no review request points at one team); no_team (no team, or no membership data).
+ *
+ * * `pull_request` - PULL_REQUEST
+ * * `review_requests` - REVIEW_REQUESTS
+ * * `only_team` - ONLY_TEAM
+ * * `all_teams` - ALL_TEAMS
+ * * `no_team` - NO_TEAM */
+ team_basis: TeamBasisEnum;
+ }
+
/**
* Typed view over the Subscription.delivery_config JSON blob.
*/
@@ -101795,6 +101902,33 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsDeliveryComparisonParams = {
+ /**
+ * GitHub login of the author to compare with their team and the repository.
+ */
+ author: string;
+ /**
+ * Window start: relative ('-30d', '-8w') or ISO8601. Defaults to -30d.
+ */
+ date_from?: string;
+ /**
+ * Window end: relative or ISO8601. Defaults to now.
+ */
+ date_to?: string;
+ /**
+ * A pull request by the author. Needs repo. A team of the author's that this pull request asked to review is the team to compare with, and the pull request stays out of the medians.
+ */
+ pr_number?: number;
+ /**
+ * 'owner/name' repository. Required with pr_number; otherwise it picks the repository when the selected source syncs several.
+ */
+ repo?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ };
+
export type EngineeringAnalyticsDeliverySummaryParams = {
/**
* GitHub login: scope the read to this author's pull requests. Pass exactly one scope.