: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): pick an author's comparison team (#102158)
Julian Bezc623c677a8c1
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 226e2fb0d381..7ead4423cb5f 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -175,7 +175,7 @@ Warehouse tables (GitHub source):- `github_workflow_jobs`: per-job attempts (runner labels, queue and duration timestamps), the cost substrate. Webhook stream plus a window-limited backfill poll; per-run polling is infeasible at this volume.- `github_team_members`: org team membership, the author→team key. Optional at the source; every read that touches it must degrade gracefully when unsynced.- `github_reviews`: submitted pull request reviews (approvals, change requests, comments), fanned out per PR with `pr_number` injected. Backs the approval split and the review states on the author page. Optional at the source, so reads must degrade gracefully when unsynced.-- `github_issue_events`: immutable issue/PR state transitions, landed raw with every event type kept (a source-side filter would pin the desc-walk watermark). The draft/ready transitions in them back `ready_to_merge_seconds` and the lifecycle timeline. GitHub caps the endpoint's history walk, so rows cover a bounded recent window growing forward from the first sync; optional, and reads must degrade gracefully when unsynced.+- `github_issue_events`: immutable issue/PR state transitions, landed raw with every event type kept (a source-side filter would pin the desc-walk watermark). The draft/ready transitions in them back `ready_to_merge_seconds` and the lifecycle timeline. Team review requests (`review_requested` events that carry `requested_team`) pick the team an author's delivery comparison uses: the repository's owner resolution asks the teams that own the changed files, so the teams an author's pull requests ask most often are the teams the author works for. GitHub adds that column only for a team request, so a repository where no pull request asked a team has no such column, and the source resolver checks for it before the read uses it. GitHub caps the endpoint's history walk, so rows cover a bounded recent window growing forward from the first sync; optional, and reads must degrade gracefully when unsynced.Other products read as sources:diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex d3a82c2f2946..d272f73d591f 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -1682,6 +1682,75 @@ class DeliverySummary:lead_time: DeliveryLeadTime+class ComparisonTeamBasis(StrEnum):+ """Why a delivery comparison shows the teams it shows. The candidates are the author's GitHub teams+ with evidence of owning code (the ownership census or a review request), or every team of an author+ without such a team."""++ # The pull request in focus asked these teams of the author's to review.+ PULL_REQUEST = "pull_request"+ # The author's team that the author's pull requests asked to review most often in the window. Ties+ # keep every tied team.+ REVIEW_REQUESTS = "review_requests"+ # The author is in one candidate team.+ ONLY_TEAM = "only_team"+ # No review request points at one of the author's candidate teams, so every candidate is shown.+ ALL_TEAMS = "all_teams"+ # The author is in no candidate team, or the team membership table is not synced.+ NO_TEAM = "no_team"+++@dataclass(frozen=True)+class ReadyToMergeMedians:+ """Medians over one population's pull requests merged in the window, bots and drafts excluded. A+ median is None when no pull request in the population could be measured."""++ merged_pr_count: int+ ready_to_merge_seconds: float | None+ p90_ready_to_merge_seconds: float | None+ ready_to_first_approval_seconds: float | None+ first_approval_to_merge_seconds: float | None+ # The share of all ready-to-merge hours spent before the first approval, as in the delivery summary.+ before_first_approval_share: float | None+++@dataclass(frozen=True)+class PullRequestReadyToMerge:+ """One merged pull request measured the way the medians measure every pull request."""++ number: int+ ready_to_merge_seconds: float | None+ ready_to_first_approval_seconds: float | None+ first_approval_to_merge_seconds: float | None+ before_first_approval_share: float | None+++@dataclass(frozen=True)+class TeamReadyToMergeMedians:+ github_team: str+ # Over the pull requests by the team's members, the same population as a github_team delivery scope.+ # None when too few other authors merged in the window: the author could read a teammate's value back.+ medians: ReadyToMergeMedians | None+++@dataclass(frozen=True)+class DeliveryComparison:+ """How long an author's pull requests take from ready to merged, next to their team's and the+ repository's. The team is never a ranking: the read holds one author and that author's own teams."""++ author: str+ has_membership_data: bool+ review_data_available: bool+ ready_data_available: bool+ team_basis: ComparisonTeamBasis+ author_medians: ReadyToMergeMedians+ # Sorted by slug; empty for the NO_TEAM basis.+ teams: list[TeamReadyToMergeMedians]+ repo_medians: ReadyToMergeMedians+ # The pull request in focus, when it merged in the window.+ pull_request: PullRequestReadyToMerge | None++class PRTimelineSegmentKind(StrEnum):"""What a pull request was waiting on during one stretch of its timeline, most specific first.diff --git a/products/engineering_analytics/backend/logic/comparison_teams.py b/products/engineering_analytics/backend/logic/comparison_teams.pynew file mode 100644index 000000000000..6d0b5107d6d7--- /dev/null+++ b/products/engineering_analytics/backend/logic/comparison_teams.py@@ -0,0 +1,49 @@+"""Which of an author's teams a delivery comparison shows.++An author can be in several GitHub teams, so membership alone does not say whose pace to compare with.+A team review request does: the repository's owner resolution asks the teams that own the changed files+to review, so the teams an author's pull requests ask most often are the teams the author works for.+"""++from posthog.dataclasses import frozen++from products.engineering_analytics.backend.facade.contracts import ComparisonTeamBasis+++@frozen+class TeamChoice:+ teams: list[str]+ basis: ComparisonTeamBasis+++def _most_requested(teams: list[str], requested_prs: dict[str, int]) -> list[str]:+ top = max(requested_prs.get(team, 0) for team in teams)+ return [team for team in teams if requested_prs.get(team, 0) == top]+++def choose_comparison_teams(+ *, author_teams: set[str], code_teams: set[str], requested_prs: dict[str, int], focus_requested: set[str]+) -> TeamChoice:+ """Pick the teams from ``author_teams``.++ ``requested_prs`` counts, per team, the author's pull requests that asked the team to review in the+ window. ``focus_requested`` holds the teams that the pull request in focus asked, if there is one.+ ``code_teams`` holds the teams the ownership census counts. The census only sees test files, so a+ review request is evidence of owning code too.++ The members table also holds groups that own no code, such as approver groups, so the candidates+ are the author's teams with that evidence. An author with no such team keeps every team.+ """+ owning = {team for team in author_teams if team in code_teams or requested_prs.get(team) or team in focus_requested}+ ranked = sorted(owning or author_teams)+ if not ranked:+ return TeamChoice(teams=[], basis=ComparisonTeamBasis.NO_TEAM)+ if len(ranked) == 1:+ return TeamChoice(teams=ranked, basis=ComparisonTeamBasis.ONLY_TEAM)+ focus = [team for team in ranked if team in focus_requested]+ if focus:+ return TeamChoice(teams=focus, basis=ComparisonTeamBasis.PULL_REQUEST)+ requested = [team for team in ranked if requested_prs.get(team)]+ if requested:+ return TeamChoice(teams=_most_requested(requested, requested_prs), basis=ComparisonTeamBasis.REVIEW_REQUESTS)+ return TeamChoice(teams=ranked, basis=ComparisonTeamBasis.ALL_TEAMS)diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.pyindex 85b5d0561c9b..02366c52d67a 100644--- a/products/engineering_analytics/backend/logic/queries/_curated.py+++ b/products/engineering_analytics/backend/logic/queries/_curated.py@@ -249,6 +249,15 @@ class CuratedGitHubSource:return Nonereturn f"({issue_events.build_query(self._tables.issue_events, created_floor=created_floor)})"+ def team_review_requests_source(self, *, created_floor: bool = False) -> str | None:+ """Curated team review requests ``SELECT`` subquery, or None when the issue events hold none.+ ``created_floor`` adds the raw-string scan floor; callers must then register {event_created_floor}+ (see run_started_floor_constant)."""+ if not (self._tables.issue_events and self._tables.issue_events_team_requests):+ return None+ query = issue_events.build_team_review_requests_query(self._tables.issue_events, created_floor=created_floor)+ return f"({query})"+def reviews_source(self) -> str | None:"""Curated submitted-reviews ``SELECT`` subquery, or None when the optional reviews tableisn't synced."""diff --git a/products/engineering_analytics/backend/logic/queries/delivery_summary.py b/products/engineering_analytics/backend/logic/queries/delivery_summary.pyindex dee7115d5a52..5de4a7c12d45 100644--- a/products/engineering_analytics/backend/logic/queries/delivery_summary.py+++ b/products/engineering_analytics/backend/logic/queries/delivery_summary.py@@ -24,6 +24,8 @@ from products.engineering_analytics.backend.facade.contracts import (DeliveryLeadTime,DeliverySummary,DurationDistribution,+ PullRequestReadyToMerge,+ ReadyToMergeMedians,ScopeRepoDistribution,ScopeRepoFigure,)@@ -47,6 +49,7 @@ CI_LOOKBACK = timedelta(days=30)_MERGED_SELECT = f"""SELECTpr.number,+ pr.author_handle,(__SCOPE__) AS in_scope,pr.created_at,pr.merged_at,@@ -114,6 +117,7 @@ class MergedPRFacts:"""The per-PR facts behind every scope and repo figure."""number: int+ author: strin_scope: boolcreated_at: datetimemerged_at: datetime@@ -213,12 +217,42 @@ def _approval_splits(facts: list[MergedPRFacts]) -> list[_ApprovalSplit]:return splits+def _median_before_approval(facts: list[MergedPRFacts]) -> float | None:+ return quantile([split.before_seconds for split in _approval_splits(facts)], 0.5)+++def _median_after_approval(facts: list[MergedPRFacts]) -> float | None:+ return quantile([split.after_seconds for split in _approval_splits(facts)], 0.5)++def _before_approval_share(facts: list[MergedPRFacts]) -> float | None:splits = _approval_splits(facts)total = sum(split.before_seconds + split.after_seconds for split in splits)return sum(split.before_seconds for split in splits) / total if total else None+def ready_to_merge_medians(facts: list[MergedPRFacts]) -> ReadyToMergeMedians:+ return ReadyToMergeMedians(+ merged_pr_count=len(facts),+ ready_to_merge_seconds=quantile(_ready_seconds(facts), 0.5),+ p90_ready_to_merge_seconds=quantile(_ready_seconds(facts), 0.9),+ ready_to_first_approval_seconds=_median_before_approval(facts),+ first_approval_to_merge_seconds=_median_after_approval(facts),+ before_first_approval_share=_before_approval_share(facts),+ )+++def pull_request_ready_to_merge(fact: MergedPRFacts) -> PullRequestReadyToMerge:+ split = next(iter(_approval_splits([fact])), None)+ return PullRequestReadyToMerge(+ number=fact.number,+ ready_to_merge_seconds=fact.ready_to_merge_seconds,+ ready_to_first_approval_seconds=split.before_seconds if split else None,+ first_approval_to_merge_seconds=split.after_seconds if split else None,+ before_first_approval_share=_before_approval_share([fact]),+ )++def _pushes_after_approval(facts: list[MergedPRFacts]) -> float | None:counts = []for fact in facts:@@ -269,10 +303,10 @@ class DeliverySummaryAggregator:return self._figure(lambda facts: quantile(_ready_seconds(facts), q))def median_ready_to_first_approval(self) -> ScopeRepoFigure:- return self._figure(lambda facts: quantile([split.before_seconds for split in _approval_splits(facts)], 0.5))+ return self._figure(_median_before_approval)def median_first_approval_to_merge(self) -> ScopeRepoFigure:- return self._figure(lambda facts: quantile([split.after_seconds for split in _approval_splits(facts)], 0.5))+ return self._figure(_median_after_approval)def before_first_approval_share(self) -> ScopeRepoFigure:return self._figure(_before_approval_share)@@ -343,9 +377,19 @@ def _lead_time()-def _query_merged_facts(+@dataclass(frozen=True, kw_only=True)+class _MergedRow:+ number: int+ author: str+ in_scope: bool+ created_at: datetime+ merged_at: datetime+ ready_to_merge_seconds: int | None+++def _query_merged_rows(curated: CuratedGitHubSource, *, scope: DeliveryScope, date_from: datetime, date_to: datetime | None-) -> list[MergedPRFacts]:+) -> list[_MergedRow]:placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from), **scope.placeholders()}date_to_clause = ""if date_to is not None:@@ -359,25 +403,77 @@ def _query_merged_facts(.replace("__DATE_TO__", date_to_clause).replace("__PR_SOURCE__", curated.pr_source()))- merged_rows = curated.run(- sql, query_type="engineering_analytics.delivery_summary_merged", placeholders=placeholders+ response = curated.run(sql, query_type="engineering_analytics.delivery_summary_merged", placeholders=placeholders)+ return [+ _MergedRow(+ number=int(number),+ author=author or "",+ in_scope=bool(in_scope),+ created_at=created_at,+ merged_at=merged_at,+ ready_to_merge_seconds=int(ready_seconds) if ready_seconds is not None else None,+ )+ for number, author, in_scope, created_at, merged_at, ready_seconds in response.results or []+ if created_at is not None and merged_at is not None+ ]+++def _query_approvals(curated: CuratedGitHubSource, numbers: ast.Constant) -> dict[int, list[datetime]]:+ reviews_source = curated.reviews_source()+ if reviews_source is None:+ return {}+ response = curated.run(+ _APPROVALS_SELECT.replace("__REVIEWS_SOURCE__", reviews_source),+ query_type="engineering_analytics.delivery_summary_approvals",+ placeholders={"pr_numbers": numbers},+ )+ return {int(number): list(times) for number, times in response.results or []}+++def _merged_facts(+ row: _MergedRow,+ *,+ approved_at: list[datetime],+ pushed_at: list[datetime] | None = None,+ gate_attempts: list[_GateAttempt] | None = None,+ cost: PRCostAggregate | None = None,+) -> MergedPRFacts:+ return MergedPRFacts(+ number=row.number,+ author=row.author,+ in_scope=row.in_scope,+ created_at=row.created_at,+ merged_at=row.merged_at,+ ready_to_merge_seconds=row.ready_to_merge_seconds,+ approved_at=approved_at,+ pushed_at=pushed_at or [],+ gate_attempts=gate_attempts or [],+ cost=cost,)- rows = [row for row in merged_rows.results or [] if row[2] is not None and row[3] is not None]- pr_numbers = sorted({int(row[0]) for row in rows})+++def query_ready_to_merge_facts(+ curated: CuratedGitHubSource, *, scope: DeliveryScope, date_from: datetime, date_to: datetime | None+) -> list[MergedPRFacts]:+ """The merged PRs with only the facts the ready-to-merge medians read: no CI, queue or cost reads."""+ rows = _query_merged_rows(curated, scope=scope, date_from=date_from, date_to=date_to)+ if not rows:+ return []+ approvals = _query_approvals(curated, ast.Constant(value=sorted({row.number for row in rows})))+ return [_merged_facts(row, approved_at=approvals.get(row.number, [])) for row in rows]+++def _query_merged_facts(+ curated: CuratedGitHubSource, *, scope: DeliveryScope, date_from: datetime, date_to: datetime | None+) -> list[MergedPRFacts]:+ rows = _query_merged_rows(curated, scope=scope, date_from=date_from, date_to=date_to)+ pr_numbers = sorted({row.number for row in rows})if not pr_numbers:return []run_from = date_from - CI_LOOKBACKnumbers = ast.Constant(value=pr_numbers)- approvals: dict[int, list[datetime]] = {}- reviews_source = curated.reviews_source()- if reviews_source is not None:- response = curated.run(- _APPROVALS_SELECT.replace("__REVIEWS_SOURCE__", reviews_source),- query_type="engineering_analytics.delivery_summary_approvals",- placeholders={"pr_numbers": numbers},- )- approvals = {int(number): list(times) for number, times in response.results or []}+ approvals = _query_approvals(curated, numbers)runs_source = curated.run_source(started_floor=True)pushes_response = curated.run(@@ -411,18 +507,14 @@ def _query_merged_facts(costs = query_pr_costs_since(curated=curated, pr_numbers=pr_numbers, run_from=run_from)return [- MergedPRFacts(- number=int(number),- in_scope=bool(in_scope),- created_at=created_at,- merged_at=merged_at,- ready_to_merge_seconds=int(ready_seconds) if ready_seconds is not None else None,- approved_at=approvals.get(int(number), []),- pushed_at=pushes.get(int(number), []),- gate_attempts=gates.get(int(number), []),- cost=costs.get(int(number)),+ _merged_facts(+ row,+ approved_at=approvals.get(row.number, []),+ pushed_at=pushes.get(row.number, []),+ gate_attempts=gates.get(row.number, []),+ cost=costs.get(row.number),)- for number, in_scope, created_at, merged_at, ready_seconds in rows+ for row in rows]diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.pyindex 098fdc77261a..a453dc483543 100644--- a/products/engineering_analytics/backend/logic/sources.py+++ b/products/engineering_analytics/backend/logic/sources.py@@ -62,6 +62,10 @@ DEPLOYMENT_STATUSES_SCHEMA = "deployment_statuses"# at the source, so reads must degrade gracefully (no review data) exactly like issue_events.REVIEWS_SCHEMA = "reviews"+# GitHub adds this column to an issue event only for a team review request, so it lands only once some+# pull request in the repo requested a team, and a read of it fails before that.+REQUESTED_TEAM_COLUMN = "requested_team"+# The curated endpoints we resolve per repo. A source's other synced endpoints (issues, commits,# teams, …) are irrelevant to the CI/PR read layer and dropped during grouping._CURATED_ENDPOINTS = frozenset(@@ -102,6 +106,8 @@ class GitHubTables:deployment_statuses: str | None = None# Optional: present only once reviews are synced; None means "no review data".reviews: str | None = None+ # True when the issue-events table has the requested_team column (see REQUESTED_TEAM_COLUMN).+ issue_events_team_requests: bool = False# Used to scope cross-store reads such as CI traces to the selected source's repository.repository: str = ""@@ -153,7 +159,7 @@ def resolve_github_tables(exact = [c for c in materialized if c.repository.casefold() == wanted]candidates = exact if exact else [c for c in materialized if c.repository == ""]for candidate in candidates:- tables = candidate.tables+ tables = candidate.tables.namespull_requests = tables.get(PULL_REQUESTS_SCHEMA)workflow_runs = tables.get(WORKFLOW_RUNS_SCHEMA)# Both endpoints are required together, by design: every read surface (cards, PR list,@@ -174,6 +180,7 @@ def resolve_github_tables(deployments=tables.get(DEPLOYMENTS_SCHEMA),deployment_statuses=tables.get(DEPLOYMENT_STATUSES_SCHEMA),reviews=tables.get(REVIEWS_SCHEMA),+ issue_events_team_requests=candidate.tables.issue_events_team_requests,repository=candidate.repository,)if source_id is not None:@@ -205,7 +212,8 @@ def resolve_job_source_tables(team: Team) -> list[JobSourceTables]:"""resolved: list[JobSourceTables] = []for source in _github_sources(team):- for tables in _synced_tables_by_repo(team=team, source=source).values():+ for repo_tables in _synced_tables_by_repo(team=team, source=source).values():+ tables = repo_tables.namesruns = tables.get(WORKFLOW_RUNS_SCHEMA)jobs = tables.get(WORKFLOW_JOBS_SCHEMA)if runs and jobs:@@ -310,7 +318,7 @@ def list_github_sources(*, team: Team, user_access_control: "UserAccessControl |synced_repos = {repofor repo, tables in by_repo.items()- if PULL_REQUESTS_SCHEMA in tables and WORKFLOW_RUNS_SCHEMA in tables+ if PULL_REQUESTS_SCHEMA in tables.names and WORKFLOW_RUNS_SCHEMA in tables.names}for repo in _configured_repositories(source) or [""]:entries.append(@@ -324,12 +332,17 @@ def list_github_sources(*, team: Team, user_access_control: "UserAccessControl |return entries+class _RepoTables(NamedTuple):+ # ``{endpoint: table name}`` for this one repo's synced curated schemas.+ names: dict[str, str]+ issue_events_team_requests: bool++class _RepoCandidate(NamedTuple):# Display repo: the source's original-case ``repository`` for its legacy/bare repo (``''`` when# a bare row has no repo to attribute it to); the parsed ``owner/repo`` for a qualified repo.repository: str- # ``{endpoint: table name}`` for this one repo's synced curated schemas.- tables: dict[str, str]+ tables: _RepoTablesdef _repo_candidates(*, team: Team, sources: QuerySet[ExternalDataSource]) -> Iterator[_RepoCandidate]:@@ -450,8 +463,8 @@ def _synced_schemas(*, team: Team, source: ExternalDataSource) -> QuerySet[Exter)-def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[str, dict[str, str]]:- """Map ``{repository: {endpoint: table name}}`` for a source's actively-synced curated schemas.+def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[str, _RepoTables]:+ """Map ``{repository: tables}`` for a source's actively-synced curated schemas.A source syncs one repo (legacy bare endpoint names like ``pull_requests``) or several(repo-qualified names like ``owner/repo.pull_requests``, the multi-repo GitHub source). Each@@ -462,6 +475,7 @@ def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[st"""legacy_repo = _source_repository(source) or Noneby_repo: dict[str, dict[str, str]] = {}+ team_requests_by_repo: dict[str, bool] = {}for schema in _synced_schemas(team=team, source=source):repository, endpoint = github_schema_repo_endpoint(schema.schema_metadata, schema.name, legacy_repo)if endpoint not in _CURATED_ENDPOINTS:@@ -469,4 +483,10 @@ def _synced_tables_by_repo(*, team: Team, source: ExternalDataSource) -> dict[sttable = schema.tableif table is not None and not table.deleted and _IDENTIFIER.match(table.name):by_repo.setdefault(repository or "", {})[endpoint] = table.name- return by_repo+ # Set together with the table name, so a later schema row for the same endpoint replaces both.+ if endpoint == ISSUE_EVENTS_SCHEMA:+ team_requests_by_repo[repository or ""] = REQUESTED_TEAM_COLUMN in (table.columns or {})+ return {+ repository: _RepoTables(names=names, issue_events_team_requests=team_requests_by_repo.get(repository, False))+ for repository, names in by_repo.items()+ }diff --git a/products/engineering_analytics/backend/logic/views/issue_events.py b/products/engineering_analytics/backend/logic/views/issue_events.pyindex 5101fc9f6c16..d4ff9f84126b 100644--- a/products/engineering_analytics/backend/logic/views/issue_events.py+++ b/products/engineering_analytics/backend/logic/views/issue_events.py@@ -13,6 +13,8 @@ inside that range verifiably never left ready.# GitHub's issue-event vocabulary for the draft/ready transitions.READY_FOR_REVIEW_EVENT = "ready_for_review"CONVERT_TO_DRAFT_EVENT = "convert_to_draft"+# Carries ``requested_team`` when a team, not a person, was asked to review.+REVIEW_REQUESTED_EVENT = "review_requested"def build_query(table_name: str, *, created_floor: bool = False) -> str:@@ -39,6 +41,26 @@ def build_query(table_name: str, *, created_floor: bool = False) -> str:"""+def build_team_review_requests_query(table_name: str, *, created_floor: bool) -> str:+ """One row per team review request: the pull request, the requested team's slug, and when. With+ ``created_floor``, callers register {event_created_floor}, as for ``build_query``."""+ table_source = (+ f"(SELECT * FROM {table_name} WHERE created_at >= {{event_created_floor}})" if created_floor else table_name+ )+ return f"""+ SELECT pr_number, team_slug, requested_at+ FROM (+ SELECT+ JSONExtractInt(issue, 'number') AS pr_number,+ ifNull(JSONExtractString(requested_team, 'slug'), '') AS team_slug,+ parseDateTimeBestEffort(created_at) AS requested_at+ FROM {table_source}+ WHERE event = '{REVIEW_REQUESTED_EVENT}'+ )+ WHERE team_slug != '' AND requested_at IS NOT NULL+ """++def build_window_start_query(table_name: str) -> str:return f"SELECT min(parseDateTimeBestEffort(created_at)) AS window_start FROM {table_name}"diff --git a/products/engineering_analytics/backend/logic/views/source_schema.py b/products/engineering_analytics/backend/logic/views/source_schema.pyindex 97fe3e3fc145..bd01b19bd384 100644--- a/products/engineering_analytics/backend/logic/views/source_schema.py+++ b/products/engineering_analytics/backend/logic/views/source_schema.py@@ -96,6 +96,9 @@ ISSUE_EVENTS_COLUMNS: dict[str, dict[str, str]] = {"actor": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},"issue": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},"created_at": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},+ # GitHub adds this object only to a team review request, so a repo where no pull request asked a team+ # lands no such column. The source resolver checks for it.+ "requested_team": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"},}# Contract for the ``github_reviews`` warehouse source: one row per submitted review, fanned outdiff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.pyindex 27694cfc71cd..5abdc676e6c1 100644--- a/products/engineering_analytics/backend/tests/test_delivery.py+++ b/products/engineering_analytics/backend/tests/test_delivery.py@@ -8,10 +8,12 @@ from parameterized import parameterizedfrom rest_framework import statusfrom products.engineering_analytics.backend.facade.contracts import (+ ComparisonTeamBasis as Basis,DeliveryScopeKind,PRTimelineSegmentKind as Kind,ScopeRepoFigure,)+from products.engineering_analytics.backend.logic.comparison_teams import choose_comparison_teamsfrom products.engineering_analytics.backend.logic.delivery_scope import DeliveryScopefrom products.engineering_analytics.backend.logic.pr_timeline import (GateAttempt,@@ -306,6 +308,7 @@ def _facts(ready_at = merged_at - timedelta(hours=ready_hours)return MergedPRFacts(number=number,+ author="alice" if in_scope else "bob",in_scope=in_scope,created_at=ready_at - timedelta(hours=1),merged_at=merged_at,@@ -317,6 +320,95 @@ def _facts()+class TestComparisonTeamChoice(SimpleTestCase):+ @parameterized.expand(+ [+ ("no_team", set(), {}, set(), [], Basis.NO_TEAM),+ ("one_team_needs_no_signal", {"team-a"}, {"team-b": 3}, set(), ["team-a"], Basis.ONLY_TEAM),+ (+ "a_group_that_owns_no_code_is_no_candidate",+ {"team-a", "approvers"},+ {},+ set(),+ ["team-a"],+ Basis.ONLY_TEAM,+ ),+ (+ "a_requested_team_owns_code_without_tests",+ {"team-a", "team-untested", "approvers"},+ {"team-untested": 2, "team-a": 1},+ set(),+ ["team-untested"],+ Basis.REVIEW_REQUESTS,+ ),+ (+ "the_pull_request_in_focus_wins",+ {"team-a", "team-b"},+ {"team-a": 5, "team-b": 1},+ {"team-b"},+ ["team-b"],+ Basis.PULL_REQUEST,+ ),+ (+ "every_team_the_focus_pull_request_asked_stays",+ {"team-a", "team-b", "team-c"},+ {"team-a": 5, "team-b": 1},+ {"team-a", "team-b"},+ ["team-a", "team-b"],+ Basis.PULL_REQUEST,+ ),+ (+ "the_most_requested_team_wins",+ {"team-a", "team-b"},+ {"team-a": 1, "team-b": 4},+ set(),+ ["team-b"],+ Basis.REVIEW_REQUESTS,+ ),+ (+ "a_tie_keeps_every_tied_team",+ {"team-a", "team-b", "team-c"},+ {"team-a": 2, "team-b": 2, "team-c": 1},+ set(),+ ["team-a", "team-b"],+ Basis.REVIEW_REQUESTS,+ ),+ (+ "requests_for_other_teams_show_every_code_team",+ {"team-b", "team-a", "approvers"},+ {"team-x": 3},+ set(),+ ["team-a", "team-b"],+ Basis.ALL_TEAMS,+ ),+ ]+ )+ def test_picks_the_teams_to_compare_with(+ self,+ _name: str,+ author_teams: set[str],+ requested_prs: dict[str, int],+ focus_requested: set[str],+ teams: list[str],+ basis: Basis,+ ) -> None:+ choice = choose_comparison_teams(+ author_teams=author_teams,+ code_teams={"team-a", "team-b", "team-c"},+ requested_prs=requested_prs,+ focus_requested=focus_requested,+ )++ assert (choice.teams, choice.basis) == (teams, basis)++ def test_every_team_is_a_candidate_without_any_evidence_of_owning_code(self) -> None:+ choice = choose_comparison_teams(+ author_teams={"team-untested", "approvers"}, code_teams={"team-a"}, requested_prs={}, focus_requested=set()+ )++ assert (choice.teams, choice.basis) == (["approvers", "team-untested"], Basis.ALL_TEAMS)++class TestDeliverySummaryAggregator(SimpleTestCase):def test_scope_figures_read_only_the_prs_in_scope(self) -> None:aggregator = DeliverySummaryAggregator(@@ -563,9 +655,14 @@ class TestDeliveryDeployWindow(_WarehouseMixin):class TestDeliveryEndpoints(APIBaseTest):- @parameterized.expand([("delivery_summary",), ("pull_request_timelines",)])- def test_requires_exactly_one_scope(self, action: str) -> None:+ @parameterized.expand(+ [+ ("delivery_summary", "exactly one of author, github_team"),+ ("pull_request_timelines", "exactly one of author, github_team"),+ ]+ )+ 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}/")assert response.status_code == status.HTTP_400_BAD_REQUEST- assert "exactly one of author, github_team" in response.json()["detail"]+ assert message in response.json()["detail"]diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.pyindex 84587db674e3..de9ec36e6777 100644--- a/products/engineering_analytics/backend/tests/test_logic_sources.py+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py@@ -9,6 +9,7 @@ from posthog.models.team import Teamfrom products.engineering_analytics.backend.facade import apifrom products.engineering_analytics.backend.facade.contracts import GitHubSource, GitHubSourceNotConnectedErrorfrom products.engineering_analytics.backend.logic.sources import (+ ISSUE_EVENTS_SCHEMA,PULL_REQUESTS_SCHEMA,WORKFLOW_JOBS_SCHEMA,WORKFLOW_RUNS_SCHEMA,@@ -70,6 +71,22 @@ class TestResolveGitHubTables(BaseTest):pull_requests="myprefixgithub_pull_requests", workflow_runs="myprefixgithub_workflow_runs")+ @parameterized.expand([("with_team_requests", ["event", "requested_team"], True), ("without", ["event"], False)])+ def test_flags_issue_events_that_hold_team_review_requests(+ self, _name: str, columns: list[str], expected: bool+ ) -> None:+ source = self._connect(prefix="flag", schemas=self._BOTH_SYNCED)+ table = create_warehouse_table_row(self.team, name="flaggithub_issue_events", source=source)+ table.columns = {+ column: {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField"} for column in columns+ }+ table.save()+ link_schema(self.team, source, name=ISSUE_EVENTS_SCHEMA, table=table, should_sync=True)++ tables = resolve_github_tables(team=self.team)++ assert (tables.issue_events, tables.issue_events_team_requests) == ("flaggithub_issue_events", expected)+def test_repo_scoped_resolution_survives_non_dict_job_inputs(self) -> None:# job_inputs is an EncryptedJSONField that can hold any JSON value; the repo-first ordering# must treat a non-dict as "no repository input", not crash the whole resolution.