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.

refactor(eng-analytics): simplify delivery reads (#102507)

Raúl Negrón-Otero4ec549e60ad0
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 30b17e740685..2428681c4c4e 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -1571,15 +1571,13 @@ class WorkflowJobAggregate:
@dataclass(frozen=True)
class PathOwnership:
- """Which team owns each of a set of repository paths, plus the repo's Slack registry.
+ """Which team owns each repository path, plus the repo's Slack registry from the root ``owners.yaml``.
+ The registry rides along because the caller that asks who owns a path usually has to reach that
+ team next, and the root file answers both questions in one read.
- The registry rides along because the caller that asks who owns a path usually has to reach
- that team next, and the root ``owners.yaml`` answers both questions in one read.
-
- ``resolved`` is false when the ownership files could not be read, which leaves every path
- ``UNOWNED_TEAM`` and the registry empty. A caller that says so beats one that reads the blind
- answer as "nobody owns this".
- """
+ ``resolved`` is false when the ownership files could not be read; every path is then
+ ``UNOWNED_TEAM`` and the registry is empty. A caller that says so beats one that reads the blind
+ answer as "nobody owns this"."""
team_by_path: Mapping[str, str]
registry: Mapping[str, TeamEntry]
@@ -1762,12 +1760,9 @@ class DeliveryComparison:
class PRTimelineSegmentKind(StrEnum):
- """What a pull request was waiting on during one stretch of its timeline, most specific first.
-
- CI and queue states win over review states: a red check blocks a merge whatever the review
- says. The red variants name what turned the check green, which is evidence about the cause,
- not proof of it.
- """
+ """What a pull request was waiting on during one stretch of its timeline. The red variants name
+ what turned the check green, which is evidence about the cause, not proof of it.
+ ``logic/pr_timeline.py`` defines the precedence."""
DRAFT = "draft"
WAITING_FOR_REVIEW = "waiting_for_review"
diff --git a/products/engineering_analytics/backend/logic/pr_timeline.py b/products/engineering_analytics/backend/logic/pr_timeline.py
index 364e8ee91666..5e82890a6887 100644
--- a/products/engineering_analytics/backend/logic/pr_timeline.py
+++ b/products/engineering_analytics/backend/logic/pr_timeline.py
@@ -104,7 +104,7 @@ class MasterFailureIndex:
@dataclass(frozen=True, kw_only=True)
class PRTimelineInput:
started_at: datetime
- # The merge, or now for an open PR.
+ # The merge, the close, or now for an open PR.
ended_at: datetime
is_open: bool
is_merged: bool
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 02366c52d67a..0041d137e378 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -243,8 +243,8 @@ class CuratedGitHubSource:
def issue_events_source(self, *, created_floor: bool = False) -> str | None:
"""Curated PR draft/ready transitions ``SELECT`` subquery, or None when the optional
- issue-events table isn't synced. ``created_floor`` adds the raw-string scan floor — callers
- must register {event_created_floor} (see run_started_floor_constant)."""
+ issue-events table isn't synced. ``created_floor`` adds the raw-string scan floor, so callers
+ must register {event_created_floor} (see ``run_started_floor_constant``)."""
if not self._tables.issue_events:
return None
return f"({issue_events.build_query(self._tables.issue_events, created_floor=created_floor)})"
@@ -281,7 +281,7 @@ class CuratedGitHubSource:
a constant NULL when the optional issue-events table isn't synced, so every consumer reads
the measure the same way."""
window = self._issue_events_window()
- cte = self._ready_by_pr_cte()
+ cte = self.ready_by_pr_cte()
if window is None or cte is None:
return _READY_TO_MERGE_UNOBSERVABLE
return ReadyToMergeSql(cte=cte, join=_READY_BY_PR_JOIN, expr=_ready_to_merge_expr(window))
@@ -298,8 +298,9 @@ class CuratedGitHubSource:
end=f"({issue_events.build_window_end_query(self._tables.issue_events)})",
)
- def _ready_by_pr_cte(self) -> str | None:
- """CTE: each PR's last observed draft-state transition, or None when the table isn't synced.
+ def ready_by_pr_cte(self, *, created_floor: bool = False) -> str | None:
+ """CTE: each PR's last observed draft-state transition and last ready event, or None when the
+ table isn't synced. ``created_floor`` works as in ``issue_events_source``.
Only the LAST switch counts: for a merged PR the newest transition is necessarily the ready
that preceded the merge (a draft can't merge); an open PR goes false while re-drafted. The
@@ -307,8 +308,12 @@ class CuratedGitHubSource:
``pr_number`` alone, unlike ``runs_by_pr``: a run's association can list the fork network's
PRs (which is why that rollup needs the repo qualifier), whereas every row of a resolved
issue-events table belongs to that one repo by table construction.
+
+ The events table and the pull requests table sync independently, so a timestamp here can run
+ ahead of what a PR's own row reports. A consumer that compares one against a PR's end must
+ bound it. ``last_ready_at`` is safe against ``merged_at`` alone, because a draft cannot merge.
"""
- source = self.issue_events_source()
+ source = self.issue_events_source(created_floor=created_floor)
if source is None:
return None
return f"""
@@ -316,7 +321,11 @@ class CuratedGitHubSource:
SELECT
pr_number,
argMax(event, tuple(created_at, id)) = '{issue_events.READY_FOR_REVIEW_EVENT}' AS last_is_ready,
- max(created_at) AS last_transition_at
+ max(created_at) AS last_transition_at,
+ -- OrNull, not maxIf: a plain maxIf falls back to the epoch default when no row
+ -- matches, and that default would pass the caller's last_ready_at IS NOT NULL
+ -- filter as if it were a real event (see dora.py's deploys CTE for the same hazard).
+ maxOrNullIf(created_at, event = '{issue_events.READY_FOR_REVIEW_EVENT}') AS last_ready_at
FROM {source} AS se
GROUP BY pr_number
)
diff --git a/products/engineering_analytics/backend/logic/queries/delivery_summary.py b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
index ade3f27e3cd8..cd63b40c4189 100644
--- a/products/engineering_analytics/backend/logic/queries/delivery_summary.py
+++ b/products/engineering_analytics/backend/logic/queries/delivery_summary.py
@@ -1,15 +1,9 @@
-"""Curated query: delivery and CI friction for one scope (an author or a GitHub team) against the repository.
+"""Curated query: delivery and CI friction for one scope against the repository. The SQL returns one
+row of facts per merged PR, and ``scope_repo_figure`` folds them into medians and shares in Python.
-Every figure is measured twice over the same window: over the scope's merged pull requests, and over
-every merged pull request in the repository (bots and drafts excluded, the scope included). The
-comparison is against the repository, not against the previous window: the question is "is this
-friction unusual here", and a trend over time says nothing about that.
-
-The SQL returns one row per merged PR and a handful of per-PR facts (ready time, approvals, pushes,
-merge-queue attempts, cost); the medians and shares are computed in Python. A window of merged PRs
-is small (thousands of rows at most), and folding in Python keeps the scope and repo figures on
-exactly one definition.
-"""
+The comparison is against the repository, not against the previous window: the question is "is this
+friction unusual here", and a trend over time says nothing about that. A window of merged pull
+requests is small, so folding in Python keeps the scope and the repo figures on one definition."""
import math
import statistics
@@ -36,10 +30,11 @@ from products.engineering_analytics.backend.logic.queries._curated import Curate
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
DECISIVE_FAILURE_CONCLUSIONS_SQL,
UNPAGED_SCAN_LIMIT,
+ date_to_filter_clause,
run_started_floor_constant,
)
from products.engineering_analytics.backend.logic.queries.dora import DeployedPR, query_deployed_prs
-from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs_since
+from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs
from products.engineering_analytics.backend.logic.views.reviews import APPROVED_STATE
_MERGED_SELECT = f"""
@@ -110,8 +105,6 @@ class _GateAttempt:
@dataclass(frozen=True, kw_only=True)
class MergedPRFacts:
- """The per-PR facts behind every scope and repo figure."""
-
number: int
author: str
in_scope: bool
@@ -196,6 +189,14 @@ def _ready_seconds(facts: list[MergedPRFacts]) -> list[float]:
return [float(f.ready_to_merge_seconds) for f in facts if f.ready_to_merge_seconds is not None]
+def _median_ready_to_merge(facts: list[MergedPRFacts]) -> float | None:
+ return quantile(_ready_seconds(facts), 0.5)
+
+
+def _p90_ready_to_merge(facts: list[MergedPRFacts]) -> float | None:
+ return quantile(_ready_seconds(facts), 0.9)
+
+
@dataclass(frozen=True, kw_only=True)
class _ApprovalSplit:
before_seconds: float
@@ -213,11 +214,11 @@ def _approval_splits(facts: list[MergedPRFacts]) -> list[_ApprovalSplit]:
return splits
-def _median_before_approval(facts: list[MergedPRFacts]) -> float | None:
+def _median_ready_to_first_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:
+def _median_first_approval_to_merge(facts: list[MergedPRFacts]) -> float | None:
return quantile([split.after_seconds for split in _approval_splits(facts)], 0.5)
@@ -232,8 +233,8 @@ def ready_to_merge_medians(facts: list[MergedPRFacts]) -> 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),
+ ready_to_first_approval_seconds=_median_ready_to_first_approval(facts),
+ first_approval_to_merge_seconds=_median_first_approval_to_merge(facts),
before_first_approval_share=_before_approval_share(facts),
)
@@ -271,50 +272,14 @@ def _failed_queue_share(facts: list[MergedPRFacts]) -> float | None:
return sum(1 for f in queued if any(gate.failed for gate in f.landing_gate_attempts)) / len(queued)
-class DeliverySummaryAggregator:
- """Folds the per-PR facts into scope and repo figures. Every figure applies one measure to both
- populations, so the scope and the repo can never be measured two different ways."""
-
- def __init__(self, facts: list[MergedPRFacts]) -> None:
- self._repo = facts
- self._scope = [fact for fact in facts if fact.in_scope]
-
- @property
- def scope_facts(self) -> list[MergedPRFacts]:
- return self._scope
-
- def _figure(self, measure: Callable[[list[MergedPRFacts]], float | None]) -> ScopeRepoFigure:
- return ScopeRepoFigure(scope=measure(self._scope), repo=measure(self._repo))
-
- def cost_per_merged_pr(self) -> ScopeRepoFigure:
- return self._figure(_median_cost)
-
- def billable_minutes_per_merged_pr(self) -> ScopeRepoFigure:
- return self._figure(_median_billable_minutes)
-
- def cost_per_push(self) -> ScopeRepoFigure:
- return self._figure(_cost_per_push)
-
- def ready_to_merge(self, q: float) -> ScopeRepoFigure:
- return self._figure(lambda facts: quantile(_ready_seconds(facts), q))
-
- def median_ready_to_first_approval(self) -> ScopeRepoFigure:
- return self._figure(_median_before_approval)
-
- def median_first_approval_to_merge(self) -> ScopeRepoFigure:
- return self._figure(_median_after_approval)
-
- def before_first_approval_share(self) -> ScopeRepoFigure:
- return self._figure(_before_approval_share)
-
- def pushes_after_approval(self) -> ScopeRepoFigure:
- return self._figure(_pushes_after_approval)
-
- def merge_queue_attempts(self) -> ScopeRepoFigure:
- return self._figure(_queue_attempts)
-
- def failed_merge_queue_share(self) -> ScopeRepoFigure:
- return self._figure(_failed_queue_share)
+def scope_repo_figure(
+ scope_facts: list[MergedPRFacts],
+ facts: list[MergedPRFacts],
+ measure: Callable[[list[MergedPRFacts]], float | None],
+) -> ScopeRepoFigure:
+ """Applies one measure to the PRs in scope and to every PR, so the scope and the repo can never be
+ measured two different ways."""
+ return ScopeRepoFigure(scope=measure(scope_facts), repo=measure(facts))
def _lead_time(
@@ -367,9 +332,9 @@ def _lead_time(
for row in deployed.rows
if row.in_scope and in_window(row.merged_at) and (date_to is None or row.deployed_at <= date_to)
),
- open_to_deploy=pair(lambda row: (row.deployed_at - row.created_at).total_seconds()),
- open_to_merge=pair(lambda row: (row.merged_at - row.created_at).total_seconds()),
- merge_to_deploy=pair(lambda row: (row.deployed_at - row.merged_at).total_seconds()),
+ open_to_deploy=pair(lambda row: row.open_to_deploy_seconds),
+ open_to_merge=pair(lambda row: row.open_to_merge_seconds),
+ merge_to_deploy=pair(lambda row: row.merge_to_deploy_seconds),
)
@@ -387,16 +352,12 @@ def _query_merged_rows(
curated: CuratedGitHubSource, *, scope: DeliveryScope, date_from: datetime, date_to: datetime | None
) -> 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:
- placeholders["date_to"] = ast.Constant(value=date_to)
- date_to_clause = "AND pr.merged_at <= {date_to}"
ready = curated.ready_to_merge_sql()
sql = ready.with_clause + (
_MERGED_SELECT.replace("__SCOPE__", scope.pr_predicate(curated))
.replace("__READY_TO_MERGE__", ready.expr)
.replace("__READY_JOIN__", ready.join)
- .replace("__DATE_TO__", date_to_clause)
+ .replace("__DATE_TO__", date_to_filter_clause(date_to, placeholders, column="pr.merged_at"))
.replace("__PR_SOURCE__", curated.pr_source())
)
response = curated.run(sql, query_type="engineering_analytics.delivery_summary_merged", placeholders=placeholders)
@@ -500,7 +461,12 @@ def _query_merged_facts(
if started_at is not None:
gates[int(number)].append(_GateAttempt(started_at=started_at, failed=bool(failed)))
- costs = query_pr_costs_since(curated=curated, pr_numbers=pr_numbers, run_from=run_from)
+ # A resolved source is one repository's tables, so dropping the owner and name cannot collide two
+ # pull requests. The timelines read keeps the full key, because it shows the repository per row.
+ costs = {
+ number: cost
+ for (_, _, number), cost in query_pr_costs(curated=curated, pr_numbers=pr_numbers, run_from=run_from).items()
+ }
return [
_merged_facts(
@@ -518,17 +484,12 @@ def query_delivery_summary(
*, curated: CuratedGitHubSource, scope: SummaryScope, date_from: datetime, date_to: datetime | None
) -> DeliverySummary:
facts = _query_merged_facts(curated, scope=scope, date_from=date_from, date_to=date_to)
- aggregator = DeliverySummaryAggregator(facts)
- scope_facts = aggregator.scope_facts
+ scope_facts = [fact for fact in facts if fact.in_scope]
placeholders: dict[str, ast.Expr] = {"date_from": ast.Constant(value=date_from), **scope.placeholders()}
- date_to_clause = ""
- if date_to is not None:
- placeholders["date_to"] = ast.Constant(value=date_to)
- date_to_clause = "AND pr.created_at <= {date_to}"
counts = curated.run(
_SCOPE_COUNTS_SELECT.replace("__SCOPE__", scope.pr_predicate(curated))
- .replace("__DATE_TO__", date_to_clause)
+ .replace("__DATE_TO__", date_to_filter_clause(date_to, placeholders, column="pr.created_at"))
.replace("__PR_SOURCE__", curated.pr_source()),
query_type="engineering_analytics.delivery_summary_counts",
placeholders=placeholders,
@@ -548,9 +509,9 @@ def query_delivery_summary(
merged_pr_count=len(scope_facts),
open_pr_count=int(open_now or 0),
draft_pr_count=int(drafts or 0),
- cost_per_merged_pr_usd=aggregator.cost_per_merged_pr(),
- billable_minutes_per_merged_pr=aggregator.billable_minutes_per_merged_pr(),
- cost_per_push_usd=aggregator.cost_per_push(),
+ cost_per_merged_pr_usd=scope_repo_figure(scope_facts, facts, _median_cost),
+ billable_minutes_per_merged_pr=scope_repo_figure(scope_facts, facts, _median_billable_minutes),
+ cost_per_push_usd=scope_repo_figure(scope_facts, facts, _cost_per_push),
total_cost_usd=sum(cost.estimated_cost_usd for cost in costed if cost.estimated_cost_usd is not None)
if costed
else None,
@@ -558,14 +519,14 @@ def query_delivery_summary(
if jobs_available
else None,
push_count=sum(f.pushes for f in scope_facts),
- median_ready_to_merge_seconds=aggregator.ready_to_merge(0.5),
- p90_ready_to_merge_seconds=aggregator.ready_to_merge(0.9),
- median_ready_to_first_approval_seconds=aggregator.median_ready_to_first_approval(),
- median_first_approval_to_merge_seconds=aggregator.median_first_approval_to_merge(),
- before_first_approval_share=aggregator.before_first_approval_share(),
- pushes_after_approval_per_merged_pr=aggregator.pushes_after_approval(),
- merge_queue_attempts_per_merged_pr=aggregator.merge_queue_attempts(),
- failed_merge_queue_share=aggregator.failed_merge_queue_share(),
+ median_ready_to_merge_seconds=scope_repo_figure(scope_facts, facts, _median_ready_to_merge),
+ p90_ready_to_merge_seconds=scope_repo_figure(scope_facts, facts, _p90_ready_to_merge),
+ median_ready_to_first_approval_seconds=scope_repo_figure(scope_facts, facts, _median_ready_to_first_approval),
+ median_first_approval_to_merge_seconds=scope_repo_figure(scope_facts, facts, _median_first_approval_to_merge),
+ before_first_approval_share=scope_repo_figure(scope_facts, facts, _before_approval_share),
+ pushes_after_approval_per_merged_pr=scope_repo_figure(scope_facts, facts, _pushes_after_approval),
+ merge_queue_attempts_per_merged_pr=scope_repo_figure(scope_facts, facts, _queue_attempts),
+ failed_merge_queue_share=scope_repo_figure(scope_facts, facts, _failed_queue_share),
lead_time=_lead_time(
curated, scope=scope, date_from=date_from, date_to=date_to, scope_merged_count=len(scope_facts)
),
diff --git a/products/engineering_analytics/backend/logic/queries/pr_cost.py b/products/engineering_analytics/backend/logic/queries/pr_cost.py
index f72467ee0645..84d494007949 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_cost.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_cost.py
@@ -48,6 +48,7 @@ from products.engineering_analytics.backend.logic.queries._buckets import (
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries._workflow_filters import (
+ UNPAGED_SCAN_LIMIT,
branch_filter_clause,
cost_run_scope_filter_clause,
date_to_filter_clause,
@@ -132,11 +133,11 @@ _EMPTY = PRCostSummary(
# is missing, matching the legacy INNER JOIN population.
#
# The only two cost queries with no scan floor (see job_cost_source(created_floor=...)) are this one
-# and _LIST_COST_SELECT: both are keyed by PR number, not by a window, and a PR's created_at would
-# cost an extra round trip here (build_pr_cost is handed a number and a repo, nothing else) or be the
-# min across a whole page there — which for a page holding one old PR is no bound at all. Left
-# unfloored deliberately; if these ever get slow, thread the PR's created_at down and floor a day
-# below it rather than inventing a window.
+# and _COSTS_BY_PR_SELECT without run_from: both are keyed by PR number, not by a window, and a PR's
+# created_at would cost an extra round trip here (build_pr_cost is handed a number and a repo, nothing
+# else) or be the min across a whole page there, which for a page holding one old PR is no bound at
+# all. Left unfloored deliberately; if these ever get slow, thread the PR's created_at down and floor
+# a day below it rather than inventing a window.
_PR_COST_SELECT = """
SELECT
c.workflow_name AS workflow_name,
@@ -201,81 +202,51 @@ def query_pr_cost(
# Per-PR billable cost across the given PR numbers, aggregated in SQL and scoped to the visible PR
# numbers so a team with deep CI history doesn't pay an all-time scan per page.
-_LIST_COST_SELECT = """
+_COSTS_BY_PR_SELECT = f"""
SELECT
c.repo_owner AS repo_owner,
c.repo_name AS repo_name,
c.pr_number AS pr_number,
__COST_AGGREGATES__
FROM __COST_SOURCE__ AS c
- WHERE c.pr_number IN {pr_numbers}
+ WHERE c.pr_number IN {{pr_numbers}} __RUN_FROM__
GROUP BY c.repo_owner, c.repo_name, c.pr_number
- LIMIT 1000000
+ LIMIT {UNPAGED_SCAN_LIMIT}
"""
-def query_pr_list_costs(
- *, curated: CuratedGitHubSource, pr_numbers: list[int]
+def query_pr_costs(
+ *, curated: CuratedGitHubSource, pr_numbers: list[int], run_from: datetime | None = None
) -> dict[tuple[str, str, int], PRCostAggregate]:
"""Per-PR billable cost across the given PR numbers' runs, keyed by (repo_owner, repo_name, pr_number).
Empty when the jobs source isn't synced or no PR numbers are given. One grouped pass over the cost
- source so the PR list can show a cost/minutes column per row without a query per PR; scoped to the
- visible PR numbers so the scan tracks the page, not the team's whole CI history.
+ source so a list can show a cost/minutes column per row without a query per PR.
+
+ A population that can be repo-wide (every PR merged in a window) passes ``run_from``: runs started
+ before it are left out, which trims the jobs scan for a population of thousands of PRs.
"""
- cost_source = curated.job_cost_source()
+ cost_source = curated.job_cost_source(created_floor=run_from is not None)
if cost_source is None or not pr_numbers:
return {}
- sql = _LIST_COST_SELECT.replace("__COST_SOURCE__", cost_source).replace("__COST_AGGREGATES__", _cost_aggregates())
- response = curated.run(
- sql,
- query_type="engineering_analytics.pr_list_costs",
- placeholders={"pr_numbers": ast.Constant(value=pr_numbers)},
+ placeholders: dict[str, ast.Expr] = {"pr_numbers": ast.Constant(value=pr_numbers)}
+ run_from_clause = ""
+ if run_from is not None:
+ placeholders["run_from"] = ast.Constant(value=run_from)
+ placeholders["job_created_floor"] = run_windowed_job_created_floor_constant(run_from)
+ run_from_clause = "AND c.run_started_at >= {run_from}"
+ sql = (
+ _COSTS_BY_PR_SELECT.replace("__COST_SOURCE__", cost_source)
+ .replace("__COST_AGGREGATES__", _cost_aggregates())
+ .replace("__RUN_FROM__", run_from_clause)
)
+ response = curated.run(sql, query_type="engineering_analytics.pr_costs", placeholders=placeholders)
return {
(repo_owner, repo_name, int(pr_number)): _aggregate(*agg)
for repo_owner, repo_name, pr_number, *agg in response.results or []
}
-# Per-PR billable cost for a population that can be repo-wide (every PR merged in a window), so unlike
-# _LIST_COST_SELECT it carries a floor: runs started before ``run_from`` are left out, which trims the
-# jobs scan for a population of thousands of PRs.
-_FLOORED_PR_COST_SELECT = """
- SELECT c.pr_number AS pr_number, __COST_AGGREGATES__
- FROM __COST_SOURCE__ AS c
- WHERE c.pr_number IN {pr_numbers} AND c.run_started_at >= {run_from}
- GROUP BY c.pr_number
- LIMIT 1000000
-"""
-
-
-def query_pr_costs_since(
- *, curated: CuratedGitHubSource, pr_numbers: list[int], run_from: datetime
-) -> dict[int, PRCostAggregate]:
- """Per-PR billable cost from the runs started at or after ``run_from``, keyed by PR number.
-
- Empty when the jobs source isn't synced or no PR numbers are given. Keyed by number alone
- because a resolved source is one repository's tables.
- """
- cost_source = curated.job_cost_source(created_floor=True)
- if cost_source is None or not pr_numbers:
- return {}
- sql = _FLOORED_PR_COST_SELECT.replace("__COST_SOURCE__", cost_source).replace(
- "__COST_AGGREGATES__", _cost_aggregates()
- )
- response = curated.run(
- sql,
- query_type="engineering_analytics.pr_costs_since",
- placeholders={
- "pr_numbers": ast.Constant(value=pr_numbers),
- "run_from": ast.Constant(value=run_from),
- "job_created_floor": run_windowed_job_created_floor_constant(run_from),
- },
- )
- return {int(pr_number): _aggregate(*agg) for pr_number, *agg in response.results or []}
-
-
# Per-workflow billable cost over a window (Workflows tab), grouped and costed in SQL and keyed by
# workflow_name. Windowed and optionally branch/run-scope filtered on the run's attributes (the cost
# source carries run_started_at and run_head_branch alongside the per-job cost columns).
@@ -585,10 +556,8 @@ def query_cost_per_merge_series(
return buckets
-# Per-runner-tier cost for one workflow (single-workflow page "where the spend goes" breakdown), scoped
-# to the page's run window (and optional branch or run scope) so the figure always answers "spend over
-# [window]", never an unbounded all-time. Grouped by the rendered (provider, os, vcpu) tier in SQL — the cost
-# source already classifies each job — and mapped to a display badge/label in Python.
+# Per-runner-tier cost for one workflow, scoped to the page's run window (and optional branch or run
+# scope) so the figure always answers "spend over [window]", never an unbounded all-time.
_RUNNER_COST_SELECT = """
SELECT
c.provider AS provider,
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_list.py b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
index a28e058723ca..013378b3ceaa 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_list.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_list.py
@@ -23,7 +23,7 @@ from products.engineering_analytics.backend.facade.contracts import (
from products.engineering_analytics.backend.logic.cost import PRCostAggregate
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries._workflow_filters import DECISIVE_FAILURE_CONCLUSIONS_SQL
-from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_list_costs
+from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs
_LIMIT = 1000
# Sparkline cap: enough to read a PR's CI history at a glance without bloating a 1000-row page.
@@ -113,7 +113,7 @@ def query_pr_push_history(
) -> dict[tuple[str, str, int], list[PushCISample]]:
"""Per-PR push rounds keyed by (repo_owner, repo_name, pr_number), oldest first, capped in
ClickHouse to the most recent ``_PUSH_HISTORY_LIMIT`` per PR. Scoped to the visible PR numbers so
- the scan tracks the page (same shape as ``query_pr_list_costs``)."""
+ the scan tracks the page (same shape as ``query_pr_costs``)."""
if not pr_numbers:
return {}
sql = (
@@ -166,7 +166,7 @@ def query_pull_request_list(
# Scope the cost and push-history rollups to exactly the PRs we're about to show (row[0] is
# pr.number), so the scans track the page instead of the team's whole CI history.
pr_numbers = sorted({int(row[0]) for row in visible})
- cost_by_pr = query_pr_list_costs(curated=curated, pr_numbers=pr_numbers)
+ cost_by_pr = query_pr_costs(curated=curated, pr_numbers=pr_numbers)
pushes_by_pr = query_pr_push_history(curated=curated, pr_numbers=pr_numbers)
items = [_map_row(row, cost_by_pr, pushes_by_pr) for row in visible]
return PullRequestList(items=items, truncated=truncated, limit=_LIMIT)
diff --git a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
index fb6772771b68..1ba2ccd8015d 100644
--- a/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
+++ b/products/engineering_analytics/backend/logic/queries/pull_request_timelines.py
@@ -1,13 +1,10 @@
-"""Curated query: pull requests in one scope as delivery timelines.
+"""Curated query: pull requests in one scope as delivery timelines, replayed with ``logic.pr_timeline``.
-Selects the pull requests in scope (an author's or a GitHub team's open PRs plus the PRs merged in
-the window, or one pull request whatever its state), fetches their immutable evidence, then replays
-each PR's states with ``logic.pr_timeline``. Every read is scoped to the selected PR numbers, so the
-scans track the listed work rather than the repository's history.
+Every read is scoped to the selected pull request numbers, so the scans track the listed work rather
+than the repository's history.
-Run attempts come from the jobs table when it is synced: the runs snapshot keeps only a run's
-newest attempt, so a failed first attempt that a re-run turned green is invisible without it.
-Without jobs, each run contributes its newest attempt only and a flake reads as never red.
+Run attempts come from the jobs table when it is synced, because the runs snapshot keeps only a run's
+newest attempt. Without jobs, a failed first attempt that a re-run turned green reads as never red.
"""
from collections import defaultdict
@@ -40,10 +37,11 @@ from products.engineering_analytics.backend.logic.queries._workflow_filters impo
DECISIVE_FAILURE_CONCLUSIONS,
DECISIVE_FAILURE_CONCLUSIONS_SQL,
UNPAGED_SCAN_LIMIT,
+ date_to_filter_clause,
run_started_floor_constant,
run_windowed_job_created_floor_constant,
)
-from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs_since
+from products.engineering_analytics.backend.logic.queries.pr_cost import query_pr_costs
from products.engineering_analytics.backend.logic.views import issue_events
_LIMIT = 200
@@ -66,11 +64,19 @@ _PRS_SELECT = f"""
LIMIT {_LIMIT + 1}
"""
-_TRANSITIONS_SELECT = f"""
- SELECT pr_number, event, created_at
- FROM __EVENTS_SOURCE__ AS se
- WHERE pr_number IN {{pr_numbers}}
- ORDER BY created_at ASC, id ASC
+_READY_AT_SELECT = f"""
+ SELECT
+ pr.number AS pr_number,
+ maxOrNullIf(
+ se.created_at,
+ se.event = '{issue_events.READY_FOR_REVIEW_EVENT}'
+ AND se.created_at <= coalesce(pr.merged_at, pr.closed_at, now())
+ ) AS last_ready_at
+ FROM __PR_SOURCE__ AS pr
+ JOIN __ISSUE_EVENTS_SOURCE__ AS se ON se.pr_number = pr.number
+ WHERE pr.number IN {{pr_numbers}}
+ GROUP BY pr.number
+ HAVING last_ready_at IS NOT NULL
LIMIT {UNPAGED_SCAN_LIMIT}
"""
@@ -81,8 +87,8 @@ _REVIEWS_SELECT = f"""
LIMIT {UNPAGED_SCAN_LIMIT}
"""
-# A skipped run never executes, so it adds no red or running time. Skipped and merge-queue runs are a
-# third of a busy team's runs, so both stay out of this list to keep it under UNPAGED_SCAN_LIMIT.
+# Skipped runs add no red or running time, and _GATE_ATTEMPTS_SELECT reads gate runs. Leaving both out
+# keeps this list under UNPAGED_SCAN_LIMIT.
_RUNS_SELECT = f"""
SELECT
id, pr_number, workflow_name, head_sha, status, conclusion, run_started_at, updated_at, run_attempt, created_at
@@ -157,8 +163,6 @@ class _JobAttempt:
class PullRequestTimelinesQuery:
- """Collects the evidence for the pull requests in one scope and replays each into a timeline."""
-
def __init__(
self, curated: CuratedGitHubSource, *, scope: DeliveryScope, date_from: datetime, date_to: datetime | None
) -> None:
@@ -198,12 +202,13 @@ class PullRequestTimelinesQuery:
run_from = max(run_from, self._date_from - CI_LOOKBACK)
ready_at = self._query_ready_at(pr_numbers, run_from)
reviews = self._query_reviews(pr_numbers)
- attempts, gates = self._query_attempts(pr_numbers, run_from)
+ attempts = self._query_run_attempts(pr_numbers, run_from)
+ gates = self._query_gate_attempts(pr_numbers, run_from)
default_branch = next((row[9] for row in prs if row[9]), "")
master_failures = self._query_master_failures(attempts, default_branch, run_from)
out_of_queue = self._query_out_of_queue(pr_numbers)
# Floored like the runs scan: an unfloored cost read scans the whole jobs history for a team scope.
- costs = query_pr_costs_since(curated=self._curated, pr_numbers=pr_numbers, run_from=run_from)
+ costs = query_pr_costs(curated=self._curated, pr_numbers=pr_numbers, run_from=run_from)
items = []
for row in prs:
@@ -225,12 +230,14 @@ class PullRequestTimelinesQuery:
number = int(number)
is_open = state == PRState.OPEN
ended_at = merged_at or (closed_at if not is_open else None) or self._now
- started_at = max(
- created_at
- if is_open and is_draft
- else self._started_at(ready_at.get(number, []), created_at, ended_at),
- run_from,
- )
+ ready = None if is_open and is_draft else ready_at.get(number)
+ if ready is not None and ready > ended_at:
+ # The two tables sync apart, so a reopened pull request can carry a ready event newer
+ # than the close its own row still reports. A start after the end builds no segments
+ # at all, which reads as a pull request with no timeline.
+ ready = None
+ # No ready event means never drafted, or issue events not synced.
+ started_at = max(ready or created_at, run_from)
pr_attempts = [attempt for attempt in attempts.get(number, []) if attempt.started_at <= ended_at]
builder = PRTimelineBuilder(
PRTimelineInput(
@@ -246,7 +253,7 @@ class PullRequestTimelinesQuery:
),
master_failures,
)
- cost = costs.get(number)
+ cost = costs.get((repo_owner, repo_name, number))
items.append(
PRTimeline(
number=number,
@@ -271,52 +278,43 @@ class PullRequestTimelinesQuery:
)
return self._result(items, truncated=truncated)
- @staticmethod
- def _started_at(ready_events: list[datetime], created_at: datetime, ended_at: datetime) -> datetime:
- """The last ready_for_review before the end, else created_at (never drafted, or unsynced)."""
- before_end = [at for at in ready_events if created_at <= at <= ended_at]
- return max(before_end) if before_end else created_at
-
def _query_prs(self) -> list[tuple]:
placeholders: dict[str, ast.Expr] = {
"date_from": ast.Constant(value=self._date_from),
**self._scope.placeholders(),
}
- date_to_clause = ""
- if self._date_to is not None:
- placeholders["date_to"] = ast.Constant(value=self._date_to)
- date_to_clause = "AND pr.merged_at <= {date_to}"
window = "1 = 1" if self._scope.kind == DeliveryScopeKind.PULL_REQUEST else _LIST_WINDOW
sql = (
_PRS_SELECT.replace("__SCOPE__", self._scope.pr_predicate(self._curated))
.replace("__WINDOW__", window)
.replace("__PR_SOURCE__", self._curated.pr_source())
- .replace("__DATE_TO__", date_to_clause)
+ .replace("__DATE_TO__", date_to_filter_clause(self._date_to, placeholders, column="pr.merged_at"))
)
response = self._curated.run(
sql, query_type="engineering_analytics.pull_request_timelines_prs", placeholders=placeholders
)
return [row for row in response.results or [] if row[6] is not None]
- def _query_ready_at(self, pr_numbers: list[int], run_from: datetime) -> dict[int, list[datetime]]:
+ def _query_ready_at(self, pr_numbers: list[int], run_from: datetime) -> dict[int, datetime]:
# A timeline never starts before run_from, so an older ready event cannot move its start. The
# floor keeps the scan from parsing the whole append-growing events history.
- source = self._curated.issue_events_source(created_floor=True)
- if source is None:
+ # Bounded to each PR's own end (not ready_by_pr_cte's unbounded latest event): the events and
+ # pull-requests tables sync apart, so a reopened PR's newest ready event can land after its own
+ # row's close. Picking the unbounded latest and discarding it wholesale on an out-of-bounds read
+ # would lose an earlier, still-valid ready event; bounding the aggregation itself keeps it.
+ pr_source = self._curated.pr_source()
+ events_source = self._curated.issue_events_source(created_floor=True)
+ if events_source is None:
return {}
response = self._curated.run(
- _TRANSITIONS_SELECT.replace("__EVENTS_SOURCE__", source),
- query_type="engineering_analytics.pull_request_timelines_transitions",
+ _READY_AT_SELECT.replace("__PR_SOURCE__", pr_source).replace("__ISSUE_EVENTS_SOURCE__", events_source),
+ query_type="engineering_analytics.pull_request_timelines_ready_at",
placeholders={
"pr_numbers": ast.Constant(value=pr_numbers),
"event_created_floor": run_started_floor_constant(run_from),
},
)
- ready_at: dict[int, list[datetime]] = defaultdict(list)
- for number, event, created_at in response.results or []:
- if event == issue_events.READY_FOR_REVIEW_EVENT:
- ready_at[int(number)].append(created_at)
- return ready_at
+ return {int(number): last_ready_at for number, last_ready_at in response.results or []}
def _query_reviews(self, pr_numbers: list[int]) -> dict[int, list[ReviewVerdict]] | None:
"""Reviews per PR, or None when the reviews table is not synced."""
@@ -333,19 +331,18 @@ class PullRequestTimelinesQuery:
reviews[int(number)].append(ReviewVerdict(reviewer=reviewer or "", state=state, submitted_at=submitted_at))
return reviews
- def _query_attempts(
- self, pr_numbers: list[int], run_from: datetime
- ) -> tuple[dict[int, list[RunAttempt]], dict[int, list[GateAttempt]]]:
- runs_source = self._curated.run_source(started_floor=True)
- placeholders: dict[str, ast.Expr] = {
+ def _runs_placeholders(self, pr_numbers: list[int], run_from: datetime) -> dict[str, ast.Expr]:
+ return {
"pr_numbers": ast.Constant(value=pr_numbers),
"run_from": ast.Constant(value=run_from),
"run_started_floor": run_started_floor_constant(run_from),
}
+
+ def _query_run_attempts(self, pr_numbers: list[int], run_from: datetime) -> dict[int, list[RunAttempt]]:
response = self._curated.run(
- _RUNS_SELECT.replace("__RUNS_SOURCE__", runs_source),
+ _RUNS_SELECT.replace("__RUNS_SOURCE__", self._curated.run_source(started_floor=True)),
query_type="engineering_analytics.pull_request_timelines_runs",
- placeholders=placeholders,
+ placeholders=self._runs_placeholders(pr_numbers, run_from),
)
runs = [row for row in response.results or [] if row[6] is not None]
# A run on its first attempt that did not fail has exactly one attempt, and its run row already
@@ -416,13 +413,15 @@ class PullRequestTimelinesQuery:
failed_jobs=(),
)
)
+ return attempts
+ def _query_gate_attempts(self, pr_numbers: list[int], run_from: datetime) -> dict[int, list[GateAttempt]]:
gates_response = self._curated.run(
- _GATE_ATTEMPTS_SELECT.replace("__RUNS_SOURCE__", runs_source).replace(
+ _GATE_ATTEMPTS_SELECT.replace("__RUNS_SOURCE__", self._curated.run_source(started_floor=True)).replace(
"__GATE_ATTEMPT__", gate_attempt_expr("r.head_branch")
),
query_type="engineering_analytics.pull_request_timelines_gate_attempts",
- placeholders=placeholders,
+ placeholders=self._runs_placeholders(pr_numbers, run_from),
)
gates: dict[int, list[GateAttempt]] = defaultdict(list)
for number, started_at, completed_at, unfinished in gates_response.results or []:
@@ -430,7 +429,7 @@ class PullRequestTimelinesQuery:
gates[int(number)].append(
GateAttempt(started_at=started_at, completed_at=None if unfinished else completed_at)
)
- return attempts, gates
+ return gates
def _query_job_attempts(self, run_ids: list[int], run_from: datetime) -> dict[int, list[_JobAttempt]]:
source = self._curated.jobs_source(created_floor=True)
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index a453dc483543..bab419976cde 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -58,7 +58,7 @@ ISSUE_EVENTS_SCHEMA = "issue_events"
# succeeded or failed), so reads must degrade gracefully when either is unsynced.
DEPLOYMENTS_SCHEMA = "deployments"
DEPLOYMENT_STATUSES_SCHEMA = "deployment_statuses"
-# Submitted pull-request reviews, the substrate for the approval split on the author page. Optional
+# Submitted pull request reviews, the substrate for the approval split on the author page. Optional
# at the source, so reads must degrade gracefully (no review data) exactly like issue_events.
REVIEWS_SCHEMA = "reviews"
diff --git a/products/engineering_analytics/backend/logic/views/reviews.py b/products/engineering_analytics/backend/logic/views/reviews.py
index 251318742cb0..59dc5f76fde8 100644
--- a/products/engineering_analytics/backend/logic/views/reviews.py
+++ b/products/engineering_analytics/backend/logic/views/reviews.py
@@ -1,12 +1,11 @@
-"""Curated pull-request reviews query builder.
+"""Curated pull request reviews query builder.
-Maps the raw ``github_reviews`` warehouse table (one row per submitted review, with the PR number
-injected by the source's fan-out) into the columns the review reads need. The review verdict
-vocabulary lives here once; consumers import the constants rather than restating the strings.
+The review verdict vocabulary lives here once, so consumers import the constants rather than
+restating the strings.
-The source drops PENDING drafts before rows land, so every row is a submitted review. The
-webhook path reshapes events into the polled REST shape, but ``upper`` still normalizes the
-state so a lowercase verdict can never silently miss the approval filter.
+The source drops PENDING drafts, so every row is a submitted review. The webhook path reshapes events
+into the polled REST shape, so ``upper`` normalizes the state and a lowercase verdict cannot miss the
+approval filter.
"""
APPROVED_STATE = "APPROVED"
diff --git a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
index f43fb7cf57fb..1a8a32fddab3 100644
--- a/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
+++ b/products/engineering_analytics/backend/management/commands/seed_engineering_analytics.py
@@ -507,13 +507,13 @@ def _issue_event_rows(prs: list[dict[str, Any]], anchor: datetime) -> list[dict[
return rows
-# Open PRs get a mix of verdicts so both open groups of the day view ("the author's move", "waiting on others") have rows.
_MERGED_REVIEW_PLANS: tuple[tuple[tuple[str, float], ...], ...] = (
(("CHANGES_REQUESTED", 0.35), ("APPROVED", 0.7)),
(("APPROVED", 0.5),),
(("COMMENTED", 0.3), ("APPROVED", 0.85)),
(("APPROVED", 0.9),),
)
+# A mix of verdicts, so both open groups of the day view have rows.
_OPEN_REVIEW_PLANS: tuple[tuple[tuple[str, float], ...], ...] = (
(("CHANGES_REQUESTED", 0.6),),
(("COMMENTED", 0.5),),
diff --git a/products/engineering_analytics/backend/tests/_github_fixtures.py b/products/engineering_analytics/backend/tests/_github_fixtures.py
index f0e5f1e5e408..fbe1b7945d4f 100644
--- a/products/engineering_analytics/backend/tests/_github_fixtures.py
+++ b/products/engineering_analytics/backend/tests/_github_fixtures.py
@@ -203,6 +203,7 @@ def _pr_row(
created_at: str,
*,
merged_at: str | None = None,
+ closed_at: str | None = None,
merge_commit_sha: str | None = None,
head_sha: str = "",
head_ref: str = "",
@@ -220,7 +221,7 @@ def _pr_row(
"created_at": created_at,
"updated_at": merged_at or created_at,
"merged_at": merged_at,
- "closed_at": merged_at,
+ "closed_at": closed_at or merged_at,
"merge_commit_sha": merge_commit_sha,
"user": _user(login),
"head": f'{{"sha": "{head_sha}", "ref": "{head_ref}"}}',
diff --git a/products/engineering_analytics/backend/tests/test_delivery.py b/products/engineering_analytics/backend/tests/test_delivery.py
index db2ae2ac11ba..b7aee64a2309 100644
--- a/products/engineering_analytics/backend/tests/test_delivery.py
+++ b/products/engineering_analytics/backend/tests/test_delivery.py
@@ -27,9 +27,13 @@ from products.engineering_analytics.backend.logic.pr_timeline import (
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 (
- DeliverySummaryAggregator,
MergedPRFacts,
+ _before_approval_share,
+ _median_ready_to_first_approval,
+ _median_ready_to_merge,
+ _pushes_after_approval,
query_delivery_summary,
+ scope_repo_figure,
)
from products.engineering_analytics.backend.logic.queries.pull_request_timelines import query_pull_request_timelines
from products.engineering_analytics.backend.logic.views.source_schema import (
@@ -75,7 +79,7 @@ def _attempt(
pushed: float | None = None,
) -> RunAttempt:
return RunAttempt(
- run_id=hash(sha) % 1000,
+ run_id=1,
workflow_name="CI",
head_sha=sha,
attempt=attempt,
@@ -416,21 +420,25 @@ class TestComparisonTeamChoice(SimpleTestCase):
assert (choice.teams, choice.basis) == (["approvers", "team-untested"], Basis.ALL_TEAMS)
-class TestDeliverySummaryAggregator(SimpleTestCase):
+class TestScopeRepoFigure(SimpleTestCase):
def test_scope_figures_read_only_the_prs_in_scope(self) -> None:
- aggregator = DeliverySummaryAggregator(
- [
- _facts(1, in_scope=True, ready_hours=10, approved_after_hours=4, pushes_after=[0, 6]),
- # Approved while still a draft: nobody waited on a reviewer after it went ready.
- _facts(2, in_scope=False, ready_hours=2, approved_after_hours=-1, pushes_after=[1]),
- _facts(3, in_scope=False, ready_hours=30, approved_after_hours=None, pushes_after=[]),
- ]
- )
+ facts = [
+ _facts(1, in_scope=True, ready_hours=10, approved_after_hours=4, pushes_after=[0, 6]),
+ # Approved while still a draft: nobody waited on a reviewer after it went ready.
+ _facts(2, in_scope=False, ready_hours=2, approved_after_hours=-1, pushes_after=[1]),
+ _facts(3, in_scope=False, ready_hours=30, approved_after_hours=None, pushes_after=[]),
+ ]
+
+ scope_facts = [fact for fact in facts if fact.in_scope]
- assert aggregator.ready_to_merge(0.5) == ScopeRepoFigure(scope=36000, repo=36000)
- assert aggregator.median_ready_to_first_approval() == ScopeRepoFigure(scope=14400, repo=7200)
- assert aggregator.before_first_approval_share() == ScopeRepoFigure(scope=0.4, repo=14400 / 43200)
- assert aggregator.pushes_after_approval() == ScopeRepoFigure(scope=1, repo=1)
+ assert scope_repo_figure(scope_facts, facts, _median_ready_to_merge) == ScopeRepoFigure(scope=36000, repo=36000)
+ assert scope_repo_figure(scope_facts, facts, _median_ready_to_first_approval) == ScopeRepoFigure(
+ scope=14400, repo=7200
+ )
+ assert scope_repo_figure(scope_facts, facts, _before_approval_share) == ScopeRepoFigure(
+ scope=0.4, repo=14400 / 43200
+ )
+ assert scope_repo_figure(scope_facts, facts, _pushes_after_approval) == ScopeRepoFigure(scope=1, repo=1)
def _review_row(review_id: int, pr_number: int, state: str, submitted_at: str) -> dict:
@@ -448,6 +456,12 @@ def _member_row(member_id: int, login: str, team_slug: str) -> dict:
return {"id": member_id, "login": login, "team_id": 1, "team_slug": team_slug, "team_name": team_slug}
+_LISTED_KINDS = {
+ 21: [Kind.CI_RUNNING, Kind.RED_FIXED_BY_PUSH, Kind.CI_RUNNING, Kind.APPROVED_NOT_ENQUEUED, Kind.MERGE_QUEUE],
+ 23: [Kind.WAITING_FOR_REVIEW],
+ 24: [Kind.DRAFT],
+ 26: [Kind.WAITING_FOR_REVIEW],
+}
_ALICE = SummaryScope.from_params(author="alice", github_team=None, pr_number=None, repo=None)
_ALICES_TEAM = SummaryScope.from_params(author=None, github_team="team-replay", pr_number=None, repo=None)
@@ -489,7 +503,6 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
REVIEWS_COLUMNS,
[_review_row(1, 21, "APPROVED", _ago_offset_with_duration(2, 6 * 3600, 0)[0])],
)
- # Bob sits in another team, so the team scope must match alice's PRs only.
self._create_table(
"github_team_members",
TEAM_MEMBERS_COLUMNS,
@@ -569,16 +582,7 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
timelines = query_pull_request_timelines(curated=curated, scope=scope, date_from=date_from, date_to=None)
kinds = {item.number: [segment.kind for segment in item.segments] for item in timelines.items}
- assert set(kinds) == expected
- assert kinds[21] == [
- Kind.CI_RUNNING,
- Kind.RED_FIXED_BY_PUSH,
- Kind.CI_RUNNING,
- Kind.APPROVED_NOT_ENQUEUED,
- Kind.MERGE_QUEUE,
- ]
- assert kinds.get(23, [Kind.WAITING_FOR_REVIEW]) == [Kind.WAITING_FOR_REVIEW]
- assert kinds.get(24, [Kind.DRAFT]) == [Kind.DRAFT]
+ assert kinds == {number: _LISTED_KINDS[number] for number in expected}
merged = next(item for item in timelines.items if item.number == 21)
assert merged.author.handle == "alice"
assert [(push.head_sha, push.pushed_at) for push in merged.pushes] == [
@@ -587,8 +591,95 @@ class TestDeliveryReadsOnWarehouse(_WarehouseMixin):
]
assert merged.segments[-1].ended_at == merged.merged_at
assert merged.started_at == _dt(_ago(2))
- old_open = next((item for item in timelines.items if item.number == 26), None)
- assert old_open is None or old_open.started_at == date_from - CI_LOOKBACK
+ starting_at_lookback = {item.number for item in timelines.items if item.started_at == date_from - CI_LOOKBACK}
+ assert starting_at_lookback == expected & {26}
+
+ def test_a_ready_event_after_the_close_still_builds_a_timeline(self) -> None:
+ closed_at = _ago(2)
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(31, "alice", "closed", 0, _ago(4), closed_at=closed_at)],
+ )
+ self._create_table(
+ "github_issue_events",
+ ISSUE_EVENTS_COLUMNS,
+ [_issue_event_row(1, "ready_for_review", 31, _ago(1))],
+ )
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
+ curated = CuratedGitHubSource.for_team(self.team)
+ scope = DeliveryScope(
+ kind=DeliveryScopeKind.PULL_REQUEST, pr_number=31, repo_owner="PostHog", repo_name="posthog"
+ )
+
+ timelines = query_pull_request_timelines(
+ curated=curated, scope=scope, date_from=datetime.now(tz=UTC) - timedelta(days=7), date_to=None
+ )
+
+ reopened = next(item for item in timelines.items if item.number == 31)
+ assert reopened.started_at == _dt(_ago(4))
+ assert reopened.segments != []
+
+ def test_an_earlier_ready_event_still_wins_when_the_latest_is_after_the_close(self) -> None:
+ # PR 33 went ready, back to draft, then ready again; the events and pull-requests tables sync
+ # apart, so its last ready event lands after its own row's close. Picking the unbounded latest
+ # ready event and discarding it wholesale on an out-of-bounds read would lose the earlier,
+ # still-valid one and overstate the review timeline from created_at instead.
+ closed_at = _ago(2)
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(33, "alice", "closed", 0, _ago(6), closed_at=closed_at)],
+ )
+ self._create_table(
+ "github_issue_events",
+ ISSUE_EVENTS_COLUMNS,
+ [
+ _issue_event_row(1, "ready_for_review", 33, _ago(5)),
+ _issue_event_row(2, "convert_to_draft", 33, _ago(4)),
+ _issue_event_row(3, "ready_for_review", 33, _ago(1)),
+ ],
+ )
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
+ curated = CuratedGitHubSource.for_team(self.team)
+ scope = DeliveryScope(
+ kind=DeliveryScopeKind.PULL_REQUEST, pr_number=33, repo_owner="PostHog", repo_name="posthog"
+ )
+
+ timelines = query_pull_request_timelines(
+ curated=curated, scope=scope, date_from=datetime.now(tz=UTC) - timedelta(days=7), date_to=None
+ )
+
+ reopened = next(item for item in timelines.items if item.number == 33)
+ assert reopened.started_at == _dt(_ago(5))
+
+ def test_a_never_ready_pr_starts_at_its_own_created_at(self) -> None:
+ # PR 32 has an issue event, but never a ready_for_review one. The bounded ready-at read must
+ # come back empty here, not fall back to ClickHouse's zero-value DateTime default, which would
+ # read as truthy and pin the timeline to run_from instead.
+ created_at = _ago(6)
+ self._create_table(
+ "github_pull_requests",
+ PULL_REQUESTS_COLUMNS,
+ [_pr_row(32, "alice", "closed", 0, created_at, closed_at=_ago(5))],
+ )
+ self._create_table(
+ "github_issue_events",
+ ISSUE_EVENTS_COLUMNS,
+ [_issue_event_row(1, "convert_to_draft", 32, _ago(5))],
+ )
+ self._create_table("github_workflow_runs", WORKFLOW_RUNS_COLUMNS, [])
+ curated = CuratedGitHubSource.for_team(self.team)
+ scope = DeliveryScope(
+ kind=DeliveryScopeKind.PULL_REQUEST, pr_number=32, repo_owner="PostHog", repo_name="posthog"
+ )
+
+ timelines = query_pull_request_timelines(
+ curated=curated, scope=scope, date_from=datetime.now(tz=UTC) - timedelta(days=7), date_to=None
+ )
+
+ never_ready = next(item for item in timelines.items if item.number == 32)
+ assert never_ready.started_at == _dt(created_at)
_ISSUE_EVENTS_WITHOUT_TEAM_REQUESTS = {